/
templated.go
806 lines (701 loc) · 24.9 KB
/
templated.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
package tracegen
import (
"fmt"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
"github.com/grafana/xk6-client-tracing/pkg/random"
"github.com/grafana/xk6-client-tracing/pkg/util"
"github.com/pkg/errors"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
)
// OTelSemantics describes a specific set of OpenTelemetry semantic conventions.
type OTelSemantics string
const (
SemanticsHTTP OTelSemantics = "http"
SemanticsDB OTelSemantics = "db"
defaultMinDuration = time.Millisecond * 500
defaultMaxDuration = time.Millisecond * 800
defaultRandomAttributeCardinality = 20
randomAttributeKeySize = 15
randomAttributeValueSize = 30
)
// Range represents and interval with the given upper and lower bound [Max, Min)
type Range struct {
Min int64
Max int64
}
// AttributeParams describe how random attributes should be created.
type AttributeParams struct {
// Count the number of attributes to create.
Count int
// Cardinality how many distinct values are created for each attribute.
Cardinality *int
}
// SpanDefaults contains template parameters that are applied to all generated spans.
type SpanDefaults struct {
// AttributeSemantics whether to create attributes that follow specific OpenTelemetry semantics.
AttributeSemantics *OTelSemantics `js:"attributeSemantics"`
// Attributes that are added to each span.
Attributes map[string]interface{} `js:"attributes"`
// RandomAttributes random attributes generated for each span.
RandomAttributes *AttributeParams `js:"randomAttributes"`
// Random events generated for each span
RandomEvents EventParams `js:"randomEvents"`
// Random links generated for each span
RandomLinks LinkParams `js:"randomLinks"`
}
// SpanTemplate parameters that define how a span is created.
type SpanTemplate struct {
// Service is used to set the service.name attribute of the corresponding resource span.
Service string `js:"service"`
// Name represents the name of the span. If empty, the name will be randomly generated.
Name *string `js:"name"`
// ParentIDX defines the index of the parent span in TraceTemplate.Spans. ParentIDX must be smaller than the
// own index. If empty, the parent is the span with the position directly before this span in TraceTemplate.Spans.
ParentIDX *int `js:"parentIdx"`
// Duration defines the interval for the generated span duration. If missing, a random duration is generated that
// is shorter than the duration of the parent span.
Duration *Range `js:"duration"`
// AttributeSemantics can be set in order to generate attributes that follow a certain OpenTelemetry semantic
// convention. So far only semantic convention for HTTP requests is supported.
AttributeSemantics *OTelSemantics `js:"attributeSemantics"`
// Attributes that are added to this span.
Attributes map[string]interface{} `js:"attributes"`
// RandomAttributes parameters to configure the creation of random attributes. If missing, no random attributes
// are added to the span.
RandomAttributes *AttributeParams `js:"randomAttributes"`
// List of events for the span with specific parameters
Events []Event `js:"events"`
// List of links for the span with specific parameters
Links []Link `js:"links"`
// Generate random events for the span
RandomEvents EventParams `js:"randomEvents"`
// Generate random links for the span
RandomLinks LinkParams `js:"randomLinks"`
}
// TraceTemplate describes how all a trace and it's spans are generated.
type TraceTemplate struct {
// Defaults parameters that are applied to each generated span.
Defaults SpanDefaults `js:"defaults"`
// Spans parameters for the individual spans of a trace.
Spans []SpanTemplate `js:"spans"`
}
type Link struct {
// Attributes for this link
Attributes map[string]interface{} `js:"attributes"`
// Generate random attributes for this link
RandomAttributes *AttributeParams `js:"randomAttributes"`
}
type Event struct {
// Name of event
Name string `js:"name"`
// Attributes for this event
Attributes map[string]interface{} `js:"attributes"`
// Generate random attributes for this event
RandomAttributes *AttributeParams `js:"randomAttributes"`
}
type LinkParams struct {
// Rate of random links per each span
Rate float32 `js:"rate"`
// Generate random attributes for this link
RandomAttributes *AttributeParams `js:"randomAttributes"`
}
type EventParams struct {
// Generate exception event if status code of the span is >= 400
GenerateExceptionOnError bool `js:"generateExceptionOnError"`
// Rate of exception events per each span
ExceptionRate float32 `js:"exceptionRate"`
// Rate of random events per each span
Rate float32 `js:"rate"`
// Generate random attributes for this event
RandomAttributes *AttributeParams `js:"randomAttributes"`
}
type internalLinkParams struct {
Count int
RandomAttributes *AttributeParams
}
type internalEventParams struct {
GenerateExceptionOnError bool
ExceptionCount int
Count int
RandomAttributes *AttributeParams
}
// NewTemplatedGenerator creates a new trace generator.
func NewTemplatedGenerator(template *TraceTemplate) (*TemplatedGenerator, error) {
gen := &TemplatedGenerator{}
err := gen.initialize(template)
if err != nil {
return nil, errors.Wrap(err, "fail to create new templated generator")
}
return gen, nil
}
// TemplatedGenerator a trace generator that creates randomized traces based on a given TraceTemplate.
// The generator interprets the template parameters such that realistically looking traces with consistent
// spans and attributes are generated.
type TemplatedGenerator struct {
randomAttributes map[string][]interface{}
resources map[string]*internalResourceTemplate
spans []*internalSpanTemplate
}
type internalSpanTemplate struct {
idx int
resource *internalResourceTemplate
parent *internalSpanTemplate
name string
kind ptrace.SpanKind
duration *Range
attributeSemantics *OTelSemantics
attributes map[string]interface{}
randomAttributes map[string][]interface{}
events []Event
links []Link
generateExceptionEvents bool
}
type internalResourceTemplate struct {
service string
hostName string
hostIP string
transport string
hostPort int
}
// Traces implements Generator for TemplatedGenerator
func (g *TemplatedGenerator) Traces() ptrace.Traces {
var (
traceID = random.TraceID()
traceData = ptrace.NewTraces()
resSpanSlice = traceData.ResourceSpans()
resSpanMap = map[string]ptrace.ResourceSpans{}
spans []ptrace.Span
)
randomTraceAttributes := make(map[string]interface{}, len(g.randomAttributes))
for k, v := range g.randomAttributes {
randomTraceAttributes[k] = random.SelectElement(v)
}
for _, tmpl := range g.spans {
// get or generate the corresponding ResourceSpans
resSpans, found := resSpanMap[tmpl.resource.service]
if !found {
resSpans = g.generateResourceSpans(resSpanSlice, tmpl.resource)
resSpanMap[tmpl.resource.service] = resSpans
}
scopeSpans := resSpans.ScopeSpans().At(0)
// generate new span
var parent *ptrace.Span
if tmpl.parent != nil {
parent = &spans[tmpl.parent.idx]
}
s := g.generateSpan(scopeSpans, tmpl, parent, traceID)
// attributes
for k, v := range randomTraceAttributes {
if _, found := s.Attributes().Get(k); !found {
_ = s.Attributes().PutEmpty(k).FromRaw(v)
}
}
spans = append(spans, s)
}
return traceData
}
func (g *TemplatedGenerator) generateResourceSpans(resSpanSlice ptrace.ResourceSpansSlice, tmpl *internalResourceTemplate) ptrace.ResourceSpans {
resSpans := resSpanSlice.AppendEmpty()
resSpans.Resource().Attributes().PutStr("k6", "true")
resSpans.Resource().Attributes().PutStr("service.name", tmpl.service)
scopeSpans := resSpans.ScopeSpans().AppendEmpty()
scopeSpans.Scope().SetName("k6")
return resSpans
}
func (g *TemplatedGenerator) generateSpan(scopeSpans ptrace.ScopeSpans, tmpl *internalSpanTemplate, parent *ptrace.Span, traceID pcommon.TraceID) ptrace.Span {
span := scopeSpans.Spans().AppendEmpty()
span.SetTraceID(traceID)
span.SetSpanID(random.SpanID())
if parent != nil {
span.SetParentSpanID(parent.SpanID())
}
span.SetName(tmpl.name)
span.SetKind(tmpl.kind)
// set start and end time
var start time.Time
var duration time.Duration
if parent == nil {
start = time.Now().Add(-5 * time.Second)
if tmpl.duration == nil {
duration = random.Duration(defaultMinDuration, defaultMaxDuration)
}
} else {
pStart := parent.StartTimestamp().AsTime()
pDuration := parent.EndTimestamp().AsTime().Sub(pStart)
start = pStart.Add(random.Duration(pDuration/20, pDuration/10))
if tmpl.duration == nil {
duration = random.Duration(pDuration/2, pDuration-pDuration/10)
}
}
if tmpl.duration != nil {
duration = random.Duration(time.Duration(tmpl.duration.Min)*time.Millisecond, time.Duration(tmpl.duration.Max)*time.Millisecond)
}
end := start.Add(duration)
span.SetStartTimestamp(pcommon.NewTimestampFromTime(start))
span.SetEndTimestamp(pcommon.NewTimestampFromTime(end))
// add attributes
for k, v := range tmpl.attributes {
_ = span.Attributes().PutEmpty(k).FromRaw(v)
}
for k, v := range tmpl.randomAttributes {
_ = span.Attributes().PutEmpty(k).FromRaw(random.SelectElement(v))
}
g.generateNetworkAttributes(tmpl, &span, parent)
if tmpl.attributeSemantics != nil {
switch *tmpl.attributeSemantics {
case SemanticsHTTP:
g.generateHTTPAttributes(tmpl, &span, parent)
}
}
// events
span.Events().EnsureCapacity(len(tmpl.events))
for _, e := range tmpl.events {
event := span.Events().AppendEmpty()
event.SetName(e.Name)
event.SetTimestamp(pcommon.NewTimestampFromTime(end))
for k, v := range e.Attributes {
_ = event.Attributes().PutEmpty(k).FromRaw(v)
}
}
if tmpl.generateExceptionEvents {
var status int64
parentAttr := pcommon.NewMap()
if parent != nil {
parentAttr = parent.Attributes()
}
if st, found := span.Attributes().Get("http.status_code"); found {
status = st.Int()
} else if st, found = parentAttr.Get("http.status_code"); found {
status = st.Int()
} else {
status = random.HTTPStatusSuccess()
span.Attributes().PutInt("http.status_code", status)
}
if status >= 400 {
exceptionEvent := generateExceptionEvent()
event := span.Events().AppendEmpty()
event.SetName(exceptionEvent.Name)
event.SetTimestamp(pcommon.NewTimestampFromTime(end))
for k, v := range exceptionEvent.Attributes {
_ = event.Attributes().PutEmpty(k).FromRaw(v)
}
}
}
// links
span.Links().EnsureCapacity(len(tmpl.links))
for _, l := range tmpl.links {
link := span.Links().AppendEmpty()
// default to linking to previous span if exist
// maybe we will be able support linking to specific spans in the future
if parent != nil {
link.SetTraceID(traceID)
link.SetSpanID(parent.SpanID())
} else {
link.SetTraceID(random.TraceID())
link.SetSpanID(random.SpanID())
}
for k, v := range l.Attributes {
_ = link.Attributes().PutEmpty(k).FromRaw(v)
}
}
return span
}
func (g *TemplatedGenerator) generateNetworkAttributes(tmpl *internalSpanTemplate, span, parent *ptrace.Span) {
if tmpl.kind == ptrace.SpanKindInternal {
return
}
putIfNotExists(span.Attributes(), "net.transport", tmpl.resource.transport)
putIfNotExists(span.Attributes(), "net.sock.family", "inet")
if tmpl.kind == ptrace.SpanKindClient {
putIfNotExists(span.Attributes(), "net.peer.port", random.Port())
} else if tmpl.kind == ptrace.SpanKindServer {
putIfNotExists(span.Attributes(), "net.sock.host.addr", tmpl.resource.hostIP)
putIfNotExists(span.Attributes(), "net.host.name", tmpl.resource.hostName)
putIfNotExists(span.Attributes(), "net.host.port", tmpl.resource.hostPort)
if parent != nil && parent.Kind() == ptrace.SpanKindClient {
ip, _ := span.Attributes().Get("net.sock.host.addr")
putIfNotExists(parent.Attributes(), "net.sock.peer.addr", ip.Str())
name, _ := span.Attributes().Get("net.host.name")
putIfNotExists(parent.Attributes(), "net.peer.name", name.Str())
}
}
}
func (g *TemplatedGenerator) generateHTTPAttributes(tmpl *internalSpanTemplate, span, parent *ptrace.Span) {
if tmpl.kind == ptrace.SpanKindInternal {
return
}
parentAttr := pcommon.NewMap()
if parent != nil {
parentAttr = parent.Attributes()
}
putIfNotExists(span.Attributes(), "http.flavor", "1.1")
if tmpl.kind == ptrace.SpanKindServer {
var method string
if m, found := span.Attributes().Get("http.method"); found {
method = m.Str()
} else if m, found = parentAttr.Get("http.method"); found {
method = m.Str()
} else {
method = random.HTTPMethod()
span.Attributes().PutStr("http.method", method)
}
var contentType []any
if ct, found := span.Attributes().Get("http.response.header.content-type"); found {
contentType = ct.Slice().AsRaw()
} else {
contentType = random.HTTPContentType()
_ = span.Attributes().PutEmptySlice("http.response.header.content-type").FromRaw(contentType)
}
var status int64
if st, found := span.Attributes().Get("http.status_code"); found {
status = st.Int()
} else if st, found = parentAttr.Get("http.status_code"); found {
status = st.Int()
} else {
status = random.HTTPStatusSuccess()
span.Attributes().PutInt("http.status_code", status)
}
if status >= 500 {
span.Status().SetCode(ptrace.StatusCodeError)
span.Status().SetMessage(http.StatusText(int(status)))
}
var requestURL *url.URL
if u, found := span.Attributes().Get("http.url"); found {
requestURL, _ = url.ParseRequestURI(u.Str())
} else if u, found = parentAttr.Get("http.url"); found {
requestURL, _ = url.ParseRequestURI(u.Str())
} else {
requestURL, _ = url.ParseRequestURI(fmt.Sprintf("https://%s:%d/%s", tmpl.resource.hostName, tmpl.resource.hostPort, tmpl.name))
span.Attributes().PutStr("http.url", requestURL.String())
}
span.Attributes().PutStr("http.scheme", requestURL.Scheme)
span.Attributes().PutStr("http.target", requestURL.Path)
putIfNotExists(span.Attributes(), "http.response_content_length", random.IntBetween(100_000, 1_000_000))
if method == http.MethodPatch || method == http.MethodPost || method == http.MethodPut {
putIfNotExists(span.Attributes(), "http.request_content_length", random.IntBetween(10_000, 100_000))
}
if parent != nil && parent.Kind() == ptrace.SpanKindClient {
if status >= 400 {
parent.Status().SetCode(ptrace.StatusCodeError)
parent.Status().SetMessage(http.StatusText(int(status)))
}
putIfNotExists(parent.Attributes(), "http.method", method)
putIfNotExists(parent.Attributes(), "http.request.header.accept", contentType)
putIfNotExists(parent.Attributes(), "http.status_code", status)
putIfNotExists(parent.Attributes(), "http.url", requestURL.String())
res, _ := span.Attributes().Get("http.response_content_length")
putIfNotExists(parent.Attributes(), "http.response_content_length", res.Int())
if req, found := span.Attributes().Get("http.request_content_length"); found {
putIfNotExists(span.Attributes(), "http.request_content_length", req.Int())
}
}
}
}
func (g *TemplatedGenerator) initialize(template *TraceTemplate) error {
g.resources = map[string]*internalResourceTemplate{}
g.randomAttributes = initializeRandomAttributes(template.Defaults.RandomAttributes)
for i, tmpl := range template.Spans {
// span templates must have a service
if tmpl.Service == "" {
return errors.New("trace template invalid: span template must have a name")
}
// get or generate the corresponding ResourceSpans
_, found := g.resources[tmpl.Service]
if !found {
res := g.initializeResource(&tmpl)
g.resources[tmpl.Service] = res
}
// span template parent index must reference a previous span
if tmpl.ParentIDX != nil && (*tmpl.ParentIDX >= i || *tmpl.ParentIDX < 0) {
return errors.New("trace template invalid: span index must be greater than span parent index")
}
// initialize span using information from the parent span, the template and child template
parentIdx := i - 1
if tmpl.ParentIDX != nil {
parentIdx = *tmpl.ParentIDX
}
var parent *internalSpanTemplate
if parentIdx >= 0 {
parent = g.spans[parentIdx]
}
var child *SpanTemplate
for j := i + 1; j < len(template.Spans); j++ {
n := template.Spans[j]
if n.ParentIDX == nil || *n.ParentIDX == i {
child = &n
break
}
}
span, err := g.initializeSpan(i, parent, &template.Defaults, &tmpl, child)
if err != nil {
return err
}
g.spans = append(g.spans, span)
}
return nil
}
func (g *TemplatedGenerator) initializeResource(tmpl *SpanTemplate) *internalResourceTemplate {
return &internalResourceTemplate{
service: tmpl.Service,
hostName: fmt.Sprintf("%s.local", tmpl.Service),
hostIP: random.IPAddr(),
hostPort: random.Port(),
transport: "ip_tcp",
}
}
func (g *TemplatedGenerator) initializeSpan(idx int, parent *internalSpanTemplate, defaults *SpanDefaults, tmpl, child *SpanTemplate) (*internalSpanTemplate, error) {
res := g.resources[tmpl.Service]
span := internalSpanTemplate{
idx: idx,
parent: parent,
resource: res,
duration: tmpl.Duration,
}
// apply defaults
if tmpl.AttributeSemantics == nil {
span.attributeSemantics = defaults.AttributeSemantics
}
span.attributes = util.MergeMaps(defaults.Attributes, tmpl.Attributes)
eventDefaultsRate := defaults.RandomEvents.Rate
var eventDefaults internalEventParams
// if rate is more than 1, use whole integers
if eventDefaultsRate > 1 {
eventDefaults = internalEventParams{
GenerateExceptionOnError: defaults.RandomEvents.GenerateExceptionOnError,
RandomAttributes: defaults.RandomEvents.RandomAttributes,
Count: int(eventDefaultsRate),
ExceptionCount: int(defaults.RandomEvents.ExceptionRate),
}
} else {
var count, exeptionCount int
if rand.Float32() < eventDefaultsRate {
count = 1
}
if rand.Float32() < eventDefaultsRate {
exeptionCount = 1
}
// if rate is less than one
eventDefaults = internalEventParams{
GenerateExceptionOnError: defaults.RandomEvents.GenerateExceptionOnError,
RandomAttributes: defaults.RandomEvents.RandomAttributes,
Count: count,
ExceptionCount: exeptionCount,
}
}
randomEvents := internalEventParams{
GenerateExceptionOnError: tmpl.RandomEvents.GenerateExceptionOnError,
RandomAttributes: tmpl.RandomEvents.RandomAttributes,
Count: int(tmpl.RandomEvents.Rate),
ExceptionCount: int(tmpl.RandomEvents.ExceptionRate),
}
// generate all non-exception events
span.events = g.initializeEvents(tmpl.Events, randomEvents, eventDefaults)
// need span status to determine if an exception event should occur
span.generateExceptionEvents = defaults.RandomEvents.GenerateExceptionOnError
linkDefaultsRate := defaults.RandomLinks.Rate
var linkDefaults internalLinkParams
if linkDefaultsRate > 1 {
linkDefaults = internalLinkParams{
RandomAttributes: defaults.RandomLinks.RandomAttributes,
Count: int(linkDefaultsRate),
}
} else if rand.Float32() < linkDefaultsRate {
linkDefaults = internalLinkParams{
RandomAttributes: defaults.RandomLinks.RandomAttributes,
Count: 1,
}
}
randomLinks := internalLinkParams{
Count: int(tmpl.RandomLinks.Rate),
RandomAttributes: tmpl.RandomEvents.RandomAttributes,
}
// initialize all links but need
span.links = g.initializeLinks(tmpl.Links, randomLinks, linkDefaults)
// set span name
if tmpl.Name != nil {
span.name = *tmpl.Name
} else {
span.name = random.Operation()
}
kind, err := initializeSpanKind(parent, tmpl, child)
if err != nil {
return nil, err
}
span.kind = kind
span.randomAttributes = initializeRandomAttributes(tmpl.RandomAttributes)
return &span, nil
}
func initializeSpanKind(parent *internalSpanTemplate, tmpl, child *SpanTemplate) (ptrace.SpanKind, error) {
var kind ptrace.SpanKind
if k, found := tmpl.Attributes["span.kind"]; found {
kindStr, ok := k.(string)
if !ok {
return ptrace.SpanKindUnspecified, errors.Errorf("attribute %s expected to be a string, but was %T", "span.kind", k)
}
kind = spanKindFromString(kindStr)
} else {
if parent == nil {
if child == nil || tmpl.Service == child.Service {
kind = ptrace.SpanKindServer
} else {
kind = ptrace.SpanKindClient
}
} else {
parentService := parent.resource.service
if tmpl.Service != parentService {
kind = ptrace.SpanKindServer
} else if child != nil && tmpl.Service != child.Service {
kind = ptrace.SpanKindClient
} else {
kind = ptrace.SpanKindInternal
}
}
}
return kind, nil
}
func spanKindFromString(s string) ptrace.SpanKind {
s = strings.ToLower(s)
s = strings.TrimPrefix(s, "span_kind_")
switch s {
case "internal":
return ptrace.SpanKindInternal
case "server":
return ptrace.SpanKindServer
case "client":
return ptrace.SpanKindClient
case "producer":
return ptrace.SpanKindProducer
case "consumer":
return ptrace.SpanKindConsumer
default:
return ptrace.SpanKindUnspecified
}
}
func putIfNotExists(m pcommon.Map, k string, v interface{}) {
if _, found := m.Get(k); !found {
_ = m.PutEmpty(k).FromRaw(v)
}
}
func initializeRandomAttributes(attributeParams *AttributeParams) map[string][]interface{} {
if attributeParams == nil {
return map[string][]interface{}{}
}
if attributeParams.Cardinality == nil {
tmp := defaultRandomAttributeCardinality
attributeParams.Cardinality = &tmp
}
attributes := make(map[string][]interface{}, attributeParams.Count)
for i := 0; i < attributeParams.Count; i++ {
key := random.K6String(randomAttributeKeySize)
values := make([]interface{}, 0, *attributeParams.Cardinality)
for j := 0; j < *attributeParams.Cardinality; j++ {
values = append(values, random.String(randomAttributeValueSize))
}
attributes[key] = values
}
return attributes
}
func (g *TemplatedGenerator) initializeEvents(tmplEvents []Event, randomEvents internalEventParams, eventDefaults internalEventParams) []Event {
count := len(tmplEvents) + randomEvents.Count + eventDefaults.Count
if count == 0 {
return []Event{}
}
events := make([]Event, 0, count)
for _, e := range tmplEvents {
event := generateEvent(e.Name, e.Attributes, e.RandomAttributes)
events = append(events, event)
}
for i := 0; i < randomEvents.ExceptionCount; i++ {
event := generateExceptionEvent()
events = append(events, event)
}
for i := 0; i < randomEvents.Count; i++ {
event := generateEvent("", nil, randomEvents.RandomAttributes)
events = append(events, event)
}
for i := 0; i < eventDefaults.Count; i++ {
event := generateEvent("", nil, eventDefaults.RandomAttributes)
events = append(events, event)
}
return events
}
func generateExceptionEvent() Event {
return Event{
Name: "exception",
Attributes: map[string]interface{}{
"exception.escape": false,
"exception.message": generateRandomExceptionMsg(),
"exception.stacktrace": generateRandomExceptionStackTrace(),
"exception.type": random.K6String(10) + ".error",
},
}
}
func generateEvent(name string, attributes map[string]interface{}, randomAttr *AttributeParams) Event {
event := Event{
Attributes: make(map[string]interface{}),
}
if name != "" {
event.Name = name
} else {
event.Name = "event " + random.K6String(10)
}
for k, v := range attributes {
event.Attributes[k] = v
}
for k, v := range initializeRandomAttributes(randomAttr) {
event.Attributes[k] = random.SelectElement(v)
}
return event
}
func generateRandomExceptionMsg() string {
return "error: " + random.K6String(20)
}
func generateRandomExceptionStackTrace() string {
var (
panics = []string{"runtime error: index out of range", "runtime error: can't divide by 0"}
functions = []string{"main.main()", "trace.makespan()", "account.login()", "payment.collect()"}
)
return "panic: " + random.SelectElement(panics) + "\n" + random.SelectElement(functions)
}
func (g *TemplatedGenerator) initializeLinks(tmplLinks []Link, randomLinks internalLinkParams, linkDefaults internalLinkParams) []Link {
count := len(tmplLinks) + randomLinks.Count + linkDefaults.Count
if count == 0 {
return []Link{}
}
links := make([]Link, 0, count)
newLink := func() *Link {
return &Link{
Attributes: make(map[string]interface{}),
}
}
for _, l := range tmplLinks {
link := newLink()
for k, v := range l.Attributes {
link.Attributes[k] = v
}
for k, v := range initializeRandomAttributes(l.RandomAttributes) {
link.Attributes[k] = random.SelectElement(v)
}
links = append(links, *link)
}
for i := 0; i < randomLinks.Count; i++ {
link := newLink()
for k, v := range initializeRandomAttributes(randomLinks.RandomAttributes) {
link.Attributes[k] = random.SelectElement(v)
}
links = append(links, *link)
}
for i := 0; i < linkDefaults.Count; i++ {
link := newLink()
for k, v := range initializeRandomAttributes(linkDefaults.RandomAttributes) {
link.Attributes[k] = random.SelectElement(v)
}
links = append(links, *link)
}
return links
}