io.opencensus.trace.TraceId Java Examples

The following examples show how to use io.opencensus.trace.TraceId. 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: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void generateSpan_NullStatus() {
  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 */
          null, /* status */
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo("[]");
}
 
Example #2
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addSampledSpanToLogEntryWithAllSpans() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("b9718fe3d82d36fce0e6a1ada1c21db0"),
              SpanId.fromLowerBase16("75159dde8c503fee"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              logger.warn("message #1");
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=b9718fe3d82d36fce0e6a1ada1c21db0 spanId=75159dde8c503fee "
              + "sampled=true WARN  - message #1");
}
 
Example #3
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void enhanceLogEntry_AddNonSampledSpanToLogEntry() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer("my-test-project-6"),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("72c905c76f99e99974afd84dc053a480"),
                  SpanId.fromLowerBase16("731e102335b7a5a0"),
                  TraceOptions.builder().setIsSampled(false).build(),
                  EMPTY_TRACESTATE)));
  assertFalse(logEntry.getTraceSampled());
  assertThat(logEntry.getTrace())
      .isEqualTo("projects/my-test-project-6/traces/72c905c76f99e99974afd84dc053a480");
  assertThat(logEntry.getSpanId()).isEqualTo("731e102335b7a5a0");
}
 
Example #4
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void enhanceLogEntry_AddSampledSpanToLogEntry() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer("my-test-project-3"),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("4c6af40c499951eb7de2777ba1e4fefa"),
                  SpanId.fromLowerBase16("de52e84d13dd232d"),
                  TraceOptions.builder().setIsSampled(true).build(),
                  EMPTY_TRACESTATE)));
  assertTrue(logEntry.getTraceSampled());
  assertThat(logEntry.getTrace())
      .isEqualTo("projects/my-test-project-3/traces/4c6af40c499951eb7de2777ba1e4fefa");
  assertThat(logEntry.getSpanId()).isEqualTo("de52e84d13dd232d");
}
 
Example #5
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonSampledSpanToLogEntryWithAllSpans() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("cd7061dfa9d312cdcc42edab3feab51b"),
              SpanId.fromLowerBase16("117d42d4c7acd066"),
              TraceOptions.builder().setIsSampled(false).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              logger.info("message #2");
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=cd7061dfa9d312cdcc42edab3feab51b spanId=117d42d4c7acd066 sampled=false INFO  "
              + "- message #2");
}
 
Example #6
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void preserveOtherKeyValuePairs() {
  String log =
      logWithSpanAndLog4jConfiguration(
          "%X{traceId} %X{myTestKey} %-5level - %msg",
          SpanContext.create(
              TraceId.fromLowerBase16("c95329bb6b7de41afbc51a231c128f97"),
              SpanId.fromLowerBase16("bf22ea74d38eddad"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              String key = "myTestKey";
              ThreadContext.put(key, "myTestValue");
              try {
                logger.error("message #4");
              } finally {
                ThreadContext.remove(key);
              }
              return null;
            }
          });
  assertThat(log).isEqualTo("c95329bb6b7de41afbc51a231c128f97 myTestValue ERROR - message #4");
}
 
Example #7
Source File: AppEngineCloudTraceContextUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}.
 *
 * @param cloudTraceContext the AppEngine {@code CloudTraceContext}.
 * @return the converted {@code SpanContext}.
 * @since 0.14
 */
public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) {
  checkNotNull(cloudTraceContext, "cloudTraceContext");

  try {
    // Extract the trace ID from the binary protobuf CloudTraceContext#traceId.
    TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId());
    ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE);
    traceIdBuf.putLong(traceIdProto.getHi());
    traceIdBuf.putLong(traceIdProto.getLo());
    ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE);
    spanIdBuf.putLong(cloudTraceContext.getSpanId());

    return SpanContext.create(
        TraceId.fromBytes(traceIdBuf.array()),
        SpanId.fromBytes(spanIdBuf.array()),
        TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(),
        TRACESTATE_DEFAULT);
  } catch (com.google.protobuf.InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: InProcessRunningSpanStoreImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private RecordEventsSpanImpl createSpan(String spanName) {
  final SpanContext spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT,
          Tracestate.builder().build());
  return RecordEventsSpanImpl.startSpan(
      spanContext,
      spanName,
      null,
      SpanId.generateRandomId(random),
      false,
      TraceParams.DEFAULT,
      startEndHandler,
      null,
      MillisClock.getInstance());
}
 
