io.opentracing.SpanContext Java Examples

The following examples show how to use io.opentracing.SpanContext. 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: PulsarFunctionsAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void handleMessageEnter(final Object function, final Object contextArg, final Object arg0) {
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer
    .buildSpan(getFunctionName(function, contextArg))
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER);

  if (arg0 != null) {
    final Record<?> record = (Record<?>)arg0;
    final SpanContext spanContext = tracer.extract(Builtin.TEXT_MAP, new TextMapExtractAdapter(record.getProperties()));
    if (spanContext != null)
      spanBuilder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = spanBuilder.start();
  final Scope scope = tracer.activateSpan(span);

  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example #2
Source File: DefaultMetadataEncoder.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf encode(ByteBuf metadata, SpanContext context, String baseRoute, String... parts) {

  if (parts.length != 1) {
    throw new IllegalArgumentException(
        "Number of parts should be strictly equal to 1 but given [" + parts.length + "]");
  }

  if (context != null) {
    final HashMap<String, String> spanMap = new HashMap<>();
    for (Map.Entry<String, String> item : context.baggageItems()) {
      spanMap.put(item.getKey(), item.getValue());
    }

    ByteBuf tracingMetadata = Tracing.mapToByteBuf(allocator, spanMap);
    return Metadata.encode(allocator, baseRoute, parts[0], tracingMetadata, metadata);
  }

  return Metadata.encode(allocator, baseRoute, parts[0], metadata);
}
 
Example #3
Source File: SpanBuilderShim.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
@Override
public SpanBuilder addReference(String referenceType, SpanContext referencedContext) {
  if (referencedContext == null) {
    return this;
  }

  // TODO - Use referenceType
  SpanContextShim contextShim = getContextShim(referencedContext);

  if (parentSpan == null && parentSpanContext == null) {
    parentSpanContext = contextShim;
  } else {
    parentLinks.add(contextShim.getSpanContext());
  }

  return this;
}
 
Example #4
Source File: AWSXRayTracerTests.java    From java-xray-tracer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("succeed on SpanContext injection (TraceID)")
void contextInjectTraceId() {
    final TextMap textMap = new TextMapAdapter(new HashMap<>());
    final SpanContext context = new AWSXRaySpanContext(Collections.singletonMap(
        TraceHeader.HEADER_KEY,
        traceHeader.toString()
    ));

    tracer.inject(context, Format.Builtin.TEXT_MAP, textMap);
    assertTrue(textMap.iterator().hasNext());

    final TraceHeader extractedTraceHeader = TraceHeader.fromString(textMap.iterator().next().getValue());
    assertEquals(traceHeader.getRootTraceId(), extractedTraceHeader.getRootTraceId());
    assertEquals(traceHeader.getParentId(), extractedTraceHeader.getParentId());
    assertEquals(traceHeader.getSampled(), extractedTraceHeader.getSampled());
}
 
Example #5
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
public static <T>
    Function<SpanContext, Function<? super Publisher<T>, ? extends Publisher<T>>> traceAsChild(
        Tracer tracer, String name, Tag... tags) {
  return (spanContext) -> {
    if (spanContext == null) {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber, subscriber.currentContext(), tracer, null, name, tags));
    } else {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber,
                  subscriber.currentContext(),
                  tracer,
                  null,
                  spanContext,
                  name,
                  tags));
    }
  };
}
 
