io.opentracing.Tracer Java Examples

The following examples show how to use io.opentracing.Tracer. 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: TracerResolverListener.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
  ServletContext servletContext = sce.getServletContext();

  String skipParameter = servletContext.getInitParameter("skipOpenTracingResolver");
  if (skipParameter != null && Boolean.parseBoolean(skipParameter)) {
    logger.info("Skipping the OpenTracing TracerResolver. "
        + "Your application is expected to set a tracer to GlobalTracer explicitly.");
    return;
  }
  if (GlobalTracer.isRegistered()) {
    logger.info("A Tracer is already registered at the GlobalTracer. Skipping resolution via TraceResolver.");
  }

  Tracer tracer = TracerResolver.resolveTracer();
  if (tracer != null) {
    logger.info(String.format("Registering resolved tracer %s to GlobalTracer.",
        tracer.getClass().getCanonicalName()));
    GlobalTracer.register(tracer);
  } else {
    logger.info("No Tracerresolver found on classpath!");
  }
}
 
Example #2
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Injects a {@code SpanContext} as key-value pairs into a given operation.
 * <p>
 * This provides a generic way to serialize a span context in any kind of textual data.
 * See {@link #extractSpanContext(Tracer, Supplier)} for the corresponding method to deserialize the
 * context from that data.
 *
 * @param tracer The Tracer to use for injecting the context.
 * @param spanContext The context to inject.
 * @param keyValueConsumer The operation that will receive the key-value pairs representing the context.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public static void injectSpanContext(final Tracer tracer, final SpanContext spanContext,
        final BiConsumer<String, String> keyValueConsumer) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(spanContext);
    Objects.requireNonNull(keyValueConsumer);

    tracer.inject(spanContext, Format.Builtin.TEXT_MAP,
            new TextMap() {
                @Override
                public Iterator<Map.Entry<String, String>> iterator() {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void put(final String key, final String value) {
                    keyValueConsumer.accept(key, value);
                }
            });
}
 
Example #3
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 #4
Source File: PDFSService.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public PDFSService(
    Provider<FabricService> fabricService,
    Provider<NodeEndpoint> identityProvider,
    Provider<Iterable<NodeEndpoint>> nodeProvider,
    Tracer tracer,
    SabotConfig config,
    BufferAllocator allocator,
    PDFSMode mode) {
  this.fabricService = fabricService;
  this.identityProvider = identityProvider;
  this.nodeProvider = nodeProvider;
  this.tracer = tracer;
  this.config = config;
  this.allocator = allocator.newChildAllocator("pdfs-allocator", 0, Long.MAX_VALUE);
  this.allowLocalAccess = mode == PDFSMode.DATA;
}
 
Example #5
Source File: TarsTraceZipkinConfiguration.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init() {
	isTrace = serverConfig.getSampleRate() > 0;
	if (isTrace) {
		try {
			createSender();
			reporter = AsyncReporter.builder(sender).build();
			Map<String, Tracer> traces = new HashMap<String, Tracer>();
			for (String servant : serverConfig.getServantAdapterConfMap().keySet()) {
				if (!servant.equals(OmConstants.AdminServant)) {
					Tracing tracing = Tracing.newBuilder().localServiceName(servant)
							.spanReporter(reporter).sampler(brave.sampler.Sampler.create(serverConfig.getSampleRate())).build();
					Tracer tracer = BraveTracer.create(tracing);
					traces.put(servant, tracer);
				}
			}
			TraceManager.getInstance().putTracers(traces);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #6
Source File: TagListenerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldDelegateSpanBuilderStringTag() {
    final Tracer.SpanBuilder builder = unit.buildSpan("test")
            .withTag("k1", "v");

    verify(listener).onTag(eq(builder), tag("k1"), eq("v"));
}
 
Example #7
Source File: LettuceAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void dispatchStart(final Object arg) {
  final RedisCommand command = (RedisCommand)arg;
  final Tracer tracer = GlobalTracer.get();

  final Span span = tracer.buildSpan(getCommandName(command))
    .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.DB_TYPE.getKey(), DB_TYPE)
    .start();

  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example #8
Source File: JfrTracerTest.java    From java-jfr-tracer with Apache License 2.0 5 votes vote down vote up
@Test
public void noJFR() throws IOException {
	// Setup tracers
	MockTracer mockTracer = new MockTracer();
	Tracer tracer = JfrTracerFactory.create(mockTracer);

	// Generate span
	tracer.buildSpan("test span").start().finish();

	// Validate span was created and recorded in JFR
	assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example #9
Source File: AbstractDeviceStore.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public AbstractDeviceStore(final SQLClient client, final Tracer tracer, final StatementConfiguration cfg) {
    super(client, tracer, cfg.getStatement("checkConnection"));

    this.client = client;
    this.tracer = tracer;

    this.readRegistrationStatement = cfg
            .getRequiredStatment("readRegistration")
            .validateParameters(
                    "tenant_id",
                    "device_id");
}
 
Example #10
Source File: SQL.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static Future<SQLConnection> setAutoCommit(final Tracer tracer, final SpanContext context, final SQLConnection connection, boolean state) {
    final Span span = startSqlSpan(tracer, context, "set autocommit", builder -> {
        builder.withTag("db.autocommit", state);
    });
    final Promise<Void> promise = Promise.promise();
    connection.setAutoCommit(state, promise);
    return finishSpan(promise.future().map(connection), span, null);
}
 
Example #11
Source File: TracingDriverTest.java    From java-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testExplicitTracer() {
  Tracer tracer = new MockTracer();
  GlobalTracer.registerIfAbsent(tracer);
  Tracer tracer2 = new MockTracer();
  TracingDriver tracingDriver = new TracingDriver();
  tracingDriver.setTracer(tracer2);
  assertEquals(tracer2, tracingDriver.getTracer());
}
 
Example #12
Source File: TracingKafkaProducer.java    From java-kafka-client with Apache License 2.0 5 votes vote down vote up
TracingKafkaProducer(Producer<K, V> producer, Tracer tracer,
    Collection<SpanDecorator> spanDecorators,
    BiFunction<String, ProducerRecord, String> producerSpanNameProvider) {
  this.producer = producer;
  this.tracer = tracer;
  this.spanDecorators = Collections.unmodifiableCollection(spanDecorators);
  this.producerSpanNameProvider = (producerSpanNameProvider == null)
      ? ClientSpanNameProvider.PRODUCER_OPERATION_NAME
      : producerSpanNameProvider;
}
 
Example #13
Source File: MetricsTest.java    From java-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTags() {
    MetricsReporter reporter = Mockito.mock(MetricsReporter.class);
    MockTracer tracer = new MockTracer();
    Tracer metricsTracer = Metrics.decorate(tracer, reporter);

    Scope parent = metricsTracer.buildSpan("parent")
            .withTag("booleanTag", true)
            .withTag("numericTag", new Integer(100))
            .startActive(true);

    parent.close();

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(1, spans.size());
    MockSpan span = spans.get(0);
    Map<String, Object> tags = span.tags();

    Object booleanTag = tags.get("booleanTag");
    assertNotNull("Expected a tag named 'booleanTag'", booleanTag);
    assertTrue("booleanTag should be a Boolean", booleanTag instanceof Boolean);
    assertEquals("booleanTag should be true", true, booleanTag);

    Object numericTag = tags.get("numericTag");
    assertNotNull("Expected a tag named 'numericTag'", numericTag);
    assertTrue("numericTag should be a Number", numericTag instanceof Number);
    assertEquals("numericTag should be 100", 100, numericTag);
}
 
Example #14
Source File: TracingFilter.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    ServletContext servletContext = filterConfig.getServletContext();

    // Check whether the servlet context provides a tracer
    Object tracerObj = servletContext.getAttribute(Tracer.class.getName());
    if (tracerObj instanceof Tracer) {
        tracer = (Tracer)tracerObj;
    } else {
        // Add current tracer to servlet context, so available to webapp
        servletContext.setAttribute(Tracer.class.getName(), tracer);
    }

    // use decorators from context attributes
    Object contextAttribute = servletContext.getAttribute(SPAN_DECORATORS);
    if (contextAttribute instanceof Collection) {
        List<ServletFilterSpanDecorator> decorators = new ArrayList<>();
        for (Object decorator: (Collection)contextAttribute) {
            if (decorator instanceof ServletFilterSpanDecorator) {
                decorators.add((ServletFilterSpanDecorator) decorator);
            } else {
                log.severe(decorator + " is not an instance of " + ServletFilterSpanDecorator.class);
            }
        }
        this.spanDecorators = decorators.size() > 0 ? decorators : this.spanDecorators;
    }

    contextAttribute = servletContext.getAttribute(SKIP_PATTERN);
    if (contextAttribute instanceof Pattern) {
        skipPattern = (Pattern) contextAttribute;
    }
}
 
Example #15
Source File: CXFITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void checkSpans(int counts) {
  final Tracer tracer = TestUtil.getGlobalTracer();
  final MockTracer mockTracer = (MockTracer)tracer;
  final List<MockSpan> spans = mockTracer.finishedSpans();
  int matchSpans = 0;
  for (final MockSpan span : spans) {
    printSpan(span);
    if (span.tags().get(Tags.COMPONENT.getKey()) == null) {
      ++matchSpans;
    }
  }

  if (counts != matchSpans)
    throw new AssertionError("spans not matched counts");
}
 
Example #16
Source File: TracingFilter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    ServletContext servletContext = filterConfig.getServletContext();
    if (servletContext == null)
        return;

    // Check whether the servlet context provides a tracer
    Object tracerObj = servletContext.getAttribute(Tracer.class.getName());
    if (tracerObj instanceof Tracer) {
        tracer = (Tracer)tracerObj;
    } else {
        // Add current tracer to servlet context, so available to webapp
        servletContext.setAttribute(Tracer.class.getName(), tracer);
    }

    // use decorators from context attributes
    Object contextAttribute = servletContext.getAttribute(SPAN_DECORATORS);
    if (contextAttribute instanceof Collection) {
        List<ServletFilterSpanDecorator> decorators = new ArrayList<>();
        for (Object decorator: (Collection)contextAttribute) {
            if (decorator instanceof ServletFilterSpanDecorator) {
                decorators.add((ServletFilterSpanDecorator) decorator);
            } else {
                log.severe(decorator + " is not an instance of " + ServletFilterSpanDecorator.class);
            }
        }
        this.spanDecorators = decorators.size() > 0 ? decorators : this.spanDecorators;
    }

    contextAttribute = servletContext.getAttribute(SKIP_PATTERN);
    if (contextAttribute instanceof Pattern) {
        skipPattern = (Pattern) contextAttribute;
    }
}
 
Example #17
Source File: BoundCommandPool.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
BoundCommandPool(final int poolSize, Tracer tracer) {
  this.executorService = new ContextMigratingExecutorService<>(new ThreadPoolExecutor(
    poolSize, poolSize, // limited pool of threads
    0, TimeUnit.SECONDS, // doesn't matter as number of threads never exceeds core size
    new PriorityBlockingQueue<>(),
    new NamedThreadFactory("bound-command")
  ), tracer);
}
 
Example #18
Source File: TraceContext.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void log(String event, long timestamp) {
	Tracer tracer = currentTracer.get();
	if (tracer != null) {
		Scope scope = tracer.scopeManager().active();
		if (scope != null) {
			scope.span().log(timestamp, event);
		}
	}
}
 
Example #19
Source File: ZipkinTracer.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public Tracer getTracer(String serviceName) {
    String hostname = configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_HOST) != null ?
            configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_HOST)
            : TracingConstants.ZIPKIN_DEFAULT_HOST;

    int port = configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_PORT) != null ?
            Integer.parseInt(configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_PORT))
            : TracingConstants.ZIPKIN_DEFAULT_PORT;

    boolean tracerLogEnabled =
            Boolean.parseBoolean(configuration.getFirstProperty(TracingConstants.CONFIG_TRACER_LOG_ENABLED) != null ?
            configuration.getFirstProperty(TracingConstants.CONFIG_TRACER_LOG_ENABLED)
            : TracingConstants.DEFAULT_TRACER_LOG_ENABLED);

    OkHttpSender sender = OkHttpSender.create("http://" + hostname + ":" + port + TracingConstants.ZIPKIN_API_CONTEXT);
    Tracer tracer = BraveTracer.create(Tracing.newBuilder()
            .localServiceName(serviceName)
            .spanReporter(AsyncReporter.builder(sender).build())
            .propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, TracingConstants.REQUEST_ID))
            .build());

    if (tracerLogEnabled) {
        Reporter reporter = new TracingReporter(LogFactory.getLog(TracingConstants.TRACER));
        Tracer tracerR = new TracerR(tracer, reporter, new ThreadLocalScopeManager());
        GlobalTracer.register(tracerR);
        return tracerR;
    } else {
        GlobalTracer.register(tracer);
        return tracer;
    }
}
 
