brave.propagation.Propagation Java Examples

The following examples show how to use brave.propagation.Propagation. 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: ExtraFieldPropagationFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void fields() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.ExtraFieldPropagationFactoryBean\">\n"
    + "  <property name=\"fields\">\n"
    + "    <list>\n"
    + "      <value>customer-id</value>\n"
    + "      <value>x-vcap-request-id</value>\n"
    + "    </list>\n"
    + "  </property>"
    + "</bean>"
  );

  Propagation<String> propagation =
    context.getBean("propagationFactory", Propagation.Factory.class).get();

  assertThat(BaggagePropagation.allKeyNames(propagation)).endsWith(
    "customer-id",
    "x-vcap-request-id"
  );
}
 
Example #2
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 #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: TracingChannelInterceptor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
TracingChannelInterceptor(Tracing tracing,
		Propagation.Setter<MessageHeaderAccessor, String> setter,
		Propagation.Getter<MessageHeaderAccessor, String> getter) {
	this.tracing = tracing;
	this.tracer = tracing.tracer();
	this.threadLocalSpan = ThreadLocalSpan.create(this.tracer);
	this.injector = tracing.propagation().injector(setter);
	this.extractor = tracing.propagation().extractor(getter);
	this.integrationObjectSupportPresent = ClassUtils.isPresent(
			"org.springframework.integration.context.IntegrationObjectSupport", null);
	this.hasDirectChannelClass = ClassUtils
			.isPresent("org.springframework.integration.channel.DirectChannel", null);
	this.directWithAttributesChannelClass = ClassUtils
			.isPresent(STREAM_DIRECT_CHANNEL, null)
					? ClassUtils.resolveClassName(STREAM_DIRECT_CHANNEL, null) : null;
}
 
Example #5
Source File: BaggagePropagationFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void propagationFactory() {
  context = new XmlBeans(""
    + "<bean id=\"userIdBaggageField\" class=\"brave.baggage.BaggageField\" factory-method=\"create\">\n"
    + "  <constructor-arg value=\"userId\" />\n"
    + "</bean>\n"
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.BaggagePropagationFactoryBean\">\n"
    + "  <property name=\"propagationFactory\">\n"
    + "    <util:constant static-field=\"brave.propagation.B3SinglePropagation.FACTORY\"/>\n"
    + "  </property>\n"
    + "  <property name=\"configs\">\n"
    + "    <list>\n"
    + "      <bean class=\"brave.spring.beans.SingleBaggageFieldFactoryBean\">\n"
    + "        <property name=\"field\" ref=\"userIdBaggageField\"/>\n"
    + "      </bean>\n"
    + "    </list>\n"
    + "  </property>\n"
    + "</bean>\n"
  );

  assertThat(context.getBean("propagationFactory", Propagation.Factory.class))
    .extracting("delegate")
    .isEqualTo(B3SinglePropagation.FACTORY);
}
 
Example #6
Source File: BaggagePropagationFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void customizers() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.BaggagePropagationFactoryBean\">\n"
    + "  <property name=\"customizers\">\n"
    + "    <list>\n"
    + "      <util:constant static-field=\"" + getClass().getName() + ".CUSTOMIZER_ONE\"/>\n"
    + "      <util:constant static-field=\"" + getClass().getName() + ".CUSTOMIZER_TWO\"/>\n"
    + "    </list>\n"
    + "  </property>\n"
    + "</bean>\n"
  );

  context.getBean("propagationFactory", Propagation.Factory.class);

  verify(CUSTOMIZER_ONE).customize(any(BaggagePropagation.FactoryBuilder.class));
  verify(CUSTOMIZER_TWO).customize(any(BaggagePropagation.FactoryBuilder.class));
}
 
Example #7
Source File: TracerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void join_createsChildWhenUnsupportedByPropagation() {
  tracer = Tracing.newBuilder()
    .propagationFactory(new Propagation.Factory() {
      @Deprecated public <K> Propagation<K> create(Propagation.KeyFactory<K> keyFactory) {
        return B3Propagation.FACTORY.create(keyFactory);
      }
    })
    .addSpanHandler(spans).build().tracer();

  TraceContext fromIncomingRequest = tracer.newTrace().context();

  TraceContext shouldBeChild = tracer.joinSpan(fromIncomingRequest).context();
  assertThat(shouldBeChild.shared())
    .isFalse();
  assertThat(shouldBeChild.parentId())
    .isEqualTo(fromIncomingRequest.spanId());
}
 
Example #8
Source File: TracingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void spanHandler_recordsWhenUnsampledIfContextSamplesLocal() {
  AtomicBoolean sampledLocal = new AtomicBoolean();
  try (Tracing tracing = Tracing.newBuilder()
    .propagationFactory(new Propagation.Factory() {
      @Deprecated public <K> Propagation<K> create(Propagation.KeyFactory<K> keyFactory) {
        return B3SinglePropagation.FACTORY.create(keyFactory);
      }

      @Override public TraceContext decorate(TraceContext context) {
        if (sampledLocal.getAndSet(true)) return context;
        return context.toBuilder().sampledLocal(true).build();
      }
    })
    .addSpanHandler(spans)
    .sampler(Sampler.NEVER_SAMPLE)
    .build()) {
    tracing.tracer().newTrace().start().name("one").finish();
    tracing.tracer().newTrace().start().name("two").finish();
  }

  assertThat(spans).hasSize(1);
  assertThat(spans.get(0).name()).isEqualTo("one");
}
 
Example #9
Source File: TestServer.java    From brave with Apache License 2.0 6 votes vote down vote up
TestServer(Propagation.Factory propagationFactory) {
  extractor = propagationFactory.get().extractor(Map::get);
  linkLocalIp = Platform.get().linkLocalIp();
  if (linkLocalIp != null) {
    // avoid dubbo's logic which might pick docker ip
    System.setProperty(Constants.DUBBO_IP_TO_BIND, linkLocalIp);
    System.setProperty(Constants.DUBBO_IP_TO_REGISTRY, linkLocalIp);
  }
  service = new ServiceConfig<>();
  service.setApplication(new ApplicationConfig("bean-provider"));
  service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
  service.setProtocol(new ProtocolConfig("dubbo", PickUnusedPort.get()));
  service.setInterface(GreeterService.class);
  service.setRef((method, parameterTypes, args) -> {
    requestQueue.add(extractor.extract(RpcContext.getContext().getAttachments()));
    return args[0];
  });
}
 
Example #10
Source File: TestServer.java    From brave with Apache License 2.0 6 votes vote down vote up
TestServer(Propagation.Factory propagationFactory, ApplicationConfig application) {
  extractor = propagationFactory.get().extractor(Map::get);
  linkLocalIp = Platform.get().linkLocalIp();
  if (linkLocalIp != null) {
    // avoid dubbo's logic which might pick docker ip
    System.setProperty(CommonConstants.DUBBO_IP_TO_BIND, linkLocalIp);
    System.setProperty(Constants.DUBBO_IP_TO_REGISTRY, linkLocalIp);
  }
  service = new ServiceConfig<>();
  service.setApplication(application);
  service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
  service.setProtocol(new ProtocolConfig("dubbo", PickUnusedPort.get()));
  service.setInterface(GreeterService.class);
  service.setRef((method, parameterTypes, args) -> {
    requestQueue.add(extractor.extract(RpcContext.getContext().getAttachments()));
    return args[0];
  });
}
 
Example #11
Source File: JmsTracing.java    From brave with Apache License 2.0 6 votes vote down vote up
JmsTracing(Builder builder) { // intentionally hidden constructor
  this.tracing = builder.messagingTracing.tracing();
  this.tracer = tracing.tracer();
  Propagation<String> propagation = tracing.propagation();
  if (JmsTypes.HAS_JMS_PRODUCER) {
    this.jmsProducerExtractor = propagation.extractor(JMSProducerRequest.GETTER);
    this.jmsProducerInjector = propagation.injector(JMSProducerRequest.SETTER);
  } else {
    this.jmsProducerExtractor = null;
    this.jmsProducerInjector = null;
  }
  this.messageProducerExtractor = propagation.extractor(MessageProducerRequest.GETTER);
  this.messageProducerInjector = propagation.injector(MessageProducerRequest.SETTER);
  this.messageConsumerExtractor = propagation.extractor(MessageConsumerRequest.GETTER);
  this.messageConsumerInjector = propagation.injector(MessageConsumerRequest.SETTER);
  this.processorExtractor = tracing.propagation().extractor(GETTER);
  this.producerSampler = builder.messagingTracing.producerSampler();
  this.consumerSampler = builder.messagingTracing.consumerSampler();
  this.remoteServiceName = builder.remoteServiceName;
  this.traceIdProperties = new LinkedHashSet<>(tracing.propagation().keys());
}
 
