-
Notifications
You must be signed in to change notification settings - Fork 175
/
trace.go
252 lines (214 loc) · 6.83 KB
/
trace.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
package trace
import (
"context"
"io"
"math/rand"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"github.com/rs/zerolog"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"github.com/onflow/flow-go/model/flow"
)
const DefaultEntityCacheSize = 1000
const SensitivityCaptureAll = 0
const EntityTypeBlock = "Block"
const EntityTypeCollection = "Collection"
const EntityTypeTransaction = "Transaction"
type SpanName string
func (s SpanName) Child(subOp string) SpanName {
return SpanName(string(s) + "." + subOp)
}
// OpenTracer is the implementation of the Tracer interface
type OpenTracer struct {
opentracing.Tracer
closer io.Closer
log zerolog.Logger
spanCache *lru.Cache
sensitivity uint
chainID string
}
type traceLogger struct {
zerolog.Logger
}
func (t traceLogger) Error(msg string) {
t.Logger.Error().Msg(msg)
}
// Infof logs a message at info priority
func (t traceLogger) Infof(msg string, args ...interface{}) {
t.Debug().Msgf(msg, args...)
}
// NewTracer creates a new tracer.
//
// TODO (ramtin) : we might need to add a mutex lock (not sure if tracer itself is thread-safe)
func NewTracer(log zerolog.Logger,
serviceName string,
chainID string,
sensitivity uint) (*OpenTracer, error) {
cfg, err := config.FromEnv()
if err != nil {
return nil, err
}
if cfg.ServiceName == "" {
cfg.ServiceName = serviceName
}
tracer, closer, err := cfg.NewTracer(config.Logger(traceLogger{log}))
if err != nil {
return nil, err
}
spanCache, err := lru.New(int(DefaultEntityCacheSize))
if err != nil {
return nil, err
}
t := &OpenTracer{
Tracer: tracer,
closer: closer,
log: log,
spanCache: spanCache,
sensitivity: sensitivity,
chainID: chainID,
}
return t, nil
}
// Ready returns a channel that will close when the network stack is ready.
func (t *OpenTracer) Ready() <-chan struct{} {
ready := make(chan struct{})
go func() {
close(ready)
}()
return ready
}
// Done returns a channel that will close when shutdown is complete.
func (t *OpenTracer) Done() <-chan struct{} {
done := make(chan struct{})
go func() {
t.closer.Close()
close(done)
}()
return done
}
// entityRootSpan returns the root span for the given entity from the cache
// and if not exist it would construct it and cache it and return it
// This should be used mostly for the very first span created for an entity on the service
func (t *OpenTracer) entityRootSpan(entityID flow.Identifier, entityType string, opts ...opentracing.StartSpanOption) opentracing.Span {
if span, ok := t.spanCache.Get(entityID); ok {
return span.(opentracing.Span)
}
// flow.Identifier to flow
traceID, err := jaeger.TraceIDFromString(entityID.String()[:32])
if err != nil {
// don't panic, gracefully move forward with background context
sp, _ := t.StartSpanFromContext(context.Background(), "entity tracing started")
return sp
}
ctx := jaeger.NewSpanContext(
traceID,
jaeger.SpanID(rand.Uint64()),
jaeger.SpanID(0),
true,
nil,
)
opts = append(opts, jaeger.SelfRef(ctx))
span := t.Tracer.StartSpan(string(entityType), opts...)
// keep full entityID
span.LogFields(log.String("entity_id", entityID.String()))
// set chainID as tag for filtering traces from different networks
span.SetTag("chainID", t.chainID)
t.spanCache.Add(entityID, span)
span.Finish() // finish span right away
return span
}
func (t *OpenTracer) StartBlockSpan(
ctx context.Context,
blockID flow.Identifier,
spanName SpanName,
opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context, bool) {
if !blockID.IsSampled(t.sensitivity) {
return &NoopSpan{&NoopTracer{}}, ctx, false
}
rootSpan := t.entityRootSpan(blockID, EntityTypeBlock)
ctx = opentracing.ContextWithSpan(ctx, rootSpan)
return t.StartSpanFromParent(rootSpan, spanName, opts...), ctx, true
}
func (t *OpenTracer) StartCollectionSpan(
ctx context.Context,
collectionID flow.Identifier,
spanName SpanName,
opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context, bool) {
if !collectionID.IsSampled(t.sensitivity) {
return &NoopSpan{&NoopTracer{}}, ctx, false
}
rootSpan := t.entityRootSpan(collectionID, EntityTypeCollection)
ctx = opentracing.ContextWithSpan(ctx, rootSpan)
return t.StartSpanFromParent(rootSpan, spanName, opts...), ctx, true
}
// StartTransactionSpan starts a span that will be aggregated under the given transaction.
// All spans for the same transaction will be aggregated under a root span
func (t *OpenTracer) StartTransactionSpan(
ctx context.Context,
transactionID flow.Identifier,
spanName SpanName,
opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context, bool) {
if !transactionID.IsSampled(t.sensitivity) {
return &NoopSpan{&NoopTracer{}}, ctx, false
}
rootSpan := t.entityRootSpan(transactionID, EntityTypeTransaction)
ctx = opentracing.ContextWithSpan(ctx, rootSpan)
return t.StartSpanFromParent(rootSpan, spanName, opts...), ctx, true
}
func (t *OpenTracer) StartSpanFromContext(
ctx context.Context,
operationName SpanName,
opts ...opentracing.StartSpanOption,
) (opentracing.Span, context.Context) {
parentSpan := opentracing.SpanFromContext(ctx)
if parentSpan == nil {
return &NoopSpan{&NoopTracer{}}, ctx
}
if _, ok := parentSpan.(*NoopSpan); ok {
return &NoopSpan{&NoopTracer{}}, ctx
}
opts = append(opts, opentracing.ChildOf(parentSpan.Context()))
span := t.Tracer.StartSpan(string(operationName), opts...)
return span, opentracing.ContextWithSpan(ctx, span)
}
func (t *OpenTracer) StartSpanFromParent(
span opentracing.Span,
operationName SpanName,
opts ...opentracing.StartSpanOption,
) opentracing.Span {
if _, ok := span.(*NoopSpan); ok {
return &NoopSpan{&NoopTracer{}}
}
opts = append(opts, opentracing.ChildOf(span.Context()))
return t.Tracer.StartSpan(string(operationName), opts...)
}
func (t *OpenTracer) RecordSpanFromParent(
span opentracing.Span,
operationName SpanName,
duration time.Duration,
logs []opentracing.LogRecord,
opts ...opentracing.StartSpanOption,
) {
if _, ok := span.(*NoopSpan); ok {
return
}
end := time.Now()
start := end.Add(-duration)
opts = append(opts, opentracing.FollowsFrom(span.Context()))
opts = append(opts, opentracing.StartTime(start))
sp := t.Tracer.StartSpan(string(operationName), opts...)
sp.FinishWithOptions(opentracing.FinishOptions{FinishTime: end, LogRecords: logs})
}
// WithSpanFromContext encapsulates executing a function within an span, i.e., it starts a span with the specified SpanName from the context,
// executes the function f, and finishes the span once the function returns.
func (t *OpenTracer) WithSpanFromContext(ctx context.Context,
operationName SpanName,
f func(),
opts ...opentracing.StartSpanOption) {
span, _ := t.StartSpanFromContext(ctx, operationName, opts...)
defer span.Finish()
f()
}