io.opencensus.trace.BlankSpan Java Examples

The following examples show how to use io.opencensus.trace.BlankSpan. 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: CensusModulesTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void traceHeaders_clientMissingCensusImpl_preservingHeaders() throws Exception {
  reset(spyClientSpanBuilder);
  when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
  Metadata headers = new Metadata();
  headers.put(
      Metadata.Key.of("never-used-key-bin", Metadata.BINARY_BYTE_MARSHALLER),
      new byte[] {});
  Set<String> originalHeaderKeys = new HashSet<>(headers.keys());

  CensusTracingModule.ClientCallTracer callTracer =
      censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
  callTracer.newClientStreamTracer(STREAM_INFO, headers);

  assertThat(headers.keys()).containsExactlyElementsIn(originalHeaderKeys);
}
 
Example #2
Source File: CensusModulesTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void traceHeaders_clientMissingCensusImpl_preservingHeaders() throws Exception {
  reset(spyClientSpanBuilder);
  when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
  Metadata headers = new Metadata();
  headers.put(
      Metadata.Key.of("never-used-key-bin", Metadata.BINARY_BYTE_MARSHALLER),
      new byte[] {});
  Set<String> originalHeaderKeys = new HashSet<String>(headers.keys());

  CensusTracingModule.ClientCallTracer callTracer =
      censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
  callTracer.newClientStreamTracer(CallOptions.DEFAULT, headers);

  assertThat(headers.keys()).containsExactlyElementsIn(originalHeaderKeys);
}
 
Example #3
Source File: OpenCensusTracerAdapter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MustBeClosedChecker")
@MustBeClosed
@Override
public Scope activateSpan(Span span) {
  final io.opencensus.trace.Span newSpan;

  if (span instanceof OpenCensusSpanAdapter) {
    final OpenCensusSpanAdapter realSpan = (OpenCensusSpanAdapter) span;
    newSpan = realSpan.getOCSpan();
  } else {
    // Cannot activate non open census spans.
    // Also, noop spans should be remembered internally as blank spans.
    newSpan = BlankSpan.INSTANCE;
  }

  // This can only be called with an adapted span.
  return new OpenCensusScopeAdapter(ocTracer.withSpan(newSpan));
}
 
Example #4
Source File: AbstractMetricBackendIT.java    From heroic with Apache License 2.0 6 votes vote down vote up
private List<MetricCollection> fetchMetrics(FetchData.Request request, boolean slicedFetch)
    throws Exception {
    if (slicedFetch) {
        List<MetricCollection> fetchedMetrics = Collections.synchronizedList(new ArrayList<>());
        backend
            .fetch(request,
                FetchQuotaWatcher.NO_QUOTA,
                mcr -> fetchedMetrics.add(mcr.getMetrics()),
                BlankSpan.INSTANCE)
            .get();
        return fetchedMetrics;
    } else {
        throw new IllegalArgumentException(
            "Tried to read data with non-supported non-sliced code path");
    }
}
 
Example #5
Source File: AbstractMetricBackendIT.java    From heroic with Apache License 2.0 6 votes vote down vote up
private void verifyReadWrite(
    final MetricCollection input, final MetricCollection expected, final DateRange range
) throws Exception {
    backend.write(new WriteMetric.Request(s1, input)).get();

    final List<MetricReadResult> data = Collections.synchronizedList(new ArrayList<>());

    FetchData.Request request =
        new FetchData.Request(expected.getType(), s1, range, QueryOptions.builder().build());

    backend.fetch(request, FetchQuotaWatcher.NO_QUOTA, data::add, BlankSpan.INSTANCE).get();

    final Set<MetricCollection> found =
        data.stream().map(MetricReadResult::getMetrics).collect(Collectors.toSet());

    assertSortedMetricsEqual(ImmutableSet.of(expected), found);
}
 
