Search in sources :

Example 6 with SpanBuilder

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

the class HttpServerHandler method handleStart.

/**
 * Instrument an incoming request before it is handled.
 *
 * <p>This method will create a span under the deserialized propagated parent context. If the
 * parent context is not present, the span will be created under the current context.
 *
 * <p>The generated span will NOT be set as current context. User can control when to enter the
 * scope of this span. Use {@link AbstractHttpHandler#getSpanFromContext} to retrieve the span.
 *
 * @param carrier the entity that holds the HTTP information.
 * @param request the request entity.
 * @return the {@link HttpRequestContext} that contains stats and trace data associated with the
 *     request.
 * @since 0.19
 */
public HttpRequestContext handleStart(C carrier, Q request) {
    checkNotNull(carrier, "carrier");
    checkNotNull(request, "request");
    SpanBuilder spanBuilder = null;
    String spanName = getSpanName(request, extractor);
    // de-serialize the context
    SpanContext spanContext = null;
    try {
        spanContext = textFormat.extract(carrier, getter);
    } catch (SpanContextParseException e) {
    // TODO: Currently we cannot distinguish between context parse error and missing context.
    // Logging would be annoying so we just ignore this error and do not even log a message.
    }
    if (spanContext == null || publicEndpoint) {
        spanBuilder = tracer.spanBuilder(spanName);
    } else {
        spanBuilder = tracer.spanBuilderWithRemoteParent(spanName, spanContext);
    }
    Span span = spanBuilder.setSpanKind(Kind.SERVER).startSpan();
    if (publicEndpoint && spanContext != null) {
        span.addLink(Link.fromSpanContext(spanContext, Type.PARENT_LINKED_SPAN));
    }
    if (span.getOptions().contains(Options.RECORD_EVENTS)) {
        addSpanRequestAttributes(span, request, extractor);
    }
    return getNewContext(span, tagger.getCurrentTagContext());
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) SpanContext(io.opencensus.trace.SpanContext) SpanContextParseException(io.opencensus.trace.propagation.SpanContextParseException) Span(io.opencensus.trace.Span)

Example 7 with SpanBuilder

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

the class ZPagesTester method recordExampleData.

private static void recordExampleData() throws InterruptedException {
    Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForCollection(Collections.singletonList(SPAN_NAME));
    // Use old RPC constants to get interval stats.
    RpcViews.registerAllViews();
    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().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).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());
        // sleep for fake work.
        Thread.sleep(200);
        tracer.getCurrentSpan().addAnnotation("Finish recording.");
    }
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) MeasureMap(io.opencensus.stats.MeasureMap)

Example 8 with SpanBuilder

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

the class HelloWorldClient method greet.

/**
 * Say hello to server.
 */
public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    SpanBuilder spanBuilder = tracer.spanBuilder("client").setRecordEvents(true).setSampler(Samplers.alwaysSample());
    try (Scope scope = spanBuilder.startScopedSpan()) {
        tracer.getCurrentSpan().addAnnotation("Saying Hello to Server.");
        response = blockingStub.sayHello(request);
        tracer.getCurrentSpan().addAnnotation("Received response from Server.");
    } catch (StatusRuntimeException e) {
        tracer.getCurrentSpan().setStatus(CanonicalCode.valueOf(e.getStatus().getCode().name()).toStatus().withDescription(e.getMessage()));
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Greeting: " + response.getMessage());
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) StatusRuntimeException(io.grpc.StatusRuntimeException)

Example 9 with SpanBuilder

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

the class QuickStart method main.

/**
 * Main launcher for the QuickStart example.
 */
public static void main(String[] args) throws InterruptedException {
    TagContextBuilder tagContextBuilder = tagger.currentBuilder().put(FRONTEND_KEY, TagValue.create("mobile-ios9.3.5"));
    SpanBuilder spanBuilder = tracer.spanBuilder("my.org/ProcessVideo").setRecordEvents(true).setSampler(Samplers.alwaysSample());
    viewManager.registerView(VIDEO_SIZE_VIEW);
    LoggingTraceExporter.register();
    // Record the processed video size.
    try (Scope scopedTags = tagContextBuilder.buildScoped();
        Scope scopedSpan = spanBuilder.startScopedSpan()) {
        tracer.getCurrentSpan().addAnnotation("Start processing video.");
        // Sleep for [0,10] milliseconds to fake work.
        Thread.sleep(new Random().nextInt(10) + 1);
        statsRecorder.newMeasureMap().put(VIDEO_SIZE, 25 * MiB).record();
        tracer.getCurrentSpan().addAnnotation("Finished processing video.");
    } catch (Exception e) {
        tracer.getCurrentSpan().addAnnotation("Exception thrown when processing video.");
        tracer.getCurrentSpan().setStatus(Status.UNKNOWN);
        logger.severe(e.getMessage());
    }
    logger.info("Wait longer than the reporting duration...");
    // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
    // TODO(songya): remove the gap once we add a shutdown hook for exporting unflushed spans.
    Thread.sleep(5100);
    ViewData viewData = viewManager.getView(VIDEO_SIZE_VIEW_NAME);
    logger.info(String.format("Recorded stats for %s:\n %s", VIDEO_SIZE_VIEW_NAME.asString(), viewData));
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) Random(java.util.Random) ViewData(io.opencensus.stats.ViewData) TagContextBuilder(io.opencensus.tags.TagContextBuilder)

Example 10 with SpanBuilder

use of io.opencensus.trace.SpanBuilder in project beam by apache.

the class BeamFnMapTaskExecutor method execute.

@Override
public void execute() throws Exception {
    Tracer tracer = Tracing.getTracer();
    SpanBuilder builder = tracer.spanBuilder("MapTaskExecutor.Span").setRecordEvents(true);
    // Start the progress tracker before execution (which blocks until execution is finished).
    try (Scope unused = builder.startScopedSpan();
        AutoCloseable unused2 = progressTrackerCloseable(progressTracker)) {
        tracer.getCurrentSpan().addAnnotation("About to execute");
        super.execute();
        tracer.getCurrentSpan().addAnnotation("Done with execute");
    }
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) Tracer(io.opencensus.trace.Tracer)

Aggregations

SpanBuilder (io.opencensus.trace.SpanBuilder)10 Scope (io.opencensus.common.Scope)6 Span (io.opencensus.trace.Span)3 Test (org.junit.Test)3 SpanContext (io.opencensus.trace.SpanContext)2 Tracer (io.opencensus.trace.Tracer)2 Random (java.util.Random)2 GenericUrl (com.google.api.client.http.GenericUrl)1 HttpRequest (com.google.api.client.http.HttpRequest)1 HttpResponse (com.google.api.client.http.HttpResponse)1 GsonBuilder (com.google.gson.GsonBuilder)1 JsonArray (com.google.gson.JsonArray)1 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 StatusRuntimeException (io.grpc.StatusRuntimeException)1 MeasureMap (io.opencensus.stats.MeasureMap)1 ViewData (io.opencensus.stats.ViewData)1 TagContextBuilder (io.opencensus.tags.TagContextBuilder)1 SpanContextParseException (io.opencensus.trace.propagation.SpanContextParseException)1 IOException (java.io.IOException)1