Java Code Examples for com.nike.wingtips.Span#getParentSpanId()

The following examples show how to use com.nike.wingtips.Span#getParentSpanId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SampleController.java    From wingtips with Apache License 2.0 6 votes vote down vote up
public EndpointSpanInfoDto(HttpServletRequest request, Span endpoint_execution_span, List<String> userIdHeaderKeys) {
    this.parent_span_info = new SpanInfoDto(
        request.getHeader(TraceHeaders.TRACE_ID),
        request.getHeader(TraceHeaders.SPAN_ID),
        request.getHeader(TraceHeaders.PARENT_SPAN_ID),
        request.getHeader(TraceHeaders.TRACE_SAMPLED),
        HttpSpanFactory.getUserIdFromHttpServletRequest(request, userIdHeaderKeys)
    );
    this.endpoint_execution_span_info = new SpanInfoDto(
        endpoint_execution_span.getTraceId(),
        endpoint_execution_span.getSpanId(),
        endpoint_execution_span.getParentSpanId(),
        String.valueOf(endpoint_execution_span.isSampleable()),
        endpoint_execution_span.getUserId()
    );
}
 
Example 2
Source File: SampleController.java    From wingtips with Apache License 2.0 6 votes vote down vote up
public EndpointSpanInfoDto(ServerWebExchange exchange, Span endpoint_execution_span, List<String> userIdHeaderKeys) {
    HttpHeaders headers = exchange.getRequest().getHeaders();
    this.parent_span_info = new SpanInfoDto(
        headers.getFirst(TraceHeaders.TRACE_ID),
        headers.getFirst(TraceHeaders.SPAN_ID),
        headers.getFirst(TraceHeaders.PARENT_SPAN_ID),
        headers.getFirst(TraceHeaders.TRACE_SAMPLED),
        HttpRequestTracingUtils.getUserIdFromRequestWithHeaders(
            new RequestWithHeadersServerWebExchangeAdapter(exchange),
            userIdHeaderKeys
        )
    );
    this.endpoint_execution_span_info = new SpanInfoDto(
        endpoint_execution_span.getTraceId(),
        endpoint_execution_span.getSpanId(),
        endpoint_execution_span.getParentSpanId(),
        String.valueOf(endpoint_execution_span.isSampleable()),
        endpoint_execution_span.getUserId()
    );
}
 
Example 3
Source File: SampleController.java    From wingtips with Apache License 2.0 6 votes vote down vote up
public EndpointSpanInfoDto(HttpServletRequest request, Span endpoint_execution_span, List<String> userIdHeaderKeys) {
    this.parent_span_info = new SpanInfoDto(
        request.getHeader(TraceHeaders.TRACE_ID),
        request.getHeader(TraceHeaders.SPAN_ID),
        request.getHeader(TraceHeaders.PARENT_SPAN_ID),
        request.getHeader(TraceHeaders.TRACE_SAMPLED),
        HttpSpanFactory.getUserIdFromHttpServletRequest(request, userIdHeaderKeys)
    );
    this.endpoint_execution_span_info = new SpanInfoDto(
        endpoint_execution_span.getTraceId(),
        endpoint_execution_span.getSpanId(),
        endpoint_execution_span.getParentSpanId(),
        String.valueOf(endpoint_execution_span.isSampleable()),
        endpoint_execution_span.getUserId()
    );
}
 