Example #6
Source File: SpringJmsAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void onMessageEnter(final Object msg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  SpanContext spanContext = null;
  if (msg instanceof SpanContextContainer)
    spanContext = ((SpanContextContainer)msg).getSpanContext();

  if (spanContext == null)
    spanContext = TracingMessageUtils.extract((Message)msg, tracer);

  if (spanContext != null)
    builder.addReference(References.FOLLOWS_FROM, spanContext);

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example #7
Source File: TracerShim.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ReturnMissingNullable")
@Override
public <C> SpanContext extract(Format<C> format, C carrier) {
  try {
    if (format == Format.Builtin.TEXT_MAP
        || format == Format.Builtin.TEXT_MAP_EXTRACT
        || format == Format.Builtin.HTTP_HEADERS) {
      return propagation.extractTextFormat((TextMapExtract) carrier);
    }
  } catch (Exception e) {
    logger.log(
        Level.INFO,
        "Exception caught while extracting span context; returning null. "
            + "Exception: [{0}] Message: [{1}]",
        new String[] {e.getClass().getName(), e.getMessage()});
  }

  return null;
}
 
Example #8
Source File: Client.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
public Future<Object> send(final Object message) {
  final SpanContext parentSpanContext = tracer.activeSpan().context();

  return executor.submit(
      () -> {
        logger.info("Child thread with message '{}' started", message);

        Span span =
            tracer
                .buildSpan("subtask")
                .addReference(References.FOLLOWS_FROM, parentSpanContext)
                .start();
        try (Scope subtaskScope = tracer.activateSpan(span)) {
          // Simulate work - make sure we finish *after* the parent Span.
          parentDoneLatch.await();
        } finally {
          span.finish();
        }

        logger.info("Child thread with message '{}' finished", message);
        return message + "::response";
      });
}
 
Example #9
Source File: PulsarClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
private static void buildConsumerSpan(final Consumer<?> consumer, final Message<?> message) {
  final Tracer tracer = GlobalTracer.get();
  final SpanContext parentContext = tracer.extract(Builtin.TEXT_MAP, new TextMapAdapter(message.getProperties()));

  final SpanBuilder spanBuilder = tracer
    .buildSpan("receive")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER)
    .withTag("topic", consumer.getTopic())
    .withTag("subscription", consumer.getSubscription())
    .withTag(Tags.PEER_SERVICE, "pulsar");

  if (parentContext != null)
    spanBuilder.addReference(References.FOLLOWS_FROM, parentContext);

  spanBuilder.start().finish();
}
 
Example #10
Source File: PlayAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void applyStart(final Object arg0) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Request<?> request = (Request<?>)arg0;
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer.buildSpan(request.method())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER)
    .withTag(Tags.HTTP_METHOD, request.method())
    .withTag(Tags.HTTP_URL, (request.secure() ? "https://" : "http://") + request.host() + request.uri());

  final SpanContext parent = tracer.extract(Builtin.HTTP_HEADERS, new HttpHeadersExtractAdapter(request.headers()));
  if (parent != null)
    spanBuilder.asChildOf(parent);

  final Span span = spanBuilder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example #11
Source File: RabbitMqTracingUtils.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
static Scope buildSendSpan(Tracer tracer, MessageProperties messageProperties) {
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_PRODUCER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_PRODUCER);

  ScopeManager scopeManager = tracer.scopeManager();
  Optional<SpanContext> existingSpanContext = Optional.ofNullable(scopeManager)
      .map(ScopeManager::activeSpan)
      .map(Span::context);

  existingSpanContext.ifPresent(spanBuilder::asChildOf);

  if (messageProperties.getHeaders() != null) {
    Optional<SpanContext> messageParentContext = findParent(messageProperties, tracer);
    messageParentContext.ifPresent(spanBuilder::asChildOf);
  }
  Span span = spanBuilder.start();
  return scopeManager.activate(span);
}
 
Example #12
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
public static <T>
    Function<SpanContext, Function<? super Publisher<T>, ? extends Publisher<T>>> traceAsChild(
        Tracer tracer, String name, Tag... tags) {
  return (spanContext) -> {
    if (spanContext == null) {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber, subscriber.currentContext(), tracer, null, name, tags));
    } else {
      return Operators.lift(
          (scannable, subscriber) ->
              new SpanSubscriber<T>(
                  subscriber,
                  subscriber.currentContext(),
                  tracer,
                  null,
                  spanContext,
                  name,
                  tags));
    }
  };
}
 
Example #13
Source File: TracingOperator.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(final CoreSubscriber<? super Void> subscriber) {
  final Context context = subscriber.currentContext();
  final Span parentSpan = context.<Span>getOrEmpty(Span.class).orElseGet(tracer::activeSpan);
  final ServerHttpRequest request = exchange.getRequest();

  final SpanContext extractedContext;
  if (parentSpan != null) {
    extractedContext = parentSpan.context();
  } else {
    extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new HttpHeadersExtractAdapter(request.getHeaders()));
  }

  final Span span = tracer.buildSpan(request.getMethodValue())
      .asChildOf(extractedContext)
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
      .start();

  try (final Scope scope = tracer.scopeManager().activate(span, false)) {
    exchange.getAttributes().put(TracingWebFilter.SERVER_SPAN_CONTEXT, span.context());
    source.subscribe(new TracingSubscriber(subscriber, exchange, context, span, spanDecorators));
  }
}
 
