brave.Tracer.SpanInScope Java Examples

The following examples show how to use brave.Tracer.SpanInScope. 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: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void send(Message message, int deliveryMode, int priority, long timeToLive)
  throws JMSException {
  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span); // animal-sniffer mistakes this for AutoCloseable
  Throwable error = null;
  try {
    delegate.send(message, deliveryMode, priority, timeToLive);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #2
Source File: TracerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void withSpanInScope_clear() {
  Span parent = tracer.newTrace();

  try (SpanInScope wsParent = tracer.withSpanInScope(parent)) {
    try (SpanInScope clearScope = tracer.withSpanInScope(null)) {
      assertThat(tracer.currentSpan())
        .isNull();
      assertThat(tracer.currentSpanCustomizer())
        .isEqualTo(NoopSpanCustomizer.INSTANCE);
    }

    // old parent reverted
    assertThat(tracer.currentSpan())
      .isEqualTo(parent);
  }
}
 
Example #3
Source File: TracerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void withSpanInScope_nested() {
  Span parent = tracer.newTrace();

  try (SpanInScope wsParent = tracer.withSpanInScope(parent)) {

    Span child = tracer.newChild(parent.context());
    try (SpanInScope wsChild = tracer.withSpanInScope(child)) {
      assertThat(tracer.currentSpan())
        .isEqualTo(child);
    }

    // old parent reverted
    assertThat(tracer.currentSpan())
      .isEqualTo(parent);
  }
}
 
Example #4
Source File: TracingProtocolExec.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public CloseableHttpResponse execute(HttpRoute route,
  org.apache.http.client.methods.HttpRequestWrapper req,
  HttpClientContext context, HttpExecutionAware execAware)
  throws IOException, HttpException {
  HttpRequestWrapper request = new HttpRequestWrapper(req, context.getTargetHost());
  Span span = tracer.nextSpan(httpSampler, request);
  context.setAttribute(Span.class.getName(), span);

  CloseableHttpResponse response = null;
  Throwable error = null;
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    return response = protocolExec.execute(route, req, context, execAware);
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleReceive(new HttpResponseWrapper(response, context, error), span);
  }
}
 
Example #5
Source File: BraveTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatProvidedSpanIsNotDetachedWhenActiveUsingAsyncClient() throws Exception {
    final WebClient client = createWebClient("/bookstore/books", new BraveClientProvider(brave));
    final Span span = brave.tracer().nextSpan().name("test span").start();

    try (SpanInScope scope = brave.tracer().withSpanInScope(span)) {
        final Future<Response> f = client.async().get();

        final Response r = f.get(1, TimeUnit.SECONDS);
        assertEquals(Status.OK.getStatusCode(), r.getStatus());
        assertThat(brave.tracer().currentSpan().context().spanId(), equalTo(span.context().spanId()));

        assertThat(TestSpanReporter.getAllSpans().size(), equalTo(3));
        assertThat(TestSpanReporter.getAllSpans().get(0).name(), equalTo("get books"));
        assertThat(TestSpanReporter.getAllSpans().get(1).name(), equalTo("get /bookstore/books"));
        assertThat(TestSpanReporter.getAllSpans().get(2).name(), equalTo("get " + client.getCurrentURI()));
    } finally {
        span.finish();
    }

    // Await till flush happens, usually a second is enough
    await().atMost(Duration.ofSeconds(1L)).until(()-> TestSpanReporter.getAllSpans().size() == 4);

    assertThat(TestSpanReporter.getAllSpans().size(), equalTo(4));
    assertThat(TestSpanReporter.getAllSpans().get(3).name(), equalTo("test span"));
}
 
Example #6
Source File: BraveTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatProvidedSpanIsNotClosedWhenActive() throws MalformedURLException {
    final WebClient client = createWebClient("/bookstore/books", new BraveClientProvider(brave));
    final Span span = brave.tracer().nextSpan().name("test span").start();

    try (SpanInScope scope = brave.tracer().withSpanInScope(span)) {
        final Response r = client.get();
        assertEquals(Status.OK.getStatusCode(), r.getStatus());

        assertThat(TestSpanReporter.getAllSpans().size(), equalTo(3));
        assertThat(TestSpanReporter.getAllSpans().get(0).name(), equalTo("get books"));
        assertThat(TestSpanReporter.getAllSpans().get(0).parentId(), not(nullValue()));
        assertThat(TestSpanReporter.getAllSpans().get(1).name(), equalTo("get /bookstore/books"));
        assertThat(TestSpanReporter.getAllSpans().get(2).name(), equalTo("get " + client.getCurrentURI()));
    } finally {
        span.finish();
    }

    // Await till flush happens, usually a second is enough
    await().atMost(Duration.ofSeconds(1L)).until(()-> TestSpanReporter.getAllSpans().size() == 4);

    assertThat(TestSpanReporter.getAllSpans().size(), equalTo(4));
    assertThat(TestSpanReporter.getAllSpans().get(3).name(), equalTo("test span"));
}
 
