io.opencensus.trace.config.TraceConfig Java Examples

The following examples show how to use io.opencensus.trace.config.TraceConfig. 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: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public static boolean setupExporter() {
  boolean enable = setupStackdriverTraceExporter();
  setupStackdriverStatsExporter();
  if (enable) {
    TraceConfig traceConfig = Tracing.getTraceConfig();
    traceConfig.updateActiveTraceParams(
        traceConfig
            .getActiveTraceParams()
            .toBuilder()
            .setSampler(PROBABILITY_SAMPLER_MIDDLE)
            .build());
    enabledExporter = true;
    System.setProperty("meghanada.stackdriver.enable", "true");
    java.util.logging.LogManager.getLogManager().reset();
  }
  return enable;
}
 
Example #2
Source File: MultiSpansTracing.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Main method.
 *
 * @param args the main arguments.
 */
public static void main(String[] args) {

  // WARNING: Be careful before you set sampler value to always sample, especially in
  // production environment. Trace data is often very large in size and is expensive to
  // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
  // downsampling is prefered.
  //
  // By default, OpenCensus provides a probabilistic sampler that will trace once in every
  // 10,000 requests, that's why if default probabilistic sampler is used
  // you might not see trace data printed or exported and this is expected behavior.

  TraceConfig traceConfig = Tracing.getTraceConfig();
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  LoggingTraceExporter.register();
  doWork();

  // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
  // Spans are exported every 5 seconds
  sleep(5100);
}
 
Example #3
Source File: MultiSpansScopedTracing.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Main method.
 *
 * @param args the main arguments.
 */
public static void main(String[] args) {

  // WARNING: Be careful before you set sampler value to always sample, especially in
  // production environment. Trace data is often very large in size and is expensive to
  // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
  // downsampling is prefered.
  //
  // By default, OpenCensus provides a probabilistic sampler that will trace once in every
  // 10,000 requests, that's why if default probabilistic sampler is used
  // you might not see trace data printed or exported and this is expected behavior.

  TraceConfig traceConfig = Tracing.getTraceConfig();
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  LoggingTraceExporter.register();
  try (Scope ss = tracer.spanBuilderWithExplicitParent("MyRootSpan", null).startScopedSpan()) {
    doWork();
  }

  // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
  // Spans are exported every 5 seconds
  sleep(5100);
}
 
Example #4
Source File: TracerImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
TracerImpl(
    RandomHandler randomHandler,
    RecordEventsSpanImpl.StartEndHandler startEndHandler,
    Clock clock,
    TraceConfig traceConfig) {
  spanBuilderOptions =
      new SpanBuilderImpl.Options(randomHandler, startEndHandler, clock, traceConfig);
}
 
Example #5
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private synchronized void sendCurrentConfig() {
  // Bouncing back CurrentLibraryConfig to Agent.
  io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto =
      TraceProtoUtils.getCurrentTraceConfig(traceConfig);
  CurrentLibraryConfig currentLibraryConfig =
      CurrentLibraryConfig.newBuilder().setConfig(currentTraceConfigProto).build();
  sendCurrentConfig(currentLibraryConfig);
}
 
Example #6
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
synchronized void sendInitialMessage(Node node) {
  io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto =
      TraceProtoUtils.getCurrentTraceConfig(traceConfig);
  // First config must have Node set.
  CurrentLibraryConfig firstConfig =
      CurrentLibraryConfig.newBuilder().setNode(node).setConfig(currentTraceConfigProto).build();
  sendCurrentConfig(firstConfig);
}
 