Example #14
Source File: SpringRabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void onMessageEnter(final Object msg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  final Message message = (Message)msg;
  if (message.getMessageProperties() != null) {
    final Map<String,Object> headers = message.getMessageProperties().getHeaders();
    final SpanContext spanContext = tracer.extract(Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers));
    if (spanContext != null)
      builder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example #15
Source File: OpenTracingBridgeTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testToIdOfExtractedContext() {
    final String traceIdString = "0af7651916cd43dd8448eb211c80319c";
    final String parentIdString = "b9c7c989f97918e1";

    // --------------------------------------------------------
    final Id traceId = Id.new128BitId();
    traceId.fromHexString(traceIdString, 0);
    assertThat(traceId.toString()).isEqualTo(traceIdString);
    // --------------------------------------------------------
    final Id spanId = Id.new64BitId();
    spanId.fromHexString(parentIdString, 0);
    assertThat(spanId.toString()).isEqualTo(parentIdString);
    // --------------------------------------------------------

    TextMap textMapExtractAdapter = new TextMapAdapter(Map.of(
        TraceContext.W3C_TRACE_PARENT_TEXTUAL_HEADER_NAME,
        "00-" + traceIdString + "-" + parentIdString + "-01",
        "User-Agent", "curl"));
    //ExternalProcessSpanContext
    SpanContext spanContext = apmTracer.extract(Format.Builtin.TEXT_MAP, textMapExtractAdapter);

    assertThat(spanContext).isNotNull();
    assertThat(spanContext.toTraceId()).isEqualTo(traceIdString);
    assertThat(spanContext.toSpanId()).isEqualTo(parentIdString);
}
 
Example #16
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Customer validateUser(Long customerId, SpanContext parent) throws ValidationException {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("validateUser")
			.withTag(Customer.KEY_CUSTOMER_ID, String.valueOf(customerId)).asChildOf(parent);
	try (Scope scope = spanBuilder.startActive(true)) {
		Request req = new Request.Builder().url(CUSTOMER_SERVICE_LOCATION + "/customers/" + customerId).get()
				//.tag(new TagWrapper(parentSpan.context()))
				.build();

		Response res = null;
		try {
			res = httpClient.newCall(req).execute();
			if (res.code() == Status.NOT_FOUND.getStatusCode()) {
				throw new ValidationException("Could not find customer " + customerId);
			}
			return Customer.fromJSon(res.body().string());
		} catch (IOException exc) {
			throw new ValidationException("Failed to validate customer");
		}
	}
}
 
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 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 #18
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String removeOwner(RealizedOrder realizedOrder, SpanContext ctx) {
	System.out.println("User " + realizedOrder.getCustomer() + " picked up order #"
			+ realizedOrder.getOrder().getOrderId() + ". Now removing customer.");

	Customer customer = realizedOrder.getCustomer();
	String url = urlCustomer + "/customers/" + customer.getId();
	Request request = new Request.Builder().url(url).delete().build();

	SpanBuilder spanBuilder = getTracer().buildSpan("DELETE: " + url);
	spanBuilder.addReference(References.FOLLOWS_FROM, ctx);
	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 call DELETE:" + url);
			return null;
		}
		System.out.println("User " + realizedOrder.getCustomer() + " removed.");
		// FIXME: Get from return value
		return String.valueOf(customer.getId());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example #19
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Collection<CompletableFuture<Robot>> dispatch(RobotOrderLineItem[] lineItems, SpanContext spanContext) {
	Collection<CompletableFuture<Robot>> robots = new ArrayList<CompletableFuture<Robot>>();
	for (RobotOrderLineItem lineItem : lineItems) {
		final CompletableFuture<Robot> future = new CompletableFuture<Robot>();
		CompletableFuture.supplyAsync(dispatch(lineItem, spanContext))
				.thenAccept((serial) -> schedulePollingForCompletion(serial, future, spanContext));
		robots.add(future);
	}
	return robots;
}
 
Example #20
Source File: AWSXRayTracerTests.java    From java-xray-tracer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("succeed on SpanContext extraction (empty)")
void contextExtractEmpty() {
    final TextMap textMap = new TextMapAdapter(new HashMap<>());
    final SpanContext context = tracer.extract(Format.Builtin.TEXT_MAP, textMap);
    assertFalse(context.baggageItems().iterator().hasNext());
}
 
Example #21
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    SpanContext spanContext,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  this.rootSpan = null;

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name).asChildOf(spanContext);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace(
        "Created span [{}], with name [{}], child of [{}]",
        this.span,
        name,
        spanContext.toString());
  }

  this.context = ctx.put(Span.class, this.span);
}
 
