Search in sources :

Example 6 with LinkData

use of io.opentelemetry.sdk.trace.data.LinkData in project inspectit-ocelot by inspectIT.

the class OcelotSpanUtils method createSpanData.

/**
 * Creates a {@link SpanData} instance based on the given arguments.
 *
 * @param protoSpan                  the protobuf representation of the span
 * @param resource                   the span's resources
 * @param instrumentationLibraryInfo the information of the tracing library
 * @param customSpanAttributes       additional attributes which should be added to each span
 *
 * @return the created {@link SpanData} instance
 */
public static SpanData createSpanData(Span protoSpan, Resource resource, InstrumentationLibraryInfo instrumentationLibraryInfo, Map<String, String> customSpanAttributes) {
    try {
        String traceId = toIdString(protoSpan.getTraceId());
        String spanId = toIdString(protoSpan.getSpanId());
        String parentSpanId = toIdString(protoSpan.getParentSpanId());
        SpanContext spanContext = createSpanContext(traceId, spanId);
        SpanContext parentSpanContext = createSpanContext(traceId, parentSpanId);
        // only create spans with valid context
        if (!spanContext.isValid()) {
            return null;
        }
        // span data
        String name = protoSpan.getName();
        long startTime = protoSpan.getStartTimeUnixNano();
        SpanLimits spanLimits = SpanLimits.getDefault();
        int totalRecordedLinks = protoSpan.getLinksCount() + protoSpan.getDroppedLinksCount();
        SpanKind spanKind = toSpanKind(protoSpan.getKind());
        List<LinkData> links = toLinkData(protoSpan.getLinksList());
        // convert attributes map to AttributesMap
        Attributes spanAttributes = toAttributes(protoSpan.getAttributesList(), customSpanAttributes);
        Map<AttributeKey<?>, Object> attributesMap = spanAttributes.asMap();
        AttributesMap spanAttributesMap = new AttributesMap(attributesMap.size());
        spanAttributesMap.putAll(attributesMap);
        // creating the actual span
        RecordEventsReadableSpan span = RecordEventsReadableSpan.startSpan(spanContext, name, instrumentationLibraryInfo, spanKind, parentSpanContext, NOOP_CONTEXT, spanLimits, NOOP_SPAN_PROCESSOR, SystemClock.getInstance(), resource, spanAttributesMap, links, totalRecordedLinks, startTime);
        // add events to the span - and filter events which occurred before the actual span
        protoSpan.getEventsList().stream().filter(event -> event.getTimeUnixNano() >= span.getStartEpochNanos()).forEach(event -> {
            Attributes attributes = toAttributes(event.getAttributesList());
            span.addEvent(event.getName(), attributes, event.getTimeUnixNano(), TimeUnit.NANOSECONDS);
        });
        // the span's status code
        Status status = protoSpan.getStatus();
        StatusCode statusCode = toStatusCode(status.getCode());
        if (statusCode != null) {
            span.setStatus(statusCode, status.getMessage());
        }
        // set end time if available
        long endTime = protoSpan.getEndTimeUnixNano();
        if (endTime > 0) {
            span.end(endTime, TimeUnit.NANOSECONDS);
        }
        return span.toSpanData();
    } catch (Exception e) {
        log.warn("Error converting OT proto span {} to span data.", protoSpan, e);
        return null;
    }
}
Also used : KeyValue(io.opentelemetry.proto.common.v1.KeyValue) Resource(io.opentelemetry.sdk.resources.Resource) Attributes(io.opentelemetry.api.common.Attributes) io.opentelemetry.api.trace(io.opentelemetry.api.trace) InstrumentationLibraryInfo(io.opentelemetry.sdk.common.InstrumentationLibraryInfo) Map(java.util.Map) Nullable(javax.annotation.Nullable) ContextKey(io.opentelemetry.context.ContextKey) Context(io.opentelemetry.context.Context) BaseEncoding(com.google.common.io.BaseEncoding) Collectors(java.util.stream.Collectors) Span(io.opentelemetry.proto.trace.v1.Span) AttributesBuilder(io.opentelemetry.api.common.AttributesBuilder) ByteString(com.google.protobuf.ByteString) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) CollectionUtils(org.springframework.util.CollectionUtils) AttributeKey(io.opentelemetry.api.common.AttributeKey) SystemClock(io.opentelemetry.sdk.internal.SystemClock) SpanData(io.opentelemetry.sdk.trace.data.SpanData) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AnyValue(io.opentelemetry.proto.common.v1.AnyValue) LinkData(io.opentelemetry.sdk.trace.data.LinkData) Status(io.opentelemetry.proto.trace.v1.Status) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) Status(io.opentelemetry.proto.trace.v1.Status) LinkData(io.opentelemetry.sdk.trace.data.LinkData) Attributes(io.opentelemetry.api.common.Attributes) ByteString(com.google.protobuf.ByteString) AttributeKey(io.opentelemetry.api.common.AttributeKey)

