brave.propagation.CurrentTraceContext Java Examples

The following examples show how to use brave.propagation.CurrentTraceContext. 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: ITRemote.java    From brave with Apache License 2.0 6 votes vote down vote up
protected ITRemote() {
  CurrentTraceContext.Builder currentTraceContextBuilder = currentTraceContextBuilder();
  if (currentTraceContextBuilder instanceof StrictCurrentTraceContext.Builder) {
    currentTraceContext = currentTraceContextBuilder.build();
    checkForLeakedScopes = (Closeable) currentTraceContext;
  } else {
    StrictScopeDecorator strictScopeDecorator = StrictScopeDecorator.create();
    currentTraceContext = currentTraceContextBuilder
      .addScopeDecorator(strictScopeDecorator).build();
    checkForLeakedScopes = strictScopeDecorator;
  }
  propagationFactory = BaggagePropagation.newFactoryBuilder(B3Propagation.FACTORY)
    .add(SingleBaggageField.newBuilder(BAGGAGE_FIELD)
      .addKeyName(BAGGAGE_FIELD_KEY)
      .build()).build();
  tracing = tracingBuilder(Sampler.ALWAYS_SAMPLE).build();
}
 
Example #2
Source File: TraceAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Bean
CurrentTraceContext sleuthCurrentTraceContext(CurrentTraceContext.Builder builder,
		@Nullable List<CurrentTraceContext.ScopeDecorator> scopeDecorators,
		@Nullable List<CurrentTraceContextCustomizer> currentTraceContextCustomizers) {
	if (scopeDecorators == null) {
		scopeDecorators = Collections.emptyList();
	}
	if (currentTraceContextCustomizers == null) {
		currentTraceContextCustomizers = Collections.emptyList();
	}

	for (CurrentTraceContext.ScopeDecorator scopeDecorator : scopeDecorators) {
		builder.addScopeDecorator(scopeDecorator);
	}
	for (CurrentTraceContextCustomizer customizer : currentTraceContextCustomizers) {
		customizer.customize(builder);
	}
	return builder.build();
}
 
Example #3
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 #4
Source File: ScopePassingSpanSubscriberTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_scope_scalar_hide_subscribe() {
	springContext.registerBean(CurrentTraceContext.class, () -> currentTraceContext);
	springContext.refresh();

	Function<? super Publisher<Integer>, ? extends Publisher<Integer>> transformer = scopePassingSpanOperator(
			this.springContext);

	try (Scope ws = this.currentTraceContext.newScope(context)) {

		transformer.apply(Mono.just(1).hide())
				.subscribe(assertScopePassingSpanSubscriber);

		transformer.apply(Mono.<Integer>error(new Exception()).hide())
				.subscribe(assertScopePassingSpanSubscriber);

		transformer.apply(Mono.<Integer>empty().hide())
				.subscribe(assertScopePassingSpanSubscriber);
	}
}
 
Example #5
Source File: ScopePassingSpanSubscriberTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_scope_scalar_subscribe() {
	springContext.registerBean(CurrentTraceContext.class, () -> currentTraceContext);
	springContext.refresh();

	Function<? super Publisher<Integer>, ? extends Publisher<Integer>> transformer = scopePassingSpanOperator(
			this.springContext);

	try (Scope ws = this.currentTraceContext.newScope(context)) {

		transformer.apply(Mono.just(1))
				.subscribe(assertNotScopePassingSpanSubscriber);

		transformer.apply(Mono.error(new Exception()))
				.subscribe(assertNotScopePassingSpanSubscriber);

		transformer.apply(Mono.empty())
				.subscribe(assertNotScopePassingSpanSubscriber);

	}
}
 
