Skip to content

Commit 411eb89

Browse files
committed
k6runner/http: create spans in k6 http runner
1 parent 10314b2 commit 411eb89

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

internal/k6runner/http.go

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import (
1010
"time"
1111

1212
"github.com/rs/zerolog"
13+
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
14+
"go.opentelemetry.io/otel/propagation"
15+
"go.opentelemetry.io/otel/trace"
1316
"golang.org/x/exp/rand"
1417
)
1518

@@ -106,14 +109,18 @@ func (r HttpRunner) Run(ctx context.Context, script Script) (*RunResponse, error
106109
waitRemaining := max(0, wait-time.Since(start))
107110
r.logger.Warn().Err(err).Dur("after", waitRemaining).Msg("retrying retryable error")
108111

112+
// Discard context, backoffSpan needs no children.
113+
_, backoffSpan := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "backoff")
114+
109115
waitTimer := time.NewTimer(waitRemaining)
110116
select {
111117
case <-ctx.Done():
118+
backoffSpan.End()
112119
waitTimer.Stop()
113-
// TODO: Log the returned error in the Processor instead.
114-
r.logger.Error().Err(err).Msg("retries exhausted")
120+
r.logger.Error().Err(err).Msg("retries exhausted") // TODO: Log the returned error in the Processor instead.
115121
return nil, fmt.Errorf("cannot retry further: %w", errors.Join(err, ctx.Err()))
116122
case <-waitTimer.C:
123+
backoffSpan.End()
117124
}
118125

119126
// Backoff linearly, adding some jitter.
@@ -165,7 +172,21 @@ func (r HttpRunner) request(ctx context.Context, script Script) (*RunResponse, e
165172

166173
req.Header.Add("content-type", "application/json")
167174

168-
resp, err := http.DefaultClient.Do(req)
175+
// Build a tracing-enabled http client.
176+
httpClient := http.Client{
177+
Transport: otelhttp.NewTransport(
178+
http.DefaultTransport,
179+
otelhttp.WithTracerProvider(trace.SpanFromContext(ctx).TracerProvider()),
180+
// Span names do not include method and path by default to avoid cardinality explosion with paths containing
181+
// IDs. As this is not the case with this endpoint, we use a custom formatter that includes both.
182+
otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
183+
return fmt.Sprintf("%s %s", r.Method, r.URL.Path)
184+
}),
185+
otelhttp.WithPropagators(propagation.TraceContext{}), // Send TraceIDs in outgoing requests.
186+
),
187+
}
188+
189+
resp, err := httpClient.Do(req)
169190
if err != nil {
170191
r.logger.Error().Err(err).Msg("sending request")
171192

0 commit comments

Comments
 (0)