io.opencensus.trace.Status Java Examples

The following examples show how to use io.opencensus.trace.Status. 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: TraceStrategyImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void endScope(Closeable scope, @Nullable Throwable throwable) {
  checkNotNull(scope, "scope");

  if (throwable != null) {
    Tracing.getTracer()
        .getCurrentSpan()
        .setStatus(
            Status.UNKNOWN.withDescription(
                throwable.getMessage() == null
                    ? throwable.getClass().getSimpleName()
                    : throwable.getMessage()));
  }

  try {
    scope.close();
  } catch (IOException ex) {
    // Ignore.
  }
}
 
Example #2
Source File: MetricReader.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the metrics from the {@link MetricProducerManager} and exports them to the {@code
 * metricExporter}.
 *
 * @param metricExporter the exporter called to export the metrics read.
 * @since 0.19
 */
public void readAndExport(MetricExporter metricExporter) {
  Span span =
      tracer
          .spanBuilder(spanName)
          .setRecordEvents(true)
          .setSampler(probabilitySampler)
          .startSpan();
  Scope scope = tracer.withSpan(span);
  try {
    ArrayList<Metric> metricsList = new ArrayList<>();
    for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) {
      metricsList.addAll(metricProducer.getMetrics());
    }
    metricExporter.export(metricsList);
  } catch (Throwable e) {
    logger.log(Level.WARNING, "Exception thrown by the metrics exporter.", e);
    span.setStatus(
        Status.UNKNOWN.withDescription("Exception when export metrics: " + exceptionMessage(e)));
  } finally {
    scope.close();
    span.end();
  }
}
 
Example #3
Source File: Handler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static Object proceed(
    ProceedingJoinPoint call, Tracer tracer, String spanName, String... annotations)
    throws Throwable {
  Scope scope = tracer.spanBuilder(spanName).startScopedSpan();
  try {
    for (String annotation : annotations) {
      tracer.getCurrentSpan().addAnnotation(annotation);
    }

    return call.proceed();

  } catch (Throwable t) {
    Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>();
    String message = t.getMessage();
    attributes.put(
        "message", AttributeValue.stringAttributeValue(message == null ? "null" : message));
    attributes.put("type", AttributeValue.stringAttributeValue(t.getClass().toString()));

    Span span = tracer.getCurrentSpan();
    span.addAnnotation("error", attributes);
    span.setStatus(Status.UNKNOWN);
    throw t;
  } finally {
    scope.close();
  }
}
 
Example #4
Source File: JsonConversionUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  SpanData spanData =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(SAMPLE_TRACE_ID),
              SpanId.fromLowerBase16(SAMPLE_SPAN_ID),
              SAMPLE_TRACE_OPTION,
              SAMPLE_TRACE_STATE),
          SpanId.fromLowerBase16(SAMPLE_PARENT_SPAN_ID),
          true,
          "SpanName",
          null,
          Timestamp.create(155196336, 194009601),
          Attributes.create(attributes, 0),
          TimedEvents.create(annotations, 0),
          TimedEvents.create(messageEvents, 0),
          Links.create(Collections.<Link>emptyList(), 0),
          null,
          Status.OK,
          Timestamp.create(155296336, 465726528));

  spanDataList = new ArrayList<SpanData>();
  spanDataList.add(spanData);
}
 
Example #5
Source File: InProcessSampledSpanStoreImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getErrorSampledSpans_MaxSpansToReturn() {
  RecordEventsSpanImpl span1 = createSampledSpan(REGISTERED_SPAN_NAME);
  testClock.advanceTime(Duration.create(0, 1000));
  span1.end(EndSpanOptions.builder().setStatus(Status.CANCELLED).build());
  // Advance time to allow other spans to be sampled.
  testClock.advanceTime(Duration.create(5, 0));
  RecordEventsSpanImpl span2 = createSampledSpan(REGISTERED_SPAN_NAME);
  testClock.advanceTime(Duration.create(0, 1000));
  span2.end(EndSpanOptions.builder().setStatus(Status.CANCELLED).build());
  Collection<SpanData> samples =
      sampleStore.getErrorSampledSpans(
          ErrorFilter.create(REGISTERED_SPAN_NAME, CanonicalCode.CANCELLED, 1));
  assertThat(samples.size()).isEqualTo(1);
  // No order guaranteed so one of the spans should be in the list.
  assertThat(samples).containsAnyOf(span1.toSpanData(), span2.toSpanData());
}
 
