brave.handler.SpanHandler Java Examples

The following examples show how to use brave.handler.SpanHandler. 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: PendingSpansClassLoaderTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void run() {
  MutableSpan defaultSpan = new MutableSpan();
  Clock clock = Platform.get().clock();
  SpanHandler orphanTracker =
      OrphanTracker.newBuilder().clock(clock).defaultSpan(defaultSpan).build();
  PendingSpans pendingSpans =
      new PendingSpans(defaultSpan, clock, orphanTracker, new AtomicBoolean());

  TraceContext context = CONTEXT.toBuilder().build(); // intentionally make a copy
  pendingSpans.getOrCreate(null, context, true);
  context = null; // orphan the context

  GarbageCollectors.blockOnGC();

  pendingSpans.expungeStaleEntries();
}
 
Example #2
Source File: TracingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
/** This test shows that duplicates are not allowed. This prevents needless overhead. */
@Test public void spanHandler_dupesIgnored() {
  SpanHandler spanHandler = new SpanHandler() {
    @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
      return true;
    }
  };

  try (Tracing tracing = Tracing.newBuilder()
    .addSpanHandler(spanHandler)
    .addSpanHandler(spanHandler) // dupe
    .build()) {
    assertThat(tracing.tracer().pendingSpans).extracting("spanHandler.delegate")
      .isEqualTo(spanHandler);
  }
}
 
Example #3
Source File: Tracer.java    From brave with Apache License 2.0 6 votes vote down vote up
Tracer(
  Clock clock,
  Propagation.Factory propagationFactory,
  SpanHandler spanHandler,
  PendingSpans pendingSpans,
  Sampler sampler,
  CurrentTraceContext currentTraceContext,
  boolean traceId128Bit,
  boolean supportsJoin,
  boolean alwaysSampleLocal,
  AtomicBoolean noop
) {
  this.clock = clock;
  this.propagationFactory = propagationFactory;
  this.spanHandler = spanHandler;
  this.pendingSpans = pendingSpans;
  this.sampler = sampler;
  this.currentTraceContext = currentTraceContext;
  this.traceId128Bit = traceId128Bit;
  this.supportsJoin = supportsJoin;
  this.alwaysSampleLocal = alwaysSampleLocal;
  this.noop = noop;
}
 
Example #4
Source File: TraceAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
// NOTE: stable bean name as might be used outside sleuth
Tracing tracing(@LocalServiceName String serviceName, Propagation.Factory factory,
		CurrentTraceContext currentTraceContext, Sampler sampler,
		SleuthProperties sleuthProperties, @Nullable List<SpanHandler> spanHandlers,
		@Nullable List<TracingCustomizer> tracingCustomizers) {
	Tracing.Builder builder = Tracing.newBuilder().sampler(sampler)
			.localServiceName(StringUtils.isEmpty(serviceName) ? DEFAULT_SERVICE_NAME
					: serviceName)
			.propagationFactory(factory).currentTraceContext(currentTraceContext)
			.traceId128Bit(sleuthProperties.isTraceId128())
			.supportsJoin(sleuthProperties.isSupportsJoin());
	if (spanHandlers != null) {
		for (SpanHandler spanHandlerFactory : spanHandlers) {
			builder.addSpanHandler(spanHandlerFactory);
		}
	}
	if (tracingCustomizers != null) {
		for (TracingCustomizer customizer : tracingCustomizers) {
			customizer.customize(builder);
		}
	}

	return builder.build();
}
 
Example #5
Source File: TraceBaggageConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Bean
SpanHandler baggageTagSpanHandler(
		@Qualifier(WHITELISTED_KEYS) List<String> whiteListedKeys,
		SleuthBaggageProperties sleuthBaggageProperties) {

	Set<String> tagFields = redirectOldPropertyToNew(WHITELISTED_KEYS,
			whiteListedKeys, "spring.sleuth.baggage.tag-fields",
			sleuthBaggageProperties.getTagFields());

	if (tagFields.isEmpty()) {
		return SpanHandler.NOOP; // Brave ignores these
	}

	return new BaggageTagSpanHandler(tagFields.stream().map(BaggageField::create)
			.toArray(BaggageField[]::new));
}
 
