...
1 package grpc_opentracing
2
3 import (
4 "strings"
5
6 grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
7 opentracing "github.com/opentracing/opentracing-go"
8 "google.golang.org/grpc/grpclog"
9 )
10
11 const (
12 TagTraceId = "trace.traceid"
13 TagSpanId = "trace.spanid"
14 TagSampled = "trace.sampled"
15 jaegerNotSampledFlag = "0"
16 )
17
18
19
20
21
22
23
24
25
26
27
28 func injectOpentracingIdsToTags(traceHeaderName string, span opentracing.Span, tags grpc_ctxtags.Tags) {
29 if err := span.Tracer().Inject(span.Context(), opentracing.HTTPHeaders,
30 &tagsCarrier{Tags: tags, traceHeaderName: traceHeaderName}); err != nil {
31 grpclog.Infof("grpc_opentracing: failed extracting trace info into ctx %v", err)
32 }
33 }
34
35
36 type tagsCarrier struct {
37 grpc_ctxtags.Tags
38 traceHeaderName string
39 }
40
41 func (t *tagsCarrier) Set(key, val string) {
42 key = strings.ToLower(key)
43
44 if key == t.traceHeaderName {
45 parts := strings.Split(val, ":")
46 if len(parts) == 4 {
47 t.Tags.Set(TagTraceId, parts[0])
48 t.Tags.Set(TagSpanId, parts[1])
49
50 if parts[3] != jaegerNotSampledFlag {
51 t.Tags.Set(TagSampled, "true")
52 } else {
53 t.Tags.Set(TagSampled, "false")
54 }
55
56 return
57 }
58 }
59
60 if strings.Contains(key, "traceid") {
61 t.Tags.Set(TagTraceId, val)
62 }
63
64 if strings.Contains(key, "spanid") && !strings.Contains(strings.ToLower(key), "parent") {
65 t.Tags.Set(TagSpanId, val)
66 }
67
68 if strings.Contains(key, "sampled") {
69 switch val {
70 case "true", "false":
71 t.Tags.Set(TagSampled, val)
72 }
73 }
74
75 if strings.HasSuffix(key, "trace-id") {
76 t.Tags.Set(TagTraceId, val)
77 }
78
79 if strings.HasSuffix(key, "parent-id") {
80 t.Tags.Set(TagSpanId, val)
81 }
82 }
83
View as plain text