brave.handler.MutableSpan Java Examples

The following examples show how to use brave.handler.MutableSpan. 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: SpanMetricsCustomizer.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
  if (cause != Cause.FINISHED) return true;

  Tag nameTag = nameToTag.get(span.name());
  if (nameTag == null) return true; // no tag

  // Example of adding a correlated tag. Note that in spans, we don't add a negative one (None)
  Tag errorTag = exception(span.error());
  if (errorTag != EXCEPTION_NONE) {
    span.tag("exception", errorTag.getValue());
  }

  // Look or create up a timer that records duration against
  registry.timer(metricName, Arrays.asList(nameTag, errorTag))
    // Timestamps are derived from a function of clock time and nanos offset
    .record(span.finishTimestamp() - span.startTimestamp(), TimeUnit.MICROSECONDS);
  return true;
}
 
Example #2
Source File: TracingFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void localEndpoint() {
  context = new XmlBeans(""
    + "<bean id=\"localEndpoint\" class=\"brave.spring.beans.EndpointFactoryBean\">\n"
    + "  <property name=\"serviceName\" value=\"brave-webmvc-example\"/>\n"
    + "  <property name=\"ip\" value=\"1.2.3.4\"/>\n"
    + "  <property name=\"port\" value=\"8080\"/>\n"
    + "</bean>"
    , ""
    + "<bean id=\"tracing\" class=\"brave.spring.beans.TracingFactoryBean\">\n"
    + "  <property name=\"localEndpoint\" ref=\"localEndpoint\"/>\n"
    + "</bean>"
  );

  MutableSpan defaultSpan = new MutableSpan();
  defaultSpan.localServiceName("brave-webmvc-example");
  defaultSpan.localIp("1.2.3.4");
  defaultSpan.localPort(8080);

  assertThat(context.getBean("tracing", Tracing.class))
    .extracting("tracer.pendingSpans.defaultSpan")
    .isEqualTo(defaultSpan);
}
 
Example #3
Source File: ITJms_1_1_TracingMessageConsumer.java    From brave with Apache License 2.0 6 votes vote down vote up
void messageListener_startsNewTrace(JMSRunnable send, MessageConsumer messageConsumer,
  Map<String, String> consumerTags) throws JMSException {
  messageConsumer.setMessageListener(
    m -> {
      tracing.tracer().currentSpanCustomizer().name("message-listener");

      // clearing headers ensures later work doesn't try to use the old parent
      String b3 = getPropertyIfString(m, "b3");
      tracing.tracer().currentSpanCustomizer().tag("b3", String.valueOf(b3 != null));
    }
  );
  send.run();

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

  assertThat(consumerSpan.name()).isEqualTo("receive");
  assertThat(consumerSpan.parentId()).isNull(); // root span
  assertThat(consumerSpan.tags()).containsAllEntriesOf(consumerTags);

  assertChildOf(listenerSpan, consumerSpan);
  assertThat(listenerSpan.name()).isEqualTo("message-listener"); // overridden name
  assertThat(listenerSpan.tags())
    .hasSize(1) // no redundant copy of consumer tags
    .containsEntry("b3", "false"); // b3 header not leaked to listener
}
 
Example #4
Source File: ITHttpClient.java    From brave with Apache License 2.0 6 votes vote down vote up
/** This prevents confusion as a blocking client should end before, the start of the next span. */
@Test public void clientTimestampAndDurationEnclosedByParent() throws IOException {
  server.enqueue(new MockResponse());

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  Clock clock = tracing.clock(parent);

  long start = clock.currentTimeMicroseconds();
  try (Scope scope = currentTraceContext.newScope(parent)) {
    get(client, "/foo");
  }
  long finish = clock.currentTimeMicroseconds();

  MutableSpan clientSpan = testSpanHandler.takeRemoteSpan(CLIENT);
  assertChildOf(clientSpan, parent);
  assertSpanInInterval(clientSpan, start, finish);
}
 
