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

The following examples show how to use io.opentracing.Tracer#activateSpan() . 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: TracingMethodInvocation.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public Object proceed() throws Throwable {
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(invocation.getMethod().getName())
    .withTag(Tags.COMPONENT.getKey(), "spring-async")
    .withTag("class", invocation.getMethod().getDeclaringClass().getSimpleName())
    .withTag("method", invocation.getMethod().getName())
    .start();

  try (final Scope ignored = tracer.activateSpan(span)) {
    return invocation.proceed();
  }
  catch (final Exception e) {
    OpenTracingApiUtil.setErrorTag(span, e);
    throw e;
  }
  finally {
    span.finish();
  }
}
 
Example 2
Source File: PulsarClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void internalSendAsyncEnter(final Object thiz, final Object arg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final MessageImpl<?> message = (MessageImpl<?>)arg;
  final Producer<?> producer = (Producer<?>)thiz;

  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan("send")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_PRODUCER)
    .withTag(Tags.MESSAGE_BUS_DESTINATION, producer.getTopic())
    .withTag(Tags.PEER_SERVICE, "pulsar")
    .start();

  message.getProperties();

  tracer.inject(span.context(), Builtin.TEXT_MAP, new PropertiesMapInjectAdapter(message.getMessageBuilder()));

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 3
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 4
Source File: GoogleHttpClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter(final Object thiz) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

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

  final Span span = tracer
    .buildSpan(request.getRequestMethod())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.HTTP_METHOD, request.getRequestMethod())
    .withTag(Tags.HTTP_URL, request.getUrl().toString())
    .withTag(Tags.PEER_PORT, getPort(request))
    .withTag(Tags.PEER_HOSTNAME, request.getUrl().getHost()).start();

  final Scope scope = tracer.activateSpan(span);
  tracer.inject(span.context(), Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(request.getHeaders()));

  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 5
Source File: TracedCallable.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public V call() throws Exception {
  final Tracer tracer = GlobalTracer.get();
  if (verbose) {
    final Span span = tracer
      .buildSpan("callable")
      .withTag(Tags.COMPONENT, "java-concurrent")
      .addReference(References.FOLLOWS_FROM, parent.context())
      .start();
    try (final Scope scope = tracer.activateSpan(span)) {
      return delegate.call();
    }
    finally {
      span.finish();
    }
  }

  try (final Scope scope = tracer.activateSpan(parent)) {
    return delegate.call();
  }
}
 
Example 6
Source File: FeignAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static Object onRequest(final Object arg1, final Object arg2) {
  final Request request = (Request)arg1;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(request.method())
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .start();

  for (final FeignSpanDecorator decorator : Configuration.spanDecorators)
    decorator.onRequest(request, (Options)arg2, span);

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return inject(tracer, span.context(), request);
}
 
