diff --git a/go.mod b/go.mod index 09dcc00..349e9a9 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/equinix-labs/otel-init-go go 1.15 require ( - github.com/google/go-cmp v0.5.6 // indirect + github.com/google/go-cmp v0.5.6 go.opentelemetry.io/otel v1.0.0-RC2 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.0.0-RC2 go.opentelemetry.io/otel/sdk v1.0.0-RC2 diff --git a/otelhelpers/env_traceparent.go b/otelhelpers/env_traceparent.go new file mode 100644 index 0000000..a9035cd --- /dev/null +++ b/otelhelpers/env_traceparent.go @@ -0,0 +1,24 @@ +package otelhelpers + +import ( + "context" + "os" + + "go.opentelemetry.io/otel" +) + +// ContextWithEnvTraceparent is a helper that looks for the the TRACEPARENT +// environment variable and if it's set, it grabs the traceparent and +// adds it to the context it returns. When there is no envvar or it's +// empty, the original context is returned unmodified. +func ContextWithEnvTraceparent(ctx context.Context) context.Context { + traceparent := os.Getenv("TRACEPARENT") + if traceparent != "" { + carrier := SimpleCarrier{} + carrier.Set("traceparent", traceparent) + prop := otel.GetTextMapPropagator() + return prop.Extract(ctx, carrier) + } + + return ctx +} diff --git a/otelhelpers/simple_carrier.go b/otelhelpers/simple_carrier.go new file mode 100644 index 0000000..1d2b7d8 --- /dev/null +++ b/otelhelpers/simple_carrier.go @@ -0,0 +1,33 @@ +package otelhelpers + +// SimpleCarrier is an abstraction for handling traceparent propagation +// that needs a type that implements the propagation.TextMapCarrier(). +// This is the simplest possible implementation that is a little fragile +// but since we're not doing anything else with it, it's fine for this. +type SimpleCarrier map[string]string + +// Get implements the otel interface for propagation. +func (otp SimpleCarrier) Get(key string) string { + return otp[key] +} + +// Set implements the otel interface for propagation. +func (otp SimpleCarrier) Set(key, value string) { + otp[key] = value +} + +// Keys implements the otel interface for propagation. +func (otp SimpleCarrier) Keys() []string { + out := []string{} + for k := range otp { + out = append(out, k) + } + return out +} + +// Clear implements the otel interface for propagation. +func (otp SimpleCarrier) Clear() { + for k := range otp { + delete(otp, k) + } +}