Skip to content

Commit

Permalink
update stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
krnowak committed Nov 6, 2019
1 parent c1d0ac2 commit cea2722
Show file tree
Hide file tree
Showing 11 changed files with 121 additions and 69 deletions.
58 changes: 29 additions & 29 deletions bridge/opentracing/internal/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ type MockContextKeyValue struct {
}

type MockTracer struct {
Resources oteldctx.Map
FinishedSpans []*MockSpan
SpareTraceIDs []otelcore.TraceID
SpareSpanIDs []otelcore.SpanID
Expand All @@ -59,7 +58,6 @@ var _ migration.DeferredContextSetupTracerExtension = &MockTracer{}

func NewMockTracer() *MockTracer {
return &MockTracer{
Resources: oteldctx.NewEmptyMap(),
FinishedSpans: nil,
SpareTraceIDs: nil,
SpareSpanIDs: nil,
Expand Down Expand Up @@ -94,14 +92,12 @@ func (t *MockTracer) Start(ctx context.Context, name string, opts ...oteltrace.S
officialTracer: t,
spanContext: spanContext,
recording: spanOpts.Record,
Attributes: oteldctx.NewMap(oteldctx.MapUpdate{
MultiKV: spanOpts.Attributes,
}),
StartTime: startTime,
EndTime: time.Time{},
ParentSpanID: t.getParentSpanID(ctx, &spanOpts),
Events: nil,
SpanKind: oteltrace.ValidateSpanKind(spanOpts.SpanKind),
Attributes: spanOpts.Attributes,
StartTime: startTime,
EndTime: time.Time{},
ParentSpanID: t.getParentSpanID(ctx, &spanOpts),
Events: nil,
SpanKind: oteltrace.ValidateSpanKind(spanOpts.SpanKind),
}
if !migration.SkipContextSetup(ctx) {
ctx = oteltrace.SetCurrentSpan(ctx, span)
Expand Down Expand Up @@ -193,10 +189,10 @@ func (t *MockTracer) DeferredContextSetupHook(ctx context.Context, span oteltrac
}

type MockEvent struct {
CtxAttributes oteldctx.Map
Timestamp time.Time
Msg string
Attributes oteldctx.Map
Correlations oteldctx.Correlations
Timestamp time.Time
Msg string
Attributes []otelcore.KeyValue
}

type MockSpan struct {
Expand All @@ -206,7 +202,7 @@ type MockSpan struct {
SpanKind oteltrace.SpanKind
recording bool

Attributes oteldctx.Map
Attributes []otelcore.KeyValue
StartTime time.Time
EndTime time.Time
ParentSpanID otelcore.SpanID
Expand Down Expand Up @@ -237,19 +233,25 @@ func (s *MockSpan) SetError(v bool) {
}

func (s *MockSpan) SetAttribute(attribute otelcore.KeyValue) {
s.applyUpdate(oteldctx.MapUpdate{
SingleKV: attribute,
})
s.applyUpdate(attribute)
}

func (s *MockSpan) SetAttributes(attributes ...otelcore.KeyValue) {
s.applyUpdate(oteldctx.MapUpdate{
MultiKV: attributes,
})
s.applyUpdate(attributes...)
}

func (s *MockSpan) applyUpdate(update oteldctx.MapUpdate) {
s.Attributes = s.Attributes.Apply(update)
func (s *MockSpan) applyUpdate(attributes ...otelcore.KeyValue) {
m := make(map[otelcore.Key]int, len(s.Attributes))
for idx, kv := range s.Attributes {
m[kv.Key] = idx
}
for _, kv := range attributes {
if idx, ok := m[kv.Key]; ok {
s.Attributes[idx].Value = kv.Value
} else {
s.Attributes = append(s.Attributes, kv)
}
}
}

func (s *MockSpan) End(options ...oteltrace.EndOption) {
Expand Down Expand Up @@ -280,12 +282,10 @@ func (s *MockSpan) AddEvent(ctx context.Context, msg string, attrs ...otelcore.K

func (s *MockSpan) AddEventWithTimestamp(ctx context.Context, timestamp time.Time, msg string, attrs ...otelcore.KeyValue) {
s.Events = append(s.Events, MockEvent{
CtxAttributes: oteldctx.FromContext(ctx),
Timestamp: timestamp,
Msg: msg,
Attributes: oteldctx.NewMap(oteldctx.MapUpdate{
MultiKV: attrs,
}),
Correlations: oteldctx.CorrelationsFromContext(ctx),
Timestamp: timestamp,
Msg: msg,
Attributes: attrs,
})
}

Expand Down
17 changes: 13 additions & 4 deletions example/basic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,15 @@ func main() {

ctx := context.Background()

ctx = distributedcontext.NewContext(ctx,
fooKey.String("foo1"),
barKey.String("bar1"),
ctx = distributedcontext.NewCorrelationsContextKV(ctx,
distributedcontext.Correlation{
KeyValue: fooKey.String("foo1"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
distributedcontext.Correlation{
KeyValue: barKey.String("bar1"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
)

commonLabels := meter.Labels(lemonsKey.Int(10))
Expand All @@ -88,7 +94,10 @@ func main() {

meter.RecordBatch(
// Note: call-site variables added as context Entries:
distributedcontext.NewContext(ctx, anotherKey.String("xyz")),
distributedcontext.NewCorrelationsContextKV(ctx, distributedcontext.Correlation{
KeyValue: anotherKey.String("xyz"),
HopLimit: distributedcontext.UnlimitedPropagation,
}),
commonLabels,

oneMetric.Measurement(1.0),
Expand Down
7 changes: 5 additions & 2 deletions example/http-stackdriver/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@ func main() {
tr := global.TraceProvider().GetTracer("stackdriver/example/client")

client := http.DefaultClient
ctx := distributedcontext.NewContext(context.Background(),
key.String("username", "donuts"),
ctx := distributedcontext.NewCorrelationsContextKV(context.Background(),
distributedcontext.Correlation{
KeyValue: key.String("username", "donuts"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
)

var body []byte
Expand Down
4 changes: 1 addition & 3 deletions example/http-stackdriver/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ func main() {
helloHandler := func(w http.ResponseWriter, req *http.Request) {
attrs, entries, spanCtx := httptrace.Extract(req.Context(), req)

req = req.WithContext(distributedcontext.WithMap(req.Context(), distributedcontext.NewMap(distributedcontext.MapUpdate{
MultiKV: entries,
})))
req = req.WithContext(distributedcontext.NewCorrelationsContextKV(req.Context(), entries...))

ctx, span := tr.Start(
req.Context(),
Expand Down
7 changes: 5 additions & 2 deletions example/http/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,11 @@ func main() {
initTracer()

client := http.DefaultClient
ctx := distributedcontext.NewContext(context.Background(),
key.String("username", "donuts"),
ctx := distributedcontext.NewCorrelationsContextKV(context.Background(),
distributedcontext.Correlation{
KeyValue: key.String("username", "donuts"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
)

var body []byte
Expand Down
4 changes: 1 addition & 3 deletions example/http/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ func main() {
helloHandler := func(w http.ResponseWriter, req *http.Request) {
attrs, entries, spanCtx := httptrace.Extract(req.Context(), req)

req = req.WithContext(distributedcontext.WithMap(req.Context(), distributedcontext.NewMap(distributedcontext.MapUpdate{
MultiKV: entries,
})))
req = req.WithContext(distributedcontext.NewCorrelationsContextKV(req.Context(), entries...))

ctx, span := tr.Start(
req.Context(),
Expand Down
12 changes: 9 additions & 3 deletions example/namedtracer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,15 @@ func main() {
tracer := tp.GetTracer("example/namedtracer/main")
ctx := context.Background()

ctx = distributedcontext.NewContext(ctx,
fooKey.String("foo1"),
barKey.String("bar1"),
ctx = distributedcontext.NewCorrelationsContextKV(ctx,
distributedcontext.Correlation{
KeyValue: fooKey.String("foo1"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
distributedcontext.Correlation{
KeyValue: barKey.String("bar1"),
HopLimit: distributedcontext.UnlimitedPropagation,
},
)

err := tracer.WithSpan(ctx, "operation", func(ctx context.Context) error {
Expand Down
23 changes: 11 additions & 12 deletions plugin/httptrace/httptrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ import (
"net/http"

"go.opentelemetry.io/otel/api/core"
dctx "go.opentelemetry.io/otel/api/distributedcontext"
"go.opentelemetry.io/otel/api/key"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/api/trace"
propagation "go.opentelemetry.io/otel/propagation/http"
)

const (
Expand All @@ -31,27 +33,24 @@ var (
HostKey = key.New("http.host")
URLKey = key.New("http.url")

propagator = propagation.HTTPTraceContextPropagator{}
scPropagator = propagation.TraceContextPropagator{}
cPropagator = propagation.CorrelationContextPropagator{}
)

// Returns the Attributes, Context Entries, and SpanContext that were encoded by Inject.
func Extract(ctx context.Context, req *http.Request) ([]core.KeyValue, []core.KeyValue, core.SpanContext) {
sc, correlationCtx := propagator.Extract(ctx, req.Header)
func Extract(ctx context.Context, req *http.Request) ([]core.KeyValue, []dctx.Correlation, core.SpanContext) {
sc := scPropagator.Extract(req.Header)
correlationCtx := cPropagator.Extract(req.Header)

attrs := []core.KeyValue{
URLKey.String(req.URL.String()),
// Etc.
}

var correlationCtxKVs []core.KeyValue
correlationCtx.Foreach(func(kv core.KeyValue) bool {
correlationCtxKVs = append(correlationCtxKVs, kv)
return true
})

return attrs, correlationCtxKVs, sc
return attrs, correlationCtx.Correlations(), sc
}

func Inject(ctx context.Context, req *http.Request) {
propagator.Inject(ctx, req.Header)
scPropagator.Inject(trace.CurrentSpan(ctx).SpanContext(), req.Header)
cPropagator.Inject(dctx.CorrelationsFromContext(ctx), req.Header)
}
54 changes: 45 additions & 9 deletions plugin/othttp/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@
package othttp

import (
"context"
"io"
"net/http"

"go.opentelemetry.io/otel/api/core"
"go.opentelemetry.io/otel/api/propagation"
dctx "go.opentelemetry.io/otel/api/distributedcontext"
propagation "go.opentelemetry.io/otel/api/propagation/http"
"go.opentelemetry.io/otel/api/trace"
"go.opentelemetry.io/otel/global"
prop "go.opentelemetry.io/otel/propagation"
prop "go.opentelemetry.io/otel/propagation/http"
)

var _ http.Handler = &Handler{}
Expand Down Expand Up @@ -51,7 +53,7 @@ type Handler struct {
handler http.Handler

tracer trace.Tracer
prop propagation.TextFormatPropagator
prop propagation.Propagator
spanOptions []trace.SpanOption
public bool
readEvent bool
Expand Down Expand Up @@ -81,7 +83,7 @@ func WithPublicEndpoint() Option {
// WithPropagator configures the Handler with a specific propagator. If this
// option isn't specificed then
// go.opentelemetry.io/otel/propagation.HTTPTraceContextPropagator is used.
func WithPropagator(p propagation.TextFormatPropagator) Option {
func WithPropagator(p propagation.Propagator) Option {
return func(h *Handler) {
h.prop = p
}
Expand Down Expand Up @@ -125,13 +127,37 @@ func WithMessageEvents(events ...event) Option {
}
}

type defaultPropagator struct {
propagation.Propagators
}

func newDefaultPropagator() propagation.Propagator {
return defaultPropagator{
Propagators: propagation.Propagators{
Scp: prop.TraceContextPropagator{},
Cp: prop.CorrelationContextPropagator{},
Bp: propagation.NoopBaggagePropagator{},
},
}
}

func (d defaultPropagator) Inject(sc core.SpanContext, c dctx.Correlations, b dctx.Baggage, s propagation.Supplier) {
d.Scp.Inject(sc, s)
d.Cp.Inject(c, s)
d.Bp.Inject(b, s)
}

func (d defaultPropagator) Extract(s propagation.Supplier) (core.SpanContext, dctx.Correlations, dctx.Baggage) {
return d.Scp.Extract(s), d.Cp.Extract(s), d.Bp.Extract(s)
}

// NewHandler wraps the passed handler, functioning like middleware, in a span
// named after the operation and with any provided HandlerOptions.
func NewHandler(handler http.Handler, operation string, opts ...Option) http.Handler {
h := Handler{handler: handler, operation: operation}
defaultOpts := []Option{
WithTracer(global.TraceProvider().GetTracer("go.opentelemtry.io/plugin/othttp")),
WithPropagator(prop.HTTPTraceContextPropagator{}),
WithTracer(global.TraceProvider().GetTracer("go.opentelemetry.io/otel/plugin/othttp")),
WithPropagator(newDefaultPropagator()),
WithSpanOptions(trace.WithSpanKind(trace.SpanKindServer)),
}

Expand All @@ -141,12 +167,20 @@ func NewHandler(handler http.Handler, operation string, opts ...Option) http.Han
return &h
}

type propagatorAsInjector struct {
prop propagation.Propagator
}

func (p propagatorAsInjector) Inject(ctx context.Context, s propagation.Supplier) {
p.prop.Inject(trace.CurrentSpan(ctx).SpanContext(), dctx.CorrelationsFromContext(ctx), dctx.BaggageFromContext(ctx), s)
}

// ServeHTTP serves HTTP requests (http.Handler)
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
opts := append([]trace.SpanOption{}, h.spanOptions...) // start with the configured options

// TODO: do something with the correlation context
sc, _ := h.prop.Extract(r.Context(), r.Header)
sc, c, b := h.prop.Extract(r.Header)
if sc.IsValid() { // not a valid span context, so no link / parent relationship to establish
var opt trace.SpanOption
if h.public {
Expand All @@ -159,7 +193,9 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
opts = append(opts, opt)
}

ctx, span := h.tracer.Start(r.Context(), h.operation, opts...)
ctx := dctx.NewCorrelationsContextMap(r.Context(), c)
ctx = dctx.NewBaggageContext(ctx, b)
ctx, span := h.tracer.Start(ctx, h.operation, opts...)
defer span.End()

readRecordFunc := func(int64) {}
Expand All @@ -178,7 +214,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}

rww := &respWriterWrapper{ResponseWriter: w, record: writeRecordFunc, ctx: ctx, injector: h.prop}
rww := &respWriterWrapper{ResponseWriter: w, record: writeRecordFunc, ctx: ctx, injector: propagatorAsInjector{prop: h.prop}}

// Setup basic span attributes before calling handler.ServeHTTP so that they
// are available to be mutated by the handler if needed.
Expand Down
2 changes: 1 addition & 1 deletion plugin/othttp/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"net/http/httptest"
"testing"

"go.opentelemetry.io/otel/propagation"
propagation "go.opentelemetry.io/otel/propagation/http"

mocktrace "go.opentelemetry.io/otel/internal/trace"
)
Expand Down
2 changes: 1 addition & 1 deletion plugin/othttp/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"io"
"net/http"

"go.opentelemetry.io/otel/api/propagation"
propagation "go.opentelemetry.io/otel/api/propagation/http"
)

var _ io.ReadCloser = &bodyWrapper{}
Expand Down

0 comments on commit cea2722

Please sign in to comment.