Example #6
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 #7
Source File: CurrentTraceContextExecutorServiceTest.java    From brave with Apache License 2.0 6 votes vote down vote up
void eachTaskHasCorrectSpanAttached(Callable<?> scheduleTwoTasks) throws Exception {
  // First task should block the queue, forcing the latter to not be scheduled immediately
  // Both should have the same parent, as the parent applies to the task creation time, not
  // execution time.
  try (CurrentTraceContext.Scope ws = currentTraceContext.newScope(context)) {
    scheduleTwoTasks.call();
  }

  // switch the current span to something else. If there's a bug, when the
  // second runnable starts, it will have this span as opposed to the one it was
  // invoked with
  try (CurrentTraceContext.Scope ws = currentTraceContext.newScope(context2)) {
    latch.countDown();
    shutdownExecutor();
    assertThat(threadValues)
      .containsExactly(context, context);
  }
}
 
Example #8
Source File: CurrentTraceContextTest.java    From brave with Apache License 2.0 6 votes vote down vote up
protected void is_inheritable(CurrentTraceContext inheritableCurrentTraceContext)
  throws Exception {
  // use a single-threaded version of newCachedThreadPool
  ExecutorService service = new ThreadPoolExecutor(0, 1,
    60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

  // submitting a job grows the pool, attaching the context to its thread
  try (Scope scope = inheritableCurrentTraceContext.newScope(context)) {
    assertThat(service.submit(inheritableCurrentTraceContext::get).get())
      .isEqualTo(context);
  }

  // same thread executes the next job and still has the same context (leaked and not cleaned up)
  assertThat(service.submit(inheritableCurrentTraceContext::get).get())
    .isEqualTo(context);

  service.shutdownNow();
}
 
Example #9
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 #10
Source File: ReactorSleuth.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
/**
 * Like {@link CurrentTraceContext#get()}, except it first checks the reactor context.
 */
static TraceContext traceContext(Context context, CurrentTraceContext fallback) {
	if (context.hasKey(TraceContext.class)) {
		return context.get(TraceContext.class);
	}
	return fallback.get();
}
 
Example #11
Source File: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
protected AnnotationConfigApplicationContext newClient(int port) {
	AnnotationConfigApplicationContext result = new AnnotationConfigApplicationContext();
	URI baseUrl = URI.create("http://127.0.0.1:" + server.getPort());
	result.registerBean(HttpTracing.class, () -> httpTracing);
	result.registerBean(CurrentTraceContext.class,
			() -> httpTracing.tracing().currentTraceContext());
	result.registerBean(HttpClient.class, () -> testHttpClient(baseUrl));
	result.registerBean(URI.class, () -> baseUrl);
	result.register(componentClasses);
	result.refresh();
	return result;
}
 
Example #12
Source File: TracingJmsListenerEndpointRegistry.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, Session session) throws JMSException {
	Span span = this.jmsTracing.nextSpan(message).name("on-message").start();
	try (CurrentTraceContext.Scope ws = this.current.newScope(span.context())) {
		super.onMessage(message, session);
	}
	catch (JMSException | RuntimeException | Error e) {
		span.error(e);
		throw e;
	}
	finally {
		span.finish();
	}
}
 
Example #13
Source File: TracingJmsListenerEndpointRegistry.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private CurrentTraceContext currentTraceContext() {
	if (this.currentTraceContext == null) {
		this.currentTraceContext = this.beanFactory
				.getBean(CurrentTraceContext.class);
	}
	return this.currentTraceContext;
}
 
Example #14
Source File: AbstractSleuthMethodInvocationProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
CurrentTraceContext currentTraceContext() {
	if (this.currentTraceContext == null) {
		this.currentTraceContext = this.beanFactory
				.getBean(CurrentTraceContext.class);
	}
	return this.currentTraceContext;
}
 
