io.opentracing.Scope Java Examples

The following examples show how to use io.opentracing.Scope. 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: App.java    From Mastering-Distributed-Tracing with MIT License 7 votes vote down vote up
@KafkaListener(topics = "message")
public void process(@Payload Message message, @Headers MessageHeaders headers) throws Exception {
    Span span = kafka.startConsumerSpan("process", headers);
    try (Scope scope = tracer.scopeManager().activate(span, true)) {
        System.out.println("Received message: " + message.message);
        if (message.image == null && message.message.trim().startsWith("/giphy")) {
            String query = message.message.split("/giphy")[1].trim();
            System.out.println("Giphy requested: " + query);
            message.image = giphy.query(query);
            if (message.image != null) {
                kafka.sendMessage(message);
                System.out.println("Updated message, url=" + message.image);
            }
        }
    }
}
 
Example #2
Source File: AbstractTracingClientTest.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentSpan() {
    {
        Span parent = mockTracer.buildSpan("parent").start();

        final String path = "/foo";
        final String url = wireMockRule.url(path);
        stubFor(get(urlPathEqualTo(path))
                .willReturn(ok()));
        try (Scope scope = mockTracer.activateSpan(parent)) {
            client.getForEntity(url, String.class);
        } finally {
            parent.finish();
        }
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    Assert.assertEquals(mockSpans.get(0).parentId(), mockSpans.get(1).context().spanId());
    Assert.assertEquals(mockSpans.get(0).context().traceId(), mockSpans.get(1).context().traceId());
}
 
Example #3
Source File: TracedController.java    From Mastering-Distributed-Tracing with MIT License 6 votes vote down vote up
/**
 * Execute HTTP GET request.
 */
protected <T> T get(String operationName, URI uri, Class<T> entityClass, RestTemplate restTemplate) {
    Span span = tracer.buildSpan(operationName).start();
    try (Scope scope = tracer.scopeManager().activate(span, false)) {
        Tags.SPAN_KIND.set(span, Tags.SPAN_KIND_CLIENT);
        Tags.HTTP_URL.set(span, uri.toString());
        Tags.HTTP_METHOD.set(span, "GET");

        HttpHeaders headers = new HttpHeaders();
        HttpHeaderInjectAdapter carrier = new HttpHeaderInjectAdapter(headers);
        tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, carrier);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(uri, HttpMethod.GET, entity, entityClass).getBody();
    } finally {
        span.finish();
    }
}
 
Example #4
Source File: MetricsTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithStartTimestamp() throws InterruptedException {
    MetricsReporter reporter = Mockito.mock(MetricsReporter.class);
    MockTracer tracer = new MockTracer();
    Tracer metricsTracer = Metrics.decorate(tracer, reporter);

    long start = System.currentTimeMillis() * 687;
    Thread.sleep(100);
    Scope parent = metricsTracer.buildSpan("parent")
            .withStartTimestamp(start)
            .startActive(true);

    parent.close();

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(1, spans.size());
    MockSpan span = spans.get(0);
    long started = span.startMicros();
    assertEquals(start, started);
}
 
Example #5
Source File: OpenTracingContext.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 {
    Scope scope = null;
    
    if (tracer.activeSpan() == null && continuation != null) {
        scope = tracer.scopeManager().activate(continuation);
    }

    try { //NOPMD
        return traceable.call(new OpenTracingContext(tracer));
    } finally {
        if (continuation != null && scope != null) {
            scope.close();
        }
    }
}
 
Example #6
Source File: FeignTracingTest.java    From feign-opentracing with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentSpanFromSpanManager() throws InterruptedException {
    {
        Span span = mockTracer.buildSpan("parent")
                .start();

        mockWebServer.enqueue(new MockResponse()
                .setResponseCode(200));

        try (Scope scope = mockTracer.activateSpan(span)) {
            StringEntityRequest
                entity = feign.<StringEntityRequest>newInstance(
                new Target.HardCodedTarget(StringEntityRequest.class,
                    mockWebServer.url("/foo").toString()));
            entity.get();
        } finally {
            span.finish();
        }
    }
    Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2));

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    Assert.assertEquals(mockSpans.get(1).context().traceId(), mockSpans.get(0).context().traceId());
    Assert.assertEquals(mockSpans.get(1).context().spanId(), mockSpans.get(0).parentId());
}
 