Example #7
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void send(Message message) throws JMSException {
  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    delegate.send(message);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #8
Source File: BraveTracerContext.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T continueSpan(final Traceable<T> traceable) throws Exception {
    SpanInScope scope = null;
    
    if (tracer.currentSpan() == null && continuationSpan != null) {
        scope = tracer.withSpanInScope(continuationSpan);
    }

    try { //NOPMD
        return traceable.call(new BraveTracerContext(brave));
    } finally {
        if (continuationSpan != null && scope != null) {
            scope.close();
        }
    }
}
 
Example #9
Source File: AbstractBraveClientProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected TraceScopeHolder<TraceScope> startTraceSpan(final Map<String, List<String>> requestHeaders,
        URI uri, String method) {

    final Request request = HttpAdapterFactory.request(requestHeaders, uri, method);
    final HttpClientAdapter<Request, ?> adapter = HttpClientAdapterFactory.create(request);
    
    final HttpClientHandler<Request, ?> handler = HttpClientHandler.create(brave, adapter);
    final Span span = handler.handleSend(
        brave
            .tracing()
            .propagation()
            .injector(inject(requestHeaders)), 
        request);

    // In case of asynchronous client invocation, the span should be detached as JAX-RS
    // client request / response filters are going to be executed in different threads.
    SpanInScope scope = null;
    if (!isAsyncInvocation() && span != null) {
        scope = brave.tracing().tracer().withSpanInScope(span);
    }

    return new TraceScopeHolder<TraceScope>(new TraceScope(span, scope), scope == null /* detached */);
}
 
Example #10
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
void send(SendDestination sendDestination, Destination destination, Message message)
  throws JMSException {
  Span span = createAndStartProducerSpan(message, destination);
  SpanInScope ws = tracer.withSpanInScope(span); // animal-sniffer mistakes this for AutoCloseable
  Throwable error = null;
  try {
    sendDestination.apply(delegate, destination, message);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #11
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority,
  long timeToLive) throws JMSException {
  Span span = createAndStartProducerSpan(message, destination);
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    delegate.send(destination, message, deliveryMode, priority, timeToLive);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #12
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@JMS2_0
public void send(Message message, CompletionListener completionListener) throws JMSException {
  Destination destination = destination(message);
  Span span = createAndStartProducerSpan(message, destination);
  SpanInScope ws = tracer.withSpanInScope(span); // animal-sniffer mistakes this for AutoCloseable
  Throwable error = null;
  try {
    delegate.send(message, TracingCompletionListener.create(completionListener, destination, span, current));
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error).finish();
    ws.close();
  }
}
 
Example #13
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@JMS2_0 public void send(Destination destination, Message message,
  CompletionListener completionListener) throws JMSException {
  Span span = createAndStartProducerSpan(message, destination);
  completionListener = TracingCompletionListener.create(completionListener, destination, span, current);
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    delegate.send(destination, message, completionListener);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error).finish();
    ws.close();
  }
}
 
Example #14
Source File: ZipkinTracingHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"try", "unused"})
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Span span = tracingDelegate.createSpan(invocation);
  try (SpanInScope scope = tracer.tracer().withSpanInScope(span)) {
    LOGGER.debug("{}: Generated tracing span for {}",
        tracingDelegate.name(),
        invocation.getOperationName());

    invocation.next(onResponse(invocation, asyncResp, span));
  } catch (Exception e) {
    LOGGER.debug("{}: Failed invocation on {}",
        tracingDelegate.name(),
        invocation.getOperationName(),
        e);

    tracingDelegate.onResponse(span, null, e);
    throw e;
  }
}
 
Example #15
Source File: TracingMessageListener.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void onMessage(Message message) {
  Span listenerSpan = startMessageListenerSpan(message);
  SpanInScope ws = tracer.withSpanInScope(listenerSpan);
  Throwable error = null;
  try {
    delegate.onMessage(message);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) listenerSpan.error(error);
    listenerSpan.finish();
    ws.close();
  }
}
 
Example #16
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override
public void publish(Topic topic, Message message, int deliveryMode, int priority, long timeToLive)
  throws JMSException {
  checkTopicPublisher();
  TopicPublisher tp = (TopicPublisher) delegate;

  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    tp.publish(topic, message, deliveryMode, priority, timeToLive);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #17
Source File: SendMessageTracingRequestHandler.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
private void handleSendMessageBatchRequest(SendMessageBatchRequest request) {
  TraceContext maybeParent = currentTraceContext.get();

  Span span;
  if (maybeParent == null) {
    span = tracer.nextSpan();
  } else {
    // If we have a span in scope assume headers were cleared before
    span = tracer.newChild(maybeParent);
  }

  span.name("publish-batch").remoteServiceName("amazon-sqs").start();
  try (SpanInScope scope = tracer.withSpanInScope(span)) {
    for (SendMessageBatchRequestEntry entry : request.getEntries()) {
      injectPerMessage(request.getQueueUrl(), entry.getMessageAttributes());
    }
  } finally {
    span.finish();
  }
}
 
Example #18
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void publish(Message message, int deliveryMode, int priority, long timeToLive)
  throws JMSException {
  checkTopicPublisher();
  TopicPublisher tp = (TopicPublisher) delegate;

  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    tp.publish(message, deliveryMode, priority, timeToLive);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #19
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void publish(Message message) throws JMSException {
  checkTopicPublisher();
  TopicPublisher tp = (TopicPublisher) delegate;

  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    tp.publish(message);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #20
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override
public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive)
  throws JMSException {
  checkQueueSender();
  QueueSender qs = (QueueSender) delegate;
  Span span = createAndStartProducerSpan(message, destination(message));
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    qs.send(queue, message, deliveryMode, priority, timeToLive);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error);
    span.finish();
    ws.close();
  }
}
 
