-
Notifications
You must be signed in to change notification settings - Fork 536
Expand file tree
/
Copy pathtextmap.go
More file actions
1506 lines (1401 loc) · 48.1 KB
/
Copy pathtextmap.go
File metadata and controls
1506 lines (1401 loc) · 48.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package tracer
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"sync/atomic"
"maps"
"github.com/DataDog/dd-trace-go/v2/ddtrace/ext"
"github.com/DataDog/dd-trace-go/v2/internal"
"github.com/DataDog/dd-trace-go/v2/internal/env"
"github.com/DataDog/dd-trace-go/v2/internal/log"
"github.com/DataDog/dd-trace-go/v2/internal/samplernames"
)
// HTTPHeadersCarrier wraps an http.Header as a TextMapWriter and TextMapReader, allowing
// it to be used using the provided Propagator implementation.
type HTTPHeadersCarrier http.Header
var _ TextMapWriter = (*HTTPHeadersCarrier)(nil)
var _ TextMapReader = (*HTTPHeadersCarrier)(nil)
// Set implements TextMapWriter.
func (c HTTPHeadersCarrier) Set(key, val string) {
http.Header(c).Set(key, val)
}
// ForeachKey implements TextMapReader.
func (c HTTPHeadersCarrier) ForeachKey(handler func(key, val string) error) error {
for k, vals := range c {
for _, v := range vals {
if err := handler(k, v); err != nil {
return err
}
}
}
return nil
}
// TextMapCarrier allows the use of a regular map[string]string as both TextMapWriter
// and TextMapReader, making it compatible with the provided Propagator.
type TextMapCarrier map[string]string
var _ TextMapWriter = (*TextMapCarrier)(nil)
var _ TextMapReader = (*TextMapCarrier)(nil)
// Set implements TextMapWriter.
func (c TextMapCarrier) Set(key, val string) {
c[key] = val
}
// ForeachKey conforms to the TextMapReader interface.
func (c TextMapCarrier) ForeachKey(handler func(key, val string) error) error {
for k, v := range c {
if err := handler(k, v); err != nil {
return err
}
}
return nil
}
const (
headerPropagationStyleInject = "DD_TRACE_PROPAGATION_STYLE_INJECT"
headerPropagationStyleExtract = "DD_TRACE_PROPAGATION_STYLE_EXTRACT"
headerPropagationStyle = "DD_TRACE_PROPAGATION_STYLE"
)
const (
// DefaultBaggageHeaderPrefix specifies the prefix that will be used in
// HTTP headers or text maps to prefix baggage keys.
DefaultBaggageHeaderPrefix = "ot-baggage-"
// DefaultTraceIDHeader specifies the key that will be used in HTTP headers
// or text maps to store the trace ID.
DefaultTraceIDHeader = "x-datadog-trace-id"
// DefaultParentIDHeader specifies the key that will be used in HTTP headers
// or text maps to store the parent ID.
DefaultParentIDHeader = "x-datadog-parent-id"
// DefaultPriorityHeader specifies the key that will be used in HTTP headers
// or text maps to store the sampling priority value.
DefaultPriorityHeader = "x-datadog-sampling-priority"
// DefaultBaggageHeader specifies the key that will be used in HTTP headers
// or text maps to store the baggage value.
DefaultBaggageHeader = "baggage"
)
// originHeader specifies the name of the header indicating the origin of the trace.
// It is used with the Synthetics product and usually has the value "synthetics".
const originHeader = "x-datadog-origin"
// traceTagsHeader holds the propagated trace tags
const traceTagsHeader = "x-datadog-tags"
// PropagatorConfig defines the configuration for initializing a propagator.
type PropagatorConfig struct {
// BaggagePrefix specifies the prefix that will be used to store baggage
// items in a map. It defaults to DefaultBaggageHeaderPrefix.
BaggagePrefix string
// TraceHeader specifies the map key that will be used to store the trace ID.
// It defaults to DefaultTraceIDHeader.
TraceHeader string
// ParentHeader specifies the map key that will be used to store the parent ID.
// It defaults to DefaultParentIDHeader.
ParentHeader string
// PriorityHeader specifies the map key that will be used to store the sampling priority.
// It defaults to DefaultPriorityHeader.
PriorityHeader string
// MaxTagsHeaderLen specifies the maximum length of trace tags header value.
// It defaults to defaultMaxTagsHeaderLen, a value of 0 disables propagation of tags.
MaxTagsHeaderLen int
// B3 specifies if B3 headers should be added for trace propagation.
// See https://github.com/openzipkin/b3-propagation
B3 bool
// BaggageHeader specifies the map key that will be used to store the baggage key-value pairs.
// It defaults to DefaultBaggageHeader.
BaggageHeader string
}
// NewPropagator returns a new propagator which uses TextMap to inject
// and extract values. It propagates trace and span IDs and baggage.
// To use the defaults, nil may be provided in place of the config.
//
// The inject and extract propagators are determined using environment variables
// with the following order of precedence:
// 1. DD_TRACE_PROPAGATION_STYLE_INJECT
// 2. DD_TRACE_PROPAGATION_STYLE (applies to both inject and extract)
// 3. If none of the above, use default values
func NewPropagator(cfg *PropagatorConfig, propagators ...Propagator) Propagator {
if cfg == nil {
cfg = new(PropagatorConfig)
}
if cfg.BaggagePrefix == "" {
cfg.BaggagePrefix = DefaultBaggageHeaderPrefix
}
if cfg.TraceHeader == "" {
cfg.TraceHeader = DefaultTraceIDHeader
}
if cfg.ParentHeader == "" {
cfg.ParentHeader = DefaultParentIDHeader
}
if cfg.PriorityHeader == "" {
cfg.PriorityHeader = DefaultPriorityHeader
}
if cfg.BaggageHeader == "" {
cfg.BaggageHeader = DefaultBaggageHeader
}
cp := new(chainedPropagator)
cp.onlyExtractFirst = internal.BoolEnv("DD_TRACE_PROPAGATION_EXTRACT_FIRST", false)
if len(propagators) > 0 {
cp.injectors = propagators
cp.extractors = propagators
return cp
}
injectorsPs := env.Get(headerPropagationStyleInject)
extractorsPs := env.Get(headerPropagationStyleExtract)
cp.injectors, cp.injectorNames = getPropagators(cfg, injectorsPs)
cp.extractors, cp.extractorsNames = getPropagators(cfg, extractorsPs)
return cp
}
// chainedPropagator implements Propagator and applies a list of injectors and extractors.
// When injecting, all injectors are called to propagate the span context.
// When extracting, it tries each extractor, selecting the first successful one.
type chainedPropagator struct {
injectors []Propagator
extractors []Propagator
injectorNames string
extractorsNames string
onlyExtractFirst bool // value of DD_TRACE_PROPAGATION_EXTRACT_FIRST
}
// getPropagators returns a list of propagators based on ps, which is a comma seperated
// list of propagators. If the list doesn't contain any valid values, the
// default propagator will be returned. Any invalid values in the list will log
// a warning and be ignored.
func getPropagators(cfg *PropagatorConfig, ps string) ([]Propagator, string) {
dd := &propagator{cfg}
defaultPs := []Propagator{dd, &propagatorW3c{}, &propagatorBaggage{}}
defaultPsName := "datadog,tracecontext,baggage"
if cfg.B3 {
defaultPs = append(defaultPs, &propagatorB3{})
defaultPsName += ",b3"
}
if ps == "" {
if prop := getDDorOtelConfig("propagationStyle"); prop != "" {
ps = prop // use the generic DD_TRACE_PROPAGATION_STYLE if set
} else {
return defaultPs, defaultPsName // no env set, so use default from configuration
}
}
ps = strings.ToLower(ps)
if ps == "none" {
return nil, ""
}
var list []Propagator
var listNames []string
if cfg.B3 {
list = append(list, &propagatorB3{})
listNames = append(listNames, "b3")
}
for v := range strings.SplitSeq(ps, ",") {
switch v := strings.ToLower(v); v {
case "datadog":
list = append(list, dd)
listNames = append(listNames, v)
case "tracecontext":
list = append(list, &propagatorW3c{})
listNames = append(listNames, v)
case "baggage":
list = append(list, &propagatorBaggage{})
listNames = append(listNames, v)
case "b3", "b3multi":
if !cfg.B3 {
// propagatorB3 hasn't already been added, add a new one.
list = append(list, &propagatorB3{})
listNames = append(listNames, v)
}
case "b3 single header":
list = append(list, &propagatorB3SingleHeader{})
listNames = append(listNames, v)
case "none":
log.Warn("Propagator \"none\" has no effect when combined with other propagators. " +
"To disable the propagator, set to `none`")
default:
log.Warn("unrecognized propagator: %s\n", v)
}
}
if len(list) == 0 {
return defaultPs, defaultPsName // no valid propagators, so return default
}
return list, strings.Join(listNames, ",")
}
// Inject defines the Propagator to propagate SpanContext data
// out of the current process. The implementation propagates the
// TraceID and the current active SpanID, as well as the Span baggage.
func (p *chainedPropagator) Inject(spanCtx *SpanContext, carrier any) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
for _, v := range p.injectors {
err := v.Inject(spanCtx, carrier)
if err != nil {
return err
}
}
return nil
}
// Extract implements Propagator. This method will attempt to extract a span context
// based on the precedence order of the propagators. Generally, the first valid
// trace context that could be extracted will be returned. However, the W3C tracestate
// header value will always be extracted and stored in the local trace context even if
// a previous propagator has succeeded so long as the trace-ids match.
// Furthermore, if we have already successfully extracted a trace context and a
// subsequent trace context has conflicting trace information, such information will
// be relayed in the returned SpanContext with a SpanLink.
func (p *chainedPropagator) Extract(carrier any) (*SpanContext, error) {
var ctx *SpanContext
var links []SpanLink
pendingBaggage := make(map[string]string) // used to store baggage items temporarily
for _, v := range p.extractors {
firstExtract := (ctx == nil) // ctx stores the most recently extracted ctx across iterations; if it's nil, no extractor has run yet
extractedCtx, err := v.Extract(carrier)
// If this is the baggage propagator, just stash its items into pendingBaggage
if _, isBaggage := v.(*propagatorBaggage); isBaggage {
if extractedCtx != nil && len(extractedCtx.baggage) > 0 { // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
maps.Copy(pendingBaggage, extractedCtx.baggage) // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
}
continue
}
if firstExtract {
if err != nil {
if p.onlyExtractFirst { // Every error is relevant when we are relying on the first extractor
return nil, err
}
if err != ErrSpanContextNotFound { // We don't care about ErrSpanContextNotFound because we could find a span context in a subsequent extractor
return nil, err
}
}
if p.onlyExtractFirst {
return extractedCtx, nil
}
ctx = extractedCtx
} else { // A local trace context has already been extracted
extractedCtx2 := extractedCtx
ctx2 := ctx
// If we can't cast to spanContext, we can't propgate tracestate or create span links
if extractedCtx2.TraceID() == ctx2.TraceID() {
if pW3C, ok := v.(*propagatorW3c); ok {
pW3C.propagateTracestate(ctx2, extractedCtx2)
// If trace IDs match but span IDs do not, use spanID from `*propagatorW3c` extractedCtx for parenting
if extractedCtx2.SpanID() != ctx2.SpanID() {
var ddCtx *SpanContext
// Grab the datadog-propagated spancontext again
if ddp := getDatadogPropagator(p); ddp != nil {
if ddSpanCtx, err := ddp.Extract(carrier); err == nil {
ddCtx = ddSpanCtx
}
}
overrideDatadogParentID(ctx2, extractedCtx2, ddCtx)
}
}
} else if extractedCtx2 != nil { // Trace IDs do not match - create span links
link := SpanLink{TraceID: extractedCtx2.TraceIDLower(), SpanID: extractedCtx2.SpanID(), TraceIDHigh: extractedCtx2.TraceIDUpper(), Attributes: map[string]string{"reason": "terminated_context", "context_headers": getPropagatorName(v)}}
if trace := extractedCtx2.trace; trace != nil {
if p := trace.priority.Load(); p != nil && uint32(*p) > 0 { // +checklocksignore - Initialization time, freshly extracted trace not yet shared.
link.Flags = 1
} else {
link.Flags = 0
}
link.Tracestate = extractedCtx2.trace.propagatingTag(tracestateHeader)
}
links = append(links, link)
}
}
}
if ctx == nil {
if len(pendingBaggage) > 0 {
ctx := &SpanContext{
baggage: make(map[string]string, len(pendingBaggage)), // +checklocksignore - Initialization time, not shared yet.
baggageOnly: true, // +checklocksignore - Initialization time, not shared yet.
}
maps.Copy(ctx.baggage, pendingBaggage) // +checklocksignore - Initialization time, not shared yet.
atomic.StoreUint32(&ctx.hasBaggage, 1)
return ctx, nil
}
// 0 successful extractions
return nil, ErrSpanContextNotFound
}
if len(pendingBaggage) > 0 {
if ctx.baggage == nil { // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
ctx.baggage = make(map[string]string, len(pendingBaggage)) // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
}
maps.Copy(ctx.baggage, pendingBaggage) // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
atomic.StoreUint32(&ctx.hasBaggage, 1)
}
if len(links) > 0 {
ctx.spanLinks = links // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
}
log.Debug("Extracted span context: %s", ctx.safeDebugString())
return ctx, nil
}
func getPropagatorName(p Propagator) string {
switch p.(type) {
case *propagator:
return "datadog"
case *propagatorB3:
return "b3multi"
case *propagatorB3SingleHeader:
return "b3"
case *propagatorW3c:
return "tracecontext"
case *propagatorBaggage:
return "baggage"
default:
return ""
}
}
// propagateTracestate will add the tracestate propagating tag to the given
// *spanContext. The W3C trace context will be extracted from the provided
// carrier. The trace id of this W3C trace context must match the trace id
// provided by the given *spanContext. If it matches, then the tracestate
// will be re-composed based on the composition of the given *spanContext,
// but will include the non-DD vendors in the W3C trace context's tracestate.
func (p *propagatorW3c) propagateTracestate(ctx *SpanContext, w3cCtx *SpanContext) {
if w3cCtx == nil {
return // It's not valid, so ignore it.
}
if ctx.TraceID() != w3cCtx.TraceID() {
return // The trace-ids must match.
}
if w3cCtx.trace == nil {
return // this shouldn't happen, since it should have a propagating tag already
}
if ctx.trace == nil {
ctx.trace = newTrace()
}
// Get the tracestate header from extracted w3C context, and propagate
// it to the span context that will be returned.
// Note: Other trace context fields like sampling priority, propagated tags,
// and origin will remain unchanged.
ts := w3cCtx.trace.propagatingTag(tracestateHeader)
priority, _ := ctx.SamplingPriority()
setPropagatingTag(ctx, tracestateHeader, composeTracestate(ctx, priority, ts))
ctx.isRemote = (w3cCtx.isRemote)
}
// propagator implements Propagator and injects/extracts span contexts
// using datadog headers. Only TextMap carriers are supported.
type propagator struct {
cfg *PropagatorConfig
}
func (p *propagator) Inject(spanCtx *SpanContext, carrier any) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
switch c := carrier.(type) {
case TextMapWriter:
return p.injectTextMap(spanCtx, c)
default:
return ErrInvalidCarrier
}
}
func (p *propagator) injectTextMap(spanCtx *SpanContext, writer TextMapWriter) error {
ctx := spanCtx
if ctx.traceID.Empty() || ctx.spanID == 0 {
return ErrInvalidSpanContext
}
// propagate the TraceID and the current active SpanID
if ctx.traceID.HasUpper() {
setPropagatingTag(ctx, keyTraceID128, ctx.traceID.UpperHex())
} else if ctx.trace != nil {
ctx.trace.unsetPropagatingTag(keyTraceID128)
}
writer.Set(p.cfg.TraceHeader, strconv.FormatUint(ctx.traceID.Lower(), 10))
writer.Set(p.cfg.ParentHeader, strconv.FormatUint(ctx.spanID, 10))
if sp, ok := ctx.SamplingPriority(); ok {
writer.Set(p.cfg.PriorityHeader, strconv.Itoa(sp))
}
if ctx.origin != "" { // +checklocksignore - Read-only after init.
writer.Set(originHeader, ctx.origin) // +checklocksignore - Read-only after init.
}
ctx.ForeachBaggageItem(func(k, v string) bool {
// Propagate OpenTracing baggage.
writer.Set(p.cfg.BaggagePrefix+k, v)
return true
})
if p.cfg.MaxTagsHeaderLen <= 0 {
return nil
}
if s := p.marshalPropagatingTags(ctx); len(s) > 0 {
writer.Set(traceTagsHeader, s)
}
return nil
}
// marshalPropagatingTags marshals all propagating tags included in ctx to a comma separated string
func (p *propagator) marshalPropagatingTags(ctx *SpanContext) string {
var sb strings.Builder
if ctx.trace == nil {
return ""
}
var properr string
ctx.trace.iteratePropagatingTags(func(k, v string) bool {
if k == tracestateHeader || k == traceparentHeader {
return true // don't propagate W3C headers with the DD propagator
}
if err := isValidPropagatableTag(k, v); err != nil {
log.Warn("Won't propagate tag %q: %s", k, err.Error())
properr = "encoding_error"
return true
}
if tagLen := sb.Len() + len(k) + len(v); tagLen > p.cfg.MaxTagsHeaderLen {
sb.Reset()
log.Warn("Won't propagate tag %q: %q length is (%d) which exceeds the maximum len of (%d).", k, v, tagLen, p.cfg.MaxTagsHeaderLen)
properr = "inject_max_size"
return false
}
if sb.Len() > 0 {
sb.WriteByte(',')
}
sb.WriteString(k)
sb.WriteByte('=')
sb.WriteString(v)
return true
})
if properr != "" {
ctx.trace.setTag(keyPropagationError, properr)
}
return sb.String()
}
func (p *propagator) Extract(carrier any) (*SpanContext, error) {
switch c := carrier.(type) {
case TextMapReader:
return p.extractTextMap(c)
default:
return nil, ErrInvalidCarrier
}
}
func (p *propagator) extractTextMap(reader TextMapReader) (*SpanContext, error) {
var ctx SpanContext
err := reader.ForeachKey(func(k, v string) error {
var err error
key := strings.ToLower(k)
switch key {
case p.cfg.TraceHeader:
var lowerTid uint64
lowerTid, err = parseUint64(v)
if err != nil {
return ErrSpanContextCorrupted
}
ctx.traceID.SetLower(lowerTid)
case p.cfg.ParentHeader:
ctx.spanID, err = parseUint64(v)
if err != nil {
return ErrSpanContextCorrupted
}
case p.cfg.PriorityHeader:
priority, err := strconv.Atoi(v)
if err != nil {
return ErrSpanContextCorrupted
}
ctx.setSamplingPriority(priority, samplernames.Unknown)
case originHeader:
ctx.origin = v // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
case traceTagsHeader:
unmarshalPropagatingTags(&ctx, v, p.cfg.MaxTagsHeaderLen)
default:
if after, ok := strings.CutPrefix(key, p.cfg.BaggagePrefix); ok {
ctx.setBaggageItem(after, v)
}
}
return nil
})
if err != nil {
return nil, err
}
if ctx.trace != nil {
tid := ctx.trace.propagatingTag(keyTraceID128)
if err := validateTID(tid); err != nil {
log.Debug("Invalid hex traceID: %s", err.Error())
ctx.trace.unsetPropagatingTag(keyTraceID128)
} else if err := ctx.traceID.SetUpperFromHex(tid); err != nil {
log.Debug("Attempted to set an invalid hex traceID: %s", err.Error())
ctx.trace.unsetPropagatingTag(keyTraceID128)
}
}
if ctx.traceID.Empty() || (ctx.spanID == 0 && ctx.origin != "synthetics") { // +checklocksignore - Initialization time, freshly extracted ctx not yet shared.
return nil, ErrSpanContextNotFound
}
return &ctx, nil
}
func validateTID(tid string) error {
if len(tid) != 16 {
return fmt.Errorf("invalid length: %q", tid)
}
if !isValidID(tid) {
return fmt.Errorf("malformed: %q", tid)
}
return nil
}
// getDatadogPropagator returns the Datadog Propagator
func getDatadogPropagator(cp *chainedPropagator) *propagator {
for _, e := range cp.extractors {
p, isDatadog := (e).(*propagator)
if isDatadog {
return p
}
}
return nil
}
// overrideDatadogParentID overrides the span ID of a context with the ID extracted from tracecontext headers.
// If the reparenting ID is not set on the context, the span ID from datadog headers is used.
// spanContexts are passed by reference to avoid copying lock value in spanContext type
func overrideDatadogParentID(ctx, w3cCtx, ddCtx *SpanContext) {
if ctx == nil || w3cCtx == nil || ddCtx == nil {
return
}
ctx.spanID = w3cCtx.spanID
if w3cCtx.reparentID != "" {
ctx.reparentID = w3cCtx.reparentID
} else {
// NIT: could be done without using fmt.Sprintf? Is it worth it?
ctx.reparentID = fmt.Sprintf("%016x", ddCtx.SpanID())
}
}
// unmarshalPropagatingTags unmarshals tags from v into ctx, dropping the
// entire header if its length exceeds maxLen. A non-positive maxLen disables
// extraction (mirroring the inject side).
func unmarshalPropagatingTags(ctx *SpanContext, v string, maxLen int) {
if ctx.trace == nil {
ctx.trace = newTrace()
}
if maxLen <= 0 {
return
}
if len(v) > maxLen {
log.Warn("Did not extract %s, size limit exceeded: %d. Incoming tags will not be propagated further.", traceTagsHeader, maxLen)
ctx.trace.setTag(keyPropagationError, "extract_max_size")
return
}
tags, err := parsePropagatableTraceTags(v)
if err != nil {
log.Warn("Did not extract %q: %s. Incoming tags will not be propagated further.", traceTagsHeader, err.Error())
ctx.trace.setTag(keyPropagationError, "decoding_error")
}
ctx.trace.replacePropagatingTags(tags)
}
// setPropagatingTag adds the key value pair to the map of propagating tags on the trace,
// creating the map if one is not initialized.
func setPropagatingTag(ctx *SpanContext, k, v string) {
if ctx.trace == nil {
// extractors initialize a new spanContext, so the trace might be nil
ctx.trace = newTrace()
}
ctx.trace.setPropagatingTag(k, v)
}
const (
b3TraceIDHeader = "x-b3-traceid"
b3SpanIDHeader = "x-b3-spanid"
b3SampledHeader = "x-b3-sampled"
b3SingleHeader = "b3"
)
// propagatorB3 implements Propagator and injects/extracts span contexts
// using B3 headers. Only TextMap carriers are supported.
type propagatorB3 struct{}
func (p *propagatorB3) Inject(spanCtx *SpanContext, carrier any) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
switch c := carrier.(type) {
case TextMapWriter:
return p.injectTextMap(spanCtx, c)
default:
return ErrInvalidCarrier
}
}
func (*propagatorB3) injectTextMap(spanCtx *SpanContext, writer TextMapWriter) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
ctx := spanCtx
if ctx.traceID.Empty() || ctx.spanID == 0 {
return ErrInvalidSpanContext
}
if !ctx.traceID.HasUpper() { // 64-bit trace id
writer.Set(b3TraceIDHeader, fmt.Sprintf("%016x", ctx.traceID.Lower()))
} else { // 128-bit trace id
writer.Set(b3TraceIDHeader, ctx.TraceID())
}
writer.Set(b3SpanIDHeader, fmt.Sprintf("%016x", ctx.spanID))
if p, ok := ctx.SamplingPriority(); ok {
if p >= ext.PriorityAutoKeep {
writer.Set(b3SampledHeader, "1")
} else {
writer.Set(b3SampledHeader, "0")
}
}
return nil
}
func (p *propagatorB3) Extract(carrier any) (*SpanContext, error) {
switch c := carrier.(type) {
case TextMapReader:
return p.extractTextMap(c)
default:
return nil, ErrInvalidCarrier
}
}
func (*propagatorB3) extractTextMap(reader TextMapReader) (*SpanContext, error) {
var ctx SpanContext
err := reader.ForeachKey(func(k, v string) error {
var err error
key := strings.ToLower(k)
switch key {
case b3TraceIDHeader:
if err := extractTraceID128(&ctx, v); err != nil {
return nil
}
case b3SpanIDHeader:
ctx.spanID, err = strconv.ParseUint(v, 16, 64)
if err != nil {
return ErrSpanContextCorrupted
}
case b3SampledHeader:
priority, err := strconv.Atoi(v)
if err != nil {
return ErrSpanContextCorrupted
}
ctx.setSamplingPriority(priority, samplernames.Unknown)
default:
}
return nil
})
if err != nil {
return nil, err
}
if ctx.traceID.Empty() || ctx.spanID == 0 {
return nil, ErrSpanContextNotFound
}
return &ctx, nil
}
// propagatorB3 implements Propagator and injects/extracts span contexts
// using B3 headers. Only TextMap carriers are supported.
type propagatorB3SingleHeader struct{}
func (p *propagatorB3SingleHeader) Inject(spanCtx *SpanContext, carrier any) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
switch c := carrier.(type) {
case TextMapWriter:
return p.injectTextMap(spanCtx, c)
default:
return ErrInvalidCarrier
}
}
func (*propagatorB3SingleHeader) injectTextMap(spanCtx *SpanContext, writer TextMapWriter) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
ctx := spanCtx
if ctx.traceID.Empty() || ctx.spanID == 0 {
return ErrInvalidSpanContext
}
sb := strings.Builder{}
var traceID string
if !ctx.traceID.HasUpper() { // 64-bit trace id
traceID = fmt.Sprintf("%016x", ctx.traceID.Lower())
} else { // 128-bit trace id
traceID = ctx.TraceID()
}
sb.WriteString(fmt.Sprintf("%s-%016x", traceID, ctx.spanID))
if p, ok := ctx.SamplingPriority(); ok {
if p >= ext.PriorityAutoKeep {
sb.WriteString("-1")
} else {
sb.WriteString("-0")
}
}
writer.Set(b3SingleHeader, sb.String())
return nil
}
func (p *propagatorB3SingleHeader) Extract(carrier any) (*SpanContext, error) {
switch c := carrier.(type) {
case TextMapReader:
return p.extractTextMap(c)
default:
return nil, ErrInvalidCarrier
}
}
func (*propagatorB3SingleHeader) extractTextMap(reader TextMapReader) (*SpanContext, error) {
var ctx SpanContext
err := reader.ForeachKey(func(k, v string) error {
var err error
key := strings.ToLower(k)
switch key {
case b3SingleHeader:
b3Parts := strings.Split(v, "-")
if len(b3Parts) >= 2 {
if err = extractTraceID128(&ctx, b3Parts[0]); err != nil {
return err
}
ctx.spanID, err = strconv.ParseUint(b3Parts[1], 16, 64)
if err != nil {
return ErrSpanContextCorrupted
}
if len(b3Parts) >= 3 {
switch b3Parts[2] {
case "":
break
case "1", "d": // Treat 'debug' traces as priority 1
ctx.setSamplingPriority(ext.PriorityAutoKeep, samplernames.Unknown)
case "0":
ctx.setSamplingPriority(ext.PriorityAutoReject, samplernames.Unknown)
default:
return ErrSpanContextCorrupted
}
}
} else {
return ErrSpanContextCorrupted
}
default:
}
return nil
})
if err != nil {
return nil, err
}
if ctx.traceID.Empty() || ctx.spanID == 0 {
return nil, ErrSpanContextNotFound
}
return &ctx, nil
}
const (
traceparentHeader = "traceparent"
tracestateHeader = "tracestate"
// tracestateDDMaxSize bounds the length of a `dd=` list-entry in tracestate.
tracestateDDMaxSize = 256
)
// propagatorW3c implements Propagator and injects/extracts span contexts
// using W3C tracecontext/traceparent headers. Only TextMap carriers are supported.
type propagatorW3c struct{}
func (p *propagatorW3c) Inject(spanCtx *SpanContext, carrier any) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
switch c := carrier.(type) {
case TextMapWriter:
return p.injectTextMap(spanCtx, c)
default:
return ErrInvalidCarrier
}
}
// injectTextMap propagates span context attributes into the writer,
// in the format of the traceparentHeader and tracestateHeader.
// traceparentHeader encodes W3C Trace Propagation version, 128-bit traceID,
// spanID, and a flags field, which supports 8 unique flags.
// The current specification only supports a single flag called sampled,
// which is equal to 00000001 when no other flag is present.
// tracestateHeader is a comma-separated list of list-members with a <key>=<value> format,
// where each list-member is managed by a vendor or instrumentation library.
func (*propagatorW3c) injectTextMap(spanCtx *SpanContext, writer TextMapWriter) error {
if spanCtx == nil {
return ErrInvalidSpanContext
}
ctx := spanCtx
if ctx.traceID.Empty() || ctx.spanID == 0 {
return ErrInvalidSpanContext
}
flags := ""
p, ok := ctx.SamplingPriority()
if ok && p >= ext.PriorityAutoKeep {
flags = "01"
} else {
flags = "00"
}
var traceID string
if ctx.traceID.HasUpper() {
setPropagatingTag(ctx, keyTraceID128, ctx.traceID.UpperHex())
traceID = ctx.TraceID()
} else {
traceID = fmt.Sprintf("%032x", ctx.traceID)
if ctx.trace != nil {
ctx.trace.unsetPropagatingTag(keyTraceID128)
}
}
writer.Set(traceparentHeader, fmt.Sprintf("00-%s-%016x-%v", traceID, ctx.spanID, flags))
// if context priority / origin / tags were updated after extraction,
// or if there is a span on the trace
// or the tracestateHeader doesn't start with `dd=`
// we need to recreate tracestate
if ctx.updated ||
(!ctx.isRemote || ctx.isRemote && ctx.trace != nil && ctx.trace.root != nil) ||
(ctx.trace != nil && !strings.HasPrefix(ctx.trace.propagatingTag(tracestateHeader), "dd=")) ||
ctx.trace.propagatingTagsLen() == 0 {
// compose a new value for the tracestate
writer.Set(tracestateHeader, composeTracestate(ctx, p, ctx.trace.propagatingTag(tracestateHeader)))
} else {
// use a cached value for the tracestate (e.g., no updating p: key)
writer.Set(tracestateHeader, ctx.trace.propagatingTag(tracestateHeader))
}
return nil
}
// stringMutator maps characters in a string to new characters. It is a state machine intended
// to replace regex patterns for simple character replacement, including collapsing runs of a
// specific range.
//
// It's designed after the `hash#Hash` interface, and to work with `strings.Map`.
type stringMutator struct {
// n is the current state of the mutator. It is used to track runs of characters that should
// be collapsed.
n bool
// fn is the function that implements the character replacement logic.
// It returns the rune to use as replacement and a bool to tell if next consecutive
// characters must be dropped if they fall in the currently matched character set.
// It's possible to return `-1` to immediately drop the current rune.
//
// This logic allows for:
// - Replace only the current rune: return <new value>, false
// - Drop only the current rune: return -1, false
// - Replace the current rune and drop the next consecutive runes if they match the same case: return <new value>, true
// - Drop all the consecutive runes matching the same case as the current one: return -1, true
//
// A known limitation is that we can only support a single case of consecutive runes.
fn func(rune) (rune, bool)
}
// Mutate the mapped string using `strings.Map` and the provided function implementing the character
// replacement logic.
func (sm *stringMutator) Mutate(fn func(rune) (rune, bool), s string) string {
sm.fn = fn
rs := strings.Map(sm.mapping, s)
sm.reset()
return rs
}
func (sm *stringMutator) mapping(r rune) rune {
v, dropConsecutiveMatches := sm.fn(r)
if v < 0 {
// We reset the state machine in any match that is not related to a consecutive run
sm.reset()
return -1
}
if dropConsecutiveMatches {
if !sm.n {
sm.n = true
return v
}
return -1
}
// We reset the state machine in any match that is not related to a consecutive run
sm.reset()
return v
}
// reset resets the state of the mutator.
func (sm *stringMutator) reset() {
sm.n = false
}
var (
// keyDisallowedFn is used to sanitize the keys of the datadog propagating tags.
// Disallowed characters are comma (reserved as a list-member separator),
// equals (reserved for list-member key-value separator),
// space and characters outside the ASCII range 0x20 to 0x7E.
// Disallowed characters must be replaced with the underscore.
// Equivalent to regexp.MustCompile(",|=|[^\\x20-\\x7E]+")
keyDisallowedFn = func(r rune) (rune, bool) {
switch {
case r == ',' || r == '=':
return '_', false
case r < 0x20 || r > 0x7E:
return '_', true
}
return r, false
}
// valueDisallowedFn is used to sanitize the values of the datadog propagating tags.
// Disallowed characters are comma (reserved as a list-member separator),
// semi-colon (reserved for separator between entries in the dd list-member),
// tilde (reserved, will represent 0x3D (equals) in the encoded tag value,
// and characters outside the ASCII range 0x20 to 0x7E.
// Equals character must be encoded with a tilde.
// Other disallowed characters must be replaced with the underscore.
// Equivalent to regexp.MustCompile(",|;|~|[^\\x20-\\x7E]+")
valueDisallowedFn = func(r rune) (rune, bool) {
switch {
case r == '=':
return '~', false
case r == ',' || r == '~' || r == ';':
return '_', false
case r < 0x20 || r > 0x7E:
return '_', true
}
return r, false
}
// originDisallowedFn is used to sanitize the value of the datadog origin tag.
// Disallowed characters are comma (reserved as a list-member separator),
// semi-colon (reserved for separator between entries in the dd list-member),
// equals (reserved for list-member key-value separator),
// and characters outside the ASCII range 0x21 to 0x7E.
// Equals character must be encoded with a tilde.
// Other disallowed characters must be replaced with the underscore.
// Equivalent to regexp.MustCompile(",|~|;|[^\\x21-\\x7E]+")
originDisallowedFn = func(r rune) (rune, bool) {