podman
595 строк · 16.8 Кб
1// Copyright 2017, OpenCensus Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package trace
16
17import (
18"context"
19crand "crypto/rand"
20"encoding/binary"
21"fmt"
22"math/rand"
23"sync"
24"sync/atomic"
25"time"
26
27"go.opencensus.io/internal"
28"go.opencensus.io/trace/tracestate"
29)
30
31type tracer struct{}
32
33var _ Tracer = &tracer{}
34
35// Span represents a span of a trace. It has an associated SpanContext, and
36// stores data accumulated while the span is active.
37//
38// Ideally users should interact with Spans by calling the functions in this
39// package that take a Context parameter.
40type span struct {
41// data contains information recorded about the span.
42//
43// It will be non-nil if we are exporting the span or recording events for it.
44// Otherwise, data is nil, and the Span is simply a carrier for the
45// SpanContext, so that the trace ID is propagated.
46data *SpanData
47mu sync.Mutex // protects the contents of *data (but not the pointer value.)
48spanContext SpanContext
49
50// lruAttributes are capped at configured limit. When the capacity is reached an oldest entry
51// is removed to create room for a new entry.
52lruAttributes *lruMap
53
54// annotations are stored in FIFO queue capped by configured limit.
55annotations *evictedQueue
56
57// messageEvents are stored in FIFO queue capped by configured limit.
58messageEvents *evictedQueue
59
60// links are stored in FIFO queue capped by configured limit.
61links *evictedQueue
62
63// spanStore is the spanStore this span belongs to, if any, otherwise it is nil.
64*spanStore
65endOnce sync.Once
66
67executionTracerTaskEnd func() // ends the execution tracer span
68}
69
70// IsRecordingEvents returns true if events are being recorded for this span.
71// Use this check to avoid computing expensive annotations when they will never
72// be used.
73func (s *span) IsRecordingEvents() bool {
74if s == nil {
75return false
76}
77return s.data != nil
78}
79
80// TraceOptions contains options associated with a trace span.
81type TraceOptions uint32
82
83// IsSampled returns true if the span will be exported.
84func (sc SpanContext) IsSampled() bool {
85return sc.TraceOptions.IsSampled()
86}
87
88// setIsSampled sets the TraceOptions bit that determines whether the span will be exported.
89func (sc *SpanContext) setIsSampled(sampled bool) {
90if sampled {
91sc.TraceOptions |= 1
92} else {
93sc.TraceOptions &= ^TraceOptions(1)
94}
95}
96
97// IsSampled returns true if the span will be exported.
98func (t TraceOptions) IsSampled() bool {
99return t&1 == 1
100}
101
102// SpanContext contains the state that must propagate across process boundaries.
103//
104// SpanContext is not an implementation of context.Context.
105// TODO: add reference to external Census docs for SpanContext.
106type SpanContext struct {
107TraceID TraceID
108SpanID SpanID
109TraceOptions TraceOptions
110Tracestate *tracestate.Tracestate
111}
112
113type contextKey struct{}
114
115// FromContext returns the Span stored in a context, or nil if there isn't one.
116func (t *tracer) FromContext(ctx context.Context) *Span {
117s, _ := ctx.Value(contextKey{}).(*Span)
118return s
119}
120
121// NewContext returns a new context with the given Span attached.
122func (t *tracer) NewContext(parent context.Context, s *Span) context.Context {
123return context.WithValue(parent, contextKey{}, s)
124}
125
126// All available span kinds. Span kind must be either one of these values.
127const (
128SpanKindUnspecified = iota
129SpanKindServer
130SpanKindClient
131)
132
133// StartOptions contains options concerning how a span is started.
134type StartOptions struct {
135// Sampler to consult for this Span. If provided, it is always consulted.
136//
137// If not provided, then the behavior differs based on whether
138// the parent of this Span is remote, local, or there is no parent.
139// In the case of a remote parent or no parent, the
140// default sampler (see Config) will be consulted. Otherwise,
141// when there is a non-remote parent, no new sampling decision will be made:
142// we will preserve the sampling of the parent.
143Sampler Sampler
144
145// SpanKind represents the kind of a span. If none is set,
146// SpanKindUnspecified is used.
147SpanKind int
148}
149
150// StartOption apply changes to StartOptions.
151type StartOption func(*StartOptions)
152
153// WithSpanKind makes new spans to be created with the given kind.
154func WithSpanKind(spanKind int) StartOption {
155return func(o *StartOptions) {
156o.SpanKind = spanKind
157}
158}
159
160// WithSampler makes new spans to be be created with a custom sampler.
161// Otherwise, the global sampler is used.
162func WithSampler(sampler Sampler) StartOption {
163return func(o *StartOptions) {
164o.Sampler = sampler
165}
166}
167
168// StartSpan starts a new child span of the current span in the context. If
169// there is no span in the context, creates a new trace and span.
170//
171// Returned context contains the newly created span. You can use it to
172// propagate the returned span in process.
173func (t *tracer) StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span) {
174var opts StartOptions
175var parent SpanContext
176if p := t.FromContext(ctx); p != nil {
177if ps, ok := p.internal.(*span); ok {
178ps.addChild()
179}
180parent = p.SpanContext()
181}
182for _, op := range o {
183op(&opts)
184}
185span := startSpanInternal(name, parent != SpanContext{}, parent, false, opts)
186
187ctx, end := startExecutionTracerTask(ctx, name)
188span.executionTracerTaskEnd = end
189extSpan := NewSpan(span)
190return t.NewContext(ctx, extSpan), extSpan
191}
192
193// StartSpanWithRemoteParent starts a new child span of the span from the given parent.
194//
195// If the incoming context contains a parent, it ignores. StartSpanWithRemoteParent is
196// preferred for cases where the parent is propagated via an incoming request.
197//
198// Returned context contains the newly created span. You can use it to
199// propagate the returned span in process.
200func (t *tracer) StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span) {
201var opts StartOptions
202for _, op := range o {
203op(&opts)
204}
205span := startSpanInternal(name, parent != SpanContext{}, parent, true, opts)
206ctx, end := startExecutionTracerTask(ctx, name)
207span.executionTracerTaskEnd = end
208extSpan := NewSpan(span)
209return t.NewContext(ctx, extSpan), extSpan
210}
211
212func startSpanInternal(name string, hasParent bool, parent SpanContext, remoteParent bool, o StartOptions) *span {
213s := &span{}
214s.spanContext = parent
215
216cfg := config.Load().(*Config)
217if gen, ok := cfg.IDGenerator.(*defaultIDGenerator); ok {
218// lazy initialization
219gen.init()
220}
221
222if !hasParent {
223s.spanContext.TraceID = cfg.IDGenerator.NewTraceID()
224}
225s.spanContext.SpanID = cfg.IDGenerator.NewSpanID()
226sampler := cfg.DefaultSampler
227
228if !hasParent || remoteParent || o.Sampler != nil {
229// If this span is the child of a local span and no Sampler is set in the
230// options, keep the parent's TraceOptions.
231//
232// Otherwise, consult the Sampler in the options if it is non-nil, otherwise
233// the default sampler.
234if o.Sampler != nil {
235sampler = o.Sampler
236}
237s.spanContext.setIsSampled(sampler(SamplingParameters{
238ParentContext: parent,
239TraceID: s.spanContext.TraceID,
240SpanID: s.spanContext.SpanID,
241Name: name,
242HasRemoteParent: remoteParent}).Sample)
243}
244
245if !internal.LocalSpanStoreEnabled && !s.spanContext.IsSampled() {
246return s
247}
248
249s.data = &SpanData{
250SpanContext: s.spanContext,
251StartTime: time.Now(),
252SpanKind: o.SpanKind,
253Name: name,
254HasRemoteParent: remoteParent,
255}
256s.lruAttributes = newLruMap(cfg.MaxAttributesPerSpan)
257s.annotations = newEvictedQueue(cfg.MaxAnnotationEventsPerSpan)
258s.messageEvents = newEvictedQueue(cfg.MaxMessageEventsPerSpan)
259s.links = newEvictedQueue(cfg.MaxLinksPerSpan)
260
261if hasParent {
262s.data.ParentSpanID = parent.SpanID
263}
264if internal.LocalSpanStoreEnabled {
265var ss *spanStore
266ss = spanStoreForNameCreateIfNew(name)
267if ss != nil {
268s.spanStore = ss
269ss.add(s)
270}
271}
272
273return s
274}
275
276// End ends the span.
277func (s *span) End() {
278if s == nil {
279return
280}
281if s.executionTracerTaskEnd != nil {
282s.executionTracerTaskEnd()
283}
284if !s.IsRecordingEvents() {
285return
286}
287s.endOnce.Do(func() {
288exp, _ := exporters.Load().(exportersMap)
289mustExport := s.spanContext.IsSampled() && len(exp) > 0
290if s.spanStore != nil || mustExport {
291sd := s.makeSpanData()
292sd.EndTime = internal.MonotonicEndTime(sd.StartTime)
293if s.spanStore != nil {
294s.spanStore.finished(s, sd)
295}
296if mustExport {
297for e := range exp {
298e.ExportSpan(sd)
299}
300}
301}
302})
303}
304
305// makeSpanData produces a SpanData representing the current state of the Span.
306// It requires that s.data is non-nil.
307func (s *span) makeSpanData() *SpanData {
308var sd SpanData
309s.mu.Lock()
310sd = *s.data
311if s.lruAttributes.len() > 0 {
312sd.Attributes = s.lruAttributesToAttributeMap()
313sd.DroppedAttributeCount = s.lruAttributes.droppedCount
314}
315if len(s.annotations.queue) > 0 {
316sd.Annotations = s.interfaceArrayToAnnotationArray()
317sd.DroppedAnnotationCount = s.annotations.droppedCount
318}
319if len(s.messageEvents.queue) > 0 {
320sd.MessageEvents = s.interfaceArrayToMessageEventArray()
321sd.DroppedMessageEventCount = s.messageEvents.droppedCount
322}
323if len(s.links.queue) > 0 {
324sd.Links = s.interfaceArrayToLinksArray()
325sd.DroppedLinkCount = s.links.droppedCount
326}
327s.mu.Unlock()
328return &sd
329}
330
331// SpanContext returns the SpanContext of the span.
332func (s *span) SpanContext() SpanContext {
333if s == nil {
334return SpanContext{}
335}
336return s.spanContext
337}
338
339// SetName sets the name of the span, if it is recording events.
340func (s *span) SetName(name string) {
341if !s.IsRecordingEvents() {
342return
343}
344s.mu.Lock()
345s.data.Name = name
346s.mu.Unlock()
347}
348
349// SetStatus sets the status of the span, if it is recording events.
350func (s *span) SetStatus(status Status) {
351if !s.IsRecordingEvents() {
352return
353}
354s.mu.Lock()
355s.data.Status = status
356s.mu.Unlock()
357}
358
359func (s *span) interfaceArrayToLinksArray() []Link {
360linksArr := make([]Link, 0, len(s.links.queue))
361for _, value := range s.links.queue {
362linksArr = append(linksArr, value.(Link))
363}
364return linksArr
365}
366
367func (s *span) interfaceArrayToMessageEventArray() []MessageEvent {
368messageEventArr := make([]MessageEvent, 0, len(s.messageEvents.queue))
369for _, value := range s.messageEvents.queue {
370messageEventArr = append(messageEventArr, value.(MessageEvent))
371}
372return messageEventArr
373}
374
375func (s *span) interfaceArrayToAnnotationArray() []Annotation {
376annotationArr := make([]Annotation, 0, len(s.annotations.queue))
377for _, value := range s.annotations.queue {
378annotationArr = append(annotationArr, value.(Annotation))
379}
380return annotationArr
381}
382
383func (s *span) lruAttributesToAttributeMap() map[string]interface{} {
384attributes := make(map[string]interface{}, s.lruAttributes.len())
385for _, key := range s.lruAttributes.keys() {
386value, ok := s.lruAttributes.get(key)
387if ok {
388keyStr := key.(string)
389attributes[keyStr] = value
390}
391}
392return attributes
393}
394
395func (s *span) copyToCappedAttributes(attributes []Attribute) {
396for _, a := range attributes {
397s.lruAttributes.add(a.key, a.value)
398}
399}
400
401func (s *span) addChild() {
402if !s.IsRecordingEvents() {
403return
404}
405s.mu.Lock()
406s.data.ChildSpanCount++
407s.mu.Unlock()
408}
409
410// AddAttributes sets attributes in the span.
411//
412// Existing attributes whose keys appear in the attributes parameter are overwritten.
413func (s *span) AddAttributes(attributes ...Attribute) {
414if !s.IsRecordingEvents() {
415return
416}
417s.mu.Lock()
418s.copyToCappedAttributes(attributes)
419s.mu.Unlock()
420}
421
422func (s *span) printStringInternal(attributes []Attribute, str string) {
423now := time.Now()
424var am map[string]interface{}
425if len(attributes) != 0 {
426am = make(map[string]interface{}, len(attributes))
427for _, attr := range attributes {
428am[attr.key] = attr.value
429}
430}
431s.mu.Lock()
432s.annotations.add(Annotation{
433Time: now,
434Message: str,
435Attributes: am,
436})
437s.mu.Unlock()
438}
439
440// Annotate adds an annotation with attributes.
441// Attributes can be nil.
442func (s *span) Annotate(attributes []Attribute, str string) {
443if !s.IsRecordingEvents() {
444return
445}
446s.printStringInternal(attributes, str)
447}
448
449// Annotatef adds an annotation with attributes.
450func (s *span) Annotatef(attributes []Attribute, format string, a ...interface{}) {
451if !s.IsRecordingEvents() {
452return
453}
454s.printStringInternal(attributes, fmt.Sprintf(format, a...))
455}
456
457// AddMessageSendEvent adds a message send event to the span.
458//
459// messageID is an identifier for the message, which is recommended to be
460// unique in this span and the same between the send event and the receive
461// event (this allows to identify a message between the sender and receiver).
462// For example, this could be a sequence id.
463func (s *span) AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64) {
464if !s.IsRecordingEvents() {
465return
466}
467now := time.Now()
468s.mu.Lock()
469s.messageEvents.add(MessageEvent{
470Time: now,
471EventType: MessageEventTypeSent,
472MessageID: messageID,
473UncompressedByteSize: uncompressedByteSize,
474CompressedByteSize: compressedByteSize,
475})
476s.mu.Unlock()
477}
478
479// AddMessageReceiveEvent adds a message receive event to the span.
480//
481// messageID is an identifier for the message, which is recommended to be
482// unique in this span and the same between the send event and the receive
483// event (this allows to identify a message between the sender and receiver).
484// For example, this could be a sequence id.
485func (s *span) AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64) {
486if !s.IsRecordingEvents() {
487return
488}
489now := time.Now()
490s.mu.Lock()
491s.messageEvents.add(MessageEvent{
492Time: now,
493EventType: MessageEventTypeRecv,
494MessageID: messageID,
495UncompressedByteSize: uncompressedByteSize,
496CompressedByteSize: compressedByteSize,
497})
498s.mu.Unlock()
499}
500
501// AddLink adds a link to the span.
502func (s *span) AddLink(l Link) {
503if !s.IsRecordingEvents() {
504return
505}
506s.mu.Lock()
507s.links.add(l)
508s.mu.Unlock()
509}
510
511func (s *span) String() string {
512if s == nil {
513return "<nil>"
514}
515if s.data == nil {
516return fmt.Sprintf("span %s", s.spanContext.SpanID)
517}
518s.mu.Lock()
519str := fmt.Sprintf("span %s %q", s.spanContext.SpanID, s.data.Name)
520s.mu.Unlock()
521return str
522}
523
524var config atomic.Value // access atomically
525
526func init() {
527config.Store(&Config{
528DefaultSampler: ProbabilitySampler(defaultSamplingProbability),
529IDGenerator: &defaultIDGenerator{},
530MaxAttributesPerSpan: DefaultMaxAttributesPerSpan,
531MaxAnnotationEventsPerSpan: DefaultMaxAnnotationEventsPerSpan,
532MaxMessageEventsPerSpan: DefaultMaxMessageEventsPerSpan,
533MaxLinksPerSpan: DefaultMaxLinksPerSpan,
534})
535}
536
537type defaultIDGenerator struct {
538sync.Mutex
539
540// Please keep these as the first fields
541// so that these 8 byte fields will be aligned on addresses
542// divisible by 8, on both 32-bit and 64-bit machines when
543// performing atomic increments and accesses.
544// See:
545// * https://github.com/census-instrumentation/opencensus-go/issues/587
546// * https://github.com/census-instrumentation/opencensus-go/issues/865
547// * https://golang.org/pkg/sync/atomic/#pkg-note-BUG
548nextSpanID uint64
549spanIDInc uint64
550
551traceIDAdd [2]uint64
552traceIDRand *rand.Rand
553
554initOnce sync.Once
555}
556
557// init initializes the generator on the first call to avoid consuming entropy
558// unnecessarily.
559func (gen *defaultIDGenerator) init() {
560gen.initOnce.Do(func() {
561// initialize traceID and spanID generators.
562var rngSeed int64
563for _, p := range []interface{}{
564&rngSeed, &gen.traceIDAdd, &gen.nextSpanID, &gen.spanIDInc,
565} {
566binary.Read(crand.Reader, binary.LittleEndian, p)
567}
568gen.traceIDRand = rand.New(rand.NewSource(rngSeed))
569gen.spanIDInc |= 1
570})
571}
572
573// NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
574func (gen *defaultIDGenerator) NewSpanID() [8]byte {
575var id uint64
576for id == 0 {
577id = atomic.AddUint64(&gen.nextSpanID, gen.spanIDInc)
578}
579var sid [8]byte
580binary.LittleEndian.PutUint64(sid[:], id)
581return sid
582}
583
584// NewTraceID returns a non-zero trace ID from a randomly-chosen sequence.
585// mu should be held while this function is called.
586func (gen *defaultIDGenerator) NewTraceID() [16]byte {
587var tid [16]byte
588// Construct the trace ID from two outputs of traceIDRand, with a constant
589// added to each half for additional entropy.
590gen.Lock()
591binary.LittleEndian.PutUint64(tid[0:8], gen.traceIDRand.Uint64()+gen.traceIDAdd[0])
592binary.LittleEndian.PutUint64(tid[8:16], gen.traceIDRand.Uint64()+gen.traceIDAdd[1])
593gen.Unlock()
594return tid
595}
596