Example #6
Source File: TracingFactoryBean.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override protected Tracing createInstance() {
  Tracing.Builder builder = Tracing.newBuilder();
  if (localServiceName != null) builder.localServiceName(localServiceName);
  if (localEndpoint == null) localEndpoint = endpoint;
  if (localEndpoint != null) {
    builder.endpoint((Endpoint) localEndpoint);
  }
  if (spanReporter != null) {
    builder.spanReporter((Reporter<Span>) spanReporter);
  }
  for (SpanHandler spanHandler : spanHandlers) {
    builder.addSpanHandler(spanHandler);
  }
  if (errorParser != null) builder.errorParser(errorParser);
  if (clock != null) builder.clock(clock);
  if (sampler != null) builder.sampler(sampler);
  if (currentTraceContext != null) builder.currentTraceContext(currentTraceContext);
  if (propagationFactory != null) builder.propagationFactory(propagationFactory);
  if (traceId128Bit != null) builder.traceId128Bit(traceId128Bit);
  if (supportsJoin != null) builder.supportsJoin(supportsJoin);
  if (customizers != null) {
    for (TracingCustomizer customizer : customizers) customizer.customize(builder);
  }
  return builder.build();
}
 
Example #7
Source File: ZipkinAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
void span_handler_comparator() {
	SpanHandler handler1 = mock(SpanHandler.class);
	SpanHandler handler2 = mock(SpanHandler.class);
	ZipkinSpanHandler zipkin1 = mock(ZipkinSpanHandler.class);
	ZipkinSpanHandler zipkin2 = mock(ZipkinSpanHandler.class);

	ArrayList<SpanHandler> spanHandlers = new ArrayList<>();
	spanHandlers.add(handler1);
	spanHandlers.add(zipkin1);
	spanHandlers.add(handler2);
	spanHandlers.add(zipkin2);

	spanHandlers.sort(SPAN_HANDLER_COMPARATOR);

	assertThat(spanHandlers).containsExactly(handler1, handler2, zipkin1, zipkin2);
}
 
Example #8
Source File: ZipkinAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
/** Returns one handler for as many reporters as exist. */
@Bean
SpanHandler zipkinSpanHandler(@Nullable List<Reporter<Span>> spanReporters,
		@Nullable Tag<Throwable> errorTag) {
	if (spanReporters == null) {
		return SpanHandler.NOOP;
	}

	LinkedHashSet<Reporter<Span>> reporters = new LinkedHashSet<>(spanReporters);
	reporters.remove(Reporter.NOOP);
	if (spanReporters.isEmpty()) {
		return SpanHandler.NOOP;
	}

	Reporter<Span> spanReporter = reporters.size() == 1 ? reporters.iterator().next()
			: new CompositeSpanReporter(reporters.toArray(new Reporter[0]));

	ZipkinSpanHandler.Builder builder = ZipkinSpanHandler.newBuilder(spanReporter);
	if (errorTag != null) {
		builder.errorTag(errorTag);
	}
	return builder.build();
}
 
Example #9
Source File: NoopAwareSpanHandlerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void doesntCrashOnNonFatalThrowable() {
  Throwable[] toThrow = new Throwable[1];
  SpanHandler handler =
      NoopAwareSpanHandler.create(new SpanHandler[] {new SpanHandler() {
        @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
          doThrowUnsafely(toThrow[0]);
          return true;
        }
      }}, noop);

  toThrow[0] = new RuntimeException();
  assertThat(handler.end(context, span, Cause.FINISHED)).isTrue();

  toThrow[0] = new Exception();
  assertThat(handler.end(context, span, Cause.FINISHED)).isTrue();

  toThrow[0] = new Error();
  assertThat(handler.end(context, span, Cause.FINISHED)).isTrue();

  toThrow[0] = new StackOverflowError(); // fatal
  try { // assertThatThrownBy doesn't work with StackOverflowError
    handler.end(context, span, Cause.FINISHED);
    failBecauseExceptionWasNotThrown(StackOverflowError.class);
  } catch (StackOverflowError e) {
  }
}
 
Example #10
Source File: TracingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void spanHandlers_clearAndAdd() {
  SpanHandler one = mock(SpanHandler.class);
  SpanHandler two = mock(SpanHandler.class);
  SpanHandler three = mock(SpanHandler.class);

  Tracing.Builder builder = Tracing.newBuilder()
      .addSpanHandler(one)
      .addSpanHandler(two)
      .addSpanHandler(three);

  Set<SpanHandler> spanHandlers = builder.spanHandlers();

  builder.clearSpanHandlers();

  spanHandlers.forEach(builder::addSpanHandler);

  assertThat(builder)
      .usingRecursiveComparison()
      .isEqualTo(Tracing.newBuilder()
          .addSpanHandler(one)
          .addSpanHandler(two)
          .addSpanHandler(three));
}
 
