Java Code Examples for io.opencensus.trace.Span#end()

The following examples show how to use io.opencensus.trace.Span#end() . 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: MetricReader.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the metrics from the {@link MetricProducerManager} and exports them to the {@code
 * metricExporter}.
 *
 * @param metricExporter the exporter called to export the metrics read.
 * @since 0.19
 */
public void readAndExport(MetricExporter metricExporter) {
  Span span =
      tracer
          .spanBuilder(spanName)
          .setRecordEvents(true)
          .setSampler(probabilitySampler)
          .startSpan();
  Scope scope = tracer.withSpan(span);
  try {
    ArrayList<Metric> metricsList = new ArrayList<>();
    for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) {
      metricsList.addAll(metricProducer.getMetrics());
    }
    metricExporter.export(metricsList);
  } catch (Throwable e) {
    logger.log(Level.WARNING, "Exception thrown by the metrics exporter.", e);
    span.setStatus(
        Status.UNKNOWN.withDescription("Exception when export metrics: " + exceptionMessage(e)));
  } finally {
    scope.close();
    span.end();
  }
}
 
Example 2
Source File: BigtableMutatorImpl.java    From heroic with Apache License 2.0 6 votes vote down vote up
private BulkMutation getOrAddBulkMutation(String tableName) {
    final Span span = tracer.spanBuilder("BigtableMutator.getOrAddBulkMutation").startSpan();
    try (Scope ws = tracer.withSpan(span)) {
        span.addAnnotation("Acquiring lock");
        synchronized (tableAccessLock) {
            span.addAnnotation("Lock acquired");

            if (tableToBulkMutation.containsKey(tableName)) {
                span.setStatus(Status.ALREADY_EXISTS.withDescription("Mutation exists in map"));
                span.end();
                return tableToBulkMutation.get(tableName);
            }

            final BulkMutation bulkMutation = session.createBulkMutation(
                session
                    .getOptions()
                    .getInstanceName()
                    .toTableName(tableName));

            tableToBulkMutation.put(tableName, bulkMutation);

            span.end();
            return bulkMutation;
        }
    }
}
 
Example 3
Source File: ZPageHttpHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public final void handle(HttpExchange httpExchange) throws IOException {
  Span span =
      tracer
          .spanBuilderWithExplicitParent(httpServerSpanName, null)
          .setRecordEvents(true)
          .startSpan();
  try (Scope ss = tracer.withSpan(span)) {
    span.putAttribute(
        "/http/method ", AttributeValue.stringAttributeValue(httpExchange.getRequestMethod()));
    httpExchange.sendResponseHeaders(200, 0);
    zpageHandler.emitHtml(
        uriQueryToMap(httpExchange.getRequestURI()), httpExchange.getResponseBody());
  } finally {
    httpExchange.close();
    span.end(END_SPAN_OPTIONS);
  }
}
 