Example 7 with LinkData

use of io.opentelemetry.sdk.trace.data.LinkData in project opentelemetry-java by open-telemetry.

the class SdkSpanTest method testAsSpanData.

@Test
void testAsSpanData() {
    String name = "GreatSpan";
    SpanKind kind = SpanKind.SERVER;
    String traceId = this.traceId;
    String spanId = this.spanId;
    String parentSpanId = this.parentSpanId;
    SpanLimits spanLimits = SpanLimits.getDefault();
    SpanProcessor spanProcessor = NoopSpanProcessor.getInstance();
    TestClock clock = TestClock.create();
    Resource resource = this.resource;
    Attributes attributes = TestUtils.generateRandomAttributes();
    AttributesMap attributesWithCapacity = new AttributesMap(32, Integer.MAX_VALUE);
    attributes.forEach((key, value) -> attributesWithCapacity.put((AttributeKey) key, value));
    Attributes event1Attributes = TestUtils.generateRandomAttributes();
    Attributes event2Attributes = TestUtils.generateRandomAttributes();
    SpanContext context = SpanContext.create(traceId, spanId, TraceFlags.getDefault(), TraceState.getDefault());
    LinkData link1 = LinkData.create(context, TestUtils.generateRandomAttributes());
    SdkSpan readableSpan = SdkSpan.startSpan(context, name, instrumentationLibraryInfo, kind, parentSpanId != null ? Span.wrap(SpanContext.create(traceId, parentSpanId, TraceFlags.getDefault(), TraceState.getDefault())) : Span.getInvalid(), Context.root(), spanLimits, spanProcessor, clock, resource, attributesWithCapacity, Collections.singletonList(link1), 1, 0);
    long startEpochNanos = clock.now();
    clock.advance(Duration.ofMillis(4));
    long firstEventEpochNanos = clock.now();
    readableSpan.addEvent("event1", event1Attributes);
    clock.advance(Duration.ofMillis(6));
    long secondEventTimeNanos = clock.now();
    readableSpan.addEvent("event2", event2Attributes);
    clock.advance(Duration.ofMillis(100));
    readableSpan.end();
    long endEpochNanos = clock.now();
    List<EventData> events = Arrays.asList(EventData.create(firstEventEpochNanos, "event1", event1Attributes, event1Attributes.size()), EventData.create(secondEventTimeNanos, "event2", event2Attributes, event2Attributes.size()));
    SpanData result = readableSpan.toSpanData();
    verifySpanData(result, attributesWithCapacity, events, Collections.singletonList(link1), name, startEpochNanos, endEpochNanos, StatusData.unset(), /* hasEnded= */
    true);
    assertThat(result.getTotalRecordedLinks()).isEqualTo(1);
    assertThat(result.getSpanContext().isSampled()).isEqualTo(false);
}
Also used : SpanContext(io.opentelemetry.api.trace.SpanContext) LinkData(io.opentelemetry.sdk.trace.data.LinkData) SpanData(io.opentelemetry.sdk.trace.data.SpanData) Resource(io.opentelemetry.sdk.resources.Resource) SemanticAttributes(io.opentelemetry.semconv.trace.attributes.SemanticAttributes) Attributes(io.opentelemetry.api.common.Attributes) SpanKind(io.opentelemetry.api.trace.SpanKind) EventData(io.opentelemetry.sdk.trace.data.EventData) TestClock(io.opentelemetry.sdk.testing.time.TestClock) AttributeKey(io.opentelemetry.api.common.AttributeKey) Test(org.junit.jupiter.api.Test)

Example 8 with LinkData

use of io.opentelemetry.sdk.trace.data.LinkData in project opentelemetry-java by open-telemetry.