Example #6
Source File: CensusSpringAspectTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void handlesException() {
  // When
  Sample sample = (Sample) context.getBean("sample");
  try {
    sample.boom();
  } catch (Exception ignored) {
    //  ok
  }

  // Then
  List<SpanData> spanList = handler.waitForExport(1);
  assertThat(spanList).isNotNull();
  assertThat(spanList.size()).isEqualTo(1);

  SpanData spanData = spanList.get(0);
  assertThat(spanData.getName()).isEqualTo("boom");
  assertThat(spanData.getStatus()).isEqualTo(Status.UNKNOWN);

  SpanData.TimedEvents<Annotation> annotations = spanData.getAnnotations();
  assertThat(annotations).isNotNull();

  List<SpanData.TimedEvent<Annotation>> events = annotations.getEvents();
  assertThat(events.size()).isEqualTo(1);
  assertThat(events.get(0).getEvent().getDescription()).isEqualTo("error");
}
 
Example #7
Source File: RecordEventsSpanImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void status_ViaEndSpanOptions() {
  RecordEventsSpanImpl span =
      RecordEventsSpanImpl.startSpan(
          spanContext,
          SPAN_NAME,
          null,
          parentSpanId,
          false,
          TraceParams.DEFAULT,
          startEndHandler,
          timestampConverter,
          testClock);
  Mockito.verify(startEndHandler, Mockito.times(1)).onStart(span);
  testClock.advanceTime(Duration.create(0, 100));
  assertThat(span.getStatus()).isEqualTo(Status.OK);
  span.setStatus(Status.CANCELLED);
  assertThat(span.getStatus()).isEqualTo(Status.CANCELLED);
  span.end(EndSpanOptions.builder().setStatus(Status.ABORTED).build());
  assertThat(span.getStatus()).isEqualTo(Status.ABORTED);
}
 
Example #8
Source File: RecordEventsSpanImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void status_ViaSetStatus() {
  RecordEventsSpanImpl span =
      RecordEventsSpanImpl.startSpan(
          spanContext,
          SPAN_NAME,
          null,
          parentSpanId,
          false,
          TraceParams.DEFAULT,
          startEndHandler,
          timestampConverter,
          testClock);
  Mockito.verify(startEndHandler, Mockito.times(1)).onStart(span);
  testClock.advanceTime(Duration.create(0, 100));
  assertThat(span.getStatus()).isEqualTo(Status.OK);
  span.setStatus(Status.CANCELLED);
  assertThat(span.getStatus()).isEqualTo(Status.CANCELLED);
  span.end();
  assertThat(span.getStatus()).isEqualTo(Status.CANCELLED);
}
 
Example #9
Source File: BigtableMutatorImpl.java    From heroic with Apache License 2.0 6 votes vote down vote up
private BulkMutation getOrAddBulkMutation(String tableName) {
    final Span span = tracer.spanBuilder("BigtableMutator.getOrAddBulkMutation").startSpan();
    try (Scope ws = tracer.withSpan(span)) {
        span.addAnnotation("Acquiring lock");
        synchronized (tableAccessLock) {
            span.addAnnotation("Lock acquired");

            if (tableToBulkMutation.containsKey(tableName)) {
                span.setStatus(Status.ALREADY_EXISTS.withDescription("Mutation exists in map"));
                span.end();
                return tableToBulkMutation.get(tableName);
            }

            final BulkMutation bulkMutation = session.createBulkMutation(
                session
                    .getOptions()
                    .getInstanceName()
                    .toTableName(tableName));

            tableToBulkMutation.put(tableName, bulkMutation);

            span.end();
            return bulkMutation;
        }
    }
}
 
