Java Code Examples for io.opentracing.Scope#close()

The following examples show how to use io.opentracing.Scope#close() . 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: ThresholdLogTracerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPropagateBaggageToChild() {
    Scope parent = tracer.buildSpan("parent").startActive(true);
    parent.span().setBaggageItem("baggage", "item");
    Scope child = tracer.buildSpan("child").startActive(true);

    fakeWork();

    assertEquals(0, tracer.reportedSpans().size());
    child.close();

    assertEquals(1, tracer.reportedSpans().size());
    parent.close();

    assertEquals(2, tracer.reportedSpans().size());
    for (Span finished : tracer.reportedSpans()) {
        assertTrue(((ThresholdLogSpan) finished).durationMicros() > 0);
        assertEquals("item", finished.getBaggageItem("baggage"));
    }
}
 
Example 2
Source File: TracingHandlerInterceptor.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                            Object handler, Exception ex) {

    if (!isTraced(httpServletRequest)) {
        return;
    }

    Span span = tracer.activeSpan();
    for (HandlerInterceptorSpanDecorator decorator : decorators) {
        decorator.onAfterCompletion(httpServletRequest, httpServletResponse, handler, ex, span);
    }
    Deque<Scope> scopeStack = getScopeStack(httpServletRequest);
    if(scopeStack.size() > 0) {
        Scope scope = scopeStack.pop();
        scope.close();
    }
    if (httpServletRequest.getAttribute(IS_ERROR_HANDLING_SPAN) != null) {
        httpServletRequest.removeAttribute(IS_ERROR_HANDLING_SPAN);
        span.finish();
    }
}
 
