File: txn_trace.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (453 lines) | stat: -rw-r--r-- 12,132 bytes parent folder | download
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package internal

import (
	"bytes"
	"container/heap"
	"sort"
	"time"

	"github.com/newrelic/go-agent/internal/jsonx"
)

// See https://source.datanerd.us/agents/agent-specs/blob/master/Transaction-Trace-LEGACY.md

type traceNodeHeap []traceNode

type traceNodeParams struct {
	attributes              map[SpanAttribute]jsonWriter
	StackTrace              StackTrace
	TransactionGUID         string
	exclusiveDurationMillis *float64
}

type traceNode struct {
	start    segmentTime
	stop     segmentTime
	threadID uint64
	duration time.Duration
	traceNodeParams
	name string
}

func (h traceNodeHeap) Len() int           { return len(h) }
func (h traceNodeHeap) Less(i, j int) bool { return h[i].duration < h[j].duration }
func (h traceNodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

// Push and Pop are unused: only heap.Init and heap.Fix are used.
func (h traceNodeHeap) Push(x interface{}) {}
func (h traceNodeHeap) Pop() interface{}   { return nil }

// TxnTrace contains the work in progress transaction trace.
type TxnTrace struct {
	Enabled             bool
	SegmentThreshold    time.Duration
	StackTraceThreshold time.Duration
	nodes               traceNodeHeap
	maxNodes            int
}

// getMaxNodes allows the maximum number of nodes to be overwritten for unit
// tests.
func (trace *TxnTrace) getMaxNodes() int {
	if 0 != trace.maxNodes {
		return trace.maxNodes
	}
	return maxTxnTraceNodes
}

// considerNode exists to prevent unnecessary calls to witnessNode: constructing
// the metric name and params map requires allocations.
func (trace *TxnTrace) considerNode(end segmentEnd) bool {
	return trace.Enabled && (end.duration >= trace.SegmentThreshold)
}

func (trace *TxnTrace) witnessNode(end segmentEnd, name string, attrs spanAttributeMap, externalGUID string) {
	node := traceNode{
		start:    end.start,
		stop:     end.stop,
		duration: end.duration,
		threadID: end.threadID,
		name:     name,
	}
	node.attributes = attrs
	node.TransactionGUID = externalGUID
	if !trace.considerNode(end) {
		return
	}
	if trace.nodes == nil {
		trace.nodes = make(traceNodeHeap, 0, startingTxnTraceNodes)
	}
	if end.exclusive >= trace.StackTraceThreshold {
		node.StackTrace = GetStackTrace()
	}
	if max := trace.getMaxNodes(); len(trace.nodes) < max {
		trace.nodes = append(trace.nodes, node)
		if len(trace.nodes) == max {
			heap.Init(trace.nodes)
		}
		return
	}

	if node.duration <= trace.nodes[0].duration {
		return
	}
	trace.nodes[0] = node
	heap.Fix(trace.nodes, 0)
}

// HarvestTrace contains a finished transaction trace ready for serialization to
// the collector.
type HarvestTrace struct {
	TxnEvent
	Trace TxnTrace
}

type nodeDetails struct {
	name          string
	relativeStart time.Duration
	relativeStop  time.Duration
	traceNodeParams
}

func printNodeStart(buf *bytes.Buffer, n nodeDetails) {
	// time.Seconds() is intentionally not used here.  Millisecond
	// precision is enough.
	relativeStartMillis := n.relativeStart.Nanoseconds() / (1000 * 1000)
	relativeStopMillis := n.relativeStop.Nanoseconds() / (1000 * 1000)

	buf.WriteByte('[')
	jsonx.AppendInt(buf, relativeStartMillis)
	buf.WriteByte(',')
	jsonx.AppendInt(buf, relativeStopMillis)
	buf.WriteByte(',')
	jsonx.AppendString(buf, n.name)
	buf.WriteByte(',')

	w := jsonFieldsWriter{buf: buf}
	buf.WriteByte('{')
	if nil != n.StackTrace {
		w.writerField("backtrace", n.StackTrace)
	}
	if nil != n.exclusiveDurationMillis {
		w.floatField("exclusive_duration_millis", *n.exclusiveDurationMillis)
	}
	if "" != n.TransactionGUID {
		w.stringField("transaction_guid", n.TransactionGUID)
	}
	for k, v := range n.attributes {
		w.writerField(k.String(), v)
	}
	buf.WriteByte('}')

	buf.WriteByte(',')
	buf.WriteByte('[')
}

func printChildren(buf *bytes.Buffer, traceStart time.Time, nodes sortedTraceNodes, next int, stop *segmentStamp, threadID uint64) int {
	firstChild := true
	for {
		if next >= len(nodes) {
			// No more children to print.
			break
		}
		if nodes[next].threadID != threadID {
			// The next node is not of the same thread.  Due to the
			// node sorting, all nodes of the same thread should be
			// together.
			break
		}
		if stop != nil && nodes[next].start.Stamp >= *stop {
			// Make sure this node is a child of the parent that is
			// being printed.
			break
		}
		if firstChild {
			firstChild = false
		} else {
			buf.WriteByte(',')
		}
		printNodeStart(buf, nodeDetails{
			name:            nodes[next].name,
			relativeStart:   nodes[next].start.Time.Sub(traceStart),
			relativeStop:    nodes[next].stop.Time.Sub(traceStart),
			traceNodeParams: nodes[next].traceNodeParams,
		})
		next = printChildren(buf, traceStart, nodes, next+1, &nodes[next].stop.Stamp, threadID)
		buf.WriteString("]]")

	}
	return next
}

type sortedTraceNodes []*traceNode

func (s sortedTraceNodes) Len() int { return len(s) }
func (s sortedTraceNodes) Less(i, j int) bool {
	// threadID is the first sort key and start.Stamp is the second key.
	if s[i].threadID == s[j].threadID {
		return s[i].start.Stamp < s[j].start.Stamp
	}
	return s[i].threadID < s[j].threadID
}
func (s sortedTraceNodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// MarshalJSON is used for testing.
//
// TODO: Eliminate this entirely by using harvestTraces.Data().
func (trace *HarvestTrace) MarshalJSON() ([]byte, error) {
	buf := bytes.NewBuffer(make([]byte, 0, 100+100*trace.Trace.nodes.Len()))

	trace.writeJSON(buf)

	return buf.Bytes(), nil
}

func (trace *HarvestTrace) writeJSON(buf *bytes.Buffer) {
	nodes := make(sortedTraceNodes, len(trace.Trace.nodes))
	for i := 0; i < len(nodes); i++ {
		nodes[i] = &trace.Trace.nodes[i]
	}
	sort.Sort(nodes)

	buf.WriteByte('[') // begin trace

	jsonx.AppendInt(buf, trace.Start.UnixNano()/1000)
	buf.WriteByte(',')
	jsonx.AppendFloat(buf, trace.Duration.Seconds()*1000.0)
	buf.WriteByte(',')
	jsonx.AppendString(buf, trace.FinalName)
	buf.WriteByte(',')
	if uri, _ := trace.Attrs.GetAgentValue(attributeRequestURI, destTxnTrace); "" != uri {
		jsonx.AppendString(buf, uri)
	} else {
		buf.WriteString("null")
	}
	buf.WriteByte(',')

	buf.WriteByte('[') // begin trace data

	// If the trace string pool is used, insert another array here.

	jsonx.AppendFloat(buf, 0.0) // unused timestamp
	buf.WriteByte(',')          //
	buf.WriteString("{}")       // unused: formerly request parameters
	buf.WriteByte(',')          //
	buf.WriteString("{}")       // unused: formerly custom parameters
	buf.WriteByte(',')          //

	printNodeStart(buf, nodeDetails{ // begin outer root
		name:          "ROOT",
		relativeStart: 0,
		relativeStop:  trace.Duration,
	})

	// exclusive_duration_millis field is added to fix the transaction trace
	// summary tab.  If exclusive_duration_millis is not provided, the UIs
	// will calculate exclusive time, which doesn't work for this root node
	// since all async goroutines are children of this root.
	exclusiveDurationMillis := trace.Duration.Seconds() * 1000.0
	details := nodeDetails{ // begin inner root
		name:          trace.FinalName,
		relativeStart: 0,
		relativeStop:  trace.Duration,
	}
	details.exclusiveDurationMillis = &exclusiveDurationMillis
	printNodeStart(buf, details)

	for next := 0; next < len(nodes); {
		if next > 0 {
			buf.WriteByte(',')
		}
		// We put each thread's nodes into the root node instead of the
		// node that spawned the thread. This approach is simple and
		// works when the segment which spawned a thread has been pruned
		// from the trace.  Each call to printChildren prints one
		// thread.
		next = printChildren(buf, trace.Start, nodes, next, nil, nodes[next].threadID)
	}

	buf.WriteString("]]") // end outer root
	buf.WriteString("]]") // end inner root

	buf.WriteByte(',')
	buf.WriteByte('{')
	buf.WriteString(`"agentAttributes":`)
	agentAttributesJSON(trace.Attrs, buf, destTxnTrace)
	buf.WriteByte(',')
	buf.WriteString(`"userAttributes":`)
	userAttributesJSON(trace.Attrs, buf, destTxnTrace, nil)
	buf.WriteByte(',')
	buf.WriteString(`"intrinsics":`)
	intrinsicsJSON(&trace.TxnEvent, buf)
	buf.WriteByte('}')

	// If the trace string pool is used, end another array here.

	buf.WriteByte(']') // end trace data

	// catGUID
	buf.WriteByte(',')
	if trace.CrossProcess.Used() && trace.CrossProcess.GUID != "" {
		jsonx.AppendString(buf, trace.CrossProcess.GUID)
	} else if trace.BetterCAT.Enabled {
		jsonx.AppendString(buf, trace.BetterCAT.TraceID())
	} else {
		buf.WriteString(`""`)
	}
	buf.WriteByte(',')       //
	buf.WriteString(`null`)  // reserved for future use
	buf.WriteByte(',')       //
	buf.WriteString(`false`) // ForcePersist is not yet supported
	buf.WriteByte(',')       //
	buf.WriteString(`null`)  // X-Ray sessions not supported
	buf.WriteByte(',')       //

	// Synthetics are supported:
	if trace.CrossProcess.IsSynthetics() {
		jsonx.AppendString(buf, trace.CrossProcess.Synthetics.ResourceID)
	} else {
		buf.WriteString(`""`)
	}

	buf.WriteByte(']') // end trace
}

type txnTraceHeap []*HarvestTrace

func (h *txnTraceHeap) isEmpty() bool {
	return 0 == len(*h)
}

func newTxnTraceHeap(max int) *txnTraceHeap {
	h := make(txnTraceHeap, 0, max)
	heap.Init(&h)
	return &h
}

// Implement sort.Interface.
func (h txnTraceHeap) Len() int           { return len(h) }
func (h txnTraceHeap) Less(i, j int) bool { return h[i].Duration < h[j].Duration }
func (h txnTraceHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

// Implement heap.Interface.
func (h *txnTraceHeap) Push(x interface{}) { *h = append(*h, x.(*HarvestTrace)) }

func (h *txnTraceHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h *txnTraceHeap) isKeeper(t *HarvestTrace) bool {
	if len(*h) < cap(*h) {
		return true
	}
	return t.Duration >= (*h)[0].Duration
}

func (h *txnTraceHeap) addTxnTrace(t *HarvestTrace) {
	if len(*h) < cap(*h) {
		heap.Push(h, t)
		return
	}

	if t.Duration <= (*h)[0].Duration {
		return
	}
	heap.Pop(h)
	heap.Push(h, t)
}

type harvestTraces struct {
	regular    *txnTraceHeap
	synthetics *txnTraceHeap
}

func newHarvestTraces() *harvestTraces {
	return &harvestTraces{
		regular:    newTxnTraceHeap(maxRegularTraces),
		synthetics: newTxnTraceHeap(maxSyntheticsTraces),
	}
}

func (traces *harvestTraces) Len() int {
	return traces.regular.Len() + traces.synthetics.Len()
}

func (traces *harvestTraces) Witness(trace HarvestTrace) {
	traceHeap := traces.regular
	if trace.CrossProcess.IsSynthetics() {
		traceHeap = traces.synthetics
	}

	if traceHeap.isKeeper(&trace) {
		cpy := new(HarvestTrace)
		*cpy = trace
		traceHeap.addTxnTrace(cpy)
	}
}

func (traces *harvestTraces) Data(agentRunID string, harvestStart time.Time) ([]byte, error) {
	if traces.Len() == 0 {
		return nil, nil
	}

	// This estimate is used to guess the size of the buffer.  No worries if
	// the estimate is small since the buffer will be lengthened as
	// necessary.  This is just about minimizing reallocations.
	estimate := 512
	for _, t := range *traces.regular {
		estimate += 100 * t.Trace.nodes.Len()
	}
	for _, t := range *traces.synthetics {
		estimate += 100 * t.Trace.nodes.Len()
	}

	buf := bytes.NewBuffer(make([]byte, 0, estimate))
	buf.WriteByte('[')
	jsonx.AppendString(buf, agentRunID)
	buf.WriteByte(',')
	buf.WriteByte('[')

	// use a function to add traces to the buffer to avoid duplicating comma
	// logic in both loops
	firstTrace := true
	addTrace := func(trace *HarvestTrace) {
		if firstTrace {
			firstTrace = false
		} else {
			buf.WriteByte(',')
		}
		trace.writeJSON(buf)
	}

	for _, trace := range *traces.regular {
		addTrace(trace)
	}
	for _, trace := range *traces.synthetics {
		addTrace(trace)
	}
	buf.WriteByte(']')
	buf.WriteByte(']')

	return buf.Bytes(), nil
}

func (traces *harvestTraces) slice() []*HarvestTrace {
	out := make([]*HarvestTrace, 0, traces.Len())
	out = append(out, (*traces.regular)...)
	out = append(out, (*traces.synthetics)...)

	return out
}

func (traces *harvestTraces) MergeIntoHarvest(h *Harvest) {}

func (traces *harvestTraces) EndpointMethod() string {
	return cmdTxnTraces
}