From 805471515a3830349843b4e167a442592113a6ce Mon Sep 17 00:00:00 2001 From: atshaw43 <108552302+atshaw43@users.noreply.github.com> Date: Wed, 11 Oct 2023 13:14:05 -0700 Subject: [PATCH] Adding segmnt splits (#111) --- .chloggen/aws_exporter_localrootspans.yaml | 27 + exporter/awsxrayexporter/awsxray.go | 8 +- .../internal/translator/segment.go | 237 +++++++- .../internal/translator/segment_test.go | 515 +++++++++++++++++- 4 files changed, 770 insertions(+), 17 deletions(-) create mode 100755 .chloggen/aws_exporter_localrootspans.yaml diff --git a/.chloggen/aws_exporter_localrootspans.yaml b/.chloggen/aws_exporter_localrootspans.yaml new file mode 100755 index 000000000000..49cc484a9928 --- /dev/null +++ b/.chloggen/aws_exporter_localrootspans.yaml @@ -0,0 +1,27 @@ +# Use this changelog template to create an entry for release notes. + +# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' +change_type: enhancement + +# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver) +component: awsxrayexporter + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: AWS X-Ray exporter to make local root spans a segment for internal/service spans and subsegment + segment for client/producer/consumer spans. + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [102] + +# (Optional) One or more lines of additional information to render under the primary note. +# These lines will be padded with 2 spaces and then inserted directly into the document. +# Use pipe (|) for multiline entries. +subtext: + +# If your change doesn't affect end users or the exported elements of any package, +# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. +# Optional: The change log or logs in which this entry should be included. +# e.g. '[user]' or '[user, api]' +# Include 'user' if the change is relevant to end users. +# Include 'api' if there is a change to a library API. +# Default: '[user]' +change_logs: [user] diff --git a/exporter/awsxrayexporter/awsxray.go b/exporter/awsxrayexporter/awsxray.go index 6cd3e77be21a..5d68b99fba3b 100644 --- a/exporter/awsxrayexporter/awsxray.go +++ b/exporter/awsxrayexporter/awsxray.go @@ -105,17 +105,21 @@ func extractResourceSpans(config component.Config, logger *zap.Logger, td ptrace for j := 0; j < rspans.ScopeSpans().Len(); j++ { spans := rspans.ScopeSpans().At(j).Spans() for k := 0; k < spans.Len(); k++ { - document, localErr := translator.MakeSegmentDocumentString( + documentsForSpan, localErr := translator.MakeSegmentDocuments( spans.At(k), resource, config.(*Config).IndexedAttributes, config.(*Config).IndexAllAttributes, config.(*Config).LogGroupNames, config.(*Config).skipTimestampValidation) + if localErr != nil { logger.Debug("Error translating span.", zap.Error(localErr)) continue } - documents = append(documents, &document) + + for l := range documentsForSpan { + documents = append(documents, &documentsForSpan[l]) + } } } } diff --git a/exporter/awsxrayexporter/internal/translator/segment.go b/exporter/awsxrayexporter/internal/translator/segment.go index 6d1efab2ff65..21470e0e0dbd 100644 --- a/exporter/awsxrayexporter/internal/translator/segment.go +++ b/exporter/awsxrayexporter/internal/translator/segment.go @@ -36,8 +36,13 @@ const ( // x-ray only span attributes - https://github.com/open-telemetry/opentelemetry-java-contrib/pull/802 const ( - awsLocalService = "aws.local.service" - awsRemoteService = "aws.remote.service" + awsLocalService = "aws.local.service" + awsRemoteService = "aws.remote.service" + awsLocalOperation = "aws.local.operation" + awsRemoteOperation = "aws.remote.operation" + remoteTarget = "remoteTarget" + awsSpanKind = "aws.span.kind" + k8sRemoteNamespace = "K8s.RemoteNamespace" ) var ( @@ -60,16 +65,232 @@ const ( identifierOffset = 11 // offset of identifier within traceID ) +const ( + localRoot = "LOCAL_ROOT" +) + +var removeAnnotationsFromServiceSegment = []string{ + awsRemoteService, + awsRemoteOperation, + remoteTarget, + k8sRemoteNamespace, +} + var ( writers = newWriterPool(2048) ) -// MakeSegmentDocumentString converts an OpenTelemetry Span to an X-Ray Segment and then serialzies to JSON +// MakeSegmentDocuments converts spans to json documents +func MakeSegmentDocuments(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]string, error) { + segments, err := MakeSegmentsFromSpan(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + + if err == nil { + var documents []string + + for _, v := range segments { + document, documentErr := MakeDocumentFromSegment(v) + if documentErr != nil { + return nil, documentErr + } + + documents = append(documents, document) + } + + return documents, nil + } + + return nil, err +} + +func isLocalRootSpanADependencySpan(span ptrace.Span) bool { + return span.Kind() != ptrace.SpanKindServer && + span.Kind() != ptrace.SpanKindInternal +} + +// IsLocalRoot We will move to using isRemote once the collector supports deserializing it. Until then, we will rely on aws.span.kind. +func isLocalRoot(span ptrace.Span) bool { + if myAwsSpanKind, ok := span.Attributes().Get(awsSpanKind); ok { + return localRoot == myAwsSpanKind.Str() + } + + return false +} + +func addNamespaceToSubsegmentWithRemoteService(span ptrace.Span, segment *awsxray.Segment) { + if (span.Kind() == ptrace.SpanKindClient || + span.Kind() == ptrace.SpanKindConsumer || + span.Kind() == ptrace.SpanKindProducer) && + segment.Type != nil && + segment.Namespace == nil { + if _, ok := span.Attributes().Get(awsRemoteService); ok { + segment.Namespace = awsxray.String("remote") + } + } +} + +func MakeDependencySubsegmentForLocalRootDependencySpan(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool, serviceSegmentID pcommon.SpanID) (*awsxray.Segment, error) { + var dependencySpan = ptrace.NewSpan() + span.CopyTo(dependencySpan) + + dependencySpan.SetParentSpanID(serviceSegmentID) + + dependencySubsegment, err := MakeSegment(dependencySpan, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + + if err != nil { + return nil, err + } + + // Make this a subsegment + dependencySubsegment.Type = awsxray.String("subsegment") + + if dependencySubsegment.Namespace == nil { + dependencySubsegment.Namespace = awsxray.String("remote") + } + + // Remove span links from consumer spans + if span.Kind() == ptrace.SpanKindConsumer { + dependencySubsegment.Links = nil + } + + myAwsRemoteService, _ := span.Attributes().Get(awsRemoteService) + + dependencySubsegment.Name = awsxray.String(myAwsRemoteService.Str()) + + return dependencySubsegment, err +} + +func MakeServiceSegmentForLocalRootDependencySpan(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool, serviceSegmentID pcommon.SpanID) (*awsxray.Segment, error) { + // We always create a segment for the service + var serviceSpan ptrace.Span = ptrace.NewSpan() + span.CopyTo(serviceSpan) + + // Set the span id to the one internally generated + serviceSpan.SetSpanID(serviceSegmentID) + + for _, v := range removeAnnotationsFromServiceSegment { + serviceSpan.Attributes().Remove(v) + } + + serviceSegment, err := MakeSegment(serviceSpan, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + + if err != nil { + return nil, err + } + + // Set the name + if myAwsLocalService, ok := span.Attributes().Get(awsLocalService); ok { + serviceSegment.Name = awsxray.String(myAwsLocalService.Str()) + } + + // Remove the HTTP field + serviceSegment.HTTP = nil + + // Remove AWS subsegment fields + serviceSegment.AWS.Operation = nil + serviceSegment.AWS.AccountID = nil + serviceSegment.AWS.RemoteRegion = nil + serviceSegment.AWS.RequestID = nil + serviceSegment.AWS.QueueURL = nil + serviceSegment.AWS.TableName = nil + serviceSegment.AWS.TableNames = nil + + // Delete all metadata that does not start with 'otel.resource.' + for _, metaDataEntry := range serviceSegment.Metadata { + for key := range metaDataEntry { + if !strings.HasPrefix(key, "otel.resource.") { + delete(metaDataEntry, key) + } + } + } + + // Make it a segment + serviceSegment.Type = nil + + // Remote namespace + serviceSegment.Namespace = nil + + // Remove span links from non-consumer spans + if span.Kind() != ptrace.SpanKindConsumer { + serviceSegment.Links = nil + } + + return serviceSegment, nil +} + +func MakeServiceSegmentForLocalRootSpanWithoutDependency(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { + segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + + if err != nil { + return nil, err + } + + segment.Type = nil + segment.Namespace = nil + + return []*awsxray.Segment{segment}, err +} + +func MakeNonLocalRootSegment(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { + segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + + if err != nil { + return nil, err + } + + addNamespaceToSubsegmentWithRemoteService(span, segment) + + return []*awsxray.Segment{segment}, nil +} + +func MakeServiceSegmentAndDependencySubsegment(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { + // If it is a local root span and a dependency span, we need to make a segment and subsegment representing the local service and remote service, respectively. + var serviceSegmentID = newSegmentID() + var segments []*awsxray.Segment + + // Make Dependency Subsegment + dependencySubsegment, err := MakeDependencySubsegmentForLocalRootDependencySpan(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation, serviceSegmentID) + if err != nil { + return nil, err + } + segments = append(segments, dependencySubsegment) + + // Make Service Segment + serviceSegment, err := MakeServiceSegmentForLocalRootDependencySpan(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation, serviceSegmentID) + if err != nil { + return nil, err + } + segments = append(segments, serviceSegment) + + return segments, err +} + +// MakeSegmentsFromSpan creates one or more segments from a span +func MakeSegmentsFromSpan(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { + if !isLocalRoot(span) { + return MakeNonLocalRootSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + } + + if !isLocalRootSpanADependencySpan(span) { + return MakeServiceSegmentForLocalRootSpanWithoutDependency(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + } + + return MakeServiceSegmentAndDependencySubsegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) +} + +// MakeSegmentDocumentString converts an OpenTelemetry Span to an X-Ray Segment and then serializes to JSON +// MakeSegmentDocumentString will be deprecated in the future func MakeSegmentDocumentString(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) (string, error) { segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) + if err != nil { return "", err } + + return MakeDocumentFromSegment(segment) +} + +// MakeDocumentFromSegment converts a segment into a JSON document +func MakeDocumentFromSegment(segment *awsxray.Segment) (string, error) { w := writers.borrow() if err := w.Encode(*segment); err != nil { return "", err @@ -122,11 +343,19 @@ func MakeSegment(span ptrace.Span, resource pcommon.Resource, indexedAttrs []str // X-Ray segment names are service names, unlike span names which are methods. Try to find a service name. // support x-ray specific service name attributes as segment name if it exists - if span.Kind() == ptrace.SpanKindServer || span.Kind() == ptrace.SpanKindConsumer { + if span.Kind() == ptrace.SpanKindServer { if localServiceName, ok := attributes.Get(awsLocalService); ok { name = localServiceName.Str() } } + + myAwsSpanKind, _ := span.Attributes().Get(awsSpanKind) + if span.Kind() == ptrace.SpanKindInternal && myAwsSpanKind.Str() == localRoot { + if localServiceName, ok := attributes.Get(awsLocalService); ok { + name = localServiceName.Str() + } + } + if span.Kind() == ptrace.SpanKindClient || span.Kind() == ptrace.SpanKindProducer { if remoteServiceName, ok := attributes.Get(awsRemoteService); ok { name = remoteServiceName.Str() diff --git a/exporter/awsxrayexporter/internal/translator/segment_test.go b/exporter/awsxrayexporter/internal/translator/segment_test.go index fcdfed6550a4..a9ca076c3659 100644 --- a/exporter/awsxrayexporter/internal/translator/segment_test.go +++ b/exporter/awsxrayexporter/internal/translator/segment_test.go @@ -1024,19 +1024,11 @@ func TestConsumerSpanWithAwsRemoteServiceName(t *testing.T) { spanName := "ABC.payment" parentSpanID := newSegmentID() user := "testingT" - attributes := make(map[string]interface{}) - attributes[conventions.AttributeHTTPMethod] = "POST" - attributes[conventions.AttributeHTTPScheme] = "https" - attributes[conventions.AttributeHTTPHost] = "payment.amazonaws.com" - attributes[conventions.AttributeHTTPTarget] = "/" - attributes[conventions.AttributeRPCService] = "ABC" - attributes[awsLocalService] = "ConsumerService" + attributes := getBasicAttributes() + attributes[awsRemoteService] = "ConsumerService" resource := constructDefaultResource() - span := constructConsumerSpan(parentSpanID, spanName, 0, "OK", attributes) - - segment, _ := MakeSegment(span, resource, nil, false, nil, false) - assert.Equal(t, "ConsumerService", *segment.Name) + span := constructConsumerSpan(parentSpanID, spanName, 0, "Ok", attributes) jsonStr, err := MakeSegmentDocumentString(span, resource, nil, false, nil, false) @@ -1075,6 +1067,480 @@ func TestServerSpanWithAwsLocalServiceName(t *testing.T) { assert.False(t, strings.Contains(jsonStr, "user")) } +func validateLocalRootDependencySubsegment(t *testing.T, segment *awsxray.Segment, span ptrace.Span, parentID string) { + tempTraceID := span.TraceID() + expectedTraceID := "1-" + fmt.Sprintf("%x", tempTraceID[0:4]) + "-" + fmt.Sprintf("%x", tempTraceID[4:16]) + + assert.Equal(t, "subsegment", *segment.Type) + assert.Equal(t, "myRemoteService", *segment.Name) + assert.Equal(t, span.SpanID().String(), *segment.ID) + assert.Equal(t, parentID, *segment.ParentID) + assert.Equal(t, expectedTraceID, *segment.TraceID) + assert.NotNil(t, segment.HTTP) + assert.Equal(t, "POST", *segment.HTTP.Request.Method) + assert.Equal(t, 2, len(segment.Annotations)) + assert.Nil(t, segment.Annotations[awsRemoteService]) + assert.Nil(t, segment.Annotations[remoteTarget]) + assert.Equal(t, "myAnnotationValue", segment.Annotations["myAnnotationKey"]) + + assert.Equal(t, 8, len(segment.Metadata["default"])) + assert.Equal(t, "receive", segment.Metadata["default"][conventions.AttributeMessagingOperation]) + assert.Equal(t, "LOCAL_ROOT", segment.Metadata["default"][awsSpanKind]) + assert.Equal(t, "myRemoteOperation", segment.Metadata["default"][awsRemoteOperation]) + assert.Equal(t, "myTarget", segment.Metadata["default"][remoteTarget]) + assert.Equal(t, "k8sRemoteNamespace", segment.Metadata["default"][k8sRemoteNamespace]) + assert.Equal(t, "myLocalService", segment.Metadata["default"][awsLocalService]) + assert.Equal(t, "awsLocalOperation", segment.Metadata["default"][awsLocalOperation]) + assert.Equal(t, "service.name=myTest", segment.Metadata["default"]["otel.resource.attributes"]) + + assert.Equal(t, "MySDK", *segment.AWS.XRay.SDK) + assert.Equal(t, "1.20.0", *segment.AWS.XRay.SDKVersion) + assert.Equal(t, true, *segment.AWS.XRay.AutoInstrumentation) + + assert.Equal(t, "UpdateItem", *segment.AWS.Operation) + assert.Equal(t, "AWSAccountAttribute", *segment.AWS.AccountID) + assert.Equal(t, "AWSRegionAttribute", *segment.AWS.RemoteRegion) + assert.Equal(t, "AWSRequestIDAttribute", *segment.AWS.RequestID) + assert.Equal(t, "AWSQueueURLAttribute", *segment.AWS.QueueURL) + assert.Equal(t, "TableName", *segment.AWS.TableName) + + assert.Equal(t, "remote", *segment.Namespace) +} + +func validateLocalRootServiceSegment(t *testing.T, segment *awsxray.Segment, span ptrace.Span) { + tempTraceID := span.TraceID() + expectedTraceID := "1-" + fmt.Sprintf("%x", tempTraceID[0:4]) + "-" + fmt.Sprintf("%x", tempTraceID[4:16]) + + assert.Nil(t, segment.Type) + assert.Equal(t, "myLocalService", *segment.Name) + assert.Equal(t, expectedTraceID, *segment.TraceID) + assert.Nil(t, segment.HTTP) + assert.Equal(t, 1, len(segment.Annotations)) + assert.Equal(t, "myAnnotationValue", segment.Annotations["myAnnotationKey"]) + assert.Equal(t, 1, len(segment.Metadata["default"])) + assert.Equal(t, "service.name=myTest", segment.Metadata["default"]["otel.resource.attributes"]) + assert.Equal(t, "MySDK", *segment.AWS.XRay.SDK) + assert.Equal(t, "1.20.0", *segment.AWS.XRay.SDKVersion) + assert.Equal(t, true, *segment.AWS.XRay.AutoInstrumentation) + assert.Nil(t, segment.AWS.Operation) + assert.Nil(t, segment.AWS.AccountID) + assert.Nil(t, segment.AWS.RemoteRegion) + assert.Nil(t, segment.AWS.RequestID) + assert.Nil(t, segment.AWS.QueueURL) + assert.Nil(t, segment.AWS.TableName) + assert.Nil(t, segment.Namespace) + + assert.Nil(t, segment.Namespace) +} + +func getBasicAttributes() map[string]interface{} { + attributes := make(map[string]interface{}) + + attributes[conventions.AttributeHTTPMethod] = "POST" + attributes[conventions.AttributeMessagingOperation] = "receive" + + attributes["otel.resource.attributes"] = "service.name=myTest" + + attributes[awsSpanKind] = "LOCAL_ROOT" + attributes[awsRemoteService] = "myRemoteService" + attributes[awsRemoteOperation] = "myRemoteOperation" + attributes[remoteTarget] = "myTarget" + attributes[k8sRemoteNamespace] = "k8sRemoteNamespace" + attributes[awsLocalService] = "myLocalService" + attributes[awsLocalOperation] = "awsLocalOperation" + + attributes["myAnnotationKey"] = "myAnnotationValue" + + attributes[awsxray.AWSOperationAttribute] = "UpdateItem" + attributes[awsxray.AWSAccountAttribute] = "AWSAccountAttribute" + attributes[awsxray.AWSRegionAttribute] = "AWSRegionAttribute" + attributes[awsxray.AWSRequestIDAttribute] = "AWSRequestIDAttribute" + attributes[awsxray.AWSQueueURLAttribute] = "AWSQueueURLAttribute" + attributes[awsxray.AWSTableNameAttribute] = "TableName" + + return attributes +} + +func getBasicResource() pcommon.Resource { + resource := constructDefaultResource() + + resource.Attributes().PutStr(conventions.AttributeTelemetrySDKName, "MySDK") + resource.Attributes().PutStr(conventions.AttributeTelemetrySDKVersion, "1.20.0") + resource.Attributes().PutStr(conventions.AttributeTelemetryAutoVersion, "1.2.3") + + return resource +} + +func addSpanLink(span ptrace.Span) { + spanLink := span.Links().AppendEmpty() + spanLink.SetTraceID(newTraceID()) + spanLink.SetSpanID(newSegmentID()) +} + +func TestLocalRootConsumer(t *testing.T) { + spanName := "destination operation" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + + span := constructConsumerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 2, len(segments)) + assert.Nil(t, err) + + validateLocalRootDependencySubsegment(t, segments[0], span, *segments[1].ID) + assert.Nil(t, segments[0].Links) + + validateLocalRootServiceSegment(t, segments[1], span) + assert.Equal(t, 1, len(segments[1].Links)) + + // Checks these values are the same for both + assert.Equal(t, segments[0].StartTime, segments[1].StartTime) + assert.Equal(t, segments[0].EndTime, segments[1].EndTime) +} + +func TestNonLocalRootConsumerProcess(t *testing.T) { + spanName := "destination operation" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + delete(attributes, awsRemoteService) + delete(attributes, awsRemoteOperation) + attributes[awsSpanKind] = "Consumer" + + span := constructConsumerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + tempTraceID := span.TraceID() + expectedTraceID := "1-" + fmt.Sprintf("%x", tempTraceID[0:4]) + "-" + fmt.Sprintf("%x", tempTraceID[4:16]) + + // Validate segment 1 (dependency subsegment) + assert.Equal(t, "subsegment", *segments[0].Type) + assert.Equal(t, "destination operation", *segments[0].Name) + assert.NotEqual(t, parentSpanID.String(), *segments[0].ID) + assert.Equal(t, span.SpanID().String(), *segments[0].ID) + assert.Equal(t, 1, len(segments[0].Links)) + assert.Equal(t, expectedTraceID, *segments[0].TraceID) + assert.NotNil(t, segments[0].HTTP) + assert.Equal(t, "POST", *segments[0].HTTP.Request.Method) + assert.Equal(t, 1, len(segments[0].Annotations)) + assert.Equal(t, "myAnnotationValue", segments[0].Annotations["myAnnotationKey"]) + assert.Equal(t, 7, len(segments[0].Metadata["default"])) + assert.Equal(t, "Consumer", segments[0].Metadata["default"][awsSpanKind]) + assert.Equal(t, "myLocalService", segments[0].Metadata["default"][awsLocalService]) + assert.Equal(t, "receive", segments[0].Metadata["default"][conventions.AttributeMessagingOperation]) + assert.Equal(t, "service.name=myTest", segments[0].Metadata["default"]["otel.resource.attributes"]) + assert.Equal(t, "MySDK", *segments[0].AWS.XRay.SDK) + assert.Equal(t, "1.20.0", *segments[0].AWS.XRay.SDKVersion) + assert.Equal(t, true, *segments[0].AWS.XRay.AutoInstrumentation) + assert.Equal(t, "UpdateItem", *segments[0].AWS.Operation) + assert.Nil(t, segments[0].Namespace) +} + +func TestLocalRootConsumerAWSNamespace(t *testing.T) { + spanName := "destination receive" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[conventions.AttributeRPCSystem] = "aws-api" + + span := constructConsumerSpan(parentSpanID, spanName, 200, "OK", attributes) + + spanLink := span.Links().AppendEmpty() + spanLink.SetTraceID(newTraceID()) + spanLink.SetSpanID(newSegmentID()) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 2, len(segments)) + assert.Nil(t, err) + + // Ensure that AWS namespace is not overwritten to remote + assert.Equal(t, "aws", *segments[0].Namespace) +} + +func TestLocalRootClient(t *testing.T) { + spanName := "SQS Get" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + + span := constructClientSpan(parentSpanID, spanName, 200, "OK", attributes) + + spanLink := span.Links().AppendEmpty() + spanLink.SetTraceID(newTraceID()) + spanLink.SetSpanID(newSegmentID()) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 2, len(segments)) + assert.Nil(t, err) + + validateLocalRootDependencySubsegment(t, segments[0], span, *segments[1].ID) + assert.Equal(t, 1, len(segments[0].Links)) + + validateLocalRootServiceSegment(t, segments[1], span) + assert.Nil(t, segments[1].Links) + + // Checks these values are the same for both + assert.Equal(t, segments[0].StartTime, segments[1].StartTime) + assert.Equal(t, segments[0].EndTime, segments[1].EndTime) +} + +func TestLocalRootProducer(t *testing.T) { + spanName := "destination operation" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + + span := constructProducerSpan(parentSpanID, spanName, 200, "Ok", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 2, len(segments)) + assert.Nil(t, err) + + validateLocalRootDependencySubsegment(t, segments[0], span, *segments[1].ID) + assert.Equal(t, 1, len(segments[0].Links)) + + validateLocalRootServiceSegment(t, segments[1], span) + assert.Nil(t, segments[1].Links) + + // Checks these values are the same for both + assert.Equal(t, segments[0].StartTime, segments[1].StartTime) + assert.Equal(t, segments[0].EndTime, segments[1].EndTime) +} + +func validateLocalRootWithoutDependency(t *testing.T, segment *awsxray.Segment, span ptrace.Span) { + tempTraceID := span.TraceID() + expectedTraceID := "1-" + fmt.Sprintf("%x", tempTraceID[0:4]) + "-" + fmt.Sprintf("%x", tempTraceID[4:16]) + + // Validate segment + assert.Nil(t, segment.Type) + assert.Equal(t, "myLocalService", *segment.Name) + assert.Equal(t, span.ParentSpanID().String(), *segment.ParentID) + assert.Equal(t, 1, len(segment.Links)) + assert.Equal(t, expectedTraceID, *segment.TraceID) + assert.Equal(t, "POST", *segment.HTTP.Request.Method) + assert.Equal(t, 2, len(segment.Annotations)) + assert.Equal(t, "myRemoteService", segment.Annotations["aws_remote_service"]) + assert.Equal(t, "myAnnotationValue", segment.Annotations["myAnnotationKey"]) + + var numberOfMetadataKeys = 8 + + if span.Kind() == ptrace.SpanKindServer { + numberOfMetadataKeys = 30 + } + + assert.Equal(t, numberOfMetadataKeys, len(segment.Metadata["default"])) + assert.Equal(t, "receive", segment.Metadata["default"][conventions.AttributeMessagingOperation]) + assert.Equal(t, "LOCAL_ROOT", segment.Metadata["default"][awsSpanKind]) + assert.Equal(t, "myRemoteOperation", segment.Metadata["default"][awsRemoteOperation]) + assert.Equal(t, "myTarget", segment.Metadata["default"][remoteTarget]) + assert.Equal(t, "k8sRemoteNamespace", segment.Metadata["default"][k8sRemoteNamespace]) + assert.Equal(t, "myLocalService", segment.Metadata["default"][awsLocalService]) + assert.Equal(t, "awsLocalOperation", segment.Metadata["default"][awsLocalOperation]) + assert.Equal(t, "service.name=myTest", segment.Metadata["default"]["otel.resource.attributes"]) + + assert.Equal(t, "service.name=myTest", segment.Metadata["default"]["otel.resource.attributes"]) + assert.Equal(t, "MySDK", *segment.AWS.XRay.SDK) + assert.Equal(t, "1.20.0", *segment.AWS.XRay.SDKVersion) + assert.Equal(t, true, *segment.AWS.XRay.AutoInstrumentation) + + assert.Equal(t, "UpdateItem", *segment.AWS.Operation) + assert.Equal(t, "AWSAccountAttribute", *segment.AWS.AccountID) + assert.Equal(t, "AWSRegionAttribute", *segment.AWS.RemoteRegion) + assert.Equal(t, "AWSRequestIDAttribute", *segment.AWS.RequestID) + assert.Equal(t, "AWSQueueURLAttribute", *segment.AWS.QueueURL) + assert.Equal(t, "TableName", *segment.AWS.TableName) + + assert.Nil(t, segment.Namespace) +} + +func TestLocalRootServer(t *testing.T) { + spanName := "MyService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + + span := constructServerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + validateLocalRootWithoutDependency(t, segments[0], span) +} + +func TestLocalRootInternal(t *testing.T) { + spanName := "MyInternalService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + + span := constructInternalSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + validateLocalRootWithoutDependency(t, segments[0], span) +} + +func TestNotLocalRootInternal(t *testing.T) { + spanName := "MyService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[awsSpanKind] = "Internal" + + span := constructInternalSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + // Validate segment + assert.Equal(t, "subsegment", *segments[0].Type) + assert.Nil(t, segments[0].Namespace) + assert.Equal(t, "MyService", *segments[0].Name) +} + +func TestNotLocalRootConsumer(t *testing.T) { + spanName := "MyService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[awsSpanKind] = "Consumer" + + span := constructConsumerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + // Validate segment + assert.Equal(t, "subsegment", *segments[0].Type) + assert.Equal(t, "remote", *segments[0].Namespace) + assert.Equal(t, "MyService", *segments[0].Name) +} + +func TestNotLocalRootClient(t *testing.T) { + spanName := "MyService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[awsSpanKind] = "Client" + + span := constructClientSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + // Validate segment + assert.Equal(t, "subsegment", *segments[0].Type) + assert.Equal(t, "remote", *segments[0].Namespace) + assert.Equal(t, "myRemoteService", *segments[0].Name) +} + +func TestNotLocalRootProducer(t *testing.T) { + spanName := "MyService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[awsSpanKind] = "Producer" + + span := constructProducerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + // Validate segment + assert.Equal(t, "subsegment", *segments[0].Type) + assert.Equal(t, "remote", *segments[0].Namespace) + assert.Equal(t, "myRemoteService", *segments[0].Name) +} + +func TestNotLocalRootServer(t *testing.T) { + spanName := "MyInternalService" + resource := getBasicResource() + parentSpanID := newSegmentID() + + attributes := getBasicAttributes() + attributes[awsSpanKind] = "Server" + delete(attributes, awsRemoteService) + delete(attributes, awsRemoteOperation) + + span := constructServerSpan(parentSpanID, spanName, 200, "OK", attributes) + + addSpanLink(span) + + segments, err := MakeSegmentsFromSpan(span, resource, []string{awsRemoteService, "myAnnotationKey"}, false, nil, false) + + assert.NotNil(t, segments) + assert.Equal(t, 1, len(segments)) + assert.Nil(t, err) + + // Validate segment + assert.Nil(t, segments[0].Type) + assert.Nil(t, segments[0].Namespace) + assert.Equal(t, "myLocalService", *segments[0].Name) +} + func constructClientSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { var ( traceID = newTraceID() @@ -1129,6 +1595,33 @@ func constructServerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.S return span } +func constructInternalSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { + var ( + traceID = newTraceID() + spanID = newSegmentID() + endTime = time.Now() + startTime = endTime.Add(-215 * time.Millisecond) + spanAttributes = constructSpanAttributes(attributes) + ) + + span := ptrace.NewSpan() + span.SetTraceID(traceID) + span.SetSpanID(spanID) + span.SetParentSpanID(parentSpanID) + span.SetName(name) + span.SetKind(ptrace.SpanKindInternal) + span.SetStartTimestamp(pcommon.NewTimestampFromTime(startTime)) + span.SetEndTimestamp(pcommon.NewTimestampFromTime(endTime)) + + status := ptrace.NewStatus() + status.SetCode(code) + status.SetMessage(message) + status.CopyTo(span.Status()) + + spanAttributes.CopyTo(span.Attributes()) + return span +} + func constructConsumerSpan(parentSpanID pcommon.SpanID, name string, code ptrace.StatusCode, message string, attributes map[string]interface{}) ptrace.Span { var ( traceID = newTraceID()