io.opentracing.propagation.Format Java Examples

The following examples show how to use io.opentracing.propagation.Format. 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: AsyncHttpClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static Object enter(final Object request, final Object handler) {
  final Request req = (Request)request;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(req.getMethod())
    .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
    .withTag(Tags.HTTP_METHOD.getKey(), req.getMethod())
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_URL.getKey(), req.getUrl()).start();

  tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new TextMap() {
    @Override
    public Iterator<Entry<String,String>> iterator() {
      throw new UnsupportedOperationException("iterator not supported with Tracer.inject()");
    }

    @Override
    public void put(final String key, final String value) {
      req.getHeaders().add(key, value);
    }
  });

  return WrapperProxy.wrap(handler, new TracingAsyncHandler(tracer, (AsyncHandler<?>)handler, span));
}
 
Example #2
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 #3
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 #4
Source File: ProxyFormat.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static <C>Object proxy(final Format<C> format) {
  try {
    if (format == Format.Builtin.BINARY)
      return builtinClass.getField("BINARY").get(null);

    if (format == Format.Builtin.HTTP_HEADERS)
      return builtinClass.getField("HTTP_HEADERS").get(null);

    if (format == Format.Builtin.TEXT_MAP)
      return builtinClass.getField("TEXT_MAP").get(null);

    throw new UnsupportedOperationException();
  }
  catch (final IllegalAccessException | NoSuchFieldException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #5
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 #6
Source File: TracingClientResponseMono.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(final CoreSubscriber<? super ClientResponse> subscriber) {
  final Context context = subscriber.currentContext();
  final Span parentSpan = context.<Span>getOrEmpty(Span.class).orElseGet(tracer::activeSpan);

  final Span span = tracer.buildSpan(request.method().toString())
      .asChildOf(parentSpan)
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
      .start();

  try (final Scope scope = tracer.scopeManager().activate(span, false)) {
    final ClientRequest.Builder requestBuilder = ClientRequest.from(request);
    requestBuilder.headers(httpHeaders ->
        tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpHeadersCarrier(httpHeaders)));
    final ClientRequest mutatedRequest = requestBuilder.build();

    next.exchange(mutatedRequest).subscribe(
        new TracingClientResponseSubscriber(subscriber, mutatedRequest, context, span, spanDecorators)
    );
  }
}
 
Example #7
Source File: TracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Message<?> preSendServerSpan(final Message<?> message) {
  final String destination = (String)message.getHeaders().get(SIMP_DESTINATION);
  final SpanBuilder spanBuilder = tracer
    .buildSpan(destination != null ? destination : UNKNOWN_DESTINATION)
    .withTag(Tags.SPAN_KIND.getKey(), spanKind)
    .withTag(Tags.COMPONENT.getKey(), WEBSOCKET);

  final Map<String,List<String>> nativeHeaders = (Map<String,List<String>>)message.getHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
  SpanContext spanContext = null;
  if (nativeHeaders != null)
    spanContext = tracer.extract(Builtin.TEXT_MAP, new NativeHeadersExtractAdapter(nativeHeaders));

  if (spanContext == null)
    spanContext = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(message.getHeaders()));

  if (spanContext != null)
    spanBuilder.asChildOf(spanContext);

  final Span span = spanBuilder.start();
  return MessageBuilder.fromMessage(message).setHeader(OPENTRACING_SPAN, span).build();
}
 
Example #8
Source File: AbstractInMemoryTracer.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public final <C> InMemorySpanContext extract(Format<C> format, C carrier) {
    requireNonNull(format);
    requireNonNull(carrier);

    try {
        final InMemoryTraceState state;
        if (format instanceof InMemoryTraceStateFormat) {
            state = ((InMemoryTraceStateFormat<C>) format).extract(carrier);
        } else if (format == Format.Builtin.TEXT_MAP) {
            state = TextMapFormatter.INSTANCE.extract((TextMap) carrier);
        } else {
            throw new UnsupportedOperationException("Format " + format + " is not supported");
        }
        return state != null ? newSpanContext(state) : null;
    } catch (Exception e) {
        // Tracing should be low impact, so don't throw if formatting failed
        LOGGER.warn("Failed to inject SpanContext into carrier", e);
        return null;
    }
}
 
