Java Code Examples for io.opentracing.util.GlobalTracer#register()

The following examples show how to use io.opentracing.util.GlobalTracer#register() . 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: OpenTracingUtil.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void configureOpenTracing(Properties configuration, String serviceName) {
	Tracer tracer = null;
	String tracerName = configuration.getProperty("tracer");
	if ("jaeger".equals(tracerName)) {
		SamplerConfiguration samplerConfig = new SamplerConfiguration().withType(ConstSampler.TYPE).withParam(1);
		SenderConfiguration senderConfig = new SenderConfiguration()
				.withAgentHost(configuration.getProperty("jaeger.reporter.host"))
				.withAgentPort(Integer.decode(configuration.getProperty("jaeger.reporter.port")));
		ReporterConfiguration reporterConfig = new ReporterConfiguration().withLogSpans(true)
				.withFlushInterval(1000).withMaxQueueSize(10000).withSender(senderConfig);
		tracer = new Configuration(serviceName).withSampler(samplerConfig).withReporter(reporterConfig).getTracer();
	} else if ("zipkin".equals(tracerName)) {
		OkHttpSender sender = OkHttpSender.create("http://" + configuration.getProperty("zipkin.reporter.host")
				+ ":" + configuration.getProperty("zipkin.reporter.port") + "/api/v2/spans");
		Reporter<Span> reporter = AsyncReporter.builder(sender).build();
		tracer = BraveTracer
				.create(Tracing.newBuilder().localServiceName(serviceName).spanReporter(reporter).build());
	}
	GlobalTracer.register(new DelegatingJfrTracer(tracer));
}
 
Example 2
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 3
Source File: InitialDataGenerationDaemon.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 * @param event
 *          The servlet context event at initialization.
 */
public void contextInitialized(ServletContextEvent event) {
  GlobalTracer.register(Tracing.init(Service.PERSISTENCE.getServiceName()));
  waitForDatabase();
  if (DataGenerator.GENERATOR.isDatabaseEmpty()) {
    LOG.info("Database is empty. Generating new database content");
    DataGenerator.GENERATOR.generateDatabaseContent(DataGenerator.SMALL_DB_CATEGORIES,
        DataGenerator.SMALL_DB_PRODUCTS_PER_CATEGORY, DataGenerator.SMALL_DB_USERS,
        DataGenerator.SMALL_DB_MAX_ORDERS_PER_USER);
  } else {
    LOG.info("Populated database found. Skipping data generation");
  }
  LOG.info("Persistence finished initializing database");
  RegistryClient.getClient().register(event.getServletContext().getContextPath());
  LOG.info("Persistence started registration daemon");
}
 
Example 4
Source File: RecommenderStartup.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 * @param event
 *            The servlet context event at initialization.
 */
public void contextInitialized(ServletContextEvent event) {
	GlobalTracer.register(Tracing.init(Service.RECOMMENDER.getServiceName()));
	RESTClient.setGlobalReadTimeout(REST_READ_TIMOUT);
	ServiceLoadBalancer.preInitializeServiceLoadBalancers(Service.PERSISTENCE);
	RegistryClient.getClient().runAfterServiceIsAvailable(Service.PERSISTENCE, () -> {
		TrainingSynchronizer.getInstance().retrieveDataAndRetrain();
		RegistryClient.getClient().register(event.getServletContext().getContextPath());
	}, Service.RECOMMENDER);
	try {
		long looptime = (Long) new InitialContext().lookup("java:comp/env/recommenderLoopTime");
		// if a looptime is specified, a retraining daemon is started
		if (looptime > 0) {
			new RetrainDaemon(looptime).start();
			LOG.info("Periodic retraining every " + looptime + " milliseconds");
		} else {
			LOG.info("Recommender loop time not set. Disabling periodic retraining.");
		}
	} catch (NamingException e) {
		LOG.info("Recommender loop time not set. Disabling periodic retraining.");
	}

}
 