Example #9
Source File: SpanBuilderImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void startRemoteSpan() {
  SpanContext spanContext =
      SpanContext.create(
          TraceId.generateRandomId(randomHandler.current()),
          SpanId.generateRandomId(randomHandler.current()),
          TraceOptions.DEFAULT);
  RecordEventsSpanImpl span =
      (RecordEventsSpanImpl)
          SpanBuilderImpl.createWithRemoteParent(SPAN_NAME, spanContext, spanBuilderOptions)
              .setRecordEvents(true)
              .startSpan();
  assertThat(span.getContext().isValid()).isTrue();
  assertThat(span.getContext().getTraceId()).isEqualTo(spanContext.getTraceId());
  assertThat(span.getContext().getTraceOptions().isSampled()).isTrue();
  SpanData spanData = span.toSpanData();
  assertThat(spanData.getParentSpanId()).isEqualTo(spanContext.getSpanId());
  assertThat(spanData.getHasRemoteParent()).isTrue();
}
 
Example #10
Source File: SpanBuilderImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static boolean makeSamplingDecision(
    @Nullable SpanContext parent,
    @Nullable Boolean hasRemoteParent,
    String name,
    @Nullable Sampler sampler,
    List<Span> parentLinks,
    TraceId traceId,
    SpanId spanId,
    TraceParams activeTraceParams) {
  // If users set a specific sampler in the SpanBuilder, use it.
  if (sampler != null) {
    return sampler.shouldSample(parent, hasRemoteParent, traceId, spanId, name, parentLinks);
  }
  // Use the default sampler if this is a root Span or this is an entry point Span (has remote
  // parent).
  if (Boolean.TRUE.equals(hasRemoteParent) || parent == null || !parent.isValid()) {
    return activeTraceParams
        .getSampler()
        .shouldSample(parent, hasRemoteParent, traceId, spanId, name, parentLinks);
  }
  // Parent is always different than null because otherwise we use the default sampler.
  return parent.getTraceOptions().isSampled() || isAnyParentLinkSampled(parentLinks);
}
 
Example #11
Source File: TextFormatGetterTest.java    From heroic with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpan () throws Exception {

  Random random = new Random(1234);
  SpanId generateSpanId = SpanId.generateRandomId(random);
  String spanId = UnsignedLongs.toString(spanIdToLong(generateSpanId));
  String traceId = TraceId.generateRandomId(random).toLowerBase16();

  final List<String> headers = new ArrayList<>();
  headers.add(traceId + "/" + spanId + ";o=1");
  doReturn(headers).when(request).getRequestHeader("X-Cloud-Trace-Context");

  final SpanContext spanContext = textFormat.extract(request, textFormatGetter);

  assertEquals(generateSpanId, spanContext.getSpanId());
}
 
Example #12
Source File: SamplersTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static void assertSamplerSamplesWithProbability(
    Sampler sampler, SpanContext parent, List<Span> parentLinks, double probability) {
  Random random = new Random(1234);
  int count = 0; // Count of spans with sampling enabled
  for (int i = 0; i < NUM_SAMPLE_TRIES; i++) {
    if (sampler.shouldSample(
        parent,
        false,
        TraceId.generateRandomId(random),
        SpanId.generateRandomId(random),
        SPAN_NAME,
        parentLinks)) {
      count++;
    }
  }
  double proportionSampled = (double) count / NUM_SAMPLE_TRIES;
  // Allow for a large amount of slop (+/- 10%) in number of sampled traces, to avoid flakiness.
  assertThat(proportionSampled < probability + 0.1 && proportionSampled > probability - 0.1)
      .isTrue();
}
 