Example #5
Source File: ConvertingSpanReporterTest.java    From zipkin-reporter-java with Apache License 2.0 6 votes vote down vote up
@Test public void remoteEndpoint() {
  MutableSpan span = new MutableSpan(context, null);

  Endpoint endpoint = Endpoint.newBuilder()
      .serviceName("fooService")
      .ip("1.2.3.4")
      .port(80)
      .build();

  span.kind(CLIENT);
  span.remoteServiceName(endpoint.serviceName());
  span.remoteIpAndPort(endpoint.ipv4(), endpoint.port());
  span.startTimestamp(1L);
  span.finishTimestamp(2L);

  spanReporter.report(span);

  assertThat(spans.get(0).remoteEndpoint())
      .isEqualTo(endpoint);
}
 
Example #6
Source File: TracerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
/**
 * Data from loopback requests should be partitioned into two spans: one for the client and the
 * other for the server.
 */
@Test public void join_sharedDataIsSeparate() {
  Span clientSide = tracer.newTrace().kind(CLIENT).start(1L);
  Span serverSide = tracer.joinSpan(clientSide.context()).kind(SERVER).start(2L);
  serverSide.finish(3L);
  clientSide.finish(4L);

  // Ensure they use the same span ID (sanity check)
  String spanId = spans.get(0).id();
  assertThat(spans).extracting(MutableSpan::id)
    .containsExactly(spanId, spanId);

  // Ensure the important parts are separated correctly
  assertThat(spans).extracting(
    MutableSpan::kind, MutableSpan::shared, MutableSpan::startTimestamp, MutableSpan::finishTimestamp
  ).containsExactly(
    tuple(SERVER, true, 2L, 3L),
    tuple(CLIENT, false, 1L, 4L)
  );
}
 
Example #7
Source File: ITHttpClient.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws IOException {
  server.enqueue(new MockResponse().setResponseCode(302)
    .addHeader("Location: " + url("/bar")));
  server.enqueue(new MockResponse().setResponseCode(404)); // hehe to a bad location!

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
  try (Scope scope = currentTraceContext.newScope(parent)) {
    get(client, "/foo");
  } catch (RuntimeException e) {
    // some clients raise 404 as an exception such as HttpClientError
  }

  MutableSpan initial = testSpanHandler.takeRemoteSpan(CLIENT);
  MutableSpan redirected = testSpanHandler.takeRemoteSpanWithErrorTag(CLIENT, "404");

  for (MutableSpan child : Arrays.asList(initial, redirected)) {
    assertChildOf(child, parent);
  }

  assertSequential(initial, redirected);

  assertThat(initial.tags().get("http.path")).isEqualTo("/foo");
  assertThat(redirected.tags().get("http.path")).isEqualTo("/bar");
}
 
Example #8
Source File: TracingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void spanHandler_dataChangesVisibleToZipkin() {
  String serviceNameOverride = "favistar";

  SpanHandler spanHandler = new SpanHandler() {
    @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
      span.localServiceName(serviceNameOverride);
      return true;
    }
  };

  List<zipkin2.Span> zipkinSpans = new ArrayList<>();
  try (Tracing tracing = Tracing.newBuilder()
    .spanReporter(zipkinSpans::add)
    .addSpanHandler(spanHandler)
    .build()) {
    tracing.tracer().newTrace().start().finish();
  }

  assertThat(zipkinSpans.get(0).localServiceName()).isEqualTo(serviceNameOverride);
}
 
Example #9
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("parametersForShouldCreateANewSpanWithClientSideTagsWhenNoPreviousTracingWasPresent")
@SuppressWarnings("unchecked")
public void shouldCreateANewSpanWithClientSideTagsWhenNoPreviousTracingWasPresent(
		ResponseEntityProvider provider) {
	ResponseEntity<String> response = provider.get(this);

	Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> {
		then(getHeader(response, "b3")).isNull();
		then(this.spans).isNotEmpty();
		Optional<MutableSpan> noTraceSpan = this.spans.spans().stream()
				.filter(span -> "GET".equals(span.name()) && !span.tags().isEmpty()
						&& span.tags().containsKey("http.path"))
				.findFirst();
		then(noTraceSpan.isPresent()).isTrue();
		then(noTraceSpan.get().tags()).containsEntry("http.path", "/notrace")
				.containsEntry("http.method", "GET");
		// TODO: matches cause there is an issue with Feign not providing the full URL
		// at the interceptor level
		then(noTraceSpan.get().tags().get("http.path")).matches(".*/notrace");
	});
	then(this.tracer.currentSpan()).isNull();
}
 
Example #10
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCloseSpanWhenErrorControllerGetsCalled() {
	try {
		this.template.getForEntity("http://fooservice/nonExistent", String.class);
		fail("An exception should be thrown");
	}
	catch (HttpClientErrorException e) {
	}

	then(this.tracer.currentSpan()).isNull();
	Optional<MutableSpan> storedSpan = this.spans.spans().stream()
			.filter(span -> "404".equals(span.tags().get("http.status_code")))
			.findFirst();
	then(storedSpan.isPresent()).isTrue();
	this.spans.spans().stream().forEach(span -> {
		int initialSize = span.annotations().size();
		int distinctSize = span.annotations().stream().map(Map.Entry::getValue)
				.distinct().collect(Collectors.toList()).size();
		log.info("logs " + span.annotations());
		then(initialSize).as("there are no duplicate log entries")
				.isEqualTo(distinctSize);
	});

	then(this.spans).isNotEmpty().extracting("kind.name").contains("CLIENT");
}
 
Example #11
Source File: ReactorNettyHttpClientSpringBootTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUseInvocationContext() throws Exception {
	disposableServer = HttpServer.create().port(0)
			// this reads the trace context header, b3, returning it in the response
			.handle((in, out) -> out
					.sendString(Flux.just(in.requestHeaders().get("b3"))))
			.bindNow();

	String b3SingleHeaderReadByServer;
	try (Scope ws = currentTraceContext.newScope(context)) {
		b3SingleHeaderReadByServer = httpClient.port(disposableServer.port()).get()
				.uri("/").responseContent().aggregate().asString().block();
	}

	MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);

	assertThat(b3SingleHeaderReadByServer).isEqualTo(context.traceIdString() + "-"
			+ clientSpan.id() + "-1-" + context.spanIdString());
}
 
Example #12
Source File: TraceRestTemplateInterceptorIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void spanRemovedFromThreadUponException() throws IOException {
	this.mockWebServer.enqueue(
			new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
	Span span = this.tracer.nextSpan().name("new trace");

	try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
		this.template.getForEntity(
				"http://localhost:" + this.mockWebServer.getPort() + "/exception",
				Map.class).getBody();
		fail("should throw an exception");
	}
	catch (RuntimeException e) {
		BDDAssertions.then(e).hasRootCauseInstanceOf(IOException.class);
	}
	finally {
		span.finish();
	}

	// 1 span "new race", 1 span "rest template"
	BDDAssertions.then(this.spans).hasSize(2);
	MutableSpan span1 = this.spans.get(0);
	BDDAssertions.then(span1.error()).hasMessage("Read timed out");
	BDDAssertions.then(span1.kind()).isEqualTo(Span.Kind.CLIENT);
}
 
Example #13
Source File: ZipkinJsonV2JsonWriterTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void missingFields_testCases() {
  jsonWriter.write(MutableSpanTest.PERMUTATIONS.get(0).get(), buffer);
  assertThat(buffer.toString()).isEqualTo("{}");

  // check for simple bugs
  for (int i = 1, length = MutableSpanTest.PERMUTATIONS.size(); i < length; i++) {
    buffer.pos = 0;

    MutableSpan span = MutableSpanTest.PERMUTATIONS.get(i).get();
    jsonWriter.write(span, buffer);

    assertThat(buffer.toString())
        .doesNotContain("null")
        .doesNotContain(":0");
  }
}
 
Example #14
Source File: TracingJobListenerTest.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_have_parent_and_child_span_when_trigger_job_data_was_created_with_differently_typed_map()
		throws Exception {
	// given
	JobDataMap data = new JobDataMap(new HashMap<Integer, Integer>());
	addSpanToJobData(data);
	Trigger trigger = newTrigger().forJob(SUCCESSFUL_JOB_KEY).usingJobData(data)
			.startNow().build();

	// when
	runJob(trigger);

	// expect
	MutableSpan parent = spanHandler.takeLocalSpan();
	MutableSpan child = spanHandler.takeLocalSpan();
	assertThat(parent.parentId()).isNull();
	assertThat(child.parentId()).isEqualTo(parent.id());
}
 
Example #15
Source File: ITJms_1_1_TracingMessageConsumer.java    From brave with Apache License 2.0 6 votes vote down vote up
void messageListener_readsBaggage(JMSRunnable send, MessageConsumer messageConsumer)
    throws JMSException {
  messageConsumer.setMessageListener(m ->
      Tags.BAGGAGE_FIELD.tag(BAGGAGE_FIELD, tracing.tracer().currentSpan())
  );

  message = jms.newMessage("baggage");
  bytesMessage = jms.newBytesMessage("baggage");
  String baggage = "joey";
  setStringProperty(message, BAGGAGE_FIELD_KEY, baggage);
  setStringProperty(bytesMessage, BAGGAGE_FIELD_KEY, baggage);
  lockMessages();
  send.run();

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

  assertThat(consumerSpan.parentId()).isNull();
  assertChildOf(listenerSpan, consumerSpan);
  assertThat(listenerSpan.tags())
      .containsEntry(BAGGAGE_FIELD.name(), baggage);
}
 
Example #16
Source File: CircuitBreakerIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_pass_tracing_information_when_using_circuit_breaker_with_fallback() {
	// given
	Tracer tracer = this.tracer;
	AtomicReference<Span> first = new AtomicReference<>();
	AtomicReference<Span> second = new AtomicReference<>();
	ScopedSpan scopedSpan = null;
	try {
		scopedSpan = tracer.startScopedSpan("start");
		// when
		BDDAssertions.thenThrownBy(() -> this.factory.create("name").run(() -> {
			first.set(tracer.currentSpan());
			throw new IllegalStateException("boom");
		}, throwable -> {
			second.set(tracer.currentSpan());
			throw new IllegalStateException("boom2");
		})).isInstanceOf(IllegalStateException.class).hasMessageContaining("boom2");

		then(this.spans).hasSize(2);
		then(scopedSpan.context().traceIdString())
				.isEqualTo(first.get().context().traceIdString());
		then(scopedSpan.context().traceIdString())
				.isEqualTo(second.get().context().traceIdString());
		then(first.get().context().spanIdString())
				.isNotEqualTo(second.get().context().spanIdString());

		MutableSpan reportedSpan = this.spans.get(0);
		then(reportedSpan.name()).contains("CircuitBreakerIntegrationTests");
		then(reportedSpan.tags().get("error")).contains("boom");

		reportedSpan = this.spans.get(1);
		then(reportedSpan.name()).contains("CircuitBreakerIntegrationTests");
		then(reportedSpan.tags().get("error")).contains("boom2");
	}
	finally {
		scopedSpan.finish();
	}
}
 
Example #17
Source File: FlatMapTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private String flatMapTraceId(TestSpanHandler spans, ClientResponse response) {
	then(response.statusCode().value()).isEqualTo(200);
	then(spans).isNotEmpty();
	LOGGER.info("Accumulated spans: " + spans);
	List<String> traceIdOfFlatMap = spans.spans().stream()
			.filter(span -> span.tags().containsKey("http.path")
					&& span.tags().get("http.path").equals("/withFlatMap"))
			.map(MutableSpan::traceId).collect(Collectors.toList());
	then(traceIdOfFlatMap).hasSize(1);
	return traceIdOfFlatMap.get(0);
}
 
Example #18
Source File: TracingRabbitListenerAdviceTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void reports_span_if_consume_fails_with_no_message() throws Throwable {
  Message message = MessageBuilder.withBody(new byte[0]).build();
  RuntimeException error = new RuntimeException("Test exception");
  onMessageConsumeFailed(message, error);

  assertThat(spans)
    .extracting(MutableSpan::kind)
    .containsExactly(CONSUMER, null);

  assertThat(spans)
    .filteredOn(span -> span.kind() == null)
    .extracting(MutableSpan::error)
    .containsExactly(error);
}
 
Example #19
Source File: SkeletalSpansTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
  if (span.kind() == null) return false; // skip local spans

  if (!context.isLocalRoot()) {
    span.parentId(context.localRootIdString()); // rewrite the parent ID
  }
  span.forEachAnnotation((timestamp, value) -> null); // drop all annotations
  span.forEachTag((key, value) -> {
    if (key.equals("error")) return ""; // linking counts errors: the value isn't important
    return null;
  });
  span.remoteIp(null); // retain only the service name
  span.remotePort(0);
  return true;
}
 
Example #20
Source File: SleuthSpanCreatorAspectMonoTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNewSpanFromSubscriberContextOuter() {
	Mono<Pair<Pair<String, String>, String>> mono = this.testBeanOuter
			.outerNewSpanInSubscriberContext();

	then(this.spans).isEmpty();

	Pair<Pair<String, String>, String> pair = mono.block();
	String outerSpanIdBefore = pair.getFirst().getFirst();
	String innerSpanId = pair.getSecond();

	then(outerSpanIdBefore).isNotEqualTo(innerSpanId);

	Awaitility.await().untilAsserted(() -> {
		MutableSpan outerSpan = spans.spans().stream().filter(
				span -> span.name().equals("outer-span-in-subscriber-context"))
				.findFirst().orElseThrow(() -> new AssertionError(
						"No span with name [outer-span-in-subscriber-context] found"));
		then(outerSpan.name()).isEqualTo("outer-span-in-subscriber-context");
		then(outerSpan.id()).isEqualTo(outerSpanIdBefore);
		MutableSpan innerSpan = spans.spans().stream()
				.filter(span -> span.name().equals("span-in-subscriber-context"))
				.findFirst().orElseThrow(() -> new AssertionError(
						"No span with name [span-in-subscriber-context] found"));
		then(innerSpan.name()).isEqualTo("span-in-subscriber-context");
		then(innerSpan.id()).isEqualTo(innerSpanId);
		then(this.tracer.currentSpan()).isNull();
	});
}
 
Example #21
Source File: BraveIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testTimingAnnotations() {
    // Use separate client factory to make sure connection is created.
    final ClientFactory clientFactory = ClientFactory.builder().build();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .decorator(BraveClient.newDecorator(newTracing("timed-client")))
                                      .build();
    assertThat(client.get("/http").aggregate().join().status()).isEqualTo(HttpStatus.OK);
    final MutableSpan[] initialConnectSpans = spanHandler.take(1);
    assertThat(initialConnectSpans[0].annotations())
            .extracting(Map.Entry::getValue).containsExactlyInAnyOrder(
            "connection-acquire.start",
            "socket-connect.start",
            "socket-connect.end",
            "connection-acquire.end",
            "ws",
            "wr");

    // Make another request which will reuse the connection so no connection timing.
    assertThat(client.get("/http").aggregate().join().status()).isEqualTo(HttpStatus.OK);

    final MutableSpan[] secondConnectSpans = spanHandler.take(1);
    assertThat(secondConnectSpans[0].annotations())
            .extracting(Map.Entry::getValue).containsExactlyInAnyOrder(
            "ws",
            "wr");
}
 
Example #22
Source File: TracingProducerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void should_add_b3_headers_when_other_headers_exist() {
  ProducerRecord<Object, String> record = new ProducerRecord<>(TEST_TOPIC, TEST_KEY, TEST_VALUE);
  record.headers().add("tx-id", "1".getBytes());
  tracingProducer.send(record);
  mockProducer.completeNext();

  MutableSpan producerSpan = spans.get(0);
  assertThat(producerSpan.kind()).isEqualTo(PRODUCER);
  assertThat(lastHeaders(mockProducer))
    .containsEntry("tx-id", "1")
    .containsEntry("b3", producerSpan.traceId() + "-" + producerSpan.id() + "-1");
}
 
Example #23
Source File: PendingSpansClassLoaderTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void run() {
  PendingSpans pendingSpans = new PendingSpans(new MutableSpan(),
    Platform.get().clock(), SpanHandler.NOOP, new AtomicBoolean());

  TraceContext context = CONTEXT.toBuilder().build(); // intentionally make a copy
  pendingSpans.getOrCreate(null, context, true);
  pendingSpans.remove(context);
}
 
Example #24
Source File: ITSpringRabbitTracing.java    From brave with Apache License 2.0 5 votes vote down vote up
/** Technical implementation of clock sharing might imply a race. This ensures happens-after */
@Test public void listenerSpanHappensAfterConsumerSpan() {
  produceMessage();
  awaitMessageConsumed();

  MutableSpan producerSpan = producerSpanHandler.takeRemoteSpan(PRODUCER);
  MutableSpan consumerSpan = consumerSpanHandler.takeRemoteSpan(CONSUMER);
  assertSequential(producerSpan, consumerSpan);
  MutableSpan listenerSpan = consumerSpanHandler.takeLocalSpan();
  assertSequential(consumerSpan, listenerSpan);
}
 
