Skip to content

Commit 794e127

Browse files
jmsnllmx-psi
andauthored
[cmd/telemetrygen] expose the generated span duration as a command pa… (open-telemetry#29116)
**Description:** As originally proposed in open-telemetry#26991 before I got distracted Exposes the duration of generated spans as a command line parameter. It uses a `DurationVar` flag so units can be easily provided and are automatically applied. Example usage: ```bash telemetrygen traces --traces 100 --otlp-insecure --span-duration 10ns # nanoseconds telemetrygen traces --traces 100 --otlp-insecure --span-duration 10us # microseconds telemetrygen traces --traces 100 --otlp-insecure --span-duration 10ms # milliseconds telemetrygen traces --traces 100 --otlp-insecure --span-duration 10s # seconds ``` **Testing:** Ran without the argument provided `telemetrygen traces --traces 1 --otlp-insecure` and seen spans publishing with the default value. Ran again with the argument provided: `telemetrygen traces --traces 1 --otlp-insecure --span-duration 1s` And observed the expected output: ``` Resource SchemaURL: https://opentelemetry.io/schemas/1.4.0 Resource attributes: -> service.name: Str(telemetrygen) ScopeSpans #0 ScopeSpans SchemaURL: InstrumentationScope telemetrygen Span #0 Trace ID : 8b441587ffa5820688b87a6b511d634c Parent ID : 39faad428638791b ID : 88f0886894bd4ee2 Name : okey-dokey Kind : Server Start time : 2023-11-12 02:05:07.97443 +0000 UTC End time : 2023-11-12 02:05:08.97443 +0000 UTC Status code : Unset Status message : Attributes: -> net.peer.ip: Str(1.2.3.4) -> peer.service: Str(telemetrygen-client) Span #1 Trace ID : 8b441587ffa5820688b87a6b511d634c Parent ID : ID : 39faad428638791b Name : lets-go Kind : Client Start time : 2023-11-12 02:05:07.97443 +0000 UTC End time : 2023-11-12 02:05:08.97443 +0000 UTC Status code : Unset Status message : Attributes: -> net.peer.ip: Str(1.2.3.4) -> peer.service: Str(telemetrygen-server) {"kind": "exporter", "data_type": "traces", "name": "debug"} ``` **Documentation:** No documentation added. --------- Co-authored-by: Pablo Baeyens <[email protected]>
1 parent 97e7916 commit 794e127

File tree

5 files changed

+74
-6
lines changed

5 files changed

+74
-6
lines changed
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: enhancement
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
7+
component: telemetrygen
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: Exposes the span duration as a command line argument `--span-duration`
11+
12+
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
13+
issues: [29116]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext:
19+
20+
# If your change doesn't affect end users or the exported elements of any package,
21+
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
22+
# Optional: The change log or logs in which this entry should be included.
23+
# e.g. '[user]' or '[user, api]'
24+
# Include 'user' if the change is relevant to end users.
25+
# Include 'api' if there is a change to a library API.
26+
# Default: '[user]'
27+
change_logs: [user]

cmd/telemetrygen/internal/traces/config.go

+4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
package traces
55

66
import (
7+
"time"
8+
79
"github.com/spf13/pflag"
810

911
"github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen/internal/common"
@@ -18,6 +20,7 @@ type Config struct {
1820
StatusCode string
1921
Batch bool
2022
LoadSize int
23+
SpanDuration time.Duration
2124
}
2225

2326
// Flags registers config flags.
@@ -32,4 +35,5 @@ func (c *Config) Flags(fs *pflag.FlagSet) {
3235
fs.StringVar(&c.StatusCode, "status-code", "0", "Status code to use for the spans, one of (Unset, Error, Ok) or the equivalent integer (0,1,2)")
3336
fs.BoolVar(&c.Batch, "batch", true, "Whether to batch traces")
3437
fs.IntVar(&c.LoadSize, "size", 0, "Desired minimum size in MB of string data for each trace generated. This can be used to test traces with large payloads, i.e. when testing the OTLP receiver endpoint max receive size.")
38+
fs.DurationVar(&c.SpanDuration, "span-duration", 123*time.Microsecond, "The duration of each generated span.")
3539
}

cmd/telemetrygen/internal/traces/traces.go

+1
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ func Run(c *Config, logger *zap.Logger) error {
132132
wg: &wg,
133133
logger: logger.With(zap.Int("worker", i)),
134134
loadSize: c.LoadSize,
135+
spanDuration: c.SpanDuration,
135136
}
136137

137138
go w.simulateTraces(telemetryAttributes)

cmd/telemetrygen/internal/traces/worker.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,14 @@ type worker struct {
2828
totalDuration time.Duration // how long to run the test for (overrides `numTraces`)
2929
limitPerSecond rate.Limit // how many spans per second to generate
3030
wg *sync.WaitGroup // notify when done
31+
loadSize int // desired minimum size in MB of string data for each generated trace
32+
spanDuration time.Duration // duration of generated spans
3133
logger *zap.Logger
32-
loadSize int
3334
}
3435

3536
const (
3637
fakeIP string = "1.2.3.4"
3738

38-
fakeSpanDuration = 123 * time.Microsecond
39-
4039
charactersPerMB = 1024 * 1024 // One character takes up one byte of space, so this number comes from the number of bytes in a megabyte
4140
)
4241

@@ -46,11 +45,15 @@ func (w worker) simulateTraces(telemetryAttributes []attribute.KeyValue) {
4645
var i int
4746

4847
for w.running.Load() {
48+
spanStart := time.Now()
49+
spanEnd := spanStart.Add(w.spanDuration)
50+
4951
ctx, sp := tracer.Start(context.Background(), "lets-go", trace.WithAttributes(
5052
semconv.NetPeerIPKey.String(fakeIP),
5153
semconv.PeerServiceKey.String("telemetrygen-server"),
5254
),
5355
trace.WithSpanKind(trace.SpanKindClient),
56+
trace.WithTimestamp(spanStart),
5457
)
5558
sp.SetAttributes(telemetryAttributes...)
5659
for j := 0; j < w.loadSize; j++ {
@@ -72,18 +75,19 @@ func (w worker) simulateTraces(telemetryAttributes []attribute.KeyValue) {
7275
semconv.PeerServiceKey.String("telemetrygen-client"),
7376
),
7477
trace.WithSpanKind(trace.SpanKindServer),
78+
trace.WithTimestamp(spanStart),
7579
)
7680
child.SetAttributes(telemetryAttributes...)
7781

7882
if err := limiter.Wait(context.Background()); err != nil {
7983
w.logger.Fatal("limiter waited failed, retry", zap.Error(err))
8084
}
8185

82-
opt := trace.WithTimestamp(time.Now().Add(fakeSpanDuration))
86+
endTimestamp := trace.WithTimestamp(spanEnd)
8387
child.SetStatus(w.statusCode, "")
84-
child.End(opt)
88+
child.End(endTimestamp)
8589
sp.SetStatus(w.statusCode, "")
86-
sp.End(opt)
90+
sp.End(endTimestamp)
8791

8892
i++
8993
if w.numTraces != 0 {

cmd/telemetrygen/internal/traces/worker_test.go

+32
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,38 @@ func TestRateOfSpans(t *testing.T) {
8080
assert.True(t, len(syncer.spans) <= 20, "there should have been less than 20 spans, had %d", len(syncer.spans))
8181
}
8282

83+
func TestSpanDuration(t *testing.T) {
84+
// prepare
85+
syncer := &mockSyncer{}
86+
87+
tracerProvider := sdktrace.NewTracerProvider()
88+
sp := sdktrace.NewSimpleSpanProcessor(syncer)
89+
tracerProvider.RegisterSpanProcessor(sp)
90+
otel.SetTracerProvider(tracerProvider)
91+
92+
targetDuration := 1 * time.Second
93+
cfg := &Config{
94+
Config: common.Config{
95+
Rate: 10,
96+
TotalDuration: time.Second / 2,
97+
WorkerCount: 1,
98+
},
99+
SpanDuration: targetDuration,
100+
}
101+
102+
// sanity check
103+
require.Len(t, syncer.spans, 0)
104+
105+
// test
106+
require.NoError(t, Run(cfg, zap.NewNop()))
107+
108+
for _, span := range syncer.spans {
109+
startTime, endTime := span.StartTime(), span.EndTime()
110+
spanDuration := endTime.Sub(startTime)
111+
assert.Equal(t, targetDuration, spanDuration)
112+
}
113+
}
114+
83115
func TestUnthrottled(t *testing.T) {
84116
// prepare
85117
syncer := &mockSyncer{}

0 commit comments

Comments
 (0)