zipkin2.reporter.urlconnection.URLConnectionSender Java Examples

The following examples show how to use zipkin2.reporter.urlconnection.URLConnectionSender. 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: 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 #2
Source File: HttpZipkinFactory.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 HttpTracing instance
 */
@Override
public Optional<HttpTracing> build(final Environment environment) {
  if (!isEnabled()) {
    LOGGER.warn("Zipkin tracing is disabled");
    return Optional.empty();
  }

  final String endpoint = URI.create(baseUrl).resolve("api/v2/spans").toString();

  final URLConnectionSender sender =
      URLConnectionSender.newBuilder()
          .endpoint(endpoint)
          .readTimeout(Math.toIntExact(readTimeout.toMilliseconds()))
          .connectTimeout(Math.toIntExact(connectTimeout.toMilliseconds()))
          .build();

  LOGGER.info("Sending spans to HTTP collector at: {}", baseUrl);

  return buildTracing(environment, sender);
}
 
Example #3
Source File: WingtipsToZipkinLifecycleListenerTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void convenience_constructor_sets_fields_as_expected(boolean baseUrlTrailingSlash) throws MalformedURLException {
    // given
    String baseUrlWithoutTrailingSlash = "http://localhost:4242";
    String baseUrl = (baseUrlTrailingSlash)
                     ? baseUrlWithoutTrailingSlash + "/"
                     : baseUrlWithoutTrailingSlash;

    // when
    WingtipsToZipkinLifecycleListener listener = new WingtipsToZipkinLifecycleListener(serviceName, baseUrl);

    // then
    assertThat(listener.serviceName).isEqualTo(serviceName);
    assertThat(listener.zipkinEndpoint.serviceName()).isEqualTo(serviceName);
    assertThat(listener.zipkinSpanConverter).isInstanceOf(WingtipsToZipkinSpanConverterDefaultImpl.class);
    assertThat(listener.zipkinSpanReporter).isInstanceOf(AsyncReporter.class);
    Object spanSender = Whitebox.getInternalState(listener.zipkinSpanReporter, "sender");
    assertThat(spanSender).isInstanceOf(URLConnectionSender.class);
    assertThat(Whitebox.getInternalState(spanSender, "endpoint"))
        .isEqualTo(new URL(baseUrlWithoutTrailingSlash + "/api/v2/spans"));
}
 
Example #4
Source File: ZipkinTraceExporter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and registers the Zipkin Trace exporter to the OpenCensus library. Only one Zipkin
 * exporter can be registered at any point.
 *
 * @param configuration configuration for this exporter.
 * @throws IllegalStateException if a Zipkin exporter is already registered.
 * @since 0.22
 */
public static void createAndRegister(ZipkinExporterConfiguration configuration) {
  synchronized (monitor) {
    checkState(handler == null, "Zipkin exporter is already registered.");
    Sender sender = configuration.getSender();
    if (sender == null) {
      sender = URLConnectionSender.create(configuration.getV2Url());
    }
    Handler newHandler =
        new ZipkinExporterHandler(
            configuration.getEncoder(),
            sender,
            configuration.getServiceName(),
            configuration.getDeadline());
    handler = newHandler;
    register(Tracing.getExportComponent().getSpanExporter(), newHandler);
  }
}
 
