brave.propagation.B3SingleFormat Java Examples

The following examples show how to use brave.propagation.B3SingleFormat. 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: BasicUsageTest.java    From zipkin-reporter-java with Apache License 2.0 6 votes vote down vote up
/** This mainly shows endpoints are taken from Brave, and error is back-filled. */
@Test public void basicSpan() {
  TraceContext context = B3SingleFormat.parseB3SingleFormat(
      "50d980fffa300f29-86154a4ba6e91385-1"
  ).context();

  tracing.tracer().toSpan(context).name("test")
      .start(1L)
      .error(new RuntimeException("this cake is a lie"))
      .finish(3L);

  triggerReport();

  assertThat(spans.get(0)).hasToString(
      "{\"traceId\":\"50d980fffa300f29\","
          + "\"id\":\"86154a4ba6e91385\","
          + "\"name\":\"test\","
          + "\"timestamp\":1,"
          + "\"duration\":2,"
          + "\"localEndpoint\":{"
          + "\"serviceName\":\"aa\","
          + "\"ipv4\":\"1.2.3.4\","
          + "\"port\":80},"
          + "\"tags\":{\"error\":\"this cake is a lie\"}}"
  );
}
 
Example #2
Source File: MutableSpanAsyncReporterTest.java    From brave with Apache License 2.0 6 votes vote down vote up
/** This mainly shows endpoints are taken from Brave, and error is back-filled. */
@Test public void basicSpan() {
  TraceContext context = B3SingleFormat.parseB3SingleFormat(
      "50d980fffa300f29-86154a4ba6e91385-1"
  ).context();

  tracing.tracer().toSpan(context).name("test")
      .start(1L)
      .error(new RuntimeException("this cake is a lie"))
      .finish(3L);

  reporter.flush();

  assertThat(zipkin.getTraces()).hasSize(1).first().hasToString(
      "[{\"traceId\":\"50d980fffa300f29\","
          + "\"id\":\"86154a4ba6e91385\","
          + "\"name\":\"test\","
          + "\"timestamp\":1,"
          + "\"duration\":2,"
          + "\"localEndpoint\":{"
          + "\"serviceName\":\"aa\","
          + "\"ipv4\":\"1.2.3.4\","
          + "\"port\":80},"
          + "\"tags\":{\"error\":\"this cake is a lie\"}}]"
  );
}
 
Example #3
Source File: ITHttpServer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void createsChildWhenJoinDisabled() throws IOException {
  tracing = tracingBuilder(NEVER_SAMPLE).supportsJoin(false).build();
  httpTracing = HttpTracing.create(tracing);
  init();

  String path = "/foo";

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  get(new Request.Builder().url(url(path))
    .header("b3", B3SingleFormat.writeB3SingleFormat(parent))
    .build());

  MutableSpan span = testSpanHandler.takeRemoteSpan(SERVER);
  assertChildOf(span, parent);
  assertThat(span.id()).isNotEqualTo(parent.spanIdString());
}
 
Example #4
Source File: ITTracingFilter_Provider.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void reusesPropagatedSpanId() {
  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);

  RpcContext.getContext().getAttachments().put("b3", B3SingleFormat.writeB3SingleFormat(parent));
  client.get().sayHello("jorge");

  assertSameIds(testSpanHandler.takeRemoteSpan(SERVER), parent);
}
 
Example #5
Source File: TracingMessagePostProcessorTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void should_prefer_current_span() {
  // Will be either a bug, or a missing processor stage which can result in an old span in headers
  Message message = MessageBuilder.withBody(new byte[0]).build();
  message.getMessageProperties().setHeader("b3", B3SingleFormat.writeB3SingleFormat(grandparent));

  Message postProcessMessage;
  try (Scope scope = tracing.currentTraceContext().newScope(parent)) {
    postProcessMessage = tracingMessagePostProcessor.postProcessMessage(message);
  }

  assertThat(spans.get(0).parentId()).isEqualTo(parent.spanIdString());
  Map<String, Object> headers = postProcessMessage.getMessageProperties().getHeaders();
  assertThat(headers.get("b3").toString()).endsWith("-" + spans.get(0).id() + "-1");
}
 