Example 4
Source File: VerifyAsyncHttpClientHelperComponentTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
        "true   |   true",
        "true   |   false",
        "false  |   true",
        "false  |   false"
}, splitBy = "\\|")
@Test
public void verify_basic_functionality(boolean surroundWithSubspan, boolean parentSpanExists) throws Exception {
    // given
    AsyncHttpClientHelper asyncClient = AsyncHttpClientHelper.builder()
        .setPerformSubSpanAroundDownstreamCalls(surroundWithSubspan)
        .build();

    String fullUrl = "http://localhost:" + serverPort + TestEndpoint.MATCHING_PATH + "?foo=bar";
    RequestBuilderWrapper rbw = asyncClient.getRequestBuilder(fullUrl, HttpMethod.GET);
    rbw.requestBuilder.setHeader(TestEndpoint.EXPECTED_HEADER_KEY, TestEndpoint.EXPECTED_HEADER_VAL);
    rbw.requestBuilder.setBody(TestEndpoint.EXPECTED_REQUEST_PAYLOAD);

    Deque<Span> distributedTraceStackForCall = null;
    Map<String, String> mdcContextForCall = null;
    Span origSpan = null;

    if (parentSpanExists) {
        origSpan = Tracer.getInstance().startRequestWithRootSpan("overallReqSpan");
        distributedTraceStackForCall = Tracer.getInstance().getCurrentSpanStackCopy();
        mdcContextForCall = MDC.getCopyOfContextMap();
        resetTracing();
    }

    // when
    Response result = asyncClient.executeAsyncHttpRequest(
            rbw, response -> response, distributedTraceStackForCall, mdcContextForCall
    ).join();

    // then
    Span subspan = findSubspan();

    assertThat(result.getStatusCode()).isEqualTo(200);
    assertThat(result.getResponseBody()).isEqualTo(TestEndpoint.RESPONSE_PAYLOAD);

    if (surroundWithSubspan) {
        assertThat(subspan).isNotNull();
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo(subspan.getTraceId());
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo(subspan.getSpanId());
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo(
                String.valueOf(subspan.getParentSpanId())
        );
        verifySubspanTags(subspan, fullUrl, "200", false);
    } else {
        assertThat(subspan).isNull();
    }

    if (parentSpanExists) {
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo(origSpan.getTraceId());
        String expectedParentSpanId = (surroundWithSubspan) ? subspan.getParentSpanId() : "null";
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo(expectedParentSpanId);
        String expectedSpanId = (surroundWithSubspan) ? subspan.getSpanId() : origSpan.getSpanId();
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo(expectedSpanId);
    }

    if (!parentSpanExists && !surroundWithSubspan) {
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo("null");
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo("null");
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo("null");
    }
}
 