Example #9
Source File: AbstractInMemoryTracer.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public final <C> void inject(InMemorySpanContext spanContext, Format<C> format, C carrier) {
    requireNonNull(spanContext);
    requireNonNull(format);
    requireNonNull(carrier);

    try {
        if (format instanceof InMemoryTraceStateFormat) {
            ((InMemoryTraceStateFormat<C>) format).inject(spanContext.traceState(), carrier);
        } else if (format == Format.Builtin.TEXT_MAP) {
            TextMapFormatter.INSTANCE.inject(spanContext.traceState(), (TextMap) carrier);
        } else {
            throw new UnsupportedOperationException("Format " + format + " is not supported");
        }
    } catch (Exception e) {
        // Tracing should be low impact, so don't throw if formatting failed
        LOGGER.warn("Failed to inject SpanContext into carrier", e);
    }
}
 
Example #10
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 #11
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 #12
Source File: OpenTracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
  log.trace("Processing message before sending it to the channel");
  boolean isConsumer = message.getHeaders().containsKey(Headers.MESSAGE_SENT_FROM_CLIENT);

  SpanBuilder spanBuilder = tracer.buildSpan(getOperationName(channel, isConsumer))
      .withTag(Tags.SPAN_KIND.getKey(), isConsumer ? Tags.SPAN_KIND_CONSUMER : Tags.SPAN_KIND_PRODUCER)
      .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
      .withTag(Tags.MESSAGE_BUS_DESTINATION.getKey(), getChannelName(channel));

  MessageTextMap<?> carrier = new MessageTextMap<>(message, isKafkaBinder);
  SpanContext extractedContext = tracer.extract(Format.Builtin.TEXT_MAP, carrier);
  if (isConsumer) {
    spanBuilder.addReference(References.FOLLOWS_FROM, extractedContext);
  } else if (tracer.activeSpan() == null) {
    // it's a client but active span is null
    // This is a fallback we try to add extractedContext in case there is something
    spanBuilder.asChildOf(extractedContext);
  }

  Span span = spanBuilder.startActive(true).span();

  if (isConsumer) {
    log.trace("Adding 'messageConsumed' header");
    carrier.put(Headers.MESSAGE_CONSUMED, "true");
    // TODO maybe we should remove Headers.MESSAGE_SENT_FROM_CLIENT header here?
  } else {
    log.trace("Adding 'messageSent' header");
    carrier.put(Headers.MESSAGE_SENT_FROM_CLIENT, "true");
  }

  tracer.inject(span.context(), Format.Builtin.TEXT_MAP, carrier);
  return carrier.getMessage();
}
 
Example #13
Source File: TracePreZuulFilter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
  final RequestContext context = RequestContext.getCurrentContext();

  // span is a child of one created in servlet-filter
  final Span span = tracer.buildSpan(context.getRequest().getMethod()).withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME).start();
  tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new TextMapAdapter(context.getZuulRequestHeaders()));
  context.set(CONTEXT_SPAN_KEY, span);

  final Scope scope = tracer.activateSpan(span);
  context.set(CONTEXT_SCOPE_KEY, scope);

  return null;
}
 
Example #14
Source File: KafkaService.java    From Mastering-Distributed-Tracing with MIT License 5 votes vote down vote up
public Span startConsumerSpan(String name, MessageHeaders headers) {
    TextMap carrier = new MessageHeadersExtractAdapter(headers);
    SpanContext parent = tracer.extract(Format.Builtin.TEXT_MAP, carrier);
    return tracer.buildSpan(name) //
            .addReference(References.FOLLOWS_FROM, parent) //
            .start();
}
 
Example #15
Source File: TracerShim.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Override
public <C> void inject(SpanContext context, Format<C> format, C carrier) {
  if (context == null) {
    logger.log(Level.INFO, "Cannot inject a null span context.");
    return;
  }

  SpanContextShim contextShim = getContextShim(context);

  if (format == Format.Builtin.TEXT_MAP
      || format == Format.Builtin.TEXT_MAP_INJECT
      || format == Format.Builtin.HTTP_HEADERS) {
    propagation.injectTextFormat(contextShim, (TextMapInject) carrier);
  }
}
 