Example 7
Source File: SpringSchedulingAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void enter(final Object thiz) {
  final ScheduledMethodRunnable runnable = (ScheduledMethodRunnable)thiz;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(runnable.getMethod().getName())
    .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
    .withTag("class", runnable.getClass().getSimpleName())
    .withTag("method", runnable.getMethod().getName())
    .start();

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 8
Source File: JRETracerTest.java    From lightstep-tracer-java with MIT License 5 votes vote down vote up
@Test
public void activeSpanTryWithResources() throws Exception {
    Tracer tracer = new JRETracer(
            new Options.OptionsBuilder().withAccessToken("{your_access_token}").build());

   Span span = tracer.buildSpan("test_span").start();
   try(Scope activeScope = tracer.activateSpan(span)) {
       assertNotNull(tracer.scopeManager().activeSpan());
   } finally {
       span.finish();
   }

   assertNull(tracer.scopeManager().activeSpan());
}
 
Example 9
Source File: TracingDriver.java    From java-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public Connection connect(String url, Properties info) throws SQLException {
  // if there is no url, we have problems
  if (url == null) {
    throw new SQLException("url is required");
  }

  final Set<String> ignoreStatements;
  final boolean withActiveSpanOnly;
  if (interceptorMode) {
    withActiveSpanOnly = TracingDriver.withActiveSpanOnly;
    ignoreStatements = TracingDriver.ignoreStatements;
  } else if (acceptsURL(url)) {
    withActiveSpanOnly = url.contains(WITH_ACTIVE_SPAN_ONLY);
    ignoreStatements = extractIgnoredStatements(url);
  } else {
    return null;
  }

  url = extractRealUrl(url);

  // find the real driver for the URL
  final Driver wrappedDriver = findDriver(url);

  final Tracer currentTracer = getTracer();
  final ConnectionInfo connectionInfo = URLParser.parser(url);
  final Span span = buildSpan("AcquireConnection", "", connectionInfo, withActiveSpanOnly,
      Collections.<String>emptySet(), currentTracer);
  final Connection connection;
  try (Scope ignored = currentTracer.activateSpan(span)) {
    connection = wrappedDriver.connect(url, info);
  } finally {
    span.finish();
  }

  return WrapperProxy
      .wrap(connection, new TracingConnection(connection, connectionInfo, withActiveSpanOnly,
          ignoreStatements, currentTracer));
}
 
Example 10
Source File: Sample01.java    From java-span-reporter with Apache License 2.0 5 votes vote down vote up
private static void run0(Tracer tracer) throws Exception {
    // start a span
    try(Scope scope0 = tracer.activateSpan(tracer.buildSpan("span-0")
            .withTag("description", "top level initial span in the original process").start())) {
        Span span0 = tracer.activeSpan();
        Tags.HTTP_URL.set(span0, "/orders"); //span0.setTag(Tags.HTTP_URL.getKey(), "/orders");
        //Tags.HTTP_METHOD.set(span0, "POST");
        //Tags.PEER_SERVICE.set(span0, "OrderManager");
        //Tags.SPAN_KIND.set(span0, Tags.SPAN_KIND_SERVER);
        try(Scope scope1 = tracer.activateSpan(tracer.buildSpan("span-1")
                .withTag("description", "the first inner span in the original process")
                .start())) {
            Span span1 = tracer.activeSpan();

            // do something

            // start another span

            try(Scope scope2 = tracer.activateSpan(tracer.buildSpan("span-2")
                    .asChildOf(span1)
                    .withTag("description", "the second inner span in the original process")
                    .start())) {
                Span span2 = tracer.activeSpan();

                // do something
                span2.log("blablabala");
                span2.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.DEBUG, "k0", "v0", "k1", 42));
                span2.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.WARN, "k0", "v0", "ex", new Exception("boom !")));

                // cross process boundary
                //Map<String, String> map = new java.util.HashMap<>();
                //tracer.inject(span2.context(), Format.Builtin.HTTP_HEADERS, new TextMapInjectAdapter(map))
                Thread.currentThread().sleep(10);
                // request.addHeaders(map);
                // request.doGet();
            }
        }
    }
}
 
Example 11
Source File: SpanManagerInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<InterceptionEvent> around(final ComponentLocation location, final Map<String,ProcessorParameterValue> parameters, final InterceptionEvent event, final InterceptionAction action) {
  final String correlationId = event.getCorrelationId();
  if (correlationId == null)
    return action.proceed();

  final Span span = SpanAssociations.get().retrieveSpan(correlationId);
  if (span == null)
    return action.proceed();

  final Tracer tracer = GlobalTracer.get();
  final Span processorSpan = tracer.buildSpan(getDocName(parameters)).asChildOf(span).start();
  Tags.COMPONENT.set(processorSpan, getComponentName(location));

  final Scope inScope = tracer.activateSpan(processorSpan);
  return action.proceed().exceptionally(exception -> {
    processorSpan.setTag(Tags.ERROR, true);
    if (exception != null)
      span.log(errorLogs(exception));

    throw new RuntimeException(exception);
  }).thenApply(finalEvent -> {
    inScope.close();
    processorSpan.finish();
    return finalEvent;
  });
}
 
Example 12
Source File: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object aroundReceiveStart(final Object thiz, final Object message) {
  if (!(message instanceof TracedMessage) && LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return message;
  }

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

  final TracedMessage<?> tracedMessage;
  if (message instanceof TracedMessage) {
    tracedMessage = (TracedMessage<?>)message;
    spanBuilder.addReference(References.FOLLOWS_FROM, tracedMessage.spanContext(tracer));
  }
  else {
    tracedMessage = null;
    spanBuilder.withTag(Tags.MESSAGE_BUS_DESTINATION, ((AbstractActor)thiz).getSelf().path().toString());
  }

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

  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return tracedMessage != null ? tracedMessage.getMessage() : message;
}
 