Example 5
Source File: JaegerDeploymentRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void registerTracer(JaegerConfig jaeger, ApplicationConfig appConfig, MetricsFactory metricsFactory) {
    if (!jaeger.serviceName.isPresent()) {
        if (appConfig.name.isPresent()) {
            jaeger.serviceName = appConfig.name;
        } else {
            jaeger.serviceName = UNKNOWN_SERVICE_NAME;
        }
    }
    initTracerConfig(jaeger);
    quarkusTracer.setMetricsFactory(metricsFactory);
    quarkusTracer.reset();
    // register Quarkus tracer to GlobalTracer.
    // Usually the tracer will be registered only here, although consumers
    // could register a different tracer in the code which runs before this class.
    // This is also used in tests.
    if (!GlobalTracer.isRegistered()) {
        log.debugf("Registering tracer to GlobalTracer %s", quarkusTracer);
        GlobalTracer.register(quarkusTracer);
    }
}
 
Example 6
Source File: OpenTracingHelper.java    From java-agent with Apache License 2.0 5 votes vote down vote up
protected void initTracer() {
    synchronized (SYNC) {
        if (tracer == null) {
            if (!GlobalTracer.isRegistered()) {
                boolean triggeringState = Rule.isTriggeringEnabled();
                if (!allowInstrumentedTracer() && triggeringState) {
                    // Temporarily disable triggering of rules unless we have explicitly allowed
                    // the tracer to be instrumented.
                    setTriggering(false);
                }
                try {
                    // Try to obtain a tracer using the TracerResolver
                    Tracer resolved = TracerResolver.resolveTracer();
                    if (resolved != null) {
                        try {
                            GlobalTracer.register(resolved);
                        } catch (RuntimeException re) {
                            log.log(Level.WARNING,
                                    "Failed to register tracer '" + resolved + "'", re);
                        }
                    }
                } finally {
                    setTriggering(triggeringState);
                }
            }
            // Initialize the tracer even if one has not been registered
            // (i.e. it will use a NoopTracer under the covers)
            tracer = new AgentTracer(GlobalTracer.get());
        }
    }
}
 
Example 7
Source File: OpenTracingHelperTest.java    From java-agent with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTracerExisting() {
    GlobalTracer.register(new MockTracer());

    OpenTracingHelper helper = new OpenTracingHelper(null);
    Tracer tracer = helper.getTracer();

    assertNotNull(tracer);

    assertTrue(tracer.buildSpan("Test").start() instanceof MockSpan);
}
 
Example 8
Source File: ImageProviderStartup.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 * @param event
 *          The servlet context event at initialization.
 */
public void contextInitialized(ServletContextEvent event) {
  GlobalTracer.register(Tracing.init(Service.IMAGE.getServiceName()));
  ServiceLoadBalancer.preInitializeServiceLoadBalancers(Service.PERSISTENCE);
  RegistryClient.getClient().runAfterServiceIsAvailable(Service.PERSISTENCE,
      new StartupCallback() {
        @Override
        public void callback() {
          SetupController.SETUP.startup();
          RegistryClient.getClient().register(event.getServletContext().getContextPath());
        }
      }, Service.IMAGE);
}
 
Example 9
Source File: WebuiStartup.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 * @param event The servlet context event at initialization.
 */
public void contextInitialized(ServletContextEvent event) {
    GlobalTracer.register(Tracing.init(Service.WEBUI.getServiceName()));
	ServiceLoadBalancer.preInitializeServiceLoadBalancers(Service.AUTH, Service.IMAGE,
			Service.PERSISTENCE, Service.RECOMMENDER);
	RegistryClient.getClient().register(event.getServletContext().getContextPath());
}
 
Example 10
Source File: AuthStartup.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * startup routine.
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 * @param event The servlet context event at initialization.
 */
public void contextInitialized(ServletContextEvent event) {
  GlobalTracer.register(Tracing.init(Service.AUTH.getServiceName()));
  RESTClient.setGlobalReadTimeout(REST_READ_TIMOUT);
  ServiceLoadBalancer.preInitializeServiceLoadBalancers(Service.PERSISTENCE);
  RegistryClient.getClient().register(event.getServletContext().getContextPath());
}
 
