1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2024-12-12 10:04:29 +02:00

Add option to specify propagators to use with httptrace Extract and Inject

This commit is contained in:
Anthony J Mirabella 2020-06-01 13:47:43 -04:00
parent 823703a6bb
commit aea2257ee4
2 changed files with 192 additions and 4 deletions

View File

@ -26,9 +26,33 @@ import (
"go.opentelemetry.io/otel/api/trace" "go.opentelemetry.io/otel/api/trace"
) )
// Option is a function that allows configuration of the httptrace Extract()
// and Inject() functions
type Option func(*config)
type config struct {
propagators propagation.Propagators
}
func newConfig(opts []Option) *config {
c := &config{propagators: global.Propagators()}
for _, o := range opts {
o(c)
}
return c
}
// WithPropagators sets the propagators to use for Extraction and Injection
func WithPropagators(props propagation.Propagators) Option {
return func(c *config) {
c.propagators = props
}
}
// Returns the Attributes, Context Entries, and SpanContext that were encoded by Inject. // Returns the Attributes, Context Entries, and SpanContext that were encoded by Inject.
func Extract(ctx context.Context, req *http.Request) ([]kv.KeyValue, []kv.KeyValue, trace.SpanContext) { func Extract(ctx context.Context, req *http.Request, opts ...Option) ([]kv.KeyValue, []kv.KeyValue, trace.SpanContext) {
ctx = propagation.ExtractHTTP(ctx, global.Propagators(), req.Header) c := newConfig(opts)
ctx = propagation.ExtractHTTP(ctx, c.propagators, req.Header)
attrs := append( attrs := append(
standard.HTTPServerAttributesFromHTTPRequest("", "", req), standard.HTTPServerAttributesFromHTTPRequest("", "", req),
@ -44,6 +68,7 @@ func Extract(ctx context.Context, req *http.Request) ([]kv.KeyValue, []kv.KeyVal
return attrs, correlationCtxKVs, trace.RemoteSpanContextFromContext(ctx) return attrs, correlationCtxKVs, trace.RemoteSpanContextFromContext(ctx)
} }
func Inject(ctx context.Context, req *http.Request) { func Inject(ctx context.Context, req *http.Request, opts ...Option) {
propagation.InjectHTTP(ctx, global.Propagators(), req.Header) c := newConfig(opts)
propagation.InjectHTTP(ctx, c.propagators, req.Header)
} }

View File

@ -0,0 +1,163 @@
package httptrace_test
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"go.opentelemetry.io/otel/api/correlation"
"go.opentelemetry.io/otel/api/global"
"go.opentelemetry.io/otel/api/kv"
"go.opentelemetry.io/otel/api/propagation"
"go.opentelemetry.io/otel/api/standard"
"go.opentelemetry.io/otel/instrumentation/httptrace"
export "go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func TestRoundtrip(t *testing.T) {
exp := &testExporter{
spanMap: make(map[string][]*export.SpanData),
}
tp, _ := sdktrace.NewProvider(sdktrace.WithSyncer(exp), sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}))
global.SetTraceProvider(tp)
tr := tp.Tracer("httptrace/client")
var expectedAttrs map[kv.Key]string
expectedCorrs := map[kv.Key]string{kv.Key("foo"): "bar"}
// Mock http server
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attrs, corrs, span := httptrace.Extract(r.Context(), r)
actualAttrs := make(map[kv.Key]string)
for _, attr := range attrs {
if attr.Key == standard.NetPeerPortKey {
// Peer port will be non-deterministic
continue
}
actualAttrs[attr.Key] = attr.Value.Emit()
}
if diff := cmp.Diff(actualAttrs, expectedAttrs); diff != "" {
t.Fatalf("[TestRoundtrip] Attributes are different: %v", diff)
}
actualCorrs := make(map[kv.Key]string)
for _, corr := range corrs {
actualCorrs[corr.Key] = corr.Value.Emit()
}
if diff := cmp.Diff(actualCorrs, expectedCorrs); diff != "" {
t.Fatalf("[TestRoundtrip] Correlations are different: %v", diff)
}
if !span.IsValid() {
t.Fatalf("[TestRoundtrip] Invalid span extracted: %v", span)
}
_, err := w.Write([]byte("OK"))
if err != nil {
t.Fatal(err)
}
}),
)
defer ts.Close()
address := ts.Listener.Addr()
hp := strings.Split(address.String(), ":")
expectedAttrs = map[kv.Key]string{
standard.HTTPFlavorKey: "1.1",
standard.HTTPHostKey: address.String(),
standard.HTTPMethodKey: "GET",
standard.HTTPSchemeKey: "http",
standard.HTTPTargetKey: "/",
standard.HTTPUserAgentKey: "Go-http-client/1.1",
standard.NetHostIPKey: hp[0],
standard.NetHostPortKey: hp[1],
standard.NetPeerIPKey: "127.0.0.1",
standard.NetTransportKey: "IP.TCP",
}
client := ts.Client()
err := tr.WithSpan(context.Background(), "test",
func(ctx context.Context) error {
ctx = correlation.ContextWithMap(ctx, correlation.NewMap(correlation.MapUpdate{SingleKV: kv.Key("foo").String("bar")}))
req, _ := http.NewRequest("GET", ts.URL, nil)
httptrace.Inject(ctx, req)
res, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %s", err.Error())
}
_ = res.Body.Close()
return nil
})
if err != nil {
panic("unexpected error in http request: " + err.Error())
}
}
func TestSpecifyPropagators(t *testing.T) {
exp := &testExporter{
spanMap: make(map[string][]*export.SpanData),
}
tp, _ := sdktrace.NewProvider(sdktrace.WithSyncer(exp), sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}))
global.SetTraceProvider(tp)
tr := tp.Tracer("httptrace/client")
expectedCorrs := map[kv.Key]string{kv.Key("foo"): "bar"}
// Mock http server
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, corrs, span := httptrace.Extract(r.Context(), r, httptrace.WithPropagators(propagation.New(propagation.WithExtractors(correlation.DefaultHTTPPropagator()))))
actualCorrs := make(map[kv.Key]string)
for _, corr := range corrs {
actualCorrs[corr.Key] = corr.Value.Emit()
}
if diff := cmp.Diff(actualCorrs, expectedCorrs); diff != "" {
t.Fatalf("[TestRoundtrip] Correlations are different: %v", diff)
}
if span.IsValid() {
t.Fatalf("[TestRoundtrip] valid span extracted, expected none: %v", span)
}
_, err := w.Write([]byte("OK"))
if err != nil {
t.Fatal(err)
}
}),
)
defer ts.Close()
client := ts.Client()
err := tr.WithSpan(context.Background(), "test",
func(ctx context.Context) error {
ctx = correlation.ContextWithMap(ctx, correlation.NewMap(correlation.MapUpdate{SingleKV: kv.Key("foo").String("bar")}))
req, _ := http.NewRequest("GET", ts.URL, nil)
httptrace.Inject(ctx, req, httptrace.WithPropagators(propagation.New(propagation.WithInjectors(correlation.DefaultHTTPPropagator()))))
res, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %s", err.Error())
}
_ = res.Body.Close()
return nil
})
if err != nil {
panic("unexpected error in http request: " + err.Error())
}
}