Example #7
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
static OcAgentTraceServiceConfigRpcHandler create(
    TraceServiceStub stub, TraceConfig traceConfig) {
  OcAgentTraceServiceConfigRpcHandler configRpcHandler =
      new OcAgentTraceServiceConfigRpcHandler(traceConfig);
  UpdatedLibraryConfigObserver updatedLibraryConfigObserver =
      new UpdatedLibraryConfigObserver(traceConfig, configRpcHandler);
  try {
    StreamObserver<CurrentLibraryConfig> currentConfigObserver =
        stub.config(updatedLibraryConfigObserver);
    configRpcHandler.setCurrentConfigObserver(currentConfigObserver);
  } catch (StatusRuntimeException e) {
    configRpcHandler.onComplete(e);
  }
  return configRpcHandler;
}
 
Example #8
Source File: BasicSetup.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * Enables OpenCensus metric and traces.
 *
 * <p>This will register all basic {@link io.opencensus.stats.View}s. When coupled with an agent,
 * it allows users to monitor application behavior.
 *
 * <p>Example usage for maven:
 *
 * <pre>{@code
 * <dependency>
 *   <groupId>io.opencensus</groupId>
 *   <artifactId>opencensus-contrib-observability-ready-util</artifactId>
 *   <version>${opencensus.version}</version>
 * </dependency>
 * }</pre>
 *
 * <p>It is recommended to call this method before doing any RPC call to avoid missing stats.
 *
 * <pre>{@code
 * BasicSetup.enableOpenCensus();
 * }</pre>
 *
 * @param endPoint the end point of OC-Agent.
 * @param probability the desired probability of sampling. Must be within [0.0, 1.0].
 * @since 0.25
 */
public static void enableOpenCensus(String endPoint, double probability) {
  // register basic rpc views
  RpcViews.registerAllGrpcBasicViews();

  // set sampling rate
  TraceConfig traceConfig = Tracing.getTraceConfig();
  TraceParams activeTraceParams = traceConfig.getActiveTraceParams();
  traceConfig.updateActiveTraceParams(
      activeTraceParams.toBuilder().setSampler(Samplers.probabilitySampler(probability)).build());

  String serviceName = firstNonNull(System.getenv("SERVICE_NAME"), DEAFULT_SERVICE_NAME);
  // create and register Trace Agent Exporter
  OcAgentTraceExporter.createAndRegister(
      OcAgentTraceExporterConfiguration.builder()
          .setEndPoint(endPoint)
          .setServiceName(serviceName)
          .setUseInsecure(true)
          .setEnableConfig(false)
          .build());

  // create and register Metrics Agent Exporter
  OcAgentMetricsExporter.createAndRegister(
      OcAgentMetricsExporterConfiguration.builder()
          .setEndPoint(endPoint)
          .setServiceName(serviceName)
          .setUseInsecure(true)
          .build());
}
 
Example #9
Source File: SpanBuilderImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
Options(
    RandomHandler randomHandler,
    RecordEventsSpanImpl.StartEndHandler startEndHandler,
    Clock clock,
    TraceConfig traceConfig) {
  this.randomHandler = checkNotNull(randomHandler, "randomHandler");
  this.startEndHandler = checkNotNull(startEndHandler, "startEndHandler");
  this.clock = checkNotNull(clock, "clock");
  this.traceConfig = checkNotNull(traceConfig, "traceConfig");
}
 
Example #10
Source File: MetaStoreServer.java    From metastore with Apache License 2.0 5 votes vote down vote up
/** Main method. This comment makes the linter happy. */
public static void main(String[] args) throws Exception {
  LOG.info("MetaStore server");
  printVersion();

  ArgumentParser parser = ArgumentParsers.newFor("metastore").build();
  parser.addArgument("-c", "--config").required(false);

  Namespace res = parser.parseArgs(args);
  String configPath = res.getString("config");
  if (configPath == null) {
    LOG.info("No configuration file set via argument, setting from environment.");
    configPath = System.getenv("METASTORE_CONFIG_PATH");
    LOG.info("Taking configuration file: " + configPath);
  } else {
    LOG.info("Taking configuration file: " + configPath);
  }

  // 2. Configure 100% sample rate, otherwise, few traces will be sampled.
  TraceConfig traceConfig = Tracing.getTraceConfig();
  TraceParams activeTraceParams = traceConfig.getActiveTraceParams();
  traceConfig.updateActiveTraceParams(
      activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build());

  String port = System.getenv("PORT");
  if (port == null) {
    port = "8980";
  }
  MetaStoreServer server = new MetaStoreServer(configPath, Integer.valueOf(port));
  server.start();
  server.blockUntilShutdown();
}
 