Example 11
Source File: TracingUtil.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the tracing with the given service name.
 */
public static void initTracing(
    String serviceName, ConfigurationSource conf) {
  if (!GlobalTracer.isRegistered() && isTracingEnabled(conf)) {
    Configuration config = Configuration.fromEnv(serviceName);
    JaegerTracer tracer = config.getTracerBuilder()
        .registerExtractor(StringCodec.FORMAT, new StringCodec())
        .registerInjector(StringCodec.FORMAT, new StringCodec())
        .build();
    GlobalTracer.register(tracer);
  }
}
 
Example 12
Source File: TracerProducer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves tracer instance to be used. It is using {@link TracerResolver} service loader to find
 * the tracer. It tracer is not resolved it will use {@link io.opentracing.noop.NoopTracer}.
 *
 * @return tracer instance
 */
@Default
@Produces
@Singleton
public Tracer produceTracer() {
  // TCK casts to MockTracer so we cannot use GlobalTracer as a bean!
  Tracer tracer = TracerResolver.resolveTracer();
  if (tracer == null) {
    tracer = GlobalTracer.get();
  }
  logger.info(String.format("Registering %s to GlobalTracer and providing it as CDI bean.", tracer));
  GlobalTracer.register(tracer);
  return tracer;
}
 
Example 13
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 14
Source File: LogTracer.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public Tracer getTracer(String serviceName) {
    boolean LogEnabled = Boolean.valueOf(configuration.getFirstProperty(TracingConstants.LOG_ENABLED));
    if (LogEnabled) {
        Tracer tracer = NoopTracerFactory.create();
        Reporter reporter = new TracingReporter(LogFactory.getLog(TracingConstants.TRACER));
        Tracer tracerR = new TracerR(tracer, reporter, new ThreadLocalScopeManager());
        GlobalTracer.register(tracerR);
        return tracerR;
    }
    return null;
}
 
Example 15
Source File: SpringMVCConfiguration.java    From java-spring-web with Apache License 2.0 4 votes vote down vote up
@Override
public void addInterceptors(InterceptorRegistry registry) {
    GlobalTracer.register(tracer);
    registry.addInterceptor(new TracingHandlerInterceptor(tracer, spanDecorators));
    registry.addInterceptor(new TestInterceptor());
}
 
Example 16
Source File: OTAgentTestBase.java    From java-agent with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void initClass() throws Exception {
    GlobalTracer.register(tracer);
}
 
Example 17
Source File: JaegerInitializer.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext sc = servletContextEvent.getServletContext();

    String serviceName = getProperty(sc, JAEGER_SERVICE_NAME);
    if (serviceName == null || serviceName.isEmpty()) {
        logger.warn("No Service Name set. Using default. Please change it.");
        serviceName = "thorntail/unknown";
    }

    Configuration configuration = new Configuration(serviceName)
            .withSampler(
                    new Configuration.SamplerConfiguration()
                            .withType(
                                    getProperty(sc, JAEGER_SAMPLER_TYPE))
                            .withParam(
                                    getPropertyAsNumber(sc, JAEGER_SAMPLER_PARAM))
                            .withManagerHostPort(
                                    getProperty(sc, JAEGER_SAMPLER_MANAGER_HOST_PORT)))
            .withReporter(
                    new ReporterConfiguration()
                            .withLogSpans(
                                    getPropertyAsBoolean(sc, JAEGER_REPORTER_LOG_SPANS))
                            .withSender(
                                    new SenderConfiguration()
                                            .withAuthUsername(getProperty(sc, JAEGER_USER))
                                            .withAuthPassword(getProperty(sc, JAEGER_PASSWORD))
                                            .withAgentHost(getProperty(sc, JAEGER_AGENT_HOST))
                                            .withAgentPort(getPropertyAsInt(sc, JAEGER_AGENT_PORT)))
                            .withFlushInterval(
                                    getPropertyAsInt(sc, JAEGER_REPORTER_FLUSH_INTERVAL))
                            .withMaxQueueSize(
                                    getPropertyAsInt(sc, JAEGER_REPORTER_MAX_QUEUE_SIZE)
                            )
            );

    String remoteEndpoint = getProperty(sc, JAEGER_ENDPOINT);
    if (remoteEndpoint != null && remoteEndpoint.trim().length() > 0) {
        configuration.getReporter()
                .withSender(new SenderConfiguration()
                                    .withEndpoint(remoteEndpoint));
    }

    String enableB3HeaderPropagation = getProperty(sc, "enableB3HeaderPropagation");
    if (enableB3HeaderPropagation != null && Boolean.parseBoolean(enableB3HeaderPropagation)) {
        logger.info("Enabling B3 Header Propagation for Jaeger");
        CodecConfiguration codecConfiguration = new CodecConfiguration();
        codecConfiguration.withCodec(Builtin.HTTP_HEADERS, new B3TextMapCodec.Builder().build());
        codecConfiguration.withCodec(Builtin.TEXT_MAP, new B3TextMapCodec.Builder().build());
        configuration.withCodec(codecConfiguration);
    }

    GlobalTracer.register(configuration.getTracer());
}
 
