This repository has been archived by the owner on Jul 31, 2023. It is now read-only.
/
error_injector_span_listener.go
99 lines (83 loc) · 2.57 KB
/
error_injector_span_listener.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
package tracer
import (
"reflect"
"sync/atomic"
"github.com/pkg/errors"
"github.com/thundra-io/thundra-lambda-agent-go/v2/constants"
"github.com/thundra-io/thundra-lambda-agent-go/v2/utils"
)
var defaultErrorMessage = "Error injected by Thundra!"
type ErrorInjectorSpanListener struct {
ErrorMessage string
ErrorType error
InjectOnFinish bool
InjectCountFreq int64
counter int64
AddInfoTags bool
}
func (e *ErrorInjectorSpanListener) OnSpanStarted(span *spanImpl) {
if !e.InjectOnFinish && e.ableToRaise() {
e.injectError(span)
}
}
func (e *ErrorInjectorSpanListener) OnSpanFinished(span *spanImpl) {
if e.InjectOnFinish && e.ableToRaise() {
e.injectError(span)
}
}
func (e *ErrorInjectorSpanListener) PanicOnError() bool {
return true
}
func (e *ErrorInjectorSpanListener) ableToRaise() bool {
counter := atomic.AddInt64(&e.counter, 1)
countfreq := e.InjectCountFreq
if e.InjectCountFreq < 1 {
countfreq = 1
}
return (counter % countfreq) == 0
}
func (e *ErrorInjectorSpanListener) addInfoTags(span *spanImpl, err error) {
infoTags := map[string]interface{}{
"type": "error_injecter_span_listener",
"error_type": reflect.TypeOf(err).String(),
"error_message": err.Error(),
"inject_on_finish": e.InjectOnFinish,
"inject_count_freq": e.InjectCountFreq,
}
span.SetTag(constants.ThundraLambdaSpanListenerInfoTag, infoTags)
}
func (e *ErrorInjectorSpanListener) injectError(span *spanImpl) {
var err error
var errMessage = defaultErrorMessage
if e.ErrorMessage != "" {
errMessage = e.ErrorMessage
}
if e.ErrorType != nil {
err = e.ErrorType
} else {
err = errors.New(errMessage)
}
utils.SetSpanError(span, err)
if e.AddInfoTags {
e.addInfoTags(span, err)
}
panic(err)
}
// NewErrorInjectorSpanListener creates and returns a new ErrorInjectorSpanListener from config
func NewErrorInjectorSpanListener(config map[string]interface{}) ThundraSpanListener {
spanListener := &ErrorInjectorSpanListener{ErrorMessage: defaultErrorMessage, AddInfoTags: true, InjectCountFreq: 1}
if errorMessage, ok := config["errorMessage"].(string); ok {
spanListener.ErrorMessage = errorMessage
}
if injectOnFinish, ok := config["injectOnFinish"].(bool); ok {
spanListener.InjectOnFinish = injectOnFinish
}
if injectCountFreq, ok := config["injectCountFreq"].(float64); ok {
spanListener.InjectCountFreq = int64(injectCountFreq)
}
if addInfoTags, ok := config["addInfoTags"].(bool); ok {
spanListener.AddInfoTags = addInfoTags
}
spanListener.ErrorType = errors.New(spanListener.ErrorMessage)
return spanListener
}