Example #15
Source File: CurrentTraceContextAssemblyTrackingClassLoaderTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void run() {
  CurrentTraceContext currentTraceContext =
    ThreadLocalCurrentTraceContext.newBuilder().build();
  SavedHooks saved = new CurrentTraceContextAssemblyTracking(currentTraceContext)
    .enableAndChain();

  TraceContext assembly = TraceContext.newBuilder().traceId(1).spanId(1).build();

  try (Scope scope = currentTraceContext.newScope(assembly)) {
    Observable.just(1).map(i -> i).test().assertNoErrors();
  } finally {
    saved.restore();
  }
}
 
Example #16
Source File: ScopePassingSpanSubscriber.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
ScopePassingSpanSubscriber(Subscriber<? super T> subscriber, Context ctx,
		CurrentTraceContext currentTraceContext, @Nullable TraceContext parent) {
	this.subscriber = subscriber;
	this.currentTraceContext = currentTraceContext;
	this.parent = parent;
	this.context = parent != null
			&& !parent.equals(ctx.getOrDefault(TraceContext.class, null))
					? ctx.put(TraceContext.class, parent) : ctx;
	if (log.isTraceEnabled()) {
		log.trace("Parent span [" + parent + "], context [" + this.context + "]");
	}
}
 
Example #17
Source File: TraceHelper.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Get or build tracing.
 */
public static Tracing getTracing(String serviceName, CurrentTraceContext context) {
    Tracing tracing = Tracing.current();
    if (tracing == null) {
        // TODO reporter based on prop/config
        tracing = getBuilder(serviceName, context).build();
    }
    return tracing;
}
 
Example #18
Source File: CurrentTraceContextExecutorTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test
public void execute() throws Exception {
  final TraceContext[] threadValues = new TraceContext[2];

  CountDownLatch latch = new CountDownLatch(1);
  // First task should block the queue, forcing the latter to not be scheduled immediately
  // Both should have the same parent, as the parent applies to the task creation time, not
  // execution time.
  try (CurrentTraceContext.Scope ws = currentTraceContext.newScope(context)) {
    executor.execute(() -> {
      threadValues[0] = currentTraceContext.get();
      try {
        latch.await();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        e.printStackTrace();
      }
    });
    // this won't run immediately because the other is blocked
    executor.execute(() -> threadValues[1] = currentTraceContext.get());
  }

  // switch the current span to something else. If there's a bug, when the
  // second runnable starts, it will have this span as opposed to the one it was
  // invoked with
  try (CurrentTraceContext.Scope ws = currentTraceContext.newScope(context2)) {
    latch.countDown();
    shutdownExecutor();
    assertThat(threadValues)
      .containsExactly(context, context);
  }
}
 
Example #19
Source File: BraveIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Tracing newTracing(String name) {
    final CurrentTraceContext currentTraceContext =
            RequestContextCurrentTraceContext.builder()
                                             .nonRequestThread("nonrequest-")
                                             .addScopeDecorator(StrictScopeDecorator.create())
                                             .build();
    return Tracing.newBuilder()
                  .currentTraceContext(currentTraceContext)
                  .localServiceName(name)
                  .addSpanHandler(spanHandler)
                  .sampler(Sampler.ALWAYS_SAMPLE)
                  .build();
}
 
Example #20
Source File: CurrentTraceContextTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void ignoresNoopScopeDecorator() {
  ScopeDecorator one = (context, scope) -> scope;

  CurrentTraceContext shouldHaveOnlyOne = newBuilder()
    .addScopeDecorator(ScopeDecorator.NOOP)
    .addScopeDecorator(one).build();

  assertThat(shouldHaveOnlyOne).extracting("scopeDecorators")
    .asInstanceOf(InstanceOfAssertFactories.ARRAY)
    .doesNotContain(ScopeDecorator.NOOP);
}
 
Example #21
Source File: CurrentTraceContextTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void newScope_decoratesWithDifferentScope() {
  Scope differentScope = () -> {
  };

  CurrentTraceContext decoratesWithDifferentScope = newBuilder()
    .addScopeDecorator((context, scope) -> differentScope).build();

  try (Scope scope = decoratesWithDifferentScope.newScope(context)) {
    assertThat(scope).isSameAs(differentScope);
  }

  try (Scope scope = decoratesWithDifferentScope.newScope(null)) {
    assertThat(scope).isSameAs(differentScope);
  }
}
 