Example #5
Source File: ZipkinTest.java    From hippo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
        URLConnectionSender sender = URLConnectionSender.create("http://103.10.0.67:9411/api/v2/spans");
        AsyncReporter reporter = AsyncReporter.builder(sender)
                .closeTimeout(100, TimeUnit.MILLISECONDS)
                .build(SpanBytesEncoder.JSON_V2);
        Tracing tracing = Tracing.newBuilder()
                .localServiceName("test1")
                .spanReporter(reporter)
                .propagationFactory(B3Propagation.FACTORY)
                .currentTraceContext(ThreadLocalCurrentTraceContext.create())
                .build();
        Tracer tracer = tracing.tracer();
        tracer.startScopedSpan("t1");
        Span span = tracer.newTrace().annotate("111").start();
        span.kind(Span.Kind.CLIENT);
       // span1.finish();
        // System.out.println(  span.context().traceId());
        //System.out.println(  span.context().spanId());
        //tracer.nextSpan().start();

       // Span span2=tracer.newChild(TraceContext.newBuilder().parentId(span.context().spanId()).traceId(span.context().traceId()).spanId(span.context().spanId()).build()).name("eeeee").annotate("222").start();
        // Span span2 = tracer.newChild(TraceContext.newBuilder().parentId(span.context().spanId()).traceId(span.context().traceId()).spanId(span.context().spanId()).build()).name("eeeee").start();
       // span2.kind(Span.Kind.SERVER);
//         System.out.println(  span.context().traceId());
//        System.out.println(  span.context().spanId());
        //System.out.println(span.annotate("").kind(Span.Kind.CLIENT));
        //Span action_1 = tracer.newChild(span.context()).name("action-1").start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //span1.finish();
            span.finish();
            //    action_1.finish();
        }
        Thread.sleep(100000000L);
    }
 
Example #6
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class) public void close_closesSender() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "</bean>"
  );

  URLConnectionSender sender = context.getBean("sender", URLConnectionSender.class);
  context.close();

  sender.sendSpans(Arrays.asList(new byte[] {'{', '}'}));
}
 
Example #7
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void encoding() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "  <property name=\"encoding\" value=\"PROTO3\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .extracting("encoding")
      .isEqualTo(Encoding.PROTO3);
}
 
Example #8
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void messageMaxBytes() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "  <property name=\"messageMaxBytes\" value=\"1024\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .extracting("messageMaxBytes")
      .isEqualTo(1024);
}
 
Example #9
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void compressionEnabled() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "  <property name=\"compressionEnabled\" value=\"false\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .extracting("compressionEnabled")
      .isEqualTo(false);
}
 
Example #10
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void readTimeout() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "  <property name=\"readTimeout\" value=\"0\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .isEqualToComparingFieldByField(URLConnectionSender.newBuilder()
          .endpoint("http://localhost:9411/api/v2/spans")
          .readTimeout(0).build());
}
 
Example #11
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void connectTimeout() {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "  <property name=\"connectTimeout\" value=\"0\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .isEqualToComparingFieldByField(URLConnectionSender.newBuilder()
          .endpoint("http://localhost:9411/api/v2/spans")
          .connectTimeout(0)
          .build());
}
 
Example #12
Source File: URLConnectionSenderFactoryBeanTest.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Test public void endpoint() throws MalformedURLException {
  context = new XmlBeans(""
      + "<bean id=\"sender\" class=\"zipkin2.reporter.beans.URLConnectionSenderFactoryBean\">\n"
      + "  <property name=\"endpoint\" value=\"http://localhost:9411/api/v2/spans\"/>\n"
      + "</bean>"
  );

  assertThat(context.getBean("sender", URLConnectionSender.class))
      .extracting("endpoint")
      .isEqualTo(URI.create("http://localhost:9411/api/v2/spans").toURL());
}
 
Example #13
Source File: URLConnectionSenderFactoryBean.java    From zipkin-reporter-java with Apache License 2.0 5 votes vote down vote up
@Override protected URLConnectionSender createInstance() {
  URLConnectionSender.Builder builder = URLConnectionSender.newBuilder();
  if (endpoint != null) builder.endpoint(endpoint);
  if (encoding != null) builder.encoding(encoding);
  if (connectTimeout != null) builder.connectTimeout(connectTimeout);
  if (readTimeout != null) builder.readTimeout(readTimeout);
  if (compressionEnabled != null) builder.compressionEnabled(compressionEnabled);
  if (messageMaxBytes != null) builder.messageMaxBytes(messageMaxBytes);
  return builder.build();
}
 