Example 18
Source File: ShardingTracer.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize sharding tracer.
 * 
 * @param tracer opentracing tracer
 */
public static void init(final Tracer tracer) {
    if (!GlobalTracer.isRegistered()) {
        GlobalTracer.register(tracer);
    }
}
 
Example 19
Source File: TracingUtil.java    From oxd with Apache License 2.0 4 votes vote down vote up
public static boolean configureGlobalTracer(OxdServerConfiguration configuration, String componentName) {
    GlobalTracer.register(createTracer(configuration, componentName));
    return true;
}
 
Example 20
Source File: JaegerTracer.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer getTracer(String serviceName) {
    String hostname = configuration.getFirstProperty(TracingConstants.JAEGER_CONFIG_HOST) != null ?
            configuration.getFirstProperty(TracingConstants.JAEGER_CONFIG_HOST)
            : TracingConstants.JAEGER_DEFAULT_HOST;

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

    String samplerType = configuration.getFirstProperty(TracingConstants.CONFIG_SAMPLER_TYPE) != null ?
            configuration.getFirstProperty(TracingConstants.CONFIG_SAMPLER_TYPE)
            : TracingConstants.DEFAULT_SAMPLER_TYPE;

    float samplerParam = configuration.getFirstProperty(TracingConstants.CONFIG_SAMPLER_PARAM) != null ?
            Float.parseFloat(configuration.getFirstProperty(TracingConstants.CONFIG_SAMPLER_PARAM))
            : TracingConstants.DEFAULT_SAMPLER_PARAM;

    int reporterFlushInterval =
            configuration.getFirstProperty(TracingConstants.CONFIG_REPORTER_FLUSH_INTERVAL) != null ?
            Integer.parseInt(configuration.getFirstProperty(TracingConstants.CONFIG_REPORTER_FLUSH_INTERVAL))
            : TracingConstants.DEFAULT_REPORTER_FLUSH_INTERVAL;

    int reporterBufferSize = configuration.getFirstProperty(TracingConstants.CONFIG_REPORTER_BUFFER_SIZE) != null ?
            Integer.parseInt(configuration.getFirstProperty(TracingConstants.CONFIG_REPORTER_BUFFER_SIZE))
            : TracingConstants.DEFAULT_REPORTER_BUFFER_SIZE;

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

    Configuration.SamplerConfiguration samplerConfig = new Configuration.SamplerConfiguration()
            .withType(samplerType)
            .withParam(samplerParam);
    Configuration.SenderConfiguration senderConfig = new Configuration.SenderConfiguration()
            .withAgentHost(hostname)
            .withAgentPort(port);
    Configuration.ReporterConfiguration reporterConfig = new Configuration.ReporterConfiguration()
            .withLogSpans(true)
            .withFlushInterval(reporterFlushInterval)
            .withMaxQueueSize(reporterBufferSize)
            .withSender(senderConfig);

    Tracer tracer = new Configuration(serviceName).withSampler(samplerConfig)
            .withReporter(reporterConfig).getTracer();

    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;
    }
}