Java Code Examples for io.opentracing.Tracer

The following examples show how to use io.opentracing.Tracer. These examples are extracted from open source projects. 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 Project: opentracing-toolbox   Source File: RenameTest.java    License: MIT License 6 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
void renamesOperationName(
        final String source,
        final CaseFormat targetFormat,
        final String target) {

    final MockTracer tracer = new MockTracer();
    final Tracer unit = new ProxyTracer(tracer)
            .with(new Rename(targetFormat));

    unit.buildSpan(source)
            .start().finish();

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    assertEquals(target, span.operationName());
}
 
Example 2
Source Project: opentracing-toolbox   Source File: TagListenerTest.java    License: MIT License 6 votes vote down vote up
@Test
void multipleListenersAreChained() {
    final Tracer unit = new ProxyTracer(new MockTracer())
            .with(listener)
            .with(listener);

    final Tracer.SpanBuilder builder = unit.buildSpan("test")
            .withTag("k1", "v");

    final Span span = builder
            .start()
            .setTag("k2", "v");

    verify(listener, times(2)).onTag(eq(builder), tag("k1"), eq("v"));
    verify(listener, times(2)).onTag(eq(span), tag("k2"), eq("v"));
}
 
Example 3
Source Project: hono   Source File: TracingHelper.java    License: 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 4
Source Project: thorntail   Source File: TracerResolverListener.java    License: 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 5
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 Project: dremio-oss   Source File: PDFSService.java    License: 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 7
Source Project: java-specialagent   Source File: TracedCallable.java    License: 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 8
Source Project: hadoop-ozone   Source File: TracingUtil.java    License: 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 9
Source Project: quarkus   Source File: QuarkusJaegerTracer.java    License: Apache License 2.0 5 votes vote down vote up
private Tracer tracer() {
    if (tracer == null) {
        synchronized (this) {
            if (tracer == null) {
                tracer = Configuration.fromEnv()
                        .withMetricsFactory(metricsFactory)
                        .getTracerBuilder()
                        .withScopeManager(getScopeManager())
                        .build();
            }
        }
    }
    return tracer;
}
 
Example 10
Source Project: hono   Source File: DeviceStores.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public AbstractDeviceAdapterStore createTable(final Vertx vertx, final Tracer tracer, final JdbcProperties properties, final Optional<String> credentials,
        final Optional<String> registrations) throws IOException {
    return new TableAdapterStore(
            JdbcProperties.dataSource(vertx, properties),
            tracer,
            Configurations.tableConfiguration(properties.getUrl(), credentials, registrations));
}
 
Example 11
Source Project: dremio-oss   Source File: CommandPoolFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return new {@link CommandPool} instance
 */
public CommandPool newPool(final DremioConfig config, final Tracer tracer) {
  if (config.getBoolean(ENABLED)) {
    final int poolSize = getPoolSize(config);
    logger.info("Starting bound command pool of size {}", poolSize);
    return new BoundCommandPool(poolSize, tracer);
  }

  logger.info("Starting unbound command pool");
  // We don't bother decorating the same thread pool.
  // The tracing context doesn't have to move.
  return new SameThreadCommandPool();
}
 
Example 12
Source Project: java-specialagent   Source File: LettuceAgentIntercept.java    License: 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 13
Source Project: java-spring-web   Source File: TracingWebFilter.java    License: Apache License 2.0 5 votes vote down vote up
public TracingWebFilter(
        final Tracer tracer,
        final int order,
        final Pattern skipPattern,
        final List<String> urlPatterns,
        final List<WebFluxSpanDecorator> spanDecorators
) {
    this.tracer = tracer;
    this.order = order;
    this.skipPattern = (skipPattern != null && StringUtils.hasText(skipPattern.pattern())) ? skipPattern : null;
    final PathPatternParser pathPatternParser = new PathPatternParser();
    this.urlPatterns = urlPatterns.stream().map(pathPatternParser::parse).collect(Collectors.toSet());
    this.spanDecorators = spanDecorators;
}
 
Example 14
Source Project: java-jfr-tracer   Source File: JfrTracerTest.java    License: 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 15
Source Project: enmasse   Source File: AbstractDeviceStore.java    License: 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 16
Source Project: enmasse   Source File: SQL.java    License: 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 17
Source Project: java-jdbc   Source File: TracingDriverTest.java    License: 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 18
Source Project: java-kafka-client   Source File: TracingKafkaProducer.java    License: 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 19
Source Project: java-metrics   Source File: MetricsTest.java    License: 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 20
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 21
Source Project: java-web-servlet-filter   Source File: TracingFilter.java    License: 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 22
Source Project: java-specialagent   Source File: CXFITest.java    License: 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 23
Source Project: java-specialagent   Source File: TracingFilter.java    License: 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 24
Source Project: dremio-oss   Source File: BoundCommandPool.java    License: 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 25
Source Project: opentracing-toolbox   Source File: TagListenerTest.java    License: 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 26
Source Project: carbon-apimgt   Source File: ZipkinTracer.java    License: 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 27
Source Project: Jupiter   Source File: OpenTracingFilter.java    License: 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 28
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 29
Source Project: java-specialagent   Source File: TestUtil.java    License: 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 30
Source Project: java-specialagent   Source File: ClassLoaderAgentTest.java    License: 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());
  }
}