Example #22
Source File: ThreadContextScopeDecorator.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a scope decorator that configures {@link BaggageFields#TRACE_ID}, {@link
 * BaggageFields#PARENT_ID}, {@link BaggageFields#SPAN_ID} and {@link BaggageFields#SAMPLED}
 *
 * @since 5.2
 * @deprecated since 5.11 use {@link #get()} or {@link #newBuilder()}
 */
@Deprecated public static CurrentTraceContext.ScopeDecorator create() {
  return new Builder()
    .clear()
    .add(SingleCorrelationField.create(BaggageFields.TRACE_ID))
    .add(SingleCorrelationField.create(BaggageFields.PARENT_ID))
    .add(SingleCorrelationField.create(BaggageFields.SPAN_ID))
    .add(SingleCorrelationField.create(BaggageFields.SAMPLED))
    .build();
}
 
Example #23
Source File: HttpServerParserAdapter.java    From brave with Apache License 2.0 5 votes vote down vote up
HttpServerParserAdapter(
  HttpRequestParser requestParser,
  HttpResponseParser responseParser,
  CurrentTraceContext currentTraceContext,
  ErrorParser errorParser
) {
  this.requestParser = requestParser;
  this.responseParser = responseParser;
  this.currentTraceContext = currentTraceContext;
  this.errorParser = errorParser;
}
 
Example #24
Source File: HttpClientHandlerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void handleSendWithParent_overrideNull() {
  try (CurrentTraceContext.Scope ws = httpTracing.tracing.currentTraceContext().newScope(null)) {
    brave.Span span = handler.handleSendWithParent(request, context);

    // If the overwrite was successful, we have a child span.
    assertThat(span.context().parentIdAsLong()).isEqualTo(context.spanId());
  }
}
 
Example #25
Source File: MDCScopeDecorator.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a scope decorator that configures {@link BaggageFields#TRACE_ID}, {@link
 * BaggageFields#PARENT_ID}, {@link BaggageFields#SPAN_ID} and {@link BaggageFields#SAMPLED}
 *
 * @since 5.2
 * @deprecated since 5.11 use {@link #get()} or {@link #newBuilder()}
 */
@Deprecated public static CurrentTraceContext.ScopeDecorator create() {
  return new Builder()
    .clear()
    .add(SingleCorrelationField.create(BaggageFields.TRACE_ID))
    .add(SingleCorrelationField.create(BaggageFields.PARENT_ID))
    .add(SingleCorrelationField.create(BaggageFields.SPAN_ID))
    .add(SingleCorrelationField.create(BaggageFields.SAMPLED))
    .build();
}
 
Example #26
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static Completable wrap(
  CompletableSource source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableCompletable<>(source, contextScoper, assembled);
  }
  return new TraceContextCompletable(source, contextScoper, assembled);
}
 
Example #27
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static <T> Maybe<T> wrap(
  MaybeSource<T> source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableMaybe<>(source, contextScoper, assembled);
  }
  return new TraceContextMaybe<>(source, contextScoper, assembled);
}
 
Example #28
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static <T> Single<T> wrap(
  SingleSource<T> source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableSingle<>(source, contextScoper, assembled);
  }
  return new TraceContextSingle<>(source, contextScoper, assembled);
}
 
Example #29
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static <T> Observable<T> wrap(
  ObservableSource<T> source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableObservable<>(source, contextScoper, assembled);
  }
  return new TraceContextObservable<>(source, contextScoper, assembled);
}
 
Example #30
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static <T> Flowable<T> wrap(
  Publisher<T> source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableFlowable<>(source, contextScoper, assembled);
  }
  return new TraceContextFlowable<>(source, contextScoper, assembled);
}