-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport.zzzgo
1004 lines (945 loc) · 28.2 KB
/
export.zzzgo
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
// TEMPLATE-FILE
// TEMPLATE-FILE
// TEMPLATE-FILE
package xopotel
import (
"context"
"encoding/json"
"fmt"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/xoplog/xop-go/xopat"
"github.com/xoplog/xop-go/xopbase"
"github.com/xoplog/xop-go/xopconst"
"github.com/xoplog/xop-go/xopnum"
"github.com/xoplog/xop-go/xopproto"
"github.com/xoplog/xop-go/xoptrace"
"github.com/xoplog/xop-go/xoputil/xopversion"
"github.com/muir/gwrap"
"github.com/muir/list"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
oteltrace "go.opentelemetry.io/otel/trace"
)
var _ sdktrace.SpanExporter = &spanExporter{}
var _ sdktrace.SpanExporter = &unhack{}
var ErrShutdown = fmt.Errorf("Shutdown called")
type spanExporter struct {
base xopbase.Logger
orderedFinish []orderedFinish
sequenceNumber int32
done int32
}
type spanReplay struct {
*spanExporter
id2Index map[oteltrace.SpanID]int
spans []sdktrace.ReadOnlySpan
subSpans [][]int
data []*datum
}
type datum struct {
baseSpan xopbase.Span
requestIndex int // index of request ancestor
attributeDefinitions map[string]*decodeAttributeDefinition
xopSpan bool
registry *xopat.Registry
}
func (x *spanExporter) addOrdered(seq int32, f func()) {
x.orderedFinish = append(x.orderedFinish, orderedFinish{
num: seq,
f: f,
})
}
type orderedFinish struct {
num int32
f func()
}
type baseSpanReplay struct {
spanReplay
*datum
span sdktrace.ReadOnlySpan
}
type decodeAttributeDefinition struct {
xopat.Make
AttributeType xopproto.AttributeType `json:"vtype"`
}
type wrappedReadOnlySpan struct {
sdktrace.ReadOnlySpan
links []sdktrace.Link
}
// ExportToXOP allows open telementry spans to be exported through
// a xopbase.Logger. If the open telementry spans were generated
// originally using xoputil, then the exported data should almost
// exactly match the original inputs.
func ExportToXOP(base xopbase.Logger) sdktrace.SpanExporter {
return &spanExporter{
base: base,
}
}
func (e *spanExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) (err error) {
// TODO: avoid returning error when possible
id2Index := makeIndex(spans)
subSpans, todo := makeSubspans(id2Index, spans)
x := spanReplay{
spanExporter: e,
id2Index: id2Index,
spans: spans,
subSpans: subSpans,
data: make([]*datum, len(spans)),
}
var toFinish []func()
var processSpan func(int) error
processSpan = func(i int) error {
x.data[i] = &datum{}
finisher, err := x.Replay(ctx, spans[i], x.data[i], i)
if err != nil {
return err
}
for _, subSpan := range subSpans[i] {
err := processSpan(subSpan)
if err != nil {
return err
}
}
toFinish = append(toFinish, finisher)
return nil
}
for _, i := range todo {
err := processSpan(i)
if err != nil {
return err
}
sort.Slice(e.orderedFinish, func(i, j int) bool {
return e.orderedFinish[i].num < e.orderedFinish[j].num
})
for _, o := range x.orderedFinish {
o.f()
}
x.orderedFinish = x.orderedFinish[:0]
for _, finisher := range toFinish {
finisher()
}
toFinish = toFinish[:0]
}
return nil
}
func (x spanReplay) Replay(ctx context.Context, span sdktrace.ReadOnlySpan, data *datum, myIndex int) (func(), error) {
var bundle xoptrace.Bundle
spanContext := span.SpanContext()
if spanContext.HasTraceID() {
bundle.Trace.TraceID().SetArray(spanContext.TraceID())
}
if spanContext.HasSpanID() {
bundle.Trace.SpanID().SetArray(spanContext.SpanID())
}
if spanContext.IsSampled() {
bundle.Trace.Flags().SetArray([1]byte{1})
}
if spanContext.TraceState().Len() != 0 {
bundle.State.SetString(spanContext.TraceState().String())
}
parentIndex, hasParent := lookupParent(x.id2Index, span)
var xopParent *datum
if hasParent {
parentContext := x.spans[parentIndex].SpanContext()
xopParent = x.data[parentIndex]
if parentContext.HasTraceID() {
bundle.Parent.TraceID().SetArray(parentContext.TraceID())
if bundle.Trace.TraceID().IsZero() {
bundle.Trace.TraceID().Set(bundle.Parent.GetTraceID())
}
}
if parentContext.HasSpanID() {
bundle.Parent.SpanID().SetArray(parentContext.SpanID())
}
if parentContext.IsSampled() {
bundle.Parent.Flags().SetArray([1]byte{1})
}
} else if span.Parent().HasTraceID() {
bundle.Parent.TraceID().SetArray(span.Parent().TraceID())
if span.Parent().HasSpanID() {
bundle.Parent.SpanID().SetArray(span.Parent().SpanID())
}
if span.Parent().IsSampled() {
bundle.Parent.Flags().SetArray([1]byte{1})
}
}
var downStreamError gwrap.AtomicValue[error]
errorReporter := func(err error) {
if err != nil {
downStreamError.Store(err)
}
}
bundle.Parent.Flags().SetBytes([]byte{1})
bundle.Trace.Flags().SetBytes([]byte{1})
spanKind := span.SpanKind()
attributeMap := mapAttributes(span.Attributes())
if b := attributeMap.GetString(xopBaggage); b != "" {
bundle.Baggage.SetString(b)
}
if spanKind == oteltrace.SpanKindUnspecified {
spanKind = oteltrace.SpanKind(defaulted(attributeMap.GetInt(otelSpanKind), int64(oteltrace.SpanKindUnspecified)))
}
if attributeMap.GetBool(spanIsLinkEventKey) {
// span is extra just for link
return func() {}, nil
}
switch spanKind {
case oteltrace.SpanKindUnspecified, oteltrace.SpanKindInternal:
if hasParent {
spanSeq := defaulted(attributeMap.GetString(xopSpanSequence), "")
data.xopSpan = xopParent.xopSpan
data.baseSpan = xopParent.baseSpan.Span(ctx, span.StartTime(), bundle, span.Name(), spanSeq)
data.requestIndex = xopParent.requestIndex
data.attributeDefinitions = xopParent.attributeDefinitions
data.registry = xopParent.registry
} else {
// This is a difficult sitatuion. We have an internal/unspecified span
// that does not have a parent present. There is no right answer for what
// to do. In the Xop world, such a span isn't allowed to exist. We'll treat
// this span as a request, but mark it as promoted.
data.xopSpan = attributeMap.GetString(xopVersion) != ""
baseRequest := x.base.Request(ctx, span.StartTime(), bundle, span.Name(), buildSourceInfo(span, attributeMap))
baseRequest.SetErrorReporter(errorReporter)
data.baseSpan = baseRequest
data.baseSpan.MetadataBool(xopPromotedMetadata, true)
data.requestIndex = myIndex
data.attributeDefinitions = make(map[string]*decodeAttributeDefinition)
data.registry = xopat.NewRegistry(false)
}
default:
baseRequest := x.base.Request(ctx, span.StartTime(), bundle, span.Name(), buildSourceInfo(span, attributeMap))
baseRequest.SetErrorReporter(errorReporter)
data.baseSpan = baseRequest
data.requestIndex = myIndex
data.attributeDefinitions = make(map[string]*decodeAttributeDefinition)
data.xopSpan = attributeMap.GetString(xopVersion) != ""
data.registry = xopat.NewRegistry(false)
if !data.xopSpan {
data.baseSpan.MetadataAny(otelReplayStuff, xopbase.ModelArg{
Model: &otelStuff{
SpanKind: xopconst.SpanKindEnum(span.SpanKind()),
Status: span.Status(),
Resource: bufferedResource{span.Resource()},
InstrumentationScope: span.InstrumentationScope(),
spanCounters: spanCounters{
DroppedAttributes: span.DroppedAttributes(),
DroppedLinks: span.DroppedLinks(),
DroppedEvents: span.DroppedEvents(),
ChildSpanCount: span.ChildSpanCount(),
},
},
})
}
}
y := baseSpanReplay{
spanReplay: x,
span: span,
datum: data,
}
for _, attribute := range span.Attributes() {
err := y.AddSpanAttribute(ctx, attribute)
if err != nil {
return func() {}, err
}
}
var maxNumber int32
for _, event := range span.Events() {
lastNumber, err := y.AddEvent(ctx, event)
if err != nil {
return func() {}, err
}
if lastNumber > maxNumber {
maxNumber = lastNumber
}
}
for _, link := range span.Links() {
if !data.xopSpan {
z := lineAttributesReplay{
baseSpanReplay: y,
lineType: lineTypeLink,
lineFormat: lineFormatDefault,
level: xopnum.InfoLevel,
}
line, err := z.AddLineAttributes(ctx, "link", span.StartTime(), link.Attributes)
if err != nil {
return func() {}, err
}
var trace xoptrace.Trace
trace.Flags().SetArray([1]byte{byte(link.SpanContext.TraceFlags())})
trace.TraceID().SetArray(link.SpanContext.TraceID())
trace.SpanID().SetArray(link.SpanContext.SpanID())
data.baseSpan.MetadataLink(otelLink, trace)
z.link = trace
if ts := link.SpanContext.TraceState(); ts.Len() != 0 {
line.String(xopOTELLinkTranceState, ts.String(), xopbase.StringDataType)
}
if link.SpanContext.IsRemote() {
line.Bool(xopOTELLinkIsRemote, true)
}
if link.DroppedAttributeCount != 0 {
line.Int64(xopOTELLinkDroppedAttributeCount, int64(link.DroppedAttributeCount), xopbase.IntDataType)
}
err = z.finishLine(ctx, "link", xopOTELLinkDetail.String(), line)
if err != nil {
return func() {}, err
}
}
}
if endTime := span.EndTime(); !endTime.IsZero() {
return func() {
data.baseSpan.Done(endTime, true)
}, nil
}
return func() {}, downStreamError.Load()
}
type lineType int
const (
lineTypeLine lineType = iota
lineTypeLink
lineTypeLinkEvent
lineTypeModel
)
type lineFormat int
const (
lineFormatDefault lineFormat = iota
lineFormatTemplate
)
var lineRE = regexp.MustCompile(`^(.+):(\d+)$`)
func (x baseSpanReplay) AddEvent(ctx context.Context, event sdktrace.Event) (int32, error) {
z := lineAttributesReplay{
baseSpanReplay: x,
lineType: lineTypeLine,
lineFormat: lineFormatDefault,
level: xopnum.InfoLevel,
}
line, err := z.AddLineAttributes(ctx, "event", event.Time, event.Attributes)
if err != nil {
return 0, err
}
err = z.finishLine(ctx, "event", event.Name, line)
return z.lineNumber, err
}
type lineAttributesReplay struct {
baseSpanReplay
lineType lineType
lineFormat lineFormat
template string
link xoptrace.Trace
modelArg xopbase.ModelArg
frames []runtime.Frame
lineNumber int32
level xopnum.Level
}
func (x *lineAttributesReplay) AddLineAttributes(ctx context.Context, what string, ts time.Time, attributes []attribute.KeyValue) (xopbase.Line, error) {
x.sequenceNumber++
x.lineNumber = x.sequenceNumber
nonSpecial := make([]attribute.KeyValue, 0, len(attributes))
for _, a := range attributes {
switch a.Key {
case xopLineNumber:
if a.Value.Type() == attribute.INT64 {
x.lineNumber = int32(a.Value.AsInt64())
} else {
return nil, errors.Errorf("invalid line number attribute type %s", a.Value.Type())
}
case xopLevel:
if a.Value.Type() == attribute.STRING {
var err error
x.level, err = xopnum.LevelString(a.Value.AsString())
if err != nil {
x.level = xopnum.InfoLevel
}
} else {
return nil, errors.Errorf("invalid line level attribute type %s", a.Value.Type())
}
case xopType:
if a.Value.Type() == attribute.STRING {
switch a.Value.AsString() {
case "link":
x.lineType = lineTypeLink
case "link-event":
x.lineType = lineTypeLinkEvent
case "model":
x.lineType = lineTypeModel
case "line":
// defaulted
default:
return nil, errors.Errorf("invalid line type attribute value %s", a.Value.AsString())
}
} else {
return nil, errors.Errorf("invalid line type attribute type %s", a.Value.Type())
}
case xopModelType:
if a.Value.Type() == attribute.STRING {
x.modelArg.ModelType = a.Value.AsString()
} else {
return nil, errors.Errorf("invalid model type attribute type %s", a.Value.Type())
}
case xopEncoding:
if a.Value.Type() == attribute.STRING {
e, ok := xopproto.Encoding_value[a.Value.AsString()]
if !ok {
return nil, errors.Errorf("invalid model encoding '%s'", a.Value.AsString())
}
x.modelArg.Encoding = xopproto.Encoding(e)
} else {
return nil, errors.Errorf("invalid model encoding attribute type %s", a.Value.Type())
}
case xopModel:
if a.Value.Type() == attribute.STRING {
x.modelArg.Encoded = []byte(a.Value.AsString())
} else {
return nil, errors.Errorf("invalid model encoding attribute type %s", a.Value.Type())
}
case xopTemplate:
if a.Value.Type() == attribute.STRING {
x.lineFormat = lineFormatTemplate
x.template = a.Value.AsString()
} else {
return nil, errors.Errorf("invalid line template attribute type %s", a.Value.Type())
}
case xopLinkData:
if a.Value.Type() == attribute.STRING {
var ok bool
x.link, ok = xoptrace.TraceFromString(a.Value.AsString())
if !ok {
return nil, errors.Errorf("invalid link data attribute value %s", a.Value.AsString())
}
} else {
return nil, errors.Errorf("invalid link data attribute type %s", a.Value.Type())
}
case xopStackTrace:
if a.Value.Type() == attribute.STRINGSLICE {
raw := a.Value.AsStringSlice()
x.frames = make([]runtime.Frame, len(raw))
for i, s := range raw {
m := lineRE.FindStringSubmatch(s)
if m == nil {
return nil, errors.Errorf("could not match stack line '%s'", s)
}
x.frames[i].File = m[1]
num, _ := strconv.ParseInt(m[2], 10, 64)
x.frames[i].Line = int(num)
}
} else {
return nil, errors.Errorf("invalid stack trace attribute type %s", a.Value.Type())
}
default:
nonSpecial = append(nonSpecial, a)
}
}
line := x.baseSpan.NoPrefill().Line(
x.level,
ts,
x.frames,
)
for _, a := range nonSpecial {
if x.xopSpan {
err := x.AddXopEventAttribute(ctx, a, line)
if err != nil {
return nil, errors.Wrapf(err, "add xop %s attribute %s", what, string(a.Key))
}
} else {
err := x.AddEventAttribute(ctx, a, line)
if err != nil {
return nil, errors.Wrapf(err, "add %s attribute %s with type %s", what, string(a.Key), a.Value.Type())
}
}
}
return line, nil
}
func (x lineAttributesReplay) finishLine(ctx context.Context, what string, name string, line xopbase.Line) error {
switch x.lineType {
case lineTypeLine:
switch x.lineFormat {
case lineFormatDefault:
x.addOrdered(x.lineNumber, func() {
line.Msg(name)
})
case lineFormatTemplate:
x.addOrdered(x.lineNumber, func() {
line.Template(x.template)
})
default:
return errors.Errorf("unexpected lineType %d", x.lineType)
}
case lineTypeLink:
x.addOrdered(x.lineNumber, func() {
line.Link(name, x.link)
})
case lineTypeLinkEvent:
return errors.Errorf("unexpected lineType: link event")
case lineTypeModel:
x.addOrdered(x.lineNumber, func() {
line.Model(name, x.modelArg)
})
default:
return errors.Errorf("unexpected lineType %d", x.lineType)
}
return nil
}
func (e *spanExporter) Shutdown(ctx context.Context) error {
atomic.StoreInt32(&e.done, 1)
return nil
}
type unhack struct {
next sdktrace.SpanExporter
}
// NewUnhacker wraps a SpanExporter and if the input is from BaseLogger or SpanLog,
// then it "fixes" the data hack in the output that puts inter-span links in sub-spans
// rather than in the span that defined them.
func NewUnhacker(exporter sdktrace.SpanExporter) sdktrace.SpanExporter {
return &unhack{next: exporter}
}
func (u *unhack) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
// TODO: fix up SpanKind if spanKind is one of the attributes
id2Index := makeIndex(spans)
subLinks := make([][]sdktrace.Link, len(spans))
for i, span := range spans {
parentIndex, ok := lookupParent(id2Index, span)
if !ok {
continue
}
var addToParent bool
for _, attribute := range span.Attributes() {
switch attribute.Key {
case spanIsLinkAttributeKey, spanIsLinkEventKey:
spans[i] = nil
addToParent = true
}
}
if !addToParent {
continue
}
subLinks[parentIndex] = append(subLinks[parentIndex], span.Links()...)
}
n := make([]sdktrace.ReadOnlySpan, 0, len(spans))
for i, span := range spans {
span := span
switch {
case len(subLinks[i]) > 0:
n = append(n, wrappedReadOnlySpan{
ReadOnlySpan: span,
links: append(list.Copy(span.Links()), subLinks[i]...),
})
case span == nil:
// skip
default:
n = append(n, span)
}
}
return u.next.ExportSpans(ctx, n)
}
func (u *unhack) Shutdown(ctx context.Context) error {
return u.next.Shutdown(ctx)
}
var _ sdktrace.ReadOnlySpan = wrappedReadOnlySpan{}
func (w wrappedReadOnlySpan) Links() []sdktrace.Link {
return w.links
}
func makeIndex(spans []sdktrace.ReadOnlySpan) map[oteltrace.SpanID]int {
id2Index := make(map[oteltrace.SpanID]int)
for i, span := range spans {
spanContext := span.SpanContext()
if spanContext.HasSpanID() {
id2Index[spanContext.SpanID()] = i
}
}
return id2Index
}
func lookupParent(id2Index map[oteltrace.SpanID]int, span sdktrace.ReadOnlySpan) (int, bool) {
parent := span.Parent()
if !parent.HasSpanID() {
return 0, false
}
parentIndex, ok := id2Index[parent.SpanID()]
if !ok {
return 0, false
}
return parentIndex, true
}
// makeSubspans figures out what subspans each span has and also which spans
// have no parent span (and thus are not a subspan). We are assuming that there
// are no cycles in the graph of spans & subspans. UNSAFE
func makeSubspans(id2Index map[oteltrace.SpanID]int, spans []sdktrace.ReadOnlySpan) ([][]int, []int) {
ss := make([][]int, len(spans))
noParent := make([]int, 0, len(spans))
for i, span := range spans {
parentIndex, ok := lookupParent(id2Index, span)
if !ok {
noParent = append(noParent, i)
continue
}
ss[parentIndex] = append(ss[parentIndex], i)
}
return ss, noParent
}
func buildSourceInfo(span sdktrace.ReadOnlySpan, attributeMap aMap) xopbase.SourceInfo {
var si xopbase.SourceInfo
var source string
var namespace string
if attributeMap.GetString(xopVersion) == "" {
// span did not come from XOP
source = otelDataSource
namespace = span.SpanKind().String()
} else {
if s := attributeMap.GetString(xopSource); s != "" {
source = s
} else if n := span.InstrumentationScope().Name; n != "" {
if v := span.InstrumentationScope().Version; v != "" {
source = n + " " + v
} else {
source = n
}
} else {
source = "OTEL"
}
namespace = defaulted(attributeMap.GetString(xopNamespace), source)
}
si.Source, si.SourceVersion = xopversion.SplitVersion(source)
si.Namespace, si.NamespaceVersion = xopversion.SplitVersion(namespace)
return si
}
type aMap struct {
strings map[attribute.Key]string
ints map[attribute.Key]int64
bools map[attribute.Key]bool
}
func mapAttributes(list []attribute.KeyValue) aMap {
m := aMap{
strings: make(map[attribute.Key]string),
ints: make(map[attribute.Key]int64),
bools: make(map[attribute.Key]bool),
}
for _, a := range list {
switch a.Value.Type() {
case attribute.STRING:
m.strings[a.Key] = a.Value.AsString()
case attribute.INT64:
m.ints[a.Key] = a.Value.AsInt64()
case attribute.BOOL:
m.bools[a.Key] = a.Value.AsBool()
}
}
return m
}
func (m aMap) GetString(k attribute.Key) string { return m.strings[k] }
func (m aMap) GetInt(k attribute.Key) int64 { return m.ints[k] }
func (m aMap) GetBool(k attribute.Key) bool { return m.bools[k] }
func defaulted[T comparable](a, b T) T {
var zero T
if a == zero {
return b
}
return a
}
func (x baseSpanReplay) AddXopEventAttribute(ctx context.Context, a attribute.KeyValue, line xopbase.Line) error {
switch a.Value.Type() {
case attribute.STRINGSLICE:
slice := a.Value.AsStringSlice()
if len(slice) < 2 {
return errors.Errorf("invalid xop attribute encoding slice is too short")
}
switch slice[1] {
// MACRO DataTypeAbbreviations
case "ZZZ":
// CONDITIONAL ONLY:i,i8,i16,i32,i64
i, err := strconv.ParseInt(slice[0], 10, 64)
if err != nil {
return errors.Wrapf(err, "key %s invalid %s", a.Key, slice[1])
}
line.zzz(xopat.K(a.Key), i, xopbase.StringToDataType["ZZZ"])
// CONDITIONAL ONLY:u,u8,u16,u32,u64,uintptr
i, err := strconv.ParseUint(slice[0], 10, 64)
if err != nil {
return errors.Wrapf(err, "key %s invalid %s", a.Key, slice[1])
}
line.zzz(xopat.K(a.Key), i, xopbase.StringToDataType["ZZZ"])
// CONDITIONAL ONLY:s,stringer,error
line.zzz(xopat.K(a.Key), slice[0], xopbase.StringToDataType["ZZZ"])
// CONDITIONAL ONLY:dur
dur, err := time.ParseDuration(slice[0])
if err != nil {
return errors.Wrapf(err, "key %s invalid %s", a.Key, slice[1])
}
line.zzz(xopat.K(a.Key), dur)
// CONDITIONAL ONLY:f32,f64
f, err := strconv.ParseFloat(slice[0], 64)
if err != nil {
return errors.Wrapf(err, "key %s invalid %s", a.Key, slice[1])
}
line.zzz(xopat.K(a.Key), f, xopbase.StringToDataType["ZZZ"])
// CONDITIONAL ONLY:time
ts, err := time.Parse(time.RFC3339Nano, slice[0])
if err != nil {
return errors.Wrapf(err, "key %s invalid %s", a.Key, slice[1])
}
line.zzz(xopat.K(a.Key), ts)
// CONDITIONAL ONLY:enum
if len(slice) != 3 {
return errors.Errorf("key %s invalid enum encoding, slice too short", a.Key)
}
ea, err := x.registry.ConstructEnumAttribute(xopat.Make{
Key: string(a.Key),
}, xopat.AttributeTypeEnum)
if err != nil {
return errors.Errorf("could not turn key %s into an enum", a.Key)
}
i, err := strconv.ParseInt(slice[2], 10, 64)
if err != nil {
return errors.Wrapf(err, "could not turn key %s into an enum", a.Key)
}
enum := ea.Add64(i, slice[0])
line.Enum(&ea.EnumAttribute, enum)
// CONDITIONAL ONLY:any
if len(slice) != 4 {
return errors.Errorf("key %s invalid any encoding, slice too short", a.Key)
}
var ma xopbase.ModelArg
ma.Encoded = []byte(slice[0])
e, ok := xopproto.Encoding_value[slice[2]]
if !ok {
return errors.Errorf("invalid model encoding '%s'", a.Value.AsString())
}
ma.Encoding = xopproto.Encoding(e)
ma.ModelType = slice[3]
line.zzz(xopat.K(a.Key), ma)
// END CONDITIONAL
}
case attribute.BOOL:
line.Bool(xopat.K(a.Key), a.Value.AsBool())
default:
return errors.Errorf("unexpected event attribute type %s for xop-encoded line", a.Value.Type())
}
return nil
}
func (x baseSpanReplay) AddEventAttribute(ctx context.Context, a attribute.KeyValue, line xopbase.Line) error {
switch a.Value.Type() {
// MACRO OTELTypes
case attribute.ZZZ:
// CONDITIONAL SKIP:BOOL
line.Zzz(xopat.K(a.Key), a.Value.AsZzz(), xopbase.ZzzDataType)
// ELSE CONDITIONAL
line.Bool(xopat.K(a.Key), a.Value.AsZzz())
// END CONDITIONAL
case attribute.ZZZSLICE:
var ma xopbase.ModelArg
ma.Model = a.Value.AsZzzSlice()
ma.ModelType = toTypeSliceName["ZZZ"]
line.Any(xopat.K(a.Key), ma)
case attribute.INVALID:
fallthrough
default:
return errors.Errorf("invalid type")
}
return nil
}
var toTypeSliceName = map[string]string{
"BOOL": "[]bool",
"STRING": "[]string",
"INT64": "[]int64",
"FLOAT64": "[]float64",
}
func (x baseSpanReplay) AddSpanAttribute(ctx context.Context, a attribute.KeyValue) (err error) {
switch a.Key {
case spanIsLinkAttributeKey,
spanIsLinkEventKey,
xopSource,
xopNamespace,
xopBaggage,
xopSpanSequence,
xopType,
otelSpanKind:
// special cases handled elsewhere
return nil
case xopVersion,
xopOTELVersion:
// dropped
return nil
}
key := string(a.Key)
defer func() {
if err != nil {
err = errors.Wrapf(err, "add span attribute %s with type %s", key, a.Value.Type())
}
}()
if strings.HasPrefix(key, attributeDefinitionPrefix) {
key := strings.TrimPrefix(key, attributeDefinitionPrefix)
if _, ok := x.data[x.requestIndex].attributeDefinitions[key]; ok {
return nil
}
if a.Value.Type() != attribute.STRING {
return errors.Errorf("expected type to be string")
}
var aDef decodeAttributeDefinition
err := json.Unmarshal([]byte(a.Value.AsString()), &aDef)
if err != nil {
return errors.Wrapf(err, "could not unmarshal attribute defintion")
}
x.data[x.requestIndex].attributeDefinitions[key] = &aDef
return nil
}
if aDef, ok := x.data[x.requestIndex].attributeDefinitions[key]; ok {
return x.AddXopMetadataAttribute(ctx, a, aDef)
}
if x.xopSpan {
return errors.Errorf("missing attribute defintion for key %s in xop span", key)
}
mkMake := func(key string, multiple bool) xopat.Make {
return xopat.Make{
Description: xopSynthesizedForOTEL,
Key: key,
Multiple: multiple,
}
}
switch a.Value.Type() {
// MACRO OTELTypes
case attribute.ZZZ:
registeredAttribute, err := x.registry.ConstructZzzAttribute(mkMake(key, false), xopat.AttributeTypeZzz)
if err != nil {
return err
}
x.baseSpan.MetadataZzz(registeredAttribute, a.Value.AsZzz())
case attribute.ZZZSLICE:
registeredAttribute, err := x.registry.ConstructZzzAttribute(mkMake(key, true), xopat.AttributeTypeZzz)
if err != nil {
return err
}
for _, v := range a.Value.AsZzzSlice() {
x.baseSpan.MetadataZzz(registeredAttribute, v)
}
case attribute.INVALID:
fallthrough
default:
return errors.Errorf("span attribute key (%s) has value type (%s) that is not expected", key, a.Value.Type())
}
return nil
}
func (x baseSpanReplay) AddXopMetadataAttribute(ctx context.Context, a attribute.KeyValue, aDef *decodeAttributeDefinition) error {
switch aDef.AttributeType {
// MACRO ZZZAttribute
case xopproto.AttributeType_ZZZ:
registeredAttribute, err := x.registry.ConstructZZZAttribute(aDef.Make, xopat.AttributeType(aDef.AttributeType))
if err != nil {
return err
}
// CONDITIONAL ONLY:Enum,Time,String,Any,Link,Duration
expectedSingleType, expectedMultiType := attribute.STRING, attribute.STRINGSLICE
// CONDITIONAL ONLY:Int64,Int,Int8,Int16,Int32
expectedSingleType, expectedMultiType := attribute.INT64, attribute.INT64SLICE
// CONDITIONAL ONLY:Bool
expectedSingleType, expectedMultiType := attribute.BOOL, attribute.BOOLSLICE
// CONDITIONAL ONLY:Float64
expectedSingleType, expectedMultiType := attribute.FLOAT64, attribute.FLOAT64SLICE
// END CONDITIONAL
expectedType := expectedSingleType
if registeredAttribute.Multiple() {
expectedType = expectedMultiType
}
if a.Value.Type() != expectedType {
return errors.Errorf("expected type %s", expectedMultiType)
}
// CONDITIONAL ONLY:String,Int64,Float64,Bool
setter := func(v zzz) error {
x.baseSpan.MetadataZZZ(registeredAttribute, v)
return nil
}
// CONDITIONAL ONLY:Int,Int8,Int16,Int32
setter := func(v int64) error {
x.baseSpan.MetadataInt64(®isteredAttribute.Int64Attribute, int64(v))
return nil
}
// CONDITIONAL ONLY:Duration
setter := func(v string) error {
d, err := time.ParseDuration(v)
if err != nil {
return err
}
x.baseSpan.MetadataInt64(®isteredAttribute.Int64Attribute, int64(d))
return nil
}
// CONDITIONAL ONLY:Time
setter := func(v string) error {
t, err := time.Parse(time.RFC3339Nano, v)
if err != nil {
return err
}
x.baseSpan.MetadataZZZ(registeredAttribute, t)
return nil
}
// CONDITIONAL ONLY:Enum
setter := func(v string) error {
i := strings.LastIndexByte(v, '/')
if i == -1 {
return errors.Errorf("invalid enum %s", v)
}
if i == len(v)-1 {
return errors.Errorf("invalid enum %s", v)
}
vi, err := strconv.ParseInt(v[i+1:], 10, 64)
if err != nil {
return errors.Wrap(err, "invalid enum")
}
enum := registeredAttribute.Add64(vi, v[:i])
x.baseSpan.MetadataEnum(®isteredAttribute.EnumAttribute, enum)
return nil
}
// CONDITIONAL ONLY:Any
setter := func(v string) error {
var ma xopbase.ModelArg
err := ma.UnmarshalJSON([]byte(v))
if err != nil {
return err
}
x.baseSpan.MetadataAny(registeredAttribute, ma)
return nil
}
// CONDITIONAL ONLY:Link
setter := func(v string) error {
t, ok := xoptrace.TraceFromString(v)
if !ok {
return errors.Errorf("invalid trace string %s", v)
}
x.baseSpan.MetadataLink(registeredAttribute, t)
return nil
}
// END CONDITIONAL
if registeredAttribute.Multiple() {
// CONDITIONAL ONLY:Enum,Time,Any,Link,Duration
values := a.Value.AsStringSlice()
// CONDITIONAL ONLY:Bool,Int64,String,Float64
values := a.Value.AsZZZSlice()
// CONDITIONAL ONLY:Int,Int8,Int16,Int32
values := a.Value.AsInt64Slice()
// END CONDITIONAL
for _, value := range values {
err := setter(value)
if err != nil {
return err
}
}
} else {
// CONDITIONAL ONLY:Enum,Time,Any,Link,Duration
value := a.Value.AsString()
// CONDITIONAL ONLY:Bool,Int64,String,Float64
value := a.Value.AsZZZ()
// CONDITIONAL ONLY:Int,Int8,Int16,Int32
value := a.Value.AsInt64()
// END CONDITIONAL
err := setter(value)
if err != nil {
return err
}
}
default: