Search in sources :

Example 16 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class OcAgentTraceExporterIntegrationTest method testExportSpans.

@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);
    }
}
Also used : ExportTraceServiceRequest(io.opencensus.proto.agent.trace.v1.ExportTraceServiceRequest) Node(io.opencensus.proto.agent.common.v1.Node) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) TraceParams(io.opencensus.trace.config.TraceParams) Span(io.opencensus.trace.Span) Scope(io.opencensus.common.Scope) TraceConfig(io.opencensus.trace.config.TraceConfig) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 17 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class OcAgentTraceExporterIntegrationTest method doWork.

private void doWork(String spanName, int i) {
    try (Scope scope = tracer.spanBuilder(spanName).startScopedSpan()) {
        // Simulate some work.
        Span span = tracer.getCurrentSpan();
        try {
            Thread.sleep(10L);
        } catch (InterruptedException e) {
            span.setStatus(Status.INTERNAL.withDescription(e.toString()));
        }
        Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>();
        attributes.put("inner work iteration number", AttributeValue.longAttributeValue(i));
        span.addAnnotation("Invoking doWork", attributes);
    }
}
Also used : AttributeValue(io.opencensus.trace.AttributeValue) Scope(io.opencensus.common.Scope) HashMap(java.util.HashMap) ByteString(com.google.protobuf.ByteString) Span(io.opencensus.trace.Span)

Example 18 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class ZPageHttpHandler method handle.

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

Example 19 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class TracingAsyncClientHttpRequestInterceptor method intercept.

/**
 * It intercepts http requests and starts a span.
 *
 * @since 0.23.0
 */
public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, org.springframework.http.client.AsyncClientHttpRequestExecution execution) throws IOException {
    HttpRequestContext context = handler.handleStart(tracer.getCurrentSpan(), request, request);
    Scope ws = tracer.withSpan(handler.getSpanFromContext(context));
    try {
        ListenableFuture<ClientHttpResponse> result = execution.executeAsync(request, body);
        result.addCallback(new TracingAsyncClientHttpRequestInterceptor.TraceListenableFutureCallback(context, handler));
        return result;
    } catch (IOException e) {
        handler.handleEnd(context, null, null, e);
        throw e;
    } finally {
        if (ws != null) {
            ws.close();
        }
    }
}
Also used : Scope(io.opencensus.common.Scope) HttpRequestContext(io.opencensus.contrib.http.HttpRequestContext) IOException(java.io.IOException) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 20 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class HttpClientHandlerTest method handleStartShouldCreateChildSpanInCurrentContext.

@Test
public void handleStartShouldCreateChildSpanInCurrentContext() {
    Scope scope = tracer.withSpan(parentSpan);
    try {
        HttpRequestContext context = handler.handleStart(null, carrier, request);
        verify(tracer).spanBuilderWithExplicitParent(any(String.class), same(parentSpan));
        assertThat(context.span).isEqualTo(childSpan);
    } finally {
        scope.close();
    }
}
Also used : Scope(io.opencensus.common.Scope) Test(org.junit.Test)

Aggregations

Scope (io.opencensus.common.Scope)48 Test (org.junit.Test)18 Span (io.opencensus.trace.Span)8 Timestamp (com.google.cloud.Timestamp)5 TagContext (io.opencensus.tags.TagContext)5 SpanBuilder (io.opencensus.trace.SpanBuilder)5 VisibleForTesting (org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting)5 ArrayList (java.util.ArrayList)4 Instant (org.joda.time.Instant)4 HttpRequestContext (io.opencensus.contrib.http.HttpRequestContext)3 SimpleTimeLimiter (com.google.common.util.concurrent.SimpleTimeLimiter)2 TimeLimiter (com.google.common.util.concurrent.TimeLimiter)2 ByteString (com.google.protobuf.ByteString)2 LongPoint (io.opencensus.metrics.LongGauge.LongPoint)2 MeasureMap (io.opencensus.stats.MeasureMap)2 TagContextBuilder (io.opencensus.tags.TagContextBuilder)2 AttributeValue (io.opencensus.trace.AttributeValue)2 Tracer (io.opencensus.trace.Tracer)2 TraceConfig (io.opencensus.trace.config.TraceConfig)2 HashMap (java.util.HashMap)2