io.opencensus.contrib.grpc.metrics.RpcViews Java Examples

The following examples show how to use io.opencensus.contrib.grpc.metrics.RpcViews. 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: Poller.java    From spanner-event-exporter with Apache License 2.0 6 votes vote down vote up
private void configureTracing() {
  try {
    // Installs a handler for /tracez page.
    ZPageHandlers.startHttpServerAndRegisterAll(8080);
    // Installs an exporter for stack driver traces.
    StackdriverExporter.createAndRegister();
    Tracing.getExportComponent()
        .getSampledSpanStore()
        .registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));

    // Installs an exporter for stack driver stats.
    StackdriverStatsExporter.createAndRegister();
    RpcViews.registerAllCumulativeViews();
  } catch (IOException e) {
    log.error("Could not start the tracing server", e);
  }
}
 
Example #2
Source File: HelloWorldServer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Main launches the server from the command line. */
public static void main(String[] args) throws IOException, InterruptedException {
  // Add final keyword to pass checkStyle.
  final int serverPort = getPortOrDefaultFromArgs(args, 0, 50051);
  final String cloudProjectId = getStringOrDefaultFromArgs(args, 1, null);
  final int zPagePort = getPortOrDefaultFromArgs(args, 2, 3000);
  final int prometheusPort = getPortOrDefaultFromArgs(args, 3, 9090);

  // Registers all RPC views. For demonstration all views are registered. You may want to
  // start with registering basic views and register other views as needed for your application.
  RpcViews.registerAllViews();

  // Registers logging trace exporter.
  LoggingTraceExporter.register();

  // Starts a HTTP server and registers all Zpages to it.
  ZPageHandlers.startHttpServerAndRegisterAll(zPagePort);
  logger.info("ZPages server starts at localhost:" + zPagePort);

  // Registers Stackdriver exporters.
  if (cloudProjectId != null) {
    StackdriverTraceExporter.createAndRegister(
        StackdriverTraceConfiguration.builder().setProjectId(cloudProjectId).build());
    StackdriverStatsExporter.createAndRegister(
        StackdriverStatsConfiguration.builder()
            .setProjectId(cloudProjectId)
            .setExportInterval(Duration.create(60, 0))
            .build());
  }

  // Register Prometheus exporters and export metrics to a Prometheus HTTPServer.
  PrometheusStatsCollector.createAndRegister();
  HTTPServer prometheusServer = new HTTPServer(prometheusPort, true);

  // Start the RPC server. You shouldn't see any output from gRPC before this.
  logger.info("gRPC starting.");
  final HelloWorldServer server = new HelloWorldServer(serverPort);
  server.start();
  server.blockUntilShutdown();
}
 
Example #3
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 #4
Source File: ZPagesTester.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private static void recordExampleData() throws InterruptedException {
  Tracing.getExportComponent()
      .getSampledSpanStore()
      .registerSpanNamesForCollection(Collections.singletonList(SPAN_NAME));
  RpcViews.registerAllViews(); // Use old RPC constants to get interval stats.
  SpanBuilder spanBuilder =
      tracer.spanBuilder(SPAN_NAME).setRecordEvents(true).setSampler(Samplers.alwaysSample());

  try (Scope scope = spanBuilder.startScopedSpan()) {
    tracer.getCurrentSpan().addAnnotation("Starts recording.");
    MeasureMap measureMap =
        statsRecorder
            .newMeasureMap()
            // Client measurements.
            .put(RpcMeasureConstants.RPC_CLIENT_STARTED_COUNT, 1)
            .put(RpcMeasureConstants.RPC_CLIENT_FINISHED_COUNT, 1)
            .put(RpcMeasureConstants.RPC_CLIENT_ROUNDTRIP_LATENCY, 1.0)
            .put(RpcMeasureConstants.RPC_CLIENT_REQUEST_COUNT, 1)
            .put(RpcMeasureConstants.RPC_CLIENT_RESPONSE_COUNT, 1)
            .put(RpcMeasureConstants.RPC_CLIENT_REQUEST_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_CLIENT_RESPONSE_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES, 1e5)
            // Server measurements.
            .put(RpcMeasureConstants.RPC_SERVER_STARTED_COUNT, 1)
            .put(RpcMeasureConstants.RPC_SERVER_FINISHED_COUNT, 1)
            .put(RpcMeasureConstants.RPC_SERVER_SERVER_LATENCY, 1.0)
            .put(RpcMeasureConstants.RPC_SERVER_REQUEST_COUNT, 1)
            .put(RpcMeasureConstants.RPC_SERVER_RESPONSE_COUNT, 1)
            .put(RpcMeasureConstants.RPC_SERVER_REQUEST_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_SERVER_RESPONSE_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES, 1e5)
            .put(RpcMeasureConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES, 1e5);
    measureMap.record(
        tagger
            .currentBuilder()
            .put(RpcMeasureConstants.RPC_STATUS, TagValue.create("OK"))
            .put(RpcMeasureConstants.RPC_METHOD, METHOD)
            .build());
    MeasureMap measureMapErrors =
        statsRecorder
            .newMeasureMap()
            .put(RpcMeasureConstants.RPC_CLIENT_ERROR_COUNT, 1)
            .put(RpcMeasureConstants.RPC_SERVER_ERROR_COUNT, 1);
    measureMapErrors.record(
        tagger
            .currentBuilder()
            .put(RpcMeasureConstants.RPC_STATUS, TagValue.create("UNKNOWN"))
            .put(RpcMeasureConstants.RPC_METHOD, METHOD)
            .build());

    Thread.sleep(200); // sleep for fake work.
    tracer.getCurrentSpan().addAnnotation("Finish recording.");
  }
}
 