Example #22
Source File: TracedController.java    From Mastering-Distributed-Tracing with MIT License 5 votes vote down vote up
protected Span startServerSpan(String operationName, HttpServletRequest request) {
    HttpServletRequestExtractAdapter carrier = new HttpServletRequestExtractAdapter(request);
    SpanContext parent = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
    Span span = tracer.buildSpan(operationName).asChildOf(parent).start();
    Tags.SPAN_KIND.set(span, Tags.SPAN_KIND_SERVER);
    return span;
}
 
Example #23
Source File: RabbitMqTracingUtils.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
private static Optional<SpanContext> findParent(
    MessageProperties messageProperties, Tracer tracer) {
  final Map<String, Object> headers = messageProperties.getHeaders();
  SpanContext spanContext =
      tracer.extract(
          Format.Builtin.TEXT_MAP, new RabbitMqMessagePropertiesExtractAdapter(headers));

  if (spanContext == null) {
    return Optional.ofNullable(tracer.activeSpan()).map(Span::context);
  } else {
    return Optional.of(spanContext);
  }
}
 
Example #24
Source File: TracingUtil.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static SpanContext extractParent(String parent, Tracer tracer) {
  if (!GlobalTracer.isRegistered()) {
    return null;
  }

  if (parent == null || parent.isEmpty()) {
    return null;
  }

  return tracer.extract(StringCodec.FORMAT, new StringBuilder(parent));
}
 
Example #25
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void oneWayAsync() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();
  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.oneWay(new AsyncMethodCallback<Void>() {
    @Override
    public void onComplete(final Void response) {
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #26
Source File: RabbitMqTracingUtils.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
static Optional<Scope> buildReceiveSpan(MessageProperties messageProperties, Tracer tracer) {
  Optional<SpanContext> context = findParent(messageProperties, tracer);
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_CONSUMER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_CONSUMER);

  context.ifPresent(spanContext -> spanBuilder.addReference(References.FOLLOWS_FROM, spanContext));
  Scope scope = tracer.scopeManager().activate(spanBuilder.start());

  return Optional.of(scope);
}
 
Example #27
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncMany() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final AtomicInteger counter = new AtomicInteger();
  for (int i = 0; i < 4; ++i) {
    final Factory protocolFactory = new Factory();
    final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
    final TAsyncClientManager clientManager = new TAsyncClientManager();
    final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
    asyncClient.withDelay(1, new AsyncMethodCallback<String>() {
      @Override
      public void onComplete(final String response) {
        assertEquals("delay 1", response);
        assertNotNull(GlobalTracer.get().activeSpan());
        counter.incrementAndGet();
      }

      @Override
      public void onError(final Exception exception) {
        exception.printStackTrace();
      }
    });
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(8));
  assertEquals(4, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(8, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(8)).buildSpan(anyString());
  verify(tracer, times(4)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #28
Source File: SpanShim.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Override
public SpanContext context() {
  /* Read the value using the read lock first. */
  SpanContextShim contextShim = spanContextTable().get(this);

  /* Switch to the write lock *only* for the relatively exceptional case
   * of no context being created.
   * (as we cannot upgrade read->write lock sadly).*/
  if (contextShim == null) {
    contextShim = spanContextTable().create(this);
  }

  return contextShim;
}
 
Example #29
Source File: QTraceFilter.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preOnMessage(Message message, Map<String, Object> filterContext) {
    SpanContext context = TraceUtil.extract(message, tracer);
    Scope scope = tracer.buildSpan(TRACE_DESC)
            .withTag("subject", message.getSubject())
            .withTag("messageId", message.getMessageId())
            .withTag("localRetries", String.valueOf(message.localRetries()))
            .withTag("times", String.valueOf(message.times()))
            .asChildOf(context)
            .startActive(true);
    filterContext.put(TRACE_OBJECT, scope.span());
    return true;
}
 
Example #30
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncWithoutArgs() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startAsyncServer();

  final Factory protocolFactory = new Factory();

  final TNonblockingTransport transport = new TNonblockingSocket("localhost", port);
  final TAsyncClientManager clientManager = new TAsyncClientManager();
  final AsyncClient asyncClient = new AsyncClient(protocolFactory, clientManager, transport);
  final AtomicInteger counter = new AtomicInteger();
  asyncClient.withoutArgs(new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("no args", response);
      assertNotNull(GlobalTracer.get().activeSpan());
      counter.incrementAndGet();
    }

    @Override
    public void onError(final Exception exception) {
      exception.printStackTrace();
    }
  });

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  assertEquals(1, counter.get());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}