forked from aws/aws-xray-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.go
439 lines (365 loc) · 11.3 KB
/
segment.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
// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package xray
import (
"context"
"crypto/rand"
"fmt"
"os"
"runtime"
"time"
"github.com/aws/aws-xray-sdk-go/header"
"github.com/aws/aws-xray-sdk-go/internal/plugins"
log "github.com/cihub/seelog"
)
// NewTraceID generates a string format of random trace ID.
func NewTraceID() string {
var r [12]byte
_, err := rand.Read(r[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("1-%08x-%02x", time.Now().Unix(), r)
}
// NewSegmentID generates a string format of segment ID.
func NewSegmentID() string {
var r [8]byte
_, err := rand.Read(r[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("%02x", r)
}
// BeginFacadeSegment creates a Segment for a given name and context.
func BeginFacadeSegment(ctx context.Context, name string, h *header.Header) (context.Context, *Segment) {
seg := basicSegment(name, h)
cfg := GetRecorder(ctx)
seg.assignConfiguration(cfg)
return context.WithValue(ctx, ContextKey, seg), seg
}
// BeginSegment creates a Segment for a given name and context.
func BeginSegment(ctx context.Context, name string) (context.Context, *Segment) {
seg := basicSegment(name, nil)
cfg := GetRecorder(ctx)
seg.assignConfiguration(cfg)
seg.Lock()
defer seg.Unlock()
seg.addPlugin(plugins.InstancePluginMetadata)
seg.addSDKAndServiceInformation()
if seg.ParentSegment.GetConfiguration().ServiceVersion != "" {
seg.GetService().Version = seg.ParentSegment.GetConfiguration().ServiceVersion
}
go func() {
select {
case <-ctx.Done():
seg.handleContextDone()
}
}()
return context.WithValue(ctx, ContextKey, seg), seg
}
func basicSegment(name string, h *header.Header) *Segment {
if len(name) > 200 {
name = name[:200]
}
seg := &Segment{parent: nil}
log.Tracef("Beginning segment named %s", name)
seg.ParentSegment = seg
seg.Lock()
defer seg.Unlock()
seg.Name = name
seg.StartTime = float64(time.Now().UnixNano()) / float64(time.Second)
seg.InProgress = true
if h == nil {
seg.TraceID = NewTraceID()
seg.ID = NewSegmentID()
seg.Sampled = true
} else {
seg.Facade = true
seg.ID = h.ParentID
seg.TraceID = h.TraceID
seg.Sampled = h.SamplingDecision == header.Sampled
}
return seg
}
// assignConfiguration assigns value to seg.Configuration
func (seg *Segment) assignConfiguration(cfg *Config) {
seg.Lock()
if cfg == nil {
seg.GetConfiguration().ContextMissingStrategy = globalCfg.contextMissingStrategy
seg.GetConfiguration().ExceptionFormattingStrategy = globalCfg.exceptionFormattingStrategy
seg.GetConfiguration().SamplingStrategy = globalCfg.samplingStrategy
seg.GetConfiguration().StreamingStrategy = globalCfg.streamingStrategy
seg.GetConfiguration().ServiceVersion = globalCfg.serviceVersion
} else {
if cfg.ContextMissingStrategy != nil {
seg.GetConfiguration().ContextMissingStrategy = cfg.ContextMissingStrategy
} else {
seg.GetConfiguration().ContextMissingStrategy = globalCfg.contextMissingStrategy
}
if cfg.ExceptionFormattingStrategy != nil {
seg.GetConfiguration().ExceptionFormattingStrategy = cfg.ExceptionFormattingStrategy
} else {
seg.GetConfiguration().ExceptionFormattingStrategy = globalCfg.exceptionFormattingStrategy
}
if cfg.SamplingStrategy != nil {
seg.GetConfiguration().SamplingStrategy = cfg.SamplingStrategy
} else {
seg.GetConfiguration().SamplingStrategy = globalCfg.samplingStrategy
}
if cfg.StreamingStrategy != nil {
seg.GetConfiguration().StreamingStrategy = cfg.StreamingStrategy
} else {
seg.GetConfiguration().StreamingStrategy = globalCfg.streamingStrategy
}
if cfg.ServiceVersion != "" {
seg.GetConfiguration().ServiceVersion = cfg.ServiceVersion
} else {
seg.GetConfiguration().ServiceVersion = globalCfg.serviceVersion
}
}
seg.Unlock()
}
// BeginSubsegment creates a subsegment for a given name and context.
func BeginSubsegment(ctx context.Context, name string) (context.Context, *Segment) {
if len(name) > 200 {
name = name[:200]
}
parent := &Segment{}
// first time to create facade segment
if getTraceHeaderFromContext(ctx) != nil && GetSegment(ctx) == nil {
_, parent = newFacadeSegment(ctx)
} else {
parent = GetSegment(ctx)
if parent == nil {
cfg := GetRecorder(ctx)
failedMessage := fmt.Sprintf("failed to begin subsegment named '%v': segment cannot be found.", name)
if cfg != nil && cfg.ContextMissingStrategy != nil {
cfg.ContextMissingStrategy.ContextMissing(failedMessage)
} else {
globalCfg.ContextMissingStrategy().ContextMissing(failedMessage)
}
return ctx, nil
}
}
seg := &Segment{parent: parent}
log.Tracef("Beginning subsegment named %s", name)
seg.Lock()
defer seg.Unlock()
parent.Lock()
defer parent.Unlock()
seg.ParentSegment = parent.ParentSegment
if seg.ParentSegment != seg && seg.ParentSegment != parent {
seg.ParentSegment.Lock()
defer seg.ParentSegment.Unlock()
}
seg.ParentSegment.totalSubSegments++
parent.rawSubsegments = append(parent.rawSubsegments, seg)
parent.openSegments++
seg.ID = NewSegmentID()
seg.Name = name
seg.StartTime = float64(time.Now().UnixNano()) / float64(time.Second)
seg.InProgress = true
return context.WithValue(ctx, ContextKey, seg), seg
}
// NewSegmentFromHeader creates a segment for downstream call and add information to the segment that gets from HTTP header.
func NewSegmentFromHeader(ctx context.Context, name string, h *header.Header) (context.Context, *Segment) {
con, seg := BeginSegment(ctx, name)
if h.TraceID != "" {
seg.TraceID = h.TraceID
}
if h.ParentID != "" {
seg.ParentID = h.ParentID
}
seg.Sampled = h.SamplingDecision == header.Sampled
switch h.SamplingDecision {
case header.Sampled:
log.Trace("Incoming header decided: Sampled=true")
case header.NotSampled:
log.Trace("Incoming header decided: Sampled=false")
}
seg.IncomingHeader = h
seg.RequestWasTraced = true
return con, seg
}
// Close a segment.
func (seg *Segment) Close(err error) {
seg.Lock()
defer seg.Unlock()
if seg.parent != nil {
log.Tracef("Closing subsegment named %s", seg.Name)
} else {
log.Tracef("Closing segment named %s", seg.Name)
}
seg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second)
seg.InProgress = false
if err != nil {
seg.addError(err)
}
seg.flush()
}
// CloseAndStream closes a subsegment and sends it.
func (subseg *Segment) CloseAndStream(err error) {
subseg.Lock()
if subseg.parent != nil {
log.Tracef("Ending subsegment named: %s", subseg.Name)
subseg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second)
subseg.InProgress = false
subseg.Emitted = true
if subseg.parent.RemoveSubsegment(subseg) {
log.Tracef("Removing subsegment named: %s", subseg.Name)
}
}
if err != nil {
subseg.addError(err)
}
subseg.beforeEmitSubsegment(subseg.parent)
subseg.Unlock()
Emit(subseg)
}
// RemoveSubsegment removes a subsegment child from a segment or subsegment.
func (seg *Segment) RemoveSubsegment(remove *Segment) bool {
seg.Lock()
defer seg.Unlock()
for i, v := range seg.rawSubsegments {
if v == remove {
seg.rawSubsegments[i] = seg.rawSubsegments[len(seg.rawSubsegments)-1]
seg.rawSubsegments[len(seg.rawSubsegments)-1] = nil
seg.rawSubsegments = seg.rawSubsegments[:len(seg.rawSubsegments)-1]
seg.totalSubSegments--
seg.openSegments--
return true
}
}
return false
}
func (seg *Segment) handleContextDone() {
seg.Lock()
defer seg.Unlock()
seg.ContextDone = true
if !seg.InProgress && !seg.Emitted {
seg.flush()
}
}
func (seg *Segment) flush() {
if (seg.openSegments == 0 && seg.EndTime > 0) || seg.ContextDone {
if seg.parent == nil {
seg.Emitted = true
Emit(seg)
} else if seg.parent != nil && seg.parent.Facade {
seg.Emitted = true
seg.beforeEmitSubsegment(seg.parent)
log.Tracef("emit lambda subsegment named: %v", seg.Name)
Emit(seg)
} else {
seg.parent.safeFlush()
}
}
}
func (seg *Segment) safeFlush() {
seg.Lock()
defer seg.Unlock()
seg.openSegments--
seg.flush()
}
func (seg *Segment) safeInProgress() bool {
seg.Lock()
b := seg.InProgress
seg.Unlock()
return b
}
func (seg *Segment) root() *Segment {
if seg.parent == nil {
return seg
}
return seg.parent.root()
}
func (seg *Segment) addPlugin(metadata *plugins.PluginMetadata) {
// Only called within a seg locked code block
if metadata == nil {
return
}
if metadata.EC2Metadata != nil {
seg.GetAWS()[plugins.EC2ServiceName] = metadata.EC2Metadata
}
if metadata.ECSMetadata != nil {
seg.GetAWS()[plugins.ECSServiceName] = metadata.ECSMetadata
}
if metadata.BeanstalkMetadata != nil {
seg.GetAWS()[plugins.EBServiceName] = metadata.BeanstalkMetadata
}
if metadata.Origin != "" {
seg.Origin = metadata.Origin
}
}
func (seg *Segment) addSDKAndServiceInformation() {
seg.GetAWS()["xray"] = SDK{Version: SDKVersion, Type: SDKType}
seg.GetService().Compiler = runtime.Compiler
seg.GetService().CompilerVersion = runtime.Version()
}
func (sub *Segment) beforeEmitSubsegment(seg *Segment) {
// Only called within a subsegment locked code block
sub.TraceID = seg.root().TraceID
sub.ParentID = seg.ID
sub.Type = "subsegment"
sub.RequestWasTraced = seg.RequestWasTraced
sub.parent = nil
}
// AddAnnotation allows adding an annotation to the segment.
func (seg *Segment) AddAnnotation(key string, value interface{}) error {
switch value.(type) {
case bool, int, uint, float32, float64, string:
default:
return fmt.Errorf("failed to add annotation key: %q value: %q to subsegment %q. value must be of type string, number or boolean", key, value, seg.Name)
}
seg.Lock()
defer seg.Unlock()
if seg.Annotations == nil {
seg.Annotations = map[string]interface{}{}
}
seg.Annotations[key] = value
return nil
}
// AddMetadata allows adding metadata to the segment.
func (seg *Segment) AddMetadata(key string, value interface{}) error {
seg.Lock()
defer seg.Unlock()
if seg.Metadata == nil {
seg.Metadata = map[string]map[string]interface{}{}
}
if seg.Metadata["default"] == nil {
seg.Metadata["default"] = map[string]interface{}{}
}
seg.Metadata["default"][key] = value
return nil
}
// AddMetadataToNamespace allows adding a namespace into metadata for the segment.
func (seg *Segment) AddMetadataToNamespace(namespace string, key string, value interface{}) error {
seg.Lock()
defer seg.Unlock()
if seg.Metadata == nil {
seg.Metadata = map[string]map[string]interface{}{}
}
if seg.Metadata[namespace] == nil {
seg.Metadata[namespace] = map[string]interface{}{}
}
seg.Metadata[namespace][key] = value
return nil
}
// AddError allows adding an error to the segment.
func (seg *Segment) AddError(err error) error {
seg.Lock()
defer seg.Unlock()
seg.addError(err)
return nil
}
func (seg *Segment) addError(err error) error {
seg.Fault = true
seg.GetCause().WorkingDirectory, _ = os.Getwd()
seg.GetCause().Exceptions = append(seg.GetCause().Exceptions, seg.ParentSegment.GetConfiguration().ExceptionFormattingStrategy.ExceptionFromError(err))
return nil
}