Example #5
Source File: HelloWorldClient.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/**
 * Greet server. If provided, the first element of {@code args} is the name to use in the
 * greeting.
 */
public static void main(String[] args) throws IOException, InterruptedException {
  // Add final keyword to pass checkStyle.
  final String user = getStringOrDefaultFromArgs(args, 0, "world");
  final String host = getStringOrDefaultFromArgs(args, 1, "localhost");
  final int serverPort = getPortOrDefaultFromArgs(args, 2, 50051);
  final String cloudProjectId = getStringOrDefaultFromArgs(args, 3, null);
  final int zPagePort = getPortOrDefaultFromArgs(args, 4, 3001);

  // Registers all RPC views. For demonstration all views are registered. You may want to
  // start with registering basic views and register other views as needed for your application.
  RpcViews.registerAllViews();

  // Starts a HTTP server and registers all Zpages to it.
  ZPageHandlers.startHttpServerAndRegisterAll(zPagePort);
  logger.info("ZPages server starts at localhost:" + zPagePort);

  // Registers logging trace exporter.
  LoggingTraceExporter.register();

  // Registers Stackdriver exporters.
  if (cloudProjectId != null) {
    StackdriverTraceExporter.createAndRegister(
        StackdriverTraceConfiguration.builder().setProjectId(cloudProjectId).build());
    StackdriverStatsExporter.createAndRegister(
        StackdriverStatsConfiguration.builder()
            .setProjectId(cloudProjectId)
            .setExportInterval(Duration.create(60, 0))
            .build());
  }

  // Register Prometheus exporters and export metrics to a Prometheus HTTPServer.
  PrometheusStatsCollector.createAndRegister();

  HelloWorldClient client = new HelloWorldClient(host, serverPort);
  try {
    client.greet(user);
  } finally {
    client.shutdown();
  }

  logger.info("Client sleeping, ^C to exit. Meanwhile you can view stats and spans on zpages.");
  while (true) {
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      logger.info("Exiting HelloWorldClient...");
    }
  }
}
 
Example #6
Source File: TracingSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length != 2) {
    System.err.println("Usage: TracingSample <instance_id> <database_id>");
    return;
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();

  // Installs a handler for /tracez page.
  ZPageHandlers.startHttpServerAndRegisterAll(8080);
  // Installs an exporter for stack driver traces.
  StackdriverExporter.createAndRegister();
  Tracing.getExportComponent()
      .getSampledSpanStore()
      .registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));

  // Installs an exporter for stack driver stats.
  StackdriverStatsExporter.createAndRegister();
  RpcViews.registerAllCumulativeViews();

  // Name of your instance & database.
  String instanceId = args[0];
  String databaseId = args[1];
  try {
    // Creates a database client
    DatabaseClient dbClient =
        spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
    // Queries the database
    try (Scope ss =
        Tracing.getTracer()
            .spanBuilderWithExplicitParent(SAMPLE_SPAN, null)
            .setSampler(Samplers.alwaysSample())
            .startScopedSpan()) {
      ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));

      System.out.println("\n\nResults:");
      // Prints the results
      while (resultSet.next()) {
        System.out.printf("%d\n\n", resultSet.getLong(0));
      }
    }
  } finally {
    // Closes the client which will free up the resources used
    spanner.close();
  }
}
 
Example #7
Source File: HelloWorld.java    From cloud-bigtable-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
  // Consult system properties to get project/instance
  String projectId = requiredProperty("bigtable.projectID");
  String instanceId = requiredProperty("bigtable.instanceID");

  try {
    // Force tracing for every request for demo purposes.  Use the default settings
    // in most cases.
    Tracing.getTraceConfig().updateActiveTraceParams(
        TraceParams.DEFAULT.toBuilder().setSampler(Samplers.probabilitySampler(1)).build());

    StackdriverTraceExporter.createAndRegister(
        StackdriverTraceConfiguration.builder()
            .setProjectId(projectId)
            .build());

    // Enable stats exporter to Stackdriver with a 5 second export time.
    // Production settings may vary.
    StackdriverStatsExporter.createAndRegister(
          StackdriverStatsConfiguration.builder()
              .setProjectId(projectId)
              .setExportInterval(Duration.create(5, 0))
              .build());

    RpcViews.registerAllGrpcViews();

    // HBase Bigtable specific setup for zpages
    HBaseTracingUtilities.setupTracingConfig();

    // Start a web server on port 8080 for tracing data
    ZPageHandlers.startHttpServerAndRegisterAll(8080);

    doHelloWorld(projectId, instanceId);

  } finally {
    System.out.println("Sleeping for 1 minute so that you can view http://localhost:8080/tracez");

    // Sleep for 1 minute.
    TimeUnit.MINUTES.sleep(1);

    // Terminating this program manually as Http-server prevents it from auto shutdown
    System.exit(0);
  }
}