Search in sources :

Example 36 with Span

use of io.opencensus.trace.Span in project instrumentation-java by census-instrumentation.

the class MultiSpansContextTracing method main.

/**
 * 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);
}
Also used : Scope(io.opencensus.common.Scope) TraceConfig(io.opencensus.trace.config.TraceConfig) Span(io.opencensus.trace.Span)

Example 37 with Span

use of io.opencensus.trace.Span in project instrumentation-java by census-instrumentation.

the class SpanBuilderImpl method startSpanInternal.

private Span startSpanInternal(@Nullable SpanContext parentContext, @Nullable Boolean hasRemoteParent, String name, @Nullable Sampler sampler, List<Span> parentLinks, @Nullable Boolean recordEvents, @Nullable Kind kind, @Nullable Span parentSpan) {
    TraceParams activeTraceParams = options.traceConfig.getActiveTraceParams();
    Random random = options.randomHandler.current();
    TraceId traceId;
    SpanId spanId = SpanId.generateRandomId(random);
    SpanId parentSpanId = null;
    // TODO(bdrutu): Handle tracestate correctly not just propagate.
    Tracestate tracestate = TRACESTATE_DEFAULT;
    if (parentContext == null || !parentContext.isValid()) {
        // New root span.
        traceId = TraceId.generateRandomId(random);
        // This is a root span so no remote or local parent.
        hasRemoteParent = null;
    } else {
        // New child span.
        traceId = parentContext.getTraceId();
        parentSpanId = parentContext.getSpanId();
        tracestate = parentContext.getTracestate();
    }
    TraceOptions traceOptions = makeSamplingDecision(parentContext, hasRemoteParent, name, sampler, parentLinks, traceId, spanId, activeTraceParams) ? SAMPLED_TRACE_OPTIONS : NOT_SAMPLED_TRACE_OPTIONS;
    if (traceOptions.isSampled() || Boolean.TRUE.equals(recordEvents)) {
        // Pass the timestamp converter from the parent to ensure that the recorded events are in
        // the right order. Implementation uses System.nanoTime() which is monotonically increasing.
        TimestampConverter timestampConverter = null;
        if (parentSpan instanceof RecordEventsSpanImpl) {
            RecordEventsSpanImpl parentRecordEventsSpan = (RecordEventsSpanImpl) parentSpan;
            timestampConverter = parentRecordEventsSpan.getTimestampConverter();
            parentRecordEventsSpan.addChild();
        }
        Span span = RecordEventsSpanImpl.startSpan(SpanContext.create(traceId, spanId, traceOptions, tracestate), name, kind, parentSpanId, hasRemoteParent, activeTraceParams, options.startEndHandler, timestampConverter, options.clock);
        linkSpans(span, parentLinks);
        return span;
    } else {
        return NoRecordEventsSpanImpl.create(SpanContext.create(traceId, spanId, traceOptions, tracestate));
    }
}
Also used : Random(java.util.Random) TimestampConverter(io.opencensus.implcore.internal.TimestampConverter) TraceId(io.opencensus.trace.TraceId) TraceOptions(io.opencensus.trace.TraceOptions) TraceParams(io.opencensus.trace.config.TraceParams) Tracestate(io.opencensus.trace.Tracestate) Span(io.opencensus.trace.Span) SpanId(io.opencensus.trace.SpanId)

Example 38 with Span

use of io.opencensus.trace.Span in project instrumentation-java by census-instrumentation.

the class CreateTimeSeriesExporter method export.

@Override
public void export(Collection<Metric> metrics) {
    List<TimeSeries> timeSeriesList = new ArrayList<>(metrics.size());
    for (Metric metric : metrics) {
        timeSeriesList.addAll(StackdriverExportUtils.createTimeSeriesList(metric, monitoredResource, domain, projectName.getProject(), constantLabels));
    }
    Span span = tracer.getCurrentSpan();
    for (List<TimeSeries> batchedTimeSeries : Lists.partition(timeSeriesList, MAX_BATCH_EXPORT_SIZE)) {
        span.addAnnotation("Export Stackdriver TimeSeries.");
        try {
            CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder().setName(projectName.toString()).addAllTimeSeries(batchedTimeSeries).build();
            metricServiceClient.createTimeSeries(request);
            span.addAnnotation("Finish exporting TimeSeries.");
        } catch (ApiException e) {
            logger.log(Level.WARNING, "ApiException thrown when exporting TimeSeries.", e);
            span.setStatus(Status.CanonicalCode.valueOf(e.getStatusCode().getCode().name()).toStatus().withDescription("ApiException thrown when exporting TimeSeries: " + StackdriverExportUtils.exceptionMessage(e)));
        } catch (Throwable e) {
            logger.log(Level.WARNING, "Exception thrown when exporting TimeSeries.", e);
            span.setStatus(Status.UNKNOWN.withDescription("Exception thrown when exporting TimeSeries: " + StackdriverExportUtils.exceptionMessage(e)));
        }
    }
}
Also used : TimeSeries(com.google.monitoring.v3.TimeSeries) CreateTimeSeriesRequest(com.google.monitoring.v3.CreateTimeSeriesRequest) ArrayList(java.util.ArrayList) Metric(io.opencensus.metrics.export.Metric) Span(io.opencensus.trace.Span) ApiException(com.google.api.gax.rpc.ApiException)

Example 39 with Span

use of io.opencensus.trace.Span in project instrumentation-java by census-instrumentation.

the class TraceWebAsyncClientAutoConfigurationTest method should_close_span_upon_success_callback.

@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();
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) Scope(io.opencensus.common.Scope) SpanData(io.opencensus.trace.export.SpanData) Span(io.opencensus.trace.Span) Order(org.springframework.core.annotation.Order) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 40 with Span

use of io.opencensus.trace.Span in project instrumentation-java by census-instrumentation.

the class SpanBuilderImplTest method startChildSpan_SampledLinkedParent.

@Test
public void startChildSpan_SampledLinkedParent() {
    Span rootSpanUnsampled = SpanBuilderImpl.createWithParent(SPAN_NAME, null, spanBuilderOptions).setSampler(Samplers.neverSample()).startSpan();
    assertThat(rootSpanUnsampled.getContext().getTraceOptions().isSampled()).isFalse();
    Span rootSpanSampled = SpanBuilderImpl.createWithParent(SPAN_NAME, null, spanBuilderOptions).setSampler(Samplers.alwaysSample()).startSpan();
    assertThat(rootSpanSampled.getContext().getTraceOptions().isSampled()).isTrue();
    // Sampled because the linked parent is sampled.
    Span childSpan = SpanBuilderImpl.createWithParent(SPAN_NAME, rootSpanUnsampled, spanBuilderOptions).setParentLinks(Collections.singletonList(rootSpanSampled)).startSpan();
    assertThat(childSpan.getContext().isValid()).isTrue();
    assertThat(childSpan.getContext().getTraceId()).isEqualTo(rootSpanUnsampled.getContext().getTraceId());
    assertThat(childSpan.getContext().getTraceOptions().isSampled()).isTrue();
}
Also used : Span(io.opencensus.trace.Span) Test(org.junit.Test)

Aggregations

Span (io.opencensus.trace.Span)47 Test (org.junit.Test)17 Benchmark (org.openjdk.jmh.annotations.Benchmark)14 BenchmarkMode (org.openjdk.jmh.annotations.BenchmarkMode)14 OutputTimeUnit (org.openjdk.jmh.annotations.OutputTimeUnit)14 Scope (io.opencensus.common.Scope)8 BlankSpan (io.opencensus.trace.BlankSpan)8 ArrayList (java.util.ArrayList)4 SpanBuilder (io.opencensus.trace.SpanBuilder)3 SpanContext (io.opencensus.trace.SpanContext)3 ApiException (com.google.api.gax.rpc.ApiException)2 ByteString (com.google.protobuf.ByteString)2 HttpRequestContext (io.opencensus.contrib.http.HttpRequestContext)2 Metric (io.opencensus.metrics.export.Metric)2 TagContext (io.opencensus.tags.TagContext)2 AttributeValue (io.opencensus.trace.AttributeValue)2 SpanId (io.opencensus.trace.SpanId)2 TraceId (io.opencensus.trace.TraceId)2 TraceConfig (io.opencensus.trace.config.TraceConfig)2 TraceParams (io.opencensus.trace.config.TraceParams)2