Example #11
Source File: NoopAwareSpanHandlerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void multiple_abandoned() {
  SpanHandler[] handlers = new SpanHandler[3];
  handlers[0] = one;
  handlers[1] = two;
  handlers[2] = three;

  when(two.handlesAbandoned()).thenReturn(true);

  SpanHandler handler = NoopAwareSpanHandler.create(handlers, noop);
  assertThat(handler.handlesAbandoned()).isTrue();
  handler.end(context, span, Cause.ABANDONED);

  verify(one, never()).end(context, span, Cause.ABANDONED);
  verify(two).end(context, span, Cause.ABANDONED);
  verify(three, never()).end(context, span, Cause.FINISHED);
}
 
Example #12
Source File: TraceFilterWebIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Bean
SpanHandler uncaughtExceptionThrown(CurrentTraceContext currentTraceContext) {
	return new SpanHandler() {
		@Override
		public boolean end(TraceContext context, MutableSpan span, Cause cause) {
			if (span.kind() != Kind.SERVER || span.error() == null
					|| !log.isErrorEnabled()) {
				return true; // don't add overhead as we only log server errors
			}

			// In TracingFilter, the exception is raised in scope. This is is more
			// explicit to ensure it works in other tech such as WebFlux.
			try (Scope scope = currentTraceContext.maybeScope(context)) {
				log.error("Uncaught exception thrown", span.error());
			}
			return true;
		}

		@Override
		public String toString() {
			return "UncaughtExceptionThrown";
		}
	};
}
 
Example #13
Source File: NoopAwareSpanHandlerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void multiple_callInSequence() {
  SpanHandler[] handlers = new SpanHandler[2];
  handlers[0] = one;
  handlers[1] = two;
  SpanHandler handler = NoopAwareSpanHandler.create(handlers, noop);
  when(one.begin(eq(context), eq(span), isNull())).thenReturn(true);
  when(one.end(eq(context), eq(span), eq(Cause.FINISHED))).thenReturn(true);

  handler.begin(context, span, null);
  handler.end(context, span, Cause.FINISHED);

  verify(one).begin(context, span, null);
  verify(two).begin(context, span, null);
  verify(two).end(context, span, Cause.FINISHED);
  verify(one).end(context, span, Cause.FINISHED);
}
 
Example #14
Source File: TracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void basicUsage() {
  try (Tracing tracing = Tracing.newBuilder().addSpanHandler(new SpanHandler() {
    // avoid NOOP short-circuiting tracing
  }).build()) {
    ScopedSpan parent = tracing.tracer().startScopedSpan("parent");
    tracing.tracer().newChild(parent.context()).finish();
    parent.finish();
  }
}
 
Example #15
Source File: PendingSpans.java    From brave with Apache License 2.0 5 votes vote down vote up
public PendingSpans(MutableSpan defaultSpan, Clock clock, SpanHandler spanHandler,
  AtomicBoolean noop) {
  this.defaultSpan = defaultSpan;
  this.clock = clock;
  this.spanHandler = spanHandler;
  this.noop = noop;
}
 
Example #16
Source File: NoopAwareSpanHandlerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void create_multiple() {
  SpanHandler[] handlers = new SpanHandler[2];
  handlers[0] = one;
  handlers[1] = two;
  SpanHandler handler = NoopAwareSpanHandler.create(handlers, noop);

  assertThat(handler).extracting("delegate.handlers")
      .asInstanceOf(InstanceOfAssertFactories.array(SpanHandler[].class))
      .containsExactly(one, two);
}
 
Example #17
Source File: SampleFeignApplication.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "sample.zipkin.enabled", havingValue = "false")
public SpanHandler spanHandler() {
	return new SpanHandler() {
		@Override
		public boolean end(TraceContext context, MutableSpan span, Cause cause) {
			logger.info(span);
			return true;
		}
	};
}
 
Example #18
Source File: NoopAwareSpanHandler.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
  for (SpanHandler handler : handlers) {
    if (cause != Cause.ABANDONED || handler.handlesAbandoned()) {
      if (!handler.end(context, span, cause)) return false;
    }
  }
  return true;
}
 
Example #19
Source File: ITHttpServer.java    From brave with Apache License 2.0 5 votes vote down vote up
void spanHandlerSeesError(String path) throws IOException {
  ConcurrentLinkedDeque<Throwable> caughtThrowables = new ConcurrentLinkedDeque<>();
  httpTracing = HttpTracing.create(tracingBuilder(Sampler.ALWAYS_SAMPLE)
      .clearSpanHandlers()
      .addSpanHandler(new SpanHandler() {
        @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
          Throwable error = span.error();
          if (error != null) {
            caughtThrowables.add(error);
          } else {
            caughtThrowables.add(new RuntimeException("Unexpected additional call to end"));
          }
          return true;
        }
      })
      // The blocking span handler goes after the error catcher, so we can assert on the errors.
      .addSpanHandler(testSpanHandler)
      .build());
  init();

  // If this passes, a span was reported with an error
  httpStatusCodeTagMatchesResponse_onUncaughtException(path, ".*not ready");

  assertThat(caughtThrowables)
      .withFailMessage("Span finished with error, but caughtThrowables empty")
      .isNotEmpty();
  if (caughtThrowables.size() > 1) {
    for (Throwable throwable : caughtThrowables) {
      Logger.getAnonymousLogger().log(Level.SEVERE, "multiple calls to finish", throwable);
    }
    assertThat(caughtThrowables).hasSize(1);
  }
}
 