Example #14
Source File: WingtipsToZipkinLifecycleListener.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * @param postZipkinSpansBaseUrl The Zipkin base URL. This is everything except the endpoint path, i.e.
 * {@code http://foo.bar:9411}.
 * @return A new {@link AsyncReporter} that uses a basic {@link URLConnectionSender} for sending spans via HTTP to
 * the standard Zipkin {@code POST /api/v2/spans} endpoint.
 */
public static Reporter<zipkin2.Span> generateBasicZipkinReporter(String postZipkinSpansBaseUrl) {
    return AsyncReporter.create(
        URLConnectionSender.create(
            postZipkinSpansBaseUrl + (postZipkinSpansBaseUrl.endsWith("/") ? "" : "/") + "api/v2/spans"
        )
    );
}
 
Example #15
Source File: HelloConsumer.java    From talk-kafka-zipkin with MIT License 5 votes vote down vote up
public static void main(String[] args) {

		final var config = ConfigFactory.load();
		/* START TRACING INSTRUMENTATION */
		final var sender = URLConnectionSender.newBuilder()
				.endpoint(config.getString("zipkin.endpoint")).build();
		final var reporter = AsyncReporter.builder(sender).build();
		final var tracing = Tracing.newBuilder().localServiceName("hello-consumer")
				.sampler(Sampler.ALWAYS_SAMPLE).spanReporter(reporter).build();
		final var kafkaTracing = KafkaTracing.newBuilder(tracing)
				.remoteServiceName("kafka").build();
		/* END TRACING INSTRUMENTATION */

		final var consumerConfigs = new Properties();
		consumerConfigs.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
				config.getString("kafka.bootstrap-servers"));
		consumerConfigs.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
				StringDeserializer.class.getName());
		consumerConfigs.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
				StringDeserializer.class.getName());
		consumerConfigs.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "hello-consumer");
		consumerConfigs.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
				OffsetResetStrategy.EARLIEST.name().toLowerCase());
		final var kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs);
		final var tracingConsumer = kafkaTracing.consumer(kafkaConsumer);

		tracingConsumer.subscribe(Collections.singletonList("hello"));

		while (!Thread.interrupted()) {
			var records = tracingConsumer.poll(Duration.ofMillis(Long.MAX_VALUE));
			for (var record : records) {
				brave.Span span = kafkaTracing.nextSpan(record).name("print-hello")
						.start();
				span.annotate("starting printing");
				out.println(String.format("Record: %s", record));
				span.annotate("printing finished");
				span.finish();
			}
		}
	}
 
Example #16
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 #17
Source File: ZipkinSpanExporterEndToEndHttpTest.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
private static ZipkinSpanExporter buildZipkinExporter(
    String endpoint, Encoding encoding, SpanBytesEncoder encoder) {
  return ZipkinSpanExporter.newBuilder()
      .setSender(URLConnectionSender.newBuilder().endpoint(endpoint).encoding(encoding).build())
      .setServiceName(SERVICE_NAME)
      .setEncoder(encoder)
      .build();
}
 
