io.opencensus.trace.TraceOptions Java Examples

The following examples show how to use io.opencensus.trace.TraceOptions. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: CloudTraceFormat.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 {
    String headerStr = getter.get(carrier, HEADER_NAME);
    if (headerStr == null || headerStr.length() < MIN_HEADER_SIZE) {
      throw new SpanContextParseException("Missing or too short header: " + HEADER_NAME);
    }
    checkArgument(headerStr.charAt(TRACE_ID_SIZE) == SPAN_ID_DELIMITER, "Invalid TRACE_ID size");

    TraceId traceId = TraceId.fromLowerBase16(headerStr.subSequence(0, TRACE_ID_SIZE));
    int traceOptionsPos = headerStr.indexOf(TRACE_OPTION_DELIMITER, TRACE_ID_SIZE);
    CharSequence spanIdStr =
        headerStr.subSequence(
            SPAN_ID_START_POS, traceOptionsPos < 0 ? headerStr.length() : traceOptionsPos);
    SpanId spanId = longToSpanId(UnsignedLongs.parseUnsignedLong(spanIdStr.toString(), 10));
    TraceOptions traceOptions = OPTIONS_NOT_SAMPLED;
    if (traceOptionsPos > 0) {
      String traceOptionsStr = headerStr.substring(traceOptionsPos + TRACE_OPTION_DELIMITER_SIZE);
      if ((UnsignedInts.parseUnsignedInt(traceOptionsStr, 10) & CLOUD_TRACE_IS_SAMPLED) != 0) {
        traceOptions = OPTIONS_SAMPLED;
      }
    }
    return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
  } catch (IllegalArgumentException e) {
    throw new SpanContextParseException("Invalid input", e);
  }
}
 
Example #14
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void enhanceLogEntry_ConvertNullProjectIdToEmptyString() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer(null),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("bfb4248a24325a905873a1d43001d9a0"),
                  SpanId.fromLowerBase16("6f23f9afd448e272"),
                  TraceOptions.builder().setIsSampled(true).build(),
                  EMPTY_TRACESTATE)));
  assertThat(logEntry.getTrace()).isEqualTo("projects//traces/bfb4248a24325a905873a1d43001d9a0");
}
 
Example #15
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 #16
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 #17
Source File: BasicOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create a link. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Link createLink(Data data) {
  return Link.fromSpanContext(
      SpanContext.create(
          TraceId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}),
          SpanId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 0}),
          TraceOptions.DEFAULT,
          TRACESTATE_DEFAULT),
      Link.Type.PARENT_LINKED_SPAN);
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #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: TraceContextFormatTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void inject_NotSampledContext_WithTraceState() {
  Map<String, String> carrier = new LinkedHashMap<String, String>();
  traceContextFormat.inject(
      SpanContext.create(TRACE_ID, SPAN_ID, TraceOptions.DEFAULT, TRACESTATE_NOT_DEFAULT),
      carrier,
      setter);
  assertThat(carrier)
      .containsExactly(
          TRACEPARENT,
          TRACEPARENT_HEADER_NOT_SAMPLED,
          TRACESTATE,
          TRACESTATE_NOT_DEFAULT_ENCODING);
}
 
Example #27
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 #28
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);
  }
}
 
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: TraceContextImplBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
  textFormatBase =
      new TextFormatBenchmarkBase(Tracing.getPropagationComponent().getTraceContextFormat());
  Random random = new Random(1234);
  spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.builder().setIsSampled(random.nextBoolean()).build(),
          Tracestate.builder().build());
  spanContextHeaders = new HashMap<String, String>();
  textFormatBase.inject(spanContext, spanContextHeaders);
}