Example #10
Source File: OcAgentExportersQuickStart.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static void doWork(int iteration, int jobs, LongGauge gauge) {
  String childSpanName = "iteration-" + iteration;
  LabelValue value = LabelValue.create(childSpanName);
  LongPoint point = gauge.getOrCreateTimeSeries(Collections.singletonList(value));
  try (Scope scope = tracer.spanBuilder(childSpanName).startScopedSpan()) {
    for (int i = 0; i < jobs; i++) {
      String grandChildSpanName = childSpanName + "-job-" + i;
      try (Scope childScope = tracer.spanBuilder(grandChildSpanName).startScopedSpan()) {
        point.set(jobs - i);
        String line = generateRandom(random.nextInt(128));
        processLine(line);
        recordStat(M_LINES_IN, 1L);
        recordStat(M_LINE_LENGTHS, (long) line.length());
      } catch (Exception e) {
        tracer.getCurrentSpan().setStatus(Status.INTERNAL.withDescription(e.toString()));
      }
    }
  }
}
 
Example #11
Source File: PrometheusStatsCollector.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void export(Collection<Metric> metrics) {
  samples.ensureCapacity(metrics.size());
  for (Metric metric : metrics) {
    try {
      samples.add(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              metric.getMetricDescriptor(), namespace));
    } catch (Throwable e) {
      logger.log(Level.WARNING, "Exception thrown when describing metrics.", e);
      tracer
          .getCurrentSpan()
          .setStatus(
              Status.UNKNOWN.withDescription(
                  "Exception thrown when describing Prometheus Metrics: "
                      + exceptionMessage(e)));
    }
  }
}
 
Example #12
Source File: CoreIngestionGroup.java    From heroic with Apache License 2.0 5 votes vote down vote up
protected AsyncFuture<Ingestion> syncWrite(final Request request) {
    final Span span = tracer.spanBuilder("CoreIngestionGroup.syncWrite").startSpan();

    if (!filter.get().apply(request.getSeries())) {
        reporter.reportDroppedByFilter();
        span.setStatus(Status.FAILED_PRECONDITION.withDescription("Dropped by filter"));
        span.end();
        return async.resolved(Ingestion.of(ImmutableList.of()));
    }

    try {
        span.addAnnotation("Acquiring write lock");
        writePermits.acquire();
    } catch (final InterruptedException e) {
        String error = "Failed to acquire semaphore for bounded request";
        span.setStatus(Status.INTERNAL.withDescription(error));
        span.end();
        return async.failed(new Exception(error, e));
    }

    span.addAnnotation("Acquired write lock");
    reporter.incrementConcurrentWrites();

    try (Scope ws = tracer.withSpan(span)) {
        return doWrite(request).onFinished(() -> {
            writePermits.release();
            reporter.decrementConcurrentWrites();
            span.end();
        });
    }
}
 
Example #13
Source File: DatadogExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static Integer errorCode(@Nullable final Status status) {
  if (status == null || status.equals(Status.OK) || status.equals(Status.ALREADY_EXISTS)) {
    return 0;
  }

  return 1;
}
 
Example #14
Source File: EndSpanFutureReporter.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public void failed(final Throwable cause) throws Exception {
  span.putAttribute("error", booleanAttributeValue(true));
  Optional.ofNullable(cause.getMessage()).ifPresent(span::addAnnotation);
  span.setStatus(Status.INTERNAL);
  span.end();
}
 
Example #15
Source File: CensusTracingModule.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  // New RPCs on client-side inherit the tracing context from the current Context.
  // Safe usage of the unsafe trace API because CONTEXT_SPAN_KEY.get() returns the same value
  // as Tracer.getCurrentSpan() except when no value available when the return value is null
  // for the direct access and BlankSpan when Tracer API is used.
  final ClientCallTracer tracerFactory =
      newClientCallTracer(ContextUtils.getValue(Context.current()), method);
  ClientCall<ReqT, RespT> call =
      next.newCall(
          method,
          callOptions.withStreamTracerFactory(tracerFactory));
  return new SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      delegate().start(
          new SimpleForwardingClientCallListener<RespT>(responseListener) {
            @Override
            public void onClose(io.grpc.Status status, Metadata trailers) {
              tracerFactory.callEnded(status);
              super.onClose(status, trailers);
            }
          },
          headers);
    }
  };
}
 