Example #18
Source File: ZipkinRecordImpl.java    From hippo with Apache License 2.0 4 votes vote down vote up
@Override
public ZipkinResp start(ZipkinReq zipkinReq) {

    if (isInitError || zipkinReq == null || StringUtils.isBlank(zipkinUrl) || StringUtils.isBlank(zipkinReq.getServiceName())) {
        return null;
    }
    Tracing tracing = null;
    try {
        Span span;
        tracing = Tracing.newBuilder()
                .localServiceName(zipkinReq.getServiceName())
                .spanReporter(AsyncReporter.builder(URLConnectionSender.create(zipkinUrl))
                        .closeTimeout(100, TimeUnit.MILLISECONDS)
                        .build(SpanBytesEncoder.JSON_V2))
                .propagationFactory(B3Propagation.FACTORY)
                .currentTraceContext(ThreadLocalCurrentTraceContext.create())
                .build();
        if (zipkinReq.getParentSpanId() != null && zipkinReq.getParentTraceId() != null) {
            span = tracing.tracer().newChild(TraceContext.newBuilder()
                    .parentId(zipkinReq.getParentSpanId())
                    .traceId(zipkinReq.getParentTraceId())
                    .spanId(zipkinReq.getParentSpanId()).build());
        } else {
            span = tracing.tracer().newTrace();
        }

        if (StringUtils.isNotBlank(zipkinReq.getAnnotate())) {
            span.annotate(zipkinReq.getAnnotate());
        }
        if (StringUtils.isNotBlank(zipkinReq.getMethodName())) {
            span.name(zipkinReq.getMethodName());
        }

        if (zipkinReq.getSpanKind() != null) {
            if (zipkinReq.getSpanKind() == SpanKind.CLIENT) {
                span.kind(Span.Kind.CLIENT);
            } else {
                span.kind(Span.Kind.SERVER);
            }
        }
        if (zipkinReq.getTags() != null && !zipkinReq.getTags().isEmpty()) {
            for (String key : zipkinReq.getTags().keySet()) {
                span.tag(key, zipkinReq.getTags().get(key));
            }
        }
        span.start();
        ZipkinResp resp = new ZipkinResp();
        resp.setParentSpanId(Long.toHexString(span.context().spanId()));
        resp.setParentTraceId(Long.toHexString(span.context().traceId()));
        resp.setSpan(span);
        resp.setTracing(tracing);
        return resp;
    } catch (Exception e) {
        LOGGER.error("zipkin start error:" + zipkinUrl, e);
        close(tracing);
        isInitError = true;
    }
    return null;
}
 
Example #19
Source File: URLConnectionSenderBenchmarks.java    From zipkin-reporter-java with Apache License 2.0 4 votes vote down vote up
@Override Sender newHttpSender(String endpoint) {
  return URLConnectionSender.create(endpoint);
}
 
Example #20
Source File: URLConnectionSenderFactoryBean.java    From zipkin-reporter-java with Apache License 2.0 4 votes vote down vote up
@Override public Class<? extends URLConnectionSender> getObjectType() {
  return URLConnectionSender.class;
}
 
Example #21
Source File: URLConnectionSenderFactoryBean.java    From zipkin-reporter-java with Apache License 2.0 4 votes vote down vote up
@Override protected void destroyInstance(Object instance) {
  ((URLConnectionSender) instance).close();
}
 
Example #22
Source File: WingtipsWithZipkinSpringBootConfigurationTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "NULL_DEFAULT_OVERRIDES",
    "NO_OVERRIDES",
    "WITH_REPORTER_OVERRIDE",
    "WITH_CONVERTER_OVERRIDE",
    "WITH_REPORTER_AND_CONVERTER_OVERRIDE"
})
@Test
public void constructor_registers_WingtipsToZipkinLifecycleListener_with_expected_values(
    DefaultOverridesScenario scenario
) throws MalformedURLException {
    // given
    String baseUrl = "http://localhost:4242/" + UUID.randomUUID().toString();
    String serviceName = UUID.randomUUID().toString();
    WingtipsZipkinProperties props = generateProps(false, baseUrl, serviceName);

    // when
    new WingtipsWithZipkinSpringBootConfiguration(props, scenario.defaultOverrides);

    // then
    List<SpanLifecycleListener> listeners = Tracer.getInstance().getSpanLifecycleListeners();
    assertThat(listeners).hasSize(1);
    assertThat(listeners.get(0)).isInstanceOf(WingtipsToZipkinLifecycleListener.class);
    WingtipsToZipkinLifecycleListener listener = (WingtipsToZipkinLifecycleListener) listeners.get(0);

    assertThat(Whitebox.getInternalState(listener, "serviceName")).isEqualTo(serviceName);
    assertThat(Whitebox.getInternalState(listener, "zipkinEndpoint"))
        .isEqualTo(Endpoint.newBuilder().serviceName(serviceName).build());
    assertThat(Whitebox.getInternalState(listener, "zipkinSpanConverter")).isNotNull();

    Object zipkinSpanReporter = Whitebox.getInternalState(listener, "zipkinSpanReporter");
    Object zipkinSpanConverter = Whitebox.getInternalState(listener, "zipkinSpanConverter");

    if (scenario.defaultOverrides != null) {
        if (scenario.defaultOverrides.zipkinReporter != null) {
            assertThat(zipkinSpanReporter).isSameAs(scenario.defaultOverrides.zipkinReporter);
        }

        if (scenario.defaultOverrides.zipkinSpanConverter != null) {
            assertThat(zipkinSpanConverter).isSameAs(scenario.defaultOverrides.zipkinSpanConverter);
        }
    }

    if (scenario.defaultOverrides == null || scenario.defaultOverrides.zipkinReporter == null) {
        assertThat(zipkinSpanReporter).isInstanceOf(AsyncReporter.class);
        Object spanSender = Whitebox.getInternalState(zipkinSpanReporter, "sender");
        assertThat(spanSender).isInstanceOf(URLConnectionSender.class);
        assertThat(Whitebox.getInternalState(spanSender, "endpoint"))
            .isEqualTo(new URL(baseUrl + "/api/v2/spans"));
    }
    
    if (scenario.defaultOverrides == null || scenario.defaultOverrides.zipkinSpanConverter == null) {
        assertThat(zipkinSpanConverter).isInstanceOf(WingtipsToZipkinSpanConverterDefaultImpl.class);
    }
}
 
