-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
tracer.go
1665 lines (1481 loc) · 55.9 KB
/
tracer.go
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
// Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tracing
import (
"context"
"fmt"
"os"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/buildutil"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/iterutil"
"github.com/cockroachdb/cockroach/pkg/util/netutil/addr"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/ring"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/petermattis/goid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/jaeger"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/exporters/zipkin"
"go.opentelemetry.io/otel/sdk/resource"
otelsdk "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/net/trace"
)
const (
// maxRecordedSpansPerTrace limits the number of spans per recording, keeping
// recordings from getting too large.
maxRecordedSpansPerTrace = 1000
// maxRecordedBytesPerSpan limits the size of logs and structured in a span;
// use a comfortable limit.
maxLogBytesPerSpan = 256 * (1 << 10) // 256 KiB
maxStructuredBytesPerSpan = 10 * (1 << 10) // 10 KiB
// maxSpanRegistrySize limits the number of local root spans tracked in
// a Tracer's registry.
maxSpanRegistrySize = 5000
// maxLogsPerSpanExternal limits the number of logs in a Span for external
// tracers (net/trace, OpenTelemetry); use a comfortable limit.
maxLogsPerSpanExternal = 1000
// maxSnapshots limits the number of snapshots that a Tracer will hold in
// memory. Beyond this limit, each new snapshot evicts the oldest one.
maxSnapshots = 10
)
// These constants are used to form keys to represent tracing context
// information in "carriers" to be transported across RPC boundaries.
const (
prefixTracerState = "crdb-tracer-"
fieldNameTraceID = prefixTracerState + "traceid"
fieldNameSpanID = prefixTracerState + "spanid"
// fieldNameRecordingType will contain the desired type of trace recording.
fieldNameRecordingType = "rec"
// fieldNameOtel{TraceID,SpanID} will contain the OpenTelemetry span info, hex
// encoded.
fieldNameOtelTraceID = prefixTracerState + "otel_traceid"
fieldNameOtelSpanID = prefixTracerState + "otel_spanid"
// fieldNameDeprecatedVerboseTracing is the carrier key indicating that the trace
// has verbose recording enabled. It means that a) spans derived from this one
// will not be no-op spans and b) they will start recording.
//
// The key is named the way it is for backwards compatibility reasons.
// TODO(andrei): remove in 22.2, once we no longer need to set this key for
// compatibility with 21.2.
fieldNameDeprecatedVerboseTracing = "crdb-baggage-sb"
spanKindTagKey = "span.kind"
)
// TODO(davidh): Once performance issues around redaction are
// resolved via #58610, this setting can be removed so that all traces
// have redactability enabled.
var enableTraceRedactable = settings.RegisterBoolSetting(
settings.TenantWritable,
"trace.redactable.enabled",
"set to true to enable redactability for unstructured events "+
"in traces and to redact traces sent to tenants. "+
"Set to false to coarsely mark unstructured events as redactable "+
" and eliminate them from tenant traces.",
false,
)
var enableNetTrace = settings.RegisterBoolSetting(
settings.TenantWritable,
"trace.debug.enable",
"if set, traces for recent requests can be seen at https://<ui>/debug/requests",
false,
).WithPublic()
var openTelemetryCollector = settings.RegisterValidatedStringSetting(
settings.TenantWritable,
"trace.opentelemetry.collector",
"address of an OpenTelemetry trace collector to receive "+
"traces using the otel gRPC protocol, as <host>:<port>. "+
"If no port is specified, 4317 will be used.",
envutil.EnvOrDefaultString("COCKROACH_OTLP_COLLECTOR", ""),
func(_ *settings.Values, s string) error {
if s == "" {
return nil
}
_, _, err := addr.SplitHostPort(s, "4317")
return err
},
).WithPublic()
var jaegerAgent = settings.RegisterValidatedStringSetting(
settings.TenantWritable,
"trace.jaeger.agent",
"the address of a Jaeger agent to receive traces using the "+
"Jaeger UDP Thrift protocol, as <host>:<port>. "+
"If no port is specified, 6381 will be used.",
envutil.EnvOrDefaultString("COCKROACH_JAEGER", ""),
func(_ *settings.Values, s string) error {
if s == "" {
return nil
}
_, _, err := addr.SplitHostPort(s, "6381")
return err
},
).WithPublic()
// ZipkinCollector is the cluster setting that specifies the Zipkin instance
// to send traces to, if any.
var ZipkinCollector = settings.RegisterValidatedStringSetting(
settings.TenantWritable,
"trace.zipkin.collector",
"the address of a Zipkin instance to receive traces, as <host>:<port>. "+
"If no port is specified, 9411 will be used.",
envutil.EnvOrDefaultString("COCKROACH_ZIPKIN", ""),
func(_ *settings.Values, s string) error {
if s == "" {
return nil
}
_, _, err := addr.SplitHostPort(s, "9411")
return err
},
).WithPublic()
// EnableActiveSpansRegistry controls Tracers configured as
// WithTracingMode(TracingModeFromEnv) (which is the default). When enabled,
// spans are allocated and registered with the active spans registry until
// finished. When disabled, span creation is short-circuited for a small
// performance improvement.
var EnableActiveSpansRegistry = settings.RegisterBoolSetting(
settings.TenantWritable,
"trace.span_registry.enabled",
"if set, ongoing traces can be seen at https://<ui>/#/debug/tracez",
envutil.EnvOrDefaultBool("COCKROACH_REAL_SPANS", true),
).WithPublic()
// panicOnUseAfterFinish, if set, causes use of a span after Finish() to panic
// if detected.
var panicOnUseAfterFinish = buildutil.CrdbTestBuild ||
envutil.EnvOrDefaultBool("COCKROACH_CRASH_ON_SPAN_USE_AFTER_FINISH", false)
// debugUseAfterFinish controls whether to debug uses of Span values after finishing.
// FOR DEBUGGING ONLY. This will slow down the program.
var debugUseAfterFinish = envutil.EnvOrDefaultBool("COCKROACH_DEBUG_SPAN_USE_AFTER_FINISH", false)
// reuseSpans controls whether spans can be re-allocated after they've been
// Finish()ed. See Tracer.spanReusePercent for details.
//
// Span reuse is incompatible with the deadlock detector because, with reuse,
// the span mutexes end up being reused and locked repeatedly in random order on
// the same goroutine. This erroneously looks like a potential deadlock to the
// detector.
var reuseSpans = !syncutil.DeadlockEnabled && envutil.EnvOrDefaultBool("COCKROACH_REUSE_TRACING_SPANS", true)
// detectSpanRefLeaks enables the detection of Span reference leaks - i.e.
// failures to decrement a Span's reference count. If detection is enabled, such
// bugs will cause crashes. Otherwise, such bugs silently prevent reallocations
// of spans, at a memory cost.
//
// The detection mechanism uses runtime finalizers; they're disabled under race
// builds elsewhere.
var detectSpanRefLeaks = buildutil.CrdbTestBuild
// TracingMode specifies whether span creation is enabled or disabled by
// default, when other conditions that don't explicitly turn tracing on don't
// apply.
type TracingMode int
const (
// TracingModeFromEnv configures tracing according to enableTracingByDefault.
TracingModeFromEnv TracingMode = iota
// TracingModeOnDemand means that Spans will no be created unless there's a
// particular reason to create them (i.e. a span being created with
// WithForceRealSpan(), a net.Trace or OpenTelemetry tracers attached).
TracingModeOnDemand
// TracingModeActiveSpansRegistry means that Spans are always created.
// Currently-open spans are accessible through the active spans registry.
//
// If no net.Trace/OpenTelemetry tracer is attached, spans do not record
// events by default (i.e. do not accumulate log messages via Span.Record() or
// a history of finished child spans). In order for a span to record events,
// it must be started with the WithRecording() option).
TracingModeActiveSpansRegistry
)
// SpanReusePercentOpt is the option produced by WithSpanReusePercent(),
// configuring the Tracer's span reuse policy.
type SpanReusePercentOpt uint
var _ TracerOption = SpanReusePercentOpt(0)
// WithSpanReusePercent configures the Tracer span reuse ratio, overriding the
// environmental default.
func WithSpanReusePercent(percent uint32) TracerOption {
if percent > 100 {
panic(fmt.Sprintf("invalid percent: %d", percent))
}
return SpanReusePercentOpt(percent)
}
func (s SpanReusePercentOpt) apply(opt *tracerOptions) {
val := uint32(s)
opt.spanReusePercent = &val
}
// spanReusePercent controls the span reuse probability for Tracers that are not
// explicitly configured with a reuse probability. Tests vary this away from the
// default of 100% in order to make the use-after-Finish detection reliable (see
// panicOnUseAfterFinish).
var spanReusePercent = util.ConstantWithMetamorphicTestRange(
"span-reuse-rate",
100, /* defaultValue - always reuse spans. This turns to 0 if reuseSpans is not set. */
0, /* metamorphic min */
101, /* metamorphic max */
)
// Tracer implements tracing requests. It supports:
//
// - forwarding events to x/net/trace instances
//
// - recording traces. Recorded events can be retrieved at any time.
//
// - OpenTelemetry tracing. This is implemented by maintaining a "shadow"
// OpenTelemetry Span inside each of our spans.
//
// Even when tracing is disabled, we still use this Tracer (with x/net/trace and
// lightstep disabled) because of its recording capability (verbose tracing needs
// to work in all cases).
//
// Tracer is currently stateless so we could have a single instance; however,
// this won't be the case if the cluster settings move away from using global
// state.
type Tracer struct {
// Preallocated noopSpans, used to avoid creating spans when we are not using
// x/net/trace or OpenTelemetry and we are not recording.
noopSpan *Span
sterileNoopSpan *Span
// backardsCompatibilityWith211, if set, makes the Tracer
// work with 21.1 remote nodes.
//
// Accessed atomically.
backwardsCompatibilityWith211 int64
// True if tracing to the debug/requests endpoint. Accessed via t.useNetTrace().
_useNetTrace int32 // updated atomically
// True if we would like spans created from this tracer to be marked
// as redactable. This will make unstructured events logged to those
// spans redactable.
// Currently, this is used to mark spans as redactable and to redact
// them at the network boundary from KV.
_redactable int32 // accessed atomically
// Pointer to an OpenTelemetry tracer used as a "shadow tracer", if any. If
// not nil, the respective *otel.Tracer will be used to create mirror spans
// for all spans that the parent Tracer creates.
otelTracer unsafe.Pointer
// _activeSpansRegistryEnabled controls whether spans are created and
// registered with activeSpansRegistry until they're Finish()ed. If not
// enabled, span creation is generally a no-op unless a recording span is
// explicitly requested.
_activeSpansRegistryEnabled int32 // accessed atomically
// activeSpans is a map that references all non-Finish'ed local root spans,
// i.e. those for which no WithParent(<non-nil>) option was supplied.
activeSpansRegistry *SpanRegistry
snapshotsMu struct {
syncutil.Mutex
// snapshots stores the activeSpansRegistry snapshots taken during the
// Tracer's lifetime. The ring buffer will contain snapshots with contiguous
// IDs, from the oldest one to <oldest id> + maxSnapshots - 1.
snapshots ring.Buffer // snapshotWithID
}
testingMu syncutil.Mutex // protects testingRecordAsyncSpans
testingRecordAsyncSpans bool // see TestingRecordAsyncSpans
// panicOnUseAfterFinish configures the Tracer to crash when a Span is used
// after it was previously Finish()ed. Crashing is best-effort if reuseSpan is
// set - use-after-Finish detection doesn't work across span re-allocations.
panicOnUseAfterFinish bool
// debugUseAfterFinish configures the Tracer to collect expensive extra info
// to help debug use-after-Finish() bugs - stack traces will be collected and
// stored on every Span.Finish().
debugUseAfterFinish bool
// spanReusePercent controls the probability that a Finish()ed Span is made
// available for reuse. A value of 100 configures the Tracer to always reuse
// spans; a value of 0 configures it to not reuse any spans. Values in between
// will cause spans to be reused randomly.
//
// Span reuse works by pooling finished spans in a sync.Pool and re-allocate
// them in order to avoid large dynamic memory allocations. When reusing
// spans, buggy code that uses previously-finished spans can result in trace
// corruption, if the span in question has been reallocated by the time it's
// erroneously used.
//
// Span reuse saves dynamic memory allocations for span creation. Creating a
// span generally still needs to allocate the Context that the span is
// associated with; contexts cannot be reused because they are immutable and
// don't have a clear lifetime. Before span reuse was introduced, we had a way
// to allocate a Span and its Context at once. Compared to that, span reuse
// doesn't save on the absolute number of allocations, but saves on the size
// of these allocations: spans are large and contexts are small. This amounts
// to savings of around 10KB worth of heap for simple queries.
//
// When a span is reused, use-after-Finish detection (as configured by
// panicOnUseAfterFinish) becomes unreliable. That's why tests metamorphically
// set this to less than 100.
spanReusePercent uint32
// spanPool holds spanAllocHelper's. If reuseSpans is set, spans are
// allocated through this pool to reduce dynamic memory allocations.
spanPool sync.Pool
// spansCreated/spansAllocated counts how many spans have been created and how
// many have been allocated (i.e. not reused through the spanPool) since the
// last time TestingGetStatsAndReset() was called. These counters are only
// incremented if the MaintainAllocationCounters testing knob was set.
spansCreated, spansAllocated int32 // atomics
testing TracerTestingKnobs
// stack is populated in NewTracer and is printed in assertions related to
// mixing tracers.
stack string
// closed is set on Close().
_closed int32 // accessed atomically
}
// SpanRegistry is a map that references all non-Finish'ed local root spans,
// i.e. those for which no WithLocalParent(<non-nil>) option was supplied. The
// map is keyed on the span ID, which is deterministically unique.
//
// In normal operation, a local root crdbSpan is inserted on creation and
// removed on .Finish().
//
// The map can be introspected by `Tracer.VisitSpans`. A Span can also be
// retrieved from its ID by `Tracer.GetActiveSpanByID`.
type SpanRegistry struct {
mu struct {
syncutil.Mutex
m map[tracingpb.SpanID]*crdbSpan
}
}
func makeSpanRegistry() *SpanRegistry {
r := &SpanRegistry{}
r.mu.m = make(map[tracingpb.SpanID]*crdbSpan)
return r
}
func (r *SpanRegistry) removeSpanLocked(id tracingpb.SpanID) {
delete(r.mu.m, id)
}
func (r *SpanRegistry) addSpan(s *crdbSpan) {
r.mu.Lock()
defer r.mu.Unlock()
r.addSpanLocked(s)
}
func (r *SpanRegistry) addSpanLocked(s *crdbSpan) {
// Ensure that the registry does not grow unboundedly in case there is a leak.
// When the registry reaches max size, each new span added kicks out an
// arbitrary existing span. We rely on map iteration order here to make this
// cheap.
if len(r.mu.m) == maxSpanRegistrySize {
for k := range r.mu.m {
delete(r.mu.m, k)
break
}
}
r.mu.m[s.spanID] = s
}
// getSpanByID looks up a span in the registry. Returns nil if not found.
func (r *SpanRegistry) getSpanByID(id tracingpb.SpanID) RegistrySpan {
r.mu.Lock()
defer r.mu.Unlock()
crdbSpan, ok := r.mu.m[id]
if !ok {
// Avoid returning a typed nil pointer.
return nil
}
return crdbSpan
}
// VisitRoots calls the visitor callback for every local root span in the
// registry. Iterations stops when the visitor returns an error. If that error
// is iterutils.StopIteration(), then VisitRoots() returns nil.
//
// The callback should not hold on to the span after it returns.
func (r *SpanRegistry) VisitRoots(visitor func(span RegistrySpan) error) error {
// Take a snapshot of the registry and release the lock.
r.mu.Lock()
spans := make([]spanRef, 0, len(r.mu.m))
for _, sp := range r.mu.m {
// We'll keep the spans alive while we're visiting them below.
spans = append(spans, makeSpanRef(sp.sp))
}
r.mu.Unlock()
defer func() {
for i := range spans {
spans[i].release()
}
}()
for _, sp := range spans {
if err := visitor(sp.Span.i.crdb); err != nil {
if iterutil.Done(err) {
return nil
}
return err
}
}
return nil
}
// visitTrace recursively calls the visitor on sp and all its descedents.
func visitTrace(sp *Span, visitor func(sp RegistrySpan)) {
visitor(sp.i.crdb)
sp.visitOpenChildren(func(sp *Span) {
visitTrace(sp, visitor)
})
}
// VisitSpans calls the visitor callback for every span in the
// registry.
//
// The callback should not hold on to the span after it returns.
func (r *SpanRegistry) VisitSpans(visitor func(span RegistrySpan)) {
// Take a snapshot of the registry and release the lock.
r.mu.Lock()
spans := make([]spanRef, 0, len(r.mu.m))
for _, sp := range r.mu.m {
// We'll keep the spans alive while we're visiting them below.
spans = append(spans, makeSpanRef(sp.sp))
}
r.mu.Unlock()
defer func() {
for i := range spans {
spans[i].release()
}
}()
for _, sp := range spans {
visitTrace(sp.Span, visitor)
}
}
// testingAll returns (pointers to) all the spans in the registry, in an
// arbitrary order. Since spans can generally finish at any point and use of a
// finished span is not permitted, this method is only suitable for tests.
func (r *SpanRegistry) testingAll() []*crdbSpan {
r.mu.Lock()
defer r.mu.Unlock()
res := make([]*crdbSpan, 0, len(r.mu.m))
for _, sp := range r.mu.m {
res = append(res, sp)
}
return res
}
// swap atomically swaps a span with its children. This is called when a parent
// finishes for promoting its (still open) children into the registry. Before
// removing the parent from the registry, the children are accessible in the
// registry through that parent; if we didn't do this swap when the parent is
// removed, the children would not be part of the registry anymore.
//
// The children are passed as spanRef's, so they're not going to be reallocated
// concurrently with this call. swap takes ownership of the spanRefs, and will
// release() them.
func (r *SpanRegistry) swap(parentID tracingpb.SpanID, children []spanRef) {
r.mu.Lock()
r.removeSpanLocked(parentID)
for _, c := range children {
sp := c.Span.i.crdb
sp.withLock(func() {
if !sp.mu.finished {
r.addSpanLocked(sp)
}
})
}
r.mu.Unlock()
for _, c := range children {
c.release()
}
}
// TracerTestingKnobs contains knobs for a Tracer.
type TracerTestingKnobs struct {
// Clock allows the time source for spans to be controlled.
Clock timeutil.TimeSource
// UseNetTrace, if set, forces the Traces to always create spans which record
// to net.Trace objects.
UseNetTrace bool
// MaintainAllocationCounters, if set, configures the Tracer to maintain
// counters about span creation. See Tracer.GetStatsAndReset().
MaintainAllocationCounters bool
// ReleaseSpanToPool, if set, if called just before a span is put in the
// sync.Pool for reuse. If the hook returns false, the span will not be put in
// the pool.
ReleaseSpanToPool func(*Span) bool
}
// Redactable returns true if the tracer is configured to emit
// redactable logs. This value will affect the redactability of messages
// from already open Spans.
func (t *Tracer) Redactable() bool {
return atomic.LoadInt32(&t._redactable) != 0
}
// SetRedactable changes the redactability of the Tracer. This
// affects any future trace spans created.
func (t *Tracer) SetRedactable(to bool) {
var n int32
if to {
n = 1
}
atomic.StoreInt32(&t._redactable, n)
}
// SetActiveSpansRegistryEnabled controls whether spans are created and
// registered with activeSpansRegistry.
func (t *Tracer) SetActiveSpansRegistryEnabled(to bool) {
var n int32
if to {
n = 1
}
atomic.StoreInt32(&t._activeSpansRegistryEnabled, n)
}
// ActiveSpansRegistryEnabled returns true if this tracer is configured
// to register spans with the activeSpansRegistry
func (t *Tracer) ActiveSpansRegistryEnabled() bool {
return atomic.LoadInt32(&t._activeSpansRegistryEnabled) != 0
}
// NewTracer creates a Tracer with default options.
//
// See NewTracerWithOpt() for controlling various configuration options.
func NewTracer() *Tracer {
var defaultSpanReusePercent uint32
if reuseSpans {
defaultSpanReusePercent = uint32(spanReusePercent)
} else {
defaultSpanReusePercent = 0
}
t := &Tracer{
stack: string(debug.Stack()),
activeSpansRegistry: makeSpanRegistry(),
// These might be overridden in NewTracerWithOpt.
panicOnUseAfterFinish: panicOnUseAfterFinish,
debugUseAfterFinish: debugUseAfterFinish,
spanReusePercent: defaultSpanReusePercent,
}
t.SetActiveSpansRegistryEnabled(true)
t.spanPool = sync.Pool{
New: func() interface{} {
if t.testing.MaintainAllocationCounters {
atomic.AddInt32(&t.spansAllocated, 1)
}
h := new(spanAllocHelper)
// Read-only span fields are assigned here. The rest are initialized in Span.reset().
h.span.helper = h
sp := &h.span
sp.i.tracer = t
c := &h.crdbSpan
*c = crdbSpan{
tracer: t,
sp: sp,
}
sp.i.crdb = c
return h
},
}
t.noopSpan = &Span{i: spanInner{tracer: t}}
t.sterileNoopSpan = &Span{i: spanInner{tracer: t, sterile: true}}
return t
}
// NewTracerWithOpt creates a Tracer and configures it according to the
// passed-in options.
func NewTracerWithOpt(ctx context.Context, opts ...TracerOption) *Tracer {
var o tracerOptions
for _, opt := range opts {
opt.apply(&o)
}
t := NewTracer()
if o.useAfterFinishOpt != nil {
t.panicOnUseAfterFinish = o.useAfterFinishOpt.panicOnUseAfterFinish
t.debugUseAfterFinish = o.useAfterFinishOpt.debugUseAfterFinish
}
if o.spanReusePercent != nil {
t.spanReusePercent = *o.spanReusePercent
}
t.testing = o.knobs
t.SetActiveSpansRegistryEnabled(o.tracingDefault != TracingModeOnDemand)
if o.sv != nil {
t.configure(ctx, o.sv, o.tracingDefault)
}
return t
}
// tracerOptions groups configuration for Tracer construction.
type tracerOptions struct {
sv *settings.Values
knobs TracerTestingKnobs
tracingDefault TracingMode
useAfterFinishOpt *useAfterFinishOpt
// spanReusePercent, if not nil, controls the probability of span reuse. A
// negative value indicates that the default should come from the environment.
// If nil, the probability comes from the environment (test vs production).
spanReusePercent *uint32
}
// TracerOption is implemented by the arguments to the Tracer constructor.
type TracerOption interface {
apply(opt *tracerOptions)
}
type clusterSettingsOpt struct {
sv *settings.Values
}
func (o clusterSettingsOpt) apply(opt *tracerOptions) {
opt.sv = o.sv
}
var _ TracerOption = clusterSettingsOpt{}
// WithClusterSettings configures the Tracer according to the relevant cluster
// settings. Future changes to those cluster settings will update the Tracer.
func WithClusterSettings(sv *settings.Values) TracerOption {
return clusterSettingsOpt{sv: sv}
}
type knobsOpt struct {
knobs TracerTestingKnobs
}
func (o knobsOpt) apply(opt *tracerOptions) {
opt.knobs = o.knobs
}
var _ TracerOption = knobsOpt{}
// WithTestingKnobs configures the Tracer with the specified knobs.
func WithTestingKnobs(knobs TracerTestingKnobs) TracerOption {
return knobsOpt{knobs: knobs}
}
type tracingModeOpt TracingMode
var _ TracerOption = tracingModeOpt(TracingModeFromEnv)
func (o tracingModeOpt) apply(opt *tracerOptions) {
opt.tracingDefault = TracingMode(o)
}
// WithTracingMode configures the Tracer's tracing mode.
func WithTracingMode(opt TracingMode) TracerOption {
return tracingModeOpt(opt)
}
type useAfterFinishOpt struct {
panicOnUseAfterFinish bool
debugUseAfterFinish bool
}
var _ TracerOption = useAfterFinishOpt{}
func (o useAfterFinishOpt) apply(opt *tracerOptions) {
opt.useAfterFinishOpt = &o
}
// WithUseAfterFinishOpt allows control over the Tracer's behavior when a Span
// is used after it had been Finish()ed.
//
// panicOnUseAfterFinish configures the Tracer to panic when it detects that any
// method on a Span is called after that Span was Finish()ed. If not set, such
// uses are tolerated as silent no-ops.
//
// debugUseAfterFinish configures the Tracer to collect stack traces on every
// Span.Finish() call. These are presented when the finished span is reused.
// This option is expensive. It's invalid to debugUseAfterFinish if
// panicOnUseAfterFinish is not set.
func WithUseAfterFinishOpt(panicOnUseAfterFinish, debugUseAfterFinish bool) TracerOption {
if debugUseAfterFinish && !panicOnUseAfterFinish {
panic("it is nonsensical to set debugUseAfterFinish when panicOnUseAfterFinish is not set, " +
"as the collected stacks will never be used")
}
return useAfterFinishOpt{
panicOnUseAfterFinish: panicOnUseAfterFinish,
debugUseAfterFinish: debugUseAfterFinish,
}
}
// configure sets up the Tracer according to the cluster settings (and keeps
// it updated if they change).
func (t *Tracer) configure(ctx context.Context, sv *settings.Values, tracingDefault TracingMode) {
// traceProvider is captured by the function below.
var traceProvider *otelsdk.TracerProvider
// reconfigure will be called every time a cluster setting affecting tracing
// is updated.
reconfigure := func(ctx context.Context) {
jaegerAgentAddr := jaegerAgent.Get(sv)
otlpCollectorAddr := openTelemetryCollector.Get(sv)
zipkinAddr := ZipkinCollector.Get(sv)
enableRedactable := enableTraceRedactable.Get(sv)
switch tracingDefault {
case TracingModeFromEnv:
t.SetActiveSpansRegistryEnabled(EnableActiveSpansRegistry.Get(sv))
case TracingModeOnDemand:
t.SetActiveSpansRegistryEnabled(false)
case TracingModeActiveSpansRegistry:
t.SetActiveSpansRegistryEnabled(true)
default:
panic(fmt.Sprintf("unrecognized tracing option: %v", tracingDefault))
}
t.SetRedactable(enableRedactable)
var nt int32
if enableNetTrace.Get(sv) {
nt = 1
}
atomic.StoreInt32(&t._useNetTrace, nt)
// Return early if the OpenTelemetry tracer is disabled.
if jaegerAgentAddr == "" && otlpCollectorAddr == "" && zipkinAddr == "" {
if traceProvider != nil {
t.SetOpenTelemetryTracer(nil)
if err := traceProvider.Shutdown(ctx); err != nil {
fmt.Fprintf(os.Stderr, "error shutting down tracer: %s", err)
}
}
return
}
opts := []otelsdk.TracerProviderOption{otelsdk.WithSampler(otelsdk.AlwaysSample())}
resource, err := resource.New(ctx,
resource.WithAttributes(semconv.ServiceNameKey.String("CockroachDB")),
)
if err == nil {
opts = append(opts, otelsdk.WithResource(resource))
} else {
fmt.Fprintf(os.Stderr, "failed to create OpenTelemetry resource: %s\n", err)
}
if otlpCollectorAddr != "" {
spanProcessor, err := createOTLPSpanProcessor(ctx, otlpCollectorAddr)
if err == nil {
opts = append(opts, otelsdk.WithSpanProcessor(spanProcessor))
} else {
fmt.Fprintf(os.Stderr, "failed to create OTLP processor: %s", err)
}
}
if jaegerAgentAddr != "" {
spanProcessor, err := createJaegerSpanCollector(ctx, jaegerAgentAddr)
if err == nil {
opts = append(opts, otelsdk.WithSpanProcessor(spanProcessor))
} else {
fmt.Fprintf(os.Stderr, "failed to create Jaeger processor: %s", err)
}
}
if zipkinAddr != "" {
spanProcessor, err := createZipkinCollector(ctx, zipkinAddr)
if err == nil {
opts = append(opts, otelsdk.WithSpanProcessor(spanProcessor))
} else {
fmt.Fprintf(os.Stderr, "failed to create Zipkin processor: %s", err)
}
}
oldTP := traceProvider
traceProvider = otelsdk.NewTracerProvider(opts...)
// Canonical OpenTelemetry wants every module to have its own Tracer
// instance, with each one initialized with a different name. We're not
// doing that though, because our code creates all the spans through a
// single Tracer (the receiver of this method). So, we're creating a
// single Tracer here.
otelTracer := traceProvider.Tracer("crdb")
t.SetOpenTelemetryTracer(otelTracer)
// Shutdown the old tracer.
if oldTP != nil {
_ = oldTP.Shutdown(context.TODO())
}
// TODO(andrei): Figure out how to cleanup the tracer when the server
// exits. It unfortunately seems hard to plumb the Stopper to here to put
// a closer on it.
}
reconfigure(ctx)
EnableActiveSpansRegistry.SetOnChange(sv, reconfigure)
enableNetTrace.SetOnChange(sv, reconfigure)
openTelemetryCollector.SetOnChange(sv, reconfigure)
ZipkinCollector.SetOnChange(sv, reconfigure)
jaegerAgent.SetOnChange(sv, reconfigure)
enableTraceRedactable.SetOnChange(sv, reconfigure)
}
func createOTLPSpanProcessor(
ctx context.Context, otlpCollectorAddr string,
) (otelsdk.SpanProcessor, error) {
host, port, err := addr.SplitHostPort(otlpCollectorAddr, "4317")
if err != nil {
return nil, err
}
exporter, err := otlptracegrpc.New(
ctx,
otlptracegrpc.WithEndpoint(fmt.Sprintf("%s:%s", host, port)),
// TODO(andrei): Add support for secure connections to the collector.
otlptracegrpc.WithInsecure())
if err != nil {
return nil, err
}
spanProcessor := otelsdk.NewBatchSpanProcessor(exporter)
return spanProcessor, nil
}
func createJaegerSpanCollector(
ctx context.Context, agentAddr string,
) (otelsdk.SpanProcessor, error) {
host, port, err := addr.SplitHostPort(agentAddr, "6831")
if err != nil {
return nil, err
}
exporter, err := jaeger.New(jaeger.WithAgentEndpoint(
jaeger.WithAgentHost(host),
jaeger.WithAgentPort(port)))
if err != nil {
return nil, err
}
spanProcessor := otelsdk.NewBatchSpanProcessor(exporter)
return spanProcessor, nil
}
func createZipkinCollector(ctx context.Context, zipkinAddr string) (otelsdk.SpanProcessor, error) {
host, port, err := addr.SplitHostPort(zipkinAddr, "9411")
if err != nil {
return nil, err
}
exporter, err := zipkin.New(fmt.Sprintf("http://%s:%s/api/v2/spans", host, port))
if err != nil {
return nil, err
}
spanProcessor := otelsdk.NewBatchSpanProcessor(exporter)
return spanProcessor, nil
}
// HasExternalSink returns whether the tracer is configured to report
// to an external tracing collector.
func (t *Tracer) HasExternalSink() bool {
return t.getOtelTracer() != nil || t.useNetTrace()
}
func (t *Tracer) useNetTrace() bool {
return t.testing.UseNetTrace || atomic.LoadInt32(&t._useNetTrace) != 0
}
// Close cleans up any resources associated with a Tracer.
func (t *Tracer) Close() {
atomic.StoreInt32(&t._closed, 1)
// Clean up the OpenTelemetry tracer, if any.
t.SetOpenTelemetryTracer(nil)
}
// closed returns true if Close() has been called.
func (t *Tracer) closed() bool {
return atomic.LoadInt32(&t._closed) == 1
}
// SetOpenTelemetryTracer sets the OpenTelemetry tracer to use as a "shadow
// tracer". A nil value means that no otel tracer will be used.
func (t *Tracer) SetOpenTelemetryTracer(tr oteltrace.Tracer) {
var p *oteltrace.Tracer
if tr == nil {
p = nil
} else {
p = &tr
}
atomic.StorePointer(&t.otelTracer, unsafe.Pointer(p))
}
// getOtelTracer returns the OpenTelemetry tracer to use, or nil.
func (t *Tracer) getOtelTracer() oteltrace.Tracer {
p := atomic.LoadPointer(&t.otelTracer)
if p == nil {
return nil
}
return *(*oteltrace.Tracer)(p)
}
// StartSpan starts a Span. See SpanOption for details.
func (t *Tracer) StartSpan(operationName string, os ...SpanOption) *Span {
_, sp := t.StartSpanCtx(noCtx, operationName, os...)
return sp
}
// spanAllocHelper
type spanAllocHelper struct {
span Span
crdbSpan crdbSpan
// Pre-allocated buffers for the span.
tagsAlloc [3]attribute.KeyValue
childrenAlloc [4]childRef
structuredEventsAlloc [3]interface{}
}
// newSpan allocates a span using the Tracer's sync.Pool. A span that was
// previously Finish()ed be returned if the Tracer is configured for Span reuse.
//+(...) must be called on the returned span before further use.
func (t *Tracer) newSpan(
traceID tracingpb.TraceID,
spanID tracingpb.SpanID,
operation string,
goroutineID uint64,
startTime time.Time,
logTags *logtags.Buffer,
eventListeners []EventListener,
kind oteltrace.SpanKind,
otelSpan oteltrace.Span,
netTr trace.Trace,
sterile bool,
notifyParentOnStructuredEvent bool,
) *Span {
if t.testing.MaintainAllocationCounters {
atomic.AddInt32(&t.spansCreated, 1)
}
h := t.spanPool.Get().(*spanAllocHelper)
h.span.reset(
traceID, spanID, operation, goroutineID,
startTime, logTags, eventListeners, kind,
otelSpan, netTr, sterile, notifyParentOnStructuredEvent)
return &h.span
}
// releaseSpanToPool makes sp available for re-allocation. If the Tracer was not
// configured for span reuse, this is a no-op.
func (t *Tracer) releaseSpanToPool(sp *Span) {
switch t.spanReusePercent {
case 0:
return
case 100: