io.jaegertracing.internal.JaegerSpanContext Java Examples

The following examples show how to use io.jaegertracing.internal.JaegerSpanContext. 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: OpenTracingTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private WebClient withTrace(final WebClient client, final JaegerSpanContext spanContext) {
    tracer.inject(spanContext, Builtin.HTTP_HEADERS, new TextMap() {

        @Override
        public void put(String key, String value) {
            client.header(key, value);
        }

        @Override
        public Iterator<Entry<String, String>> iterator() {
            return null;
        }
    });

    return client;
}
 
Example #2
Source File: TestStringCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
void testExtract() throws Exception {
  StringCodec codec = new StringCodec();

  LambdaTestUtils.intercept(EmptyTracerStateStringException.class,
      () -> codec.extract(null));

  StringBuilder sb = new StringBuilder().append("123");
  LambdaTestUtils.intercept(MalformedTracerStateStringException.class,
      "String does not match tracer state format",
      () -> codec.extract(sb));

  sb.append(":456:789");
  LambdaTestUtils.intercept(MalformedTracerStateStringException.class,
      "String does not match tracer state format",
      () -> codec.extract(sb));
  sb.append(":66");
  JaegerSpanContext context = codec.extract(sb);
  String expectedContextString = new String("123:456:789:66");
  assertTrue(context.getTraceId().equals("123"));
  assertTrue(context.toString().equals(expectedContextString));
}
 
Example #3
Source File: JaegerPropagatorTest.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
@Test
public void extract_SampledContext_Short_TraceId() {
  Map<String, String> carrier = new LinkedHashMap<>();
  JaegerSpanContext context =
      new JaegerSpanContext(
          SHORT_TRACE_ID_HI,
          SHORT_TRACE_ID_LOW,
          SPAN_ID_LONG,
          DEPRECATED_PARENT_SPAN_LONG,
          (byte) 1);
  carrier.put(PROPAGATION_HEADER, TextMapCodec.contextAsString(context));

  assertThat(getSpanContext(jaegerPropagator.extract(Context.current(), carrier, getter)))
      .isEqualTo(
          SpanContext.createFromRemoteParent(
              SHORT_TRACE_ID, SPAN_ID, SAMPLED_TRACE_OPTIONS, TRACE_STATE_DEFAULT));
}
 
Example #4
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatNewInnerSpanIsCreatedUsingAsyncInvocation() throws InterruptedException {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/books/async"), spanId).get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    await().atMost(Duration.ofSeconds(1L)).until(()-> REPORTER.getSpans().size() == 2);

    assertThat(REPORTER.getSpans().size(), equalTo(2));
    assertEquals("Processing books", REPORTER.getSpans().get(0).getOperationName());
    assertEquals("GET /bookstore/books/async", REPORTER.getSpans().get(1).getOperationName());
    assertThat(REPORTER.getSpans().get(1).getReferences(), not(empty()));
    assertThat(REPORTER.getSpans().get(1).getReferences().get(0).getSpanContext().getSpanId(),
        equalTo(spanId.getSpanId()));
}
 
Example #5
Source File: NestedMdcScopesTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void mdcIsRestoredCorrectly() {
    ThreadLocalScopeManager threadLocalScopeManager = new ThreadLocalScopeManager();
    MDCScopeManager mdcScopeManager = new MDCScopeManager(threadLocalScopeManager);

    assertNull(mdcScopeManager.active());
    assertNull(threadLocalScopeManager.active());
    assertNull(MDC.get("traceId"));

    JaegerSpanContext span = new JaegerSpanContext(1, 1, 1, 1, Byte.valueOf("0"));
    Scope scope = mdcScopeManager.activate(new TestSpan(span), true);
    assertSame(span, threadLocalScopeManager.active().span().context());
    assertEquals("10000000000000001", MDC.get("traceId"));

    JaegerSpanContext subSpan = new JaegerSpanContext(2, 2, 2, 1, Byte.valueOf("0"));
    Scope subScope = mdcScopeManager.activate(new TestSpan(subSpan), true);
    assertSame(subSpan, threadLocalScopeManager.active().span().context());
    assertEquals("20000000000000002", MDC.get("traceId"));

    subScope.close();

    assertSame(span, threadLocalScopeManager.active().span().context());
    assertEquals("10000000000000001", MDC.get("traceId"));

    scope.close();

    assertNull(mdcScopeManager.active());
    assertNull(threadLocalScopeManager.active());
    assertNull(MDC.get("traceId"));
}
 
Example #6
Source File: StringCodec.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public void inject(JaegerSpanContext context, StringBuilder string) {
  int intFlag = context.getFlags() & 255;
  string.append(context.getTraceId())
      .append(":").append(Long.toHexString(context.getSpanId()))
      .append(":").append(Long.toHexString(context.getParentId()))
      .append(":").append(Integer.toHexString(intFlag));
}
 
Example #7
Source File: MDCScope.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public MDCScope(Scope scope) {
    this.wrapped = scope;
    this.originalTraceId = MDC.get(TRACE_ID);
    this.originalSpanId = MDC.get(SPAN_ID);
    this.originalSampled = MDC.get(SAMPLED);
    if (scope.span().context() instanceof JaegerSpanContext) {
        putContext((JaegerSpanContext) scope.span().context());
    }
}
 
Example #8
Source File: TracingPropagationTest.java    From tchannel-java with MIT License 5 votes vote down vote up
private static TraceResponse observeSpanAndDownstream(String encodings, Trace requestTrace) {
    Span span = tracingContext.currentSpan();
    TraceResponse response = new TraceResponse();
    JaegerSpanContext context = (JaegerSpanContext) span.context();
    response.requestTrace = requestTrace;
    response.traceId = context.toTraceId();
    response.sampled = context.isSampled();
    response.baggage = span.getBaggageItem(BAGGAGE_KEY);
    try {
        response.downstream = callDownstream(encodings);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
 
Example #9
Source File: TracingPropagationTest.java    From tchannel-java with MIT License 5 votes vote down vote up
/**
 * Validates that span information is encoded in request (call request frame, not headers) and propagated through.
 *
 * @param upstreamSpanContext the upstream span context, i.e., the root span context
 * @param requestTrace trace information as part of request
 */
private void validateRequestTrace(SpanContext upstreamSpanContext, Trace requestTrace) {
    assertNotNull(requestTrace);
    JaegerSpanContext upstreamContext = (JaegerSpanContext) upstreamSpanContext;
    assertEquals(upstreamContext.getTraceIdLow(), requestTrace.traceId);
    // span encoded in request is child span of upstream span
    assertEquals(upstreamContext.getSpanId(), requestTrace.parentId);
    assertNotEquals(upstreamContext.getSpanId(), requestTrace.spanId);
    assertEquals(upstreamContext.getFlags(), requestTrace.traceFlags);
}
 
Example #10
Source File: InboundRequestTraceTest.java    From tchannel-java with MIT License 5 votes vote down vote up
@Test
public void testInboundRequestWithNonNullTrace() {
    Trace trace = new Trace(42, 0, 42, (byte) 1);
    request.setTrace(trace);

    Span span = Tracing.startInboundSpan(request,tracer, new TracingContext.Default());
    JaegerSpanContext spanContext = (JaegerSpanContext) span.context();
    assertEquals(trace.traceId, spanContext.getTraceIdLow());
    assertEquals(trace.spanId, spanContext.getParentId());
    assertEquals(trace.traceFlags, spanContext.getFlags());
    assertNotEquals(trace.spanId, spanContext.getSpanId());
}
 
Example #11
Source File: TraceBehavior.java    From tchannel-java with MIT License 5 votes vote down vote up
private ObservedSpan observeSpan() {
    if (!tchannel.getTracingContext().hasSpan()) {
        return new ObservedSpan("no span", false, "no span");
    }
    JaegerSpanContext spanContext = (JaegerSpanContext) tchannel.getTracingContext().currentSpan().context();

    return new ObservedSpan(
            spanContext.toTraceId(),
            spanContext.isSampled(),
            spanContext.getBaggageItem(BAGGAGE_KEY));
}
 
Example #12
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatNewInnerSpanIsCreated() throws Exception {
    final JaegerSpanContext spanId = fromRandom();

    final Map<String, List<String>> headers = new HashMap<>();
    tracer.inject(spanId, Builtin.HTTP_HEADERS, new TextMapInjectAdapter(headers));

    final BookStoreService service = createJaxWsService(headers);
    assertThat(service.getBooks().size(), equalTo(2));

    assertThat(REPORTER.getSpans().size(), equalTo(2));
    assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("Get Books"));
    assertThat(REPORTER.getSpans().get(1).getOperationName(), equalTo("POST /BookStore"));
}
 
Example #13
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatNewInnerSpanIsCreated() {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/books"), spanId).get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    assertThat(REPORTER.getSpans().size(), equalTo(2));
    assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("Get Books"));
    assertThat(REPORTER.getSpans().get(1).getOperationName(), equalTo("GET /bookstore/books"));
}
 
Example #14
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatCurrentSpanIsAnnotatedWithKeyValue() {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/book/1"), spanId).get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    assertThat(REPORTER.getSpans().size(), equalTo(1));
    assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("GET /bookstore/book/1"));
    assertThat(REPORTER.getSpans().get(0).getTags(), hasItem("book-id", "1"));
}
 
Example #15
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatParallelSpanIsAnnotatedWithTimeline() {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/process"), spanId).put("");
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    assertThat(REPORTER.getSpans().size(), equalTo(2));
    assertThat(REPORTER.getSpans(), hasSpan("Processing books", hasItem("Processing started")));
    assertThat(REPORTER.getSpans(), hasSpan("PUT /bookstore/process"));
}
 
Example #16
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatOuterSpanIsCreatedUsingAsyncInvocation() {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/books/async/notrace"), spanId).get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    assertThat(REPORTER.getSpans().size(), equalTo(1));
    assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("GET /bookstore/books/async/notrace"));
}
 
Example #17
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatInnerSpanIsCreatedUsingPseudoAsyncInvocation() {
    final JaegerSpanContext spanId = fromRandom();

    final Response r = withTrace(createWebClient("/bookstore/books/pseudo-async"), spanId).get();
    assertEquals(Status.OK.getStatusCode(), r.getStatus());

    assertThat(REPORTER.getSpans().size(), equalTo(2));
    assertThat(REPORTER.getSpans().get(1).getOperationName(), equalTo("GET /bookstore/books/pseudo-async"));
    assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("Processing books"));
}
 
Example #18
Source File: JaegerTracerB3CustomizerCustomSpringTest.java    From java-spring-jaeger with Apache License 2.0 5 votes vote down vote up
private void assertOnB3Headers(JaegerSpanContext context) {
  // Note: This test ensures that B3 codec actually works
  // If it would not, values would never be extracted from B3 headers and context will be null
  assertThat(context).isNotNull();
  assertThat(context.getTraceId()).isEqualTo("abc");
  assertThat(context.getSpanId()).isEqualTo(3567L);
}
 
Example #19
Source File: MDCScopeManager.java    From Mastering-Distributed-Tracing with MIT License 5 votes vote down vote up
ScopeWrapper(Scope scope) {
    this.scope = scope;
    this.previousTraceId = lookup("trace_id");
    this.previousSpanId = lookup("span_id");
    this.previousSampled = lookup("trace_sampled");

    JaegerSpanContext ctx = (JaegerSpanContext) scope.span().context();
    String traceId = Long.toHexString(ctx.getTraceId());
    String spanId = Long.toHexString(ctx.getSpanId());
    String sampled = String.valueOf(ctx.isSampled());
    
    replace("trace_id", traceId);
    replace("span_id", spanId);
    replace("trace_sampled", sampled);
}
 
Example #20
Source File: JaegerTracerB3CustomizerCustomSpringTest.java    From java-spring-jaeger with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomizersTextMapShouldContainB3() {
  TextMap textMap = createTextMap();

  JaegerSpanContext context = (JaegerSpanContext) tracer.extract(Format.Builtin.TEXT_MAP, textMap);

  assertOnB3Headers(context);
}
 
Example #21
Source File: JaegerTracerB3CustomizerCustomSpringTest.java    From java-spring-jaeger with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomizersHttpHeadersShouldContainB3() {
  TextMap textMap = createTextMap();

  JaegerSpanContext context = (JaegerSpanContext) tracer.extract(Format.Builtin.HTTP_HEADERS, textMap);

  assertOnB3Headers(context);
}
 
Example #22
Source File: StringCodec.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public JaegerSpanContext extract(StringBuilder s) {
  if (s == null) {
    throw new EmptyTracerStateStringException();
  }
  String value = s.toString();
  if (!"".equals(value)) {
    String[] parts = value.split(":");
    if (parts.length != 4) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("MalformedTracerStateString: {}", value);
      }
      throw new MalformedTracerStateStringException(value);
    } else {
      String traceId = parts[0];
      if (traceId.length() <= 32 && traceId.length() >= 1) {
        return new JaegerSpanContext(high(traceId),
            (new BigInteger(traceId, 16)).longValue(),
            (new BigInteger(parts[1], 16)).longValue(),
            (new BigInteger(parts[2], 16)).longValue(),
            (new BigInteger(parts[3], 16)).byteValue());
      } else {
        throw new TraceIdOutOfBoundException(
            "Trace id [" + traceId + "] length is not within 1 and 32");
      }
    }
  } else {
    throw new EmptyTracerStateStringException();
  }
}
 
