Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize Brave Zipkin tracing for Dropwizard servers and JAX RS clients #235

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import io.dropwizard.setup.Environment;
import javax.ws.rs.ext.ExceptionMapper;


public final class DropwizardServers {
private DropwizardServers() {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@

package com.palantir.remoting1.servers;

import com.github.kristofa.brave.AnnotationSubmitter;
import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.InheritableServerClientAndLocalSpanState;
import com.github.kristofa.brave.Sampler;
import com.github.kristofa.brave.ServerClientAndLocalSpanState;
import com.github.kristofa.brave.ServerRequestInterceptor;
import com.github.kristofa.brave.ServerResponseInterceptor;
import com.github.kristofa.brave.ServerTracer;
import com.github.kristofa.brave.ThreadLocalServerClientAndLocalSpanState;
import com.github.kristofa.brave.SpanCollector;
import com.github.kristofa.brave.ext.SlfLoggingSpanCollector;
import com.github.kristofa.brave.http.DefaultSpanNameProvider;
import com.github.kristofa.brave.jaxrs2.BraveContainerRequestFilter;
Expand All @@ -30,6 +31,7 @@
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.net.InetAddresses;
import com.twitter.zipkin.gen.Endpoint;
import io.dropwizard.Configuration;
import io.dropwizard.jetty.ConnectorFactory;
import io.dropwizard.jetty.HttpConnectorFactory;
Expand All @@ -39,12 +41,13 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.EnumSet;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.DispatcherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Static utilities for registering Brave/Zipkin filters with Dropwizard applications. */
final class DropwizardTracingFilters {
private static final Logger logger = LoggerFactory.getLogger(DropwizardTracingFilters.class);

private DropwizardTracingFilters() {}

Expand All @@ -57,32 +60,45 @@ private DropwizardTracingFilters() {}
* TODO(rfink) Is there a more stable way to retrieve IP/Port information?
*/
static void registerTracers(Environment environment, Configuration config, String tracerName) {
ServerTracer serverTracer = getServerTracer(extractIp(config), extractPort(config), tracerName);
final BraveTracer tracer = getOrCreateBraveTracer(config, tracerName);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

final isn't normally used in this codebase

environment.jersey().register(new BraveContainerRequestFilter(
new ServerRequestInterceptor(serverTracer),
new ServerRequestInterceptor(tracer.getBrave().serverTracer()),
new DefaultSpanNameProvider()
));
environment.jersey().register(new BraveContainerResponseFilter(
new ServerResponseInterceptor(serverTracer)
new ServerResponseInterceptor(tracer.getBrave().serverTracer())
));
environment.servlets()
.addFilter(TraceIdLoggingFilter.class.getSimpleName(), TraceIdLoggingFilter.INSTANCE)
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
Tracers.setActiveTracer(tracer);
}

private static ServerTracer getServerTracer(int ip, int port, String name) {
return ServerTracer.builder()
.traceSampler(Sampler.ALWAYS_SAMPLE)
.randomGenerator(new Random())
.state(new ThreadLocalServerClientAndLocalSpanState(ip, port, name))
.spanCollector(new SlfLoggingSpanCollector("tracing.server." + name))
.clock(new AnnotationSubmitter.Clock() {
@Override
public long currentTimeMicroseconds() {
return TimeUnit.MICROSECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
}
})

private static BraveTracer getOrCreateBraveTracer(Configuration config, String name) {
Tracer activeTracer = Tracers.activeTracer();
return (activeTracer instanceof BraveTracer)
? (BraveTracer) activeTracer
: createBraveTracer(config, name);
}

private static BraveTracer createBraveTracer(Configuration config, String name) {
int ip = extractIp(config);
int port = extractPort(config);
ServerClientAndLocalSpanState state = new InheritableServerClientAndLocalSpanState(
Endpoint.create(name, ip, port));
// TODO (davids) make the sampler and collectors configurable
Sampler sampler = Sampler.ALWAYS_SAMPLE;
final String loggerName = "tracing." + name;
SpanCollector spanCollector = new SlfLoggingSpanCollector(loggerName);

logger.info("Starting tracer for {} writing to logger {}", name, loggerName);
Brave brave = new Brave.Builder(state)
.traceSampler(sampler)
.spanCollector(spanCollector)
.clock(BraveTracer.defaultClock())
.build();
return new BraveTracer(brave);
}

private static int extractIp(Configuration config) {
Expand All @@ -101,14 +117,14 @@ public String apply(ConnectorFactory factory) {
})
.or("");

if (!bindHost.isEmpty()) {
if (bindHost.isEmpty()) {
return 0;
} else {
try {
return InetAddresses.coerceToInteger(InetAddress.getByName(bindHost));
} catch (UnknownHostException e) {
return 0;
}
} else {
return 0;
}
}

Expand Down Expand Up @@ -136,4 +152,5 @@ private static Optional<ConnectorFactory> extractConnector(Configuration config,
return Optional.absent();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,9 @@ public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Closeable traceContext = populateTraceContext(request);
try {
//noinspection unused - try-with-resources
try (Closeable traceContext = populateTraceContext(request)) {
chain.doFilter(request, response);
} finally {
traceContext.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void before() {

when(braveMockAppender.getName()).thenReturn("MOCK");
// the logger used by the brave server instance
braveLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("tracing.server.testTracerName");
braveLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("tracing.testTracerName");
braveLogger.setLevel(null);
braveLogger.addAppender(braveMockAppender);

Expand Down
64 changes: 62 additions & 2 deletions dropwizard-servers/versions.lock
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
"transitive": [
"com.fasterxml.jackson.datatype:jackson-datatype-guava",
"com.palantir.remoting1:error-handling",
"com.palantir.remoting1:ssl-config",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson"
]
},
Expand Down Expand Up @@ -107,6 +109,8 @@
"transitive": [
"com.fasterxml.jackson.datatype:jackson-datatype-guava",
"com.palantir.remoting1:error-handling",
"com.palantir.remoting1:ssl-config",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson",
"io.dropwizard:dropwizard-lifecycle",
"io.dropwizard:dropwizard-util"
Expand All @@ -118,6 +122,30 @@
"com.palantir.remoting1:error-handling": {
"project": true
},
"com.palantir.remoting1:http-clients-api": {
"project": true,
"transitive": [
"com.palantir.remoting1:brave-extensions"
]
},
"com.palantir.remoting1:service-config": {
"project": true,
"transitive": [
"com.palantir.remoting1:http-clients-api"
]
},
"com.palantir.remoting1:ssl-config": {
"project": true,
"transitive": [
"com.palantir.remoting1:service-config"
]
},
"com.palantir.tokens:auth-tokens": {
"locked": "0.2.3",
"transitive": [
"com.palantir.remoting1:service-config"
]
},
"io.dropwizard.metrics:metrics-annotation": {
"locked": "3.1.1",
"transitive": [
Expand Down Expand Up @@ -551,8 +579,9 @@
]
},
"org.slf4j:jcl-over-slf4j": {
"locked": "1.7.10",
"locked": "1.7.12",
"transitive": [
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-logging"
]
},
Expand All @@ -574,6 +603,7 @@
"ch.qos.logback:logback-classic",
"com.palantir.remoting1:brave-extensions",
"com.palantir.remoting1:error-handling",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson",
"io.dropwizard:dropwizard-lifecycle",
"io.dropwizard:dropwizard-logging",
Expand Down Expand Up @@ -629,6 +659,8 @@
"transitive": [
"com.fasterxml.jackson.datatype:jackson-datatype-guava",
"com.palantir.remoting1:error-handling",
"com.palantir.remoting1:ssl-config",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson"
]
},
Expand Down Expand Up @@ -699,6 +731,8 @@
"transitive": [
"com.fasterxml.jackson.datatype:jackson-datatype-guava",
"com.palantir.remoting1:error-handling",
"com.palantir.remoting1:ssl-config",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson",
"io.dropwizard:dropwizard-lifecycle",
"io.dropwizard:dropwizard-util"
Expand All @@ -710,6 +744,30 @@
"com.palantir.remoting1:error-handling": {
"project": true
},
"com.palantir.remoting1:http-clients-api": {
"project": true,
"transitive": [
"com.palantir.remoting1:brave-extensions"
]
},
"com.palantir.remoting1:service-config": {
"project": true,
"transitive": [
"com.palantir.remoting1:http-clients-api"
]
},
"com.palantir.remoting1:ssl-config": {
"project": true,
"transitive": [
"com.palantir.remoting1:service-config"
]
},
"com.palantir.tokens:auth-tokens": {
"locked": "0.2.3",
"transitive": [
"com.palantir.remoting1:service-config"
]
},
"io.dropwizard.metrics:metrics-annotation": {
"locked": "3.1.1",
"transitive": [
Expand Down Expand Up @@ -1143,8 +1201,9 @@
]
},
"org.slf4j:jcl-over-slf4j": {
"locked": "1.7.10",
"locked": "1.7.12",
"transitive": [
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-logging"
]
},
Expand All @@ -1166,6 +1225,7 @@
"ch.qos.logback:logback-classic",
"com.palantir.remoting1:brave-extensions",
"com.palantir.remoting1:error-handling",
"com.palantir.tokens:auth-tokens",
"io.dropwizard:dropwizard-jackson",
"io.dropwizard:dropwizard-lifecycle",
"io.dropwizard:dropwizard-logging",
Expand Down
5 changes: 5 additions & 0 deletions ext/brave-extensions/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
apply from: "${rootDir}/gradle/publish.gradle"

dependencies {
compile project(":http-clients-api")
compile "io.zipkin.brave:brave-core"
compile "org.slf4j:slf4j-api"

testCompile "junit:junit"
testCompile "org.hamcrest:hamcrest-all"
testCompile "org.mockito:mockito-core"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2016 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.remoting1.servers;

import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.SpanId;
import com.google.common.base.Preconditions;

public final class BraveContext implements Tracer.TraceContext {

private final Brave brave;
private final SpanId spanId;

@SuppressWarnings("WeakerAccess") // public API
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is to suppress the intelliJ hint?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this suppresses an IntelliJ warning since this is unused in this project

public static BraveContext beginLocalTrace(Brave brave, String component, String operation) {
return new BraveContext(brave, brave.localTracer().startNewSpan(component, operation));
}

private BraveContext(Brave brave, SpanId spanId) {
this.brave = Preconditions.checkNotNull(brave, "brave");
this.spanId = Preconditions.checkNotNull(spanId, "spanId");
}

public Brave getBrave() {
return brave;
}

public SpanId getSpanId() {
return spanId;
}

@Override
public void close() {
getBrave().localTracer().finishSpan();
}

}