Fixed checkstyle issues

This commit is contained in:
Marcin Grzejszczak
2016-01-20 12:36:38 +01:00
parent 1084ca1126
commit 7b6a533498
34 changed files with 491 additions and 462 deletions

View File

@@ -3,11 +3,11 @@
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- this. in front of fields -->
<module name="RequireThis">
<property name="checkMethods" value="false"/>
</module>
<module name="TreeWalker">
<!-- this. in front of fields -->
<module name="RequireThis">
<property name="checkMethods" value="false"/>
</module>
<!-- tabs instead of spaces -->
<module name="RegexpSinglelineJava">
<property name="format" value="^\t* "/>

14
pom.xml
View File

@@ -106,17 +106,19 @@
</dependencies>
<executions>
<execution>
<id>verify-style</id>
<phase>process-classes</phase>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<headerLocation>LICENSE.txt</headerLocation>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<logViolationsToConsole>true</logViolationsToConsole>
<failOnViolation>false</failOnViolation>
</configuration>
</plugin>
</plugins>
</build>

View File

@@ -48,7 +48,7 @@ public class TraceAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public DefaultTracer traceManager(Sampler sampler,
ApplicationEventPublisher publisher) {
ApplicationEventPublisher publisher) {
return new DefaultTracer(sampler, random(), publisher);
}
}

View File

@@ -16,13 +16,12 @@
package org.springframework.cloud.sleuth.event;
import java.util.ArrayList;
import lombok.Value;
import org.springframework.cloud.sleuth.Span;
import org.springframework.context.ApplicationListener;
import java.util.ArrayList;
/**
* @author Spencer Gibb
*/
@@ -32,6 +31,6 @@ public class ArrayListSpanAccumulator implements ApplicationListener<SpanRelease
@Override
public void onApplicationEvent(SpanReleasedEvent event) {
spans.add(event.getSpan());
this.spans.add(event.getSpan());
}
}

View File

@@ -25,6 +25,6 @@ public class SleuthHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return new TraceCallable<>(tracer, callable);
return new TraceCallable<>(this.tracer, callable);
}
}

View File