Example #6
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void enhanceLogEntry_AddBlankSpanToLogEntry() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer("my-test-project-7"), BlankSpan.INSTANCE);
  assertFalse(logEntry.getTraceSampled());
  assertThat(logEntry.getTrace())
      .isEqualTo("projects/my-test-project-7/traces/00000000000000000000000000000000");
  assertThat(logEntry.getSpanId()).isEqualTo("0000000000000000");
}
 
Example #7
Source File: CensusModulesTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void traceHeaders_missingCensusImpl_notPropagateSpanContext()
    throws Exception {
  reset(spyClientSpanBuilder);
  when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
  Metadata headers = new Metadata();

  CensusTracingModule.ClientCallTracer callTracer =
      censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
  callTracer.newClientStreamTracer(STREAM_INFO, headers);

  assertThat(headers.keys()).isEmpty();
}
 
Example #8
Source File: CensusTracingModule.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public ClientStreamTracer newClientStreamTracer(
    ClientStreamTracer.StreamInfo info, Metadata headers) {
  if (span != BlankSpan.INSTANCE) {
    headers.discardAll(tracingHeader);
    headers.put(tracingHeader, span.getContext());
  }
  return new ClientTracer(span);
}
 
Example #9
Source File: OpenCensusUtils.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Propagate information of current tracing context. This information will be injected into HTTP
 * header.
 *
 * @param span the span to be propagated.
 * @param headers the headers used in propagation.
 */
public static void propagateTracingContext(Span span, HttpHeaders headers) {
  Preconditions.checkArgument(span != null, "span should not be null.");
  Preconditions.checkArgument(headers != null, "headers should not be null.");
  if (propagationTextFormat != null && propagationTextFormatSetter != null) {
    if (!span.equals(BlankSpan.INSTANCE)) {
      propagationTextFormat.inject(span.getContext(), headers, propagationTextFormatSetter);
    }
  }
}
 
Example #10
Source File: AbstractConsumerIT.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Test
public void consumeOneMessage() throws Exception {
    final Series s1 = Series.of("s1", ImmutableMap.of("host", "localhost"));
    final MetricCollection mc =
        MetricCollection.points(ImmutableList.of(new Point(10, 42), new Point(20, 43)));
    WriteMetric.Request request = new WriteMetric.Request(s1, mc);

    consumer.accept(request);

    tryUntil(() -> {
        final List<MetricReadResult> data = Collections.synchronizedList(new ArrayList<>());

        instance.inject(coreComponent -> {
            FetchData.Request fetchDataRequest =
                new FetchData.Request(MetricType.POINT, s1, new DateRange(0, 100),
                    QueryOptions.defaults());
            return coreComponent
                .metricManager()
                .useDefaultGroup()
                .fetch(fetchDataRequest,
                    FetchQuotaWatcher.NO_QUOTA,
                    data::add,
                    BlankSpan.INSTANCE
                );
        }).get();

        assertFalse(data.isEmpty());
        final MetricCollection collection = data.iterator().next().getMetrics();
        assertEquals(mc, collection);
        return null;
    });
}
 
Example #11
Source File: CensusTracingModule.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public ClientStreamTracer newClientStreamTracer(CallOptions callOptions, Metadata headers) {
  if (span != BlankSpan.INSTANCE) {
    headers.discardAll(tracingHeader);
    headers.put(tracingHeader, span.getContext());
  }
  return new ClientTracer(span);
}
 
Example #12
Source File: RecordTraceEventsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@TearDown
public void doTearDown() {
  checkState(linkedSpan != BlankSpan.INSTANCE, "Uninitialized linkedSpan");
  checkState(span != BlankSpan.INSTANCE, "Uninitialized span");
  linkedSpan.end();
  span.end();
}
 
Example #13
Source File: ContextUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCurrentSpan_ContextSetToNull() {
  Context orig = ContextUtils.withValue(Context.current(), null).attach();
  try {
    Span span = ContextUtils.getValue(Context.current());
    // ContextUtils.getValue always returns non-null.
    assertThat(span).isEqualTo(BlankSpan.INSTANCE);
  } finally {
    Context.current().detach(orig);
  }
}
 
