-
Notifications
You must be signed in to change notification settings - Fork 196
/
span_test.go
1641 lines (1457 loc) · 50.3 KB
/
span_test.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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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_test
import (
"context"
"fmt"
"os"
"sort"
"sync"
"testing"
"time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.elastic.co/apm/v2"
"go.elastic.co/apm/v2/apmtest"
"go.elastic.co/apm/v2/model"
"go.elastic.co/apm/v2/transport/transporttest"
)
func TestStartSpanTransactionNotSampled(t *testing.T) {
tracer, _ := apm.NewTracer("tracer_testing", "")
defer tracer.Close()
// sample nothing
tracer.SetSampler(apm.NewRatioSampler(0))
tx := tracer.StartTransaction("name", "type")
assert.False(t, tx.Sampled())
span := tx.StartSpan("name", "type", nil)
assert.True(t, span.Dropped())
}
func TestTracerStartSpan(t *testing.T) {
tracer, r := transporttest.NewRecorderTracer()
defer tracer.Close()
txTimestamp := time.Now()
tx := tracer.StartTransactionOptions("name", "type", apm.TransactionOptions{
Start: txTimestamp,
})
txTraceContext := tx.TraceContext()
span0 := tx.StartSpan("name", "type", nil)
span0TraceContext := span0.TraceContext()
span0.End()
tx.End()
// Even if the transaction and parent span have been ended,
// it is possible to report a span with their IDs.
tracer.StartSpan("name", "type",
txTraceContext.Span,
apm.SpanOptions{
Parent: span0TraceContext,
Start: txTimestamp.Add(time.Second),
},
).End()
tracer.Flush(nil)
payloads := r.Payloads()
assert.Len(t, payloads.Transactions, 1)
assert.Len(t, payloads.Spans, 2)
assert.Equal(t, payloads.Transactions[0].ID, payloads.Spans[0].ParentID)
assert.Equal(t, payloads.Spans[0].ID, payloads.Spans[1].ParentID)
for _, span := range payloads.Spans {
assert.Equal(t, payloads.Transactions[0].TraceID, span.TraceID)
assert.Equal(t, payloads.Transactions[0].ID, span.TransactionID)
}
assert.NotZero(t, payloads.Spans[1].ID)
assert.Equal(t, time.Time(payloads.Transactions[0].Timestamp).Add(time.Second), time.Time(payloads.Spans[1].Timestamp))
// The span created after the transaction (obviously?)
// doesn't get included in the transaction's span count.
assert.Equal(t, 1, payloads.Transactions[0].SpanCount.Started)
}
func TestSpanParentID(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpan("name", "type", nil)
traceContext := tx.TraceContext()
parentID := span.ParentID()
span.End()
tx.End()
// Assert that the parentID is not empty when the span hasn't been ended.
// And that the Span's parentID equals the traceContext Span.
assert.NotEqual(t, parentID, apm.SpanID{})
assert.Equal(t, traceContext.Span, parentID)
// Assert that the parentID is not empty after the span has ended.
assert.NotZero(t, span.ParentID())
assert.Equal(t, traceContext.Span, span.ParentID())
tracer.Flush(nil)
payloads := tracer.Payloads()
require.Len(t, payloads.Spans, 1)
assert.Equal(t, model.SpanID(parentID), payloads.Spans[0].ParentID)
}
func TestSpanEnsureType(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpan("name", "", nil)
span.End()
tx.End()
tracer.Flush(nil)
payloads := tracer.Payloads()
require.Len(t, payloads.Spans, 1)
assert.Equal(t, "custom", payloads.Spans[0].Type)
}
func TestSpanLink(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
links := []apm.SpanLink{
{Trace: apm.TraceID{1}, Span: apm.SpanID{1}},
{Trace: apm.TraceID{2}, Span: apm.SpanID{2}},
}
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpanOptions("name", "type", apm.SpanOptions{
Links: links,
})
span.End()
tx.End()
tracer.Flush(nil)
payloads := tracer.Payloads()
require.Len(t, payloads.Spans, 1)
require.Len(t, payloads.Spans[0].Links, len(links))
// Assert span links are identical.
expectedLinks := []model.SpanLink{
{TraceID: model.TraceID{1}, SpanID: model.SpanID{1}},
{TraceID: model.TraceID{2}, SpanID: model.SpanID{2}},
}
assert.Equal(t, expectedLinks, payloads.Spans[0].Links)
}
func TestSpanAddLink(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpanOptions("name", "type", apm.SpanOptions{})
span.AddLink(apm.SpanLink{
Trace: apm.TraceID{1},
Span: apm.SpanID{1},
})
span.End()
tx.End()
tracer.Flush(nil)
payloads := tracer.Payloads()
require.Len(t, payloads.Spans, 1)
require.Len(t, payloads.Spans[0].Links, 1)
// Assert span links are identical.
expectedLinks := []model.SpanLink{
{TraceID: model.TraceID{1}, SpanID: model.SpanID{1}},
}
assert.Equal(t, expectedLinks, payloads.Spans[0].Links)
}
func TestSpanTiming(t *testing.T) {
var spanStart, spanEnd time.Time
txStart := time.Now()
tx, spans, _ := apmtest.WithTransactionOptions(
apm.TransactionOptions{Start: txStart},
func(ctx context.Context) {
time.Sleep(500 * time.Millisecond)
span, _ := apm.StartSpan(ctx, "name", "type")
spanStart = time.Now()
time.Sleep(500 * time.Millisecond)
spanEnd = time.Now()
span.End()
},
)
require.Len(t, spans, 1)
span := spans[0]
assert.InEpsilon(t,
spanStart.Sub(txStart),
time.Time(span.Timestamp).Sub(time.Time(tx.Timestamp)),
0.1, // 10% error
)
assert.InEpsilon(t,
spanEnd.Sub(spanStart)/time.Millisecond,
span.Duration,
0.1, // 10% error
)
}
func TestSpanType(t *testing.T) {
spanTypes := []string{"type", "type.subtype", "type.subtype.action", "type.subtype.action.figure"}
_, spans, _ := apmtest.WithTransaction(func(ctx context.Context) {
for _, spanType := range spanTypes {
span, _ := apm.StartSpan(ctx, "name", spanType)
span.End()
}
})
require.Len(t, spans, 4)
check := func(s model.Span, spanType, spanSubtype, spanAction string) {
assert.Equal(t, spanType, s.Type)
assert.Equal(t, spanSubtype, s.Subtype)
assert.Equal(t, spanAction, s.Action)
}
check(spans[0], "type", "", "")
check(spans[1], "type", "subtype", "")
check(spans[2], "type", "subtype", "action")
check(spans[3], "type", "subtype", "action.figure")
}
func TestStartExitSpan(t *testing.T) {
_, spans, _ := apmtest.WithTransaction(func(ctx context.Context) {
span, _ := apm.StartSpanOptions(ctx, "name", "type", apm.SpanOptions{ExitSpan: true})
span.Duration = 2 * time.Millisecond
assert.True(t, span.IsExitSpan())
span.End()
})
require.Len(t, spans, 1)
// When the context's DestinationService is not explicitly set, ending
// the exit span will assign the value.
assert.Equal(t, spans[0].Context.Destination.Service.Resource, "type")
// When the context's ServiceTarget is not explicitly set, ending
// the exit span will assign the value.
assert.Equal(t, spans[0].Context.Service.Target.Type, "type")
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpanOptions("name", "type", apm.SpanOptions{ExitSpan: true})
assert.True(t, span.IsExitSpan())
// when the parent span is an exit span, children with a different type or
// subtype should be noops.
span2 := tx.StartSpan("name", "differenttype", span)
span2.End()
assert.True(t, span2.Dropped())
// Exit spans MAY have child spans that have the same `type` and `subtype`.
span3 := tx.StartSpan("name", "type", span)
span3.End()
assert.False(t, span3.Dropped())
span.End()
// Spans should still be marked as an exit span after they've been
// ended.
assert.True(t, span.IsExitSpan())
// Even ended exit spans MAY have child spans that have the same
// `type` and `subtype`.
span4 := tx.StartSpan("name", "type", span)
span4.End()
assert.False(t, span4.Dropped())
}
func TestSpanStackTraceMinDurationSpecialCases(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
// verify that no stacktraces are recorded
tracer.SetSpanStackTraceMinDuration(-1)
tx := tracer.StartTransaction("name", "type")
span := tx.StartSpan("span", "span", nil)
span.End()
tx.End()
tracer.Flush(nil)
tracer.Close()
spans := tracer.Payloads().Spans
require.Len(t, spans, 1)
assert.Len(t, spans[0].Stacktrace, 0)
// verify that stacktraces are always recorded
tracer = apmtest.NewRecordingTracer()
defer tracer.Close()
tracer.SetSpanStackTraceMinDuration(0)
tx = tracer.StartTransaction("name", "type")
span = tx.StartSpan("span2", "span2", nil)
span.End()
tx.End()
tracer.Flush(nil)
spans = tracer.Payloads().Spans
require.Len(t, spans, 1)
assert.NotEmpty(t, spans[0].Stacktrace)
}
func TestCompressSpanNonSiblings(t *testing.T) {
// Asserts that non sibling spans are not compressed.
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tracer.SetSpanCompressionEnabled(true)
// Avoid the spans from being dropped by fast exit spans.
tracer.SetExitSpanMinDuration(time.Nanosecond)
tx := tracer.StartTransaction("name", "type")
parent := tx.StartSpan("parent", "parent", nil)
createSpans := []struct {
name, typ string
parent apm.TraceContext
}{
{name: "not compressed", typ: "internal", parent: parent.TraceContext()},
{name: "not compressed", typ: "internal", parent: tx.TraceContext()},
{name: "compressed", typ: "internal", parent: parent.TraceContext()},
{name: "compressed", typ: "internal", parent: parent.TraceContext()},
{name: "compressed", typ: "different", parent: tx.TraceContext()},
{name: "compressed", typ: "different", parent: tx.TraceContext()},
}
for _, span := range createSpans {
span := tx.StartSpanOptions(span.name, span.typ, apm.SpanOptions{
ExitSpan: true, Parent: span.parent,
})
span.Duration = time.Millisecond
span.End()
}
parent.End()
tx.End()
tracer.Flush(nil)
spans := tracer.Payloads().Spans
require.Len(t, spans, 5)
// First two spans should not have been compressed together.
require.Nil(t, spans[0].Composite)
require.Nil(t, spans[1].Composite)
assert.NotNil(t, spans[2].Composite)
assert.Equal(t, 2, spans[2].Composite.Count)
assert.Equal(t, float64(2), spans[2].Composite.Sum)
assert.Equal(t, "exact_match", spans[2].Composite.CompressionStrategy)
assert.NotNil(t, spans[3].Composite)
assert.Equal(t, 2, spans[3].Composite.Count)
assert.Equal(t, float64(2), spans[3].Composite.Sum)
assert.Equal(t, "exact_match", spans[3].Composite.CompressionStrategy)
}
func TestCompressSpanExactMatch(t *testing.T) {
// Aserts that that span compression works on compressable spans with
// "exact_match" strategy.
tests := []struct {
setup func(t *testing.T) func()
assertFunc func(t *testing.T, tx model.Transaction, spans []model.Span)
name string
compressionEnabled bool
}{
// |______________transaction (095b51e1b6ca784c) - 2.0013ms_______________|
// m
// m
// m
// m
// m
// m
// m
// m
// m
// m
// |___________________mysql SELECT * FROM users - 2ms____________________|
// r
// i
// r
{
name: "CompressFalse",
compressionEnabled: false,
assertFunc: func(t *testing.T, tx model.Transaction, spans []model.Span) {
require.NotEmpty(t, tx)
require.Equal(t, 14, len(spans))
for _, span := range spans {
require.Nil(t, span.Composite)
}
},
},
// |______________transaction (7d3254511f02b26b) - 2.0013ms_______________|
// 10
// |___________________mysql SELECT * FROM users - 2ms___________________|
// r
// i
// r
{
name: "CompressTrueSettingTweak",
compressionEnabled: true,
setup: func(*testing.T) func() {
// This setting
envVarName := "ELASTIC_APM_SPAN_COMPRESSION_EXACT_MATCH_MAX_DURATION"
og := os.Getenv(envVarName)
os.Setenv(envVarName, "1ms")
return func() { os.Setenv(envVarName, og) }
},
assertFunc: func(t *testing.T, tx model.Transaction, spans []model.Span) {
require.NotNil(t, tx)
require.Equal(t, 5, len(spans))
composite := spans[0]
require.NotNil(t, composite.Composite)
assert.Equal(t, "SELECT * FROM users", composite.Name)
assert.Equal(t, "exact_match", composite.Composite.CompressionStrategy)
assert.Equal(t, composite.Composite.Count, 10)
assert.Equal(t, 0.001, composite.Composite.Sum)
assert.Equal(t, 0.001, composite.Duration)
for _, span := range spans[1:] {
require.Nil(t, span.Composite)
}
},
},
// |______________transaction (5797fe58c6ccce29) - 2.0013ms_______________|
// |_____________________11 Calls to mysql - 2.001ms______________________|
// r
// i
// r
{
name: "CompressSpanCount4",
compressionEnabled: true,
assertFunc: func(t *testing.T, tx model.Transaction, spans []model.Span) {
require.NotEmpty(t, tx)
var composite = spans[0]
assert.Equal(t, composite.Context.Destination.Service.Resource, "mysql")
require.NotNil(t, composite.Composite)
assert.Equal(t, "SELECT * FROM users", composite.Name)
assert.Equal(t, composite.Composite.Count, 11)
assert.Equal(t, "exact_match", composite.Composite.CompressionStrategy)
// Sum should be at least the time that each span ran for. The
// model time is in Milliseconds and the span duration should be
// at least 2 Milliseconds
assert.Equal(t, int(composite.Composite.Sum), 2)
assert.Equal(t, int(composite.Duration), 2)
for _, span := range spans {
if span.Type == "mysql" {
continue
}
assert.Nil(t, span.Composite)
}
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.setup != nil {
defer test.setup(t)()
}
tracer := apmtest.NewRecordingTracer()
tracer.SetExitSpanMinDuration(time.Nanosecond)
defer tracer.Close()
tracer.SetSpanCompressionEnabled(test.compressionEnabled)
// When compression is enabled:
// Compress 10 spans into 1 and add another span with a different type
// [ Transaction ]
// [ mysql (11) ] [ request ] [ internal ] [ request ]
//
txStart := time.Now()
tx := tracer.StartTransactionOptions("name", "type",
apm.TransactionOptions{Start: txStart},
)
currentTime := txStart
for i := 0; i < 10; i++ {
span := tx.StartSpanOptions("SELECT * FROM users", "mysql", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
// Compressed when the exact_match threshold is >= 2ms.
{
span := tx.StartSpanOptions("SELECT * FROM users", "mysql", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 2 * time.Millisecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
// None of these should be added to the composite.
{
span := tx.StartSpanOptions("GET /", "request", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
{
// Not an exit span, should not be compressed
span := tx.StartSpanOptions("calculate complex", "internal", apm.SpanOptions{
Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
{
// Exit span, this is a good candidate to be compressed, but
// since it can't be compressed with the last request type ("internal")
span := tx.StartSpanOptions("GET /", "request", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
tx.Duration = currentTime.Sub(txStart)
tx.End()
tracer.Flush(nil)
transaction := tracer.Payloads().Transactions[0]
spans := tracer.Payloads().Spans
defer func() {
if t.Failed() {
apmtest.WriteTraceWaterfall(os.Stdout, transaction, spans)
apmtest.WriteTraceTable(os.Stdout, transaction, spans)
}
}()
if test.assertFunc != nil {
test.assertFunc(t, transaction, spans)
}
})
}
}
func TestCompressSpanName(t *testing.T) {
type testcase struct {
name string
serviceTargetName string
serviceTargetType string
expectedName string
}
testcases := []testcase{{
name: "unknown",
expectedName: "Calls to unknown",
}, {
name: "unknown type",
serviceTargetName: "foo",
// service target type is inferred so the expected name is type/name
expectedName: "Calls to request/foo",
}, {
name: "unknown name",
serviceTargetType: "bar",
expectedName: "Calls to bar",
}, {
name: "known",
serviceTargetName: "foo",
serviceTargetType: "bar",
expectedName: "Calls to bar/foo",
}}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
t.Cleanup(tracer.Close)
tracer.SetSpanCompressionEnabled(true)
tracer.SetSpanCompressionSameKindMaxDuration(5 * time.Second)
// Don't drop fast exit spans.
tracer.SetExitSpanMinDuration(0)
txStart := time.Now()
tx := tracer.StartTransactionOptions("name", "type",
apm.TransactionOptions{
Start: txStart,
},
)
currentTime := txStart
// These should be compressed into 1 since they meet the compression
// criteria.
path := []string{"/a", "/b", "/c", "/d", "/e"}
for i := 0; i < len(path); i++ {
span := tx.StartSpanOptions(fmt.Sprint("GET ", path[i]), "request", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.Context.SetServiceTarget(apm.ServiceTargetSpanContext{
Type: tc.serviceTargetType,
Name: tc.serviceTargetName,
})
span.End()
}
tx.Duration = currentTime.Sub(txStart)
tx.End()
tracer.Flush(nil)
transaction := tracer.Payloads().Transactions[0]
spans := tracer.Payloads().Spans
t.Cleanup(func() {
if t.Failed() {
apmtest.WriteTraceWaterfall(os.Stdout, transaction, spans)
apmtest.WriteTraceTable(os.Stdout, transaction, spans)
}
})
require.Equal(t, 1, len(spans))
requestSpan := spans[0]
assert.NotNil(t, requestSpan.Composite)
assert.Equal(t, 5, requestSpan.Composite.Count)
assert.Equal(t, tc.expectedName, requestSpan.Name)
assert.Equal(t, "same_kind", requestSpan.Composite.CompressionStrategy)
})
}
}
func TestCompressSpanSameKind(t *testing.T) {
// Aserts that that span compression works on compressable spans with
// "same_kind" strategy, and that different span types are not compressed.
testCase := func(tracer *apmtest.RecordingTracer) (model.Transaction, []model.Span, func()) {
txStart := time.Now()
tx := tracer.StartTransactionOptions("name", "type",
apm.TransactionOptions{Start: txStart},
)
currentTime := txStart
// Span is compressable, but cannot be compressed since the next span
// is not the same kind. It's published.
{
span := tx.StartSpanOptions("SELECT * FROM users", "mysql", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
// These should be compressed into 1 since they meet the compression
// criteria.
path := []string{"/a", "/b", "/c", "/d", "/e"}
for i := 0; i < len(path); i++ {
span := tx.StartSpanOptions(fmt.Sprint("GET ", path[i]), "request", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
// This span exceeds the default threshold (5ms) and won't be compressed.
{
span := tx.StartSpanOptions("GET /f", "request", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 6 * time.Millisecond
currentTime = currentTime.Add(span.Duration)
span.End()
}
// Span is compressable and the next span is the same kind, but cannot be compressed
// since the service target fields are different (inferred by the db instance).
{
span := tx.StartSpanOptions("SELECT * FROM users", "mysql", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
span.Context.SetServiceTarget(apm.ServiceTargetSpanContext{
Type: "db",
Name: "foo",
})
currentTime = currentTime.Add(span.Duration)
span.End()
}
{
span := tx.StartSpanOptions("SELECT * FROM users", "mysql", apm.SpanOptions{
ExitSpan: true, Start: currentTime,
})
span.Duration = 100 * time.Nanosecond
span.Context.SetServiceTarget(apm.ServiceTargetSpanContext{
Type: "db",
Name: "bar",
})
currentTime = currentTime.Add(span.Duration)
span.End()
}
tx.Duration = currentTime.Sub(txStart)
tx.End()
tracer.Flush(nil)
transaction := tracer.Payloads().Transactions[0]
spans := tracer.Payloads().Spans
debugFunc := func() {
if t.Failed() {
apmtest.WriteTraceWaterfall(os.Stdout, transaction, spans)
apmtest.WriteTraceTable(os.Stdout, transaction, spans)
}
}
return transaction, spans, debugFunc
}
t.Run("DefaultDisabled", func(t *testing.T) {
// By default same kind compression is disabled thus count will be 7.
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tracer.SetSpanCompressionEnabled(true)
// Don't drop fast exit spans.
tracer.SetExitSpanMinDuration(0)
_, spans, debugFunc := testCase(tracer)
defer debugFunc()
require.Equal(t, 9, len(spans))
mysqlSpan := spans[0]
assert.Equal(t, "mysql", mysqlSpan.Context.Destination.Service.Resource)
assert.Nil(t, mysqlSpan.Composite)
requestSpan := spans[1]
assert.Equal(t, "request", requestSpan.Context.Destination.Service.Resource)
require.Nil(t, requestSpan.Composite)
})
t.Run("10msThreshold", func(t *testing.T) {
// With this threshold the composite count will be 6.
os.Setenv("ELASTIC_APM_SPAN_COMPRESSION_SAME_KIND_MAX_DURATION", "10ms")
defer os.Unsetenv("ELASTIC_APM_SPAN_COMPRESSION_SAME_KIND_MAX_DURATION")
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tracer.SetSpanCompressionEnabled(true)
// Don't drop fast exit spans.
tracer.SetExitSpanMinDuration(0)
_, spans, debugFunc := testCase(tracer)
defer debugFunc()
mysqlSpan := spans[0]
assert.Equal(t, mysqlSpan.Context.Destination.Service.Resource, "mysql")
assert.Nil(t, mysqlSpan.Composite)
requestSpan := spans[1]
assert.Equal(t, requestSpan.Context.Destination.Service.Resource, "request")
assert.NotNil(t, requestSpan.Composite)
assert.Equal(t, 6, requestSpan.Composite.Count)
assert.Equal(t, "Calls to request", requestSpan.Name)
assert.Equal(t, "same_kind", requestSpan.Composite.CompressionStrategy)
// Check that the aggregate sum is at least the duration of the time we
// we waited for.
assert.Greater(t, requestSpan.Composite.Sum, float64(5*100/time.Millisecond))
// Check that the total composite span duration is at least 5 milliseconds.
assert.Greater(t, requestSpan.Duration, float64(5*100/time.Millisecond))
})
t.Run("DefaultThresholdDropFastExitSpan", func(t *testing.T) {
tracer := apmtest.NewRecordingTracer()
defer tracer.Close()
tracer.SetSpanCompressionEnabled(true)
tx, spans, debugFunc := testCase(tracer)
defer debugFunc()
// drops all spans except the last request span.
require.Equal(t, 1, len(spans))
// Collects statistics about the dropped spans (request and mysql).
require.Equal(t, 4, len(tx.DroppedSpansStats))
})
}
func TestCompressSpanSameKindParentSpan(t *testing.T) {
// This test asserts the span compression works when the spans are children
// of another span.
tracer := apmtest.NewRecordingTracer()
tracer.SetSpanCompressionEnabled(true)
tracer.SetExitSpanMinDuration(0)
tracer.SetSpanCompressionSameKindMaxDuration(5 * time.Millisecond)
// This test case covers spans that have other spans as parents.
// |_______________transaction (6b1e4866252dea6f) - 1.45ms________________|
// |__internal internal op - 700µs___|
// |request GET /r|
// |request G|
// |___internal another op - 750µs____|
// |2 Calls to re|
txStart := time.Now()
tx := tracer.StartTransactionOptions("name", "type",
apm.TransactionOptions{Start: txStart},
)
ctx := apm.ContextWithTransaction(context.Background(), tx)
currentTime := txStart
{
// Doesn't compress any spans since none meet the necessary conditions
// the "request" type are both the same type but the parent
parent, ctx := apm.StartSpanOptions(ctx, "internal op", "internal", apm.SpanOptions{
Start: currentTime,
})
// Have span propagate context downstream, this should not allow for
// compression
child, ctx := apm.StartSpanOptions(ctx, "GET /resource", "request", apm.SpanOptions{
Start: currentTime.Add(100 * time.Microsecond),
})
grandChild, _ := apm.StartSpanOptions(ctx, "GET /different", "request", apm.SpanOptions{
ExitSpan: true,
Start: currentTime.Add(120 * time.Microsecond),
})
grandChild.Duration = 200 * time.Microsecond
grandChild.End()
child.Duration = 300 * time.Microsecond
child.End()
parent.Duration = 700 * time.Microsecond
currentTime = currentTime.Add(parent.Duration)
parent.End()
}
{
// Compresses the last two spans together since they are both exit
// spans, same "request" type, don't propagate ctx and succeed.
parent, ctx := apm.StartSpanOptions(ctx, "another op", "internal", apm.SpanOptions{
Start: currentTime.Add(50 * time.Microsecond),
})
child, _ := apm.StartSpanOptions(ctx, "GET /res", "request", apm.SpanOptions{
ExitSpan: true,
Start: currentTime.Add(120 * time.Microsecond),
})
otherChild, _ := apm.StartSpanOptions(ctx, "GET /diff", "request", apm.SpanOptions{
ExitSpan: true,
Start: currentTime.Add(150 * time.Microsecond),
})
otherChild.Duration = 250 * time.Microsecond
otherChild.End()
child.Duration = 300 * time.Microsecond
child.End()
parent.Duration = 750 * time.Microsecond
currentTime = currentTime.Add(parent.Duration)
parent.End()
}
tx.Duration = currentTime.Sub(txStart)
tx.End()
tracer.Flush(nil)
transaction := tracer.Payloads().Transactions[0]
spans := tracer.Payloads().Spans
defer func() {
if t.Failed() {
apmtest.WriteTraceTable(os.Stdout, transaction, spans)
apmtest.WriteTraceWaterfall(os.Stdout, transaction, spans)
}
}()
require.NotNil(t, transaction)
assert.Equal(t, 5, len(spans))
compositeSpan := spans[3]
compositeParent := spans[4]
require.NotNil(t, compositeSpan)
require.NotNil(t, compositeSpan.Composite)
assert.Equal(t, "Calls to request", compositeSpan.Name)
assert.Equal(t, "request", compositeSpan.Type)
assert.Equal(t, "internal", compositeParent.Type)
assert.Equal(t, compositeSpan.Composite.Count, 2)
assert.Equal(t, compositeSpan.ParentID, compositeParent.ID)
assert.GreaterOrEqual(t, compositeParent.Duration, compositeSpan.Duration)
}
func TestCompressSpanSameKindParentSpanContext(t *testing.T) {
// This test ensures that the compression also works when the s.Parent is
// set (via the context.Context).
// |________________transaction (6df3948c6eff7b57) - 15ms_________________|
// |_____________________internal parent - 14ms______________________|
// |_3 db - 3ms__|
// |_internal algorithm - 6ms__|
// |2 Calls to client |
// |inte|
tracer := apmtest.NewRecordingTracer()
tracer.SetSpanCompressionEnabled(true)
tracer.SetExitSpanMinDuration(0)
tracer.SetSpanCompressionSameKindMaxDuration(5 * time.Millisecond)
txStart := time.Now()
tx := tracer.StartTransactionOptions("name", "type",
apm.TransactionOptions{Start: txStart},
)
ctx := apm.ContextWithTransaction(context.Background(), tx)
parentStart := txStart.Add(time.Millisecond)
parent, ctx := apm.StartSpanOptions(ctx, "parent", "internal", apm.SpanOptions{
Start: parentStart,
})
// These spans are all compressed into a composite.
childrenStart := parentStart.Add(2 * time.Millisecond)
for i := 0; i < 3; i++ {
span, _ := apm.StartSpanOptions(ctx, "db", "redis", apm.SpanOptions{
ExitSpan: true,
Start: childrenStart,
})
childrenStart = childrenStart.Add(time.Millisecond)
span.Duration = time.Millisecond
span.End()
}
// We create a nother "internal" type span from which 3 children (below)
// are created. one of them
testSpans := []struct {
name string
typ string
duration time.Duration
}{
{name: "GET /some", typ: "client", duration: time.Millisecond},
{name: "GET /resource", typ: "client", duration: 2 * time.Millisecond},
{name: "compute something", typ: "internal", duration: time.Millisecond},
}
subParent, ctx := apm.StartSpanOptions(ctx, "algorithm", "internal", apm.SpanOptions{
Start: childrenStart.Add(time.Millisecond),
})
childrenStart = childrenStart.Add(time.Millisecond)
for _, childCfg := range testSpans {
child, _ := apm.StartSpanOptions(ctx, childCfg.name, childCfg.typ, apm.SpanOptions{
ExitSpan: true,
Start: childrenStart.Add(childCfg.duration),
})
childrenStart = childrenStart.Add(childCfg.duration)
child.Duration = childCfg.duration
child.End()
}
childrenStart = childrenStart.Add(time.Millisecond)
subParent.Duration = 6 * time.Millisecond
subParent.End()
parent.Duration = childrenStart.Add(2 * time.Millisecond).Sub(txStart)
parent.End()
tx.Duration = 15 * time.Millisecond
tx.End()
tracer.Flush(nil)
transaction := tracer.Payloads().Transactions[0]
spans := tracer.Payloads().Spans
defer func() {
if t.Failed() {
apmtest.WriteTraceTable(os.Stdout, transaction, spans)
apmtest.WriteTraceWaterfall(os.Stdout, transaction, spans)
}
}()
require.NotNil(t, transaction)
assert.Equal(t, 5, len(spans))
sort.SliceStable(spans, func(i, j int) bool {
return time.Time(spans[i].Timestamp).Before(time.Time(spans[j].Timestamp))
})
redisSpan := spans[1]
require.NotNil(t, redisSpan.Composite)
assert.Equal(t, "db", redisSpan.Name)
assert.Equal(t, 3, redisSpan.Composite.Count)
assert.Equal(t, float64(3), redisSpan.Composite.Sum)
assert.Equal(t, "exact_match", redisSpan.Composite.CompressionStrategy)
clientSpan := spans[3]
require.NotNil(t, clientSpan.Composite)
assert.Equal(t, "Calls to client", clientSpan.Name)
assert.Equal(t, clientSpan.ParentID, spans[2].ID)