Example #13
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static List<Link> sampleLinks() {
  return Lists.newArrayList(
      Link.fromSpanContext(
          SpanContext.create(
              TraceId.fromBytes(
                  new byte[] {FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, 0}),
              SpanId.fromBytes(new byte[] {0, 0, 0, 0, 0, 0, 2, 0}),
              TraceOptions.builder().setIsSampled(false).build(),
              Tracestate.builder().build()),
          Link.Type.CHILD_LINKED_SPAN,
          ImmutableMap.of(
              "Bool", AttributeValue.booleanAttributeValue(true),
              "Long", AttributeValue.longAttributeValue(299792458L),
              "String",
                  AttributeValue.stringAttributeValue(
                      "Man is condemned to be free; because once thrown into the world, "
                          + "he is responsible for everything he does. -- Sartre"))));
}
 
Example #14
Source File: SpanOperationsBenchmark.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private void initAttributes() {
  attributeValues = createAttributeValues(size);
  attributeKeys = new String[size];
  attributeMap = new HashMap<>(size);
  messageEvents = new MessageEvent[size];
  links = new Link[size];
  for (int i = 0; i < size; i++) {
    attributeKeys[i] = ATTRIBUTE_KEY + "-i";
    attributeMap.put(attributeKeys[i], attributeValues[i]);
    messageEvents[i] = MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID + i).build();
    links[i] =
        Link.fromSpanContext(
            SpanContext.create(
                TraceId.fromBytes(
                    new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (byte) i}),
                SpanId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, (byte) i}),
                TraceOptions.DEFAULT,
                TRACESTATE_DEFAULT),
            Link.Type.PARENT_LINKED_SPAN);
  }
}
 
Example #15
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 #16
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 #17
Source File: StatsTestUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MockableSpan with a random trace ID and span ID.
 */
@SuppressWarnings("deprecation")
public static MockableSpan generateRandomSpan(Random random) {
  return new MockableSpan(
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT),
      null);
}
 
Example #18
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 #19
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 #20
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void overwriteExistingTracingKey() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("18e4ae44273a0c44e0c9ea4380792c66"),
              SpanId.fromLowerBase16("199a7e16daa000a7"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              ThreadContext.put(
                  OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY, "existingTraceId");
              try {
                logger.error("message #5");
              } finally {
                ThreadContext.remove(OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY);
              }
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=18e4ae44273a0c44e0c9ea4380792c66 spanId=199a7e16daa000a7 "
              + "sampled=true ERROR - message #5");
}
 
Example #21
Source File: OpenCensusTraceContextDataInjectorTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void rawContextDataWithTracingData() {
  OpenCensusTraceContextDataInjector plugin = new OpenCensusTraceContextDataInjector();
  SpanContext spanContext =
      SpanContext.create(
          TraceId.fromLowerBase16("e17944156660f55b8cae5ce3f45d4a40"),
          SpanId.fromLowerBase16("fc3d2ba0d283b66a"),
          TraceOptions.builder().setIsSampled(true).build(),
          EMPTY_TRACESTATE);
  Scope scope = tracer.withSpan(new TestSpan(spanContext));
  try {
    String key = "myTestKey";
    ThreadContext.put(key, "myTestValue");
    try {
      assertThat(plugin.rawContextData().toMap())
          .containsExactly(
              "myTestKey",
              "myTestValue",
              "traceId",
              "e17944156660f55b8cae5ce3f45d4a40",
              "spanId",
              "fc3d2ba0d283b66a",
              "traceSampled",
              "true");
    } finally {
      ThreadContext.remove(key);
    }
  } finally {
    scope.close();
  }
}
 
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: StatsTestUtils.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MockableSpan with a random trace ID and span ID.
 */
@SuppressWarnings("deprecation")
public static MockableSpan generateRandomSpan(Random random) {
  return new MockableSpan(
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT),
      null);
}
 
Example #26
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 #27
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static SpanContext sampleSpanContext() {
  return SpanContext.create(
      TraceId.fromBytes(new byte[] {FF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}),
      SpanId.fromBytes(new byte[] {0, 0, 0, 0, 0, 0, 1, 0}),
      TraceOptions.builder().setIsSampled(true).build(),
      Tracestate.builder().build());
}
 
