Search in sources :

Example 41 with Scope

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

the class JaegerExporterHandlerIntegrationTest method exportToJaeger.

@Test
public void exportToJaeger() throws IOException, InterruptedException {
    Tracer tracer = Tracing.getTracer();
    final long startTimeInMicros = MILLISECONDS.toMicros(currentTimeMillis());
    final long startNanoTime = System.nanoTime();
    SpanBuilder spanBuilder = tracer.spanBuilder(SPAN_NAME).setRecordEvents(true).setSampler(Samplers.alwaysSample());
    int spanDurationInMillis = new Random().nextInt(10) + 1;
    Scope scopedSpan = spanBuilder.startScopedSpan();
    try {
        tracer.getCurrentSpan().addAnnotation(START_PROCESSING_VIDEO);
        // Fake work.
        Thread.sleep(spanDurationInMillis);
        tracer.getCurrentSpan().putAttribute("foo", AttributeValue.stringAttributeValue("bar"));
        tracer.getCurrentSpan().addAnnotation(FINISHED_PROCESSING_VIDEO);
    } catch (Exception e) {
        tracer.getCurrentSpan().addAnnotation("Exception thrown when processing video.");
        tracer.getCurrentSpan().setStatus(Status.UNKNOWN);
        logger.error(e.getMessage());
    } finally {
        scopedSpan.close();
    }
    final long durationInMicros = NANOSECONDS.toMicros(System.nanoTime() - startNanoTime);
    final long endTimeInMicros = startTimeInMicros + durationInMicros;
    // Shutdown the export component to force a flush. This will cause problems if multiple tests
    // are added in this class, but this is not the case for the moment.
    Tracing.getExportComponent().shutdown();
    JaegerTraceExporter.unregister();
    logger.info("Wait for Jaeger to process the span...");
    long timeWaitingForSpansToBeExportedInMillis = 1100L;
    Thread.sleep(timeWaitingForSpansToBeExportedInMillis);
    // Get traces recorded by Jaeger:
    HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(tracesForServiceEndpoint(SERVICE_NAME)));
    HttpResponse response = request.execute();
    String body = response.parseAsString();
    assertWithMessage("Response was: " + body).that(response.getStatusCode()).isEqualTo(200);
    JsonObject result = new JsonParser().parse(body).getAsJsonObject();
    // Pretty-print for debugging purposes:
    logger.debug(new GsonBuilder().setPrettyPrinting().create().toJson(result));
    assertThat(result).isNotNull();
    assertThat(result.get("total").getAsInt()).isEqualTo(0);
    assertThat(result.get("limit").getAsInt()).isEqualTo(0);
    assertThat(result.get("offset").getAsInt()).isEqualTo(0);
    assertThat(result.get("errors").getAsJsonNull()).isEqualTo(JsonNull.INSTANCE);
    JsonArray data = result.get("data").getAsJsonArray();
    assertThat(data).isNotNull();
    assertThat(data.size()).isEqualTo(1);
    JsonObject trace = data.get(0).getAsJsonObject();
    assertThat(trace).isNotNull();
    assertThat(trace.get("traceID").getAsString()).matches("[a-z0-9]{1,32}");
    JsonArray spans = trace.get("spans").getAsJsonArray();
    assertThat(spans).isNotNull();
    assertThat(spans.size()).isEqualTo(1);
    JsonObject span = spans.get(0).getAsJsonObject();
    assertThat(span).isNotNull();
    assertThat(span.get("traceID").getAsString()).matches("[a-z0-9]{1,32}");
    assertThat(span.get("spanID").getAsString()).matches("[a-z0-9]{1,16}");
    assertThat(span.get("flags").getAsInt()).isEqualTo(1);
    assertThat(span.get("operationName").getAsString()).isEqualTo(SPAN_NAME);
    assertThat(span.get("references").getAsJsonArray()).isEmpty();
    assertThat(span.get("startTime").getAsLong()).isAtLeast(startTimeInMicros);
    assertThat(span.get("startTime").getAsLong()).isAtMost(endTimeInMicros);
    assertThat(span.get("duration").getAsLong()).isAtLeast(MILLISECONDS.toMicros(spanDurationInMillis));
    assertThat(span.get("duration").getAsLong()).isAtMost(durationInMicros);
    JsonArray tags = span.get("tags").getAsJsonArray();
    assertThat(tags.size()).isEqualTo(2);
    JsonObject tag = tags.get(0).getAsJsonObject();
    assertThat(tag.get("key").getAsString()).isEqualTo("foo");
    assertThat(tag.get("type").getAsString()).isEqualTo("string");
    assertThat(tag.get("value").getAsString()).isEqualTo("bar");
    JsonObject statusTag = tags.get(1).getAsJsonObject();
    assertThat(statusTag.get("key").getAsString()).isEqualTo(JaegerExporterHandler.STATUS_CODE);
    assertThat(statusTag.get("type").getAsString()).isEqualTo("int64");
    assertThat(statusTag.get("value").getAsLong()).isEqualTo(0);
    JsonArray logs = span.get("logs").getAsJsonArray();
    assertThat(logs.size()).isEqualTo(2);
    JsonObject log1 = logs.get(0).getAsJsonObject();
    long ts1 = log1.get("timestamp").getAsLong();
    assertThat(ts1).isAtLeast(startTimeInMicros);
    assertThat(ts1).isAtMost(endTimeInMicros);
    JsonArray fields1 = log1.get("fields").getAsJsonArray();
    assertThat(fields1.size()).isEqualTo(1);
    JsonObject field1 = fields1.get(0).getAsJsonObject();
    assertThat(field1.get("key").getAsString()).isEqualTo("message");
    assertThat(field1.get("type").getAsString()).isEqualTo("string");
    assertThat(field1.get("value").getAsString()).isEqualTo(START_PROCESSING_VIDEO);
    JsonObject log2 = logs.get(1).getAsJsonObject();
    long ts2 = log2.get("timestamp").getAsLong();
    assertThat(ts2).isAtLeast(startTimeInMicros);
    assertThat(ts2).isAtMost(endTimeInMicros);
    assertThat(ts2).isAtLeast(ts1);
    JsonArray fields2 = log2.get("fields").getAsJsonArray();
    assertThat(fields2.size()).isEqualTo(1);
    JsonObject field2 = fields2.get(0).getAsJsonObject();
    assertThat(field2.get("key").getAsString()).isEqualTo("message");
    assertThat(field2.get("type").getAsString()).isEqualTo("string");
    assertThat(field2.get("value").getAsString()).isEqualTo(FINISHED_PROCESSING_VIDEO);
    assertThat(span.get("processID").getAsString()).isEqualTo("p1");
    assertThat(span.get("warnings").getAsJsonNull()).isEqualTo(JsonNull.INSTANCE);
    JsonObject processes = trace.get("processes").getAsJsonObject();
    assertThat(processes.size()).isEqualTo(1);
    JsonObject p1 = processes.get("p1").getAsJsonObject();
    assertThat(p1.get("serviceName").getAsString()).isEqualTo(SERVICE_NAME);
    assertThat(p1.get("tags").getAsJsonArray().size()).isEqualTo(0);
    assertThat(trace.get("warnings").getAsJsonNull()).isEqualTo(JsonNull.INSTANCE);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) SpanBuilder(io.opencensus.trace.SpanBuilder) GsonBuilder(com.google.gson.GsonBuilder) Tracer(io.opencensus.trace.Tracer) HttpResponse(com.google.api.client.http.HttpResponse) JsonObject(com.google.gson.JsonObject) GenericUrl(com.google.api.client.http.GenericUrl) AssumptionViolatedException(org.junit.AssumptionViolatedException) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) Random(java.util.Random) Scope(io.opencensus.common.Scope) JsonParser(com.google.gson.JsonParser) Test(org.junit.Test)

