-
Notifications
You must be signed in to change notification settings - Fork 27
/
traces.go
1454 lines (1344 loc) · 41.7 KB
/
traces.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.
// Portions copied from OpenTelemetry Collector (contrib), from the
// elastic exporter.
//
// Copyright 2020, OpenTelemetry Authors
//
// Licensed 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 otlp
import (
"context"
"encoding/hex"
"fmt"
"math"
"net"
"net/url"
"slices"
"strconv"
"strings"
"time"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
semconv "go.opentelemetry.io/collector/semconv/v1.5.0"
"google.golang.org/grpc/codes"
"github.com/elastic/apm-data/model/modelpb"
)
const (
keywordLength = 1024
dot = "."
underscore = "_"
outcomeSuccess = "success"
outcomeFailure = "failure"
outcomeUnknown = "unknown"
attributeNetworkConnectionType = "network.connection.type"
attributeNetworkConnectionSubtype = "network.connection.subtype"
attributeNetworkMCC = "network.carrier.mcc"
attributeNetworkMNC = "network.carrier.mnc"
attributeNetworkCarrierName = "network.carrier.name"
attributeNetworkICC = "network.carrier.icc"
attributeHttpRequestMethod = "http.request.method"
attributeHttpResponseStatusCode = "http.response.status_code"
attributeServerAddress = "server.address"
attributeServerPort = "server.port"
attributeUrlFull = "url.full"
attributeUrlScheme = "url.scheme"
attributeUrlPath = "url.path"
attributeUrlQuery = "url.query"
attributeUserAgentOriginal = "user_agent.original"
attributeDbElasticsearchClusterName = "db.elasticsearch.cluster.name"
attributeStackTrace = "code.stacktrace" // semconv 1.24 or later
attributeDataStreamDataset = "data_stream.dataset"
attributeDataStreamNamespace = "data_stream.namespace"
)
// ConsumeTracesResult contains the number of rejected spans and error message for partial success response.
type ConsumeTracesResult struct {
ErrorMessage string
RejectedSpans int64
}
// ConsumeTraces calls ConsumeTracesWithResult but ignores the result.
// It exists to satisfy the go.opentelemetry.io/collector/consumer.Traces interface.
func (c *Consumer) ConsumeTraces(ctx context.Context, traces ptrace.Traces) error {
_, err := c.ConsumeTracesWithResult(ctx, traces)
return err
}
// ConsumeTracesWithResult consumes OpenTelemetry trace data,
// converting into Elastic APM events and reporting to the Elastic APM schema.
func (c *Consumer) ConsumeTracesWithResult(ctx context.Context, traces ptrace.Traces) (ConsumeTracesResult, error) {
if err := semAcquire(ctx, c.sem, 1); err != nil {
return ConsumeTracesResult{}, err
}
defer c.sem.Release(1)
receiveTimestamp := time.Now()
resourceSpans := traces.ResourceSpans()
batch := make(modelpb.Batch, 0, resourceSpans.Len())
for i := 0; i < resourceSpans.Len(); i++ {
c.convertResourceSpans(resourceSpans.At(i), receiveTimestamp, &batch)
}
if err := c.config.Processor.ProcessBatch(ctx, &batch); err != nil {
return ConsumeTracesResult{}, err
}
return ConsumeTracesResult{RejectedSpans: 0}, nil
}
func (c *Consumer) convertResourceSpans(
resourceSpans ptrace.ResourceSpans,
receiveTimestamp time.Time,
out *modelpb.Batch,
) {
baseEvent := modelpb.APMEvent{}
baseEvent.Event = &modelpb.Event{}
baseEvent.Event.Received = modelpb.FromTime(receiveTimestamp)
var timeDelta time.Duration
resource := resourceSpans.Resource()
translateResourceMetadata(resource, &baseEvent)
if exportTimestamp, ok := exportTimestamp(resource); ok {
timeDelta = receiveTimestamp.Sub(exportTimestamp)
}
scopeSpans := resourceSpans.ScopeSpans()
for i := 0; i < scopeSpans.Len(); i++ {
c.convertScopeSpans(scopeSpans.At(i), &baseEvent, timeDelta, out)
}
}
func (c *Consumer) convertScopeSpans(
in ptrace.ScopeSpans,
baseEvent *modelpb.APMEvent,
timeDelta time.Duration,
out *modelpb.Batch,
) {
otelSpans := in.Spans()
for i := 0; i < otelSpans.Len(); i++ {
c.convertSpan(otelSpans.At(i), in.Scope(), baseEvent, timeDelta, out)
}
}
func (c *Consumer) convertSpan(
otelSpan ptrace.Span,
otelLibrary pcommon.InstrumentationScope,
baseEvent *modelpb.APMEvent,
timeDelta time.Duration,
out *modelpb.Batch,
) {
root := otelSpan.ParentSpanID().IsEmpty()
var parentID string
if !root {
parentID = hexSpanID(otelSpan.ParentSpanID())
}
startTime := otelSpan.StartTimestamp().AsTime()
endTime := otelSpan.EndTimestamp().AsTime()
duration := endTime.Sub(startTime)
// Message consumption results in either a transaction or a span based
// on whether the consumption is active or passive. Otel spans
// currently do not have the metadata to make this distinction. For
// now, we assume that the majority of consumption is passive, and
// therefore start a transaction whenever span kind == consumer.
name := otelSpan.Name()
spanID := hexSpanID(otelSpan.SpanID())
representativeCount := getRepresentativeCountFromTracestateHeader(otelSpan.TraceState().AsRaw())
event := baseEvent.CloneVT()
translateScopeMetadata(otelLibrary, event)
initEventLabels(event)
event.Timestamp = modelpb.FromTime(startTime.Add(timeDelta))
if id := hexTraceID(otelSpan.TraceID()); id != "" {
event.Trace = &modelpb.Trace{}
event.Trace.Id = id
}
if event.Event == nil {
event.Event = &modelpb.Event{}
}
event.Event.Duration = uint64(duration)
event.Event.Outcome = spanStatusOutcome(otelSpan.Status())
if parentID != "" {
event.ParentId = parentID
}
if root || otelSpan.Kind() == ptrace.SpanKindServer || otelSpan.Kind() == ptrace.SpanKindConsumer {
event.Transaction = &modelpb.Transaction{}
event.Transaction.Id = spanID
event.Transaction.Name = name
event.Transaction.Sampled = true
event.Transaction.RepresentativeCount = representativeCount
if spanID != "" {
event.Span = &modelpb.Span{}
event.Span.Id = spanID
}
TranslateTransaction(otelSpan.Attributes(), otelSpan.Status(), otelLibrary, event)
} else {
event.Span = &modelpb.Span{}
event.Span.Id = spanID
event.Span.Name = name
event.Span.RepresentativeCount = representativeCount
TranslateSpan(otelSpan.Kind(), otelSpan.Attributes(), event)
}
translateSpanLinks(event, otelSpan.Links())
if len(event.Labels) == 0 {
event.Labels = nil
}
if len(event.NumericLabels) == 0 {
event.NumericLabels = nil
}
*out = append(*out, event)
events := otelSpan.Events()
event = event.CloneVT()
event.Labels = baseEvent.Labels // only copy common labels to span events
event.NumericLabels = baseEvent.NumericLabels // only copy common labels to span events
event.Event = &modelpb.Event{}
event.Event.Received = baseEvent.Event.Received // only copy event.received to span events
event.Destination = nil // don't set destination for span events
for i := 0; i < events.Len(); i++ {
*out = append(*out, c.convertSpanEvent(events.At(i), event, timeDelta))
}
}
// TranslateTransaction converts incoming otlp/otel trace data into the
// expected elasticsearch format.
func TranslateTransaction(
attributes pcommon.Map,
spanStatus ptrace.Status,
library pcommon.InstrumentationScope,
event *modelpb.APMEvent,
) {
isJaeger := strings.HasPrefix(event.Agent.Name, "Jaeger")
var (
netHostName string
netHostPort int
)
var (
httpScheme string
httpURL string
httpServerName string
httpHost string
http modelpb.HTTP
httpRequest modelpb.HTTPRequest
httpResponse modelpb.HTTPResponse
urlPath string
urlQuery string
)
var isHTTP, isRPC, isMessaging bool
var messagingQueueName string
var samplerType, samplerParam pcommon.Value
attributes.Range(func(kDots string, v pcommon.Value) bool {
if isJaeger {
switch kDots {
case "sampler.type":
samplerType = v
return true
case "sampler.param":
samplerParam = v
return true
}
}
k := replaceDots(kDots)
switch v.Type() {
case pcommon.ValueTypeSlice:
switch kDots {
case "elastic.profiler_stack_trace_ids":
var vSlice = v.Slice()
event.Transaction.ProfilerStackTraceIds = slices.Grow(event.Transaction.ProfilerStackTraceIds, vSlice.Len())
for i := 0; i < vSlice.Len(); i++ {
var idVal = vSlice.At(i)
if idVal.Type() == pcommon.ValueTypeStr {
event.Transaction.ProfilerStackTraceIds = append(event.Transaction.ProfilerStackTraceIds, idVal.Str())
}
}
default:
setLabel(k, event, v)
}
case pcommon.ValueTypeInt:
switch kDots {
case semconv.AttributeHTTPStatusCode, attributeHttpResponseStatusCode:
isHTTP = true
httpResponse.StatusCode = uint32(v.Int())
http.Response = &httpResponse
case semconv.AttributeNetPeerPort:
if event.Source == nil {
event.Source = &modelpb.Source{}
}
event.Source.Port = uint32(v.Int())
case semconv.AttributeNetHostPort, attributeServerPort:
netHostPort = int(v.Int())
case semconv.AttributeRPCGRPCStatusCode:
isRPC = true
event.Transaction.Result = codes.Code(v.Int()).String()
default:
setLabel(k, event, v)
}
case pcommon.ValueTypeMap:
case pcommon.ValueTypeStr:
stringval := truncate(v.Str())
switch kDots {
// http.*
case semconv.AttributeHTTPMethod, attributeHttpRequestMethod:
isHTTP = true
httpRequest.Method = stringval
http.Request = &httpRequest
case semconv.AttributeHTTPURL, semconv.AttributeHTTPTarget, "http.path":
isHTTP = true
httpURL = stringval
case attributeUrlPath:
isHTTP = true
urlPath = stringval
case attributeUrlQuery:
isHTTP = true
urlQuery = stringval
case semconv.AttributeHTTPHost:
isHTTP = true
httpHost = stringval
case semconv.AttributeHTTPScheme, attributeUrlScheme:
isHTTP = true
httpScheme = stringval
case semconv.AttributeHTTPStatusCode, attributeHttpResponseStatusCode:
if intv, err := strconv.Atoi(stringval); err == nil {
isHTTP = true
httpResponse.StatusCode = uint32(intv)
http.Response = &httpResponse
}
case "http.protocol":
if !strings.HasPrefix(stringval, "HTTP/") {
// Unexpected, store in labels for debugging.
modelpb.Labels(event.Labels).Set(k, stringval)
break
}
stringval = strings.TrimPrefix(stringval, "HTTP/")
fallthrough
case semconv.AttributeHTTPFlavor:
isHTTP = true
http.Version = stringval
case semconv.AttributeHTTPServerName:
isHTTP = true
httpServerName = stringval
case semconv.AttributeHTTPClientIP:
if ip, err := modelpb.ParseIP(stringval); err == nil {
if event.Client == nil {
event.Client = &modelpb.Client{}
}
event.Client.Ip = ip
}
case semconv.AttributeHTTPUserAgent, attributeUserAgentOriginal:
if event.UserAgent == nil {
event.UserAgent = &modelpb.UserAgent{}
}
event.UserAgent.Original = stringval
// net.*
case semconv.AttributeNetPeerIP:
if event.Source == nil {
event.Source = &modelpb.Source{}
}
if ip, err := modelpb.ParseIP(stringval); err == nil {
event.Source.Ip = ip
}
case semconv.AttributeNetPeerName:
if event.Source == nil {
event.Source = &modelpb.Source{}
}
event.Source.Domain = stringval
case semconv.AttributeNetHostName, attributeServerAddress:
netHostName = stringval
case attributeNetworkConnectionType:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Connection == nil {
event.Network.Connection = &modelpb.NetworkConnection{}
}
event.Network.Connection.Type = stringval
case attributeNetworkConnectionSubtype:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Connection == nil {
event.Network.Connection = &modelpb.NetworkConnection{}
}
event.Network.Connection.Subtype = stringval
case attributeNetworkMCC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Mcc = stringval
case attributeNetworkMNC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Mnc = stringval
case attributeNetworkCarrierName:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Name = stringval
case attributeNetworkICC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Icc = stringval
// messaging.*
//
// messaging.destination is now called messaging.destination.name in the latest semconv
// https://opentelemetry.io/docs/specs/semconv/attributes-registry/messaging
// keep both of them for the backward compatibility
case "message_bus.destination", semconv.AttributeMessagingDestination, "messaging.destination.name":
isMessaging = true
messagingQueueName = stringval
case semconv.AttributeMessagingSystem:
isMessaging = true
modelpb.Labels(event.Labels).Set(k, stringval)
case semconv.AttributeMessagingOperation:
isMessaging = true
modelpb.Labels(event.Labels).Set(k, stringval)
// rpc.*
//
// TODO(axw) add RPC fieldset to ECS? Currently we drop these
// attributes, and rely on the operation name like we do with
// Elastic APM agents.
case semconv.AttributeRPCSystem:
isRPC = true
case semconv.AttributeRPCGRPCStatusCode:
isRPC = true
case semconv.AttributeRPCService:
case semconv.AttributeRPCMethod:
// miscellaneous
case "type":
event.Transaction.Type = stringval
case "session.id":
if event.Session == nil {
event.Session = &modelpb.Session{}
}
event.Session.Id = stringval
case semconv.AttributeServiceVersion:
// NOTE support for sending service.version as a span tag
// is deprecated, and will be removed in 8.0. Instrumentation
// should set this as a resource attribute (OTel) or tracer
// tag (Jaeger).
event.Service.Version = stringval
// data_stream.*
case attributeDataStreamDataset:
if event.DataStream == nil {
event.DataStream = &modelpb.DataStream{}
}
event.DataStream.Dataset = sanitizeDataStreamDataset(stringval)
case attributeDataStreamNamespace:
if event.DataStream == nil {
event.DataStream = &modelpb.DataStream{}
}
event.DataStream.Namespace = sanitizeDataStreamNamespace(stringval)
default:
modelpb.Labels(event.Labels).Set(k, stringval)
}
default:
setLabel(k, event, v)
}
return true
})
if event.Transaction.Type == "" {
switch {
case isMessaging:
event.Transaction.Type = "messaging"
case isHTTP, isRPC:
event.Transaction.Type = "request"
default:
event.Transaction.Type = "unknown"
}
}
if isHTTP {
if http.SizeVT() != 0 {
event.Http = &http
}
// Set outcome nad result from status code.
if statusCode := httpResponse.StatusCode; statusCode > 0 {
if event.Event.Outcome == outcomeUnknown {
event.Event.Outcome = serverHTTPStatusCodeOutcome(int(statusCode))
}
if event.Transaction.Result == "" {
event.Transaction.Result = httpStatusCodeResult(int(statusCode))
}
}
httpHost := httpHost
if httpHost == "" {
httpHost = httpServerName
if httpHost == "" {
httpHost = netHostName
if httpHost == "" {
httpHost = event.GetHost().GetHostname()
}
}
if httpHost != "" && netHostPort > 0 {
httpHost = net.JoinHostPort(httpHost, strconv.Itoa(netHostPort))
}
}
// Build a relative url from the UrlPath and UrlQuery.
httpURL := httpURL
if httpURL == "" && urlPath != "" {
httpURL = urlPath
if urlQuery != "" {
httpURL += "?" + urlQuery
}
}
// Build the modelpb.URL from http{URL,Host,Scheme}.
event.Url = modelpb.ParseURL(httpURL, httpHost, httpScheme)
}
if isMessaging {
// Overwrite existing event.Transaction.Message
event.Transaction.Message = nil
if messagingQueueName != "" {
event.Transaction.Message = &modelpb.Message{}
event.Transaction.Message.QueueName = messagingQueueName
}
}
if event.Client == nil && event.Source != nil {
event.Client = &modelpb.Client{}
event.Client.Ip = event.Source.Ip
event.Client.Port = event.Source.Port
event.Client.Domain = event.Source.Domain
}
if samplerType != (pcommon.Value{}) {
// The client has reported its sampling rate, so we can use it to extrapolate span metrics.
parseSamplerAttributes(samplerType, samplerParam, event)
}
if event.Transaction.Result == "" {
event.Transaction.Result = spanStatusResult(spanStatus)
}
// if outcome and result are still not assigned, assign success
if event.Event.Outcome == outcomeUnknown {
event.Event.Outcome = outcomeSuccess
if event.Transaction.Result == "" {
event.Transaction.Result = "Success"
}
}
}
// TranslateSpan converts incoming otlp/otel trace data into the
// expected elasticsearch format.
func TranslateSpan(spanKind ptrace.SpanKind, attributes pcommon.Map, event *modelpb.APMEvent) {
isJaeger := strings.HasPrefix(event.GetAgent().GetName(), "Jaeger")
var (
netPeerName string
netPeerIP string
netPeerPort int
)
var (
peerService string
peerAddress string
)
var (
httpURL string
httpHost string
httpTarget string
httpScheme = "http"
)
var (
messageSystem string
messageOperation string
messageTempDestination bool
)
var (
rpcSystem string
rpcService string
)
var http modelpb.HTTP
var httpRequest modelpb.HTTPRequest
var httpResponse modelpb.HTTPResponse
var message modelpb.Message
var db modelpb.DB
var destinationService modelpb.DestinationService
var serviceTarget modelpb.ServiceTarget
var isHTTP, isDatabase, isRPC, isMessaging bool
var samplerType, samplerParam pcommon.Value
attributes.Range(func(kDots string, v pcommon.Value) bool {
if isJaeger {
switch kDots {
case "sampler.type":
samplerType = v
return true
case "sampler.param":
samplerParam = v
return true
}
}
k := replaceDots(kDots)
switch v.Type() {
case pcommon.ValueTypeBool:
switch kDots {
case semconv.AttributeMessagingTempDestination:
messageTempDestination = v.Bool()
fallthrough
default:
setLabel(k, event, v)
}
case pcommon.ValueTypeInt:
switch kDots {
case "http.status_code", attributeHttpResponseStatusCode:
httpResponse.StatusCode = uint32(v.Int())
http.Response = &httpResponse
isHTTP = true
case semconv.AttributeNetPeerPort, "peer.port", attributeServerPort:
netPeerPort = int(v.Int())
case semconv.AttributeRPCGRPCStatusCode:
rpcSystem = "grpc"
isRPC = true
default:
setLabel(k, event, v)
}
case pcommon.ValueTypeStr:
stringval := truncate(v.Str())
switch kDots {
// http.*
case semconv.AttributeHTTPHost:
httpHost = stringval
isHTTP = true
case semconv.AttributeHTTPScheme:
httpScheme = stringval
isHTTP = true
case semconv.AttributeHTTPTarget:
httpTarget = stringval
isHTTP = true
case semconv.AttributeHTTPURL:
httpURL = stringval
isHTTP = true
case semconv.AttributeHTTPMethod, attributeHttpRequestMethod:
httpRequest.Method = stringval
http.Request = &httpRequest
isHTTP = true
// db.*
case "sql.query":
if db.Type == "" {
db.Type = "sql"
}
fallthrough
case semconv.AttributeDBStatement:
// Statement should not be truncated, use original string value.
db.Statement = v.Str()
isDatabase = true
case semconv.AttributeDBName, "db.instance", attributeDbElasticsearchClusterName:
db.Instance = stringval
isDatabase = true
case semconv.AttributeDBSystem, "db.type":
db.Type = stringval
isDatabase = true
case semconv.AttributeDBUser:
db.UserName = stringval
isDatabase = true
// net.*
case semconv.AttributeNetPeerName, "peer.hostname":
netPeerName = stringval
case semconv.AttributeNetPeerIP, "peer.ipv4", "peer.ipv6":
netPeerIP = stringval
case "peer.address":
peerAddress = stringval
case attributeNetworkConnectionType:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Connection == nil {
event.Network.Connection = &modelpb.NetworkConnection{}
}
event.Network.Connection.Type = stringval
case attributeNetworkConnectionSubtype:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Connection == nil {
event.Network.Connection = &modelpb.NetworkConnection{}
}
event.Network.Connection.Subtype = stringval
case attributeNetworkMCC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Mcc = stringval
case attributeNetworkMNC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Mnc = stringval
case attributeNetworkCarrierName:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Name = stringval
case attributeNetworkICC:
if event.Network == nil {
event.Network = &modelpb.Network{}
}
if event.Network.Carrier == nil {
event.Network.Carrier = &modelpb.NetworkCarrier{}
}
event.Network.Carrier.Icc = stringval
// server.*
case attributeServerAddress:
netPeerName = stringval
// session.*
case "session.id":
if event.Session == nil {
event.Session = &modelpb.Session{}
}
event.Session.Id = stringval
// messaging.*
//
// messaging.destination is now called messaging.destination.name in the latest semconv
// https://opentelemetry.io/docs/specs/semconv/attributes-registry/messaging
// keep both of them for the backward compatibility
case "message_bus.destination", semconv.AttributeMessagingDestination, "messaging.destination.name":
message.QueueName = stringval
isMessaging = true
case semconv.AttributeMessagingOperation:
messageOperation = stringval
isMessaging = true
case semconv.AttributeMessagingSystem:
messageSystem = stringval
isMessaging = true
// rpc.*
//
// TODO(axw) add RPC fieldset to ECS? Currently we drop these
// attributes, and rely on the operation name and span type/subtype
// like we do with Elastic APM agents.
case semconv.AttributeRPCSystem:
rpcSystem = stringval
isRPC = true
case semconv.AttributeRPCService:
rpcService = stringval
isRPC = true
case semconv.AttributeRPCGRPCStatusCode:
rpcSystem = "grpc"
isRPC = true
case semconv.AttributeRPCMethod:
// url.*
case attributeUrlFull:
httpURL = stringval
isHTTP = true
case attributeStackTrace:
if event.Code == nil {
event.Code = &modelpb.Code{}
}
// stacktrace is expected to be large thus un-truncated value is needed
event.Code.Stacktrace = v.Str()
// miscellaneous
case "span.kind": // filter out
case semconv.AttributePeerService:
peerService = stringval
// data_stream.*
case attributeDataStreamDataset:
if event.DataStream == nil {
event.DataStream = &modelpb.DataStream{}
}
event.DataStream.Dataset = sanitizeDataStreamDataset(stringval)
case attributeDataStreamNamespace:
if event.DataStream == nil {
event.DataStream = &modelpb.DataStream{}
}
event.DataStream.Namespace = sanitizeDataStreamNamespace(stringval)
default:
setLabel(k, event, v)
}
default:
setLabel(k, event, v)
}
return true
})
if netPeerName == "" && (!strings.ContainsRune(peerAddress, ':') || net.ParseIP(peerAddress) != nil) {
// peer.address is not necessarily a hostname
// or IP address; it could be something like
// a JDBC connection string or ip:port. Ignore
// values containing colons, except for IPv6.
netPeerName = peerAddress
}
destPort := netPeerPort
destAddr := netPeerName
if destAddr == "" {
destAddr = netPeerIP
}
var fullURL *url.URL
if httpURL != "" {
fullURL, _ = url.Parse(httpURL)
} else if httpTarget != "" {
// Build http.url from http.scheme, http.target, etc.
if u, err := url.Parse(httpTarget); err == nil {
fullURL = u
fullURL.Scheme = httpScheme
if httpHost == "" {
// Set host from net.peer.*
httpHost = destAddr
if destPort > 0 {
httpHost = net.JoinHostPort(httpHost, strconv.Itoa(destPort))
}
}
fullURL.Host = httpHost
httpURL = fullURL.String()
}
}
if fullURL != nil {
var port int
portString := fullURL.Port()
if portString != "" {
port, _ = strconv.Atoi(portString)
} else {
port = schemeDefaultPort(fullURL.Scheme)
}
// Set destination.{address,port} from the HTTP URL,
// replacing peer.* based values to ensure consistency.
destAddr = truncate(fullURL.Hostname())
if port > 0 {
destPort = port
}
}
serviceTarget.Name = peerService
destinationService.Name = peerService
destinationService.Resource = peerService
if peerAddress != "" {
destinationService.Resource = peerAddress
}
if isHTTP {
if httpResponse.StatusCode > 0 && event.Event.Outcome == outcomeUnknown {
event.Event.Outcome = clientHTTPStatusCodeOutcome(int(httpResponse.StatusCode))
}
if http.SizeVT() != 0 {
event.Http = &http
}
if event.Url == nil {
event.Url = &modelpb.URL{}
}
event.Url.Original = httpURL
}
if isDatabase {
event.Span.Db = &db
}
if isMessaging {
event.Span.Message = &message
}
switch {
case isDatabase:
event.Span.Type = "db"
event.Span.Subtype = db.Type
serviceTarget.Type = event.Span.Type
if event.Span.Subtype != "" {
serviceTarget.Type = event.Span.Subtype
if destinationService.Name == "" {
// For database requests, we currently just identify
// the destination service by db.system.
destinationService.Name = event.Span.Subtype
destinationService.Resource = event.Span.Subtype
}
}
if db.Instance != "" {
serviceTarget.Name = db.Instance
}
case isMessaging:
event.Span.Type = "messaging"
event.Span.Subtype = messageSystem
if messageOperation == "" && spanKind == ptrace.SpanKindProducer {
messageOperation = "send"
}
event.Span.Action = messageOperation
serviceTarget.Type = event.Span.Type
if event.Span.Subtype != "" {
serviceTarget.Type = event.Span.Subtype
if destinationService.Name == "" {
destinationService.Name = event.Span.Subtype
destinationService.Resource = event.Span.Subtype
}
}
if destinationService.Resource != "" && message.QueueName != "" {
destinationService.Resource += "/" + message.QueueName
}
if message.QueueName != "" && !messageTempDestination {
serviceTarget.Name = message.QueueName
}
case isRPC:
event.Span.Type = "external"
event.Span.Subtype = rpcSystem
serviceTarget.Type = event.Span.Type
if event.Span.Subtype != "" {
serviceTarget.Type = event.Span.Subtype
}
// Set destination.service.* from the peer address, unless peer.service was specified.
if destinationService.Name == "" {
destHostPort := net.JoinHostPort(destAddr, strconv.Itoa(destPort))
destinationService.Name = destHostPort
destinationService.Resource = destHostPort
}
if rpcService != "" {
serviceTarget.Name = rpcService
}
case isHTTP:
event.Span.Type = "external"
subtype := "http"
event.Span.Subtype = subtype
serviceTarget.Type = event.Span.Subtype
if fullURL != nil {
url := url.URL{Scheme: fullURL.Scheme, Host: fullURL.Host}
resource := url.Host
if destPort == schemeDefaultPort(url.Scheme) {
if fullURL.Port() != "" {
// Remove the default port from destination.service.name
url.Host = destAddr
} else {
// Add the default port to destination.service.resource
resource = fmt.Sprintf("%s:%d", resource, destPort)
}
}
serviceTarget.Name = resource
if destinationService.Name == "" {
destinationService.Name = url.String()
destinationService.Resource = resource
}
}
default:
// Only set event.Span.Type if not already set
if event.Span.Type == "" {
switch spanKind {
case ptrace.SpanKindInternal:
event.Span.Type = "app"
event.Span.Subtype = "internal"