Example 5
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void executeAsyncHttpRequest_sets_up_and_executes_call_as_expected(
    boolean performSubspan, boolean currentTracingInfoNull
) {
    // given
    Whitebox.setInternalState(helperSpy, "performSubSpanAroundDownstreamCalls", performSubspan);

    CircuitBreaker<Response> circuitBreakerMock = mock(CircuitBreaker.class);
    doReturn(Optional.of(circuitBreakerMock)).when(helperSpy).getCircuitBreaker(any(RequestBuilderWrapper.class));
    ManualModeTask<Response> cbManualTaskMock = mock(ManualModeTask.class);
    doReturn(cbManualTaskMock).when(circuitBreakerMock).newManualModeTask();

    String url = "http://localhost/some/path";
    String method = "GET";
    BoundRequestBuilder reqMock = mock(BoundRequestBuilder.class);
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(url, method, reqMock, Optional.empty(), false);
    AsyncResponseHandler responseHandlerMock = mock(AsyncResponseHandler.class);

    Span initialSpan = (currentTracingInfoNull) ? null : Tracer.getInstance().startRequestWithRootSpan("foo");
    Deque<Span> initialSpanStack = (currentTracingInfoNull)
                                   ? null
                                   : Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> initialMdc = (currentTracingInfoNull) ? null : MDC.getCopyOfContextMap();
    resetTracingAndMdc();

    // when
    CompletableFuture resultFuture = helperSpy.executeAsyncHttpRequest(
        rbw, responseHandlerMock, initialSpanStack, initialMdc
    );

    // then
    // Verify that the circuit breaker came from the getCircuitBreaker helper method and that its
    //      throwExceptionIfCircuitBreakerIsOpen() method was called.
    verify(helperSpy).getCircuitBreaker(rbw);
    verify(cbManualTaskMock).throwExceptionIfCircuitBreakerIsOpen();

    // Verify that the inner request's execute method was called with a
    //      AsyncCompletionHandlerWithTracingAndMdcSupport for the handler.
    ArgumentCaptor<AsyncHandler> executedHandlerCaptor = ArgumentCaptor.forClass(AsyncHandler.class);
    verify(reqMock).execute(executedHandlerCaptor.capture());
    AsyncHandler executedHandler = executedHandlerCaptor.getValue();
    assertThat(executedHandler).isInstanceOf(AsyncCompletionHandlerWithTracingAndMdcSupport.class);

    // Verify that the AsyncCompletionHandlerWithTracingAndMdcSupport was created with the expected args
    AsyncCompletionHandlerWithTracingAndMdcSupport achwtams =
        (AsyncCompletionHandlerWithTracingAndMdcSupport) executedHandler;
    assertThat(achwtams.completableFutureResponse).isSameAs(resultFuture);
    assertThat(achwtams.responseHandlerFunction).isSameAs(responseHandlerMock);
    assertThat(achwtams.performSubSpanAroundDownstreamCalls).isEqualTo(performSubspan);
    assertThat(achwtams.circuitBreakerManualTask).isEqualTo(Optional.of(cbManualTaskMock));
    if (performSubspan) {
        int initialSpanStackSize = (initialSpanStack == null) ? 0 : initialSpanStack.size();
        assertThat(achwtams.distributedTraceStackToUse).hasSize(initialSpanStackSize + 1);
        Span subspan = (Span) achwtams.distributedTraceStackToUse.peek();
        assertThat(subspan.getSpanName())
            .isEqualTo(initialSpanNameFromStrategy.get());
        if (initialSpan != null) {
            assertThat(subspan.getTraceId()).isEqualTo(initialSpan.getTraceId());
            assertThat(subspan.getParentSpanId()).isEqualTo(initialSpan.getSpanId());
        }
        assertThat(achwtams.mdcContextToUse.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId());
    }
    else {
        assertThat(achwtams.distributedTraceStackToUse).isSameAs(initialSpanStack);
        assertThat(achwtams.mdcContextToUse).isSameAs(initialMdc);
    }

    // Verify that the trace headers were added (or not depending on state).
    Span spanForDownstreamCall = achwtams.getSpanForCall();
    if (initialSpan == null && !performSubspan) {
        assertThat(spanForDownstreamCall).isNull();
        verifyNoMoreInteractions(reqMock);
    }
    else {
        assertThat(spanForDownstreamCall).isNotNull();
        verify(reqMock).setHeader(TraceHeaders.TRACE_SAMPLED,
                                  convertSampleableBooleanToExpectedB3Value(spanForDownstreamCall.isSampleable()));
        verify(reqMock).setHeader(TraceHeaders.TRACE_ID, spanForDownstreamCall.getTraceId());
        verify(reqMock).setHeader(TraceHeaders.SPAN_ID, spanForDownstreamCall.getSpanId());
        if (spanForDownstreamCall.getParentSpanId() == null) {
            verify(reqMock, never()).setHeader(eq(TraceHeaders.PARENT_SPAN_ID), anyString());
        }
        else {
            verify(reqMock).setHeader(TraceHeaders.PARENT_SPAN_ID, spanForDownstreamCall.getParentSpanId());
        }
        verify(reqMock, never()).setHeader(eq(TraceHeaders.SPAN_NAME), anyString());
    }

    // Verify that any subspan had request tagging performed.
    if (performSubspan) {
        strategyRequestTaggingArgs.get().verifyArgs(spanForDownstreamCall, rbw, wingtipsTagAndNamingAdapterMock);
    }
}
 
