io.opentracing.util.GlobalTracer Java Examples

The following examples show how to use io.opentracing.util.GlobalTracer. 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: 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 #2
Source File: FluxAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #3
Source File: ScheduledCallableAgentRule.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter
public static void exit(final @ClassName String className, final @Advice.Origin String origin, @Advice.Argument(value = 0, readOnly = false, typing = Typing.DYNAMIC) Callable<?> arg) throws Exception {
  if (!isAllowed(className, origin))
    return;

  final Tracer tracer = GlobalTracer.get();
  if (isVerbose(className)) {
    final Span span = tracer
      .buildSpan("schedule")
      .withTag(Tags.COMPONENT, "java-concurrent")
      .start();
    arg = new TracedCallable<>(arg, span, true);
    span.finish();
  }
  else if (tracer.activeSpan() != null) {
    arg = new TracedCallable<>(arg, tracer.activeSpan(), false);
  }
}
 
Example #4
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 #5
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 #6
Source File: XceiverServerRatis.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public void submitRequest(ContainerCommandRequestProto request,
    HddsProtos.PipelineID pipelineID) throws IOException {
  RaftClientReply reply;
  Span span = TracingUtil
      .importAndCreateSpan(
          "XceiverServerRatis." + request.getCmdType().name(),
          request.getTraceID());
  try (Scope scope = GlobalTracer.get().activateSpan(span)) {

    RaftClientRequest raftClientRequest =
        createRaftClientRequest(request, pipelineID,
            RaftClientRequest.writeRequestType());
    try {
      reply = server.submitClientRequestAsync(raftClientRequest)
          .get(requestTimeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
      throw new IOException(e.getMessage(), e);
    }
    processReply(reply);
  } finally {
    span.finish();
  }
}
 
Example #7
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String doGeneralGetCall(String url, SpanContext parent, String kindOfSpanReference) {
	Request request = new Request.Builder().url(url).get().build();

	SpanBuilder spanBuilder = getTracer().buildSpan("GET: " + url);
	spanBuilder.addReference(kindOfSpanReference, parent);
	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 GET:" + url);
			return null;
		}
		return response.body().string();
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example #8
Source File: MonoAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #9
Source File: TraceAllMethod.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
  Method delegateMethod = findDelegatedMethod(method);
  if (delegateMethod == null) {
    throw new NoSuchMethodException("Method not found: " +
      method.getName());
  }

  Span span = GlobalTracer.get().buildSpan(
      name + "." + method.getName())
      .start();
  try (Scope scope = GlobalTracer.get().activateSpan(span)) {
    try {
      return delegateMethod.invoke(delegate, args);
    } catch (Exception ex) {
      if (ex.getCause() != null) {
        throw ex.getCause();
      } else {
        throw ex;
      }
    } finally {
      span.finish();
    }
  }
}
 
Example #10
Source File: CursorsServiceAT.java    From nakadi with MIT License 6 votes vote down vote up
@Test
public void whenFirstCursorIsNotCommittedThenNextCursorsAreNotSkipped() throws Exception {
    final NakadiCursor c1 = NakadiCursor.of(timeline, P1, OLDEST_OFFSET);
    final NakadiCursor c2 = NakadiCursor.of(timeline, P2, NEW_OFFSET);
    testCursors = ImmutableList.of(c1, c2);
    testCursors.forEach(this::registerNakadiCursor);

    setPartitions(new Partition[]{
            new Partition(etName, P1, streamId, null, Partition.State.ASSIGNED),
            new Partition(etName, P2, streamId, null, Partition.State.ASSIGNED)});
    final List<Boolean> result = cursorsService.commitCursors(streamId, sid, testCursors,
            GlobalTracer.get().buildSpan("test").start());

    assertFalse(result.get(0));
    assertTrue(result.get(1));

    checkCurrentOffsetInZk(P1, OLD_OFFSET);
    checkCurrentOffsetInZk(P2, NEW_OFFSET);
}
 