@@ -71,7 +71,7 @@ public abstract class TraceCommand<R> extends HystrixCommand<R> {
@Override
protected R run() throws Exception {
enforceThatHystrixThreadIsNotPollutedByPreviousTraces();
Span span = this.tracer.joinTrace(getCommandKey().name(), parentSpan);
Span span = this.tracer.joinTrace(getCommandKey().name(), this.parentSpan);
try {
return doRun();
} finally {

View File

@@ -15,76 +15,79 @@
*/
package org.springframework.cloud.sleuth.instrument.web.client;
import static feign.Util.checkNotNull;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import feign.InvocationHandlerFactory;
import feign.InvocationHandlerFactory.MethodHandler;
import feign.Target;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.instrument.hystrix.TraceCommand;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.instrument.hystrix.TraceCommand;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import feign.InvocationHandlerFactory;
import feign.InvocationHandlerFactory.MethodHandler;
import feign.Target;
import static feign.Util.checkNotNull;
/**
* Wraps execution in Sleuth's TraceCommand
*/
final class SleuthHystrixInvocationHandler implements InvocationHandler {
private final Target<?> target;
private final Map<Method, MethodHandler> dispatch;
private final Tracer tracer;
private final Target<?> target;
private final Map<Method, MethodHandler> dispatch;
private final Tracer tracer;
SleuthHystrixInvocationHandler(Target<?> target, Map<Method, MethodHandler> dispatch, Tracer tracer) {
this.tracer = checkNotNull(tracer, "traceManager");
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
}
SleuthHystrixInvocationHandler(Target<?> target, Map<Method, MethodHandler> dispatch,
Tracer tracer) {
this.tracer = checkNotNull(tracer, "traceManager");
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
String groupKey = this.target.name();
String commandKey = method.getName();
HystrixCommand.Setter setter = HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
@Override public Object invoke(final Object proxy, final Method method,
final Object[] args) throws Throwable {
String groupKey = this.target.name();
String commandKey = method.getName();
HystrixCommand.Setter setter = HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
HystrixCommand<Object> hystrixCommand = new TraceCommand<Object>(this.tracer, setter) {
@Override
public Object doRun() throws Exception {
try {
return SleuthHystrixInvocationHandler.this.dispatch.get(method).invoke(args);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw (Error)t;
}
}
};
HystrixCommand<Object> hystrixCommand = new TraceCommand<Object>(this.tracer,
setter) {
@Override public Object doRun() throws Exception {
try {
return SleuthHystrixInvocationHandler.this.dispatch.get(method)
.invoke(args);
}
catch (Exception e) {
throw e;
}
catch (Throwable t) {
throw (Error) t;
}
}
};
if (HystrixCommand.class.isAssignableFrom(method.getReturnType())) {
return hystrixCommand;
}
return hystrixCommand.execute();
}
if (HystrixCommand.class.isAssignableFrom(method.getReturnType())) {
return hystrixCommand;
}
return hystrixCommand.execute();
}
static final class Factory implements InvocationHandlerFactory {
static final class Factory implements InvocationHandlerFactory {
private final Tracer tracer;
private final Tracer tracer;
public Factory(Tracer tracer) {
this.tracer = tracer;
}
public Factory(Tracer tracer) {
this.tracer = tracer;
}
@Override
public InvocationHandler create(@SuppressWarnings("rawtypes") Target target, Map<Method, MethodHandler> dispatch) {
return new SleuthHystrixInvocationHandler(target, dispatch, this.tracer);
}
}
@Override public InvocationHandler create(
@SuppressWarnings("rawtypes") Target target,
Map<Method, MethodHandler> dispatch) {
return new SleuthHystrixInvocationHandler(target, dispatch, this.tracer);
}
}
}

View File

@@ -44,7 +44,7 @@ public class DefaultTracer implements Tracer {
private final Random random;
public DefaultTracer(Sampler defaultSampler,
Random random, ApplicationEventPublisher publisher) {
Random random, ApplicationEventPublisher publisher) {
this.defaultSampler = defaultSampler;
this.random = random;
this.publisher = publisher;
@@ -159,7 +159,7 @@ public class DefaultTracer implements Tracer {
}
private long createId() {
return random.nextLong();
return this.random.nextLong();
}
@Override

View File

@@ -39,13 +39,13 @@ public class SpanPassingForHystrixViaAnnotationsIntegrationTests {
}
private Span givenASpanInCurrentThread() {
Span span = tracer.startTrace("existing");
tracer.continueSpan(span);
Span span = this.tracer.startTrace("existing");
this.tracer.continueSpan(span);
return span;
}
private void whenHystrixCommandAnnotatedMethodGetsExecuted() {
hystrixCommandInvocationSpanCatcher.invokeLogicWrappedInHystrixCommand();
this.hystrixCommandInvocationSpanCatcher.invokeLogicWrappedInHystrixCommand();
}
private void thenTraceIdIsPassedFromTheCurrentThreadToTheHystrixOne(final Span span) {
@@ -53,8 +53,8 @@ public class SpanPassingForHystrixViaAnnotationsIntegrationTests {
@Override
public void run() {
then(span)
.hasTraceIdEqualTo(hystrixCommandInvocationSpanCatcher.getTraceId())
.hasNameNotEqualTo(hystrixCommandInvocationSpanCatcher.getSpanName());
.hasTraceIdEqualTo(SpanPassingForHystrixViaAnnotationsIntegrationTests.this.hystrixCommandInvocationSpanCatcher.getTraceId())
.hasNameNotEqualTo(SpanPassingForHystrixViaAnnotationsIntegrationTests.this.hystrixCommandInvocationSpanCatcher.getSpanName());
}
});
}
@@ -81,24 +81,24 @@ public class SpanPassingForHystrixViaAnnotationsIntegrationTests {
@HystrixCommand
public void invokeLogicWrappedInHystrixCommand() {
spanCaughtFromHystrixThread = new AtomicReference<>(SpanContextHolder.getCurrentSpan());
this.spanCaughtFromHystrixThread = new AtomicReference<>(SpanContextHolder.getCurrentSpan());
}
public Long getTraceId() {
if (spanCaughtFromHystrixThread == null ||
spanCaughtFromHystrixThread.get() == null) {
if (this.spanCaughtFromHystrixThread == null ||
this.spanCaughtFromHystrixThread.get() == null) {
return null;
}
return spanCaughtFromHystrixThread.get().getTraceId();
return this.spanCaughtFromHystrixThread.get().getTraceId();
}
public String getSpanName() {
if (spanCaughtFromHystrixThread == null ||
(spanCaughtFromHystrixThread.get() != null &&
spanCaughtFromHystrixThread.get().getName() == null)) {
if (this.spanCaughtFromHystrixThread == null ||
(this.spanCaughtFromHystrixThread.get() != null &&
this.spanCaughtFromHystrixThread.get().getName() == null)) {
return null;
}
return spanCaughtFromHystrixThread.get().getName();
return this.spanCaughtFromHystrixThread.get().getName();
}
}
}

View File

@@ -40,13 +40,13 @@ public class TraceAsyncIntegrationTests {
}
private Span givenASpanInCurrentThread() {
Span span = tracer.startTrace("existing");
tracer.continueSpan(span);
Span span = this.tracer.startTrace("existing");
this.tracer.continueSpan(span);
return span;
}
private void whenAsyncProcessingTakesPlace() {
classPerformingAsyncLogic.invokeAsynchronousLogic();
this.classPerformingAsyncLogic.invokeAsynchronousLogic();
}
private void thenTraceIdIsPassedFromTheCurrentThreadToTheAsyncOne(final Span span) {
@@ -54,8 +54,8 @@ public class TraceAsyncIntegrationTests {
@Override
public void run() {
then(span)
.hasTraceIdEqualTo(classPerformingAsyncLogic.getTraceId())
.hasNameNotEqualTo(classPerformingAsyncLogic.getSpanName());
.hasTraceIdEqualTo(TraceAsyncIntegrationTests.this.classPerformingAsyncLogic.getTraceId())
.hasNameNotEqualTo(TraceAsyncIntegrationTests.this.classPerformingAsyncLogic.getSpanName());
}
});
}
@@ -83,21 +83,21 @@ public class TraceAsyncIntegrationTests {
@Async
public void invokeAsynchronousLogic() {
span.set(SpanContextHolder.getCurrentSpan());
this.span.set(SpanContextHolder.getCurrentSpan());
}
public Long getTraceId() {
if (span.get() == null) {
if (this.span.get() == null) {
return null;
}
return span.get().getTraceId();
return this.span.get().getTraceId();
}
public String getSpanName() {
if (span.get() != null && span.get().getName() == null) {
if (this.span.get() != null && this.span.get().getName() == null) {
return null;
}
return span.get().getName();
return this.span.get().getName();
}
}
}

View File

@@ -38,7 +38,7 @@ public class SampleBackground {
@SneakyThrows
@Async
public void background() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("background-sleep-millis", String.valueOf(millis));
}

View File

@@ -36,7 +36,7 @@ public class IntegrationTestZipkinSpanReporter implements ZipkinSpanReporter {
@Override
public void report(Span span) {
log.debug(span);
hashedSpans.add(span);
this.hashedSpans.add(span);
}
}

View File

@@ -74,7 +74,7 @@ public class MessagingApplicationTests extends AbstractIntegrationTest {
}
private void thenThereIsAtLeastOneBinaryAnnotationWithKey(String binaryAnnotationKey) {
then(integrationTestSpanCollector.hashedSpans.stream()
then(this.integrationTestSpanCollector.hashedSpans.stream()
.map(s -> s.binaryAnnotations)
.flatMap(Collection::stream)
.anyMatch(b -> b.key.equals(binaryAnnotationKey))).isTrue();

View File

@@ -39,7 +39,7 @@ public class SampleController {
@SneakyThrows
@RequestMapping("/")
public String hi() {
Thread.sleep(random.nextInt(1000));
Thread.sleep(this.random.nextInt(1000));
String s = this.restTemplate.getForObject("http://zipkin/hi2", String.class);
return "hi/" + s;
}

View File

@@ -54,7 +54,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/")
public String hi() {
Thread.sleep(random.nextInt(1000));
Thread.sleep(this.random.nextInt(1000));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/hi2", String.class);
@@ -66,7 +66,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
return new Callable<String>() {
@Override
public String call() throws Exception {
int millis = random.nextInt(1000);
int millis = SampleController.this.random.nextInt(1000);
Thread.sleep(millis);
SampleController.this.tracer.addTag("callable-sleep-millis", String.valueOf(millis));
Span currentSpan = SampleController.this.accessor.getCurrentSpan();
@@ -84,7 +84,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/hi2")
public String hi2() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
return "hi2";
@@ -95,7 +95,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
public String traced() {
Span span = this.tracer.startTrace("customTraceEndpoint",
new AlwaysSampler());
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
@@ -109,7 +109,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/start")
public String start() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));

View File

@@ -48,8 +48,9 @@ public class RequestSendingRunnable implements Runnable {
@Override
public void run() {
log.info("Sending the request to url [{}] with trace id in headers [{}]", url, traceId);
ResponseEntity<String> responseEntity = restTemplate.exchange(requestWithTraceId(traceId), String.class);
log.info("Sending the request to url [{}] with trace id in headers [{}]", this.url, this.traceId);
ResponseEntity<String> responseEntity =
this.restTemplate.exchange(requestWithTraceId(this.traceId), String.class);
then(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
log.info("Received the following response [{}]", responseEntity);
}
@@ -57,7 +58,7 @@ public class RequestSendingRunnable implements Runnable {
private RequestEntity requestWithTraceId(long traceId) {
HttpHeaders headers = new HttpHeaders();
headers.add(Span.TRACE_ID_NAME, Span.toHex(traceId));
URI uri = URI.create(url);
URI uri = URI.create(this.url);
RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, uri);
log.info("Request [" + requestEntity + "] is ready");
return requestEntity;

View File

@@ -38,7 +38,7 @@ public class SampleBackground {
@SneakyThrows
@Async
public void background() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("background-sleep-millis", String.valueOf(millis));
}

View File

@@ -54,7 +54,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/")
public String hi() {
Thread.sleep(random.nextInt(1000));
Thread.sleep(this.random.nextInt(1000));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/hi2", String.class);
@@ -66,7 +66,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
return new Callable<String>() {
@Override
public String call() throws Exception {
int millis = random.nextInt(1000);
int millis = SampleController.this.random.nextInt(1000);
Thread.sleep(millis);
SampleController.this.tracer.addTag("callable-sleep-millis", String.valueOf(millis));
Span currentSpan = SampleController.this.accessor.getCurrentSpan();
@@ -84,7 +84,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/hi2")
public String hi2() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
return "hi2";
@@ -95,7 +95,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
public String traced() {
Span span = this.tracer.startTrace("customTraceEndpoint",
new AlwaysSampler());
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
@@ -109,7 +109,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/start")
public String start() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));

View File

@@ -38,7 +38,7 @@ public class SampleBackground {
@SneakyThrows
@Async
public void background() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("background-sleep-millis", String.valueOf(millis));
}

View File

@@ -54,7 +54,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/")
public String hi() {
Thread.sleep(random.nextInt(1000));
Thread.sleep(this.random.nextInt(1000));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/hi2", String.class);
@@ -66,7 +66,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
return new Callable<String>() {
@Override
public String call() throws Exception {
int millis = random.nextInt(1000);
int millis = SampleController.this.random.nextInt(1000);
Thread.sleep(millis);
SampleController.this.tracer.addTag("callable-sleep-millis", String.valueOf(millis));
Span currentSpan = SampleController.this.accessor.getCurrentSpan();
@@ -84,7 +84,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/hi2")
public String hi2() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
return "hi2";
@@ -95,7 +95,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
public String traced() {
Span span = this.tracer.startTrace("customTraceEndpoint",
new AlwaysSampler());
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));
@@ -109,7 +109,7 @@ ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@SneakyThrows
@RequestMapping("/start")
public String start() {
int millis = random.nextInt(1000);
int millis = this.random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.tracer.addTag("random-sleep-millis", String.valueOf(millis));

View File

@@ -27,42 +27,44 @@ import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class ServerPropertiesHostLocatorTests {
Span span = new Span(1, 3, "name", 1L, Collections.<Long>emptyList(), 2L, true, true,
"process");
Span span = new Span(1, 3, "name", 1L, Collections.<Long>emptyList(), 2L, true, true,
"process");
@Test
public void portDefaultsTo8080() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(new ServerProperties(), "unknown");
@Test
public void portDefaultsTo8080() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(
new ServerProperties(), "unknown");
assertThat(locator.locate(span).getPort()).isEqualTo((short) 8080);
}
assertThat(locator.locate(this.span).getPort()).isEqualTo((short) 8080);
}
@Test
public void portFromServerProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(1234);
@Test
public void portFromServerProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(1234);
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties, "unknown");
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties,
"unknown");
assertThat(locator.locate(span).getPort()).isEqualTo((short) 1234);
}
assertThat(locator.locate(this.span).getPort()).isEqualTo((short) 1234);
}
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(new ServerProperties(), "unknown");
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(
new ServerProperties(), "unknown");
assertThat(locator.locate(span).getAddress())
.isEqualTo("127.0.0.1");
}
assertThat(locator.locate(this.span).getAddress()).isEqualTo("127.0.0.1");
}
@Test
public void hostFromServerPropertiesIp() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
properties.setAddress(InetAddress.getByAddress(new byte[]{1, 2, 3, 4}));
@Test
public void hostFromServerPropertiesIp() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
properties.setAddress(InetAddress.getByAddress(new byte[] { 1, 2, 3, 4 }));
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties, "unknown");
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties,
"unknown");
assertThat(locator.locate(span).getAddress())
.isEqualTo("1.2.3.4");
}
assertThat(locator.locate(this.span).getAddress()).isEqualTo("1.2.3.4");
}
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.cloud.sleuth.zipkin.stream;
import java.util.Iterator;
import java.util.NoSuchElementException;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.stream.Host;
@@ -24,55 +22,62 @@ import org.springframework.cloud.sleuth.stream.SleuthSink;
import org.springframework.cloud.sleuth.stream.Spans;
import zipkin.Sampler;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* This converts sleuth spans to zipkin ones, skipping invalid or unsampled.
*/
@CommonsLog
final class SamplingZipkinSpanIterator implements Iterator<zipkin.Span> {
private final Sampler sampler;
private final Iterator<Span> delegate;
private final Host host;
private zipkin.Span peeked;
private final Sampler sampler;
private final Iterator<Span> delegate;
private final Host host;
private zipkin.Span peeked;
SamplingZipkinSpanIterator(Sampler sampler, Spans input) {
this.sampler = sampler;
this.delegate = input.getSpans().iterator();
this.host = input.getHost();
}
SamplingZipkinSpanIterator(Sampler sampler, Spans input) {
this.sampler = sampler;
this.delegate = input.getSpans().iterator();
this.host = input.getHost();
}
@Override
public boolean hasNext() {
while (peeked == null && delegate.hasNext()) {
peeked = convertAndSample(delegate.next(), host);
}
return peeked != null;
}
@Override
public boolean hasNext() {
while (this.peeked == null && this.delegate.hasNext()) {
this.peeked = convertAndSample(this.delegate.next(), this.host);
}
return this.peeked != null;
}
@Override
public zipkin.Span next() {
// implicitly peeks
if (!hasNext()) throw new NoSuchElementException();
zipkin.Span result = peeked;
peeked = null;
return result;
}
@Override
public zipkin.Span next() {
// implicitly peeks
if (!hasNext())
throw new NoSuchElementException();
zipkin.Span result = this.peeked;
this.peeked = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
/** returns a converted span or null if it is invalid or unsampled. */
zipkin.Span convertAndSample(Span input, Host host) {
if (!input.getName().equals("message/" + SleuthSink.INPUT)) {
zipkin.Span result = ZipkinMessageListener.convert(input, host);
if (this.sampler.isSampled(result.traceId)) {
return result;
}
} else {
log.warn("Message tracing cycle detected for: " + input);
}
return null;
}
/**
* returns a converted span or null if it is invalid or unsampled.
*/
zipkin.Span convertAndSample(Span input, Host host) {
if (!input.getName().equals("message/" + SleuthSink.INPUT)) {
zipkin.Span result = ZipkinMessageListener.convert(input, host);
if (this.sampler.isSampled(result.traceId)) {
return result;
}
}
else {
log.warn("Message tracing cycle detected for: " + input);
}
return null;
}
}

View File

@@ -48,7 +48,7 @@ public class ZipkinMessageListener {
@ServiceActivator(inputChannel = SleuthSink.INPUT)
public void sink(Spans input) {
Iterator<zipkin.Span> sampled = new SamplingZipkinSpanIterator(sampler, input);
Iterator<zipkin.Span> sampled = new SamplingZipkinSpanIterator(this.sampler, input);
if (sampled.hasNext()) {
this.spanStore.accept(sampled);
}

View File

@@ -31,46 +31,52 @@ import static org.assertj.core.api.Assertions.assertThat;
public class SamplingZipkinSpanIteratorTests {
Host host = new Host("myservice", "1.2.3.4", 8080);
Host host = new Host("myservice", "1.2.3.4", 8080);
@Test
public void skipsInputSpans() {
Spans spans = new Spans(host, Collections.singletonList(span("message/sleuth")));
@Test
public void skipsInputSpans() {
Spans spans = new Spans(this.host,
Collections.singletonList(span("message/sleuth")));
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(Sampler.create(1.0f), spans);
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(
Sampler.create(1.0f), spans);
assertThat(result).isEmpty();
}
assertThat(result).isEmpty();
}
@Test
public void retainsValidSpans() {
Spans spans = new Spans(host, Arrays.asList(span("foo"), span("bar"), span("baz")));
@Test
public void retainsValidSpans() {
Spans spans = new Spans(this.host,
Arrays.asList(span("foo"), span("bar"), span("baz")));
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(Sampler.create(1.0f), spans);
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(
Sampler.create(1.0f), spans);
assertThat(result).extracting(s -> s.name).containsExactly("foo", "bar", "baz");
}
assertThat(result).extracting(s -> s.name).containsExactly("foo", "bar", "baz");
}
@Test
public void retainsOnlySampledSpans() {
Spans spans = new Spans(host, Arrays.asList(span("foo"), span("bar"), span("baz")));
@Test
public void retainsOnlySampledSpans() {
Spans spans = new Spans(this.host,
Arrays.asList(span("foo"), span("bar"), span("baz")));
Sampler everyOtherSampler = new Sampler() {
AtomicInteger counter = new AtomicInteger();
Sampler everyOtherSampler = new Sampler() {
AtomicInteger counter = new AtomicInteger();
public boolean isSampled(long l) {
return counter.getAndIncrement() % 2 == 0;
}
};
public boolean isSampled(long l) {
return counter.getAndIncrement() % 2 == 0;
}
};
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(everyOtherSampler, spans);
Iterator<zipkin.Span> result = new SamplingZipkinSpanIterator(everyOtherSampler,
spans);
assertThat(result).extracting(s -> s.name).containsExactly("foo", "baz");
}
assertThat(result).extracting(s -> s.name).containsExactly("foo", "baz");
}
Span span(String name) {
Long id = new Random().nextLong();
return new Span(1, 3, name, id, Collections.<Long>emptyList(), id, true, true,
"process");
}
Span span(String name) {
Long id = new Random().nextLong();
return new Span(1, 3, name, id, Collections.<Long>emptyList(), id, true, true,
"process");
}
}

View File

@@ -36,14 +36,14 @@ public class ZipkinMessageListenerTests {
@Test
public void convertsTimestampAndDurationToMicroseconds() {
long start = System.currentTimeMillis();
span.log("http/request/retry"); // System.currentTimeMillis
this.span.log("http/request/retry"); // System.currentTimeMillis
zipkin.Span result = ZipkinMessageListener.convert(span, host);
zipkin.Span result = ZipkinMessageListener.convert(this.span, this.host);
assertThat(result.timestamp)
.isEqualTo(span.getBegin() * 1000);
.isEqualTo(this.span.getBegin() * 1000);
assertThat(result.duration)
.isEqualTo((span.getEnd() - span.getBegin()) * 1000);
.isEqualTo((this.span.getEnd() - this.span.getBegin()) * 1000);
assertThat(result.annotations.get(0).timestamp)
.isGreaterThanOrEqualTo(start * 1000)
.isLessThanOrEqualTo(System.currentTimeMillis() * 1000);
@@ -52,13 +52,13 @@ public class ZipkinMessageListenerTests {
/** Sleuth host corresponds to annotation/binaryAnnotation.host in zipkin. */
@Test
public void annotationsIncludeHost() {
span.log("http/request/retry");
span.tag("spring-boot/version", "1.3.1.RELEASE");
this.span.log("http/request/retry");
this.span.tag("spring-boot/version", "1.3.1.RELEASE");
zipkin.Span result = ZipkinMessageListener.convert(span, host);
zipkin.Span result = ZipkinMessageListener.convert(this.span, this.host);
assertThat(result.annotations.get(0).endpoint)
.isEqualTo(endpoint);
.isEqualTo(this.endpoint);
assertThat(result.binaryAnnotations.get(0).endpoint)
.isEqualTo(result.annotations.get(0).endpoint);
}
@@ -70,11 +70,11 @@ public class ZipkinMessageListenerTests {
*/
@Test
public void spanWithoutAnnotationsLogsComponent() {
zipkin.Span result = ZipkinMessageListener.convert(span, host);
zipkin.Span result = ZipkinMessageListener.convert(this.span, this.host);
assertThat(result.binaryAnnotations).hasSize(1);
assertThat(result.binaryAnnotations.get(0)).isEqualToComparingFieldByField(
BinaryAnnotation.create("lc", span.getProcessId(), endpoint));
BinaryAnnotation.create("lc", this.span.getProcessId(), this.endpoint));
}
// TODO: "unknown" bc process id, documented as not nullable, is null in some tests.
@@ -82,9 +82,9 @@ public class ZipkinMessageListenerTests {
public void nullProcessIdCoercesToUnknownServiceName() {
Span noProcessId = Span.builder().traceId(1L).name("parent").remote(true).build();
zipkin.Span result = ZipkinMessageListener.convert(noProcessId, host);
zipkin.Span result = ZipkinMessageListener.convert(noProcessId, this.host);
assertThat(result.binaryAnnotations)
.containsOnly(BinaryAnnotation.create("lc", "unknown", endpoint));
.containsOnly(BinaryAnnotation.create("lc", "unknown", this.endpoint));
}
}

View File

@@ -14,21 +14,21 @@ public class FallbackHavingEndpointLocator implements EndpointLocator {
private final ServerPropertiesEndpointLocator serverPropertiesEndpointLocator;
public FallbackHavingEndpointLocator(DiscoveryClientEndpointLocator discoveryClientEndpointLocator,
ServerPropertiesEndpointLocator serverPropertiesEndpointLocator) {
ServerPropertiesEndpointLocator serverPropertiesEndpointLocator) {
this.discoveryClientEndpointLocator = discoveryClientEndpointLocator;
this.serverPropertiesEndpointLocator = serverPropertiesEndpointLocator;
}
@Override
public Endpoint local() {
if (discoveryClientEndpointLocator == null) {
return serverPropertiesEndpointLocator.local();
if (this.discoveryClientEndpointLocator == null) {
return this.serverPropertiesEndpointLocator.local();
}
try {
return discoveryClientEndpointLocator.local();
return this.discoveryClientEndpointLocator.local();
} catch (Exception e) {
log.warn("Exception occurred while trying to fetch the Zipkin process endpoint. Falling back to server properties endpoint locator.", e);
return serverPropertiesEndpointLocator.local();
return this.serverPropertiesEndpointLocator.local();
}
}
}

View File

@@ -1,5 +1,9 @@
package org.springframework.cloud.sleuth.zipkin;
import lombok.extern.apachecommons.CommonsLog;
import zipkin.Codec;
import zipkin.Span;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
@@ -14,9 +18,6 @@ import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import lombok.extern.apachecommons.CommonsLog;
import zipkin.Codec;
import zipkin.Span;
import static java.util.concurrent.TimeUnit.SECONDS;
@@ -24,116 +25,125 @@ import static java.util.concurrent.TimeUnit.SECONDS;
* Submits spans using Zipkin's {@code POST /spans} endpoint.
*/
@CommonsLog
public final class HttpZipkinSpanReporter implements ZipkinSpanReporter, Flushable, Closeable {
private static final Charset UTF_8 = Charset.forName("UTF-8");
public final class HttpZipkinSpanReporter
implements ZipkinSpanReporter, Flushable, Closeable {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final String url;
private final BlockingQueue<Span> pending = new LinkedBlockingQueue<>(1000);
private final Flusher flusher; // Nullable for testing
private final String url;
private final BlockingQueue<Span> pending = new LinkedBlockingQueue<>(1000);
private final Flusher flusher; // Nullable for testing
/**
* @param baseUrl URL of the zipkin query server instance. Like: http://localhost:9411/
* @param flushInterval in seconds. 0 implies spans are {@link #flush() flushed} externally.
*/
public HttpZipkinSpanReporter(String baseUrl, int flushInterval) {
this.url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "api/v1/spans";
this.flusher = flushInterval > 0 ? new Flusher(this, flushInterval) : null;
}
/**
* @param baseUrl URL of the zipkin query server instance. Like: http://localhost:9411/
* @param flushInterval in seconds. 0 implies spans are {@link #flush() flushed} externally.
*/
public HttpZipkinSpanReporter(String baseUrl, int flushInterval) {
this.url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "api/v1/spans";
this.flusher = flushInterval > 0 ? new Flusher(this, flushInterval) : null;
}
/**
* Queues the span for collection, or drops it if the queue is full.
*
* @param span Span, should not be <code>null</code>.
*/
@Override
public void report(Span span) {
// TODO: metrics.incrementAcceptedSpans(1);
if (!pending.offer(span)) {
// TODO: metrics.incrementDroppedSpans(1);
}
}
/**
* Queues the span for collection, or drops it if the queue is full.
*
* @param span Span, should not be <code>null</code>.
*/
@Override public void report(Span span) {
// TODO: metrics.incrementAcceptedSpans(1);
if (!this.pending.offer(span)) {
// TODO: metrics.incrementDroppedSpans(1);
}
}
/**
* Calling this will flush any pending spans to the http transport on the current thread.
*/
@Override
public void flush() {
if (pending.isEmpty()) return;
List<Span> drained = new ArrayList<>(pending.size());
pending.drainTo(drained);
if (drained.isEmpty()) return;
/**
* Calling this will flush any pending spans to the http transport on the current thread.
*/
@Override public void flush() {
if (this.pending.isEmpty())
return;
List<Span> drained = new ArrayList<>(this.pending.size());
this.pending.drainTo(drained);
if (drained.isEmpty())
return;
// json-encode the spans for transport
byte[] json = Codec.JSON.writeSpans(drained);
// NOTE: https://github.com/openzipkin/zipkin-java/issues/66 will throw instead of return null.
if (json == null) {
log.debug("failed to encode spans, dropping them: " + drained);
// TODO: metrics.incrementDroppedSpans(spanCount);
return;
}
// json-encode the spans for transport
byte[] json = Codec.JSON.writeSpans(drained);
// NOTE: https://github.com/openzipkin/zipkin-java/issues/66 will throw instead of return null.
if (json == null) {
log.debug("failed to encode spans, dropping them: " + drained);
// TODO: metrics.incrementDroppedSpans(spanCount);
return;
}
// Send the json to the zipkin endpoint
try {
postSpans(json);
} catch (IOException e) {
if (log.isDebugEnabled()) { // don't pollute logs unless debug is on.
// TODO: logger test
log.debug("error POSTing spans to " + url + ": as json: " + new String(json, UTF_8), e);
}
// TODO: metrics.incrementDroppedSpans(spanCount);
return;
}
}
// Send the json to the zipkin endpoint
try {
postSpans(json);
}
catch (IOException e) {
if (log.isDebugEnabled()) { // don't pollute logs unless debug is on.
// TODO: logger test
log.debug(
"error POSTing spans to " + this.url + ": as json: " + new String(json,
UTF_8), e);
}
// TODO: metrics.incrementDroppedSpans(spanCount);
return;
}
}
/** Calls flush on a fixed interval */
static final class Flusher implements Runnable {
final Flushable flushable;
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
/**
* Calls flush on a fixed interval
*/
static final class Flusher implements Runnable {
final Flushable flushable;
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Flusher(Flushable flushable, int flushInterval) {
this.flushable = flushable;
this.scheduler.scheduleWithFixedDelay(this, 0, flushInterval, SECONDS);
}
Flusher(Flushable flushable, int flushInterval) {
this.flushable = flushable;
this.scheduler.scheduleWithFixedDelay(this, 0, flushInterval, SECONDS);
}
@Override
public void run() {
try {
flushable.flush();
} catch (IOException ignored) {
}
}
}
@Override public void run() {
try {
this.flushable.flush();
}
catch (IOException ignored) {
}
}
}
void postSpans(byte[] json) throws IOException {
// intentionally not closing the connection, so as to use keep-alives
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(json.length);
connection.getOutputStream().write(json);
void postSpans(byte[] json) throws IOException {
// intentionally not closing the connection, so as to use keep-alives
HttpURLConnection connection = (HttpURLConnection) new URL(this.url).openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(json.length);
connection.getOutputStream().write(json);
try (InputStream in = connection.getInputStream()) {
while (in.read() != -1) ; // skip
} catch (IOException e) {
try (InputStream err = connection.getErrorStream()) {
if (err != null) { // possible, if the connection was dropped
while (err.read() != -1) ; // skip
}
}
throw e;
}
}
try (InputStream in = connection.getInputStream()) {
while (in.read() != -1)
; // skip
}
catch (IOException e) {
try (InputStream err = connection.getErrorStream()) {
if (err != null) { // possible, if the connection was dropped
while (err.read() != -1)
; // skip
}
}
throw e;
}
}
/**
* Requests a cease of delivery. There will be at most one in-flight request processing after this
* call returns.
*/
@Override
public void close() {
if (flusher != null) flusher.scheduler.shutdown();
// throw any outstanding spans on the floor
int dropped = pending.drainTo(new LinkedList<>());
// TODO: metrics.incrementDroppedSpans(dropped);
}
/**
* Requests a cease of delivery. There will be at most one in-flight request processing after this
* call returns.
*/
@Override public void close() {
if (this.flusher != null)
this.flusher.scheduler.shutdown();
// throw any outstanding spans on the floor
int dropped = this.pending.drainTo(new LinkedList<>());
// TODO: metrics.incrementDroppedSpans(dropped);
}
}

View File

@@ -30,11 +30,11 @@ import zipkin.Endpoint;
public class ServerPropertiesEndpointLocator implements EndpointLocator {
private final ServerProperties serverProperties;
private final String appName;
private final String appName;
private Integer port;
public ServerPropertiesEndpointLocator(ServerProperties serverProperties,
String appName) {
String appName) {
this.serverProperties = serverProperties;
this.appName = appName;
}
@@ -43,8 +43,7 @@ public class ServerPropertiesEndpointLocator implements EndpointLocator {
public Endpoint local() {
int address = getAddress();
Integer port = getPort();
Endpoint ep = Endpoint.create(this.appName, address, port);
return ep;
return Endpoint.create(this.appName, address, port);
}
@EventListener(EmbeddedServletContainerInitializedEvent.class)

View File

@@ -41,7 +41,7 @@ public class ZipkinAutoConfiguration {
@ConditionalOnMissingBean(ZipkinSpanReporter.class)
public ZipkinSpanReporter reporter() {
ZipkinProperties zipkin = zipkinProperties();
return new HttpZipkinSpanReporter(zipkin.getBaseUrl(), zipkin.getFlushInterval());
return new HttpZipkinSpanReporter(zipkin.getBaseUrl(), zipkin.getFlushInterval());
}
@Bean

View File

@@ -1,9 +1,9 @@
package org.springframework.cloud.sleuth.zipkin;
public interface ZipkinSpanReporter {
/**
* Receives completed spans from {@link ZipkinSpanListener} and submits them to a Zipkin
* collector.
*/
void report(zipkin.Span span);
/**
* Receives completed spans from {@link ZipkinSpanListener} and submits them to a Zipkin
* collector.
*/
void report(zipkin.Span span);
}

View File

@@ -18,36 +18,36 @@ public class FallbackHavingEndpointLocatorTests {
@Test
public void should_use_system_property_locator_if_discovery_client_locator_is_not_present() {
BDDMockito.given(serverPropertiesEndpointLocator.local()).willReturn(expectedEndpoint);
BDDMockito.given(this.serverPropertiesEndpointLocator.local()).willReturn(this.expectedEndpoint);
FallbackHavingEndpointLocator sut = new FallbackHavingEndpointLocator(null,
serverPropertiesEndpointLocator);
this.serverPropertiesEndpointLocator);
Endpoint endpoint = sut.local();
then(endpoint).isSameAs(expectedEndpoint);
then(endpoint).isSameAs(this.expectedEndpoint);
}
@Test
public void should_use_system_property_locator_if_discovery_client_locator_throws_an_exception() {
BDDMockito.given(discoveryClientEndpointLocator.local()).willThrow(new RuntimeException());
BDDMockito.given(serverPropertiesEndpointLocator.local()).willReturn(expectedEndpoint);
FallbackHavingEndpointLocator sut = new FallbackHavingEndpointLocator(discoveryClientEndpointLocator,
serverPropertiesEndpointLocator);
BDDMockito.given(this.discoveryClientEndpointLocator.local()).willThrow(new RuntimeException());
BDDMockito.given(this.serverPropertiesEndpointLocator.local()).willReturn(this.expectedEndpoint);
FallbackHavingEndpointLocator sut = new FallbackHavingEndpointLocator(this.discoveryClientEndpointLocator,
this.serverPropertiesEndpointLocator);
Endpoint endpoint = sut.local();
then(endpoint).isSameAs(expectedEndpoint);
then(endpoint).isSameAs(this.expectedEndpoint);
}
@Test
public void should_use_discovery_client_locator_by_default() {
BDDMockito.given(discoveryClientEndpointLocator.local()).willReturn(expectedEndpoint);
BDDMockito.given(serverPropertiesEndpointLocator.local()).willThrow(new RuntimeException());
FallbackHavingEndpointLocator sut = new FallbackHavingEndpointLocator(discoveryClientEndpointLocator,
serverPropertiesEndpointLocator);
BDDMockito.given(this.discoveryClientEndpointLocator.local()).willReturn(this.expectedEndpoint);
BDDMockito.given(this.serverPropertiesEndpointLocator.local()).willThrow(new RuntimeException());
FallbackHavingEndpointLocator sut = new FallbackHavingEndpointLocator(this.discoveryClientEndpointLocator,
this.serverPropertiesEndpointLocator);
Endpoint endpoint = sut.local();
then(endpoint).isSameAs(expectedEndpoint);
then(endpoint).isSameAs(this.expectedEndpoint);
}
}

View File

@@ -4,93 +4,92 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.mockwebserver.SocketPolicy;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import zipkin.Codec;
import zipkin.Span;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class HttpZipkinSpanReporterTest {
@Rule
public final MockWebServer server = new MockWebServer();
@Rule public final MockWebServer server = new MockWebServer();
// set flush interval to 0 so that tests can drive flushing explicitly
HttpZipkinSpanReporter reporter = new HttpZipkinSpanReporter(server.url("").toString(), 0);
// set flush interval to 0 so that tests can drive flushing explicitly
HttpZipkinSpanReporter reporter = new HttpZipkinSpanReporter(
this.server.url("").toString(), 0);
@Test
public void reportDoesntDoIO() throws Exception {
reporter.report(span(1L, "foo"));
@Test
public void reportDoesntDoIO() throws Exception {
this.reporter.report(span(1L, "foo"));
assertThat(server.getRequestCount()).isZero();
}
assertThat(this.server.getRequestCount()).isZero();
}
@Test
public void reportIncrementsAcceptedMetrics() throws Exception {
reporter.report(span(1L, "foo"));
@Test
public void reportIncrementsAcceptedMetrics() throws Exception {
this.reporter.report(span(1L, "foo"));
// TODO: assertThat(metrics.acceptedSpans.get()).isEqualTo(1);
// TODO: assertThat(metrics.droppedSpans.get()).isZero();
}
// TODO: assertThat(metrics.acceptedSpans.get()).isEqualTo(1);
// TODO: assertThat(metrics.droppedSpans.get()).isZero();
}
@Test
public void dropsWhenQueueIsFull() throws Exception {
for (int i = 0; i < 1001; i++)
reporter.report(span(1L, "foo"));
@Test
public void dropsWhenQueueIsFull() throws Exception {
for (int i = 0; i < 1001; i++)
this.reporter.report(span(1L, "foo"));
// TODO: assertThat(metrics.acceptedSpans.get()).isEqualTo(1001);
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(1);
}
// TODO: assertThat(metrics.acceptedSpans.get()).isEqualTo(1001);
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(1);
}
@Test
public void postsSpans() throws Exception {
server.enqueue(new MockResponse());
@Test
public void postsSpans() throws Exception {
this.server.enqueue(new MockResponse());
reporter.report(span(1L, "foo"));
reporter.report(span(2L, "bar"));
this.reporter.report(span(1L, "foo"));
this.reporter.report(span(2L, "bar"));
reporter.flush(); // manually flush the spans
this.reporter.flush(); // manually flush the spans
// Ensure a proper request was sent
RecordedRequest request = server.takeRequest();
assertThat(request.getRequestLine()).isEqualTo("POST /api/v1/spans HTTP/1.1");
assertThat(request.getHeader("Content-Type")).isEqualTo("application/json");
// Ensure a proper request was sent
RecordedRequest request = this.server.takeRequest();
assertThat(request.getRequestLine()).isEqualTo("POST /api/v1/spans HTTP/1.1");
assertThat(request.getHeader("Content-Type")).isEqualTo("application/json");
// Now, let's read back the spans we sent!
List<Span> zipkinSpans = Codec.JSON.readSpans(request.getBody().readByteArray());
assertThat(zipkinSpans).containsExactly(
span(1L, "foo"),
span(2L, "bar")
);
}
// Now, let's read back the spans we sent!
List<Span> zipkinSpans = Codec.JSON.readSpans(request.getBody().readByteArray());
assertThat(zipkinSpans).containsExactly(span(1L, "foo"), span(2L, "bar"));
}
@Test
public void incrementsDroppedSpansWhenServerErrors() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500));
@Test
public void incrementsDroppedSpansWhenServerErrors() throws Exception {
this.server.enqueue(new MockResponse().setResponseCode(500));
reporter.report(span(1L, "foo"));
reporter.report(span(2L, "bar"));
this.reporter.report(span(1L, "foo"));
this.reporter.report(span(2L, "bar"));
reporter.flush(); // manually flush the spans
this.reporter.flush(); // manually flush the spans
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(2);
}
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(2);
}
@Test
public void incrementsDroppedSpansWhenServerDisconnects() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST));
@Test
public void incrementsDroppedSpansWhenServerDisconnects() throws Exception {
this.server.enqueue(new MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST));
reporter.report(span(1L, "foo"));
reporter.report(span(2L, "bar"));
this.reporter.report(span(1L, "foo"));
this.reporter.report(span(2L, "bar"));
reporter.flush(); // manually flush the spans
this.reporter.flush(); // manually flush the spans
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(2);
}
// TODO: assertThat(metrics.droppedSpans.get()).isEqualTo(2);
}
static Span span(long traceId, String spanName) {
return new Span.Builder().traceId(traceId).id(traceId).name(spanName).build();
}
static Span span(long traceId, String spanName) {
return new Span.Builder().traceId(traceId).id(traceId).name(spanName).build();
}
}

View File

@@ -16,48 +16,51 @@
package org.springframework.cloud.sleuth.zipkin;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static org.assertj.core.api.Assertions.assertThat;
public class ServerPropertiesEndpointLocatorTests {
@Test
public void portDefaultsTo8080() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(new ServerProperties(), "unknown");
@Test
public void portDefaultsTo8080() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
new ServerProperties(), "unknown");
assertThat(locator.local().port).isEqualTo((short) 8080);
}
assertThat(locator.local().port).isEqualTo((short) 8080);
}
@Test
public void portFromServerProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(1234);
@Test
public void portFromServerProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(1234);
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(properties, "unknown");
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
properties, "unknown");
assertThat(locator.local().port).isEqualTo((short) 1234);
}
assertThat(locator.local().port).isEqualTo((short) 1234);
}
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(new ServerProperties(), "unknown");
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
new ServerProperties(), "unknown");
assertThat(locator.local().ipv4)
.isEqualTo(127 << 24 | 1);
}
assertThat(locator.local().ipv4).isEqualTo(127 << 24 | 1);
}
@Test
public void hostFromServerPropertiesIp() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
properties.setAddress(InetAddress.getByAddress(new byte[]{1, 2, 3, 4}));
@Test
public void hostFromServerPropertiesIp() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
properties.setAddress(InetAddress.getByAddress(new byte[] { 1, 2, 3, 4 }));
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(properties, "unknown");
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
properties, "unknown");
assertThat(locator.local().ipv4)
.isEqualTo(1 << 24 | 2 << 16 | 3 << 8 | 4);
}
assertThat(locator.local().ipv4).isEqualTo(1 << 24 | 2 << 16 | 3 << 8 | 4);
}
}

