brave.http.HttpTracing Java Examples

The following examples show how to use brave.http.HttpTracing. 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: ServerTracingModule.java    From ratpack-zipkin with Apache License 2.0 6 votes vote down vote up
@Provides @Singleton
public HttpTracing getHttpTracing(final Config config, final ServerConfig serverConfig) {
  Tracing tracing = Tracing.newBuilder()
                           .sampler(config.sampler)
                           .currentTraceContext(new RatpackCurrentTraceContext())
                           .endpoint(buildEndpoint(config.serviceName, serverConfig.getPort(),
                               serverConfig.getAddress()))
                           .spanReporter(config.spanReporter)
                           .propagationFactory(config.propagationFactory)
                           .build();
  return HttpTracing.newBuilder(tracing)
                    .clientParser(config.clientParser)
                    .serverParser(config.serverParser)
                    .serverSampler(config.serverSampler)
                    .clientSampler(config.clientSampler)
                    .build();
}
 
Example #2
Source File: HelloWorldApplication.java    From dropwizard-zipkin with Apache License 2.0 6 votes vote down vote up
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {

  final Optional<HttpTracing> tracing = zipkinBundle.getHttpTracing();

  final Client client;
  if (tracing.isPresent()) {
    client =
        new ZipkinClientBuilder(environment, tracing.get())
            .build(configuration.getZipkinClient());
  } else {
    final ZipkinClientConfiguration clientConfig = configuration.getZipkinClient();
    client =
        new JerseyClientBuilder(environment)
            .using(clientConfig)
            .build(clientConfig.getServiceName());
  }

  // Register resources
  final HelloWorldResource resource = new HelloWorldResource(client);
  environment.jersey().register(resource);
}
 
Example #3
Source File: Catalog.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject search(@QueryParam("q") final String query, @Context final TracerContext tracing) throws Exception {
    final CloseableHttpClient httpclient = TracingHttpClientBuilder
        .create(tracing.unwrap(HttpTracing.class))
        .build();

    try {
        final URI uri = new URIBuilder("https://www.googleapis.com/books/v1/volumes")
            .setParameter("q", query)
            .build();
        
        final HttpGet request = new HttpGet(uri);
        request.setHeader("Accept", "application/json");
        
        final HttpResponse response = httpclient.execute(request);
        final String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        try (final StringReader reader = new StringReader(data)) {
            return Json.createReader(reader).readObject();
        }
    } finally {
        httpclient.close();
    }
}
 
Example #4
Source File: HttpTracingFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void customizers() {
  context = new XmlBeans(""
    + "<bean id=\"httpTracing\" class=\"brave.spring.beans.HttpTracingFactoryBean\">\n"
    + "  <property name=\"tracing\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".TRACING\"/>\n"
    + "  </property>\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>"
    + "</bean>"
  );

  context.getBean("httpTracing", HttpTracing.class);

  verify(CUSTOMIZER_ONE).customize(any(HttpTracing.Builder.class));
  verify(CUSTOMIZER_TWO).customize(any(HttpTracing.Builder.class));
}
 
Example #5
Source File: TraceRestTemplateInterceptorTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void notSampledHeaderAddedWhenNotSampled() {
	this.tracing.close();
	this.tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
			.addSpanHandler(this.spans).sampler(Sampler.NEVER_SAMPLE).build();
	this.template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
			TracingClientHttpRequestInterceptor.create(HttpTracing.create(tracing))));

	Span span = tracing.tracer().nextSpan().name("new trace");
	Map<String, String> headers;

	try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(span.start())) {
		headers = this.template.getForEntity("/", Map.class).getBody();
	}
	finally {
		span.finish();
	}

	then(this.spans).isEmpty();
}
 
Example #6
Source File: HttpTracingFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void clientParser() {
  context = new XmlBeans(""
    + "<bean id=\"httpTracing\" class=\"brave.spring.beans.HttpTracingFactoryBean\">\n"
    + "  <property name=\"tracing\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".TRACING\"/>\n"
    + "  </property>\n"
    + "  <property name=\"clientParser\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".CLIENT_PARSER\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("httpTracing", HttpTracing.class))
    .extracting("clientParser")
    .isEqualTo(CLIENT_PARSER);
}
 