Example #16
Source File: PrometheusStatsCollector.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void export(Collection<Metric> metrics) {
  samples.ensureCapacity(metrics.size());
  for (Metric metric : metrics) {
    MetricDescriptor metricDescriptor = metric.getMetricDescriptor();
    if (containsDisallowedLeLabelForHistogram(
            convertToLabelNames(metricDescriptor.getLabelKeys()),
            getType(metricDescriptor.getType()))
        || containsDisallowedQuantileLabelForSummary(
            convertToLabelNames(metricDescriptor.getLabelKeys()),
            getType(metricDescriptor.getType()))) {
      // silently skip Distribution metricdescriptor with "le" label key and Summary
      // metricdescriptor with "quantile" label key
      continue;
    }
    try {
      samples.add(PrometheusExportUtils.createMetricFamilySamples(metric, namespace));
    } catch (Throwable e) {
      logger.log(Level.WARNING, "Exception thrown when collecting metric samples.", e);
      tracer
          .getCurrentSpan()
          .setStatus(
              Status.UNKNOWN.withDescription(
                  "Exception thrown when collecting Prometheus Metric Samples: "
                      + exceptionMessage(e)));
    }
  }
}
 
Example #17
Source File: NoRecordEventsSpanImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotCrash() {
  Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>();
  attributes.put(
      "MyStringAttributeKey", AttributeValue.stringAttributeValue("MyStringAttributeValue"));
  Map<String, AttributeValue> multipleAttributes = new HashMap<String, AttributeValue>();
  multipleAttributes.put(
      "MyStringAttributeKey", AttributeValue.stringAttributeValue("MyStringAttributeValue"));
  multipleAttributes.put("MyBooleanAttributeKey", AttributeValue.booleanAttributeValue(true));
  multipleAttributes.put("MyLongAttributeKey", AttributeValue.longAttributeValue(123));
  // Tests only that all the methods are not crashing/throwing errors.
  noRecordEventsSpan.putAttribute(
      "MyStringAttributeKey2", AttributeValue.stringAttributeValue("MyStringAttributeValue2"));
  noRecordEventsSpan.addAttributes(attributes);
  noRecordEventsSpan.addAttributes(multipleAttributes);
  noRecordEventsSpan.addAnnotation("MyAnnotation");
  noRecordEventsSpan.addAnnotation("MyAnnotation", attributes);
  noRecordEventsSpan.addAnnotation("MyAnnotation", multipleAttributes);
  noRecordEventsSpan.addAnnotation(Annotation.fromDescription("MyAnnotation"));
  noRecordEventsSpan.addNetworkEvent(NetworkEvent.builder(NetworkEvent.Type.SENT, 1L).build());
  noRecordEventsSpan.addMessageEvent(MessageEvent.builder(MessageEvent.Type.SENT, 1L).build());
  noRecordEventsSpan.addLink(
      Link.fromSpanContext(SpanContext.INVALID, Link.Type.CHILD_LINKED_SPAN));
  noRecordEventsSpan.setStatus(Status.OK);
  noRecordEventsSpan.end(EndSpanOptions.DEFAULT);
  noRecordEventsSpan.end();
}
 
Example #18
Source File: HelloWorldServer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void sleepFor(int milliseconds) {
  try {
    Thread.sleep(milliseconds);
  } catch (InterruptedException e) {
    Span span = tracer.getCurrentSpan();
    span.addAnnotation("Exception thrown when performing work " + e.getMessage());
    span.setStatus(Status.UNKNOWN);
  }
}
 