Example #14
Source File: CensusModulesTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void traceHeaders_missingCensusImpl_notPropagateSpanContext()
    throws Exception {
  reset(spyClientSpanBuilder);
  when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
  Metadata headers = new Metadata();

  CensusTracingModule.ClientCallTracer callTracer =
      censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
  callTracer.newClientStreamTracer(CallOptions.DEFAULT, headers);

  assertThat(headers.keys()).isEmpty();
}
 
Example #15
Source File: TracerImplTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createSpanBuilder() {
  SpanBuilder spanBuilder = tracer.spanBuilderWithExplicitParent(SPAN_NAME, BlankSpan.INSTANCE);
  assertThat(spanBuilder).isInstanceOf(SpanBuilderImpl.class);
}
 
Example #16
Source File: AbstractConsumerIT.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Test
public void consumeManyMessages() throws Exception {
    expectAtLeastOneCommit = true;
    final Series s1 = Series.of("s1", ImmutableMap.of("host", "localhost"));

    List<Point> consumedPoints = new ArrayList<>();
    for (int count = 1; count <= 10; count++) {
        Point p = new Point(count, 42);
        final MetricCollection mc = MetricCollection.points(ImmutableList.of(p));
        consumedPoints.add(p);

        WriteMetric.Request request = new WriteMetric.Request(s1, mc);

        consumer.accept(request);
        Thread.sleep(100);
    }

    tryUntil(() -> {
        final List<MetricReadResult> data = Collections.synchronizedList(new ArrayList<>());

        instance.inject(coreComponent -> {
            FetchData.Request fetchDataRequest =
                new FetchData.Request(MetricType.POINT, s1, new DateRange(0, 100),
                    QueryOptions.defaults());
            return coreComponent
                .metricManager()
                .useDefaultGroup()
                .fetch(fetchDataRequest,
                    FetchQuotaWatcher.NO_QUOTA,
                    data::add,
                    BlankSpan.INSTANCE
                );
        }).get();

        assertFalse(data.isEmpty());
        final MetricCollection metricCollection = data.iterator().next().getMetrics();
        List<Metric> collection = new ArrayList<>(metricCollection.data());
        collection.sort(Metric.comparator);
        assertEquals(consumedPoints, collection);
        return null;
    });
}
 
Example #17
Source File: StartEndSpanBenchmark.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@TearDown
public void doTearDown() {
  checkState(rootSpan != BlankSpan.INSTANCE, "Uninitialized rootSpan");
  rootSpan.end();
}
 
Example #18
Source File: Fetch.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public AsyncFuture<Void> run(final ShellIO io, final TaskParameters base) throws Exception {
    final Parameters params = (Parameters) base;
    final long now = clock.currentTimeMillis();

    final Series series = Tasks.parseSeries(mapper, params.series);

    final long start = params.start.map(t -> Tasks.parseInstant(t, now)).orElse(now);
    final long end =
        params.end.map(t -> Tasks.parseInstant(t, now)).orElseGet(() -> defaultEnd(start));

    final DateRange range = new DateRange(start, end);

    final DateFormat flip = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    final DateFormat point = new SimpleDateFormat("HH:mm:ss.SSS");

    final MetricBackendGroup readGroup = metrics.useOptionalGroup(params.group);
    final MetricType source = MetricType.fromIdentifier(params.source).orElse(MetricType.POINT);

    final QueryOptions.Builder optionsBuilder =
        QueryOptions.builder().tracing(Tracing.fromBoolean(params.tracing));
    final QueryOptions options = optionsBuilder.build();

    final Consumer<MetricReadResult> printMetricsCollection = metricsAndResources -> {
        MetricCollection g = metricsAndResources.getMetrics();
        Calendar current = null;
        Calendar last = null;

        for (final Metric d : g.data()) {
            current = Calendar.getInstance();
            current.setTime(new Date(d.getTimestamp()));

            if (flipped(last, current)) {
                io.out().println(flip.format(current.getTime()));
            }
            String fs = String.format("  %s: %s", point.format(new Date(d.getTimestamp())), d);
            io.out().println(fs);

            last = current;
        }
    };

    final LazyTransform<FetchData.Result, Void> handleResult = result -> {

        io.out().println("TRACE:");
        result.getTrace().formatTrace(io.out());
        io.out().flush();

        return async.resolved();
    };

    return readGroup
        .fetch(new FetchData.Request(source, series, range, options),
            FetchQuotaWatcher.NO_QUOTA, printMetricsCollection, BlankSpan.INSTANCE)
        .lazyTransform(handleResult);
}
 