Example #6
Source File: TracingMessagePostProcessorTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void should_retain_baggage() {
  Message message = MessageBuilder.withBody(new byte[0]).build();
  message.getMessageProperties().setHeader("b3", B3SingleFormat.writeB3SingleFormat(parent));
  message.getMessageProperties().setHeader(BAGGAGE_FIELD_KEY, "");

  Message postProcessMessage = tracingMessagePostProcessor.postProcessMessage(message);

  assertThat(spans.get(0).parentId()).isEqualTo(parent.spanIdString());
  Map<String, Object> headers = postProcessMessage.getMessageProperties().getHeaders();
  assertThat(headers.get("b3").toString()).endsWith("-" + spans.get(0).id() + "-1");
  assertThat(headers.get(BAGGAGE_FIELD_KEY).toString()).isEmpty();
}
 
Example #7
Source File: TracingMessagePostProcessorTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void should_resume_headers() {
  Message message = MessageBuilder.withBody(new byte[0]).build();
  message.getMessageProperties().setHeader("b3", B3SingleFormat.writeB3SingleFormat(parent));

  Message postProcessMessage = tracingMessagePostProcessor.postProcessMessage(message);

  assertThat(spans.get(0).parentId()).isEqualTo(parent.spanIdString());
  Map<String, Object> headers = postProcessMessage.getMessageProperties().getHeaders();
  assertThat(headers.get("b3").toString()).endsWith("-" + spans.get(0).id() + "-1");
}
 
Example #8
Source File: BaseITTracingServerInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
Channel clientWithB3SingleHeader(TraceContext parent) {
  return ClientInterceptors.intercept(client, new ClientInterceptor() {
    @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
      return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
        @Override public void start(Listener<RespT> responseListener, Metadata headers) {
          headers.put(Key.of("b3", ASCII_STRING_MARSHALLER),
              B3SingleFormat.writeB3SingleFormat(parent));
          super.start(responseListener, headers);
        }
      };
    }
  });
}
 
Example #9
Source File: KafkaTracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void nextSpan_prefers_b3_header() {
  consumerRecord.headers().add("b3", B3SingleFormat.writeB3SingleFormatAsBytes(incoming));

  Span child;
  try (Scope ws = tracing.currentTraceContext().newScope(parent)) {
    child = kafkaTracing.nextSpan(consumerRecord);
  }
  child.finish();

  assertThat(spans.get(0).id()).isEqualTo(child.context().spanIdString());
  assertChildOf(spans.get(0), incoming);
}
 
Example #10
Source File: ITJms_1_1_TracingMessageConsumer.java    From brave with Apache License 2.0 5 votes vote down vote up
TraceContext resetB3PropertyWithNewSampledContext(JmsTestRule jms) throws JMSException {
  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  message = jms.newMessage("foo");
  bytesMessage = jms.newBytesMessage("foo");
  String b3 = B3SingleFormat.writeB3SingleFormatWithoutParentId(parent);
  setStringProperty(message, "b3", b3);
  setStringProperty(bytesMessage, "b3", b3);
  lockMessages();
  return parent;
}
 
Example #11
Source File: TracingJMSConsumerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void receive_continues_parent_trace_single_header() throws Exception {
  ActiveMQTextMessage message = new ActiveMQTextMessage();
  message.setStringProperty("b3", B3SingleFormat.writeB3SingleFormatWithoutParentId(parent));

  receive(message);

  // Ensure the current span in on the message, not the parent
  MutableSpan consumer = testSpanHandler.takeRemoteSpan(CONSUMER);
  assertChildOf(consumer, parent);

  TraceContext messageContext = parseB3SingleFormat(message.getStringProperty("b3")).context();
  assertThat(messageContext.traceIdString()).isEqualTo(consumer.traceId());
  assertThat(messageContext.spanIdString()).isEqualTo(consumer.id());
}
 
Example #12
Source File: TracingMessageListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void listener_continues_parent_trace_single_header() {
  tracingMessageListener =
    new TracingMessageListener(delegate, jmsTracing, false);

  ActiveMQTextMessage message = new ActiveMQTextMessage();
  setStringProperty(message, "b3", B3SingleFormat.writeB3SingleFormatWithoutParentId(parent));

  onMessageConsumed(message);

  // clearing headers ensures later work doesn't try to use the old parent
  assertNoProperties(message);

  assertChildOf(testSpanHandler.takeLocalSpan(), parent);
}
 
Example #13
Source File: TracingMessageListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void continues_parent_trace_single_header() {
  ActiveMQTextMessage message = new ActiveMQTextMessage();
  setStringProperty(message, "b3", B3SingleFormat.writeB3SingleFormatWithoutParentId(parent));

  onMessageConsumed(message);

  // clearing headers ensures later work doesn't try to use the old parent
  assertNoProperties(message);

  MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
  MutableSpan listenerSpan = testSpanHandler.takeLocalSpan();

  assertChildOf(consumerSpan, parent);
  assertChildOf(listenerSpan, consumerSpan);
}
 
Example #14
Source File: TracingMessageListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void listener_has_no_tags_when_header_present() {
  tracingMessageListener =
    new TracingMessageListener(delegate, jmsTracing, false);

  ActiveMQTextMessage message = new ActiveMQTextMessage();
  setStringProperty(message, "b3", B3SingleFormat.writeB3SingleFormatWithoutParentId(parent));
  message.setDestination(createDestination("foo", QUEUE_TYPE));
  onMessageConsumed(message);

  assertThat(testSpanHandler.takeLocalSpan().tags()).isEmpty();
}
 
Example #15
Source File: JmsTracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void nextSpan_prefers_b3_header() {
  TraceContext incoming = newTraceContext(SamplingFlags.NOT_SAMPLED);
  setStringProperty(message, "b3", B3SingleFormat.writeB3SingleFormat(incoming));

  Span child;
  try (Scope ws = tracing.currentTraceContext().newScope(parent)) {
    child = jmsTracing.nextSpan(message);
  }
  assertChildOf(child.context(), incoming);
  assertThat(child.isNoop()).isTrue();
}
 
Example #16
Source File: ITHttpServer.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void reusesPropagatedSpanId() throws IOException {
  String path = "/foo";

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  get(new Request.Builder().url(url(path))
    .header("b3", B3SingleFormat.writeB3SingleFormat(parent))
    .build());

  assertSameIds(testSpanHandler.takeRemoteSpan(SERVER), parent);
}
 
Example #17
Source File: ITTracingFilter_Provider.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void createsChildWhenJoinDisabled() {
  tracing = tracingBuilder(NEVER_SAMPLE).supportsJoin(false).build();
  init();

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);

  RpcContext.getContext().getAttachments().put("b3", B3SingleFormat.writeB3SingleFormat(parent));
  client.get().sayHello("jorge");

  MutableSpan span = testSpanHandler.takeRemoteSpan(SERVER);
  assertChildOf(span, parent);
  assertThat(span.id()).isNotEqualTo(parent.spanIdString());
}
 
Example #18
Source File: BraveTracer.java    From brave-opentracing with Apache License 2.0 5 votes vote down vote up
@Override public TraceContextOrSamplingFlags extract(BinaryExtract binaryExtract) {
  try {
    return B3SingleFormat.parseB3SingleFormat(ascii.decode(binaryExtract.extractionBuffer()));
  } catch (RuntimeException e) {
    return TraceContextOrSamplingFlags.EMPTY;
  }
}
 
Example #19
Source File: ITTracingFilter_Provider.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void createsChildWhenJoinDisabled() {
  tracing = tracingBuilder(NEVER_SAMPLE).supportsJoin(false).build();
  init();

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);

  RpcContext.getContext().getAttachments().put("b3", B3SingleFormat.writeB3SingleFormat(parent));
  client.get().sayHello("jorge");

  assertChildOf(testSpanHandler.takeRemoteSpan(SERVER), parent);
}
 
Example #20
Source File: ITTracingFilter_Provider.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void reusesPropagatedSpanId() {
  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);

  RpcContext.getContext().getAttachments().put("b3", B3SingleFormat.writeB3SingleFormat(parent));
  client.get().sayHello("jorge");

  assertSameIds(testSpanHandler.takeRemoteSpan(SERVER), parent);
}
 