Example #20
Source File: SkeletalSpansTest.java    From brave with Apache License 2.0 5 votes vote down vote up
/** Ensures reporting is partitioned by trace ID */
static SpanHandler toSpanHandler(Map<String, List<MutableSpan>> spans) {
  return new SpanHandler() {
    @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
      spans.computeIfAbsent(span.traceId(), k -> new ArrayList<>()).add(span);
      return true;
    }
  };
}
 
Example #21
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 #22
Source File: TracerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
Map<Long, List<String>> tracerThatPartitionsNamesOnlocalRootId() {
  Map<Long, List<String>> reportedNames = new LinkedHashMap<>();
  tracer = Tracing.newBuilder().addSpanHandler(new SpanHandler() {
    @Override public boolean end(TraceContext context, MutableSpan span, Cause cause) {
      assertThat(context.localRootId()).isNotZero();
      reportedNames.computeIfAbsent(context.localRootId(), k -> new ArrayList<>())
        .add(span.name());
      return true; // retain
    }
  }).alwaysSampleLocal().build().tracer();
  return reportedNames;
}
 
Example #23
Source File: SpanHandlerTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
SpanHandler handlerTwo() {
	return new SpanHandler() {
		@Override
		public boolean end(TraceContext traceContext, MutableSpan span,
				Cause cause) {
			span.name(span.name() + " bar");
			return true; // keep this span
		}
	};
}
 
Example #24
Source File: TraceAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
SpanHandler testSpanHandler() {
	return new SpanHandler() {
		@Override
		public boolean end(TraceContext context, MutableSpan span, Cause cause) {
			return true;
		}
	};
}
 
Example #25
Source File: NoopAwareSpanHandlerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void multiple_shortCircuitWhenFirstReturnsFalse() {
  SpanHandler[] handlers = new SpanHandler[2];
  handlers[0] = one;
  handlers[1] = two;
  SpanHandler handler = NoopAwareSpanHandler.create(handlers, noop);
  handler.end(context, span, Cause.FINISHED);

  verify(one).end(context, span, Cause.FINISHED);
  verify(two, never()).end(context, span, Cause.FINISHED);
}
 
Example #26
Source File: OrphanTrackerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void allocatedAndUsed_logsAndAddsFlushAnnotation() {
  span.startTimestamp(1L);
  assertThat(tracker.begin(context, span, null)).isTrue();
  assertThat(tracker.end(context, span, SpanHandler.Cause.ORPHANED)).isTrue();

  assertThat(span.annotationTimestampAt(0)).isOne(); // initial value of clock
  assertThat(span.annotationValueAt(0)).isEqualTo("brave.flush");

  assertThat(messages).containsExactly(
      "Span 0000000000000001/0000000000000002 neither finished nor flushed before GC"
  );
  assertThrowableIdentifiesCaller();
}
 
Example #27
Source File: SamplerAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
SpanHandler testSpanHandler() {
	return new SpanHandler() {
		@Override
		public boolean end(TraceContext context, MutableSpan span, Cause cause) {
			return true;
		}
	};
}
 
Example #28
Source File: EndToEndBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
public TracedCorrelated() {
  super(Tracing.newBuilder()
    .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
      // intentionally added twice to test overhead of multiple correlations
      .addScopeDecorator(ThreadContextScopeDecorator.get())
      .addScopeDecorator(ThreadContextScopeDecorator.get())
      .build())
    .addSpanHandler(new SpanHandler() {
      // intentionally not NOOP to ensure spans report
    })
    .build());
}
 
Example #29
Source File: EndToEndBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
public Traced() {
  super(Tracing.newBuilder()
      .addSpanHandler(new SpanHandler() {
        // intentionally not NOOP to ensure spans report
      })
      .build());
}
 
Example #30
Source File: EndToEndBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
public Traced128() {
  super(Tracing.newBuilder()
    .traceId128Bit(true)
    .addSpanHandler(new SpanHandler() {
      // intentionally not NOOP to ensure spans report
    })
    .build());
}