Example #19
Source File: OpenCensusUtilsTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
public void testPropagateTracingContextInvalidSpan() {
  OpenCensusUtils.setPropagationTextFormat(mockTextFormat);
  // No injection. No exceptions should be thrown.
  OpenCensusUtils.propagateTracingContext(BlankSpan.INSTANCE, headers);
}
 
Example #20
Source File: ContextUtilsTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetCurrentSpan_DefaultContext() {
  Span span = ContextUtils.getValue(Context.current());
  assertThat(span).isEqualTo(BlankSpan.INSTANCE);
}
 
Example #21
Source File: OcHttpServletUtil.java    From opencensus-java with Apache License 2.0 3 votes vote down vote up
/**
 * Enters the scope of code where the given {@link ServletRequest} will be processed and returns
 * an object that represents the scope. The scope is exited when the returned object is closed. A
 * span created for the {@link ServletRequest} is set to the current Context.
 *
 * <p>Supports try-with-resource idiom.
 *
 * <p>Example of usage:
 *
 * <pre>{@code
 * void AsyncRequestProcessor(AsyncContext asyncCtx) {
 *   try (Scope ws = OcHttpServletUtil.withScope(asyncCtx.getRequest) {
 *     tracer.getCurrentSpan().addAnnotation("my annotation");
 *     doSomeOtherWork();  // Here "span" is the current Span.
 *   }
 * }
 * }</pre>
 *
 * <p>Prior to Java SE 7, you can use a finally block to ensure that a resource is closed
 * regardless of whether the try statement completes normally or abruptly.
 *
 * <p>Example of usage prior to Java SE7:
 *
 * <pre>{@code
 * void AsyncRequestProcessor(AsyncContext asyncCtx) {
 *   Scope ws = OcHttpServletUtil.withScope(asyncCtx.getRequest)
 *   try {
 *     tracer.getCurrentSpan().addAnnotation("my annotation");
 *     doSomeOtherWork();  // Here "span" is the current Span.
 *   } finally {
 *     ws.close();
 *   }
 * }
 * }</pre>
 *
 * @param request The {@link ServletRequest} request that is about to be processed.
 * @return an object that defines a scope where the span associated with the given {@link
 *     ServletRequest} will be set to the current Context.
 * @throws NullPointerException if {@code request} is {@code null}.
 * @since 0.20.0
 */
@MustBeClosed
public static Scope withScope(ServletRequest request) {
  checkNotNull(request, "request");
  OcHttpServletListener listener =
      (OcHttpServletListener) request.getAttribute(OPENCENSUS_SERVLET_LISTENER);
  if (listener != null) {
    return listener.withSpan();
  }
  return Tracing.getTracer().withSpan(BlankSpan.INSTANCE);
}
 
Example #22
Source File: ContextUtils.java    From opencensus-java with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the value from the specified {@code Context}.
 *
 * @param context the specified {@code Context}.
 * @return the value from the specified {@code Context}.
 * @since 0.21
 */
public static Span getValue(Context context) {
  @javax.annotation.Nullable
  Span span = CONTEXT_SPAN_KEY.get(Utils.checkNotNull(context, "context"));
  return span == null ? BlankSpan.INSTANCE : span;
}