Example #7
Source File: TranslationService.java    From talk-kafka-zipkin with MIT License 6 votes vote down vote up
@Override
public void run(TranslationServiceConfiguration configuration,
		Environment environment) {

	/* START TRACING INSTRUMENTATION */
	final var sender = URLConnectionSender.newBuilder()
			.endpoint(configuration.getZipkinEndpoint()).build();
	final var reporter = AsyncReporter.builder(sender).build();
	final var tracing = Tracing.newBuilder().localServiceName("translation-service")
			.sampler(Sampler.ALWAYS_SAMPLE).spanReporter(reporter).build();
	final var httpTracing = HttpTracing.newBuilder(tracing).build();
	final var jerseyTracingFilter = TracingApplicationEventListener
			.create(httpTracing);
	environment.jersey().register(jerseyTracingFilter);
	/* END TRACING INSTRUMENTATION */

	final var repository = new TranslationRepository();
	final var translationResource = new TranslationResource(repository);
	environment.jersey().register(translationResource);

	final var healthCheck = new TranslationServiceHealthCheck();
	environment.healthChecks().register("translation-service", healthCheck);
}
 
Example #8
Source File: HttpTracingFactoryBeanTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void clientSampler() {
  context = new XmlBeans(""
    + "<bean id=\"httpTracing\" class=\"brave.spring.beans.HttpTracingFactoryBean\">\n"
    + "  <property name=\"tracing\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".TRACING\"/>\n"
    + "  </property>\n"
    + "  <property name=\"clientSampler\">\n"
    + "    <util:constant static-field=\"brave.http.HttpSampler.NEVER_SAMPLE\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("httpTracing", HttpTracing.class))
    .extracting("clientSampler")
    .isEqualTo(HttpSampler.NEVER_SAMPLE);
}
 
Example #9
Source File: KafkaZipkinFactory.java    From dropwizard-zipkin with Apache License 2.0 6 votes vote down vote up
/**
 * Build a new {@link HttpTracing} instance for interfacing with Zipkin
 *
 * @param environment Environment
 * @return Brave instance
 */
@Override
public Optional<HttpTracing> build(final Environment environment) {
  if (!isEnabled()) {
    LOGGER.warn("Zipkin tracing is disabled");
    return Optional.empty();
  }

  final KafkaSender sender =
      KafkaSender.newBuilder()
          .bootstrapServers(bootstrapServers)
          .topic(topic)
          .overrides(overrides)
          .build();

  LOGGER.info("Sending spans to Kafka topic \"{}\" at: {}", topic, bootstrapServers);

  return buildTracing(environment, sender);
}
 
Example #10
Source File: TraceHttpAutoConfigurationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
/**
 * Shows bean aliases work to configure the same instance for both client and server
 */
@Test
public void configuresUserProvidedHttpClientAndServerParser() {
	contextRunner().withUserConfiguration(HttpParserConfig.class).run((context) -> {
		HttpRequestParser serverRequestParser = context.getBean(HttpTracing.class)
				.serverRequestParser();
		HttpResponseParser serverResponseParser = context.getBean(HttpTracing.class)
				.serverResponseParser();
		HttpRequestParser clientRequestParser = context.getBean(HttpTracing.class)
				.clientRequestParser();
		HttpResponseParser clientResponseParser = context.getBean(HttpTracing.class)
				.clientResponseParser();

		then(clientRequestParser).isSameAs(HttpParserConfig.REQUEST_PARSER);
		then(clientResponseParser).isSameAs(HttpParserConfig.RESPONSE_PARSER);
		then(serverRequestParser).isSameAs(HttpParserConfig.REQUEST_PARSER);
		then(serverResponseParser).isSameAs(HttpParserConfig.RESPONSE_PARSER);
	});
}
 
Example #11
Source File: TraceFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void createsChildFromHeadersWhenJoinUnsupported() throws Exception {
	Tracing tracing = Tracing.newBuilder()
			.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
					.addScopeDecorator(StrictScopeDecorator.create()).build())
			.addSpanHandler(this.spans).supportsJoin(false).build();
	HttpTracing httpTracing = HttpTracing.create(tracing);
	this.request = builder().header("b3", "0000000000000014-000000000000000a")
			.buildRequest(new MockServletContext());

	TracingFilter.create(httpTracing).doFilter(this.request, this.response,
			this.filterChain);

	then(Tracing.current().tracer().currentSpan()).isNull();
	then(this.spans).hasSize(1);
	then(this.spans.get(0).parentId()).isEqualTo("000000000000000a");
}
 
Example #12
Source File: BraveClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void newDecorator_shouldWorkWhenRequestContextCurrentTraceContextConfigured() {
    BraveClient.newDecorator(
            HttpTracing.create(
                    Tracing.newBuilder().currentTraceContext(RequestContextCurrentTraceContext.ofDefault())
                           .build()));
}
 
Example #13
Source File: BraveClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new tracing {@link HttpClient} decorator using the specified {@link HttpTracing} instance.
 */