Example #20
Source File: OpenTracingFilter.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private void injectContext(Tracer tracer, Span span, final JRequest request) {
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMap() {

        @Override
        public Iterator<Map.Entry<String, String>> iterator() {
            throw new UnsupportedOperationException("iterator");
        }

        @Override
        public void put(String key, String value) {
            request.putAttachment(key, value);
        }
    });
}
 
Example #21
Source File: TracingRedisAdvancedClusterAsyncCommands.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
private <T> RedisFuture<T> continueScopeSpan(RedisFuture<T> redisFuture) {
  Tracer tracer = tracingConfiguration.getTracer();
  Span span = tracer.activeSpan();
  CompletableRedisFuture<T> customRedisFuture = new CompletableRedisFuture<>(redisFuture);
  redisFuture.whenComplete((v, throwable) -> {
    try (Scope ignored = tracer.scopeManager().activate(span)) {
      if (throwable != null) {
        customRedisFuture.completeExceptionally(throwable);
      } else {
        customRedisFuture.complete(v);
      }
    }
  });
  return customRedisFuture;
}
 
Example #22
Source File: TestUtil.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static MockTracer getTracer() {
  final Tracer tracer = getGlobalTracer();
  if (tracer instanceof NoopTracer)
    throw new AssertionError("No tracer is registered");

  return tracer instanceof MockTracer ? (MockTracer)tracer : null;
}
 