Example #7
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("orderJob");
	spanBuilder.withTag(RobotOrder.KEY_ORDER_ID, String.valueOf(order.getOrderId()));
	spanBuilder.addReference(References.FOLLOWS_FROM, parent.context());
	Span span = spanBuilder.start();
	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Customer customer = validateUser(order.getCustomerId(), scope.span().context());
		Collection<CompletableFuture<Robot>> robots = dispatch(order.getLineItems(), scope.span().context());
		CompletableFuture<Void> allOf = CompletableFuture.allOf(robots.toArray(new CompletableFuture[0]));
		allOf.get();
		List<Robot> collect = robots.stream().map((robot) -> get(robot)).collect(Collectors.toList());

		// TODO verify that all list items got realized - otherwise add errors for the ones missing etc
		completedOrders.put(order.getOrderId(),
				new RealizedOrder(order, customer, collect.toArray(new Robot[0]), null));
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		completedOrders.put(order.getOrderId(), new RealizedOrder(order, null, null, t));
	} finally {
		span.finish();
		parent.finish();
	}
	orderQueue.remove(order.getOrderId());
}
 
Example #8
Source File: TracingClientChannelInboundHandlerAdapter.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  final Span span = handlerContext.channel().attr(CLIENT_ATTRIBUTE_KEY).get();

  final boolean finishSpan = message instanceof HttpResponse;
  Scope scope = null;

  if (span != null && finishSpan) {
    scope = GlobalTracer.get().activateSpan(span);
    span.setTag(Tags.HTTP_STATUS, ((HttpResponse)message).status().code());
  }

  try {
    handlerContext.fireChannelRead(message);
  }
  finally {
    if (span != null && scope != null) {
      scope.close();
      span.finish();
    }
  }
}
 
Example #9
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 #10
Source File: OpenTracingContext.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Callable<T> wrap(final String description, final Traceable<T> traceable) {
    final Callable<T> callable = new Callable<T>() {
        @Override
        public T call() throws Exception {
            return traceable.call(new OpenTracingContext(tracer));
        }
    };

    // Carry over parent from the current thread
    final Span parent = tracer.activeSpan();
    return () -> {
        try (Scope scope = newOrChildSpan(description, parent)) {
            return callable.call();
        }
    };
}
 
Example #11
Source File: ErrorReportingTest.java    From opentracing-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleError() {
    Span span = tracer.buildSpan("one").start();
    try (Scope scope = tracer.activateSpan(span)) {
        throw new RuntimeException("Invalid state");
    } catch (Exception e) {
        Tags.ERROR.set(span, true);
    } finally {
        span.finish();
    }

    assertNull(tracer.scopeManager().activeSpan());

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(spans.size(), 1);
    assertEquals(spans.get(0).tags().get(Tags.ERROR.getKey()), true);
}
 
Example #12
Source File: ThreadLocalScopeManagerTest.java    From opentracing-java with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultActivateSpan() throws Exception {
    Span span = mock(Span.class);

    Scope scope = source.activate(span);
    try {
        assertNotNull(scope);

        Span otherSpan = source.activeSpan();
        assertEquals(otherSpan, span);
    } finally {
        scope.close();
    }

    // Make sure the Span is not finished.
    verify(span, never()).finish();

    // And now Scope/Span are gone:
    Span missingSpan = source.activeSpan();
    assertNull(missingSpan);
}
 
Example #13
Source File: OpenCensusTracerAdapter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MustBeClosedChecker")
@MustBeClosed
@Override
public Scope activateSpan(Span span) {
  final io.opencensus.trace.Span newSpan;

  if (span instanceof OpenCensusSpanAdapter) {
    final OpenCensusSpanAdapter realSpan = (OpenCensusSpanAdapter) span;
    newSpan = realSpan.getOCSpan();
  } else {
    // Cannot activate non open census spans.
    // Also, noop spans should be remembered internally as blank spans.
    newSpan = BlankSpan.INSTANCE;
  }

  // This can only be called with an adapted span.
  return new OpenCensusScopeAdapter(ocTracer.withSpan(newSpan));
}
 
