-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathspan.go
320 lines (293 loc) · 7.92 KB
/
span.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package apmot // import "go.elastic.co/apm/module/apmot/v2"
import (
"fmt"
"net/http"
"net/url"
"sync"
"time"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"go.elastic.co/apm/module/apmhttp/v2"
"go.elastic.co/apm/v2"
)
// otSpan wraps apm objects to implement the opentracing.Span interface.
type otSpan struct {
tracer *otTracer
mu sync.Mutex
span *apm.Span
tags opentracing.Tags
ctx spanContext
}
// Span returns s.span, the underlying apm.Span. This is used to satisfy
// SpanFromContext.
func (s *otSpan) Span() *apm.Span {
return s.span
}
// SetOperationName sets or changes the operation name.
func (s *otSpan) SetOperationName(operationName string) opentracing.Span {
if s.span != nil {
s.span.Name = operationName
} else {
s.ctx.tx.Name = operationName
}
return s
}
// SetTag adds or changes a tag.
func (s *otSpan) SetTag(key string, value interface{}) opentracing.Span {
s.mu.Lock()
defer s.mu.Unlock()
if s.tags == nil {
s.tags = make(opentracing.Tags, 1)
}
s.tags[key] = value
return s
}
// Finish ends the span; this (or FinishWithOptions) must be the last method
// call on the span, except for calls to Context which may be called at any
// time.
func (s *otSpan) Finish() {
s.FinishWithOptions(opentracing.FinishOptions{})
}
// FinishWithOptions is like Finish, but provides explicit control over the
// end timestamp and log data.
func (s *otSpan) FinishWithOptions(opts opentracing.FinishOptions) {
s.mu.Lock()
defer s.mu.Unlock()
if !opts.FinishTime.IsZero() {
duration := opts.FinishTime.Sub(s.ctx.startTime)
if s.span != nil {
s.span.Duration = duration
} else {
s.ctx.tx.Duration = duration
}
}
if s.span != nil {
for _, record := range opts.LogRecords {
timestamp := record.Timestamp
if timestamp.IsZero() {
timestamp = opts.FinishTime
}
logFields(s.tracer.tracer, nil, s.span, timestamp, record.Fields)
}
s.setSpanContext()
s.span.End()
} else {
s.setTransactionContext()
for _, record := range opts.LogRecords {
timestamp := record.Timestamp
if timestamp.IsZero() {
timestamp = opts.FinishTime
}
logFields(s.tracer.tracer, s.ctx.tx, nil, timestamp, record.Fields)
}
s.ctx.tx.End()
}
}
// Tracer returns the Tracer that created this span.
func (s *otSpan) Tracer() opentracing.Tracer {
return s.tracer
}
// Context returns the span's current context.
//
// It is valid to call Context after calling Finish or FinishWithOptions.
// The resulting context is also valid after the span is finished.
func (s *otSpan) Context() opentracing.SpanContext {
return &s.ctx
}
// BaggageItem returns the empty string; we do not support baggage.
func (*otSpan) BaggageItem(key string) string {
return ""
}
// SetBaggageItem is a no-op; we do not support baggage.
func (s *otSpan) SetBaggageItem(key, val string) opentracing.Span {
// We do not support baggage.
return s
}
func stringify(v interface{}) string {
if v, ok := v.(string); ok {
return v
}
return fmt.Sprint(v)
}
func (s *otSpan) setSpanContext() {
var (
dbContext apm.DatabaseSpanContext
component string
httpURL string
httpMethod string
httpHost string
haveDBContext bool
haveHTTPContext bool
haveHTTPHostTag bool
)
for k, v := range s.tags {
switch k {
case "component":
component = stringify(v)
case "db.instance":
dbContext.Instance = stringify(v)
haveDBContext = true
case "db.statement":
dbContext.Statement = stringify(v)
haveDBContext = true
case "db.type":
dbContext.Type = stringify(v)
haveDBContext = true
case "db.user":
dbContext.User = stringify(v)
haveDBContext = true
case "http.url":
haveHTTPContext = true
httpURL = stringify(v)
case "http.method":
haveHTTPContext = true
httpMethod = stringify(v)
case "http.host":
haveHTTPContext = true
haveHTTPHostTag = true
httpHost = stringify(v)
// Elastic APM-specific tags:
case "type":
s.span.Type = stringify(v)
default:
s.span.Context.SetLabel(k, stringify(v))
}
}
switch {
case haveHTTPContext:
if s.span.Type == "" {
s.span.Type = "external"
s.span.Subtype = "http"
}
url, err := url.Parse(httpURL)
if err == nil {
// handles the case where the url.Host hasn't been set.
// Tries obtaining the host value from the "http.host" tag.
// If not found, or if the url.Host has a value, it won't
// mutate the existing host.
if url.Host == "" && haveHTTPHostTag {
url.Host = httpHost
}
s.span.Context.SetHTTPRequest(&http.Request{
ProtoMinor: 1,
ProtoMajor: 1,
Method: httpMethod,
URL: url,
})
}
case haveDBContext:
if s.span.Type == "" {
s.span.Type = "db"
s.span.Subtype = dbContext.Type
}
s.span.Context.SetDatabase(dbContext)
}
if s.span.Type == "" {
s.span.Type = "custom"
s.span.Subtype = component
}
}
func (s *otSpan) setTransactionContext() {
var (
component string
httpMethod string
httpStatusCode = -1
httpURL string
isError bool
)
for k, v := range s.tags {
switch k {
case "component":
component = stringify(v)
case "http.method":
httpMethod = stringify(v)
case "http.status_code":
if code, ok := v.(uint16); ok {
httpStatusCode = int(code)
}
case "http.url":
httpURL = stringify(v)
case "error":
isError, _ = v.(bool)
// Elastic APM-specific tags:
case "type":
s.ctx.tx.Type = stringify(v)
case "result":
s.ctx.tx.Result = stringify(v)
case "user.id":
s.ctx.tx.Context.SetUserID(stringify(v))
case "user.email":
s.ctx.tx.Context.SetUserEmail(stringify(v))
case "user.username":
s.ctx.tx.Context.SetUsername(stringify(v))
default:
s.ctx.tx.Context.SetLabel(k, stringify(v))
}
}
if s.ctx.tx.Type == "" {
if httpURL != "" {
s.ctx.tx.Type = "request"
} else if component != "" {
s.ctx.tx.Type = component
} else {
s.ctx.tx.Type = "custom"
}
}
if s.ctx.tx.Result == "" {
if httpStatusCode != -1 {
s.ctx.tx.Result = apmhttp.StatusCodeResult(httpStatusCode)
s.ctx.tx.Context.SetHTTPStatusCode(httpStatusCode)
} else if isError {
s.ctx.tx.Result = "error"
}
}
if httpURL != "" {
uri, err := url.ParseRequestURI(httpURL)
if err == nil {
var req http.Request
req.ProtoMajor = 1 // Assume HTTP/1.1
req.ProtoMinor = 1
req.Method = httpMethod
req.URL = uri
s.ctx.tx.Context.SetHTTPRequest(&req)
}
}
}
// LogKV is part of the opentracing.Span interface.
// We send error events to Elastic APM.
func (s *otSpan) LogKV(keyValues ...interface{}) {
logKV(s.tracer.tracer, s.ctx.tx, s.span, time.Time{}, keyValues)
}
// LogFields is part of the opentracing.Span interface.
// We send error events to Elastic APM.
func (s *otSpan) LogFields(fields ...log.Field) {
logFields(s.tracer.tracer, s.ctx.tx, s.span, time.Time{}, fields)
}
// LogEvent is deprecated, and is a no-op.
func (s *otSpan) LogEvent(event string) {
// Deprecated, no-op.
}
// LogEventWithPayload is deprecated, and is a no-op.
func (s *otSpan) LogEventWithPayload(event string, payload interface{}) {
// Deprecated, no-op.
}
// Log is deprecated, and is a no-op.
func (s *otSpan) Log(ld opentracing.LogData) {
// Deprecated, no-op.
}