Example #23
Source File: WingtipsWithZipkinSpringBoot2WebfluxConfigurationTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "NULL_DEFAULT_OVERRIDES",
    "NO_OVERRIDES",
    "WITH_REPORTER_OVERRIDE",
    "WITH_CONVERTER_OVERRIDE",
    "WITH_REPORTER_AND_CONVERTER_OVERRIDE"
})
@Test
public void constructor_registers_WingtipsToZipkinLifecycleListener_with_expected_values(
    DefaultOverridesScenario scenario
) throws MalformedURLException {
    // given
    String baseUrl = "http://localhost:4242/" + UUID.randomUUID().toString();
    String serviceName = UUID.randomUUID().toString();
    WingtipsZipkinProperties props = generateProps(false, baseUrl, serviceName);

    // when
    WingtipsWithZipkinSpringBoot2WebfluxConfiguration config =
        new WingtipsWithZipkinSpringBoot2WebfluxConfiguration(props, scenario.defaultOverrides);

    // then
    assertThat(config.wingtipsZipkinProperties).isSameAs(props);

    List<SpanLifecycleListener> listeners = Tracer.getInstance().getSpanLifecycleListeners();
    assertThat(listeners).hasSize(1);
    assertThat(listeners.get(0)).isInstanceOf(WingtipsToZipkinLifecycleListener.class);
    WingtipsToZipkinLifecycleListener listener = (WingtipsToZipkinLifecycleListener) listeners.get(0);

    assertThat(Whitebox.getInternalState(listener, "serviceName")).isEqualTo(serviceName);
    assertThat(Whitebox.getInternalState(listener, "zipkinEndpoint"))
        .isEqualTo(Endpoint.newBuilder().serviceName(serviceName).build());
    assertThat(Whitebox.getInternalState(listener, "zipkinSpanConverter")).isNotNull();

    Object zipkinSpanReporter = Whitebox.getInternalState(listener, "zipkinSpanReporter");
    Object zipkinSpanConverter = Whitebox.getInternalState(listener, "zipkinSpanConverter");

    if (scenario.defaultOverrides != null) {
        assertThat(config.zipkinReporterOverride).isSameAs(scenario.defaultOverrides.zipkinReporter);
        assertThat(config.zipkinSpanConverterOverride).isSameAs(scenario.defaultOverrides.zipkinSpanConverter);

        if (scenario.defaultOverrides.zipkinReporter != null) {
            assertThat(zipkinSpanReporter).isSameAs(scenario.defaultOverrides.zipkinReporter);
        }

        if (scenario.defaultOverrides.zipkinSpanConverter != null) {
            assertThat(zipkinSpanConverter).isSameAs(scenario.defaultOverrides.zipkinSpanConverter);
        }
    }

    if (scenario.defaultOverrides == null || scenario.defaultOverrides.zipkinReporter == null) {
        assertThat(zipkinSpanReporter).isInstanceOf(AsyncReporter.class);
        Object spanSender = Whitebox.getInternalState(zipkinSpanReporter, "sender");
        assertThat(spanSender).isInstanceOf(URLConnectionSender.class);
        assertThat(Whitebox.getInternalState(spanSender, "endpoint"))
            .isEqualTo(new URL(baseUrl + "/api/v2/spans"));

        assertThat(config.zipkinReporterOverride).isNull();
    }
    
    if (scenario.defaultOverrides == null || scenario.defaultOverrides.zipkinSpanConverter == null) {
        assertThat(zipkinSpanConverter).isInstanceOf(WingtipsToZipkinSpanConverterDefaultImpl.class);
        assertThat(config.zipkinSpanConverterOverride).isNull();
    }
}
 