Example #21
Source File: BaggagePropagationTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void inject_field_multiple_key_names() {
  BaggageField userId = BaggageField.create("userId");
  BaggageField sessionId = BaggageField.create("sessionId");

  SingleBaggageField userIdConfig = SingleBaggageField.newBuilder(userId)
    .addKeyName("userId")
    .addKeyName("baggage-userId")
    .addKeyName("baggage_userId")
    .build();

  SingleBaggageField sessionIdConfig = SingleBaggageField.newBuilder(sessionId)
    .addKeyName("sessionId")
    .addKeyName("baggage-sessionId")
    .addKeyName("baggage_sessionId")
    .build();

  factory = newFactoryBuilder(B3SinglePropagation.FACTORY)
    .add(userIdConfig)
    .add(sessionIdConfig)
    .build();
  initialize();

  userId.updateValue(context, "bob");
  sessionId.updateValue(context, "12345");

  injector.inject(context, request);

  // NOTE: the labels are downcased
  assertThat(request).containsOnly(
    entry("b3", B3SingleFormat.writeB3SingleFormat(context)),
    entry("userid", "bob"),
    entry("sessionid", "12345"),
    entry("baggage-userid", "bob"),
    entry("baggage-sessionid", "12345"),
    entry("baggage_userid", "bob"),
    entry("baggage_sessionid", "12345")
  );
}
 
Example #22
Source File: TraceContextPropagationChannelInterceptorTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private void assertThatNewSpanIdWasSetOnMessage(String expectedSpanId) {
	Message<?> message = this.channel.receive(0);
	assertThat(message).as("message was null").isNotNull();

	String b3 = message.getHeaders().get("b3", String.class);
	// Trace and Span IDs are implicitly checked
	TraceContext extracted = B3SingleFormat.parseB3SingleFormat(b3).context();

	assertThat(extracted.spanIdString()).as("spanId was equal to parent's id")
			.isNotEqualTo(expectedSpanId);
}
 
Example #23
Source File: TraceStreamChannelInterceptorTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private void assertThatNewSpanIdWasSetOnMessage(String expectedSpanId) {
	Message<?> message = this.channel.receive(0);
	assertThat(message).as("message was null").isNotNull();

	String b3 = message.getHeaders().get("b3", String.class);
	// Trace and Span IDs are implicitly checked
	TraceContext extracted = B3SingleFormat.parseB3SingleFormat(b3).context();

	assertThat(extracted.spanIdString()).as("spanId was equal to parent's id")
			.isNotEqualTo(expectedSpanId);
}
 
Example #24
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/traceid", method = RequestMethod.GET)
public String traceId(@RequestHeader("b3") String b3Single) {
	TraceContextOrSamplingFlags traceContext = B3SingleFormat
			.parseB3SingleFormat(b3Single);
	then(traceContext.context()).isNotNull();
	return b3Single;
}
 
Example #25
Source File: BasicUsageTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
/** This shows that in practice, we don't report when the user tells us not to! */
@Test public void abandonedSpan() {
  TraceContext context = B3SingleFormat.parseB3SingleFormat(
      "50d980fffa300f29-86154a4ba6e91385-1"
  ).context();

  tracing.tracer().toSpan(context).name("test")
      .start(1L)
      .abandon(); // whoops.. don't need this one!

  triggerReport();

  assertThat(spans).isEmpty();
}
 
Example #26
Source File: SkeletalSpansTest.java    From brave with Apache License 2.0 4 votes vote down vote up
/** To reduce code, we don't use real client-server instrumentation. This fakes headers. */
static TraceContext fakeUseOfHeaders(TraceContext context) {
  return B3SingleFormat.parseB3SingleFormat(B3SingleFormat.writeB3SingleFormat(context))
    .context();
}
 
Example #27
Source File: B3SingleFormatClassLoaderTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public void run() {
  String expected = "1234567812345678-1234567812345678-1";
  String written =
    B3SingleFormat.writeB3SingleFormat(B3SingleFormat.parseB3SingleFormat(expected).context());
  if (!written.equals(expected)) throw new AssertionError();
}
 
Example #28
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/noresponse")
public void noResponse(@RequestHeader("b3") String b3Single) {
	TraceContextOrSamplingFlags traceContext = B3SingleFormat
			.parseB3SingleFormat(b3Single);
	then(traceContext.context()).isNotNull();
}
 
Example #29
Source File: BraveTracer.java    From brave-opentracing with Apache License 2.0 4 votes vote down vote up
@Override public void inject(TraceContext traceContext, BinaryInject binaryInject) {
  byte[] injected = B3SingleFormat.writeB3SingleFormatAsBytes(traceContext);
  binaryInject.injectionBuffer(injected.length).put(injected);
}