Java Code Examples for io.opentracing.Tracer#extract()

The following examples show how to use io.opentracing.Tracer#extract() . 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: Tracing.java    From opentracing-tutorial with Apache License 2.0 6 votes vote down vote up
public static Span startServerSpan(Tracer tracer, javax.ws.rs.core.HttpHeaders httpHeaders, String operationName) {
    // format the headers for extraction
    MultivaluedMap<String, String> rawHeaders = httpHeaders.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<String, String>();
    for (String key : rawHeaders.keySet()) {
        headers.put(key, rawHeaders.get(key).get(0));
    }

    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(headers));
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(operationName);
        } else {
            spanBuilder = tracer.buildSpan(operationName).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(operationName);
    }
    // TODO could add more tags like http.url
    return spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start();
}
 
Example 2
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 3
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Extracts a {@code SpanContext} from given key-value pairs.
 * <p>
 * This provides a generic way to deserialize a span context from any kind of textual data.
 * See {@link #injectSpanContext(Tracer, SpanContext, BiConsumer)} for the corresponding method to
 * serialize the context in that data.
 *
 * @param tracer The Tracer to use for extracting the context.
 * @param keyValueIteratorSupplier The supplier that provides an iterator over key-values pairs representing the
 *            context.
 * @return The context or {@code null} if the given options do not contain a context.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public static SpanContext extractSpanContext(final Tracer tracer,
        final Supplier<Iterator<Map.Entry<String, String>>> keyValueIteratorSupplier) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(keyValueIteratorSupplier);

    return tracer.extract(Format.Builtin.TEXT_MAP, new TextMap() {
        @Override
        public Iterator<Map.Entry<String, String>> iterator() {
            return keyValueIteratorSupplier.get();
        }

        @Override
        public void put(final String key, final String value) {
            throw new UnsupportedOperationException();
        }
    });
}
 
Example 4
Source File: Simple.java    From lightstep-tracer-java with MIT License 6 votes vote down vote up
private static Span createChildViaInjectExtract(Tracer tracer, SpanContext parentCtx) {
    final Map<String, String> textMap = new HashMap<>();
    final TextMap demoCarrier = new TextMap() {
        public void put(String key, String value) {
            textMap.put(key, value);
        }

        public Iterator<Map.Entry<String, String>> iterator() {
            return textMap.entrySet().iterator();
        }
    };

    tracer.inject(parentCtx, Format.Builtin.TEXT_MAP, demoCarrier);
    System.out.println("Carrier contents:");
    for (Map.Entry<String, String> entry : textMap.entrySet()) {
        System.out.println(
                "    key='" + entry.getKey() +
                        "', value='" + entry.getValue() + "'");
    }
    SpanContext extracted = tracer.extract(Format.Builtin.TEXT_MAP, demoCarrier);
    return tracer.buildSpan("grandchild").asChildOf(extracted).start();
}
 
Example 5
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 6
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 7
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 8
Source File: SamplingTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
private SpanContext extractedTraceState(Tracer tracer, ReportingLevel reportingLevel) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, "foo");
    headers.put(Constants.HAWKULAR_APM_ID, "foo");
    headers.put(Constants.HAWKULAR_APM_LEVEL, reportingLevel.toString());

    return tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(headers));
}
 
Example 9
Source File: APMTracerReferenceTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
protected SpanContext extractedTraceState(Tracer tracer, String id) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID);
    headers.put(Constants.HAWKULAR_APM_ID, id);
    headers.put(Constants.HAWKULAR_APM_TXN, TEST_TXN);

    return tracer.extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(headers));
}
 
Example 10
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
protected SpanContext extractSpanContext(Tracer tracer, String id) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID);
    headers.put(Constants.HAWKULAR_APM_ID, id);
    headers.put(Constants.HAWKULAR_APM_TXN, TEST_TXN);

    return tracer.extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(headers));
}
 
Example 11
Source File: OpenTracingFilter.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private Span extractContext(Tracer tracer, JRequest request) {
    MessageWrapper msg = request.message();
    Tracer.SpanBuilder spanBuilder = tracer.buildSpan(msg != null ? msg.getOperationName() : "null");
    try {
        SpanContext spanContext = tracer.extract(
                Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(request.getAttachments()));
        if (spanContext != null) {
            spanBuilder.asChildOf(spanContext);
        }
    } catch (Throwable t) {
        spanBuilder.withTag("Error", "extract from request failed: " + t.getMessage());
    }
    return spanBuilder.start();
}
 
