Java Code Examples for io.opentracing.Span#context()

The following examples show how to use io.opentracing.Span#context() . 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: TracingClientInterceptor.java    From java-grpc with Apache License 2.0 6 votes vote down vote up
private SpanContext getActiveSpanContext() {
  if (activeSpanSource != null) {
    Span activeSpan = activeSpanSource.getActiveSpan();
    if (activeSpan != null) {
      return activeSpan.context();
    }
  }
  if (activeSpanContextSource != null) {
    final SpanContext spanContext = activeSpanContextSource.getActiveSpanContext();
    if (spanContext != null) {
      return spanContext;
    }
  }
  if (tracer.activeSpan() != null) {
    return tracer.activeSpan().context();
  }
  return null;
}
 
Example 2
Source File: TracingOperator.java    From java-spring-web 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)) {
        exchange.getAttributes().put(TracingWebFilter.SERVER_SPAN_CONTEXT, span.context());
        source.subscribe(new TracingSubscriber(subscriber, exchange, context, span, spanDecorators));
    }
}
 
Example 3
Source File: OpenTracingPlugin.java    From riptide with MIT License 6 votes vote down vote up
private CompletableFuture<ClientHttpResponse> inject(
        final RequestExecution execution,
        final RequestArguments arguments) throws IOException {

    @Nullable final Span span = arguments.getAttribute(internalSpan)
            .orElse(null);

    if (span == null) {
        return execution.execute(arguments);
    }

    decorator.onRequest(span, arguments);

    final SpanContext context = span.context();
    return execution.execute(injection.inject(tracer, arguments, context))
            .whenComplete(decorateOnResponse(span, arguments))
            .whenComplete(decorateOnError(span, arguments));
}
 
Example 4
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindPrimaryReferenceSingleChildOfSpanContextWithOtherRefs() {
    Tracer tracer = new APMTracer();

    SpanContext spanCtx1 = extractSpanContext(tracer, TEST_APM_ID1);

    Reference ref1 = new Reference(References.CHILD_OF, spanCtx1);

    Span span2 = tracer.buildSpan("test2").start();
    Reference ref2 = new Reference(References.FOLLOWS_FROM, span2.context());

    Span span3 = tracer.buildSpan("test3").start();
    Reference ref3 = new Reference(References.CHILD_OF, span3.context());
    Span span4 = tracer.buildSpan("test4").start();
    Reference ref4 = new Reference(References.CHILD_OF, span4.context());

    assertEquals(ref1, APMSpan.findPrimaryReference(Arrays.asList(ref1, ref2, ref3, ref4)));
}
 
Example 5
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 6
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindPrimaryReferenceMultipleChildOfSpan() {
    Tracer tracer = new APMTracer();
    Span span1 = tracer.buildSpan("test1").start();
    Reference ref1 = new Reference(References.CHILD_OF, span1.context());
    Span span2 = tracer.buildSpan("test2").start();
    Reference ref2 = new Reference(References.CHILD_OF, span2.context());
    assertNull(APMSpan.findPrimaryReference(Arrays.asList(ref1, ref2)));
}
 
Example 7
Source File: TracingUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static SpanContext useOrCreateSpanContext(SpanContext spanContext, Span span) {
    LOGGER.debug("Creating a new span. {}", span.context());
    if (spanContext == null) {
        LOGGER.debug("Using the new span context. {}", span.context());
        spanContext = span.context();
    }
    return spanContext;
}
 
Example 8
Source File: InboundRequestTraceTest.java    From tchannel-java with MIT License 5 votes vote down vote up
@Test
public void testInboundRequestWithNonNullTrace() {
    Trace trace = new Trace(42, 0, 42, (byte) 1);
    request.setTrace(trace);

    Span span = Tracing.startInboundSpan(request,tracer, new TracingContext.Default());
    JaegerSpanContext spanContext = (JaegerSpanContext) span.context();
    assertEquals(trace.traceId, spanContext.getTraceIdLow());
    assertEquals(trace.spanId, spanContext.getParentId());
    assertEquals(trace.traceFlags, spanContext.getFlags());
    assertNotEquals(trace.spanId, spanContext.getSpanId());
}
 
