-
Notifications
You must be signed in to change notification settings - Fork 47
/
open_tracing.go
338 lines (293 loc) · 7.92 KB
/
open_tracing.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
package tracer
import (
"context"
"encoding/json"
"fmt"
"log"
"math"
"net/http"
"net/url"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
opentracing "github.com/opentracing/opentracing-go"
ext "github.com/opentracing/opentracing-go/ext"
otlog "github.com/opentracing/opentracing-go/log"
config "github.com/uber/jaeger-client-go/config"
"google.golang.org/grpc/metadata"
"pkg.agungdp.dev/candi"
"pkg.agungdp.dev/candi/candishared"
"pkg.agungdp.dev/candi/codebase/interfaces"
"pkg.agungdp.dev/candi/config/env"
)
// InitOpenTracing init jaeger tracing
func InitOpenTracing(serviceName string, opts ...OptionFunc) error {
option := Option{
AgentHost: env.BaseEnv().JaegerTracingHost,
Level: env.BaseEnv().Environment,
BuildNumberTag: env.BaseEnv().BuildNumber,
MaxGoroutineTag: env.BaseEnv().MaxGoroutines,
}
for _, opt := range opts {
opt(&option)
}
if option.Level != "" {
serviceName = fmt.Sprintf("%s-%s", serviceName, strings.ToLower(option.Level))
}
defaultTags := []opentracing.Tag{
{Key: "num_cpu", Value: runtime.NumCPU()},
{Key: "go_version", Value: runtime.Version()},
{Key: "candi_version", Value: candi.Version},
}
if option.MaxGoroutineTag != 0 {
defaultTags = append(defaultTags, opentracing.Tag{
Key: "max_goroutines", Value: option.MaxGoroutineTag,
})
}
if option.BuildNumberTag != "" {
defaultTags = append(defaultTags, opentracing.Tag{
Key: "build_number", Value: option.BuildNumberTag,
})
}
cfg := &config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
BufferFlushInterval: 1 * time.Second,
LocalAgentHostPort: option.AgentHost,
},
ServiceName: serviceName,
Tags: defaultTags,
}
tracer, _, err := cfg.NewTracer(config.MaxTagValueLength(math.MaxInt32))
if err != nil {
log.Printf("ERROR: cannot init opentracing connection: %v\n", err)
return err
}
opentracing.SetGlobalTracer(tracer)
return nil
}
type jaegerImpl struct {
ctx context.Context
span opentracing.Span
tags map[string]interface{}
}
// StartTrace starting trace child span from parent span
func StartTrace(ctx context.Context, operationName string) interfaces.Tracer {
if candishared.GetValueFromContext(ctx, skipTracer) != nil {
return &jaegerImpl{ctx: ctx}
}
span := opentracing.SpanFromContext(ctx)
if span == nil {
// init new span
span, ctx = opentracing.StartSpanFromContext(ctx, operationName)
} else {
span = opentracing.GlobalTracer().StartSpan(operationName, opentracing.ChildOf(span.Context()))
ctx = opentracing.ContextWithSpan(ctx, span)
}
return &jaegerImpl{
ctx: ctx,
span: span,
}
}
// StartTraceWithContext starting trace child span from parent span, returning tracer and context
func StartTraceWithContext(ctx context.Context, operationName string) (interfaces.Tracer, context.Context) {
t := StartTrace(ctx, operationName)
return t, t.Context()
}
// Context get active context
func (t *jaegerImpl) Context() context.Context {
return t.ctx
}
// Tags create tags in tracer span
func (t *jaegerImpl) Tags() map[string]interface{} {
t.tags = make(map[string]interface{})
return t.tags
}
// SetTag set tags in tracer span
func (t *jaegerImpl) SetTag(key string, value interface{}) {
if t.span == nil {
return
}
if t.tags == nil {
t.tags = make(map[string]interface{})
}
t.tags[key] = value
}
// InjectHTTPHeader to continue tracer to http request host
func (t *jaegerImpl) InjectHTTPHeader(req *http.Request) {
if t.span == nil {
return
}
ext.SpanKindRPCClient.Set(t.span)
t.span.Tracer().Inject(
t.span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header),
)
}
// InjectGRPCMetaData to continue tracer to grpc metadata context
func (t *jaegerImpl) InjectGRPCMetadata(md metadata.MD) {
if t.span == nil {
return
}
ext.SpanKindRPCClient.Set(t.span)
t.span.Tracer().Inject(
t.span.Context(),
opentracing.HTTPHeaders,
GRPCMetadataReaderWriter(md),
)
}
// SetError set error in span
func (t *jaegerImpl) SetError(err error) {
SetError(t.ctx, err)
}
// SetError log data
func (t *jaegerImpl) Log(key string, value interface{}) {
Log(t.ctx, key, value)
}
// Finish trace with additional tags data, must in deferred function
func (t *jaegerImpl) Finish(additionalTags ...map[string]interface{}) {
if t.span == nil {
return
}
defer t.span.Finish()
if additionalTags != nil && t.tags == nil {
t.tags = make(map[string]interface{})
}
for _, tag := range additionalTags {
for k, v := range tag {
t.tags[k] = v
}
}
for k, v := range t.tags {
t.span.SetTag(k, toString(v))
}
t.span.SetTag("num_goroutines", runtime.NumGoroutine())
}
// Log trace
func Log(ctx context.Context, key string, value interface{}) {
span := opentracing.SpanFromContext(ctx)
if span == nil {
return
}
span.LogKV(key, toString(value))
}
// LogEvent trace
func LogEvent(ctx context.Context, event string, payload ...interface{}) {
span := opentracing.SpanFromContext(ctx)
if span == nil {
return
}
if payload != nil {
for _, p := range payload {
if e, ok := p.(error); ok && e != nil {
ext.Error.Set(span, true)
}
span.LogEventWithPayload(event, toString(p))
}
} else {
span.LogEvent(event)
}
}
// WithTraceFunc functional with context and tags in function params
func WithTraceFunc(ctx context.Context, operationName string, fn func(context.Context, map[string]interface{})) {
t := StartTrace(ctx, operationName)
defer t.Finish()
fn(t.Context(), t.Tags())
}
// WithTraceFuncTracer functional with Tracer instance in function params
func WithTraceFuncTracer(ctx context.Context, operationName string, fn func(t interfaces.Tracer)) {
t := StartTrace(ctx, operationName)
defer t.Finish()
fn(t)
}
func toString(v interface{}) (s string) {
switch val := v.(type) {
case error:
if val != nil {
s = val.Error()
}
case string:
s = val
case int:
s = strconv.Itoa(val)
case []byte:
s = string(val)
default:
b, _ := json.Marshal(val)
s = string(b)
}
if len(s) >= int(env.BaseEnv().JaegerMaxPacketSize) {
return fmt.Sprintf("<<Overflow, cannot show data. Size is = %d bytes, JAEGER_MAX_PACKET_SIZE = %d bytes>>", len(s), env.BaseEnv().JaegerMaxPacketSize)
}
return
}
// GetTraceID func
func GetTraceID(ctx context.Context) string {
span := opentracing.SpanFromContext(ctx)
if span == nil {
return ""
}
traceID := fmt.Sprintf("%+v", span)
splits := strings.Split(traceID, ":")
if len(splits) > 0 {
return splits[0]
}
return traceID
}
// SetError func
func SetError(ctx context.Context, err error) {
span := opentracing.SpanFromContext(ctx)
if span == nil || err == nil {
return
}
ext.Error.Set(span, true)
span.SetTag("error.message", err.Error())
span.LogFields(otlog.String("stacktrace", string(debug.Stack())))
}
// GetTraceURL log trace url
func GetTraceURL(ctx context.Context) (u string) {
traceID := GetTraceID(ctx)
if traceID == "" {
return
}
urlAgent, err := url.Parse("//" + env.BaseEnv().JaegerTracingHost)
if urlAgent != nil && err == nil {
u = fmt.Sprintf("http://%s:16686/trace/%s", urlAgent.Hostname(), traceID)
}
return
}
// GRPCMetadataReaderWriter grpc metadata
type GRPCMetadataReaderWriter metadata.MD
// ForeachKey method
func (mrw GRPCMetadataReaderWriter) ForeachKey(handler func(string, string) error) error {
for key, values := range mrw {
for _, value := range values {
dk, dv, err := metadata.DecodeKeyValue(key, value)
if err != nil {
return err
}
if err := handler(dk, dv); err != nil {
return err
}
}
}
return nil
}
// Set method
func (mrw GRPCMetadataReaderWriter) Set(key, value string) {
// headers should be lowercase
k := strings.ToLower(key)
mrw[k] = append(mrw[k], value)
}
var skipTracer candishared.ContextKey = "nooptracer"
// SkipTraceContext inject to context for skip span tracer
func SkipTraceContext(ctx context.Context) context.Context {
return candishared.SetToContext(ctx, skipTracer, struct{}{})
}