Example 3
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Fulfill and complete the response observable.
 *
 * When called directly, this method completes on the event loop, but it can also be used in a callback (see
 * {@link #scheduleDirect(CoreScheduler, CouchbaseResponse, Subject)} for example.
 */
private void completeResponse(final CouchbaseResponse response,
    final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
    // Noone is listening anymore, handle tracing and/or orphan reporting
    // depending on if enabled or not.
    CouchbaseRequest request = response.request();
    if (request != null && !request.isActive()) {
        if (env().operationTracingEnabled() && request.span() != null) {
            Scope scope = env().tracer().scopeManager()
                    .activate(request.span(), true);
            scope.span().setBaggageItem("couchbase.orphan", "true");
            scope.close();
        }
        if (env().orphanResponseReportingEnabled()) {
            env().orphanResponseReporter().report(response);
        }
    }

    try {
        observable.onNext(response);
        observable.onCompleted();
    } catch (Exception ex) {
        LOGGER.warn("Caught exception while onNext on observable", ex);
        observable.onError(ex);
    }
}
 
Example 4
Source File: ThresholdLogTracerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCompleteSimpleSpanOnClose() {
    assertNull(tracer.activeSpan());
    Scope scope = tracer.buildSpan("span").startActive(false);
    assertNotNull(tracer.activeSpan());
    fakeWork();
    scope.close();
    assertNull(tracer.activeSpan());

    assertEquals(0, tracer.reportedSpans().size());

    scope.span().finish();
    assertNull(tracer.activeSpan());

    assertEquals(1, tracer.reportedSpans().size());
    Span finished = tracer.reportedSpans().remove(0);
    assertEquals("span", ((ThresholdLogSpan)finished).operationName());
    assertTrue(((ThresholdLogSpan) finished).durationMicros() > 0);
}
 
Example 5
Source File: TracedScheduledExecutorServiceTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void scheduleRunnableTest() throws InterruptedException {
	ScheduledExecutorService executorService = toTraced(Executors.newScheduledThreadPool(NUMBER_OF_THREADS));

	MockSpan parentSpan = mockTracer.buildSpan("foo").start();
	Scope scope = mockTracer.scopeManager().activate(parentSpan);
	executorService.schedule(new TestRunnable(), 300, TimeUnit.MILLISECONDS);
	scope.close();

	countDownLatch.await();
	assertParentSpan(parentSpan);
	assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 6
Source File: ThresholdLogTracerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCompleteSimpleSpanOnClose() {
    assertNull(tracer.activeSpan());
    Scope scope = tracer.buildSpan("span").startActive(true);
    assertNotNull(tracer.activeSpan());
    fakeWork();
    scope.close();
    assertNull(tracer.activeSpan());

    assertEquals(1, tracer.reportedSpans().size());
    Span finished = tracer.reportedSpans().remove(0);
    assertEquals("span", ((ThresholdLogSpan)finished).operationName());
    assertTrue(((ThresholdLogSpan) finished).durationMicros() > 0);
}
 
Example 7
Source File: TracedRunnableTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedRunnable() throws InterruptedException {
  MockSpan parentSpan = mockTracer.buildSpan("foo").start();
  Scope scope = mockTracer.scopeManager().activate(parentSpan);

  Thread thread = createThread(toTraced(new TestRunnable()));
  thread.start();
  thread.join();
  scope.close();

  assertParentSpan(parentSpan);
  assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 8
Source File: OpenTracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
  Scope scope = tracer.scopeManager().active();
  if (scope == null) {
    return;
  }

  log.trace(String.format("Completed sending and current span is %s", scope.span()));
  handleException(ex, scope.span());
  log.trace("Closing messaging span scope " + scope);
  scope.close();
  log.trace(String.format("Messaging span scope %s successfully closed", scope));
}
 
Example 9
Source File: TracedExecutorServiceTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubmitRunnableTyped() throws InterruptedException {
  ExecutorService executorService = toTraced(Executors.newFixedThreadPool(NUMBER_OF_THREADS));

  MockSpan parentSpan = mockTracer.buildSpan("foo").start();
  Scope scope = mockTracer.scopeManager().activate(parentSpan);
  executorService.submit(new TestRunnable(), new Object());
  scope.close();

  countDownLatch.await();
  assertParentSpan(parentSpan);
  assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 10
Source File: OpenTracingBridgeTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testInjectExtract() {
    final String traceId = "0af7651916cd43dd8448eb211c80319c";
    final String parentId = "b9c7c989f97918e1";

    Span otSpan = apmTracer.buildSpan("span")
        .asChildOf(apmTracer.extract(Format.Builtin.TEXT_MAP,
            new TextMapAdapter(Map.of(
                TraceContext.W3C_TRACE_PARENT_TEXTUAL_HEADER_NAME, "00-" + traceId + "-" + parentId + "-01",
                "User-Agent", "curl"))))
        .start();
    final Scope scope = apmTracer.activateSpan(otSpan);
    Transaction transaction = tracer.currentTransaction();
    assertThat(transaction).isNotNull();
    assertThat(transaction.isSampled()).isTrue();
    assertThat(transaction.getTraceContext().getTraceId().toString()).isEqualTo(traceId);
    assertThat(transaction.getTraceContext().getParentId().toString()).isEqualTo(parentId);
    Span span = apmTracer.activeSpan();
    assertThat(span).isNotNull();
    assertThat(span.getBaggageItem("User-Agent")).isNull();

    final HashMap<String, String> map = new HashMap<>();
    apmTracer.inject(otSpan.context(), Format.Builtin.TEXT_MAP, new TextMapAdapter(map));
    final TraceContext injectedContext = TraceContext.with64BitId(tracer);
    assertThat(TraceContext.<Map<String, String>>getFromTraceContextTextHeaders().asChildOf(injectedContext, map, TextHeaderMapAccessor.INSTANCE)).isTrue();
    assertThat(injectedContext.getTraceId().toString()).isEqualTo(traceId);
    assertThat(injectedContext.getParentId()).isEqualTo(transaction.getTraceContext().getId());
    assertThat(injectedContext.isSampled()).isTrue();
    assertThat(map.get("User-Agent")).isNull();

    scope.close();
    otSpan.finish();
    assertThat(reporter.getTransactions()).hasSize(1);
}
 
Example 11
Source File: TracedExecutorServiceTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAnyTimeUnit() throws InterruptedException, ExecutionException, TimeoutException {
  ExecutorService executorService = toTraced(Executors.newFixedThreadPool(NUMBER_OF_THREADS));

  MockSpan parentSpan = mockTracer.buildSpan("foo").start();
  Scope scope = mockTracer.scopeManager().activate(parentSpan);
  executorService.invokeAny(Arrays.asList(new TestCallable()), 1, TimeUnit.SECONDS);
  scope.close();

  countDownLatch.await();
  assertParentSpan(parentSpan);
  assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 12
Source File: OpenTracingExecutionDecorator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public void after(final ExecutionInput executionInput, final ExecutionResult executionResult) {
    Scope scope = executionScopes.remove(executionInput);
    if (scope != null) {
        scope.close();
    }
}
 
Example 13
Source File: AbstractOpenTracingClientProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void stopTraceSpan(final TraceScopeHolder<TraceScope> holder, final Throwable ex) {
    if (holder == null) {
        return;
    }

    final TraceScope traceScope = holder.getScope();
    if (traceScope != null) {
        Span span = traceScope.getSpan();
        Scope scope = traceScope.getScope();
        
        // If the client invocation was asynchronous , the trace span has been created
        // in another thread and should be re-attached to the current one.
        if (holder.isDetached()) {
            scope = tracer.scopeManager().activate(span);
        }

        span.setTag(Tags.ERROR.getKey(), Boolean.TRUE);
        if (ex != null) {
            final Map<String, Object> logEvent = new HashMap<>(2);
            logEvent.put("event", Tags.ERROR.getKey());
            logEvent.put("message", ex.getMessage());
            span.log(logEvent);
        }
        span.finish();
        
        scope.close();
    }
}
 
Example 14
Source File: ThreadLocalScopeTest.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
@Test
public void implicitSpanStack() throws Exception {
    Span backgroundSpan = mock(Span.class);
    Span foregroundSpan = mock(Span.class);

    Scope backgroundActive = scopeManager.activate(backgroundSpan);
    try {
        assertNotNull(backgroundActive);
        assertEquals(scopeManager.activeSpan(), backgroundSpan);

        // Activate a new Scope on top of the background one.
        Scope foregroundActive = scopeManager.activate(foregroundSpan);
        try {
            assertNotNull(foregroundActive);
            assertEquals(scopeManager.activeSpan(), foregroundSpan);
        } finally {
          foregroundActive.close();
        }

        // And now the backgroundActive should be reinstated.
        assertEquals(scopeManager.activeSpan(), backgroundSpan);
    } finally {
        backgroundActive.close();
    }

    // The background and foreground Spans should NOT be finished.
    verify(backgroundSpan, times(0)).finish();
    verify(foregroundSpan, times(0)).finish();

    // And now nothing is active.
    assertNull(scopeManager.activeSpan());
}
 
Example 15
Source File: TracedExecutorServiceTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAny() throws InterruptedException, ExecutionException {
  ExecutorService executorService = toTraced(Executors.newFixedThreadPool(NUMBER_OF_THREADS));

  MockSpan parentSpan = mockTracer.buildSpan("foo").start();
  Scope scope = mockTracer.scopeManager().activate(parentSpan);
  executorService.invokeAny(Arrays.asList(new TestCallable()));
  scope.close();

  countDownLatch.await();
  assertParentSpan(parentSpan);
  assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 16
Source File: AWSXRaySpanBuilderTests.java    From java-xray-tracer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("set explicit span as parent from remote server")
void setExplicitParentSpanFromRemote() {

    // SpanContext can be passed to remote servers using inject() and
    // extract(), so assume we read this in from e.g. HTTP headers
    final SpanContext remoteContext = new AWSXRaySpanContext(Collections.singletonMap(
            TraceHeader.HEADER_KEY,
            traceHeader.toString()
    ));

    final Scope childScope =  tracer
            .buildSpan("child-span")
            .asChildOf(remoteContext)
            .startActive(true);

    final Entity childEntity  = ((AWSXRayScope) childScope).span().getEntity();

    assertEquals(childEntity.getParentSegment().getTraceId(), traceHeader.getRootTraceId());
    assertEquals(childEntity.getParentSegment().getId(), traceHeader.getParentId());

    // Check that trace header is correctly set in the child
    final String childTraceHeader = childScope.span().getBaggageItem(TraceHeader.HEADER_KEY);
    assertNotNull(childTraceHeader);

    childScope.close();
}
 
Example 17
Source File: AWSXRaySpanBuilderTests.java    From java-xray-tracer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("set explicit span as parent")
void setExplicitParentSpan() {

    // NB we *don't* startActive here - assume this Span
    // object came from somewhere else in the code
    final AWSXRaySpan explicitParentSpan = mockSpan("explicit-parent-span");

    // This implicit parent should be ignored by SpanBuilder
    // when we set the explicit parent
    final Scope implicitParentScope = tracer
            .buildSpan("implicit-parent-span")
            .startActive(true);

    final Scope childScope =  tracer
            .buildSpan("child-span")
            .asChildOf(explicitParentSpan)
            .startActive(true);

    final Entity explicitParentEntity = explicitParentSpan.getEntity();
    final Entity implicitParentEntity = ((AWSXRayScope) implicitParentScope).span().getEntity();
    final Entity childEntity  = ((AWSXRayScope) childScope).span().getEntity();

    assertFalse(explicitParentEntity.getSubsegments().isEmpty());
    assertTrue(implicitParentEntity.getSubsegments().isEmpty());

    assertEquals(explicitParentEntity, childEntity.getParent());
    assertNotEquals(explicitParentEntity.getId(), childEntity.getId());

    // Check that trace header is correctly set in the child
    final String childTraceHeader = childScope.span().getBaggageItem(TraceHeader.HEADER_KEY);
    assertNotNull(childTraceHeader);
    assertTrue(childTraceHeader.contains(explicitParentEntity.getTraceId().toString()));
    assertTrue(childTraceHeader.contains(explicitParentEntity.getId()));

    childScope.close();
    implicitParentScope.close();
}
 
Example 18
Source File: TracedExecutorServiceTest.java    From java-concurrent with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubmitCallable() throws InterruptedException {
  ExecutorService executorService = toTraced(Executors.newFixedThreadPool(NUMBER_OF_THREADS));

  MockSpan parentSpan = mockTracer.buildSpan("foo").start();
  Scope scope = mockTracer.scopeManager().activate(parentSpan);
  executorService.submit(new TestCallable());
  scope.close();

  countDownLatch.await();
  assertParentSpan(parentSpan);
  assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example 19
Source File: OpenTracingFilter.java    From flower with Apache License 2.0 4 votes vote down vote up
@Override
public Object doFilter(Object message, ServiceContext context, FilterChain chain) {
  String spanName = context.getFlowName() + "." + context.getCurrentServiceName();
  SpanBuilder spanBuilder = getTracer().buildSpan(spanName);
  SpanContext spanContext = null;
  Map<String, String> headerMap = getMap(context);
  if (headerMap != null) {
    spanContext = getTracer().extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(headerMap));
    if (spanContext != null) {
      spanBuilder.asChildOf(spanContext);
    }
  }


  Span span = spanBuilder.start();
  span.log("Flower Trace start.");

  span.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
  Scope scope = tracer.scopeManager().activate(span);
  addAttachements(context, span);

  span.setTag("id", context.getId());
  span.setTag("sync", context.isSync());
  span.setTag("codec", context.getCodec());
  span.setTag("flowName", context.getFlowName());
  span.setTag("serviceName", context.getCurrentServiceName());
  span.setTag("flowMessage.transactionId", context.getFlowMessage().getTransactionId());
  span.setTag("flowMessage.messageType", context.getFlowMessage().getMessageType());

  try {
    return chain.doFilter(message, context);
  } catch (Exception ex) {
    Tags.ERROR.set(span, true);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(Fields.EVENT, "error");
    map.put(Fields.ERROR_OBJECT, ex);
    map.put(Fields.MESSAGE, ex.getMessage());
    span.log(map);
    throw new FlowException(ex);
  } finally {
    span.log("Flower Trace end.");
    scope.close();
    span.finish();
  }

}
 
Example 20
Source File: SolrDispatchFilter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain, boolean retry) throws IOException, ServletException {
  if (!(_request instanceof HttpServletRequest)) return;
  HttpServletRequest request = closeShield((HttpServletRequest)_request, retry);
  HttpServletResponse response = closeShield((HttpServletResponse)_response, retry);
  Scope scope = null;
  Span span = null;
  try {

    if (cores == null || cores.isShutDown()) {
      try {
        init.await();
      } catch (InterruptedException e) { //well, no wait then
      }
      final String msg = "Error processing the request. CoreContainer is either not initialized or shutting down.";
      if (cores == null || cores.isShutDown()) {
        log.error(msg);
        throw new UnavailableException(msg);
      }
    }

    String requestPath = ServletUtils.getPathAfterContext(request);
    // No need to even create the HttpSolrCall object if this path is excluded.
    if (excludePatterns != null) {
      for (Pattern p : excludePatterns) {
        Matcher matcher = p.matcher(requestPath);
        if (matcher.lookingAt()) {
          chain.doFilter(request, response);
          return;
        }
      }
    }

    SpanContext parentSpan = GlobalTracer.get().extract(request);
    Tracer tracer = GlobalTracer.getTracer();

    Tracer.SpanBuilder spanBuilder = null;
    String hostAndPort = request.getServerName() + "_" + request.getServerPort();
    if (parentSpan == null) {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort);
    } else {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort)
          .asChildOf(parentSpan);
    }

    spanBuilder
        .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
        .withTag(Tags.HTTP_URL.getKey(), request.getRequestURL().toString());
    span = spanBuilder.start();
    scope = tracer.scopeManager().activate(span);

    AtomicReference<HttpServletRequest> wrappedRequest = new AtomicReference<>();
    if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been sent
      return;
    }
    if (wrappedRequest.get() != null) {
      request = wrappedRequest.get();
    }

    if (cores.getAuthenticationPlugin() != null) {
      if (log.isDebugEnabled()) {
        log.debug("User principal: {}", request.getUserPrincipal());
      }
    }

    HttpSolrCall call = getHttpSolrCall(request, response, retry);
    ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
    try {
      Action result = call.call();
      switch (result) {
        case PASSTHROUGH:
          chain.doFilter(request, response);
          break;
        case RETRY:
          doFilter(request, response, chain, true); // RECURSION
          break;
        case FORWARD:
          request.getRequestDispatcher(call.getPath()).forward(request, response);
          break;
        case ADMIN:
        case PROCESS:
        case REMOTEQUERY:
        case RETURN:
          break;
      }
    } finally {
      call.destroy();
      ExecutorUtil.setServerThreadFlag(null);
    }
  } finally {
    if (span != null) span.finish();
    if (scope != null) scope.close();

    GlobalTracer.get().clearContext();
    consumeInputFully(request, response);
    SolrRequestInfo.reset();
    SolrRequestParsers.cleanupMultipartFiles(request);
  }
}