Example #11
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 #12
Source File: TracingContextProvider.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public MiniConProp.ContextSnapshot capture() {
    Tracer tracer = GlobalTracer.get();
    ScopeManager scopeManager = tracer.scopeManager();
    Scope activeScope = scopeManager.active();

    if (activeScope != null) {
        Span span = activeScope.span();
        return () -> {
            Scope propagated = scopeManager.activate(span, false);
            return propagated::close;
        };
    }

    return MiniConProp.ContextSnapshot.NOOP;
}
 
Example #13
Source File: TestUtil.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Tracer getGlobalTracer() {
  try {
    final Field field = GlobalTracer.class.getDeclaredField("tracer");
    field.setAccessible(true);
    final Tracer tracer = (Tracer)field.get(null);
    field.setAccessible(false);
    return tracer;
  }
  catch (final IllegalAccessException | NoSuchFieldException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #14
Source File: TracingService.java    From nakadi with MIT License 5 votes vote down vote up
public static Span getNewSpanWithParent(final String operationName, final Long timeStamp,
                                        final SpanContext spanContext) {
    return GlobalTracer.get()
            .buildSpan(operationName)
            .withStartTimestamp(TimeUnit.MILLISECONDS.toMicros(timeStamp))
            .asChildOf(spanContext).start();
}
 
Example #15
Source File: TracingAsyncHandler.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public Object onCompleted() throws Exception {
  final Response response = builder.build();
  if (response != null)
    span.setTag(Tags.HTTP_STATUS, response.getStatusCode());

  try (final Scope scope = GlobalTracer.get().activateSpan(span)) {
    return asyncHandler.onCompleted();
  }
  finally {
    span.finish();
  }
}
 
Example #16
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 #17
Source File: JmsAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object createProducer(final Object thiz) {
  try {
    Class.forName("javax.jms.JMSContext", false, thiz.getClass().getClassLoader());
    return new io.opentracing.contrib.jms2.TracingMessageProducer((MessageProducer)thiz, GlobalTracer.get());
  }
  catch (final ClassNotFoundException e) {
    return new io.opentracing.contrib.jms.TracingMessageProducer((MessageProducer)thiz, GlobalTracer.get());
  }
}
 
Example #18
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 #19
Source File: LettuceAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void connectStart(Object arg) {
  final RedisURI redisURI = (RedisURI) arg;
  final Tracer tracer = GlobalTracer.get();

  final Span span = tracer.buildSpan("CONNECT")
    .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.DB_TYPE.getKey(), DB_TYPE)
    .withTag(Tags.PEER_HOSTNAME, redisURI.getHost())
    .withTag(Tags.PEER_PORT, redisURI.getPort())
    .withTag("db.redis.dbIndex", redisURI.getDatabase())
    .start();

  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example #20
Source File: Tracing.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * This function is used to inject the current span context into the request to
 * be made.
 *
 * @param requestBuilder The requestBuilder object that gets injected
 */
public static void inject(Invocation.Builder requestBuilder) {
  Span activeSpan = GlobalTracer.get().activeSpan();
  if (activeSpan != null) {
    GlobalTracer.get().inject(activeSpan.context(), Format.Builtin.HTTP_HEADERS,
        Tracing.requestBuilderCarrier(requestBuilder));
  }
}
 
Example #21
Source File: LettuceFluxTerminationRunnable.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(final Subscription subscription) {
  final Span span = GlobalTracer.get().buildSpan(LettuceAgentIntercept.getCommandName(command))
    .withTag(Tags.COMPONENT.getKey(), LettuceAgentIntercept.COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.DB_TYPE.getKey(), LettuceAgentIntercept.DB_TYPE)
    .start();

  owner.span = span;
  if (finishSpanOnClose)
    span.finish();
}
 
Example #22
Source File: ElasticsearchTransportClientAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public static Object transport(final Object request, final Object listener) {
  final Tracer.SpanBuilder spanBuilder = GlobalTracer.get()
    .buildSpan(request.getClass().getSimpleName())
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);

  final Span span = spanBuilder.start();
  SpanDecorator.onRequest(span);
  return WrapperProxy.wrap(listener, new TracingResponseListener<>((ActionListener)listener, span));
}
 
Example #23
Source File: ServletFilterAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static TracingFilter getFilter(final ServletContext context, final boolean proxy) throws ServletException {
  Objects.requireNonNull(context);
  TracingFilter filter = servletContextToFilter.get(context);
  if (filter != null)
    return filter;

  synchronized (servletContextToFilter) {
    filter = servletContextToFilter.get(context);
    if (filter != null)
      return filter;

    servletContextToFilter.put(context, filter = proxy ? new TracingProxyFilter(GlobalTracer.get(), context) : new TracingFilter(GlobalTracer.get(), Configuration.spanDecorators, Configuration.skipPattern));
    return filter;
  }
}
 
Example #24
Source File: Main.java    From batfish with Apache License 2.0 5 votes vote down vote up
private static void initTracer() {
  Configuration config =
      new Configuration(_settings.getServiceName())
          .withSampler(new SamplerConfiguration().withType("const").withParam(1))
          .withReporter(
              new ReporterConfiguration()
                  .withSender(
                      SenderConfiguration.fromEnv()
                          .withAgentHost(_settings.getTracingAgentHost())
                          .withAgentPort(_settings.getTracingAgentPort()))
                  .withLogSpans(false));
  GlobalTracer.registerIfAbsent(config.getTracer());
}
 
Example #25
Source File: AkkaHttpSyncHandler.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
static Span buildSpan(final HttpRequest request) {
  final SpanBuilder spanBuilder = GlobalTracer.get().buildSpan(request.method().value())
    .withTag(Tags.COMPONENT, COMPONENT_NAME_SERVER)
    .withTag(Tags.HTTP_URL, request.getUri().toString())
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER);

  final SpanContext context = GlobalTracer.get().extract(Builtin.HTTP_HEADERS, new HttpHeadersExtractAdapter(request));
  if (context != null)
    spanBuilder.addReference(References.FOLLOWS_FROM, context);

  return spanBuilder.start();
}
 