Example 9
Source File: TracingPropagationTest.java    From tchannel-java with MIT License 5 votes vote down vote up
private static TraceResponse observeSpanAndDownstream(String encodings, Trace requestTrace) {
    Span span = tracingContext.currentSpan();
    TraceResponse response = new TraceResponse();
    JaegerSpanContext context = (JaegerSpanContext) span.context();
    response.requestTrace = requestTrace;
    response.traceId = context.toTraceId();
    response.sampled = context.isSampled();
    response.baggage = span.getBaggageItem(BAGGAGE_KEY);
    try {
        response.downstream = callDownstream(encodings);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
 
Example 10
Source File: MockTracer.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
private SpanContext activeSpanContext() {
    Span span = activeSpan();
    if (span == null) {
        return null;
    }

    return span.context();
}
 
Example 11
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindPrimaryReferenceMultipleFollowsFrom() {
    Tracer tracer = new APMTracer();
    Span span1 = tracer.buildSpan("test1").start();
    Reference ref1 = new Reference(References.FOLLOWS_FROM, span1.context());
    Span span2 = tracer.buildSpan("test2").start();
    Reference ref2 = new Reference(References.FOLLOWS_FROM, span2.context());
    assertNull(APMSpan.findPrimaryReference(Arrays.asList(ref1, ref2)));
}
 
Example 12
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindPrimaryReferenceSingleFollowsFrom() {
    Tracer tracer = new APMTracer();
    Span span = tracer.buildSpan("test").start();

    Reference ref = new Reference(References.FOLLOWS_FROM, span.context());
    assertEquals(ref, APMSpan.findPrimaryReference(Arrays.asList(ref)));
}
 
Example 13
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindPrimaryReferenceSingleChildOfSpan() {
    Tracer tracer = new APMTracer();
    Span span = tracer.buildSpan("test").start();

    Reference ref = new Reference(References.CHILD_OF, span.context());
    assertEquals(ref, APMSpan.findPrimaryReference(Arrays.asList(ref)));
}
 
Example 14
Source File: ServerTracingFilter.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a parent for a span created by this filter (jax-rs span).
 * The context from the active span takes precedence over context in the request,
 * but only if joinExistingActiveSpan has been set.
 * The current active span should be child-of extracted context and for example
 * created at a lower level e.g. jersey filter.
 */
private SpanContext parentSpanContext(ContainerRequestContext requestContext) {
    Span activeSpan = tracer.activeSpan();
    if (activeSpan != null && this.joinExistingActiveSpan) {
        return activeSpan.context();
    } else {
        return tracer.extract(
                Format.Builtin.HTTP_HEADERS,
                new ServerHeadersExtractTextMap(requestContext.getHeaders())
        );
    }
}
 
Example 15
Source File: TracingHandler.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Helper method for accessing server span context associated with current request.
 *
 * @param routingContext routing context
 * @return server span context or null if not present
 */
public static SpanContext serverSpanContext(final RoutingContext routingContext) {
    SpanContext serverContext = null;

    final Object object = routingContext.get(CURRENT_SPAN);
    if (object instanceof Span) {
        final Span span = (Span) object;
        serverContext = span.context();
    } else {
        log.error("Sever SpanContext is null or not an instance of SpanContext");
    }

    return serverContext;
}
 
Example 16
Source File: TracingHandler.java    From java-vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for accessing server span context associated with current request.
 *
 * @param routingContext routing context
 * @return server span context or null if not present
 */
public static SpanContext serverSpanContext(RoutingContext routingContext) {
    SpanContext serverContext = null;

    Object object = routingContext.get(CURRENT_SPAN);
    if (object instanceof Span) {
        Span span = (Span) object;
        serverContext = span.context();
    } else {
        log.error("Sever SpanContext is null or not an instance of SpanContext");
    }

    return serverContext;
}
 
Example 17
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void doFullRegisterOrderAndRemove() throws InterruptedException, ExecutionException {
	SpanBuilder spanBuilder = getTracer().buildSpan("fullSystemTest");
	final Span span = spanBuilder.start();
	try {
		SpanContext parentContext = span.context();

		// Register 
		CompletableFuture<Customer> newCustomer = CompletableFuture
				.supplyAsync(() -> registerRandomCustomer(parentContext));
		// Maybe not get the types and colors over and over. Looks pretty in the traces though...
		CompletableFuture<RobotType[]> availableTypes = CompletableFuture
				.supplyAsync(() -> getAllTypes(parentContext));
		CompletableFuture<Color[]> availableColors = CompletableFuture
				.supplyAsync(() -> getAllColors(parentContext));
		CompletableFuture.allOf(newCustomer, availableTypes, availableColors);

		Customer customer = newCustomer.get();

		// First completion stage done. Now we can create the order
		List<RobotOrderLineItem> lineItems = createRandomOrder(availableTypes.get(), availableColors.get());
		CompletableFuture<RobotOrder> robotOrderCompletable = CompletableFuture
				.supplyAsync(() -> postOrder(customer, lineItems, parentContext));

		// Rest will happen asynchrously when data is available...
		CompletableFuture<RealizedOrder> realizedOrderFuture = new CompletableFuture<RealizedOrder>();
		// When we have the order, we schedule the polling for an available order...
		robotOrderCompletable
				.thenAccept((order) -> awaitOrderCompletion(order, realizedOrderFuture, parentContext));
		// Once the order is realized, we will remove the customer.
		realizedOrderFuture.thenApply((realizedOrder) -> removeOwner(realizedOrder, parentContext))
				.thenAccept((customerId) -> span.finish());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		throw t;
	}
}
 
Example 18
Source File: MockTracer.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private SpanContext activeSpanContext() {
    Span span = activeSpan();
    if (span == null) {
        return null;
    }

    return span.context();
}