Example 6
Source File: VerifyAsyncHttpClientHelperComponentTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void verify_basic_functionality(boolean surroundWithSubspan, boolean parentSpanExists) throws Exception {
    // given
    AsyncHttpClientHelper asyncClient = new AsyncHttpClientHelper(surroundWithSubspan);

    String fullUrl = "http://localhost:" + serverPort + TestEndpoint.MATCHING_PATH + "?foo=bar";
    RequestBuilderWrapper rbw = asyncClient.getRequestBuilder(fullUrl, HttpMethod.GET);
    rbw.requestBuilder.setHeader(TestEndpoint.EXPECTED_HEADER_KEY, TestEndpoint.EXPECTED_HEADER_VAL);
    rbw.requestBuilder.setBody(TestEndpoint.EXPECTED_REQUEST_PAYLOAD);

    Deque<Span> distributedTraceStackForCall = null;
    Map<String, String> mdcContextForCall = null;
    Span origSpan = null;

    if (parentSpanExists) {
        origSpan = Tracer.getInstance().startRequestWithRootSpan("overallReqSpan");
        distributedTraceStackForCall = Tracer.getInstance().getCurrentSpanStackCopy();
        mdcContextForCall = MDC.getCopyOfContextMap();
        resetTracing();
    }

    // when
    Response result = asyncClient.executeAsyncHttpRequest(
        rbw, response -> response, distributedTraceStackForCall, mdcContextForCall
    ).join();

    // then
    Span subspan = findSubspan();

    assertThat(result.getStatusCode()).isEqualTo(200);
    assertThat(result.getResponseBody()).isEqualTo(TestEndpoint.RESPONSE_PAYLOAD);

    if (surroundWithSubspan) {
        assertThat(subspan).isNotNull();
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo(subspan.getTraceId());
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo(subspan.getSpanId());
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo(
            String.valueOf(subspan.getParentSpanId())
        );
        verifySubspanTags(subspan, fullUrl, "200", false);
    }
    else {
        assertThat(subspan).isNull();
    }

    if (parentSpanExists) {
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo(origSpan.getTraceId());
        String expectedParentSpanId = (surroundWithSubspan) ? subspan.getParentSpanId() : "null";
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo(expectedParentSpanId);
        String expectedSpanId = (surroundWithSubspan) ? subspan.getSpanId() : origSpan.getSpanId();
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo(expectedSpanId);
    }

    if (!parentSpanExists && !surroundWithSubspan) {
        assertThat(result.getHeader(TraceHeaders.TRACE_ID)).isEqualTo("null");
        assertThat(result.getHeader(TraceHeaders.SPAN_ID)).isEqualTo("null");
        assertThat(result.getHeader(TraceHeaders.PARENT_SPAN_ID)).isEqualTo("null");
    }
}
 