Example 13
Source File: HttpURLConnectionAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void enter(final Object thiz, final boolean connected) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  if (connected)
    return;

  final HttpURLConnection connection = (HttpURLConnection)thiz;
  final Tracer tracer = GlobalTracer.get();
  final SpanContext spanContext = tracer.extract(Builtin.HTTP_HEADERS, new HttpURLConnectionExtractAdapter(connection));

  if (spanContext != null)
    return;

  final Span span = tracer.buildSpan(connection.getRequestMethod())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.HTTP_METHOD, connection.getRequestMethod())
    .withTag(Tags.HTTP_URL, connection.getURL().toString())
    .withTag(Tags.PEER_PORT, getPort(connection))
    .withTag(Tags.PEER_HOSTNAME, connection.getURL().getHost()).start();

  final Scope scope = tracer.activateSpan(span);
  tracer.inject(span.context(), Builtin.HTTP_HEADERS, new HttpURLConnectionInjectAdapter(connection));

  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 14
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 15
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 16
Source File: SpringRabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void handleDeliveryStart(Object thiz, Object props) {
  if (WrapperProxy.isWrapper(thiz, TracingConsumer.class))
    return;

  if (AgentRuleUtil.callerEquals(1, 3, "io.opentracing.contrib.rabbitmq.TracingConsumer.handleDelivery"))
    return;

  final AMQP.BasicProperties properties = (AMQP.BasicProperties)props;
  final Tracer tracer = GlobalTracer.get();
  final Span span = TracingUtils.buildChildSpan(properties, null, tracer);
  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 17
Source File: RabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static AMQP.BasicProperties enterPublish(final Object exchange, final Object routingKey, final Object props) {
  final AMQP.BasicProperties properties = (AMQP.BasicProperties)props;
  final Tracer tracer = GlobalTracer.get();
  final Span span = TracingUtils.buildSpan((String)exchange, (String)routingKey, properties, tracer);

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(SpanDecorator.COMPONENT_NAME, span, scope);

  return inject(properties, span, tracer);
}
 
Example 18
Source File: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static Object askStart(final Object arg0, final Object message, final String method, final Object sender) {
  if (arg0 instanceof DeadLetterActorRef)
    return message;

  if (arg0 instanceof ActorRef && ((ActorRef)arg0).isTerminated())
    return message;

  if (sender instanceof PromiseActorRef || arg0 instanceof PromiseActorRef)
    return message;

  if (sender instanceof ActorRef && ((ActorRef)sender).isTerminated())
    return message;

  final String path;
  if (arg0 instanceof ActorRef)
    path = ((ActorRef)arg0).path().toString();
  else if (arg0 instanceof ActorSelection)
    path = ((ActorSelection)arg0).toSerializationFormat();
  else
    return message;

  if (path.contains("/system/"))
    return message;

  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(method)
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_PRODUCER)
    .withTag(Tags.MESSAGE_BUS_DESTINATION, path)
    .start();

  final HashMap<String,String> headers = new HashMap<>();
  tracer.inject(span.context(), Format.Builtin.TEXT_MAP_INJECT, headers::put);

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return new TracedMessage<>(message, headers);
}
 
Example 19
Source File: DefaultActivation.java    From riptide with MIT License 4 votes vote down vote up
@Override
public Scope activate(final Tracer tracer, final Span span) {
    return tracer.activateSpan(span);
}
 
Example 20
Source File: TracingUtils.java    From dremio-oss with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a child span with operation name and tags.
 * Child span is active and lasts as long as the work.
 * @param <R> - return type.
 * @param work - Some user function. Accepts the child span.
 * @param tracer - tracer
 * @param operation - operation name
 * @param tags - an even length list of tags.
 * @return - whatever the user function "work" returns.
 */
public static <R> R trace(Function<Span, R> work, Tracer tracer, String operation, String... tags) {
  Span span = TracingUtils.buildChildSpan(tracer, operation, tags);
  try (Scope s = tracer.activateSpan(span)) {
    return work.apply(span);
  } finally {
    span.finish();
  }
}