Example #14
Source File: TracingCallback.java    From java-kafka-client with Apache License 2.0 6 votes vote down vote up
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
  if (exception != null) {
    for (SpanDecorator decorator : spanDecorators) {
      decorator.onError(exception, span);
    }
  }

  try (Scope ignored = tracer.scopeManager().activate(span)) {
    if (callback != null) {
      callback.onCompletion(metadata, exception);
    }
  } finally {
    span.finish();
  }
}
 
Example #15
Source File: TracerShimTest.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
@Test
public void activateSpan() {
  Span otSpan = tracerShim.buildSpan("one").start();
  io.opentelemetry.trace.Span span = ((SpanShim) otSpan).getSpan();

  assertNull(tracerShim.activeSpan());
  assertNull(tracerShim.scopeManager().activeSpan());

  try (Scope scope = tracerShim.activateSpan(otSpan)) {
    assertNotNull(tracerShim.activeSpan());
    assertNotNull(tracerShim.scopeManager().activeSpan());
    assertEquals(span, ((SpanShim) tracerShim.activeSpan()).getSpan());
    assertEquals(span, ((SpanShim) tracerShim.scopeManager().activeSpan()).getSpan());
  }

  assertNull(tracerShim.activeSpan());
  assertNull(tracerShim.scopeManager().activeSpan());
}
 
Example #16
Source File: TracingDataSource.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Override
public Connection getConnection() throws SQLException {
  final Span span = buildSpan("AcquireConnection", "", connectionInfo, withActiveSpanOnly,
      ignoreStatements, tracer);
  final Connection connection;
  try (Scope ignored = tracer.activateSpan(span)) {
    connection = underlying.getConnection();
  } catch (Exception e) {
    JdbcTracingUtils.onError(e, span);
    throw e;
  } finally {
    span.finish();
  }

  return WrapperProxy
      .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly,
          ignoreStatements, tracer));
}
 
Example #17
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 #18
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Customer registerRandomCustomer(SpanContext parent) {
	String newCustomerJSon = getNewCustomerJSonString();
	RequestBody body = RequestBody.create(JSON, newCustomerJSon);
	Request request = new Request.Builder().url(urlCustomer + "/customers").put(body).build();

	SpanBuilder spanBuilder = getTracer().buildSpan("Create random user");
	spanBuilder.asChildOf(parent);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Response response = httpClient.newCall(request).execute();
		if (!response.isSuccessful()) {
			Logger.log("Failed to create customer " + newCustomerJSon);
			return null;
		}
		return Customer.fromJSon(response.body().string());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example #19
Source File: TracedExecutorTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
private void testTracedExecutor(Executor executor) {
  Span span = mockTracer.buildSpan("foo").start();
  try (Scope scope = mockTracer.activateSpan(span)) {
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
      mockTracer.buildSpan("child").start().finish();
      return "ok";
    }, executor);
    completableFuture.join();
  }
  span.finish();
  await().until(() -> mockTracer.finishedSpans().size() == 2);

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(2, mockSpans.size());
  TestUtils.assertSameTraceId(mockSpans);
}
 
Example #20
Source File: ThresholdLogTracerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCompleteClientAndParentSpanImplicit() {
    Scope parent = tracer.buildSpan("parent").startActive(true);
    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);
    }
}
 
Example #21
Source File: Factory.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("inProduction");
	spanBuilder.addReference(References.FOLLOWS_FROM, parent.context());
	Span span = spanBuilder.start();
	span.setTag(Robot.KEY_SERIAL_NUMBER, String.valueOf(serialNumber));
	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Robot chassis = createChassis(serialNumber, robotTypeId, scope.span().context());
		// Takes some time to roll the robot over to the painting
		Utils.sleep(10);
		Robot paintedRobot = paintRobot(chassis, paint, scope.span().context());
		completedRobots.put(paintedRobot.getSerialNumber(), paintedRobot);
		jobsInProduction.remove(serialNumber);
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		throw t;
	} finally {
		span.finish();
		parent.finish();
	}
}
 
