Java Code Examples for io.opencensus.trace.SpanContext#create()

The following examples show how to use io.opencensus.trace.SpanContext#create() . 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: 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 3
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 4
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 5
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 6
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 7
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);
}
 
Example 8
Source File: B3FormatImplBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
  textFormatBase = new TextFormatBenchmarkBase(new B3Format());
  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);
}
 
Example 9
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 10
Source File: B3FormatTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void parseMissingSampledAndMissingFlag() throws SpanContextParseException {
  Map<String, String> headersNotSampled = new HashMap<String, String>();
  headersNotSampled.put(X_B3_TRACE_ID, TRACE_ID_BASE16);
  headersNotSampled.put(X_B3_SPAN_ID, SPAN_ID_BASE16);
  SpanContext spanContext = SpanContext.create(TRACE_ID, SPAN_ID, TraceOptions.DEFAULT);
  assertThat(b3Format.extract(headersNotSampled, getter)).isEqualTo(spanContext);
}
 
Example 11
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 12
Source File: OpenCensusSleuthSpan.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static SpanContext fromSleuthSpan(org.springframework.cloud.sleuth.Span span) {
  return SpanContext.create(
      TraceId.fromBytes(
          ByteBuffer.allocate(TraceId.SIZE)
              .putLong(span.getTraceIdHigh())
              .putLong(span.getTraceId())
              .array()),
      SpanId.fromBytes(ByteBuffer.allocate(SpanId.SIZE).putLong(span.getSpanId()).array()),
      Boolean.TRUE.equals(span.isExportable()) ? sampledOptions : notSampledOptions);
}
 
Example 13
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 14
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 15
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);
}