forked from stripe/veneur
/
trace.go
340 lines (276 loc) · 8.02 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
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
// Package trace provies an experimental API for initiating
// traces. Veneur's tracing API also provides
// an opentracing compatibility layer. The Veneur tracing API
// is completely independent of the opentracing
// compatibility layer, with the exception of one convenience
// function.
package trace
import (
"context"
"io"
"math/rand"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/stripe/veneur/ssf"
"github.com/golang/protobuf/proto"
opentracing "github.com/opentracing/opentracing-go"
"github.com/sirupsen/logrus"
)
// Experimental
const ResourceKey = "resource"
// (Experimental)
// If this is set to true,
// traces will be generated but not actually sent.
// This should only be set before any traces are generated
var disabled bool = false
var enabledMtx sync.RWMutex
// Make an unexported `key` type that we use as a String such
// that we don't get lint warnings from using it as a key in
// Context. See https://blog.golang.org/context#TOC_3.2.
type key string
const traceKey key = "trace"
// Service is our service name and should be set exactly once,
// at startup
var Service = ""
// For an error to be recorded correctly in DataDog, these three tags
// need to be set
const errorMessageTag = "error.msg"
const errorTypeTag = "error.type"
const errorStackTag = "error.stack"
// Trace is a convenient structural representation
// of a TraceSpan. It is intended to map transparently
// to the more general type SSFSample.
type Trace struct {
// the ID for the root span
// which is also the ID for the trace itself
TraceID int64
// For the root span, this will be equal
// to the TraceId
SpanID int64
// For the root span, this will be <= 0
ParentID int64
// The Resource should be the same for all spans in the same trace
Resource string
Start time.Time
End time.Time
// If non-zero, the trace will be treated
// as an error
Status ssf.SSFSample_Status
Tags map[string]string
// Unlike the Resource, this should not contain spaces
// It should be of the format foo.bar.baz
Name string
// Sent holds a channel. If set, this channel receives an
// error (or nil) when the span has been serialized and sent.
Sent chan<- error
// Samples holds a list of samples / metrics to be reported
// alongside a span.
Samples []*ssf.SSFSample
error bool
}
// Set the end timestamp and finalize Span state
func (t *Trace) finish() {
if t.End.IsZero() {
t.End = time.Now()
}
}
// (Experimental)
// Enabled sets tracing to enabled.
func Enable() {
enabledMtx.Lock()
defer enabledMtx.Unlock()
disabled = false
}
// (Experimental)
// Disabled sets tracing to disabled.
func Disable() {
enabledMtx.Lock()
defer enabledMtx.Unlock()
disabled = true
}
func Disabled() bool {
enabledMtx.RLock()
defer enabledMtx.RUnlock()
return disabled
}
// Duration is a convenience function for
// the difference between the Start and End timestamps.
// It assumes the span has already ended.
func (t *Trace) Duration() time.Duration {
if t.End.IsZero() {
return -1
}
return t.End.Sub(t.Start)
}
// SSFSpan converts the Trace to an SSFSpan type.
// It sets the duration, so it assumes the span has already ended.
// (It is safe to call on a span that has not ended, but the duration
// field will be invalid)
func (t *Trace) SSFSpan() *ssf.SSFSpan {
name := t.Name
span := &ssf.SSFSpan{
StartTimestamp: t.Start.UnixNano(),
Error: t.error,
TraceId: t.TraceID,
Id: t.SpanID,
ParentId: t.ParentID,
EndTimestamp: t.End.UnixNano(),
Name: name,
Tags: t.Tags,
Service: Service,
Metrics: t.Samples,
}
return span
}
// Add adds a number of metrics/samples to a Trace.
func (t *Trace) Add(samples ...*ssf.SSFSample) {
t.Samples = append(t.Samples, samples...)
}
// ProtoMarshalTo writes the Trace as a protocol buffer
// in text format to the specified writer.
func (t *Trace) ProtoMarshalTo(w io.Writer) error {
packet, err := proto.Marshal(t.SSFSpan())
if err != nil {
return err
}
_, err = w.Write(packet)
return err
}
// Record sends a trace to a veneur instance using the DefaultClient .
func (t *Trace) Record(name string, tags map[string]string) error {
return t.ClientRecord(DefaultClient, name, tags)
}
// ClientRecord uses the given client to send a trace to a veneur
// instance.
func (t *Trace) ClientRecord(cl *Client, name string, tags map[string]string) error {
if t.Tags == nil {
t.Tags = map[string]string{}
}
t.finish()
for k, v := range tags {
t.Tags[k] = v
}
if name == "" {
name = t.Name
}
span := t.SSFSpan()
span.Name = name
return Record(cl, span, t.Sent)
}
func (t *Trace) Error(err error) {
t.Status = ssf.SSFSample_CRITICAL
t.error = true
errorType := reflect.TypeOf(err).Name()
if errorType == "" {
errorType = "error"
}
if t.Tags == nil {
t.Tags = map[string]string{}
}
t.Tags[errorMessageTag] = err.Error()
t.Tags[errorTypeTag] = errorType
t.Tags[errorStackTag] = err.Error()
}
// Attach attaches the current trace to the context
// and returns a copy of the context with that trace
// stored under the key "trace".
func (t *Trace) Attach(c context.Context) context.Context {
return context.WithValue(c, traceKey, t)
}
// SpanFromContext is used to create a child span
// when the parent trace is in the context
func SpanFromContext(c context.Context) *Trace {
parent, ok := c.Value(traceKey).(*Trace)
if !ok {
logrus.WithField("type", reflect.TypeOf(c.Value(traceKey))).Error("expected *Trace from context")
}
return StartChildSpan(parent)
}
// StartSpanFromContext is used to create a child span
// when the parent trace is in the context
func StartSpanFromContext(ctx context.Context, name string, opts ...opentracing.StartSpanOption) (s *Span, c context.Context) {
defer func() {
if r := recover(); r != nil {
s = nil
c = ctx
}
}()
if name == "" {
pc, _, _, ok := runtime.Caller(1)
details := runtime.FuncForPC(pc)
if ok && details != nil {
name = stripPackageName(details.Name())
}
}
sp, c := opentracing.StartSpanFromContext(ctx, name, opts...)
s = sp.(*Span)
s.Name = name
return s, c
}
// SetParent updates the ParentId, TraceId, and Resource of a trace
// based on the parent's values (SpanId, TraceId, Resource).
func (t *Trace) SetParent(parent *Trace) {
t.ParentID = parent.SpanID
t.TraceID = parent.TraceID
t.Resource = parent.Resource
}
// context returns a spanContext representing the trace
// from the point of view of itself .
// (The parentid for the trace will be set as the parentid for the context)
func (t *Trace) context() *spanContext {
c := &spanContext{}
c.Init()
c.baggageItems["traceid"] = strconv.FormatInt(t.TraceID, 10)
c.baggageItems["parentid"] = strconv.FormatInt(t.ParentID, 10)
c.baggageItems["spanid"] = strconv.FormatInt(t.SpanID, 10)
c.baggageItems[ResourceKey] = t.Resource
return c
}
// contextAsParent returns a spanContext representing the trace
// from the point of view of its direct children.
// (The SpanId for the trace will be set as the ParentId for the context)
func (t *Trace) contextAsParent() *spanContext {
c := &spanContext{}
c.Init()
c.baggageItems["traceid"] = strconv.FormatInt(t.TraceID, 10)
c.baggageItems["parentid"] = strconv.FormatInt(t.SpanID, 10)
c.baggageItems[ResourceKey] = t.Resource
return c
}
// StartTrace is called by to create the root-level span
// for a trace
func StartTrace(resource string) *Trace {
traceID := proto.Int64(rand.Int63())
t := &Trace{
TraceID: *traceID,
SpanID: *traceID,
ParentID: 0,
Resource: resource,
Tags: map[string]string{},
}
t.Start = time.Now()
return t
}
// StartChildSpan creates a new Span with the specified parent
func StartChildSpan(parent *Trace) *Trace {
spanID := proto.Int64(rand.Int63())
span := &Trace{
SpanID: *spanID,
}
span.SetParent(parent)
span.Start = time.Now()
return span
}
// stripPackageName strips the package name from a function
// name (as formatted by the runtime package)
func stripPackageName(name string) string {
i := strings.LastIndex(name, "/")
if i < 0 || i >= len(name)-1 {
return name
}
return name[i+1:]
}