Example #16
Source File: TraceServerFilter.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void doFilter(Request request, Response response, FilterChain chain)
		throws Throwable {
	if (!isTrace || !(request instanceof TarsServantRequest)) {
		chain.doFilter(request, response);
	} else {
		
		TarsServantRequest tarsServantRequest = (TarsServantRequest)request;
		
		try(TraceContext traceContext = TraceContext.getInstance().initCurrentTrace(tarsServantRequest.getServantName())) {
			Tracer tracer = TraceContext.getInstance().getCurrentTracer();
			Map<String, String> status = tarsServantRequest.getStatus();
			if (tracer == null || status == null || status.isEmpty()) {
				chain.doFilter(request, response);
				return;
			} 
			try (Scope scope = tracer.buildSpan(tarsServantRequest.getFunctionName())
					.asChildOf(tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(status)))
					.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).startActive(true)) {
				Endpoint endpoint = ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().get(tarsServantRequest.getServantName()).getEndpoint();
				scope.span().setTag("server.ipv4", ConfigurationManager.getInstance().getServerConfig().getLocalIP());
				if (endpoint != null) {
					scope.span().setTag("server.port", endpoint.port());
					if (StringUtils.isNotEmpty(endpoint.setDivision())) {
						scope.span().setTag("tars.set_division", endpoint.setDivision());
					}
					scope.span().setTag("tars.server.version", ClientVersion.getVersion());
				}
				chain.doFilter(request, response);
				TarsServantResponse tarsServantResponse = (TarsServantResponse)response;
				if (response != null && tarsServantResponse.getCause() != null && tarsServantResponse.getCause().getMessage() != null) {
					scope.span().log(tarsServantResponse.getCause().getMessage());
				}
				
			}
		}
	}

}
 
Example #17
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 #18
Source File: SofaTracerRuntimeExceptionTest.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
private void buildSofaTracerRuntimeException() throws SofaTracerRuntimeException {
    try {
        HashMap<String, String> headers = new HashMap<String, String>();
        Format format = Mockito.mock(Format.class);
        sofaTracer.extract(format, new TestCarry(headers));
    } catch (Exception e) {
        throw new SofaTracerRuntimeException(e.getMessage());
    }
}
 
Example #19
Source File: MockTracer.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public <C> void inject(MockSpan.MockContext ctx, Format<C> format, C carrier) {
    if (carrier instanceof TextMapInject) {
        TextMapInject textMap = (TextMapInject) carrier;
        for (Map.Entry<String, String> entry : ctx.baggageItems()) {
            textMap.put(BAGGAGE_KEY_PREFIX + entry.getKey(), entry.getValue());
        }
        textMap.put(SPAN_ID_KEY, String.valueOf(ctx.spanId()));
        textMap.put(TRACE_ID_KEY, String.valueOf(ctx.traceId()));
    } else {
        throw new IllegalArgumentException("Unknown carrier");
    }
}
 
Example #20
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 #21
Source File: SpringWebSocketAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void sendEnter(final Object arg) {
  final Tracer tracer = GlobalTracer.get();
  final StompHeaders headers = (StompHeaders)arg;
  final Span span = tracer.buildSpan(headers.getDestination())
    .withTag(Tags.COMPONENT, "stomp-session")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .start();

  tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new StompHeadersInjectAdapter(headers));
  spanHolder.set(span);
}
 
Example #22
Source File: TracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private Message<?> preSendClientSpan(final Message<?> message) {
  final String destination = (String)message.getHeaders().get(SIMP_DESTINATION);
  final Span span = tracer
    .buildSpan(destination != null ? destination : UNKNOWN_DESTINATION)
    .withTag(Tags.SPAN_KIND.getKey(), spanKind)
    .withTag(Tags.COMPONENT.getKey(), WEBSOCKET).start();
  final MessageBuilder<?> messageBuilder = MessageBuilder.fromMessage(message).setHeader(OPENTRACING_SPAN, span);
  tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(messageBuilder));
  return messageBuilder.build();
}
 