Example #25
Source File: MutableSpanBenchmarks.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
public static MutableSpan newServerSpan() {
  MutableSpan span = new MutableSpan();
  span.name("get /");
  span.kind(Span.Kind.SERVER);
  span.remoteIpAndPort("::1", 63596);
  span.startTimestamp(1533706251750057L);
  span.finishTimestamp(1533706251935296L);
  span.tag("http.method", "GET");
  span.tag("http.path", "/");
  span.tag("mvc.controller.class", "Frontend");
  span.tag("mvc.controller.method", "callBackend");
  return span;
}
 
Example #26
Source File: BraveClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSubmitSpanWhenSampled() throws Exception {
    final SpanCollector collector = new SpanCollector();

    final Tracing tracing = Tracing.newBuilder()
                                   .localServiceName(TEST_SERVICE)
                                   .addSpanHandler(collector)
                                   .sampler(Sampler.create(1.0f))
                                   .build();
    final RequestLog requestLog = testRemoteInvocation(tracing, null);

    // check span name
    final MutableSpan span = collector.spans().poll(10, TimeUnit.SECONDS);
    assertThat(span).isNotNull();
    assertThat(span.name()).isEqualTo(TEST_SPAN);

    // check kind
    assertThat(span.kind()).isSameAs(Kind.CLIENT);

    // only one span should be submitted
    assertThat(collector.spans().poll(1, TimeUnit.SECONDS)).isNull();

    // check # of annotations (we add wire annotations)
    assertThat(span.annotations()).hasSize(2);
    assertTags(span);

    assertThat(span.traceId().length()).isEqualTo(16);

    // check duration is correct from request log
    assertThat(span.finishTimestamp() - span.startTimestamp())
            .isEqualTo(requestLog.totalDurationNanos() / 1000);

    // check service name
    assertThat(span.localServiceName()).isEqualTo(TEST_SERVICE);

    // check remote service name
    assertThat(span.remoteServiceName()).isEqualTo(null);
}
 
Example #27
Source File: ITHttpServer.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void readsBaggage_existingTrace() throws IOException {
  String traceId = "463ac35c9f6413ad";

  readsBaggage(new Request.Builder()
    .header("X-B3-TraceId", traceId)
    .header("X-B3-SpanId", traceId));

  MutableSpan span = testSpanHandler.takeRemoteSpan(SERVER);
  assertThat(span.traceId()).isEqualTo(traceId);
  assertThat(span.id()).isEqualTo(traceId);
}
 
Example #28
Source File: ConvertingSpanReporterTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void writeTo_sharedStatus() {
  MutableSpan span = new MutableSpan(context, null);

  span.setShared();
  span.startTimestamp(1L);
  span.kind(SERVER);
  span.finishTimestamp(2L);

  spanReporter.report(span);

  assertThat(spans.get(0).shared())
      .isTrue();
}
 
Example #29
Source File: OpenTracing0_33_BraveSpanTest.java    From brave-opentracing with Apache License 2.0 5 votes vote down vote up
@Test @UseDataProvider("dataProviderKind")
public void spanKind_afterStart(String tagValue, Kind kind) {
  tracer.buildSpan("foo")
      .start()
      .setTag(Tags.SPAN_KIND.getKey(), tagValue)
      .finish();

  MutableSpan span = spans.get(0);
  assertThat(span.kind())
      .isEqualTo(kind);

  assertThat(span.tags())
      .isEmpty();
}
 
Example #30
Source File: TracingChannelInterceptorTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_store_kafka_as_remote_service_name_when_kafka_header_is_present() {
	ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
	channel.addInterceptor(this.interceptor);
	List<Message<?>> messages = new ArrayList<>();
	channel.subscribe(messages::add);

	Map<String, Object> headers = new HashMap<>();
	headers.put(KafkaHeaders.MESSAGE_KEY, "hello");
	channel.send(MessageBuilder.createMessage("foo", new MessageHeaders(headers)));

	assertThat(this.spans).extracting(MutableSpan::remoteServiceName)
			.contains("kafka");
}