| 1 | package tracing |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "net/http" |
| 7 | |
| 8 | "go.opentelemetry.io/contrib/exporters/autoexport" |
| 9 | "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 10 | "go.opentelemetry.io/contrib/propagators/autoprop" |
| 11 | "go.opentelemetry.io/otel/attribute" |
| 12 | "go.opentelemetry.io/otel/propagation" |
| 13 | "go.opentelemetry.io/otel/sdk/resource" |
| 14 | sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 15 | semconv "go.opentelemetry.io/otel/semconv/v1.17.0" |
| 16 | "go.opentelemetry.io/otel/trace" |
| 17 | "go.uber.org/zap" |
| 18 | |
| 19 | "github.com/caddyserver/caddy/v2" |
| 20 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 21 | ) |
| 22 | |
| 23 | const ( |
| 24 | defaultSpanName = "handler" |
| 25 | nextCallCtxKey caddy.CtxKey = "nextCall" |
| 26 | ) |
| 27 | |
| 28 | // nextCall store the next handler, and the error value return on calling it (if any) |
| 29 | type nextCall struct { |
| 30 | next caddyhttp.Handler |
| 31 | err error |
| 32 | } |
| 33 | |
| 34 | // openTelemetryWrapper is responsible for the tracing injection, extraction and propagation. |
| 35 | type openTelemetryWrapper struct { |
| 36 | propagators propagation.TextMapPropagator |
| 37 | |
| 38 | handler http.Handler |
| 39 | |
| 40 | spanName string |
| 41 | spanAttributes map[string]string |
| 42 | } |
| 43 | |
| 44 | // newOpenTelemetryWrapper is responsible for the openTelemetryWrapper initialization using provided configuration. |
| 45 | func newOpenTelemetryWrapper( |
| 46 | ctx context.Context, |
| 47 | spanName string, |
| 48 | spanAttributes map[string]string, |
| 49 | ) (openTelemetryWrapper, error) { |
| 50 | if spanName == "" { |
| 51 | spanName = defaultSpanName |
| 52 | } |
| 53 | |
| 54 | ot := openTelemetryWrapper{ |
| 55 | spanName: spanName, |
| 56 | spanAttributes: spanAttributes, |
| 57 | } |
| 58 | |
| 59 | version, _ := caddy.Version() |
| 60 | res, err := ot.newResource(caddyhttp.ServerHeader, version) |
| 61 | if err != nil { |
| 62 | return ot, fmt.Errorf("creating resource error: %w", err) |
| 63 | } |
| 64 | |
| 65 | traceExporter, err := autoexport.NewSpanExporter(ctx) |
| 66 | if err != nil { |
| 67 | return ot, fmt.Errorf("creating trace exporter error: %w", err) |
| 68 | } |
| 69 | |
| 70 | ot.propagators = autoprop.NewTextMapPropagator() |
| 71 | |
| 72 | tracerProvider := globalTracerProvider.getTracerProvider( |
| 73 | sdktrace.WithBatcher(traceExporter), |
| 74 | sdktrace.WithResource(res), |
| 75 | ) |
| 76 | |
| 77 | ot.handler = otelhttp.NewHandler(http.HandlerFunc(ot.serveHTTP), |
| 78 | ot.spanName, |
| 79 | otelhttp.WithTracerProvider(tracerProvider), |
| 80 | otelhttp.WithPropagators(ot.propagators), |
| 81 | otelhttp.WithSpanNameFormatter(ot.spanNameFormatter), |
| 82 | ) |
| 83 | |
| 84 | return ot, nil |
| 85 | } |
| 86 | |
| 87 | // serveHTTP injects a tracing context and call the next handler. |
| 88 | func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request) { |
| 89 | ctx := r.Context() |
| 90 | ot.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header)) |
| 91 | spanCtx := trace.SpanContextFromContext(ctx) |
| 92 | if spanCtx.IsValid() { |
| 93 | traceID := spanCtx.TraceID().String() |
| 94 | spanID := spanCtx.SpanID().String() |
| 95 | // Add a trace_id placeholder, accessible via `{http.vars.trace_id}`. |
| 96 | caddyhttp.SetVar(ctx, "trace_id", traceID) |
| 97 | // Add a span_id placeholder, accessible via `{http.vars.span_id}`. |
| 98 | caddyhttp.SetVar(ctx, "span_id", spanID) |
| 99 | // Add the traceID and spanID to the log fields for the request. |
| 100 | if extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok { |
| 101 | extra.Add(zap.String("traceID", traceID)) |
| 102 | extra.Add(zap.String("spanID", spanID)) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | next := ctx.Value(nextCallCtxKey).(*nextCall) |
| 107 | next.err = next.next.ServeHTTP(w, r) |
| 108 | |
| 109 | // Add custom span attributes to the current span |
| 110 | span := trace.SpanFromContext(ctx) |
| 111 | if span.IsRecording() && len(ot.spanAttributes) > 0 { |
| 112 | replacer := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 113 | attributes := make([]attribute.KeyValue, 0, len(ot.spanAttributes)) |
| 114 | for key, value := range ot.spanAttributes { |
| 115 | // Allow placeholder replacement in attribute values |
| 116 | replacedValue := replacer.ReplaceAll(value, "") |
| 117 | attributes = append(attributes, attribute.String(key, replacedValue)) |
| 118 | } |
| 119 | span.SetAttributes(attributes...) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // ServeHTTP propagates call to the by wrapped by `otelhttp` next handler. |
| 124 | func (ot *openTelemetryWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { |
| 125 | n := &nextCall{ |
| 126 | next: next, |
| 127 | err: nil, |
| 128 | } |
| 129 | ot.handler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nextCallCtxKey, n))) |
| 130 | |
| 131 | return n.err |
| 132 | } |
| 133 | |
| 134 | // cleanup flush all remaining data and shutdown a tracerProvider |
| 135 | func (ot *openTelemetryWrapper) cleanup(logger *zap.Logger) error { |
| 136 | return globalTracerProvider.cleanupTracerProvider(logger) |
| 137 | } |
| 138 | |
| 139 | // newResource creates a resource that describe current handler instance and merge it with a default attributes value. |
| 140 | func (ot *openTelemetryWrapper) newResource( |
| 141 | webEngineName, |
| 142 | webEngineVersion string, |
| 143 | ) (*resource.Resource, error) { |
| 144 | return resource.Merge(resource.Default(), resource.NewSchemaless( |
| 145 | semconv.WebEngineName(webEngineName), |
| 146 | semconv.WebEngineVersion(webEngineVersion), |
| 147 | )) |
| 148 | } |
| 149 | |
| 150 | // spanNameFormatter performs the replacement of placeholders in the span name |
| 151 | func (ot *openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string { |
| 152 | return r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer).ReplaceAll(operation, "") |
| 153 | } |