diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5025771 --- /dev/null +++ b/go.mod @@ -0,0 +1,17 @@ +module go.unistack.org/micro-tracer-otel/v4 + +go 1.20 + +require ( + go.opentelemetry.io/otel v1.16.0 + go.opentelemetry.io/otel/sdk v1.16.0 + go.opentelemetry.io/otel/trace v1.16.0 + go.unistack.org/micro/v4 v4.0.4 +) + +require ( + github.com/go-logr/logr v1.2.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + go.opentelemetry.io/otel/metric v1.16.0 // indirect + golang.org/x/sys v0.9.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..336d915 --- /dev/null +++ b/go.sum @@ -0,0 +1,26 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +go.opentelemetry.io/otel v1.16.0 h1:Z7GVAX/UkAXPKsy94IU+i6thsQS4nb7LviLpnaNeW8s= +go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4= +go.opentelemetry.io/otel/metric v1.16.0 h1:RbrpwVG1Hfv85LgnZ7+txXioPDoh6EdbZHo26Q3hqOo= +go.opentelemetry.io/otel/metric v1.16.0/go.mod h1:QE47cpOmkwipPiefDwo2wDzwJrlfxxNYodqc4xnGCo4= +go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= +go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= +go.opentelemetry.io/otel/trace v1.16.0 h1:8JRpaObFoW0pxuVPapkgH8UhHQj+bJW8jJsCZEu5MQs= +go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0= +go.unistack.org/micro/v4 v4.0.1 h1:xo1IxbVfgh8i0eY0VeYa3cbb13u5n/Mxnp3FOgWD4Jo= +go.unistack.org/micro/v4 v4.0.1/go.mod h1:p/J5UcSJjfHsWGT31uKoghQ5rUQZzQJBAFy+Z4+ZVMs= +go.unistack.org/micro/v4 v4.0.4 h1:tbCpqXQTAqK57LeasRR1uSTnGC+xs7K57bxifKmhzUQ= +go.unistack.org/micro/v4 v4.0.4/go.mod h1:+wBa98rSf+mRXb/MuSVFPXtDrqN0k8rzPQiC8wRCwCo= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/options.go b/options.go new file mode 100644 index 0000000..e6a9c2a --- /dev/null +++ b/options.go @@ -0,0 +1,25 @@ +package otel + +import ( + tracesdk "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" + "go.unistack.org/micro/v4/tracer" +) + +type providerKey struct{} + +func Provider(opts ...tracesdk.TracerProvider) tracer.Option { + return tracer.SetOption(providerKey{}, opts) +} + +type providerOptionsKey struct{} + +func ProviderOptions(opts ...tracesdk.TracerProviderOption) tracer.Option { + return tracer.SetOption(providerOptionsKey{}, opts) +} + +type tracerOptionsKey struct{} + +func TracerOptions(opts ...trace.TracerOption) tracer.Option { + return tracer.SetOption(tracerOptionsKey{}, opts) +} diff --git a/otel.go b/otel.go new file mode 100644 index 0000000..3e2bdcb --- /dev/null +++ b/otel.go @@ -0,0 +1,284 @@ +package otel + +import ( + "context" + "errors" + "fmt" + "strings" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/baggage" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + tracesdk "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" + "go.unistack.org/micro/v4/metadata" + "go.unistack.org/micro/v4/tracer" +) + +var _ tracer.Tracer = (*otelTracer)(nil) + +type otelTracer struct { + opts tracer.Options + tracep *tracesdk.TracerProvider + tracer trace.Tracer + propagator propagation.TextMapPropagator +} + +type otelSpan struct { + ctx context.Context + tracer trace.Tracer + tracep *tracesdk.TracerProvider + span trace.Span + opts tracer.SpanOptions + status tracer.SpanStatus + statusMsg string +} + +func (ot *otelTracer) Name() string { + return ot.opts.Name +} + +func (ot *otelTracer) Flush(ctx context.Context) error { + return ot.tracep.ForceFlush(ctx) +} + +func (ot *otelTracer) Init(opts ...tracer.Option) error { + for _, o := range opts { + o(&ot.opts) + } + + var to []trace.TracerOption + if o, ok := ot.opts.Context.Value(tracerOptionsKey{}).([]trace.TracerOption); ok { + to = o + } + + var tp *tracesdk.TracerProvider + if p, ok := ot.opts.Context.Value(providerKey{}).(*tracesdk.TracerProvider); ok { + tp = p + } + + if o, ok := ot.opts.Context.Value(providerOptionsKey{}).([]tracesdk.TracerProviderOption); ok { + tp = tracesdk.NewTracerProvider(o...) + } + + if tp == nil { + return fmt.Errorf("missing Provider or ProviderOptions option") + } + + ot.tracep = tp + ot.tracer = tp.Tracer(ot.opts.Name, to...) + ot.propagator = propagation.NewCompositeTextMapPropagator( + propagation.Baggage{}, + propagation.TraceContext{}, + ) + + return nil +} + +func (ot *otelTracer) Start(ctx context.Context, name string, opts ...tracer.SpanOption) (context.Context, tracer.Span) { + options := tracer.NewSpanOptions(opts...) + var span trace.Span + switch options.Kind { + case tracer.SpanKindInternal, tracer.SpanKindUnspecified: + ctx, span = ot.startSpanFromContext(ctx, name) + case tracer.SpanKindClient, tracer.SpanKindProducer: + ctx, span = ot.startSpanFromOutgoingContext(ctx, name) + case tracer.SpanKindServer, tracer.SpanKindConsumer: + ctx, span = ot.startSpanFromIncomingContext(ctx, name) + } + return ctx, &otelSpan{ctx: ctx, tracep: ot.tracep, tracer: ot.tracer, span: span, opts: options} +} + +func (os *otelSpan) SetStatus(st tracer.SpanStatus, msg string) { + switch st { + case tracer.SpanStatusError: + os.span.SetStatus(codes.Error, msg) + os.span.RecordError(errors.New(msg)) + case tracer.SpanStatusOK: + os.span.SetStatus(codes.Ok, msg) + case tracer.SpanStatusUnset: + os.span.SetStatus(codes.Unset, msg) + } + os.status = st + os.statusMsg = msg +} + +func (os *otelSpan) Status() (tracer.SpanStatus, string) { + return os.status, os.statusMsg +} + +func (os *otelSpan) Tracer() tracer.Tracer { + return &otelTracer{tracep: os.tracep, tracer: os.tracer} +} + +func (os *otelSpan) Finish(opts ...tracer.SpanOption) { + if len(os.opts.Labels) > 0 { + os.span.SetAttributes(convertLabels(os.opts.Labels...)...) + } + os.span.End() +} + +func (os *otelSpan) AddEvent(name string, opts ...tracer.EventOption) { + os.span.AddEvent(name) +} + +func (os *otelSpan) Context() context.Context { + return trace.ContextWithSpan(os.ctx, os.span) +} + +func (os *otelSpan) SetName(name string) { + os.span.SetName(name) +} + +func (os *otelSpan) SetLabels(labels ...interface{}) { + os.opts.Labels = labels +} + +func (os *otelSpan) Kind() tracer.SpanKind { + return os.opts.Kind +} + +func (os *otelSpan) AddLabels(labels ...interface{}) { + os.opts.Labels = append(os.opts.Labels, labels...) +} + +func NewTracer(opts ...tracer.Option) *otelTracer { + options := tracer.NewOptions(opts...) + return &otelTracer{opts: options} +} + +func (ot *otelTracer) startSpanFromContext(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { + md, ok := metadata.FromContext(ctx) + if !ok { + md = metadata.New(1) + } + + mc := make(propagation.MapCarrier) + for k, v := range md { + for _, f := range ot.propagator.Fields() { + if strings.EqualFold(k, f) { + mc[f] = v + } + } + } + + ctx = ot.propagator.Extract(ctx, mc) + spanCtx := trace.SpanContextFromContext(ctx) + ctx = baggage.ContextWithBaggage(ctx, baggage.FromContext(ctx)) + + var span trace.Span + ctx, span = ot.tracer.Start(trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, opts...) + + mc = make(propagation.MapCarrier) + ot.propagator.Inject(ctx, mc) + for k, v := range mc { + md.Set(k, v) + } + ctx = metadata.NewContext(ctx, md) + + return ctx, span +} + +func (ot *otelTracer) startSpanFromOutgoingContext(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { + md, ok := metadata.FromOutgoingContext(ctx) + if !ok { + md = metadata.New(1) + } + + mc := make(propagation.MapCarrier) + for k, v := range md { + for _, f := range ot.propagator.Fields() { + if strings.EqualFold(k, f) { + mc[f] = v + } + } + } + + ctx = ot.propagator.Extract(ctx, mc) + spanCtx := trace.SpanContextFromContext(ctx) + ctx = baggage.ContextWithBaggage(ctx, baggage.FromContext(ctx)) + + var span trace.Span + ctx, span = ot.tracer.Start(trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, opts...) + + mc = make(propagation.MapCarrier) + ot.propagator.Inject(ctx, mc) + for k, v := range mc { + md.Set(k, v) + } + ctx = metadata.NewOutgoingContext(ctx, md) + + return ctx, span +} + +func (ot *otelTracer) startSpanFromIncomingContext(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + md = metadata.New(1) + } + + mc := make(propagation.MapCarrier) + for k, v := range md { + for _, f := range ot.propagator.Fields() { + if strings.EqualFold(k, f) { + mc[f] = v + } + } + } + + ctx = ot.propagator.Extract(ctx, mc) + spanCtx := trace.SpanContextFromContext(ctx) + ctx = baggage.ContextWithBaggage(ctx, baggage.FromContext(ctx)) + + var span trace.Span + ctx, span = ot.tracer.Start(trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, opts...) + + mc = make(propagation.MapCarrier) + ot.propagator.Inject(ctx, mc) + for k, v := range mc { + md.Set(k, v) + } + ctx = metadata.NewIncomingContext(ctx, md) + + return ctx, span +} + +func convertLabels(labels ...interface{}) []attribute.KeyValue { + kv := make([]attribute.KeyValue, 0, len(labels)/2) + for idx := 0; idx < len(labels)/2; idx += 2 { + if v, ok := labels[idx].(attribute.KeyValue); ok { + kv = append(kv, v) + } + switch v := labels[idx+1].(type) { + case attribute.KeyValue: + kv = append(kv, v) + case bool: + kv = append(kv, attribute.Bool(labels[idx].(string), v)) + case []bool: + kv = append(kv, attribute.BoolSlice(labels[idx].(string), v)) + case float64: + kv = append(kv, attribute.Float64(labels[idx].(string), v)) + case []float64: + kv = append(kv, attribute.Float64Slice(labels[idx].(string), v)) + case int: + kv = append(kv, attribute.Int(labels[idx].(string), v)) + case []int: + kv = append(kv, attribute.IntSlice(labels[idx].(string), v)) + case int64: + kv = append(kv, attribute.Int64(labels[idx].(string), v)) + case []int64: + kv = append(kv, attribute.Int64Slice(labels[idx].(string), v)) + case string: + kv = append(kv, attribute.String(labels[idx].(string), v)) + case []string: + kv = append(kv, attribute.StringSlice(labels[idx].(string), v)) + case fmt.Stringer: + kv = append(kv, attribute.Stringer(labels[idx].(string), v)) + default: + kv = append(kv, attribute.String(labels[idx].(string), fmt.Sprintf("%v", v))) + } + } + + return kv +}