forked from elastic/apm-agent-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
372 lines (337 loc) · 11.6 KB
/
transaction.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// 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 apm // import "go.elastic.co/apm"
import (
cryptorand "crypto/rand"
"encoding/binary"
"math/rand"
"sync"
"time"
)
// StartTransaction returns a new Transaction with the specified
// name and type, and with the start time set to the current time.
// This is equivalent to calling StartTransactionOptions with a
// zero TransactionOptions.
func (t *Tracer) StartTransaction(name, transactionType string) *Transaction {
return t.StartTransactionOptions(name, transactionType, TransactionOptions{})
}
// StartTransactionOptions returns a new Transaction with the
// specified name, type, and options.
func (t *Tracer) StartTransactionOptions(name, transactionType string, opts TransactionOptions) *Transaction {
td, _ := t.transactionDataPool.Get().(*TransactionData)
if td == nil {
td = &TransactionData{
Duration: -1,
Context: Context{
captureBodyMask: CaptureBodyTransactions,
},
spanTimings: make(spanTimingsMap),
}
var seed int64
if err := binary.Read(cryptorand.Reader, binary.LittleEndian, &seed); err != nil {
seed = time.Now().UnixNano()
}
td.rand = rand.New(rand.NewSource(seed))
}
tx := &Transaction{tracer: t, TransactionData: td}
// Take a snapshot of config that should apply to all spans within the
// transaction.
instrumentationConfig := t.instrumentationConfig()
tx.recording = instrumentationConfig.recording
if !tx.recording || !t.Active() {
return tx
}
tx.maxSpans = instrumentationConfig.maxSpans
tx.spanFramesMinDuration = instrumentationConfig.spanFramesMinDuration
tx.stackTraceLimit = instrumentationConfig.stackTraceLimit
tx.Context.captureHeaders = instrumentationConfig.captureHeaders
tx.propagateLegacyHeader = instrumentationConfig.propagateLegacyHeader
tx.Context.sanitizedFieldNames = instrumentationConfig.sanitizedFieldNames
tx.breakdownMetricsEnabled = t.breakdownMetrics.enabled
var root bool
if opts.TraceContext.Trace.Validate() == nil {
tx.traceContext.Trace = opts.TraceContext.Trace
tx.traceContext.Options = opts.TraceContext.Options
if opts.TraceContext.Span.Validate() == nil {
tx.parentSpan = opts.TraceContext.Span
}
if opts.TransactionID.Validate() == nil {
tx.traceContext.Span = opts.TransactionID
} else {
binary.LittleEndian.PutUint64(tx.traceContext.Span[:], tx.rand.Uint64())
}
if opts.TraceContext.State.Validate() == nil {
tx.traceContext.State = opts.TraceContext.State
}
} else {
// Start a new trace. We reuse the trace ID for the root transaction's ID
// if one is not specified in the options.
root = true
binary.LittleEndian.PutUint64(tx.traceContext.Trace[:8], tx.rand.Uint64())
binary.LittleEndian.PutUint64(tx.traceContext.Trace[8:], tx.rand.Uint64())
if opts.TransactionID.Validate() == nil {
tx.traceContext.Span = opts.TransactionID
} else {
copy(tx.traceContext.Span[:], tx.traceContext.Trace[:])
}
}
if root {
var result SampleResult
if instrumentationConfig.extendedSampler != nil {
result = instrumentationConfig.extendedSampler.SampleExtended(SampleParams{
TraceContext: tx.traceContext,
})
if !result.Sampled {
// Special case: for unsampled transactions we
// report a sample rate of 0, so that we do not
// count them in aggregations in the server.
// This is necessary to avoid overcounting, as
// we will scale the sampled transactions.
result.SampleRate = 0
}
sampleRate := roundSampleRate(result.SampleRate)
tx.traceContext.State = NewTraceState(TraceStateEntry{
Key: elasticTracestateVendorKey,
Value: formatElasticTracestateValue(sampleRate),
})
} else if instrumentationConfig.sampler != nil {
result.Sampled = instrumentationConfig.sampler.Sample(tx.traceContext)
} else {
result.Sampled = true
}
if result.Sampled {
o := tx.traceContext.Options.WithRecorded(true)
tx.traceContext.Options = o
}
} else {
// TODO(axw) make this behaviour configurable. In some cases
// it may not be a good idea to honour the recorded flag, as
// it may open up the application to DoS by forced sampling.
// Even ignoring bad actors, a service that has many feeder
// applications may end up being sampled at a very high rate.
tx.traceContext.Options = opts.TraceContext.Options
}
tx.Name = name
tx.Type = transactionType
tx.timestamp = opts.Start
if tx.timestamp.IsZero() {
tx.timestamp = time.Now()
}
return tx
}
// TransactionOptions holds options for Tracer.StartTransactionOptions.
type TransactionOptions struct {
// TraceContext holds the TraceContext for a new transaction. If this is
// zero, a new trace will be started.
TraceContext TraceContext
// TransactionID holds the ID to assign to the transaction. If this is
// zero, a new ID will be generated and used instead.
TransactionID SpanID
// Start is the start time of the transaction. If this has the
// zero value, time.Now() will be used instead.
Start time.Time
}
// Transaction describes an event occurring in the monitored service.
type Transaction struct {
tracer *Tracer
traceContext TraceContext
mu sync.RWMutex
// TransactionData holds the transaction data. This field is set to
// nil when either of the transaction's End or Discard methods are called.
*TransactionData
}
// Sampled reports whether or not the transaction is sampled.
func (tx *Transaction) Sampled() bool {
if tx == nil {
return false
}
return tx.traceContext.Options.Recorded()
}
// TraceContext returns the transaction's TraceContext.
//
// The resulting TraceContext's Span field holds the transaction's ID.
// If tx is nil, a zero (invalid) TraceContext is returned.
func (tx *Transaction) TraceContext() TraceContext {
if tx == nil {
return TraceContext{}
}
return tx.traceContext
}
// ShouldPropagateLegacyHeader reports whether instrumentation should
// propagate the legacy "Elastic-Apm-Traceparent" header in addition to
// the standard W3C "traceparent" header.
//
// This method will be removed in a future major version when we remove
// support for propagating the legacy header.
func (tx *Transaction) ShouldPropagateLegacyHeader() bool {
tx.mu.Lock()
defer tx.mu.Unlock()
if tx.ended() {
return false
}
return tx.propagateLegacyHeader
}
// EnsureParent returns the span ID for for tx's parent, generating a
// parent span ID if one has not already been set and tx has not been
// ended. If tx is nil or has been ended, a zero (invalid) SpanID is
// returned.
//
// This method can be used for generating a span ID for the RUM
// (Real User Monitoring) agent, where the RUM agent is initialized
// after the backend service returns.
func (tx *Transaction) EnsureParent() SpanID {
if tx == nil {
return SpanID{}
}
tx.mu.Lock()
defer tx.mu.Unlock()
if tx.ended() {
return SpanID{}
}
tx.TransactionData.mu.Lock()
defer tx.TransactionData.mu.Unlock()
if tx.parentSpan.isZero() {
// parentSpan can only be zero if tx is a root transaction
// for which GenerateParentTraceContext() has not previously
// been called. Reuse the latter half of the trace ID for
// the parent span ID; the first half is used for the
// transaction ID.
copy(tx.parentSpan[:], tx.traceContext.Trace[8:])
}
return tx.parentSpan
}
// Discard discards a previously started transaction.
//
// Calling Discard will set tx's TransactionData field to nil, so callers must
// ensure tx is not updated after Discard returns.
func (tx *Transaction) Discard() {
tx.mu.Lock()
defer tx.mu.Unlock()
if tx.ended() {
return
}
tx.reset(tx.tracer)
tx.TransactionData = nil
}
// End enqueues tx for sending to the Elastic APM server.
//
// Calling End will set tx's TransactionData field to nil, so callers
// must ensure tx is not updated after End returns.
//
// If tx.Duration has not been set, End will set it to the elapsed time
// since the transaction's start time.
func (tx *Transaction) End() {
tx.mu.Lock()
defer tx.mu.Unlock()
if tx.ended() {
return
}
if tx.recording {
if tx.Duration < 0 {
tx.Duration = time.Since(tx.timestamp)
}
if tx.Outcome == "" {
tx.Outcome = tx.Context.outcome()
}
tx.enqueue()
} else {
tx.reset(tx.tracer)
}
tx.TransactionData = nil
}
func (tx *Transaction) enqueue() {
event := tracerEvent{eventType: transactionEvent}
event.tx.Transaction = tx
event.tx.TransactionData = tx.TransactionData
select {
case tx.tracer.events <- event:
default:
// Enqueuing a transaction should never block.
tx.tracer.breakdownMetrics.recordTransaction(tx.TransactionData)
// TODO(axw) use an atomic operation to increment.
tx.tracer.statsMu.Lock()
tx.tracer.stats.TransactionsDropped++
tx.tracer.statsMu.Unlock()
tx.reset(tx.tracer)
}
}
// ended reports whether or not End or Discard has been called.
//
// This must be called with tx.mu held.
func (tx *Transaction) ended() bool {
return tx.TransactionData == nil
}
// TransactionData holds the details for a transaction, and is embedded
// inside Transaction. When a transaction is ended, its TransactionData
// field will be set to nil.
type TransactionData struct {
// Name holds the transaction name, initialized with the value
// passed to StartTransaction.
Name string
// Type holds the transaction type, initialized with the value
// passed to StartTransaction.
Type string
// Duration holds the transaction duration, initialized to -1.
//
// If you do not update Duration, calling Transaction.End will
// calculate the duration based on the elapsed time since the
// transaction's start time.
Duration time.Duration
// Context describes the context in which the transaction occurs.
Context Context
// Result holds the transaction result.
Result string
// Outcome holds the transaction outcome: success, failure, or
// unknown (the default). If Outcome is set to something else,
// it will be replaced with "unknown".
//
// Outcome is used for error rate calculations. A value of "success"
// indicates that a transaction succeeded, while "failure" indicates
// that the transaction failed. If Outcome is set to "unknown" (or
// some other value), then the transaction will not be included in
// error rate calculations.
Outcome string
recording bool
maxSpans int
spanFramesMinDuration time.Duration
stackTraceLimit int
breakdownMetricsEnabled bool
propagateLegacyHeader bool
timestamp time.Time
mu sync.Mutex
spansCreated int
spansDropped int
childrenTimer childrenTimer
spanTimings spanTimingsMap
rand *rand.Rand // for ID generation
// parentSpan holds the transaction's parent ID. It is protected by
// mu, since it can be updated by calling EnsureParent.
parentSpan SpanID
}
// reset resets the TransactionData back to its zero state and places it back
// into the transaction pool.
func (td *TransactionData) reset(tracer *Tracer) {
*td = TransactionData{
Context: td.Context,
Duration: -1,
rand: td.rand,
spanTimings: td.spanTimings,
}
td.Context.reset()
td.spanTimings.reset()
tracer.transactionDataPool.Put(td)
}