Example 7
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void executeAsyncHttpRequest_sets_up_and_executes_call_as_expected(
    boolean performSubspan, boolean currentTracingInfoNull
) {
    // given
    Whitebox.setInternalState(helperSpy, "performSubSpanAroundDownstreamCalls", performSubspan);

    CircuitBreaker<Response> circuitBreakerMock = mock(CircuitBreaker.class);
    doReturn(Optional.of(circuitBreakerMock)).when(helperSpy).getCircuitBreaker(any(RequestBuilderWrapper.class));
    ManualModeTask<Response> cbManualTaskMock = mock(ManualModeTask.class);
    doReturn(cbManualTaskMock).when(circuitBreakerMock).newManualModeTask();

    String url = "http://localhost/some/path";
    String method = "GET";
    AsyncHttpClient.BoundRequestBuilder reqMock = mock(AsyncHttpClient.BoundRequestBuilder.class);
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(url, method, reqMock, Optional.empty(), false);
    AsyncResponseHandler responseHandlerMock = mock(AsyncResponseHandler.class);

    Span initialSpan = (currentTracingInfoNull) ? null : Tracer.getInstance().startRequestWithRootSpan("foo");
    Deque<Span> initialSpanStack = (currentTracingInfoNull)
                                   ? null
                                   : Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> initialMdc = (currentTracingInfoNull) ? null : MDC.getCopyOfContextMap();
    resetTracingAndMdc();

    // when
    CompletableFuture resultFuture = helperSpy.executeAsyncHttpRequest(
        rbw, responseHandlerMock, initialSpanStack, initialMdc
    );

    // then
    // Verify that the circuit breaker came from the getCircuitBreaker helper method and that its
    //      throwExceptionIfCircuitBreakerIsOpen() method was called.
    verify(helperSpy).getCircuitBreaker(rbw);
    verify(cbManualTaskMock).throwExceptionIfCircuitBreakerIsOpen();

    // Verify that the inner request's execute method was called with a
    //      AsyncCompletionHandlerWithTracingAndMdcSupport for the handler.
    ArgumentCaptor<AsyncHandler> executedHandlerCaptor = ArgumentCaptor.forClass(AsyncHandler.class);
    verify(reqMock).execute(executedHandlerCaptor.capture());
    AsyncHandler executedHandler = executedHandlerCaptor.getValue();
    assertThat(executedHandler).isInstanceOf(AsyncCompletionHandlerWithTracingAndMdcSupport.class);

    // Verify that the AsyncCompletionHandlerWithTracingAndMdcSupport was created with the expected args
    AsyncCompletionHandlerWithTracingAndMdcSupport achwtams =
        (AsyncCompletionHandlerWithTracingAndMdcSupport) executedHandler;
    assertThat(achwtams.completableFutureResponse).isSameAs(resultFuture);
    assertThat(achwtams.responseHandlerFunction).isSameAs(responseHandlerMock);
    assertThat(achwtams.performSubSpanAroundDownstreamCalls).isEqualTo(performSubspan);
    assertThat(achwtams.circuitBreakerManualTask).isEqualTo(Optional.of(cbManualTaskMock));
    if (performSubspan) {
        int initialSpanStackSize = (initialSpanStack == null) ? 0 : initialSpanStack.size();
        assertThat(achwtams.distributedTraceStackToUse).hasSize(initialSpanStackSize + 1);
        Span subspan = (Span) achwtams.distributedTraceStackToUse.peek();
        assertThat(subspan.getSpanName())
            .isEqualTo(initialSpanNameFromStrategy.get());
        if (initialSpan != null) {
            assertThat(subspan.getTraceId()).isEqualTo(initialSpan.getTraceId());
            assertThat(subspan.getParentSpanId()).isEqualTo(initialSpan.getSpanId());
        }
        assertThat(achwtams.mdcContextToUse.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId());
    }
    else {
        assertThat(achwtams.distributedTraceStackToUse).isSameAs(initialSpanStack);
        assertThat(achwtams.mdcContextToUse).isSameAs(initialMdc);
    }

    // Verify that the trace headers were added (or not depending on state).
    Span spanForDownstreamCall = achwtams.getSpanForCall();
    if (initialSpan == null && !performSubspan) {
        assertThat(spanForDownstreamCall).isNull();
        verifyNoMoreInteractions(reqMock);
    }
    else {
        assertThat(spanForDownstreamCall).isNotNull();
        verify(reqMock).setHeader(TraceHeaders.TRACE_SAMPLED,
                                  convertSampleableBooleanToExpectedB3Value(spanForDownstreamCall.isSampleable()));
        verify(reqMock).setHeader(TraceHeaders.TRACE_ID, spanForDownstreamCall.getTraceId());
        verify(reqMock).setHeader(TraceHeaders.SPAN_ID, spanForDownstreamCall.getSpanId());
        if (spanForDownstreamCall.getParentSpanId() == null) {
            verify(reqMock, never()).setHeader(eq(TraceHeaders.PARENT_SPAN_ID), anyString());
        }
        else {
            verify(reqMock).setHeader(TraceHeaders.PARENT_SPAN_ID, spanForDownstreamCall.getParentSpanId());
        }
        verify(reqMock, never()).setHeader(eq(TraceHeaders.SPAN_NAME), anyString());
    }

    // Verify that any subspan had request tagging performed.
    if (performSubspan) {
        strategyRequestTaggingArgs.get().verifyArgs(spanForDownstreamCall, rbw, wingtipsTagAndNamingAdapterMock);
    }
}
 