public static Function<? super HttpClient, BraveClient> newDecorator(
        HttpTracing httpTracing) {
    try {
        ensureScopeUsesRequestContext(httpTracing.tracing());
    } catch (IllegalStateException e) {
        logger.warn("{} - it is appropriate to ignore this warning if this client is not being used " +
                    "inside an Armeria server (e.g., this is a normal spring-mvc tomcat server).",
                    e.getMessage());
    }
    return delegate -> new BraveClient(delegate, httpTracing);
}
 
Example #14
Source File: TracingMainExec.java    From brave with Apache License 2.0 5 votes vote down vote up
TracingMainExec(HttpTracing httpTracing, ClientExecChain mainExec) {
  this.tracer = httpTracing.tracing().tracer();
  this.currentTraceContext = httpTracing.tracing().currentTraceContext();
  this.serverName = "".equals(httpTracing.serverName()) ? null : httpTracing.serverName();
  this.handler = HttpClientHandler.create(httpTracing);
  this.mainExec = mainExec;
}
 
Example #15
Source File: HttpClientTracingHandlerIntegrationTest.java    From xio with Apache License 2.0 5 votes vote down vote up
protected XioClient newClient(int port) {
  // System.out.println("newClient port: " + port);
  HttpTracing httpTracing = null; // TODO(CK): remove this when the tests are fixed
  state = new HttpClientTracingState(httpTracing, false);

  return new XioClientBootstrap(ClientConfig.fromConfig("xio.h1TestClient"), eventLoopGroup)
      .address(new InetSocketAddress("127.0.0.1", port))
      .ssl(false)
      .proto(Protocol.HTTP)
      .handler(new ApplicationHandler())
      .tracingHandler(() -> new HttpClientTracingHandler(state))
      .usePool(false)
      .build();
}
 
Example #16
Source File: BraveTracerContext.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(final Class<T> clazz) {
    if (HttpTracing.class.equals(clazz)) {
        return (T)brave;
    } else if (Tracing.class.equals(clazz)) {
        return (T)brave.tracing();
    } else if (Tracer.class.equals(clazz)) {
        return (T)tracer;
    } else {
        throw new IllegalArgumentException("The class is '" + clazz
              + "'not supported and cannot be unwrapped");
    }
}
 
Example #17
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
		throws BeansException {
	LazyBean<HttpTracing> httpTracing = LazyBean.create(this.springContext,
			HttpTracing.class);
	if (bean instanceof HttpClient) {
		// This adds handlers to manage the span lifecycle. All require explicit
		// propagation of the current span as a reactor context property.
		// This done in mapConnect, added last so that it is setup first.
		// https://projectreactor.io/docs/core/release/reference/#_simple_context_examples

		// In our case, we treat a normal response no differently than one in
		// preparation of a redirect follow-up.
		TracingDoOnResponse doOnResponse = new TracingDoOnResponse(httpTracing);
		return ((HttpClient) bean)
				.doOnResponseError(new TracingDoOnErrorResponse(httpTracing))
				.doOnRedirect(doOnResponse).doOnResponse(doOnResponse)
				.doOnRequestError(new TracingDoOnErrorRequest(httpTracing))
				.doOnRequest(new TracingDoOnRequest(httpTracing))
				.mapConnect(new TracingMapConnect(() -> {
					HttpTracing ref = httpTracing.get();
					return ref != null ? ref.tracing().currentTraceContext().get()
							: null;
				}));
	}
	return bean;
}
 
Example #18
Source File: TraceRequestHttpHeadersFilter.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
AbstractHttpHeadersFilter(HttpTracing httpTracing) {
	this.tracer = httpTracing.tracing().tracer();
	this.extractor = httpTracing.tracing().propagation()
			.extractor(HttpClientRequest::header);
	this.handler = HttpClientHandler.create(httpTracing);
	this.httpTracing = httpTracing;
}
 
Example #19
Source File: TraceWebFilter.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
HttpServerHandler<HttpServerRequest, HttpServerResponse> handler() {
	if (this.handler == null) {
		this.handler = HttpServerHandler
				.create(this.beanFactory.getBean(HttpTracing.class));
	}
	return this.handler;
}
 
Example #20
Source File: JerseyServerBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public Set<Object> getSingletons() {
  return new LinkedHashSet<>(asList(new Resource(), TracingApplicationEventListener.create(
    HttpTracing.create(Tracing.newBuilder()
      .sampler(Sampler.NEVER_SAMPLE)
      .spanReporter(Reporter.NOOP)
      .build())
  )));
}
 