Example #26
Source File: TraceUtil.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static void recordEvent(String event, Tracer tracer) {
    if (tracer == null) {
        tracer = GlobalTracer.get();
    }
    Scope scope = tracer.scopeManager().active();
    if (scope == null) return;
    scope.span().log(event);
}
 
Example #27
Source File: TracingExecutionInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeExecution(BeforeExecution context, ExecutionAttributes executionAttributes) {
  final Span span = GlobalTracer.get().buildSpan(context.request().getClass().getSimpleName())
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.PEER_SERVICE, executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
    .withTag(Tags.COMPONENT, COMPONENT_NAME).start();

  executionAttributes.putAttribute(SPAN_ATTRIBUTE, span);
}
 
Example #28
Source File: AkkaActorITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
  return receiveBuilder().matchAny(x -> {
    final Span span = GlobalTracer.get().activeSpan();
    if (forward)
      getSender().forward(span == null, getContext());
    else
      getSender().tell(span == null, getSelf());
  }).build();
}
 
Example #29
Source File: GrpcTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void sayHello(final HelloRequest req, final StreamObserver<HelloReply> responseObserver) {
  // verify that there is an active span in case of using GlobalTracer:
  if (GlobalTracer.get().activeSpan() == null)
    throw new RuntimeException("no active span");

  final HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
 
Example #30
Source File: Driver.java    From batfish with Apache License 2.0 5 votes vote down vote up
private static void initTracer() {
  io.jaegertracing.Configuration config =
      new io.jaegertracing.Configuration(_mainSettings.getServiceName())
          .withSampler(new SamplerConfiguration().withType("const").withParam(1))
          .withReporter(
              new ReporterConfiguration()
                  .withSender(
                      SenderConfiguration.fromEnv()
                          .withAgentHost(_mainSettings.getTracingAgentHost())
                          .withAgentPort(_mainSettings.getTracingAgentPort()))
                  .withLogSpans(false));
  GlobalTracer.registerIfAbsent(config.getTracer());
}