Example #21
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@JMS2_0 public void send(Destination destination, Message message, int deliveryMode, int priority,
  long timeToLive, CompletionListener completionListener) throws JMSException {
  Span span = createAndStartProducerSpan(message, destination);
  completionListener = TracingCompletionListener.create(completionListener, destination, span, current);
  SpanInScope ws = tracer.withSpanInScope(span);
  Throwable error = null;
  try {
    delegate.send(destination, message, deliveryMode, priority, timeToLive, completionListener);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error).finish();
    ws.close();
  }
}
 
Example #22
Source File: TracingMessageProducer.java    From brave with Apache License 2.0 6 votes vote down vote up
@JMS2_0 public void send(Message message, int deliveryMode, int priority, long timeToLive,
  CompletionListener completionListener) throws JMSException {
  Destination destination = destination(message);
  Span span = createAndStartProducerSpan(message, destination);
  completionListener = TracingCompletionListener.create(completionListener, destination, span, current);
  SpanInScope ws = tracer.withSpanInScope(span); // animal-sniffer mistakes this for AutoCloseable
  Throwable error = null;
  try {
    delegate.send(message, deliveryMode, priority, timeToLive, completionListener);
  } catch (Throwable t) {
    propagateIfFatal(t);
    error = t;
    throw t;
  } finally {
    if (error != null) span.error(error).finish();
    ws.close();
  }
}
 
Example #23
Source File: TracingDispatcher.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public MockResponse dispatch(RecordedRequest req) throws InterruptedException {
  RecordedRequestWrapper request = new RecordedRequestWrapper(req);
  Span span = handler.handleReceive(request);
  MockResponse response = null;
  Throwable error = null;
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    return response = delegate.dispatch(req);
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleSend(new MockResponseWrapper(request, response, error), span);
  }
}
 
Example #24
Source File: TracerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void toString_withSpanInScope() {
  TraceContext context = TraceContext.newBuilder().traceId(1L).spanId(10L).sampled(true).build();
  try (SpanInScope ws = tracer.withSpanInScope(tracer.toSpan(context))) {
    assertThat(tracer.toString()).hasToString(
      "Tracer{currentSpan=0000000000000001/000000000000000a, spanHandler=[TestSpanHandler{[]}, OrphanTracker{}]}"
    );
  }
}
 
Example #25
Source File: TracingInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
  RequestWrapper request = new RequestWrapper(chain.request());
  Span span = handler.handleSend(request);
  Response response = null;
  Throwable error = null;
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    return response = chain.proceed(request.build());
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleReceive(new ResponseWrapper(response, error), span);
  }
}
 
Example #26
Source File: TracingExceptionListener.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void onException(JMSException exception) {
  Span span = tracer.currentSpan();
  if (span == null) {
    delegate.onException(exception);
    return;
  }
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    delegate.onException(exception);
  } finally {
    span.error(exception);
  }
}
 
Example #27
Source File: CurrentSpanCustomizerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void annotate() {
  span.start();
  try (SpanInScope ws = tracing.tracer().withSpanInScope(span)) {
    spanCustomizer.annotate("foo");
  }
  span.flush();

  assertThat(spans.get(0).annotations())
    .extracting(Map.Entry::getValue)
    .containsExactly("foo");
}
 
Example #28
Source File: CurrentSpanCustomizerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void tag() {
  span.start();
  try (SpanInScope ws = tracing.tracer().withSpanInScope(span)) {
    spanCustomizer.tag("foo", "bar");
  }
  span.flush();

  assertThat(spans).flatExtracting(s -> s.tags().entrySet())
    .containsExactly(entry("foo", "bar"));
}
 
Example #29
Source File: CurrentSpanCustomizerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void name() {
  span.start();
  try (SpanInScope ws = tracing.tracer().withSpanInScope(span)) {
    spanCustomizer.name("newname");
  }
  span.flush();

  assertThat(spans).extracting(MutableSpan::name)
    .containsExactly("newname");
}
 
Example #30
Source File: NoopSpanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void equals_lazySpan_notSameContext() {
  Span current;
  try (SpanInScope ws = tracer.withSpanInScope(tracer.newTrace())) {
    current = tracer.currentSpan();
  }

  assertThat(span).isNotEqualTo(current);
}