Example #21
Source File: HttpTracingFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void serverRequestSampler() {
  context = new XmlBeans(""
    + "<bean id=\"httpTracing\" class=\"brave.spring.beans.HttpTracingFactoryBean\">\n"
    + "  <property name=\"tracing\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".TRACING\"/>\n"
    + "  </property>\n"
    + "  <property name=\"serverSampler\">\n"
    + "    <bean class=\"brave.sampler.SamplerFunctions\" factory-method=\"neverSample\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("httpTracing", HttpTracing.class).serverRequestSampler())
    .isEqualTo(SamplerFunctions.neverSample());
}
 
Example #22
Source File: LazyClient.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private Client delegate() {
	if (this.delegate == null) {
		try {
			this.delegate = this.beanFactory.getBean(Client.class);
		}
		catch (BeansException ex) {
			this.delegate = TracingFeignClient.create(
					beanFactory.getBean(HttpTracing.class),
					new Client.Default(null, null));
		}
	}
	return this.delegate;
}
 
Example #23
Source File: BraveClientFeature.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Portable(final Tracing tracing) {
    this(
            HttpTracing
                    .newBuilder(tracing)
                    .clientParser(new HttpClientSpanParser())
                    .build()
    );
}
 
Example #24
Source File: HelloService.java    From talk-kafka-zipkin with MIT License 5 votes vote down vote up
@Override
public void run(HelloServiceConfiguration configuration, Environment environment) {
	/* START TRACING INSTRUMENTATION */
	final var sender = URLConnectionSender.newBuilder()
			.endpoint(configuration.getZipkinEndpoint()).build();
	final var reporter = AsyncReporter.builder(sender).build();
	final var tracing = Tracing.newBuilder().localServiceName("hello-service")
			.sampler(Sampler.ALWAYS_SAMPLE).spanReporter(reporter).build();
	final var httpTracing = HttpTracing.newBuilder(tracing).build();
	final var jerseyTracingFilter = TracingApplicationEventListener
			.create(httpTracing);
	environment.jersey().register(jerseyTracingFilter);
	/* END TRACING INSTRUMENTATION */

	// Without instrumentation
	// final HttpClient httpClient =
	// new
	// HttpClientBuilder(environment).using(configuration.getHttpClientConfiguration())
	// .build(getName());
	final var httpClient = TracingHttpClientBuilder.create(httpTracing).build();
	final var url = configuration.getTranslationServiceUrl() + "/translate";
	final var translationServiceClient = new HelloTranslationServiceClient(httpClient,
			url);

	final var helloResource = new HelloResource(translationServiceClient);
	environment.jersey().register(helloResource);

	final var helloServiceHealthCheck = new HelloServiceHealthCheck();
	environment.healthChecks().register("hello-service", helloServiceHealthCheck);
}
 
Example #25
Source File: HttpTracingFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void clientRequestSampler() {
  context = new XmlBeans(""
    + "<bean id=\"httpTracing\" class=\"brave.spring.beans.HttpTracingFactoryBean\">\n"
    + "  <property name=\"tracing\">\n"
    + "    <util:constant static-field=\"" + getClass().getName() + ".TRACING\"/>\n"
    + "  </property>\n"
    + "  <property name=\"clientSampler\">\n"
    + "    <bean class=\"brave.sampler.SamplerFunctions\" factory-method=\"neverSample\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("httpTracing", HttpTracing.class).clientRequestSampler())
    .isEqualTo(SamplerFunctions.neverSample());
}
 
Example #26
Source File: TracingClientHttpRequestInterceptorAutowireTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Bean HttpTracing httpTracing() {
  return HttpTracing.create(Tracing.newBuilder().build());
}
 
Example #27
Source File: TracingConfiguration.java    From brave-webmvc-example with MIT License 4 votes vote down vote up
/** Decides how to name and tag spans. By default they are named the same as the http method. */
@Bean HttpTracing httpTracing(Tracing tracing) {
  return HttpTracing.create(tracing);
}
 
Example #28
Source File: TracingCallFactory.java    From brave with Apache License 2.0 4 votes vote down vote up
public static Call.Factory create(HttpTracing httpTracing, OkHttpClient ok) {
  return new TracingCallFactory(httpTracing, ok);
}
 
Example #29
Source File: TracingProtocolExec.java    From brave with Apache License 2.0 4 votes vote down vote up
TracingProtocolExec(HttpTracing httpTracing, ClientExecChain protocolExec) {
  this.tracer = httpTracing.tracing().tracer();
  this.httpSampler = httpTracing.clientRequestSampler();
  this.handler = HttpClientHandler.create(httpTracing);
  this.protocolExec = protocolExec;
}
 
Example #30
Source File: TracingClientHttpRequestInterceptor.java    From brave with Apache License 2.0 4 votes vote down vote up
public static ClientHttpRequestInterceptor create(Tracing tracing) {
  return create(HttpTracing.create(tracing));
}