-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
126 lines (101 loc) · 2.5 KB
/
context.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
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package minitrace
import (
"context"
"sync"
"time"
)
// A span context embedded into ctx.context
type spanContext struct {
parent context.Context
// Shared trace context
traceContext *traceContext
spanID uint64
}
func newSpanContext(ctx context.Context, tracingCtx *traceContext) *spanContext {
return &spanContext{
parent: ctx,
traceContext: tracingCtx,
}
}
type tracingKey struct{}
var activeTraceKey = tracingKey{}
func (s *spanContext) Deadline() (deadline time.Time, ok bool) {
return s.parent.Deadline()
}
func (s *spanContext) Done() <-chan struct{} {
return s.parent.Done()
}
func (s *spanContext) Err() error {
return s.parent.Err()
}
func (s *spanContext) Value(key interface{}) interface{} {
if key == activeTraceKey {
return s
} else {
return s.parent.Value(key)
}
}
type traceContext struct {
/// Frozen fields
traceID uint64
createUnixTimeNs uint64
createMonoTimeNs uint64
/// Shared mutable fields
mu sync.Mutex
collectedSpans []Span
attachment interface{}
collected bool
}
func newTraceContext(traceID uint64, attachment interface{}) *traceContext {
return &traceContext{
traceID: traceID,
createUnixTimeNs: unixtimeNs(),
createMonoTimeNs: monotimeNs(),
attachment: attachment,
collected: false,
}
}
func (tc *traceContext) accessAttachment(fn func(attachment interface{})) (ok bool) {
tc.mu.Lock()
defer tc.mu.Unlock()
if tc.collected {
return false
}
fn(tc.attachment)
return true
}
func (tc *traceContext) pushSpan(span *Span) (ok bool) {
tc.mu.Lock()
defer tc.mu.Unlock()
if tc.collected {
return false
}
tc.collectedSpans = append(tc.collectedSpans, *span)
return true
}
func (tc *traceContext) collect() (trace Trace, attachment interface{}) {
tc.mu.Lock()
defer tc.mu.Unlock()
if tc.collected {
return
}
tc.collected = true
trace.Spans = tc.collectedSpans
trace.TraceID = tc.traceID
attachment = tc.attachment
tc.collectedSpans = nil
tc.attachment = nil
return
}