Example #24
Source File: TwitterConsoleConsumer.java    From talk-kafka-zipkin with MIT License 4 votes vote down vote up
public static void main(String[] args) {

		final var config = ConfigFactory.load();
		final var kafkaBootstrapServers = config.getString("kafka.bootstrap-servers");
		final var schemaRegistryUrl = config.getString("schema-registry.url");

		/* START TRACING INSTRUMENTATION */
		final var sender = URLConnectionSender.newBuilder()
				.endpoint(config.getString("zipkin.endpoint")).build();
		final var reporter = AsyncReporter.builder(sender).build();
		final var tracing = Tracing.newBuilder()
				.localServiceName("twitter-console-consumer")
				.sampler(Sampler.ALWAYS_SAMPLE).spanReporter(reporter).build();
		final var kafkaTracing = KafkaTracing.newBuilder(tracing)
				.remoteServiceName("kafka").build();
		/* END TRACING INSTRUMENTATION */

		final var consumerConfigs = new Properties();
		consumerConfigs.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
				kafkaBootstrapServers);
		consumerConfigs.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
				StringDeserializer.class.getName());
		consumerConfigs.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
				SpecificAvroDeserializer.class.getName());
		consumerConfigs.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
				schemaRegistryUrl);
		consumerConfigs.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "twitter-console");
		final var kafkaConsumer = new KafkaConsumer<String, Tweet>(consumerConfigs);
		final var tracingConsumer = kafkaTracing.consumer(kafkaConsumer);

		tracingConsumer.subscribe(
				Collections.singletonList(config.getString("topics.input-tweets")));

		while (!Thread.interrupted()) {
			final var records = tracingConsumer.poll(Duration.ofMillis(Long.MAX_VALUE));
			for (var record : records) {
				var span = kafkaTracing.nextSpan(record).name("print-hello").start();
				try (var ignored = tracing.tracer().withSpanInScope(span)) {
					span.annotate("starting printing");
					out.println(String.format("Record: %s", record));
					span.annotate("printing finished");
				}
				catch (RuntimeException | Error e) {
					span.error(e);
					throw e;
				}
				finally {
					span.finish();
				}
			}
		}

	}
 
Example #25
Source File: ZipkinSpanExporter.java    From opentelemetry-java with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the zipkin endpoint. This will use the endpoint to assign a {@link URLConnectionSender}
 * instance to this builder.
 *
 * @param endpoint The Zipkin endpoint URL, ex. "http://zipkinhost:9411/api/v2/spans".
 * @return this.
 * @see URLConnectionSender
 * @since 0.4.0
 */
public Builder setEndpoint(String endpoint) {
  setSender(URLConnectionSender.create(endpoint));
  return this;
}