Example #23
Source File: ClassLoaderAgentTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassLoaderFindResources() throws IOException {
  try (final URLClassLoader classLoader = new URLClassLoader(new URL[0], null)) {
    final Enumeration<URL> resources = classLoader.findResources(AssembleUtil.classNameToResource(Tracer.class));
    assertNotNull(resources);
    assertTrue(resources.hasMoreElements());
  }
}
 
Example #24
Source File: CustomAsyncConfigurerAutoConfiguration.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  if (bean instanceof AsyncConfigurer && !(bean instanceof TracedAsyncConfigurer)) {
    AsyncConfigurer configurer = (AsyncConfigurer) bean;
    Tracer tracer = this.beanFactory.getBean(Tracer.class);
    return new TracedAsyncConfigurer(tracer, configurer);
  }
  return bean;
}
 
Example #25
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 #26
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 #27
Source File: MeteredTracerProvider.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public MeteredTracerProvider(Set<MetricsReporter> metricsReporter) {
  MicrometerMetricsFactory internalMetricsFactory = new MicrometerMetricsFactory();
  Configuration configuration = Configuration.fromEnv();
  Tracer tracer =
      configuration.getTracerBuilder().withMetricsFactory(internalMetricsFactory).build();

  this.tracerProvider = new TracerProvider(Metrics.decorate(tracer, metricsReporter));
}
 
Example #28
Source File: Catalog.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject search(@QueryParam("q") final String query, @Context final TracerContext tracing) throws Exception {
    final GoogleBooksApi api = Feign
        .builder()
        .client(new TracingClient(new ApacheHttpClient(), tracing.unwrap(Tracer.class)))
        .target(GoogleBooksApi.class, "https://www.googleapis.com");
 
    final feign.Response response = api.search(query);
    try (final Reader reader = response.body().asReader()) {
        return Json.createReader(reader).readObject();
    }
}
 
Example #29
Source File: TraceUtil.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static void setTag(String key, String value, Tracer tracer) {
    if (tracer == null) {
        tracer = GlobalTracer.get();
    }
    Scope scope = tracer.scopeManager().active();
    if (scope == null) return;
    scope.span().setTag(key, value);
}
 
Example #30
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);
}