the class SdkSpanBuilderTest method sampler_updatedTraceState.

@Test
void sampler_updatedTraceState() {
    String samplerAttributeName = "sampler-attribute";
    AttributeKey<String> samplerAttributeKey = stringKey(samplerAttributeName);
    SdkSpan span = (SdkSpan) SdkTracerProvider.builder().setSampler(new Sampler() {

        @Override
        public SamplingResult shouldSample(Context parentContext, String traceId, String name, SpanKind spanKind, Attributes attributes, List<LinkData> parentLinks) {
            return new SamplingResult() {

                @Override
                public SamplingDecision getDecision() {
                    return SamplingDecision.RECORD_AND_SAMPLE;
                }

                @Override
                public Attributes getAttributes() {
                    return Attributes.empty();
                }

                @Override
                public TraceState getUpdatedTraceState(TraceState parentTraceState) {
                    return parentTraceState.toBuilder().put("newkey", "newValue").build();
                }
            };
        }

        @Override
        public String getDescription() {
            return "test sampler";
        }
    }).build().get("test").spanBuilder(SPAN_NAME).setAttribute(samplerAttributeKey, "none").startSpan();
    try {
        assertThat(span.getSpanContext().isSampled()).isTrue();
        assertThat(span.toSpanData().getAttributes().get(samplerAttributeKey)).isNotNull();
        assertThat(span.toSpanData().getSpanContext().getTraceState()).isEqualTo(TraceState.builder().put("newkey", "newValue").build());
    } finally {
        span.end();
    }
}
Also used : Context(io.opentelemetry.context.Context) SpanContext(io.opentelemetry.api.trace.SpanContext) TraceState(io.opentelemetry.api.trace.TraceState) LinkData(io.opentelemetry.sdk.trace.data.LinkData) SamplingResult(io.opentelemetry.sdk.trace.samplers.SamplingResult) Attributes(io.opentelemetry.api.common.Attributes) SpanKind(io.opentelemetry.api.trace.SpanKind) Sampler(io.opentelemetry.sdk.trace.samplers.Sampler) SamplingDecision(io.opentelemetry.sdk.trace.samplers.SamplingDecision) Test(org.junit.jupiter.api.Test)

Example 9 with LinkData

use of io.opentelemetry.sdk.trace.data.LinkData in project opentelemetry-java by open-telemetry.

the class SdkSpanBuilderTest method truncateLink.

@Test
void truncateLink() {
    int maxNumberOfLinks = 8;
    SpanLimits spanLimits = SpanLimits.builder().setMaxNumberOfLinks(maxNumberOfLinks).build();
    TracerProvider tracerProvider = SdkTracerProvider.builder().setSpanLimits(spanLimits).build();
    // Verify methods do not crash.
    SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME);
    for (int i = 0; i < 2 * maxNumberOfLinks; i++) {
        spanBuilder.addLink(sampledSpanContext);
    }
    SdkSpan span = (SdkSpan) spanBuilder.startSpan();
    try {
        SpanData spanData = span.toSpanData();
        List<LinkData> links = spanData.getLinks();
        assertThat(links).hasSize(maxNumberOfLinks);
        for (int i = 0; i < maxNumberOfLinks; i++) {
            assertThat(links.get(i)).isEqualTo(LinkData.create(sampledSpanContext));
            assertThat(spanData.getTotalRecordedLinks()).isEqualTo(2 * maxNumberOfLinks);
        }
    } finally {
        span.end();
    }
}
Also used : SpanBuilder(io.opentelemetry.api.trace.SpanBuilder) SpanData(io.opentelemetry.sdk.trace.data.SpanData) LinkData(io.opentelemetry.sdk.trace.data.LinkData) TracerProvider(io.opentelemetry.api.trace.TracerProvider) Test(org.junit.jupiter.api.Test)

Example 10 with LinkData

use of io.opentelemetry.sdk.trace.data.LinkData in project opentelemetry-java by open-telemetry.

