-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathcause.go
617 lines (539 loc) · 16.5 KB
/
cause.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package translator // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/awsxrayexporter/internal/translator"
import (
"bufio"
"encoding/hex"
"net/textproto"
"regexp"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
conventionsv112 "go.opentelemetry.io/collector/semconv/v1.12.0"
conventions "go.opentelemetry.io/collector/semconv/v1.27.0"
awsxray "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray"
)
// ExceptionEventName the name of the exception event.
// TODO: Remove this when collector defines this semantic convention.
const (
ExceptionEventName = "exception"
AwsIndividualHTTPEventName = "HTTP request failure"
AwsIndividualHTTPErrorEventType = "aws.http.error.event"
AwsIndividualHTTPErrorMsgAttr = "aws.http.error_message"
)
func makeCause(span ptrace.Span, attributes map[string]pcommon.Value, resource pcommon.Resource) (isError, isFault, isThrottle bool,
filtered map[string]pcommon.Value, cause *awsxray.CauseData,
) {
status := span.Status()
filtered = attributes
var (
message string
errorKind string
)
isAwsSdkSpan := isAwsSdkSpan(span)
hasExceptionEvents := false
hasAwsIndividualHTTPError := false
for i := 0; i < span.Events().Len(); i++ {
event := span.Events().At(i)
if event.Name() == ExceptionEventName {
hasExceptionEvents = true
break
}
if isAwsSdkSpan && event.Name() == AwsIndividualHTTPEventName {
hasAwsIndividualHTTPError = true
break
}
}
hasExceptions := hasExceptionEvents || hasAwsIndividualHTTPError
switch {
case hasExceptions:
language := ""
if val, ok := resource.Attributes().Get(conventionsv112.AttributeTelemetrySDKLanguage); ok {
language = val.Str()
}
isRemote := false
if span.Kind() == ptrace.SpanKindClient || span.Kind() == ptrace.SpanKindProducer {
isRemote = true
}
var exceptions []awsxray.Exception
for i := 0; i < span.Events().Len(); i++ {
event := span.Events().At(i)
if event.Name() == ExceptionEventName {
exceptionType := ""
message = ""
stacktrace := ""
if val, ok := event.Attributes().Get(conventionsv112.AttributeExceptionType); ok {
exceptionType = val.Str()
}
if val, ok := event.Attributes().Get(conventionsv112.AttributeExceptionMessage); ok {
message = val.Str()
}
if val, ok := event.Attributes().Get(conventionsv112.AttributeExceptionStacktrace); ok {
stacktrace = val.Str()
}
parsed := parseException(exceptionType, message, stacktrace, isRemote, language)
exceptions = append(exceptions, parsed...)
} else if isAwsSdkSpan && event.Name() == AwsIndividualHTTPEventName {
errorCode, ok1 := event.Attributes().Get(conventions.AttributeHTTPResponseStatusCode)
errorMessage, ok2 := event.Attributes().Get(AwsIndividualHTTPErrorMsgAttr)
if ok1 && ok2 {
eventEpochTime := event.Timestamp().AsTime().UnixMicro()
strs := []string{
errorCode.AsString(),
strconv.FormatFloat(float64(eventEpochTime)/1_000_000, 'f', 6, 64),
errorMessage.Str(),
}
message = strings.Join(strs, "@")
segmentID := newSegmentID()
exception := awsxray.Exception{
ID: aws.String(hex.EncodeToString(segmentID[:])),
Type: aws.String(AwsIndividualHTTPErrorEventType),
Remote: aws.Bool(true),
Message: aws.String(message),
}
exceptions = append(exceptions, exception)
}
}
}
cause = &awsxray.CauseData{
Type: awsxray.CauseTypeObject,
CauseObject: awsxray.CauseObject{
Exceptions: exceptions,
},
}
case status.Code() != ptrace.StatusCodeError:
cause = nil
default:
// Use OpenCensus behavior if we didn't find any exception events to ease migration.
message = status.Message()
filtered = make(map[string]pcommon.Value)
for key, value := range attributes {
switch key {
case "http.status_text":
if message == "" {
message = value.Str()
}
default:
filtered[key] = value
}
}
if message != "" {
segmentID := newSegmentID()
cause = &awsxray.CauseData{
Type: awsxray.CauseTypeObject,
CauseObject: awsxray.CauseObject{
Exceptions: []awsxray.Exception{
{
ID: aws.String(hex.EncodeToString(segmentID[:])),
Type: aws.String(errorKind),
Message: aws.String(message),
},
},
},
}
}
}
val, ok := span.Attributes().Get(conventionsv112.AttributeHTTPStatusCode)
if !ok {
val, ok = span.Attributes().Get(conventions.AttributeHTTPResponseStatusCode)
}
// The segment status for http spans will be based on their http.statuscode as we found some http
// spans does not fill with status.Code() but always filled with http.statuscode
var code int64
if ok {
code = val.Int()
}
// Default values
isThrottle = false
isError = false
isFault = false
switch {
case !ok || code < 400 || code > 599:
if status.Code() == ptrace.StatusCodeError {
isFault = true
}
case code >= 400 && code <= 499:
isError = true
if code == 429 {
isThrottle = true
}
case code >= 500 && code <= 599:
isFault = true
}
return isError, isFault, isThrottle, filtered, cause
}
func parseException(exceptionType string, message string, stacktrace string, isRemote bool, language string) []awsxray.Exception {
exceptions := make([]awsxray.Exception, 0, 1)
segmentID := newSegmentID()
exceptions = append(exceptions, awsxray.Exception{
ID: aws.String(hex.EncodeToString(segmentID[:])),
Type: aws.String(exceptionType),
Remote: aws.Bool(isRemote),
Message: aws.String(message),
})
if stacktrace == "" {
return exceptions
}
switch language {
case "java":
exceptions = fillJavaStacktrace(stacktrace, exceptions)
case "python":
exceptions = fillPythonStacktrace(stacktrace, exceptions)
case "javascript":
exceptions = fillJavaScriptStacktrace(stacktrace, exceptions)
case "dotnet":
exceptions = fillDotnetStacktrace(stacktrace, exceptions)
case "php":
// The PHP SDK formats stack traces exactly like Java would
exceptions = fillJavaStacktrace(stacktrace, exceptions)
case "go":
exceptions = fillGoStacktrace(stacktrace, exceptions)
}
return exceptions
}
func fillJavaStacktrace(stacktrace string, exceptions []awsxray.Exception) []awsxray.Exception {
r := textproto.NewReader(bufio.NewReader(strings.NewReader(stacktrace)))
// Skip first line containing top level message
exception := &exceptions[0]
isRemote := exception.Remote
_, err := r.ReadLine()
if err != nil {
return exceptions
}
var line string
line, err = r.ReadLine()
if err != nil {
return exceptions
}
exception.Stack = nil
for {
if strings.HasPrefix(line, "\tat ") {
parenIdx := strings.IndexByte(line, '(')
if parenIdx >= 0 && line[len(line)-1] == ')' {
label := line[len("\tat "):parenIdx]
slashIdx := strings.IndexByte(label, '/')
if slashIdx >= 0 {
// Class loader or Java module prefix, remove it
label = label[slashIdx+1:]
}
path := line[parenIdx+1 : len(line)-1]
line := 0
colonIdx := strings.IndexByte(path, ':')
if colonIdx >= 0 {
lineStr := path[colonIdx+1:]
path = path[0:colonIdx]
line, _ = strconv.Atoi(lineStr)
}
stack := awsxray.StackFrame{
Path: aws.String(path),
Label: aws.String(label),
Line: aws.Int(line),
}
exception.Stack = append(exception.Stack, stack)
}
} else if strings.HasPrefix(line, "Caused by: ") {
causeType := line[len("Caused by: "):]
colonIdx := strings.IndexByte(causeType, ':')
causeMessage := ""
if colonIdx >= 0 {
// Skip space after colon too.
causeMessage = causeType[colonIdx+2:]
causeType = causeType[0:colonIdx]
}
for {
// Need to peek lines since the message may have newlines.
line, err = r.ReadLine()
if err != nil {
break
}
if strings.HasPrefix(line, "\tat ") && strings.IndexByte(line, '(') >= 0 && line[len(line)-1] == ')' {
// Stack frame (hopefully, user can masquerade since we only have a string), process above.
break
}
// String append overhead in this case, but multiline messages should be far less common than single
// line ones.
causeMessage += line
}
segmentID := newSegmentID()
exceptions = append(exceptions, awsxray.Exception{
ID: aws.String(hex.EncodeToString(segmentID[:])),
Type: aws.String(causeType),
Remote: isRemote,
Message: aws.String(causeMessage),
Stack: nil,
})
// when append causes `exceptions` to outgrow its existing
// capacity, re-allocation will happen so the place
// `exception` points to is no longer `exceptions[len(exceptions)-2]`,
// consequently, we cannot write `exception.Cause = newException.ID`
// below.
newException := &exceptions[len(exceptions)-1]
exceptions[len(exceptions)-2].Cause = newException.ID
exception.Cause = newException.ID
exception = newException
// We peeked to a line starting with "\tat", a stack frame, so continue straight to processing.
continue
}
// We skip "..." (common frames) and Suppressed By exceptions.
line, err = r.ReadLine()
if err != nil {
break
}
}
return exceptions
}
func fillPythonStacktrace(stacktrace string, exceptions []awsxray.Exception) []awsxray.Exception {
// Need to read in reverse order so can't use a reader. Python formatted tracebacks always use '\n'
// for newlines so we can just split on it without worrying about Windows newlines.
lines := strings.Split(stacktrace, "\n")
// Skip last line containing top level exception / message
lineIdx := len(lines) - 2
if lineIdx < 0 {
return exceptions
}
line := lines[lineIdx]
exception := &exceptions[0]
isRemote := exception.Remote
exception.Stack = nil
for {
if strings.HasPrefix(line, " File ") {
parts := strings.Split(line, ",")
if len(parts) == 3 {
filePart := parts[0]
file := filePart[8 : len(filePart)-1]
lineNumber := 0
if strings.HasPrefix(parts[1], " line ") {
lineNumber, _ = strconv.Atoi(parts[1][6:])
}
label := ""
if strings.HasPrefix(parts[2], " in ") {
label = parts[2][4:]
}
stack := awsxray.StackFrame{
Path: aws.String(file),
Label: aws.String(label),
Line: aws.Int(lineNumber),
}
exception.Stack = append(exception.Stack, stack)
}
} else if strings.HasPrefix(line, "During handling of the above exception, another exception occurred:") {
nextFileLineIdx := lineIdx - 1
for {
if nextFileLineIdx < 0 {
// Couldn't find a " File ..." line before end of input, malformed stack trace.
return exceptions
}
if strings.HasPrefix(lines[nextFileLineIdx], " File ") {
break
}
nextFileLineIdx--
}
// Join message which potentially has newlines. Message starts two lines from the next "File " line and ends
// two lines before the "During handling " line.
message := strings.Join(lines[nextFileLineIdx+2:lineIdx-1], "\n")
lineIdx = nextFileLineIdx
colonIdx := strings.IndexByte(message, ':')
if colonIdx < 0 {
// Error not followed by a colon, malformed stack trace.
return exceptions
}
causeType := message[0:colonIdx]
causeMessage := message[colonIdx+2:]
segmentID := newSegmentID()
exceptions = append(exceptions, awsxray.Exception{
ID: aws.String(hex.EncodeToString(segmentID[:])),
Type: aws.String(causeType),
Remote: isRemote,
Message: aws.String(causeMessage),
})
// when append causes `exceptions` to outgrow its existing
// capacity, re-allocation will happen so the place
// `exception` points to is no longer `exceptions[len(exceptions)-2]`,
// consequently, we cannot write `exception.Cause = newException.ID`
// below.
newException := &exceptions[len(exceptions)-1]
exceptions[len(exceptions)-2].Cause = newException.ID
exception.Cause = newException.ID
exception = newException
// lineIdx is set to the next File line so ready to process it.
line = lines[lineIdx]
continue
}
lineIdx--
if lineIdx < 0 {
break
}
line = lines[lineIdx]
}
return exceptions
}
func fillJavaScriptStacktrace(stacktrace string, exceptions []awsxray.Exception) []awsxray.Exception {
r := textproto.NewReader(bufio.NewReader(strings.NewReader(stacktrace)))
// Skip first line containing top level message
exception := &exceptions[0]
_, err := r.ReadLine()
if err != nil {
return exceptions
}
var line string
line, err = r.ReadLine()
if err != nil {
return exceptions
}
exception.Stack = nil
for {
if strings.HasPrefix(line, " at ") {
parenIdx := strings.IndexByte(line, '(')
label := ""
path := ""
lineIdx := 0
if parenIdx >= 0 && line[len(line)-1] == ')' {
label = line[7:parenIdx]
path = line[parenIdx+1 : len(line)-1]
} else if parenIdx < 0 {
label = ""
path = line[7:]
}
colonFirstIdx := strings.IndexByte(path, ':')
colonSecondIdx := indexOf(path, ':', colonFirstIdx)
if colonFirstIdx >= 0 && colonSecondIdx >= 0 && colonFirstIdx != colonSecondIdx {
lineStr := path[colonFirstIdx+1 : colonSecondIdx]
path = path[0:colonFirstIdx]
lineIdx, _ = strconv.Atoi(lineStr)
} else if colonFirstIdx < 0 && strings.Contains(path, "native") {
path = "native"
}
// only append the exception if at least one of the values is not default
if path != "" || label != "" || lineIdx != 0 {
stack := awsxray.StackFrame{
Path: aws.String(path),
Label: aws.String(label),
Line: aws.Int(lineIdx),
}
exception.Stack = append(exception.Stack, stack)
}
}
line, err = r.ReadLine()
if err != nil {
break
}
}
return exceptions
}
func fillDotnetStacktrace(stacktrace string, exceptions []awsxray.Exception) []awsxray.Exception {
r := textproto.NewReader(bufio.NewReader(strings.NewReader(stacktrace)))
// Skip first line containing top level message
exception := &exceptions[0]
_, err := r.ReadLine()
if err != nil {
return exceptions
}
var line string
line, err = r.ReadLine()
if err != nil {
return exceptions
}
exception.Stack = nil
for {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "at ") {
index := strings.Index(line, " in ")
if index >= 0 {
parts := strings.Split(line, " in ")
label := parts[0][len("at "):]
path := parts[1]
lineNumber := 0
colonIdx := strings.LastIndexByte(parts[1], ':')
if colonIdx >= 0 {
lineStr := path[colonIdx+1:]
if strings.HasPrefix(lineStr, "line") {
lineStr = lineStr[5:]
}
path = path[0:colonIdx]
lineNumber, _ = strconv.Atoi(lineStr)
}
stack := awsxray.StackFrame{
Path: aws.String(path),
Label: aws.String(label),
Line: aws.Int(lineNumber),
}
exception.Stack = append(exception.Stack, stack)
} else {
idx := strings.LastIndexByte(line, ')')
if idx >= 0 {
label := line[len("at ") : idx+1]
path := ""
lineNumber := 0
stack := awsxray.StackFrame{
Path: aws.String(path),
Label: aws.String(label),
Line: aws.Int(lineNumber),
}
exception.Stack = append(exception.Stack, stack)
}
}
}
line, err = r.ReadLine()
if err != nil {
break
}
}
return exceptions
}
func fillGoStacktrace(stacktrace string, exceptions []awsxray.Exception) []awsxray.Exception {
var line string
var label string
var path string
var lineNumber int
plnre := regexp.MustCompile(`([^:\s]+)\:(\d+)`)
re := regexp.MustCompile(`^goroutine.*\brunning\b.*:$`)
r := textproto.NewReader(bufio.NewReader(strings.NewReader(stacktrace)))
// Skip first line containing top level message
exception := &exceptions[0]
_, err := r.ReadLine()
if err != nil {
return exceptions
}
line, err = r.ReadLine()
if err != nil {
return exceptions
}
exception.Stack = nil
for {
match := re.Match([]byte(line))
if match {
line, _ = r.ReadLine()
}
label = line
line, _ = r.ReadLine()
matches := plnre.FindStringSubmatch(line)
if len(matches) == 3 {
path = matches[1]
lineNumber, _ = strconv.Atoi(matches[2])
}
stack := awsxray.StackFrame{
Path: aws.String(path),
Label: aws.String(label),
Line: aws.Int(lineNumber),
}
exception.Stack = append(exception.Stack, stack)
line, err = r.ReadLine()
if err != nil {
break
}
}
return exceptions
}
// indexOf returns position of the first occurrence of a Byte in str starting at pos index.
func indexOf(str string, c byte, pos int) int {
if pos < 0 {
return -1
}
index := strings.IndexByte(str[pos+1:], c)
if index > -1 {
return index + pos + 1
}
return -1
}