Example #11
Source File: HelloWorldServer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void initTracing() {
  TraceConfig traceConfig = Tracing.getTraceConfig();

  // default sampler is set to Samplers.alwaysSample() for demonstration. In production
  // or in high QPS environment please use default sampler.
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  // Register LoggingTraceExporter to see traces in logs.
  LoggingTraceExporter.register();

  // Register Jaeger Tracing. Refer to https://www.jaegertracing.io/docs/1.8/getting-started/ to
  // run Jaeger
  JaegerTraceExporter.createAndRegister("http://localhost:14268/api/traces", "helloworldserver");
}
 
Example #12
Source File: Application.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void initTracingAndLoggingExporter() {
  TraceConfig traceConfig = Tracing.getTraceConfig();
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  LoggingTraceExporter.register();
}
 
Example #13
Source File: HelloWorldClient.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void initTracing() {
  TraceConfig traceConfig = Tracing.getTraceConfig();
  Logger.getRootLogger().setLevel(Level.INFO);
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  LoggingTraceExporter.register();
  // Register Jaeger Tracing. Refer to https://www.jaegertracing.io/docs/1.8/getting-started/ to
  // run Jaeger
  JaegerTraceExporter.createAndRegister("http://localhost:14268/api/traces", "helloworldclient");
}
 
Example #14
Source File: MultiSpansContextTracing.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * Main method.
 *
 * @param args the main arguments.
 */
