/
tracker.go
105 lines (83 loc) · 2.33 KB
/
tracker.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
package datadog
import (
"context"
"fmt"
"time"
"google.golang.org/grpc/codes"
microerr "github.com/micro/go-micro/errors"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
type tracker struct {
startedAt time.Time
profile *StatsProfile
span ddtrace.Span
startSpanOptions []ddtrace.StartSpanOption
reqEndpoint string
reqService string
}
type requestDescriptor interface {
Service() string
Endpoint() string
}
type publicationDescriptor interface {
Topic() string
}
// newRequestTracker creates a new tracker for an RPC request (client or server).
func newRequestTracker(req requestDescriptor, profile *StatsProfile) *tracker {
return &tracker{
profile: profile,
reqService: req.Service(),
reqEndpoint: req.Endpoint(),
}
}
// newPublicationTracker creates a new tracker for a publication (client or server).
func newPublicationTracker(pub publicationDescriptor, profile *StatsProfile) *tracker {
return &tracker{
profile: profile,
reqService: "micro.pubsub",
reqEndpoint: pub.Topic(),
}
}
// start monitoring a request. You can choose to let this method
// start a span for the request or attach one later.
func (t *tracker) StartSpanFromContext(ctx context.Context) context.Context {
t.startedAt = time.Now()
opts := []ddtrace.StartSpanOption{
tracer.ResourceName(t.reqEndpoint),
tracer.SpanType(ext.AppTypeRPC),
tracer.StartTime(t.startedAt),
}
t.span, ctx = StartSpanFromContext(ctx, t.profile.Role, opts...)
return ctx
}
// finishWithError end a request's monitoring session. If there is a span ongoing, it will
// be ended.
func (t *tracker) finishWithError(err error, noDebugStack bool) {
if t.span == nil {
return
}
statusCode := codes.OK
finishOptions := []tracer.FinishOption{
tracer.FinishTime(time.Now()),
}
microErr, ok := err.(*microerr.Error)
if ok {
finishOptions = append(finishOptions, tracer.WithError(
fmt.Errorf("%s: %s", microErr.Id, microErr.Detail),
))
c, ok := microCodeToStatusCode[microErr.Code]
if ok {
statusCode = c
} else {
statusCode = codes.Unknown
}
}
t.span.SetTag(tagStatus, statusCode.String())
if noDebugStack {
finishOptions = append(finishOptions, tracer.NoDebugStack())
}
t.span.Finish(finishOptions...)
t.span = nil
}