Example #19
Source File: InProcessSampledSpanStoreImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getErrorSampledSpans_NullCode_MaxSpansToReturn() {
  RecordEventsSpanImpl span1 = createSampledSpan(REGISTERED_SPAN_NAME);
  testClock.advanceTime(Duration.create(0, 1000));
  span1.end(EndSpanOptions.builder().setStatus(Status.CANCELLED).build());
  RecordEventsSpanImpl span2 = createSampledSpan(REGISTERED_SPAN_NAME);
  testClock.advanceTime(Duration.create(0, 1000));
  span2.end(EndSpanOptions.builder().setStatus(Status.UNKNOWN).build());
  Collection<SpanData> samples =
      sampleStore.getErrorSampledSpans(ErrorFilter.create(REGISTERED_SPAN_NAME, null, 1));
  assertThat(samples.size()).isEqualTo(1);
  assertThat(samples).containsAnyOf(span1.toSpanData(), span2.toSpanData());
}
 
Example #20
Source File: CensusTracingModule.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Record a finished stream and mark the current time as the end time.
 *
 * <p>Can be called from any thread without synchronization.  Calling it the second time or more
 * is a no-op.
 */
@Override
public void streamClosed(io.grpc.Status status) {
  if (streamClosedUpdater != null) {
    if (streamClosedUpdater.getAndSet(this, 1) != 0) {
      return;
    }
  } else {
    if (streamClosed != 0) {
      return;
    }
    streamClosed = 1;
  }
  span.end(createEndSpanOptions(status, isSampledToLocalTracing));
}
 
Example #21
Source File: ZipkinExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ClientKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          // TODO SpanId.fromLowerBase16
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "Sent.helloworld.Greeter.SayHello", /* name */
          Kind.CLIENT, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(ZipkinExporterHandler.generateSpan(data, localEndpoint))
      .isEqualTo(
          Span.newBuilder()
              .traceId(TRACE_ID)
              .parentId(PARENT_SPAN_ID)
              .id(SPAN_ID)
              .kind(Span.Kind.CLIENT)
              .name(data.getName())
              .timestamp(1505855794000000L + 194009601L / 1000)
              .duration(
                  (1505855799000000L + 465726528L / 1000)
                      - (1505855794000000L + 194009601L / 1000))
              .localEndpoint(localEndpoint)
              .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED")
              .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT")
              .putTag(ZipkinExporterHandler.STATUS_CODE, "OK")
              .build());
}
 
Example #22
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_NoKindAndRemoteParent() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          null, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"ENTRY\","
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #23
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ServerKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          Kind.SERVER, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"ENTRY\","
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #24
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ClientKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          Kind.CLIENT, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"EXIT\","
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #25
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ErrorStatus() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          Kind.CLIENT, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OUT_OF_RANGE, /* status, any but OK */
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"EXIT\","
              + "\"error\":true,"
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #26
Source File: ZipkinExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ServerKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          // TODO SpanId.fromLowerBase16
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "Recv.helloworld.Greeter.SayHello", /* name */
          Kind.SERVER, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(ZipkinExporterHandler.generateSpan(data, localEndpoint))
      .isEqualTo(
          Span.newBuilder()
              .traceId(TRACE_ID)
              .parentId(PARENT_SPAN_ID)
              .id(SPAN_ID)
              .kind(Span.Kind.SERVER)
              .name(data.getName())
              .timestamp(1505855794000000L + 194009601L / 1000)
              .duration(
                  (1505855799000000L + 465726528L / 1000)
                      - (1505855794000000L + 194009601L / 1000))
              .localEndpoint(localEndpoint)
              .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED")
              .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT")
              .putTag(ZipkinExporterHandler.STATUS_CODE, "OK")
              .build());
}
 
Example #27
Source File: ZipkinExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_NoKindAndRemoteParent() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          // TODO SpanId.fromLowerBase16
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "Recv.helloworld.Greeter.SayHello", /* name */
          null, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(ZipkinExporterHandler.generateSpan(data, localEndpoint))
      .isEqualTo(
          Span.newBuilder()
              .traceId(TRACE_ID)
              .parentId(PARENT_SPAN_ID)
              .id(SPAN_ID)
              .kind(Span.Kind.SERVER)
              .name(data.getName())
              .timestamp(1505855794000000L + 194009601L / 1000)
              .duration(
                  (1505855799000000L + 465726528L / 1000)
                      - (1505855794000000L + 194009601L / 1000))
              .localEndpoint(localEndpoint)
              .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED")
              .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT")
              .putTag(ZipkinExporterHandler.STATUS_CODE, "OK")
              .build());
}
 
