|
| 1 | +package runtime |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "cuelang.org/go/cue" |
| 6 | + "cuelang.org/go/cue/cuecontext" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "go.opentelemetry.io/otel" |
| 11 | + "go.opentelemetry.io/otel/baggage" |
| 12 | + "go.opentelemetry.io/otel/propagation" |
| 13 | + tracesdk "go.opentelemetry.io/otel/sdk/trace" |
| 14 | + "go.opentelemetry.io/otel/trace" |
| 15 | + "k8s.io/klog" |
| 16 | + "net/http" |
| 17 | + "strings" |
| 18 | +) |
| 19 | + |
| 20 | +func init() { |
| 21 | + // set the default OTel implementation if the controller did not already handle the setup |
| 22 | + // fallback functionality - preferred to update the controller to handle this |
| 23 | + oTelTracerProviderSet := otel.GetTracerProvider().Tracer("check") != otel.Tracer("check") |
| 24 | + if !oTelTracerProviderSet { |
| 25 | + tp := tracesdk.NewTracerProvider() |
| 26 | + otel.SetTracerProvider(tp) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +type ctxKey string |
| 31 | + |
| 32 | +// PropagatedCtx . |
| 33 | +type PropagatedCtx struct { |
| 34 | + pCtx []byte |
| 35 | + context.Context |
| 36 | +} |
| 37 | + |
| 38 | +const ( |
| 39 | + key ctxKey = "PropagatedCtx" |
| 40 | + headerPrefix = "X-Vela" |
| 41 | + traceParent = "traceparent" |
| 42 | + traceState = "tracestate" |
| 43 | + encodedCtx = "Encoded-Context" |
| 44 | +) |
| 45 | + |
| 46 | +// StartSpan creates a new OpenTelemetry span and returns the updated context and span. |
| 47 | +func StartSpan(ctx context.Context, name string) (context.Context, trace.Span, error) { |
| 48 | + tracer := otel.Tracer(name) |
| 49 | + ctx, span := tracer.Start(ctx, name) |
| 50 | + return ctx, span, nil |
| 51 | +} |
| 52 | + |
| 53 | +// StartSpanWithBaggage creates a new OpenTelemetry span and attaches encoded JSON context as baggage. |
| 54 | +func StartSpanWithBaggage(ctx context.Context, name string, hCtx json.Marshaler) (context.Context, trace.Span, error) { |
| 55 | + jsonCtx, err := json.Marshal(hCtx) |
| 56 | + if err != nil { |
| 57 | + klog.Errorf("failed to marshal json: %v", err) |
| 58 | + return nil, nil, err |
| 59 | + } |
| 60 | + |
| 61 | + member, err := baggage.NewMember(strings.ToLower(encodedCtx), base64.StdEncoding.EncodeToString(jsonCtx)) |
| 62 | + if err != nil { |
| 63 | + klog.Errorf("failed to encode context baggage header: \n%v", err) |
| 64 | + return nil, nil, err |
| 65 | + } |
| 66 | + bag, err := baggage.New(member) |
| 67 | + if err != nil { |
| 68 | + klog.Errorf("failed to create context bag: \n%v", err) |
| 69 | + return nil, nil, err |
| 70 | + } |
| 71 | + ctx = baggage.ContextWithBaggage(ctx, bag) |
| 72 | + |
| 73 | + ctx, span, err := StartSpan(ctx, name) |
| 74 | + return ctx, span, err |
| 75 | +} |
| 76 | + |
| 77 | +// WithBaggage appends additional baggage entries to the context. |
| 78 | +func WithBaggage(ctx context.Context, b map[string]string) (context.Context, error) { |
| 79 | + members := baggage.FromContext(ctx).Members() |
| 80 | + for k, v := range b { |
| 81 | + m, err := baggage.NewMember(k, v) |
| 82 | + if err != nil { |
| 83 | + klog.Errorf("failed to create new member\n%v", err) |
| 84 | + continue |
| 85 | + } |
| 86 | + members = append(members, m) |
| 87 | + } |
| 88 | + bag, err := baggage.New(members...) |
| 89 | + if err != nil { |
| 90 | + klog.Errorf("failed to create context bag: \n%v", err) |
| 91 | + return ctx, err |
| 92 | + } |
| 93 | + return baggage.ContextWithBaggage(ctx, bag), nil |
| 94 | +} |
| 95 | + |
| 96 | +// TraceHeaderPropagator . |
| 97 | +type TraceHeaderPropagator struct { |
| 98 | + traceContextPropagator propagation.TraceContext |
| 99 | +} |
| 100 | + |
| 101 | +// Inject serializes the span baggage and trace context into the provided HTTP headers. |
| 102 | +func (cp TraceHeaderPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) { |
| 103 | + bag := baggage.FromContext(ctx) |
| 104 | + for _, member := range bag.Members() { |
| 105 | + headerName := fmt.Sprintf("%s-%s", headerPrefix, member.Key()) |
| 106 | + carrier.Set(headerName, member.Value()) |
| 107 | + } |
| 108 | + cp.traceContextPropagator.Inject(ctx, carrier) |
| 109 | +} |
| 110 | + |
| 111 | +// Extract reconstructs the span context and baggage from the provided HTTP headers. |
| 112 | +func (cp TraceHeaderPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context { |
| 113 | + ctx = traceHeaderPropagator.traceContextPropagator.Extract(ctx, carrier) |
| 114 | + appContext := &PropagatedCtx{ |
| 115 | + Context: ctx, |
| 116 | + } |
| 117 | + for _, hKey := range carrier.Keys() { |
| 118 | + value := carrier.Get(hKey) |
| 119 | + if strings.HasPrefix(hKey, headerPrefix) { |
| 120 | + strippedKey := strings.TrimPrefix(hKey, headerPrefix+"-") |
| 121 | + |
| 122 | + switch strippedKey { |
| 123 | + |
| 124 | + case encodedCtx: |
| 125 | + dataBytes, err := base64.StdEncoding.DecodeString(value) |
| 126 | + appContext.pCtx = dataBytes |
| 127 | + if err != nil { |
| 128 | + klog.Errorf("error decoding base64 context: %v\n", err) |
| 129 | + continue |
| 130 | + } |
| 131 | + |
| 132 | + case traceParent, traceState: // do nothing |
| 133 | + |
| 134 | + default: |
| 135 | + appContext.Context = context.WithValue(appContext.Context, strings.ToLower(strippedKey), value) |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + return context.WithValue(ctx, key, appContext) |
| 141 | +} |
| 142 | + |
| 143 | +// RawJSON returns the embedded JSON context as a json.RawMessage. |
| 144 | +func (p *PropagatedCtx) RawJSON() json.RawMessage { |
| 145 | + return json.RawMessage(p.pCtx) |
| 146 | +} |
| 147 | + |
| 148 | +// UnmarshalContext unmarshals the embedded JSON context into the provided struct. |
| 149 | +func (p *PropagatedCtx) UnmarshalContext(out interface{}) error { |
| 150 | + return json.Unmarshal(p.pCtx, out) |
| 151 | +} |
| 152 | + |
| 153 | +// GetCueContext returns the embedded JSON context as a CUE value. |
| 154 | +func (p *PropagatedCtx) GetCueContext() (*cue.Value, error) { |
| 155 | + cueCtx := cuecontext.New() |
| 156 | + cueVal := cueCtx.CompileString(string(p.pCtx)) |
| 157 | + if cueVal.Err() != nil { |
| 158 | + return &cue.Value{}, cueVal.Err() |
| 159 | + } |
| 160 | + return &cueVal, nil |
| 161 | +} |
| 162 | + |
| 163 | +// ContextFromHeaders extracts the span context and baggage from an HTTP request and returns the reconstructed ctx. |
| 164 | +func ContextFromHeaders(r *http.Request) context.Context { |
| 165 | + return traceHeaderPropagator.Extract(context.Background(), propagation.HeaderCarrier(r.Header)) |
| 166 | +} |
| 167 | + |
| 168 | +// GetPropagatedContext retrieves the PropagatedCtx from the given context if present. |
| 169 | +func GetPropagatedContext(ctx context.Context) (*PropagatedCtx, bool) { |
| 170 | + pCtx := ctx.Value(key) |
| 171 | + if pCtx != nil { |
| 172 | + if pc, ok := pCtx.(*PropagatedCtx); ok { |
| 173 | + return pc, true |
| 174 | + } |
| 175 | + return nil, false |
| 176 | + } |
| 177 | + return nil, false |
| 178 | +} |
| 179 | + |
| 180 | +// Fields returns the list of HTTP headers used for trace context propagation. |
| 181 | +func (cp TraceHeaderPropagator) Fields() []string { |
| 182 | + return []string{ |
| 183 | + traceParent, |
| 184 | + traceState, |
| 185 | + fmt.Sprintf("%s-%s", headerPrefix, encodedCtx), |
| 186 | + } |
| 187 | +} |
0 commit comments