Example #28
Source File: BinaryFormatImplBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
  binaryFormat = new BinaryFormatImpl();
  Random random = new Random(1234);
  spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.builder().setIsSampled(random.nextBoolean()).build(),
          Tracestate.builder().build());
  spanContextBinary = binaryFormat.toByteArray(spanContext);
}
 
Example #29
Source File: BinaryFormatImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public SpanContext fromByteArray(byte[] bytes) throws SpanContextParseException {
  checkNotNull(bytes, "bytes");
  if (bytes.length == 0 || bytes[0] != VERSION_ID) {
    throw new SpanContextParseException("Unsupported version.");
  }
  if (bytes.length < REQUIRED_FORMAT_LENGTH) {
    throw new SpanContextParseException("Invalid input: truncated");
  }
  // TODO: the following logic assumes that fields are written in ID order. The spec does not say
  // that. If it decides not to, this logic would need to be more like a loop
  TraceId traceId;
  SpanId spanId;
  TraceOptions traceOptions = TraceOptions.DEFAULT;
  int pos = 1;
  if (bytes[pos] == TRACE_ID_FIELD_ID) {
    traceId = TraceId.fromBytes(bytes, pos + ID_SIZE);
    pos += ID_SIZE + TraceId.SIZE;
  } else {
    // TODO: update the spec to suggest that the trace ID is not actually optional
    throw new SpanContextParseException("Invalid input: expected trace ID at offset " + pos);
  }
  if (bytes[pos] == SPAN_ID_FIELD_ID) {
    spanId = SpanId.fromBytes(bytes, pos + ID_SIZE);
    pos += ID_SIZE + SpanId.SIZE;
  } else {
    // TODO: update the spec to suggest that the span ID is not actually optional.
    throw new SpanContextParseException("Invalid input: expected span ID at offset " + pos);
  }
  // Check to see if we are long enough to include an options field, and also that the next field
  // is an options field. Per spec we simply stop parsing at first unknown field instead of
  // failing.
  if (bytes.length > pos && bytes[pos] == TRACE_OPTION_FIELD_ID) {
    if (bytes.length < ALL_FORMAT_LENGTH) {
      throw new SpanContextParseException("Invalid input: truncated");
    }
    traceOptions = TraceOptions.fromByte(bytes[pos + ID_SIZE]);
  }
  return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
}
 
Example #30
Source File: B3Format.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public <C /*>>> extends @NonNull Object*/> SpanContext extract(C carrier, Getter<C> getter)
    throws SpanContextParseException {
  checkNotNull(carrier, "carrier");
  checkNotNull(getter, "getter");
  try {
    TraceId traceId;
    String traceIdStr = getter.get(carrier, X_B3_TRACE_ID);
    if (traceIdStr != null) {
      if (traceIdStr.length() == TraceId.SIZE) {
        // This is an 8-byte traceID.
        traceIdStr = UPPER_TRACE_ID + traceIdStr;
      }
      traceId = TraceId.fromLowerBase16(traceIdStr);
    } else {
      throw new SpanContextParseException("Missing X_B3_TRACE_ID.");
    }
    SpanId spanId;
    String spanIdStr = getter.get(carrier, X_B3_SPAN_ID);
    if (spanIdStr != null) {
      spanId = SpanId.fromLowerBase16(spanIdStr);
    } else {
      throw new SpanContextParseException("Missing X_B3_SPAN_ID.");
    }
    TraceOptions traceOptions = TraceOptions.DEFAULT;
    if (SAMPLED_VALUE.equals(getter.get(carrier, X_B3_SAMPLED))
        || FLAGS_VALUE.equals(getter.get(carrier, X_B3_FLAGS))) {
      traceOptions = TraceOptions.builder().setIsSampled(true).build();
    }
    return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
  } catch (IllegalArgumentException e) {
    throw new SpanContextParseException("Invalid input.", e);
  }
}