Example 42 with Scope

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

the class TimeLimitedHandler method export.

@Override
public void export(final Collection<SpanData> spanDataList) {
    final Scope exportScope = newExportScope();
    try {
        TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor());
        timeLimiter.callWithTimeout(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                timeLimitedExport(spanDataList);
                return null;
            }
        }, deadline.toMillis(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        handleException(e, "Timeout when exporting traces: " + e);
    } catch (InterruptedException e) {
        handleException(e, "Interrupted when exporting traces: " + e);
    } catch (Exception e) {
        handleException(e, "Failed to export traces: " + e);
    } finally {
        exportScope.close();
    }
}
Also used : SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) TimeLimiter(com.google.common.util.concurrent.TimeLimiter) Scope(io.opencensus.common.Scope) TimeoutException(java.util.concurrent.TimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 43 with Scope

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

the class ScopedTagMapTest method createBuilderFromCurrentTags.

@Test
public void createBuilderFromCurrentTags() {
    TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
    Scope scope = tagger.withTagContext(scopedTags);
    try {
        TagContext newTags = tagger.currentBuilder().put(KEY_2, VALUE_2).build();
        assertThat(tagContextToList(newTags)).containsExactly(Tag.create(KEY_1, VALUE_1), Tag.create(KEY_2, VALUE_2));
        assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
    } finally {
        scope.close();
    }
}
Also used : Scope(io.opencensus.common.Scope) TagContext(io.opencensus.tags.TagContext) Test(org.junit.Test)

Example 44 with Scope

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

the class ScopedTagMapTest method addToCurrentTagsWithBuilder.

@Test
public void addToCurrentTagsWithBuilder() {
    TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
    Scope scope1 = tagger.withTagContext(scopedTags);
    try {
        Scope scope2 = tagger.currentBuilder().put(KEY_2, VALUE_2).buildScoped();
        try {
            assertThat(tagContextToList(tagger.getCurrentTagContext())).containsExactly(Tag.create(KEY_1, VALUE_1), Tag.create(KEY_2, VALUE_2));
        } finally {
            scope2.close();
        }
        assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
    } finally {
        scope1.close();
    }
}
Also used : Scope(io.opencensus.common.Scope) TagContext(io.opencensus.tags.TagContext) Test(org.junit.Test)

Example 45 with Scope

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

the class ScopedTagMapTest method multiScopeTagMapWithMetadata.

@Test
public void multiScopeTagMapWithMetadata() {
    TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1, METADATA_UNLIMITED_PROPAGATION).put(KEY_2, VALUE_2, METADATA_UNLIMITED_PROPAGATION).build();
    Scope scope1 = tagger.withTagContext(scopedTags);
    try {
        // Scope 1
        Scope scope2 = tagger.currentBuilder().put(KEY_3, VALUE_3, METADATA_NO_PROPAGATION).put(KEY_2, VALUE_4, METADATA_NO_PROPAGATION).buildScoped();
        try {
            // Scope 2
            assertThat(tagContextToList(tagger.getCurrentTagContext())).containsExactly(Tag.create(KEY_1, VALUE_1, METADATA_UNLIMITED_PROPAGATION), Tag.create(KEY_2, VALUE_4, METADATA_NO_PROPAGATION), Tag.create(KEY_3, VALUE_3, METADATA_NO_PROPAGATION));
        } finally {
            // Close Scope 2
            scope2.close();
        }
        assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
    } finally {
        scope1.close();
    }
}
Also used : Scope(io.opencensus.common.Scope) TagContext(io.opencensus.tags.TagContext) 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