public static void main(String[] args) {

  // WARNING: Be careful before you set sampler value to always sample, especially in
  // production environment. Trace data is often very large in size and is expensive to
  // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
  // downsampling is prefered.
  //
  // By default, OpenCensus provides a probabilistic sampler that will trace once in every
  // 10,000 requests, that's why if default probabilistic sampler is used
  // you might not see trace data printed or exported and this is expected behavior.

  TraceConfig traceConfig = Tracing.getTraceConfig();
  traceConfig.updateActiveTraceParams(
      traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

  LoggingTraceExporter.register();
  Span span = tracer.spanBuilderWithExplicitParent("MyRootSpan", null).startSpan();
  try (Scope ws = tracer.withSpan(span)) {
    doWork();
  }
  span.end();

  // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
  // Spans are exported every 5 seconds
  sleep(5100);
}
 
Example #15
Source File: OcAgentExportersQuickStart.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private static void configureAlwaysSample() {
  TraceConfig traceConfig = Tracing.getTraceConfig();
  TraceParams activeTraceParams = traceConfig.getActiveTraceParams();
  traceConfig.updateActiveTraceParams(
      activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build());
}
 
Example #16
Source File: HeroicCore.java    From heroic with Apache License 2.0 4 votes vote down vote up
private void enableTracing(TracingConfig config) throws IOException {
    final TracingConfig.Lightstep lightstep = config.getLightstep();

    if (!lightstep.getCollectorHost().isBlank()) {
        final Options.OptionsBuilder optionsBuilder = new Options.OptionsBuilder()
            .withAccessToken(lightstep.getAccessToken())
            .withMaxReportingIntervalMillis(lightstep.getReportingIntervalMs())
            .withMaxBufferedSpans(lightstep.getMaxBufferedSpans())
            .withCollectorProtocol("http")
            .withResetClient(lightstep.getResetClient())
            .withComponentName(lightstep.getComponentName())
            .withCollectorHost(lightstep.getCollectorHost())
            .withCollectorPort(lightstep.getCollectorPort());

        final Options options;
        try {
            options = optionsBuilder.build();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Malformed configuration for LightStep.", e);
        }

        log.info("Creating LightStep tracing exporter");
        LightStepExporterHandler handler =
            new LightStepExporterHandler(new JRETracer(options));
        log.info("Registering LightStep exporter as the SquashingTraceExporter delegate");
        SquashingTraceExporter.createAndRegister(
            handler,
            config.getSquash().getThreshold(),
            config.getSquash().getWhitelist()
        );

        log.info("Setting global trace probability to {}", config.getProbability());
        TraceConfig traceConfig = Tracing.getTraceConfig();
        traceConfig.updateActiveTraceParams(
            traceConfig
                .getActiveTraceParams()
                .toBuilder()
                .setSampler(Samplers.probabilitySampler(config.getProbability()))
                .build());
    }

    if (config.getZpagesPort() > 0) {
        log.info("Starting zpage handlers on port {}", config.getZpagesPort());
        // Start a web server for tracing data
        ZPageHandlers.startHttpServerAndRegisterAll(config.getZpagesPort());
    }
}
 
Example #17
Source File: OcAgentTraceExporterIntegrationTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testExportSpans() throws InterruptedException, IOException {
  // Mock a real-life scenario in production, where Agent is not enabled at first, then enabled
  // after an outage. Users should be able to see traces shortly after Agent is up.

  // Configure to be always-sampled.
  TraceConfig traceConfig = Tracing.getTraceConfig();
  TraceParams activeTraceParams = traceConfig.getActiveTraceParams();
  traceConfig.updateActiveTraceParams(
      activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build());

  // Register the OcAgent Exporter first.
  // Agent is not yet up and running so Exporter will just retry connection.
  OcAgentTraceExporter.createAndRegister(
      OcAgentTraceExporterConfiguration.builder()
          .setServiceName(SERVICE_NAME)
          .setUseInsecure(true)
          .setEnableConfig(false)
          .build());

  // Create one root span and 5 children.
  try (Scope scope = tracer.spanBuilder("root").startScopedSpan()) {
    for (int i = 0; i < 5; i++) {
      // Fake work
      doWork("first-iteration-child-" + i, i);
    }
  }

  // Wait 5s so that SpanExporter exports exports all spans.
  Thread.sleep(5000);

  // No interaction with Agent so far.
  assertThat(fakeOcAgentTraceServiceGrpc.getExportTraceServiceRequests()).isEmpty();

  // Image an outage happened, now start Agent. Exporter should be able to connect to Agent
  // when the next batch of SpanData arrives.
  agent.start();

  // Create one root span and 8 children.
  try (Scope scope = tracer.spanBuilder("root2").startScopedSpan()) {
    for (int i = 0; i < 8; i++) {
      // Fake work
      doWork("second-iteration-child-" + i, i);
    }
  }

  // Wait 5s so that SpanExporter exports exports all spans.
  Thread.sleep(5000);

  List<ExportTraceServiceRequest> exportRequests =
      fakeOcAgentTraceServiceGrpc.getExportTraceServiceRequests();
  assertThat(exportRequests.size()).isAtLeast(2);

  ExportTraceServiceRequest firstRequest = exportRequests.get(0);
  Node expectedNode = OcAgentNodeUtils.getNodeInfo(SERVICE_NAME);
  Node actualNode = firstRequest.getNode();
  assertThat(actualNode.getIdentifier().getHostName())
      .isEqualTo(expectedNode.getIdentifier().getHostName());
  assertThat(actualNode.getIdentifier().getPid())
      .isEqualTo(expectedNode.getIdentifier().getPid());
  assertThat(actualNode.getLibraryInfo()).isEqualTo(expectedNode.getLibraryInfo());
  assertThat(actualNode.getServiceInfo()).isEqualTo(expectedNode.getServiceInfo());

  List<io.opencensus.proto.trace.v1.Span> spanProtos = new ArrayList<>();
  for (int i = 1; i < exportRequests.size(); i++) {
    spanProtos.addAll(exportRequests.get(i).getSpansList());
  }

  // On some platforms (e.g Windows) SpanData will never be dropped, so spans from the first batch
  // may also be exported after Agent is up.
  assertThat(spanProtos.size()).isAtLeast(9);

  Set<String> exportedSpanNames = new HashSet<>();
  for (io.opencensus.proto.trace.v1.Span spanProto : spanProtos) {
    if ("root2".equals(spanProto.getName().getValue())) {
      assertThat(spanProto.getChildSpanCount().getValue()).isEqualTo(8);
      assertThat(spanProto.getParentSpanId()).isEqualTo(ByteString.EMPTY);
    } else if ("root".equals(spanProto.getName().getValue())) {
      // This won't happen on Linux but does happen on Windows.
      assertThat(spanProto.getChildSpanCount().getValue()).isEqualTo(5);
      assertThat(spanProto.getParentSpanId()).isEqualTo(ByteString.EMPTY);
    }
    exportedSpanNames.add(spanProto.getName().getValue());
  }

  // The second batch of spans should be exported no matter what.
  assertThat(exportedSpanNames).contains("root2");
  for (int i = 0; i < 8; i++) {
    assertThat(exportedSpanNames).contains("second-iteration-child-" + i);
  }
}
 
Example #18
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
UpdatedLibraryConfigObserver(
    TraceConfig traceConfig, OcAgentTraceServiceConfigRpcHandler configRpcHandler) {
  this.traceConfig = traceConfig;
  this.configRpcHandler = configRpcHandler;
}
 
Example #19
Source File: TraceComponentImplLite.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TraceConfig getTraceConfig() {
  return traceComponentImplBase.getTraceConfig();
}
 
Example #20
Source File: TraceComponentImplLite.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TraceConfig getTraceConfig() {
  return traceComponentImplBase.getTraceConfig();
}
 
Example #21
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private OcAgentTraceServiceConfigRpcHandler(TraceConfig traceConfig) {
  this.traceConfig = traceConfig;
}
 
Example #22
Source File: OcHttpServletFilter.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/** Creates a new {@code OcHttpServletFilter}. */
public OcHttpServletFilter() {
  TraceConfig traceConfig = Tracing.getTraceConfig();
  traceConfig.updateActiveTraceParams(traceConfig.getActiveTraceParams().toBuilder().build());
  handler = buildHttpServerHandler();
}
 
Example #23
Source File: TraceConfigzZPageHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private TraceConfigzZPageHandler(TraceConfig traceConfig) {
  this.traceConfig = traceConfig;
}
 
Example #24
Source File: TraceConfigzZPageHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
static TraceConfigzZPageHandler create(TraceConfig traceConfig) {
  return new TraceConfigzZPageHandler(traceConfig);
}
 
Example #25
Source File: TraceComponentImpl.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TraceConfig getTraceConfig() {
  return traceComponentImplBase.getTraceConfig();
}
 
Example #26
Source File: TraceComponentImpl.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TraceConfig getTraceConfig() {
  return traceComponentImplBase.getTraceConfig();
}
 
Example #27
Source File: TraceComponentImplBase.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
public TraceConfig getTraceConfig() {
  return traceConfig;
}
 
Example #28
Source File: TracingTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void defaultTraceConfig() {
  assertThat(Tracing.getTraceConfig()).isSameInstanceAs(TraceConfig.getNoopTraceConfig());
}
 
Example #29
Source File: TraceComponentTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void defaultTraceConfig() {
  assertThat(TraceComponent.newNoopTraceComponent().getTraceConfig())
      .isSameInstanceAs(TraceConfig.getNoopTraceConfig());
}
 
Example #30
Source File: TraceComponent.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TraceConfig getTraceConfig() {
  return TraceConfig.getNoopTraceConfig();
}