Example 4
Source File: BasicOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create a child span. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span createSpanWithExplicitParent(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent("ChildSpan", data.span)
          .setRecordEvents(data.recorded)
          .setSampler(data.sampled ? Samplers.alwaysSample() : Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 5
Source File: AbstractHttpHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
void spanEnd(Span span, int httpStatus, @Nullable Throwable error) {
  if (span.getOptions().contains(Options.RECORD_EVENTS)) {
    span.putAttribute(
        HttpTraceAttributeConstants.HTTP_STATUS_CODE,
        AttributeValue.longAttributeValue(httpStatus));
    span.setStatus(HttpTraceUtil.parseResponseStatus(httpStatus, error));
  }
  span.end();
}
 
Example 6
Source File: InProcessSampledSpanStoreImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private void addSpanNameToAllErrorBuckets(String spanName) {
  for (CanonicalCode code : CanonicalCode.values()) {
    if (code != CanonicalCode.OK) {
      Span sampledSpan = createSampledSpan(spanName);
      Span notSampledSpan = createNotSampledSpan(spanName);
      testClock.advanceTime(Duration.create(0, 1000));
      sampledSpan.end(EndSpanOptions.builder().setStatus(code.toStatus()).build());
      notSampledSpan.end(EndSpanOptions.builder().setStatus(code.toStatus()).build());
    }
  }
}
 
Example 7
Source File: CoreIngestionGroup.java    From heroic with Apache License 2.0 5 votes vote down vote up
protected AsyncFuture<Ingestion> syncWrite(final Request request) {
    final Span span = tracer.spanBuilder("CoreIngestionGroup.syncWrite").startSpan();

    if (!filter.get().apply(request.getSeries())) {
        reporter.reportDroppedByFilter();
        span.setStatus(Status.FAILED_PRECONDITION.withDescription("Dropped by filter"));
        span.end();
        return async.resolved(Ingestion.of(ImmutableList.of()));
    }

    try {
        span.addAnnotation("Acquiring write lock");
        writePermits.acquire();
    } catch (final InterruptedException e) {
        String error = "Failed to acquire semaphore for bounded request";
        span.setStatus(Status.INTERNAL.withDescription(error));
        span.end();
        return async.failed(new Exception(error, e));
    }

    span.addAnnotation("Acquired write lock");
    reporter.incrementConcurrentWrites();

    try (Scope ws = tracer.withSpan(span)) {
        return doWrite(request).onFinished(() -> {
            writePermits.release();
            reporter.decrementConcurrentWrites();
            span.end();
        });
    }
}
 
Example 8
Source File: BasicOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create a child span from the current span. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span createSpanWithCurrentSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilder("ChildSpanFromCurrent")
          .setRecordEvents(data.recorded)
          .setSampler(data.sampled ? Samplers.alwaysSample() : Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 9
Source File: BasicOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create a child span with a remote parent. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span createSpanWithRemoteParent(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithRemoteParent("ChildSpanFromRemoteParent", data.span.getContext())
          .setRecordEvents(data.recorded)
          .setSampler(data.sampled ? Samplers.alwaysSample() : Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 10
Source File: MultiSpansTracing.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void doWork() {
  Span rootSpan = tracer.spanBuilderWithExplicitParent("MyRootSpan", null).startSpan();
  rootSpan.addAnnotation("Annotation to the root Span before child is created.");
  Span childSpan = tracer.spanBuilderWithExplicitParent("MyChildSpan", rootSpan).startSpan();
  childSpan.addAnnotation("Annotation to the child Span");
  childSpan.end();
  rootSpan.addAnnotation("Annotation to the root Span after child is ended.");
  rootSpan.end();
}
 
Example 11
Source File: BasicOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create a root span. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span createRootSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent("RootSpan", null)
          .setRecordEvents(data.recorded)
          .setSampler(data.sampled ? Samplers.alwaysSample() : Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 12
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a sampled child {@code Span}.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndSampledChildSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent(SPAN_NAME, data.rootSpan)
          .setSampler(Samplers.alwaysSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 13
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a child {@code Span} with
 * record events option.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndRecordEventsChildSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent(SPAN_NAME, data.rootSpan)
          .setSampler(Samplers.neverSample())
          .setRecordEvents(true)
          .startSpan();
  span.end();
  return span;
}
 
Example 14
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a non-sampled child {@code
 * Span}.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndNonSampledChildSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent(SPAN_NAME, data.rootSpan)
          .setSampler(Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 15
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a sampled root {@code Span}.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndSampledRootSpan(Data data) {
  Span span = data.tracer.spanBuilder(SPAN_NAME).setSampler(Samplers.alwaysSample()).startSpan();
  span.end();
  return span;
}
 
Example 16
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a root {@code Span} with record
 * events option.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndRecordEventsRootSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent(SPAN_NAME, null)
          .setSampler(Samplers.neverSample())
          .setRecordEvents(true)
          .startSpan();
  span.end();
  return span;
}
 
Example 17
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark attempts to measure performance of start/end for a non-sampled root {@code
 * Span}.
 */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span startEndNonSampledRootSpan(Data data) {
  Span span =
      data.tracer
          .spanBuilderWithExplicitParent(SPAN_NAME, null)
          .setSampler(Samplers.neverSample())
          .startSpan();
  span.end();
  return span;
}
 
Example 18
Source File: MultiSpansContextTracing.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void doSomeMoreWork() {
  // Create a child Span of the current Span.
  Span span = tracer.spanBuilder("MyChildSpan").startSpan();
  try (Scope ws = tracer.withSpan(span)) {
    doSomeOtherWork();
  }
  span.end();
}
 
Example 19
Source File: SpanBuilderImplTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void startRemoteChildSpan_WithProbabilitySamplerDefaultSampler() {
  when(traceConfig.getActiveTraceParams()).thenReturn(TraceParams.DEFAULT);
  // This traceId will not be sampled by the ProbabilitySampler because the first 8 bytes as long
  // is not less than probability * Long.MAX_VALUE;
  TraceId traceId =
      TraceId.fromBytes(
          new byte[] {
            (byte) 0x8F,
            (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF,
            (byte) 0xFF,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0
          });

  // If parent is sampled then the remote child must be sampled.
  Span childSpan =
      SpanBuilderImpl.createWithRemoteParent(
              SPAN_NAME,
              SpanContext.create(
                  traceId,
                  SpanId.generateRandomId(randomHandler.current()),
                  TraceOptions.builder().setIsSampled(true).build()),
              spanBuilderOptions)
          .startSpan();
  assertThat(childSpan.getContext().isValid()).isTrue();
  assertThat(childSpan.getContext().getTraceId()).isEqualTo(traceId);
  assertThat(childSpan.getContext().getTraceOptions().isSampled()).isTrue();
  childSpan.end();

  assertThat(traceConfig.getActiveTraceParams()).isEqualTo(TraceParams.DEFAULT);

  // If parent is not sampled then the remote child must be not sampled.
  childSpan =
      SpanBuilderImpl.createWithRemoteParent(
              SPAN_NAME,
              SpanContext.create(
                  traceId,
                  SpanId.generateRandomId(randomHandler.current()),
                  TraceOptions.DEFAULT),
              spanBuilderOptions)
          .startSpan();
  assertThat(childSpan.getContext().isValid()).isTrue();
  assertThat(childSpan.getContext().getTraceId()).isEqualTo(traceId);
  assertThat(childSpan.getContext().getTraceOptions().isSampled()).isFalse();
  childSpan.end();
}
 
Example 20
Source File: TraceWebAsyncClientAutoConfigurationTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 10000)
@Order(1)
public void should_close_span_upon_success_callback()
    throws ExecutionException, InterruptedException {
  tracer = Tracing.getTracer();
  Span initialSpan = tracer.spanBuilder("initial").startSpan();

  try (Scope ws = tracer.withSpan(initialSpan)) {
    ListenableFuture<ResponseEntity<String>> future =
        asyncRestTemplate.getForEntity("http://localhost:" + port() + "/async", String.class);
    String result = future.get().getBody();

    assertThat(result).isEqualTo("async");
  } finally {
    initialSpan.end();
  }

  // 3 spans are initial, client, server.
  List<SpanData> spans = handler.waitForExport(3);
  SpanData clientSpan = null;
  for (SpanData span : spans) {
    if (span.getKind() == CLIENT) {
      clientSpan = span;
      assertThat(clientSpan.getName()).isEqualTo("/async");
      assertThat(clientSpan.getStatus().isOk()).isTrue();
      assertThat(
              clientSpan
                  .getAttributes()
                  .getAttributeMap()
                  .get(HttpTraceAttributeConstants.HTTP_METHOD))
          .isEqualTo(AttributeValue.stringAttributeValue("GET"));
      assertThat(
              clientSpan
                  .getAttributes()
                  .getAttributeMap()
                  .get(HttpTraceAttributeConstants.HTTP_HOST))
          .isEqualTo(AttributeValue.stringAttributeValue("localhost"));
      assertThat(
              clientSpan
                  .getAttributes()
                  .getAttributeMap()
                  .get(HttpTraceAttributeConstants.HTTP_PATH))
          .isEqualTo(AttributeValue.stringAttributeValue("/async"));
      assertThat(clientSpan.getKind()).isEqualTo(CLIENT);
      break;
    }
  }
  assertThat(clientSpan).isNotNull();
}