Example #23
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void withError() throws Exception {
  TestUtil.setGlobalTracer(tracer);

  startNewThreadPoolServer();

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);
  CustomService.Client client = new CustomService.Client(protocol);

  try {
    assertEquals("Say Good bye", client.withError());
    fail();
  }
  catch (final Exception ignore) {
  }

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

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

  assertTrue(mockSpans.get(0).parentId() != 0 || mockSpans.get(1).parentId() != 0);

  assertNull(tracer.activeSpan());

  verify(tracer, times(2)).buildSpan(anyString());
  verify(tracer, times(1)).inject(any(SpanContext.class), any(Format.class), any());
}
 
Example #24
Source File: SofaTracer.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public <C> SpanContext extract(Format<C> format, C carrier) {

    RegistryExtractorInjector<C> registryExtractor = TracerFormatRegistry.getRegistry(format);
    if (registryExtractor == null) {
        throw new IllegalArgumentException("Unsupported extractor format: " + format);
    }
    return registryExtractor.extract(carrier);
}
 
Example #25
Source File: OpenTracingFilter.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	if (!isTraced(requestContext)) {
		SpanContext extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS,
				new HttpServletRequestExtractAdapter(httpRequest));

		final Scope scope = tracer.buildSpan(httpRequest.getRequestURL().toString()).asChildOf(extractedContext)
				.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).startActive(false);

		httpRequest.setAttribute(SERVER_SPAN_SCOPE, scope);
		httpRequest.setAttribute(SERVER_SPAN_CONTEXT, scope.span().context());
	}
}
 
Example #26
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void async() 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.say("Async", "World", new AsyncMethodCallback<String>() {
    @Override
    public void onComplete(final String response) {
      assertEquals("Say Async World", 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 #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: 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 #29
Source File: ProxyTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  final Class<?> class0 = Format.Builtin.class;

  final URLClassLoader classLoader = new URLClassLoader(new URL[0], null) {
    final Set<String> loaded = new HashSet<>();

    @Override
    protected Class<?> findClass(final String name) throws ClassNotFoundException {
      if (loaded.contains(name))
        return super.findClass(name);

      final byte[] bytes = AssembleUtil.readBytes(ClassLoader.getSystemClassLoader().getResource(AssembleUtil.classNameToResource(name)));
      try {
        return defineClass(name, bytes, 0, bytes.length);
      }
      finally {
        loaded.add(name);
      }
    }
  };

  final Class<?> proxy0 = ProxyTest.class;
  final Class<?> proxy1 = Class.forName(ProxyTest.class.getName(), false, classLoader);

  final Class<?> class1 = Class.forName(class0.getName(), false, classLoader);
  final Object obj = class1.getField("TEXT_MAP").get(null);

  Thread.currentThread().setContextClassLoader(proxy0.getClassLoader());
  final Object customToSystem = proxy0.getMethod("proxy", Object.class).invoke(null, obj);
  System.out.println(customToSystem.toString());

  Thread.currentThread().setContextClassLoader(proxy1.getClassLoader());
  final Object systemToCustom = proxy1.getMethod("proxy", Object.class).invoke(null, Format.Builtin.HTTP_HEADERS);
  System.out.println(systemToCustom.toString());
}
 
Example #30
Source File: MockTracer.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public <C> MockSpan.MockContext extract(Format<C> format, C carrier) {
    Long traceId = null;
    Long spanId = null;
    Map<String, String> baggage = new HashMap<>();

    if (carrier instanceof TextMapExtract) {
        TextMapExtract textMap = (TextMapExtract) carrier;
        for (Map.Entry<String, String> entry : textMap) {
            if (TRACE_ID_KEY.equals(entry.getKey())) {
                traceId = Long.valueOf(entry.getValue());
            } else if (SPAN_ID_KEY.equals(entry.getKey())) {
                spanId = Long.valueOf(entry.getValue());
            } else if (entry.getKey().startsWith(BAGGAGE_KEY_PREFIX)){
                String key = entry.getKey().substring((BAGGAGE_KEY_PREFIX.length()));
                baggage.put(key, entry.getValue());
            }
        }
    } else {
        throw new IllegalArgumentException("Unknown carrier");
    }

    if (traceId != null && spanId != null) {
        return new MockSpan.MockContext(traceId, spanId, baggage);
    }

    return null;
}