the class SdkSpanBuilder method startSpan.

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Span startSpan() {
    Context parentContext = parent == null ? Context.current() : parent;
    Span parentSpan = Span.fromContext(parentContext);
    SpanContext parentSpanContext = parentSpan.getSpanContext();
    String traceId;
    IdGenerator idGenerator = tracerSharedState.getIdGenerator();
    String spanId = idGenerator.generateSpanId();
    if (!parentSpanContext.isValid()) {
        // New root span.
        traceId = idGenerator.generateTraceId();
    } else {
        // New child span.
        traceId = parentSpanContext.getTraceId();
    }
    List<LinkData> immutableLinks = links == null ? Collections.emptyList() : Collections.unmodifiableList(links);
    // Avoid any possibility to modify the links list by adding links to the Builder after the
    // startSpan is called. If that happens all the links will be added in a new list.
    links = null;
    Attributes immutableAttributes = attributes == null ? Attributes.empty() : attributes;
    SamplingResult samplingResult = tracerSharedState.getSampler().shouldSample(parentContext, traceId, spanName, spanKind, immutableAttributes, immutableLinks);
    SamplingDecision samplingDecision = samplingResult.getDecision();
    TraceState samplingResultTraceState = samplingResult.getUpdatedTraceState(parentSpanContext.getTraceState());
    SpanContext spanContext = ImmutableSpanContext.create(traceId, spanId, isSampled(samplingDecision) ? TraceFlags.getSampled() : TraceFlags.getDefault(), samplingResultTraceState, /* remote= */
    false, tracerSharedState.isIdGeneratorSafeToSkipIdValidation());
    if (!isRecording(samplingDecision)) {
        return Span.wrap(spanContext);
    }
    Attributes samplingAttributes = samplingResult.getAttributes();
    if (!samplingAttributes.isEmpty()) {
        samplingAttributes.forEach((key, value) -> attributes().put((AttributeKey) key, value));
    }
    // Avoid any possibility to modify the attributes by adding attributes to the Builder after the
    // startSpan is called. If that happens all the attributes will be added in a new map.
    AttributesMap recordedAttributes = attributes;
    attributes = null;
    return SdkSpan.startSpan(spanContext, spanName, instrumentationLibraryInfo, spanKind, parentSpan, parentContext, spanLimits, tracerSharedState.getActiveSpanProcessor(), tracerSharedState.getClock(), tracerSharedState.getResource(), recordedAttributes, immutableLinks, totalNumberOfLinksAdded, startEpochNanos);
}
Also used : Context(io.opentelemetry.context.Context) SpanContext(io.opentelemetry.api.trace.SpanContext) ImmutableSpanContext(io.opentelemetry.api.internal.ImmutableSpanContext) TraceState(io.opentelemetry.api.trace.TraceState) SpanContext(io.opentelemetry.api.trace.SpanContext) ImmutableSpanContext(io.opentelemetry.api.internal.ImmutableSpanContext) LinkData(io.opentelemetry.sdk.trace.data.LinkData) SamplingResult(io.opentelemetry.sdk.trace.samplers.SamplingResult) Attributes(io.opentelemetry.api.common.Attributes) Span(io.opentelemetry.api.trace.Span) AttributeKey(io.opentelemetry.api.common.AttributeKey) SamplingDecision(io.opentelemetry.sdk.trace.samplers.SamplingDecision)

Aggregations

LinkData (io.opentelemetry.sdk.trace.data.LinkData)14 Test (org.junit.jupiter.api.Test)9 Attributes (io.opentelemetry.api.common.Attributes)6 AttributeKey (io.opentelemetry.api.common.AttributeKey)3 SpanContext (io.opentelemetry.api.trace.SpanContext)3 Context (io.opentelemetry.context.Context)3 SpanData (io.opentelemetry.sdk.trace.data.SpanData)3 SpanRef (io.jaegertracing.thriftjava.SpanRef)2 SpanKind (io.opentelemetry.api.trace.SpanKind)2 TraceState (io.opentelemetry.api.trace.TraceState)2 Resource (io.opentelemetry.sdk.resources.Resource)2 SamplingDecision (io.opentelemetry.sdk.trace.samplers.SamplingDecision)2 SamplingResult (io.opentelemetry.sdk.trace.samplers.SamplingResult)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 BaseEncoding (com.google.common.io.BaseEncoding)1 ByteString (com.google.protobuf.ByteString)1 AttributesBuilder (io.opentelemetry.api.common.AttributesBuilder)1 ImmutableSpanContext (io.opentelemetry.api.internal.ImmutableSpanContext)1 io.opentelemetry.api.trace (io.opentelemetry.api.trace)1 Span (io.opentelemetry.api.trace.Span)1