Example #12
Source File: KafkaTracing.java    From brave with Apache License 2.0 6 votes vote down vote up
KafkaTracing(Builder builder) { // intentionally hidden constructor
  this.messagingTracing = builder.messagingTracing;
  this.tracer = builder.messagingTracing.tracing().tracer();
  Propagation<String> propagation = messagingTracing.tracing().propagation();
  this.producerExtractor = propagation.extractor(KafkaProducerRequest.GETTER);
  this.consumerExtractor = propagation.extractor(KafkaConsumerRequest.GETTER);
  this.processorExtractor = propagation.extractor(GETTER);
  this.producerInjector = propagation.injector(KafkaProducerRequest.SETTER);
  this.consumerInjector = propagation.injector(KafkaConsumerRequest.SETTER);
  this.producerSampler = messagingTracing.producerSampler();
  this.consumerSampler = messagingTracing.consumerSampler();
  this.remoteServiceName = builder.remoteServiceName;
  this.singleRootSpanOnReceiveBatch = builder.singleRootSpanOnReceiveBatch;

  // We clear the trace ID headers, so that a stale consumer span is not preferred over current
  // listener. We intentionally don't clear BaggagePropagation.allKeyNames as doing so will
  // application fields "user_id" or "country_code"
  this.traceIdHeaders = new LinkedHashSet<>(propagation.keys());

  // When baggage or similar is in use, the result != TraceContextOrSamplingFlags.EMPTY
  this.emptyExtraction = propagation.extractor((c, k) -> null).extract(Boolean.TRUE);
}
 
Example #13
Source File: BaggagePropagationFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void propagationFactory_noFields() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.BaggagePropagationFactoryBean\">\n"
    + "  <property name=\"propagationFactory\">\n"
    + "    <util:constant static-field=\"brave.propagation.B3SinglePropagation.FACTORY\"/>\n"
    + "  </property>\n"
    + "</bean>\n"
  );

  assertThat(context.getBean("propagationFactory", Propagation.Factory.class))
    .isEqualTo(B3SinglePropagation.FACTORY);
}
 
Example #14
Source File: TraceSpringIntegrationAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Bean
TracingChannelInterceptor traceChannelInterceptor(Tracing tracing,
		Propagation.Setter<MessageHeaderAccessor, String> traceMessagePropagationSetter,
		Propagation.Getter<MessageHeaderAccessor, String> traceMessagePropagationGetter) {
	return new TracingChannelInterceptor(tracing, traceMessagePropagationSetter,
			traceMessagePropagationGetter);
}
 
Example #15
Source File: TraceAutoConfigurationPropagationCustomizationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void stillCreatesDefault() {
	this.contextRunner.run((context) -> {
		BDDAssertions.then(context.getBean(Propagation.Factory.class))
				.isEqualTo(TraceBaggageConfiguration.B3_FACTORY);
	});
}
 
Example #16
Source File: TraceAutoConfigurationPropagationCustomizationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void allowsCustomization() {
	this.contextRunner
			.withPropertyValues("spring.sleuth.baggage.remote-fields=country-code")
			.run((context) -> {
				BDDAssertions.then(context.getBean(Propagation.Factory.class))
						.extracting("delegate")
						.isEqualTo(TraceBaggageConfiguration.B3_FACTORY);
			});
}
 
Example #17
Source File: TraceAutoConfigurationPropagationCustomizationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultValueUsedWhenApplicationNameNotSet() {
	this.contextRunner.withPropertyValues("spring.application.name=")
			.run((context) -> {
				BDDAssertions.then(context.getBean(Propagation.Factory.class))
						.isEqualTo(TraceBaggageConfiguration.B3_FACTORY);
			});
}
 
Example #18
Source File: TraceAutoConfigurationPropagationCustomizationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void allowsCustomizationOfBuilder() {
	this.contextRunner
			.withPropertyValues("spring.sleuth.baggage.remote-fields=country-code")
			.withUserConfiguration(CustomPropagationFactoryBuilderConfig.class)
			.run((context) -> BDDAssertions
					.then(context.getBean(Propagation.Factory.class))
					.extracting("delegate").isSameAs(B3SinglePropagation.FACTORY));
}
 
Example #19
Source File: TraceAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
void should_use_B3Propagation_factory_by_default() {
	this.contextRunner.run((context -> {
		final Propagation.Factory bean = context.getBean(Propagation.Factory.class);
		BDDAssertions.then(bean).isInstanceOf(Propagation.Factory.class);
	}));
}
 
Example #20
Source File: TraceAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
void should_use_baggagePropagationFactoryBuilder_bean() {
	// BaggagePropagation.FactoryBuilder unwraps itself if there are no baggage fields
	// defined
	this.contextRunner
			.withUserConfiguration(WithBaggagePropagationFactoryBuilderBean.class)
			.run((context -> BDDAssertions
					.then(context.getBean(Propagation.Factory.class))
					.isSameAs(B3SinglePropagation.FACTORY)));
}
 
Example #21
Source File: TraceBaggageConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
static ListAssert<Tuple> assertThatBaggageFieldNameToKeyNames(
		AssertableApplicationContext context) {
	return assertThat(context.getBean(Propagation.Factory.class))
			.extracting("configs").asInstanceOf(InstanceOfAssertFactories.ARRAY)
			.extracting("field.name", "keyNames.toArray")
			.asInstanceOf(InstanceOfAssertFactories.list(Tuple.class));
}
 