Example #23
Source File: JaegerPropagatorTest.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Test
public void extract_SampledContext() {
  Map<String, String> carrier = new LinkedHashMap<>();
  JaegerSpanContext context =
      new JaegerSpanContext(
          TRACE_ID_HI, TRACE_ID_LOW, SPAN_ID_LONG, DEPRECATED_PARENT_SPAN_LONG, (byte) 5);
  carrier.put(PROPAGATION_HEADER, TextMapCodec.contextAsString(context));

  assertThat(getSpanContext(jaegerPropagator.extract(Context.current(), carrier, getter)))
      .isEqualTo(
          SpanContext.createFromRemoteParent(
              TRACE_ID, SPAN_ID, SAMPLED_TRACE_OPTIONS, TRACE_STATE_DEFAULT));
}
 
Example #24
Source File: JaegerTraceFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 解析跟踪上下文
 *
 * @return 跟踪上下文
 */
protected JaegerSpanContext reject() {
    Map<String, Object> ctx = (Map<String, Object>) invocation.removeAttachment(HIDDEN_KEY_TRACE_JAEGER);
    return ctx == null ? null : new JaegerSpanContext(
            (Long) ctx.get(TRACE_ID_HIGH),
            (Long) ctx.get(TRACE_ID_LOW),
            (Long) ctx.get(SPAN_ID),
            (Long) ctx.get(PARENT_ID),
            (Byte) ctx.get(FLAGS));
}
 
Example #25
Source File: JaegerPropagatorTest.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Test
public void extract_NotSampledContext() {
  Map<String, String> carrier = new LinkedHashMap<>();
  JaegerSpanContext context =
      new JaegerSpanContext(
          TRACE_ID_HI, TRACE_ID_LOW, SPAN_ID_LONG, DEPRECATED_PARENT_SPAN_LONG, (byte) 0);
  carrier.put(PROPAGATION_HEADER, TextMapCodec.contextAsString(context));

  assertThat(getSpanContext(jaegerPropagator.extract(Context.current(), carrier, getter)))
      .isEqualTo(
          SpanContext.createFromRemoteParent(
              TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TRACE_STATE_DEFAULT));
}
 
Example #26
Source File: JaegerTraceFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 构建调用传递的上下文,返回Object,方便继承
 *
 * @param jsc 上下文
 * @return 传递的上下文
 */
protected Object build(JaegerSpanContext jsc) {
    Map<String, Object> ctx = new HashMap<>(5);
    ctx.put(TRACE_ID_HIGH, jsc.getTraceIdHigh());
    ctx.put(TRACE_ID_LOW, jsc.getTraceIdLow());
    ctx.put(SPAN_ID, jsc.getSpanId());
    ctx.put(PARENT_ID, jsc.getParentId());
    ctx.put(FLAGS, jsc.getFlags());
    return ctx;
}
 
Example #27
Source File: JaegerPropagatorTest.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Test
public void extract_UrlEncodedContext() throws UnsupportedEncodingException {
  Map<String, String> carrier = new LinkedHashMap<>();
  JaegerSpanContext context =
      new JaegerSpanContext(
          TRACE_ID_HI, TRACE_ID_LOW, SPAN_ID_LONG, DEPRECATED_PARENT_SPAN_LONG, (byte) 5);
  carrier.put(
      PROPAGATION_HEADER, URLEncoder.encode(TextMapCodec.contextAsString(context), "UTF-8"));

  assertThat(getSpanContext(jaegerPropagator.extract(Context.current(), carrier, getter)))
      .isEqualTo(
          SpanContext.createFromRemoteParent(
              TRACE_ID, SPAN_ID, SAMPLED_TRACE_OPTIONS, TRACE_STATE_DEFAULT));
}
 
Example #28
Source File: JaegerTraceFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public void begin(final String name, final String component, final Map<String, String> tags) {
    //拿到当前请求的跟踪span
    JaegerSpanContext parent = reject();
    //构建新span
    span = tracer.buildSpan(name).withStartTimestamp(SystemClock.microTime()).asChildOf(parent).start();
    //注入新的span
    inject(span.context());
    //标签
    tag(tags);
}
 
Example #29
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static JaegerSpanContext fromRandom() {
    return new JaegerSpanContext(RANDOM.getAndIncrement() /* traceId hi */,
        RANDOM.getAndIncrement() /* traceId lo */, RANDOM.getAndIncrement() /* spanId */,
        RANDOM.getAndIncrement() /* parentId */, (byte) 1 /* sampled */);
}
 
Example #30
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static JaegerSpanContext fromRandom() {
    return new JaegerSpanContext(RANDOM.getAndIncrement() /* traceId hi */,
        RANDOM.getAndIncrement() /* traceId lo */, RANDOM.getAndIncrement() /* spanId */,
        RANDOM.getAndIncrement() /* parentId */, (byte) 1 /* sampled */);
}