Example #22
Source File: OpenTracing0_33_BraveScopeManagerTest.java    From brave-opentracing with Apache License 2.0 5 votes vote down vote up
@Test public void activate() {
  BraveSpan span = opentracing.buildSpan("spanA").start();

  try (Scope scopeA = opentracing.scopeManager().activate(span)) {
    assertThat(opentracing.scopeManager().activeSpan().context().unwrap())
        .isEqualTo(span.context().unwrap());
  }

  assertThat(opentracing.scopeManager().activeSpan())
      .isNull();
}
 
Example #23
Source File: AsyncAnnotationTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Async
public Future<String> fooAsync() {
  MockSpan innerSpan = tracer.buildSpan("fooInner").start();
  try (Scope fooScope = tracer.activateSpan(innerSpan)) {
    return new AsyncResult<>("whatever");
  } finally {
    innerSpan.finish();
  }

}
 
Example #24
Source File: OpenTracingContext.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Scope newOrChildSpan(final String description, final Span parent) {
    Span span = null;
    
    if (parent == null) {
        span = tracer.buildSpan(description).start(); 
    } else {
        span = tracer.buildSpan(description).asChildOf(parent).start();
    }
    
    return new ScopedSpan(span, tracer.scopeManager().activate(span));
}
 
Example #25
Source File: ThriftAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void onError(final Object exception) {
  final Scope scope = GlobalTracer.get().scopeManager().active();
  if (scope != null) {
    new DefaultClientSpanDecorator().onError((Throwable)exception, scope.span());
    scope.close();
  }
}
 
Example #26
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 #27
Source File: TracingCallbackTest.java    From java-kafka-client with Apache License 2.0 5 votes vote down vote up
@Test
public void onCompletionWithCustomErrorDecorators() {
  Span span = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(span)) {
    TracingCallback callback = new TracingCallback(null, span, mockTracer,
        Arrays.asList(SpanDecorator.STANDARD_TAGS, createDecorator()));
    callback.onCompletion(null, new RuntimeException("test"));
  }

  List<MockSpan> finished = mockTracer.finishedSpans();
  assertEquals(1, finished.size());
  assertEquals(true, finished.get(0).tags().get(Tags.ERROR.getKey()));
  assertEquals("overwritten", finished.get(0).tags().get("error.of"));
  assertEquals("error-test", finished.get(0).tags().get("new.error.tag"));
}
 
Example #28
Source File: TracingRedisAsyncCommands.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
private <T> RedisFuture<T> continueScopeSpan(RedisFuture<T> redisFuture) {
  Tracer tracer = tracingConfiguration.getTracer();
  Span span = tracer.activeSpan();
  CompletableRedisFuture<T> customRedisFuture = new CompletableRedisFuture<>(redisFuture);
  redisFuture.whenComplete((v, throwable) -> {
    try (Scope ignored = tracer.scopeManager().activate(span)) {
      if (throwable != null) {
        customRedisFuture.completeExceptionally(throwable);
      } else {
        customRedisFuture.complete(v);
      }
    }
  });
  return customRedisFuture;
}
 
Example #29
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 #30
Source File: AbstractJettyTest.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final AsyncContext asyncContext = request.startAsync(request, response);

    // TODO: This could be avoided by using an OpenTracing aware Runnable (when available)
    final Span cont = tracer.activeSpan();

    asyncContext.start(new Runnable() {
        @Override
        public void run() {
            HttpServletResponse asyncResponse = (HttpServletResponse) asyncContext.getResponse();
            try (Scope activeScope = tracer.scopeManager().activate(cont)) {
                try {
                    Thread.sleep(ASYNC_SLEEP_TIME_MS);
                    asyncResponse.setStatus(204);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    asyncResponse.setStatus(500);
                } finally {
                    asyncContext.complete();
                }
            }
        }
    });
}