Example #22
Source File: PropagationTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void accept(Propagation<?> propagation) {
  TraceContext.Injector<Map<Object, String>> injector = propagation.injector(Map::put);
  TraceContext.Extractor<Map<Object, String>> extractor = propagation.extractor(Map::get);

  TraceContext ctx = TraceContext.newBuilder().traceId(1L).spanId(2L).sampled(false).build();
  Map<Object, String> map = new LinkedHashMap<>();
  injector.inject(ctx, map);

  assertThat(extractor.extract(map).context())
    .isEqualToIgnoringGivenFields(ctx, "traceIdString", "spanIdString");
}
 
Example #23
Source File: BaggagePropagationFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void propagationFactory_default() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.BaggagePropagationFactoryBean\"/>\n"
  );

  assertThat(context.getBean("propagationFactory", Propagation.Factory.class))
    .isEqualTo(B3Propagation.FACTORY);
}
 
Example #24
Source File: ExtraFieldPropagationFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void propagationFactory() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.ExtraFieldPropagationFactoryBean\">\n"
    + "  <property name=\"propagationFactory\">\n"
    + "    <util:constant static-field=\""
    + B3SinglePropagation.class.getName()
    + ".FACTORY\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("propagationFactory", Propagation.Factory.class))
    .extracting("delegate")
    .isEqualTo(B3SinglePropagation.FACTORY);
}
 
Example #25
Source File: JmsTracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void nextSpan_should_clear_propagation_headers() {
  Propagation.B3_STRING.injector(SETTER).inject(parent, message);
  Propagation.B3_SINGLE_STRING.injector(SETTER).inject(parent, message);

  jmsTracing.nextSpan(message);
  assertThat(ITJms.propertiesToMap(message)).isEmpty();
}
 
Example #26
Source File: ExtraFieldPropagationFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void propagationFactory_default() {
  context = new XmlBeans(""
    + "<bean id=\"propagationFactory\" class=\"brave.spring.beans.ExtraFieldPropagationFactoryBean\"/>"
  );

  assertThat(context.getBean("propagationFactory", Propagation.Factory.class))
    .extracting("delegate")
    .isEqualTo(B3Propagation.FACTORY);
}
 
Example #27
Source File: BaggagePropagationTest.java    From brave with Apache License 2.0 5 votes vote down vote up
/** Less overhead and distraction for the edge case of correlation-only. */
@Test public void extract_baggage_onlyOneExtraWhenNothingRemote() {
  Propagation.Factory factory = newFactoryBuilder(B3Propagation.FACTORY)
      .add(SingleBaggageField.local(vcapRequestId))
      .add(SingleBaggageField.local(amznTraceId)).build();
  extractor = factory.get().extractor(Map::get);

  TraceContextOrSamplingFlags extracted = extractor.extract(request);
  assertThat(extracted.extra())
      .hasSize(1)
      .noneMatch(Extra.class::isInstance);
}
 
Example #28
Source File: BaggagePropagationTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void allKeyNames_baggagePropagation_noRemote() {
  Propagation.Factory factory = BaggagePropagation.newFactoryBuilder(B3SinglePropagation.FACTORY)
      .add(SingleBaggageField.local(BaggageField.create("redacted"))) // local shouldn't return
      .add(SingleBaggageField.local(BaggageField.create("user-id")))
      .add(SingleBaggageField.local(BaggageField.create("session-id"))).build();

  assertThat(BaggagePropagation.allKeyNames(factory.get()))
      .containsExactly("b3");
}
 
Example #29
Source File: CustomTraceIdPropagation.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * @param delegate some configuration of {@link B3Propagation#newFactoryBuilder()}
 * @param customTraceIdName something not "b3"
 */
public static Propagation.Factory create(Propagation.Factory delegate, String customTraceIdName) {
  if (delegate == null) throw new NullPointerException("delegate == null");
  if (customTraceIdName == null) throw new NullPointerException("customTraceIdName == null");
  if (!delegate.create(KeyFactory.STRING).keys().contains("b3")) {
    throw new IllegalArgumentException("delegate must implement B3 propagation");
  }
  return new CustomTraceIdPropagation(delegate, customTraceIdName);
}
 
Example #30
Source File: TextMapPropagation.java    From brave with Apache License 2.0 5 votes vote down vote up
TextMapExtractor(
    Propagation<String> propagation,
    Set<String> allNames,
    Getter<Map<String, String>, String> getter) {
  this.allNames = allNames;
  this.delegate = propagation.extractor(getter);
}