Example 8
Source File: WingtipsToLightStepLifecycleListener.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@Override
public void spanCompleted(Span wingtipsSpan) {
    try {
        String operationName = wingtipsSpan.getSpanName();
        long startTimeMicros = wingtipsSpan.getSpanStartTimeEpochMicros();

        // Given we should only be in this method on span completion, we are not going to wrap this conversion in a
        // try/catch. duration should be set on the Wingtips span.
        long durationMicros = TimeUnit.NANOSECONDS.toMicros(wingtipsSpan.getDurationNanos());
        long stopTimeMicros = startTimeMicros + durationMicros;

        // Sanitize the wingtips trace/span/parent IDs if necessary. This guarantees we can convert them to
        //      longs as required by LightStep.
        String wtSanitizedSpanId = sanitizeIdIfNecessary(wingtipsSpan.getSpanId(), false);
        String wtSanitizedTraceId = sanitizeIdIfNecessary(wingtipsSpan.getTraceId(), true);
        String wtSanitizedParentId = sanitizeIdIfNecessary(wingtipsSpan.getParentSpanId(), false);

        // Handle the common SpanBuilder settings.
        SpanBuilder lsSpanBuilder = (SpanBuilder) (
            tracer.buildSpan(operationName)
                  .withStartTimestamp(wingtipsSpan.getSpanStartTimeEpochMicros())
                  .ignoreActiveSpan()
                  .withTag("wingtips.span_id", wingtipsSpan.getSpanId())
                  .withTag("wingtips.trace_id", wingtipsSpan.getTraceId())
                  .withTag("wingtips.parent_id", String.valueOf(wingtipsSpan.getParentSpanId()))
                  .withTag("span.type", wingtipsSpan.getSpanPurpose().name())
        );

        // Force the LightStep span to have a Trace ID and Span ID matching the Wingtips span.
        //      NOTE: LightStep requires Ids to be longs, so we convert the sanitized wingtips trace/span IDs.
        long lsSpanId = TraceAndSpanIdGenerator.unsignedLowerHexStringToLong(wtSanitizedSpanId);
        long lsTraceId = TraceAndSpanIdGenerator.unsignedLowerHexStringToLong(wtSanitizedTraceId);
        lsSpanBuilder.withTraceIdAndSpanId(lsTraceId, lsSpanId);

        // Handle the parent ID / parent context SpanBuilder settings.
        if (wingtipsSpan.getParentSpanId() != null) {
            long lsParentId = TraceAndSpanIdGenerator.unsignedLowerHexStringToLong(wtSanitizedParentId);

            SpanContext lsSpanContext = new SpanContext(lsTraceId, lsParentId);

            lsSpanBuilder = (SpanBuilder)(lsSpanBuilder.asChildOf(lsSpanContext));
        }

        // Start the OT span and set logs and tags from the wingtips span.
        io.opentracing.Span lsSpan = lsSpanBuilder.start();

        for (Span.TimestampedAnnotation wingtipsAnnotation : wingtipsSpan.getTimestampedAnnotations()) {
            lsSpan.log(wingtipsAnnotation.getTimestampEpochMicros(), wingtipsAnnotation.getValue());
        }

        for (Map.Entry<String, String> wtTag : wingtipsSpan.getTags().entrySet()) {
            lsSpan.setTag(wtTag.getKey(), wtTag.getValue());
        }

        // Add some custom boolean tags if any of the IDs had to be sanitized. The raw unsanitized ID will be
        //      available via the wingtips.*_id tags.
        if (!wtSanitizedSpanId.equals(wingtipsSpan.getSpanId())) {
            lsSpan.setTag("wingtips.span_id.invalid", true);
            wingtipsSpan.putTag("sanitized_span_id", wtSanitizedSpanId);
        }
        if (!wtSanitizedTraceId.equals(wingtipsSpan.getTraceId())) {
            lsSpan.setTag("wingtips.trace_id.invalid", true);
            wingtipsSpan.putTag("sanitized_trace_id", wtSanitizedTraceId);
        }
        if (wtSanitizedParentId != null && !wtSanitizedParentId.equals(wingtipsSpan.getParentSpanId())) {
            lsSpan.setTag("wingtips.parent_id.invalid", true);
            wingtipsSpan.putTag("sanitized_parent_id", wtSanitizedParentId);
        }

        // on finish, the tracer library initialized on the creation of this listener will cache and transport the span
        // data to the LightStep Satellite.
        lsSpan.finish(stopTimeMicros);
    } catch (Exception ex) {
        long currentBadSpanCount = spanHandlingErrorCounter.incrementAndGet();
        // Adopted from WingtipsToZipkinLifecycleListener from Wingtips-Zipkin2 plugin.
        // Only log once every MIN_SPAN_HANDLING_ERROR_LOG_INTERVAL_MILLIS time interval to prevent log spam from a
        // malicious (or broken) caller.
        long currentTimeMillis = System.currentTimeMillis();
        long timeSinceLastLogMsgMillis = currentTimeMillis - lastSpanHandlingErrorLogTimeEpochMillis;

        if (timeSinceLastLogMsgMillis >= MIN_SPAN_HANDLING_ERROR_LOG_INTERVAL_MILLIS) {
            // We're not synchronizing the read and write to lastSpanHandlingErrorLogTimeEpochMillis, and that's ok.
            // If we get a few extra log messages due to a race condition it's not the end of the world - we're
            // still satisfying the goal of not allowing a malicious caller to endlessly spam the logs.
            lastSpanHandlingErrorLogTimeEpochMillis = currentTimeMillis;

            lightStepToWingtipsLogger.warn(
                    "There have been {} spans that were not LightStep compatible, or that experienced an error "
                    + "during span handling. Latest example: "
                    + "wingtips_span_with_error=\"{}\", conversion_or_handling_error=\"{}\"",
                    currentBadSpanCount, wingtipsSpan.toKeyValueString(), ex.toString()
            );
        }
    }
}
 