Example #28
Source File: HttpRequestTracingTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20_000L)
public void executeCreatesSpan() throws IOException {
  MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse().setStatusCode(200);
  HttpTransport transport =
      new MockHttpTransport.Builder().setLowLevelHttpResponse(mockResponse).build();
  HttpRequest request =
      new HttpRequestFactory(transport, null)
          .buildGetRequest(new GenericUrl("https://google.com/"));
  request.execute();

  // This call blocks - we set a timeout on this test to ensure we don't wait forever
  List<SpanData> spans = testHandler.waitForExport(1);
  assertEquals(1, spans.size());
  SpanData span = spans.get(0);

  // Ensure the span name is set
  assertEquals(SPAN_NAME_HTTP_REQUEST_EXECUTE, span.getName());

  // Ensure we have basic span attributes
  assertAttributeEquals(span, "http.path", "/");
  assertAttributeEquals(span, "http.host", "google.com");
  assertAttributeEquals(span, "http.url", "https://google.com/");
  assertAttributeEquals(span, "http.method", "GET");

  // Ensure we have a single annotation for starting the first attempt
  assertEquals(1, span.getAnnotations().getEvents().size());

  // Ensure we have 2 message events, SENT and RECEIVED
  assertEquals(2, span.getMessageEvents().getEvents().size());
  assertEquals(
      MessageEvent.Type.SENT, span.getMessageEvents().getEvents().get(0).getEvent().getType());
  assertEquals(
      MessageEvent.Type.RECEIVED,
      span.getMessageEvents().getEvents().get(1).getEvent().getType());

  // Ensure we record the span status as OK
  assertEquals(Status.OK, span.getStatus());
}
 
Example #29
Source File: JaegerExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void addStatusTags(List<Tag> tags, @Nullable Status status) {
  if (status == null) {
    return;
  }
  Tag statusTag = new Tag(STATUS_CODE, TagType.LONG).setVLong(status.getCanonicalCode().value());
  tags.add(statusTag);
  if (status.getDescription() != null) {
    tags.add(new Tag(STATUS_MESSAGE, TagType.STRING).setVStr(status.getDescription()));
  }
}
 
Example #30
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void convertErrorSpanDataToJaegerThriftSpan() throws SenderException {
  long startTime = 1519629870001L;
  long endTime = 1519630148002L;
  String statusMessage = "timeout";
  SpanData spanData =
      SpanData.create(
          sampleSpanContext(),
          SpanId.fromBytes(new byte[] {(byte) 0x7F, FF, FF, FF, FF, FF, FF, FF}),
          true,
          "test",
          Kind.SERVER,
          Timestamp.fromMillis(startTime),
          SpanData.Attributes.create(Collections.<String, AttributeValue>emptyMap(), 0),
          SpanData.TimedEvents.create(Collections.<TimedEvent<Annotation>>emptyList(), 0),
          SpanData.TimedEvents.create(Collections.<TimedEvent<MessageEvent>>emptyList(), 0),
          SpanData.Links.create(Collections.<Link>emptyList(), 0),
          0,
          Status.DEADLINE_EXCEEDED.withDescription(statusMessage),
          Timestamp.fromMillis(endTime));

  handler.export(singletonList(spanData));

  verify(mockSender).send(eq(process), captor.capture());
  List<Span> spans = captor.getValue();

  assertThat(spans.size()).isEqualTo(1);
  Span span = spans.get(0);

  assertThat(span.tags.size()).isEqualTo(3);
  assertThat(span.tags)
      .containsExactly(
          new Tag(JaegerExporterHandler.SPAN_KIND, TagType.STRING).setVStr("server"),
          new Tag(JaegerExporterHandler.STATUS_CODE, TagType.LONG).setVLong(4),
          new Tag(JaegerExporterHandler.STATUS_MESSAGE, TagType.STRING).setVStr(statusMessage));
}