Example 12
Source File: TracingServerChannelInboundHandlerAdapter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  if (!(message instanceof HttpRequest)) {
    handlerContext.fireChannelRead(message);
    return;
  }

  final HttpRequest request = (HttpRequest)message;
  final Tracer tracer = GlobalTracer.get();

  final SpanBuilder spanBuilder = tracer.buildSpan(request.method().name())
    .withTag(Tags.COMPONENT, "netty")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER)
    .withTag(Tags.HTTP_METHOD, request.method().name())
    .withTag(Tags.HTTP_URL, request.uri());

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

  final Span span = spanBuilder.start();
  try (final Scope scope = tracer.activateSpan(span)) {
    handlerContext.channel().attr(SERVER_ATTRIBUTE_KEY).set(span);

    try {
      handlerContext.fireChannelRead(message);
    }
    catch (final Throwable t) {
      OpenTracingApiUtil.setErrorTag(span, t);
      span.finish();
      throw t;
    }
  }
}
 
Example 13
Source File: TracingClientChannelOutboundHandlerAdapter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
  if (!(message instanceof HttpRequest)) {
    context.write(message, promise);
    return;
  }

  final HttpRequest request = (HttpRequest)message;
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan(request.method().name())
    .withTag(Tags.COMPONENT, "netty")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_METHOD, request.method().name())
    .withTag(Tags.HTTP_URL, request.uri());

  final SpanContext parentContext = tracer.extract(Builtin.HTTP_HEADERS, new NettyExtractAdapter(request.headers()));

  if (parentContext != null)
    builder.asChildOf(parentContext);

  final Span span = builder.start();
  try (final Scope scope = tracer.activateSpan(span)) {
    // AWS calls are often signed, so we can't add headers without breaking
    // the signature.
    if (!request.headers().contains("amz-sdk-invocation-id")) {
      tracer.inject(span.context(), Builtin.HTTP_HEADERS, new NettyInjectAdapter(request.headers()));
    }

    context.channel().attr(TracingClientChannelInboundHandlerAdapter.CLIENT_ATTRIBUTE_KEY).set(span);
    try {
      context.write(message, promise);
    }
    catch (final Throwable t) {
      OpenTracingApiUtil.setErrorTag(span, t);
      span.finish();
      throw t;
    }
  }
}
 
Example 14
Source File: TracingFilterUtil.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Span buildSpan(final HttpServletRequest httpRequest, final Tracer tracer, final List<ServletFilterSpanDecorator> spanDecorators) {
  final SpanContext extractedContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new HttpServletRequestExtractAdapter(httpRequest));
  final Span span = tracer.buildSpan(httpRequest.getMethod())
    .asChildOf(extractedContext)
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
    .start();

  httpRequest.setAttribute(SERVER_SPAN_CONTEXT, span.context());
  for (final ServletFilterSpanDecorator spanDecorator: spanDecorators)
    spanDecorator.onRequest(httpRequest, span);

  return span;
}
 
Example 15
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 16
Source File: TraceUtil.java    From qmq with Apache License 2.0 4 votes vote down vote up
public static SpanContext extract(Message message, Tracer tracer) {
    return tracer.extract(Format.Builtin.TEXT_MAP, new QmqMessageExtractAdapter(message));
}
 
Example 17
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
public static SpanContext deserializeTracingMetadata(
    Tracer tracer, Map<String, String> metadata) {
  TextMapExtractAdapter adapter = new TextMapExtractAdapter(metadata);
  return tracer.extract(Format.Builtin.TEXT_MAP, adapter);
}
 
Example 18
Source File: WorkItem.java    From batfish with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
SpanContext getSourceSpan(Tracer tracer) {
  return tracer.extract(Builtin.TEXT_MAP, new TextMapAdapter(_spanData));
}
 
Example 19
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Extracts a {@code SpanContext} from the headers of a vert.x event bus message.
 *
 * @param tracer The Tracer to use for extracting the context.
 * @param headers The headers to extract the context from.
 * @return The context or {@code null} if the given options do not contain a context.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public static SpanContext extractSpanContext(final Tracer tracer, final MultiMap headers) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(headers);

    return tracer.extract(Format.Builtin.TEXT_MAP, new MultiMapExtractAdapter(headers));
}
 
Example 20
Source File: TracingKafkaUtils.java    From java-kafka-client with Apache License 2.0 2 votes vote down vote up
/**
 * Extract Span Context from record headers
 *
 * @param headers record headers
 * @return span context
 */
public static SpanContext extractSpanContext(Headers headers, Tracer tracer) {
  return tracer
      .extract(Format.Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers));
}