View File

@@ -75,14 +75,14 @@ public class ZipkinSpanListenerTests {
@Test
public void convertsTimestampAndDurationToMicroseconds() {
long start = System.currentTimeMillis();
parent.log("http/request/retry"); // System.currentTimeMillis
this.parent.log("http/request/retry"); // System.currentTimeMillis
zipkin.Span result = listener.convert(parent);
zipkin.Span result = this.listener.convert(this.parent);
assertThat(result.timestamp)
.isEqualTo(parent.getBegin() * 1000);
.isEqualTo(this.parent.getBegin() * 1000);
assertThat(result.duration)
.isEqualTo((parent.getEnd() - parent.getBegin()) * 1000);
.isEqualTo((this.parent.getEnd() - this.parent.getBegin()) * 1000);
assertThat(result.annotations.get(0).timestamp)
.isGreaterThanOrEqualTo(start * 1000)
.isLessThanOrEqualTo(System.currentTimeMillis() * 1000);
@@ -91,13 +91,13 @@ public class ZipkinSpanListenerTests {
/** Sleuth host corresponds to annotation/binaryAnnotation.host in zipkin. */
@Test
public void annotationsIncludeHost() {
parent.log("http/request/retry");
parent.tag("spring-boot/version", "1.3.1.RELEASE");
this.parent.log("http/request/retry");
this.parent.tag("spring-boot/version", "1.3.1.RELEASE");
zipkin.Span result = listener.convert(parent);
zipkin.Span result = this.listener.convert(this.parent);
assertThat(result.annotations.get(0).endpoint)
.isEqualTo(listener.localEndpoint);
.isEqualTo(this.listener.localEndpoint);
assertThat(result.binaryAnnotations.get(0).endpoint)
.isEqualTo(result.annotations.get(0).endpoint);
}
@@ -105,7 +105,7 @@ public class ZipkinSpanListenerTests {
/** zipkin's Endpoint.serviceName should never be null. */
@Test
public void localEndpointIncludesServiceName() {
assertThat(listener.localEndpoint.serviceName)
assertThat(this.listener.localEndpoint.serviceName)
.isNotEmpty();
}
@@ -125,10 +125,10 @@ public class ZipkinSpanListenerTests {
@Test
public void rpcAnnotations() {
Span context = this.tracer.joinTrace("child", parent);
Span context = this.tracer.joinTrace("child", this.parent);
this.application.publishEvent(new ClientSentEvent(this, context));
this.application.publishEvent(new ServerReceivedEvent(this, parent, context));
this.application.publishEvent(new ServerSentEvent(this, parent, context));
this.application.publishEvent(new ServerReceivedEvent(this, this.parent, context));
this.application.publishEvent(new ServerSentEvent(this, this.parent, context));
this.application.publishEvent(new ClientReceivedEvent(this, context));
this.tracer.close(context);
assertEquals(2, this.test.spans.size());