Example 9
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
private SpanInfoDto spanInfoDtoFromSpan(Span span) {
    return new SpanInfoDto(
        span.getTraceId(), span.getSpanId(), span.getParentSpanId(), String.valueOf(span.isSampleable()),
        span.getUserId()
    );
}
 
Example 10
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
private SpanInfoDto spanInfoDtoFromSpan(Span span) {
    return new SpanInfoDto(
        span.getTraceId(), span.getSpanId(), span.getParentSpanId(), String.valueOf(span.isSampleable()),
        span.getUserId()
    );
}
 
Example 11
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
private SpanInfoDto spanInfoDtoFromSpan(Span span) {
    return new SpanInfoDto(
        span.getTraceId(), span.getSpanId(), span.getParentSpanId(), String.valueOf(span.isSampleable()),
        span.getUserId()
    );
}
 
Example 12
Source File: HttpRequestTracingUtils.java    From wingtips with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the tracing headers on the given {@link HttpObjectForPropagation} with values from the given {@link Span}.
 * Does nothing if any of the given arguments are null (i.e. it is safe to pass null, but nothing will happen).
 *
 * <p>This method conforms to the <a href="https://github.com/openzipkin/b3-propagation">B3 propagation spec</a>.
 *
 * @param httpObjectForPropagation The {@link HttpObjectForPropagation} to set tracing headers on. Can be null -
 * if this is null then this method will do nothing.
 * @param span The {@link Span} to get the tracing info from to set on the headers. Can be null - if this is null
 * then this method will do nothing.
 */
public static void propagateTracingHeaders(HttpObjectForPropagation httpObjectForPropagation, Span span) {
    if (span == null || httpObjectForPropagation == null)
        return;

    httpObjectForPropagation.setHeader(TRACE_ID, span.getTraceId());
    httpObjectForPropagation.setHeader(SPAN_ID, span.getSpanId());
    httpObjectForPropagation.setHeader(TRACE_SAMPLED, (span.isSampleable()) ? "1" : "0");
    if (span.getParentSpanId() != null)
        httpObjectForPropagation.setHeader(PARENT_SPAN_ID, span.getParentSpanId());
}