Bumping versions
This commit is contained in:
@@ -30,8 +30,7 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
* @author Marcin Grzejszczak
|
||||
* @since 2.2.0
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Value("${spring.zipkin.service.name:${spring.application.name:default}}")
|
||||
|
||||
@@ -32,11 +32,9 @@ import org.springframework.beans.factory.BeanFactoryAware;
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*/
|
||||
abstract class AbstractSleuthMethodInvocationProcessor
|
||||
implements SleuthMethodInvocationProcessor, BeanFactoryAware {
|
||||
abstract class AbstractSleuthMethodInvocationProcessor implements SleuthMethodInvocationProcessor, BeanFactoryAware {
|
||||
|
||||
private static final Log logger = LogFactory
|
||||
.getLog(AbstractSleuthMethodInvocationProcessor.class);
|
||||
private static final Log logger = LogFactory.getLog(AbstractSleuthMethodInvocationProcessor.class);
|
||||
|
||||
private static final String CLASS_KEY = "class";
|
||||
|
||||
@@ -110,8 +108,7 @@ abstract class AbstractSleuthMethodInvocationProcessor
|
||||
|
||||
CurrentTraceContext currentTraceContext() {
|
||||
if (this.currentTraceContext == null) {
|
||||
this.currentTraceContext = this.beanFactory
|
||||
.getBean(CurrentTraceContext.class);
|
||||
this.currentTraceContext = this.beanFactory.getBean(CurrentTraceContext.class);
|
||||
}
|
||||
return this.currentTraceContext;
|
||||
}
|
||||
@@ -125,8 +122,7 @@ abstract class AbstractSleuthMethodInvocationProcessor
|
||||
|
||||
SpanTagAnnotationHandler spanTagAnnotationHandler() {
|
||||
if (this.spanTagAnnotationHandler == null) {
|
||||
this.spanTagAnnotationHandler = new SpanTagAnnotationHandler(
|
||||
this.beanFactory);
|
||||
this.spanTagAnnotationHandler = new SpanTagAnnotationHandler(this.beanFactory);
|
||||
}
|
||||
return this.spanTagAnnotationHandler;
|
||||
}
|
||||
|
||||
@@ -36,13 +36,12 @@ class DefaultSpanCreator implements NewSpanParser {
|
||||
|
||||
@Override
|
||||
public void parse(MethodInvocation pjp, NewSpan newSpan, SpanCustomizer span) {
|
||||
String name = newSpan == null || StringUtils.isEmpty(newSpan.name())
|
||||
? pjp.getMethod().getName() : newSpan.name();
|
||||
String name = newSpan == null || StringUtils.isEmpty(newSpan.name()) ? pjp.getMethod().getName()
|
||||
: newSpan.name();
|
||||
String changedName = SpanNameUtil.toLowerHyphen(name);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("For the class [" + pjp.getThis().getClass() + "] method " + "["
|
||||
+ pjp.getMethod().getName() + "] will name the span [" + changedName
|
||||
+ "]");
|
||||
log.debug("For the class [" + pjp.getThis().getClass() + "] method " + "[" + pjp.getMethod().getName()
|
||||
+ "] will name the span [" + changedName + "]");
|
||||
}
|
||||
span.name(changedName);
|
||||
}
|
||||
|
||||
@@ -28,17 +28,15 @@ import org.springframework.util.StringUtils;
|
||||
* @author Marcin Grzejszczak
|
||||
* @since 2.1.0
|
||||
*/
|
||||
class NonReactorSleuthMethodInvocationProcessor
|
||||
extends AbstractSleuthMethodInvocationProcessor {
|
||||
class NonReactorSleuthMethodInvocationProcessor extends AbstractSleuthMethodInvocationProcessor {
|
||||
|
||||
@Override
|
||||
public Object process(MethodInvocation invocation, NewSpan newSpan,
|
||||
ContinueSpan continueSpan) throws Throwable {
|
||||
public Object process(MethodInvocation invocation, NewSpan newSpan, ContinueSpan continueSpan) throws Throwable {
|
||||
return proceedUnderSynchronousSpan(invocation, newSpan, continueSpan);
|
||||
}
|
||||
|
||||
private Object proceedUnderSynchronousSpan(MethodInvocation invocation,
|
||||
NewSpan newSpan, ContinueSpan continueSpan) throws Throwable {
|
||||
private Object proceedUnderSynchronousSpan(MethodInvocation invocation, NewSpan newSpan, ContinueSpan continueSpan)
|
||||
throws Throwable {
|
||||
Span span = tracer().currentSpan();
|
||||
// in case of @ContinueSpan and no span in tracer we start new span and should
|
||||
// close it on completion
|
||||
|
||||
@@ -44,8 +44,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Marcin Grzejszczak
|
||||
* @since 2.1.0
|
||||
*/
|
||||
class ReactorSleuthMethodInvocationProcessor
|
||||
extends AbstractSleuthMethodInvocationProcessor {
|
||||
class ReactorSleuthMethodInvocationProcessor extends AbstractSleuthMethodInvocationProcessor {
|
||||
|
||||
Tracing tracing;
|
||||
|
||||
@@ -59,21 +58,19 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object process(MethodInvocation invocation, NewSpan newSpan,
|
||||
ContinueSpan continueSpan) throws Throwable {
|
||||
public Object process(MethodInvocation invocation, NewSpan newSpan, ContinueSpan continueSpan) throws Throwable {
|
||||
Method method = invocation.getMethod();
|
||||
if (isReactorReturnType(method.getReturnType())) {
|
||||
return proceedUnderReactorSpan(invocation, newSpan, continueSpan);
|
||||
}
|
||||
else {
|
||||
return nonReactorSleuthMethodInvocationProcessor().process(invocation,
|
||||
newSpan, continueSpan);
|
||||
return nonReactorSleuthMethodInvocationProcessor().process(invocation, newSpan, continueSpan);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Object proceedUnderReactorSpan(MethodInvocation invocation, NewSpan newSpan,
|
||||
ContinueSpan continueSpan) throws Throwable {
|
||||
private Object proceedUnderReactorSpan(MethodInvocation invocation, NewSpan newSpan, ContinueSpan continueSpan)
|
||||
throws Throwable {
|
||||
Span spanPrevious = tracer().currentSpan();
|
||||
// in case of @ContinueSpan and no span in tracer we start new span and should
|
||||
// close it on completion
|
||||
@@ -89,16 +86,13 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
Publisher<?> publisher = (Publisher) invocation.proceed();
|
||||
|
||||
if (publisher instanceof Mono) {
|
||||
return new MonoSpan((Mono<Object>) publisher, this, newSpan, span, invocation,
|
||||
log);
|
||||
return new MonoSpan((Mono<Object>) publisher, this, newSpan, span, invocation, log);
|
||||
}
|
||||
else if (publisher instanceof Flux) {
|
||||
return new FluxSpan((Flux<Object>) publisher, this, newSpan, span, invocation,
|
||||
log);
|
||||
return new FluxSpan((Flux<Object>) publisher, this, newSpan, span, invocation, log);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException(
|
||||
"Unexpected type of publisher: " + publisher.getClass());
|
||||
throw new IllegalArgumentException("Unexpected type of publisher: " + publisher.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,8 +103,7 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
private NonReactorSleuthMethodInvocationProcessor nonReactorSleuthMethodInvocationProcessor() {
|
||||
if (this.nonReactorSleuthMethodInvocationProcessor == null) {
|
||||
this.nonReactorSleuthMethodInvocationProcessor = new NonReactorSleuthMethodInvocationProcessor();
|
||||
this.nonReactorSleuthMethodInvocationProcessor
|
||||
.setBeanFactory(this.beanFactory);
|
||||
this.nonReactorSleuthMethodInvocationProcessor.setBeanFactory(this.beanFactory);
|
||||
}
|
||||
return this.nonReactorSleuthMethodInvocationProcessor;
|
||||
}
|
||||
@@ -129,9 +122,8 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
|
||||
final NewSpan newSpan;
|
||||
|
||||
FluxSpan(Flux<Object> source, ReactorSleuthMethodInvocationProcessor processor,
|
||||
NewSpan newSpan, @Nullable Span span, MethodInvocation invocation,
|
||||
String log) {
|
||||
FluxSpan(Flux<Object> source, ReactorSleuthMethodInvocationProcessor processor, NewSpan newSpan,
|
||||
@Nullable Span span, MethodInvocation invocation, String log) {
|
||||
super(source);
|
||||
this.span = span;
|
||||
this.newSpan = newSpan;
|
||||
@@ -155,10 +147,9 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
else {
|
||||
span = this.span;
|
||||
}
|
||||
try (Scope ws = this.processor.currentTraceContext()
|
||||
.maybeScope(span.context())) {
|
||||
this.source.subscribe(new SpanSubscriber(actual, this.processor,
|
||||
this.invocation, this.span == null, span, this.log, this.hasLog));
|
||||
try (Scope ws = this.processor.currentTraceContext().maybeScope(span.context())) {
|
||||
this.source.subscribe(new SpanSubscriber(actual, this.processor, this.invocation, this.span == null,
|
||||
span, this.log, this.hasLog));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,9 +169,8 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
|
||||
final NewSpan newSpan;
|
||||
|
||||
MonoSpan(Mono<Object> source, ReactorSleuthMethodInvocationProcessor processor,
|
||||
NewSpan newSpan, @Nullable Span span, MethodInvocation invocation,
|
||||
String log) {
|
||||
MonoSpan(Mono<Object> source, ReactorSleuthMethodInvocationProcessor processor, NewSpan newSpan,
|
||||
@Nullable Span span, MethodInvocation invocation, String log) {
|
||||
super(source);
|
||||
this.processor = processor;
|
||||
this.newSpan = newSpan;
|
||||
@@ -202,17 +192,15 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
else {
|
||||
span = this.span;
|
||||
}
|
||||
try (Scope ws = this.processor.currentTraceContext()
|
||||
.maybeScope(span.context())) {
|
||||
this.source.subscribe(new SpanSubscriber(actual, this.processor,
|
||||
this.invocation, this.span == null, span, this.log, this.hasLog));
|
||||
try (Scope ws = this.processor.currentTraceContext().maybeScope(span.context())) {
|
||||
this.source.subscribe(new SpanSubscriber(actual, this.processor, this.invocation, this.span == null,
|
||||
span, this.log, this.hasLog));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final class SpanSubscriber
|
||||
implements CoreSubscriber<Object>, Subscription, Scannable {
|
||||
private static final class SpanSubscriber implements CoreSubscriber<Object>, Subscription, Scannable {
|
||||
|
||||
final CoreSubscriber<? super Object> actual;
|
||||
|
||||
@@ -232,10 +220,8 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
|
||||
Subscription parent;
|
||||
|
||||
SpanSubscriber(CoreSubscriber<? super Object> actual,
|
||||
ReactorSleuthMethodInvocationProcessor processor,
|
||||
MethodInvocation invocation, boolean isNewSpan, Span span, String log,
|
||||
boolean hasLog) {
|
||||
SpanSubscriber(CoreSubscriber<? super Object> actual, ReactorSleuthMethodInvocationProcessor processor,
|
||||
MethodInvocation invocation, boolean isNewSpan, Span span, String log, boolean hasLog) {
|
||||
this.actual = actual;
|
||||
this.isNewSpan = isNewSpan;
|
||||
this.span = span;
|
||||
@@ -244,8 +230,7 @@ class ReactorSleuthMethodInvocationProcessor
|
||||
this.processor = processor;
|
||||
|
||||
this.currentTraceContext = processor.tracing().currentTraceContext();
|
||||
this.context = actual.currentContext().put(TraceContext.class,
|
||||
span.context());
|
||||
this.context = actual.currentContext().put(TraceContext.class, span.context());
|
||||
|
||||
processor.before(invocation, this.span, this.log, this.hasLog);
|
||||
}
|
||||
|
||||
@@ -120,8 +120,7 @@ class SleuthAdvisorConfig extends AbstractPointcutAdvisor implements BeanFactory
|
||||
/**
|
||||
* Checks if a class or a method is is annotated with Sleuth related annotations.
|
||||
*/
|
||||
private final class AnnotationClassOrMethodOrArgsPointcut
|
||||
extends DynamicMethodMatcherPointcut {
|
||||
private final class AnnotationClassOrMethodOrArgsPointcut extends DynamicMethodMatcherPointcut {
|
||||
|
||||
@Override
|
||||
public boolean matches(Method method, Class<?> targetClass, Object... args) {
|
||||
@@ -136,8 +135,7 @@ class SleuthAdvisorConfig extends AbstractPointcutAdvisor implements BeanFactory
|
||||
@Override
|
||||
public boolean matches(Class<?> clazz) {
|
||||
return new AnnotationClassOrMethodFilter(NewSpan.class).matches(clazz)
|
||||
|| new AnnotationClassOrMethodFilter(ContinueSpan.class)
|
||||
.matches(clazz);
|
||||
|| new AnnotationClassOrMethodFilter(ContinueSpan.class).matches(clazz);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -180,12 +178,9 @@ class SleuthInterceptor implements IntroductionInterceptor, BeanFactoryAware {
|
||||
if (method == null) {
|
||||
return invocation.proceed();
|
||||
}
|
||||
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method,
|
||||
invocation.getThis().getClass());
|
||||
NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod,
|
||||
NewSpan.class);
|
||||
ContinueSpan continueSpan = SleuthAnnotationUtils
|
||||
.findAnnotation(mostSpecificMethod, ContinueSpan.class);
|
||||
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass());
|
||||
NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, NewSpan.class);
|
||||
ContinueSpan continueSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, ContinueSpan.class);
|
||||
if (newSpan == null && continueSpan == null) {
|
||||
return invocation.proceed();
|
||||
}
|
||||
@@ -194,8 +189,7 @@ class SleuthInterceptor implements IntroductionInterceptor, BeanFactoryAware {
|
||||
|
||||
private SleuthMethodInvocationProcessor methodInvocationProcessor() {
|
||||
if (this.methodInvocationProcessor == null) {
|
||||
this.methodInvocationProcessor = this.beanFactory
|
||||
.getBean(SleuthMethodInvocationProcessor.class);
|
||||
this.methodInvocationProcessor = this.beanFactory.getBean(SleuthMethodInvocationProcessor.class);
|
||||
}
|
||||
return this.methodInvocationProcessor;
|
||||
}
|
||||
|
||||
@@ -42,24 +42,21 @@ final class SleuthAnnotationUtils {
|
||||
}
|
||||
|
||||
static boolean isMethodAnnotated(Method method) {
|
||||
return findAnnotation(method, NewSpan.class) != null
|
||||
|| findAnnotation(method, ContinueSpan.class) != null;
|
||||
return findAnnotation(method, NewSpan.class) != null || findAnnotation(method, ContinueSpan.class) != null;
|
||||
}
|
||||
|
||||
static boolean hasAnnotatedParams(Method method, Object[] args) {
|
||||
return !findAnnotatedParameters(method, args).isEmpty();
|
||||
}
|
||||
|
||||
static List<SleuthAnnotatedParameter> findAnnotatedParameters(Method method,
|
||||
Object[] args) {
|
||||
static List<SleuthAnnotatedParameter> findAnnotatedParameters(Method method, Object[] args) {
|
||||
Annotation[][] parameters = method.getParameterAnnotations();
|
||||
List<SleuthAnnotatedParameter> result = new ArrayList<>();
|
||||
int i = 0;
|
||||
for (Annotation[] parameter : parameters) {
|
||||
for (Annotation parameter2 : parameter) {
|
||||
if (parameter2 instanceof SpanTag) {
|
||||
result.add(new SleuthAnnotatedParameter(i, (SpanTag) parameter2,
|
||||
args[i]));
|
||||
result.add(new SleuthAnnotatedParameter(i, (SpanTag) parameter2, args[i]));
|
||||
}
|
||||
}
|
||||
i++;
|
||||
@@ -78,13 +75,12 @@ final class SleuthAnnotationUtils {
|
||||
T annotation = AnnotationUtils.findAnnotation(method, clazz);
|
||||
if (annotation == null) {
|
||||
try {
|
||||
annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass()
|
||||
.getMethod(method.getName(), method.getParameterTypes()), clazz);
|
||||
annotation = AnnotationUtils.findAnnotation(
|
||||
method.getDeclaringClass().getMethod(method.getName(), method.getParameterTypes()), clazz);
|
||||
}
|
||||
catch (NoSuchMethodException | SecurityException ex) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Exception occurred while tyring to find the annotation",
|
||||
ex);
|
||||
log.debug("Exception occurred while tyring to find the annotation", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import org.aopalliance.intercept.MethodInvocation;
|
||||
*/
|
||||
interface SleuthMethodInvocationProcessor {
|
||||
|
||||
Object process(MethodInvocation invocation, NewSpan newSpan,
|
||||
ContinueSpan continueSpan) throws Throwable;
|
||||
Object process(MethodInvocation invocation, NewSpan newSpan, ContinueSpan continueSpan) throws Throwable;
|
||||
|
||||
}
|
||||
|
||||
@@ -56,13 +56,11 @@ class SpanTagAnnotationHandler {
|
||||
void addAnnotatedParameters(MethodInvocation pjp) {
|
||||
try {
|
||||
Method method = pjp.getMethod();
|
||||
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method,
|
||||
pjp.getThis().getClass());
|
||||
Method mostSpecificMethod = AopUtils.getMostSpecificMethod(method, pjp.getThis().getClass());
|
||||
List<SleuthAnnotatedParameter> annotatedParameters = SleuthAnnotationUtils
|
||||
.findAnnotatedParameters(mostSpecificMethod, pjp.getArguments());
|
||||
getAnnotationsFromInterfaces(pjp, mostSpecificMethod, annotatedParameters);
|
||||
mergeAnnotatedMethodsIfNecessary(pjp, method, mostSpecificMethod,
|
||||
annotatedParameters);
|
||||
mergeAnnotatedMethodsIfNecessary(pjp, method, mostSpecificMethod, annotatedParameters);
|
||||
addAnnotatedArguments(annotatedParameters);
|
||||
}
|
||||
catch (SecurityException ex) {
|
||||
@@ -70,8 +68,7 @@ class SpanTagAnnotationHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private void getAnnotationsFromInterfaces(MethodInvocation pjp,
|
||||
Method mostSpecificMethod,
|
||||
private void getAnnotationsFromInterfaces(MethodInvocation pjp, Method mostSpecificMethod,
|
||||
List<SleuthAnnotatedParameter> annotatedParameters) {
|
||||
Class<?>[] implementedInterfaces = pjp.getThis().getClass().getInterfaces();
|
||||
if (implementedInterfaces.length > 0) {
|
||||
@@ -79,10 +76,8 @@ class SpanTagAnnotationHandler {
|
||||
for (Method methodFromInterface : implementedInterface.getMethods()) {
|
||||
if (methodsAreTheSame(mostSpecificMethod, methodFromInterface)) {
|
||||
List<SleuthAnnotatedParameter> annotatedParametersForActualMethod = SleuthAnnotationUtils
|
||||
.findAnnotatedParameters(methodFromInterface,
|
||||
pjp.getArguments());
|
||||
mergeAnnotatedParameters(annotatedParameters,
|
||||
annotatedParametersForActualMethod);
|
||||
.findAnnotatedParameters(methodFromInterface, pjp.getArguments());
|
||||
mergeAnnotatedParameters(annotatedParameters, annotatedParametersForActualMethod);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,25 +85,22 @@ class SpanTagAnnotationHandler {
|
||||
}
|
||||
|
||||
private boolean methodsAreTheSame(Method mostSpecificMethod, Method method1) {
|
||||
return method1.getName().equals(mostSpecificMethod.getName()) && Arrays.equals(
|
||||
method1.getParameterTypes(), mostSpecificMethod.getParameterTypes());
|
||||
return method1.getName().equals(mostSpecificMethod.getName())
|
||||
&& Arrays.equals(method1.getParameterTypes(), mostSpecificMethod.getParameterTypes());
|
||||
}
|
||||
|
||||
private void mergeAnnotatedMethodsIfNecessary(MethodInvocation pjp, Method method,
|
||||
Method mostSpecificMethod,
|
||||
private void mergeAnnotatedMethodsIfNecessary(MethodInvocation pjp, Method method, Method mostSpecificMethod,
|
||||
List<SleuthAnnotatedParameter> annotatedParameters) {
|
||||
// that can happen if we have an abstraction and a concrete class that is
|
||||
// annotated with @NewSpan annotation
|
||||
if (!method.equals(mostSpecificMethod)) {
|
||||
List<SleuthAnnotatedParameter> annotatedParametersForActualMethod = SleuthAnnotationUtils
|
||||
.findAnnotatedParameters(method, pjp.getArguments());
|
||||
mergeAnnotatedParameters(annotatedParameters,
|
||||
annotatedParametersForActualMethod);
|
||||
mergeAnnotatedParameters(annotatedParameters, annotatedParametersForActualMethod);
|
||||
}
|
||||
}
|
||||
|
||||
private void mergeAnnotatedParameters(
|
||||
List<SleuthAnnotatedParameter> annotatedParametersIndices,
|
||||
private void mergeAnnotatedParameters(List<SleuthAnnotatedParameter> annotatedParametersIndices,
|
||||
List<SleuthAnnotatedParameter> annotatedParametersIndicesForActualMethod) {
|
||||
for (SleuthAnnotatedParameter container : annotatedParametersIndicesForActualMethod) {
|
||||
final int index = container.parameterIndex;
|
||||
@@ -141,20 +133,19 @@ class SpanTagAnnotationHandler {
|
||||
}
|
||||
|
||||
private String resolveTagKey(SleuthAnnotatedParameter container) {
|
||||
return StringUtils.hasText(container.annotation.value())
|
||||
? container.annotation.value() : container.annotation.key();
|
||||
return StringUtils.hasText(container.annotation.value()) ? container.annotation.value()
|
||||
: container.annotation.key();
|
||||
}
|
||||
|
||||
String resolveTagValue(SpanTag annotation, Object argument) {
|
||||
String value = null;
|
||||
if (annotation.resolver() != NoOpTagValueResolver.class) {
|
||||
TagValueResolver tagValueResolver = this.beanFactory
|
||||
.getBean(annotation.resolver());
|
||||
TagValueResolver tagValueResolver = this.beanFactory.getBean(annotation.resolver());
|
||||
value = tagValueResolver.resolve(argument);
|
||||
}
|
||||
else if (StringUtils.hasText(annotation.expression())) {
|
||||
value = this.beanFactory.getBean(TagValueExpressionResolver.class)
|
||||
.resolve(annotation.expression(), argument);
|
||||
value = this.beanFactory.getBean(TagValueExpressionResolver.class).resolve(annotation.expression(),
|
||||
argument);
|
||||
}
|
||||
else if (argument != null) {
|
||||
value = argument.toString();
|
||||
|
||||
@@ -33,22 +33,18 @@ import org.springframework.expression.spel.support.SimpleEvaluationContext;
|
||||
*/
|
||||
class SpelTagValueExpressionResolver implements TagValueExpressionResolver {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(SpelTagValueExpressionResolver.class);
|
||||
private static final Log log = LogFactory.getLog(SpelTagValueExpressionResolver.class);
|
||||
|
||||
@Override
|
||||
public String resolve(String expression, Object parameter) {
|
||||
try {
|
||||
SimpleEvaluationContext context = SimpleEvaluationContext
|
||||
.forReadOnlyDataBinding().build();
|
||||
SimpleEvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
|
||||
ExpressionParser expressionParser = new SpelExpressionParser();
|
||||
Expression expressionToEvaluate = expressionParser
|
||||
.parseExpression(expression);
|
||||
Expression expressionToEvaluate = expressionParser.parseExpression(expression);
|
||||
return expressionToEvaluate.getValue(context, parameter, String.class);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
log.error("Exception occurred while tying to evaluate the SPEL expression ["
|
||||
+ expression + "]", ex);
|
||||
log.error("Exception occurred while tying to evaluate the SPEL expression [" + expression + "]", ex);
|
||||
}
|
||||
return parameter.toString();
|
||||
}
|
||||
|
||||
@@ -93,8 +93,7 @@ class SleuthProperties {
|
||||
/**
|
||||
* List of span names to ignore. They will not be sent to external systems.
|
||||
*/
|
||||
private List<String> spanNamePatternsToSkip = Arrays
|
||||
.asList("^catalogWatchTaskScheduler$");
|
||||
private List<String> spanNamePatternsToSkip = Arrays.asList("^catalogWatchTaskScheduler$");
|
||||
|
||||
/**
|
||||
* Additional list of span names to ignore. Will be appended to
|
||||
@@ -122,8 +121,7 @@ class SleuthProperties {
|
||||
return this.additionalSpanNamePatternsToIgnore;
|
||||
}
|
||||
|
||||
public void setAdditionalSpanNamePatternsToIgnore(
|
||||
List<String> additionalSpanNamePatternsToIgnore) {
|
||||
public void setAdditionalSpanNamePatternsToIgnore(List<String> additionalSpanNamePatternsToIgnore) {
|
||||
this.additionalSpanNamePatternsToIgnore = additionalSpanNamePatternsToIgnore;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,8 +56,7 @@ class SpanIgnoringSpanHandler extends SpanHandler {
|
||||
}
|
||||
List<Pattern> spanNamesToIgnore = spanNamesToIgnore();
|
||||
String name = span.name();
|
||||
if (StringUtils.hasText(name)
|
||||
&& spanNamesToIgnore.stream().anyMatch(p -> p.matcher(name).matches())) {
|
||||
if (StringUtils.hasText(name) && spanNamesToIgnore.stream().anyMatch(p -> p.matcher(name).matches())) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will ignore a span with name [" + name + "]");
|
||||
}
|
||||
@@ -67,16 +66,14 @@ class SpanIgnoringSpanHandler extends SpanHandler {
|
||||
}
|
||||
|
||||
private List<Pattern> spanNamesToIgnore() {
|
||||
return spanNames().stream()
|
||||
.map(regex -> cache.computeIfAbsent(regex, Pattern::compile))
|
||||
return spanNames().stream().map(regex -> cache.computeIfAbsent(regex, Pattern::compile))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<String> spanNames() {
|
||||
List<String> spanNamesToIgnore = new ArrayList<>(
|
||||
this.sleuthProperties.getSpanHandler().getSpanNamePatternsToSkip());
|
||||
spanNamesToIgnore.addAll(this.sleuthProperties.getSpanHandler()
|
||||
.getAdditionalSpanNamePatternsToIgnore());
|
||||
spanNamesToIgnore.addAll(this.sleuthProperties.getSpanHandler().getAdditionalSpanNamePatternsToIgnore());
|
||||
return spanNamesToIgnore;
|
||||
}
|
||||
|
||||
|
||||
@@ -74,15 +74,12 @@ public class TraceAutoConfiguration {
|
||||
@ConditionalOnMissingBean
|
||||
// NOTE: stable bean name as might be used outside sleuth
|
||||
Tracing tracing(@LocalServiceName String serviceName, Propagation.Factory factory,
|
||||
CurrentTraceContext currentTraceContext, Sampler sampler,
|
||||
SleuthProperties sleuthProperties, @Nullable List<SpanHandler> spanHandlers,
|
||||
@Nullable List<TracingCustomizer> tracingCustomizers) {
|
||||
CurrentTraceContext currentTraceContext, Sampler sampler, SleuthProperties sleuthProperties,
|
||||
@Nullable List<SpanHandler> spanHandlers, @Nullable List<TracingCustomizer> tracingCustomizers) {
|
||||
Tracing.Builder builder = Tracing.newBuilder().sampler(sampler)
|
||||
.localServiceName(StringUtils.isEmpty(serviceName) ? DEFAULT_SERVICE_NAME
|
||||
: serviceName)
|
||||
.localServiceName(StringUtils.isEmpty(serviceName) ? DEFAULT_SERVICE_NAME : serviceName)
|
||||
.propagationFactory(factory).currentTraceContext(currentTraceContext)
|
||||
.traceId128Bit(sleuthProperties.isTraceId128())
|
||||
.supportsJoin(sleuthProperties.isSupportsJoin());
|
||||
.traceId128Bit(sleuthProperties.isTraceId128()).supportsJoin(sleuthProperties.isSupportsJoin());
|
||||
if (spanHandlers != null) {
|
||||
for (SpanHandler spanHandlerFactory : spanHandlers) {
|
||||
builder.addSpanHandler(spanHandlerFactory);
|
||||
@@ -143,8 +140,7 @@ public class TraceAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.sleuth.span-handler.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.span-handler.enabled", matchIfMissing = true)
|
||||
SpanHandler spanIgnoringSpanHandler(SleuthProperties sleuthProperties) {
|
||||
return new SpanIgnoringSpanHandler(sleuthProperties);
|
||||
}
|
||||
|
||||
@@ -122,36 +122,30 @@ class TraceBaggageConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
Propagation.Factory sleuthPropagation(
|
||||
BaggagePropagation.FactoryBuilder factoryBuilder,
|
||||
@Qualifier(BAGGAGE_KEYS) List<String> baggageKeys,
|
||||
@Qualifier(LOCAL_KEYS) List<String> localKeys,
|
||||
@Qualifier(PROPAGATION_KEYS) List<String> propagationKeys,
|
||||
SleuthBaggageProperties sleuthBaggageProperties,
|
||||
Propagation.Factory sleuthPropagation(BaggagePropagation.FactoryBuilder factoryBuilder,
|
||||
@Qualifier(BAGGAGE_KEYS) List<String> baggageKeys, @Qualifier(LOCAL_KEYS) List<String> localKeys,
|
||||
@Qualifier(PROPAGATION_KEYS) List<String> propagationKeys, SleuthBaggageProperties sleuthBaggageProperties,
|
||||
@Nullable List<BaggagePropagationCustomizer> baggagePropagationCustomizers) {
|
||||
|
||||
Set<String> localFields = redirectOldPropertyToNew(LOCAL_KEYS, localKeys,
|
||||
"spring.sleuth.baggage.local-fields",
|
||||
Set<String> localFields = redirectOldPropertyToNew(LOCAL_KEYS, localKeys, "spring.sleuth.baggage.local-fields",
|
||||
sleuthBaggageProperties.getLocalFields());
|
||||
for (String fieldName : localFields) {
|
||||
factoryBuilder.add(SingleBaggageField.local(BaggageField.create(fieldName)));
|
||||
}
|
||||
|
||||
Set<String> remoteFields = redirectOldPropertyToNew(PROPAGATION_KEYS,
|
||||
propagationKeys, "spring.sleuth.baggage.remote-fields",
|
||||
sleuthBaggageProperties.getRemoteFields());
|
||||
Set<String> remoteFields = redirectOldPropertyToNew(PROPAGATION_KEYS, propagationKeys,
|
||||
"spring.sleuth.baggage.remote-fields", sleuthBaggageProperties.getRemoteFields());
|
||||
for (String fieldName : remoteFields) {
|
||||
factoryBuilder.add(SingleBaggageField.remote(BaggageField.create(fieldName)));
|
||||
}
|
||||
|
||||
if (!baggageKeys.isEmpty()) {
|
||||
logger.warn("'" + BAGGAGE_KEYS + "' will be removed in a future release.\n"
|
||||
+ "To change header names define a @Bean of type "
|
||||
+ SingleBaggageField.class.getName());
|
||||
+ "To change header names define a @Bean of type " + SingleBaggageField.class.getName());
|
||||
|
||||
for (String key : baggageKeys) {
|
||||
factoryBuilder.add(SingleBaggageField.newBuilder(BaggageField.create(key))
|
||||
.addKeyName("baggage-" + key) // for HTTP
|
||||
factoryBuilder.add(SingleBaggageField.newBuilder(BaggageField.create(key)).addKeyName("baggage-" + key) // for
|
||||
// HTTP
|
||||
.addKeyName("baggage_" + key) // for messaging
|
||||
.build());
|
||||
}
|
||||
@@ -165,8 +159,8 @@ class TraceBaggageConfiguration {
|
||||
return factoryBuilder.build();
|
||||
}
|
||||
|
||||
static Set<String> redirectOldPropertyToNew(String oldProperty, List<String> oldValue,
|
||||
String newProperty, List<String> newValue) {
|
||||
static Set<String> redirectOldPropertyToNew(String oldProperty, List<String> oldValue, String newProperty,
|
||||
List<String> newValue) {
|
||||
Set<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
|
||||
result.addAll(newValue);
|
||||
if (!oldValue.isEmpty()) {
|
||||
@@ -187,22 +181,18 @@ class TraceBaggageConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(CorrelationScopeDecorator.class)
|
||||
@ConditionalOnBean(CorrelationScopeDecorator.Builder.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.baggage.correlation-enabled",
|
||||
matchIfMissing = true)
|
||||
ScopeDecorator correlationScopeDecorator(
|
||||
@Qualifier(WHITELISTED_MDC_KEYS) List<String> whiteListedMDCKeys,
|
||||
@ConditionalOnProperty(value = "spring.sleuth.baggage.correlation-enabled", matchIfMissing = true)
|
||||
ScopeDecorator correlationScopeDecorator(@Qualifier(WHITELISTED_MDC_KEYS) List<String> whiteListedMDCKeys,
|
||||
SleuthBaggageProperties sleuthBaggageProperties,
|
||||
@Nullable List<CorrelationScopeCustomizer> correlationScopeCustomizers) {
|
||||
|
||||
Set<String> correlationFields = redirectOldPropertyToNew(WHITELISTED_MDC_KEYS,
|
||||
whiteListedMDCKeys, "spring.sleuth.baggage.correlation-fields",
|
||||
sleuthBaggageProperties.getCorrelationFields());
|
||||
Set<String> correlationFields = redirectOldPropertyToNew(WHITELISTED_MDC_KEYS, whiteListedMDCKeys,
|
||||
"spring.sleuth.baggage.correlation-fields", sleuthBaggageProperties.getCorrelationFields());
|
||||
|
||||
// Add fields from properties
|
||||
CorrelationScopeDecorator.Builder builder = MDCScopeDecorator.newBuilder();
|
||||
for (String field : correlationFields) {
|
||||
builder.add(SingleCorrelationField.newBuilder(BaggageField.create(field))
|
||||
.build());
|
||||
builder.add(SingleCorrelationField.newBuilder(BaggageField.create(field)).build());
|
||||
}
|
||||
|
||||
// handle user overrides
|
||||
@@ -233,20 +223,17 @@ class TraceBaggageConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
SpanHandler baggageTagSpanHandler(
|
||||
@Qualifier(WHITELISTED_KEYS) List<String> whiteListedKeys,
|
||||
SpanHandler baggageTagSpanHandler(@Qualifier(WHITELISTED_KEYS) List<String> whiteListedKeys,
|
||||
SleuthBaggageProperties sleuthBaggageProperties) {
|
||||
|
||||
Set<String> tagFields = redirectOldPropertyToNew(WHITELISTED_KEYS,
|
||||
whiteListedKeys, "spring.sleuth.baggage.tag-fields",
|
||||
sleuthBaggageProperties.getTagFields());
|
||||
Set<String> tagFields = redirectOldPropertyToNew(WHITELISTED_KEYS, whiteListedKeys,
|
||||
"spring.sleuth.baggage.tag-fields", sleuthBaggageProperties.getTagFields());
|
||||
|
||||
if (tagFields.isEmpty()) {
|
||||
return SpanHandler.NOOP; // Brave ignores these
|
||||
}
|
||||
|
||||
return new BaggageTagSpanHandler(tagFields.stream().map(BaggageField::create)
|
||||
.toArray(BaggageField[]::new));
|
||||
return new BaggageTagSpanHandler(tagFields.stream().map(BaggageField::create).toArray(BaggageField[]::new));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -39,21 +39,18 @@ class TraceEnvironmentPostProcessor implements EnvironmentPostProcessor {
|
||||
private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment,
|
||||
SpringApplication application) {
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
// This doesn't work with all logging systems but it's a useful default so you see
|
||||
// traces in logs without having to configure it.
|
||||
if (Boolean
|
||||
.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"))) {
|
||||
map.put("logging.pattern.level", "%5p [${spring.zipkin.service.name:"
|
||||
+ "${spring.application.name:}},%X{traceId:-},%X{spanId:-}]");
|
||||
if (Boolean.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"))) {
|
||||
map.put("logging.pattern.level",
|
||||
"%5p [${spring.zipkin.service.name:" + "${spring.application.name:}},%X{traceId:-},%X{spanId:-}]");
|
||||
}
|
||||
addOrReplace(environment.getPropertySources(), map);
|
||||
}
|
||||
|
||||
private void addOrReplace(MutablePropertySources propertySources,
|
||||
Map<String, Object> map) {
|
||||
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
|
||||
MapPropertySource target = null;
|
||||
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
|
||||
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
|
||||
|
||||
@@ -39,24 +39,20 @@ import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
@ConditionalOnBean(AsyncConfigurer.class)
|
||||
@AutoConfigureBefore(AsyncDefaultAutoConfiguration.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.async.enabled", matchIfMissing = true)
|
||||
@AutoConfigureAfter(
|
||||
name = "org.springframework.cloud.sleuth.instrument.scheduling.TraceSchedulingAutoConfiguration")
|
||||
@AutoConfigureAfter(name = "org.springframework.cloud.sleuth.instrument.scheduling.TraceSchedulingAutoConfiguration")
|
||||
class AsyncCustomAutoConfiguration implements BeanPostProcessor {
|
||||
|
||||
@Autowired
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
if (bean instanceof AsyncConfigurer
|
||||
&& !(bean instanceof LazyTraceAsyncCustomizer)) {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof AsyncConfigurer && !(bean instanceof LazyTraceAsyncCustomizer)) {
|
||||
AsyncConfigurer configurer = (AsyncConfigurer) bean;
|
||||
return new LazyTraceAsyncCustomizer(this.beanFactory, configurer);
|
||||
}
|
||||
|
||||
@@ -59,10 +59,8 @@ import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
|
||||
class AsyncDefaultAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.sleuth.scheduled.enabled",
|
||||
matchIfMissing = true)
|
||||
public static ExecutorBeanPostProcessor executorBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
@ConditionalOnProperty(value = "spring.sleuth.scheduled.enabled", matchIfMissing = true)
|
||||
public static ExecutorBeanPostProcessor executorBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new ExecutorBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
@@ -76,13 +74,11 @@ class AsyncDefaultAutoConfiguration {
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnMissingBean(AsyncConfigurer.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.async.configurer.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.async.configurer.enabled", matchIfMissing = true)
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
static class DefaultAsyncConfigurerSupport extends AsyncConfigurerSupport {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(DefaultAsyncConfigurerSupport.class);
|
||||
private static final Log log = LogFactory.getLog(DefaultAsyncConfigurerSupport.class);
|
||||
|
||||
@Autowired
|
||||
private BeanFactory beanFactory;
|
||||
@@ -113,25 +109,21 @@ class AsyncDefaultAutoConfiguration {
|
||||
catch (NoUniqueBeanDefinitionException ex) {
|
||||
log.debug("Could not find unique TaskExecutor bean", ex);
|
||||
try {
|
||||
return this.beanFactory.getBean(
|
||||
AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME,
|
||||
return this.beanFactory.getBean(AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME,
|
||||
Executor.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex2) {
|
||||
if (log.isInfoEnabled()) {
|
||||
log.info(
|
||||
"More than one TaskExecutor bean found within the context, and none is named "
|
||||
+ "'taskExecutor'. Mark one of them as primary or name it 'taskExecutor' (possibly "
|
||||
+ "as an alias) in order to use it for async processing: "
|
||||
+ ex.getBeanNamesFound());
|
||||
log.info("More than one TaskExecutor bean found within the context, and none is named "
|
||||
+ "'taskExecutor'. Mark one of them as primary or name it 'taskExecutor' (possibly "
|
||||
+ "as an alias) in order to use it for async processing: " + ex.getBeanNamesFound());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
log.debug("Could not find default TaskExecutor bean", ex);
|
||||
try {
|
||||
return this.beanFactory.getBean(
|
||||
AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME,
|
||||
return this.beanFactory.getBean(AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME,
|
||||
Executor.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex2) {
|
||||
|
||||
@@ -64,18 +64,14 @@ class ExecutorBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
if (bean instanceof LazyTraceThreadPoolTaskExecutor
|
||||
|| bean instanceof TraceableScheduledExecutorService
|
||||
|| bean instanceof TraceableExecutorService
|
||||
|| bean instanceof LazyTraceAsyncTaskExecutor
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof LazyTraceThreadPoolTaskExecutor || bean instanceof TraceableScheduledExecutorService
|
||||
|| bean instanceof TraceableExecutorService || bean instanceof LazyTraceAsyncTaskExecutor
|
||||
|| bean instanceof LazyTraceExecutor) {
|
||||
log.info("Bean is already instrumented " + beanName);
|
||||
return bean;
|
||||
@@ -124,18 +120,14 @@ class ExecutorBeanPostProcessor implements BeanPostProcessor {
|
||||
boolean classFinal = Modifier.isFinal(bean.getClass().getModifiers());
|
||||
boolean cglibProxy = !methodFinal && !classFinal;
|
||||
try {
|
||||
return createProxy(bean, cglibProxy, new ExecutorMethodInterceptor<>(executor,
|
||||
this.beanFactory, beanName));
|
||||
return createProxy(bean, cglibProxy, new ExecutorMethodInterceptor<>(executor, this.beanFactory, beanName));
|
||||
}
|
||||
catch (AopConfigException ex) {
|
||||
if (cglibProxy) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Exception occurred while trying to create a proxy, falling back to JDK proxy",
|
||||
ex);
|
||||
log.debug("Exception occurred while trying to create a proxy, falling back to JDK proxy", ex);
|
||||
}
|
||||
return createProxy(bean, false, new ExecutorMethodInterceptor<>(executor,
|
||||
this.beanFactory, beanName));
|
||||
return createProxy(bean, false, new ExecutorMethodInterceptor<>(executor, this.beanFactory, beanName));
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
@@ -178,70 +170,58 @@ class ExecutorBeanPostProcessor implements BeanPostProcessor {
|
||||
return !sleuthAsyncProperties.getIgnoredBeans().contains(beanName);
|
||||
}
|
||||
|
||||
Object createThreadPoolTaskExecutorProxy(Object bean, boolean cglibProxy,
|
||||
ThreadPoolTaskExecutor executor, String beanName) {
|
||||
Object createThreadPoolTaskExecutorProxy(Object bean, boolean cglibProxy, ThreadPoolTaskExecutor executor,
|
||||
String beanName) {
|
||||
if (!cglibProxy) {
|
||||
return new LazyTraceThreadPoolTaskExecutor(this.beanFactory, executor,
|
||||
beanName);
|
||||
return new LazyTraceThreadPoolTaskExecutor(this.beanFactory, executor, beanName);
|
||||
}
|
||||
return getProxiedObject(bean, beanName, true, executor,
|
||||
() -> new LazyTraceThreadPoolTaskExecutor(this.beanFactory, executor,
|
||||
beanName));
|
||||
() -> new LazyTraceThreadPoolTaskExecutor(this.beanFactory, executor, beanName));
|
||||
}
|
||||
|
||||
Supplier<Executor> createThreadPoolTaskSchedulerProxy(
|
||||
ThreadPoolTaskScheduler executor, String beanName) {
|
||||
return () -> new LazyTraceThreadPoolTaskScheduler(this.beanFactory, executor,
|
||||
beanName);
|
||||
Supplier<Executor> createThreadPoolTaskSchedulerProxy(ThreadPoolTaskScheduler executor, String beanName) {
|
||||
return () -> new LazyTraceThreadPoolTaskScheduler(this.beanFactory, executor, beanName);
|
||||
}
|
||||
|
||||
Supplier<Executor> createScheduledThreadPoolExecutorProxy(
|
||||
ScheduledThreadPoolExecutor executor, String beanName) {
|
||||
return () -> new LazyTraceScheduledThreadPoolExecutor(executor.getCorePoolSize(),
|
||||
executor.getThreadFactory(), executor.getRejectedExecutionHandler(),
|
||||
this.beanFactory, executor, beanName);
|
||||
Supplier<Executor> createScheduledThreadPoolExecutorProxy(ScheduledThreadPoolExecutor executor, String beanName) {
|
||||
return () -> new LazyTraceScheduledThreadPoolExecutor(executor.getCorePoolSize(), executor.getThreadFactory(),
|
||||
executor.getRejectedExecutionHandler(), this.beanFactory, executor, beanName);
|
||||
}
|
||||
|
||||
Object createExecutorServiceProxy(Object bean, boolean cglibProxy,
|
||||
ExecutorService executor, String beanName) {
|
||||
Object createExecutorServiceProxy(Object bean, boolean cglibProxy, ExecutorService executor, String beanName) {
|
||||
return getProxiedObject(bean, beanName, cglibProxy, executor, () -> {
|
||||
if (executor instanceof ScheduledExecutorService) {
|
||||
return new TraceableScheduledExecutorService(this.beanFactory, executor,
|
||||
beanName);
|
||||
return new TraceableScheduledExecutorService(this.beanFactory, executor, beanName);
|
||||
}
|
||||
return new TraceableExecutorService(this.beanFactory, executor, beanName);
|
||||
});
|
||||
}
|
||||
|
||||
Object createScheduledExecutorServiceProxy(Object bean, boolean cglibProxy,
|
||||
ScheduledExecutorService executor, String beanName) {
|
||||
Object createScheduledExecutorServiceProxy(Object bean, boolean cglibProxy, ScheduledExecutorService executor,
|
||||
String beanName) {
|
||||
return getProxiedObject(bean, beanName, cglibProxy, executor,
|
||||
() -> new TraceableScheduledExecutorService(this.beanFactory, executor,
|
||||
beanName));
|
||||
() -> new TraceableScheduledExecutorService(this.beanFactory, executor, beanName));
|
||||
}
|
||||
|
||||
Object createAsyncTaskExecutorProxy(Object bean, boolean cglibProxy,
|
||||
AsyncTaskExecutor executor, String beanName) {
|
||||
Object createAsyncTaskExecutorProxy(Object bean, boolean cglibProxy, AsyncTaskExecutor executor, String beanName) {
|
||||
return getProxiedObject(bean, beanName, cglibProxy, executor, () -> {
|
||||
if (bean instanceof ThreadPoolTaskScheduler) {
|
||||
return new LazyTraceThreadPoolTaskScheduler(this.beanFactory,
|
||||
(ThreadPoolTaskScheduler) executor, beanName);
|
||||
return new LazyTraceThreadPoolTaskScheduler(this.beanFactory, (ThreadPoolTaskScheduler) executor,
|
||||
beanName);
|
||||
}
|
||||
return new LazyTraceAsyncTaskExecutor(this.beanFactory, executor, beanName);
|
||||
});
|
||||
}
|
||||
|
||||
private Object getProxiedObject(Object bean, String beanName, boolean cglibProxy,
|
||||
Executor executor, Supplier<Executor> supplier) {
|
||||
ProxyFactoryBean factory = proxyFactoryBean(bean, beanName, cglibProxy, executor,
|
||||
supplier);
|
||||
private Object getProxiedObject(Object bean, String beanName, boolean cglibProxy, Executor executor,
|
||||
Supplier<Executor> supplier) {
|
||||
ProxyFactoryBean factory = proxyFactoryBean(bean, beanName, cglibProxy, executor, supplier);
|
||||
try {
|
||||
return getObject(factory);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Exception occurred while trying to get a proxy. Will fallback to a different implementation",
|
||||
log.debug("Exception occurred while trying to get a proxy. Will fallback to a different implementation",
|
||||
ex);
|
||||
}
|
||||
try {
|
||||
@@ -250,38 +230,32 @@ class ExecutorBeanPostProcessor implements BeanPostProcessor {
|
||||
log.debug(
|
||||
"Will wrap ThreadPoolTaskScheduler in its tracing representation due to previous errors");
|
||||
}
|
||||
return createThreadPoolTaskSchedulerProxy(
|
||||
(ThreadPoolTaskScheduler) bean, beanName).get();
|
||||
return createThreadPoolTaskSchedulerProxy((ThreadPoolTaskScheduler) bean, beanName).get();
|
||||
}
|
||||
else if (bean instanceof ScheduledThreadPoolExecutor) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Will wrap ScheduledThreadPoolExecutor in its tracing representation due to previous errors");
|
||||
}
|
||||
return createScheduledThreadPoolExecutorProxy(
|
||||
(ScheduledThreadPoolExecutor) bean, beanName).get();
|
||||
return createScheduledThreadPoolExecutorProxy((ScheduledThreadPoolExecutor) bean, beanName).get();
|
||||
}
|
||||
}
|
||||
catch (Exception ex2) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Fallback for special wrappers failed, will try the tracing representation instead",
|
||||
ex2);
|
||||
log.debug("Fallback for special wrappers failed, will try the tracing representation instead", ex2);
|
||||
}
|
||||
}
|
||||
return supplier.get();
|
||||
}
|
||||
}
|
||||
|
||||
private ProxyFactoryBean proxyFactoryBean(Object bean, String beanName,
|
||||
boolean cglibProxy, Executor executor, Supplier<Executor> supplier) {
|
||||
private ProxyFactoryBean proxyFactoryBean(Object bean, String beanName, boolean cglibProxy, Executor executor,
|
||||
Supplier<Executor> supplier) {
|
||||
ProxyFactoryBean factory = new ProxyFactoryBean();
|
||||
factory.setProxyTargetClass(cglibProxy);
|
||||
factory.addAdvice(new ExecutorMethodInterceptor<Executor>(executor,
|
||||
this.beanFactory, beanName) {
|
||||
factory.addAdvice(new ExecutorMethodInterceptor<Executor>(executor, this.beanFactory, beanName) {
|
||||
@Override
|
||||
Executor executor(BeanFactory beanFactory, Executor executor,
|
||||
String beanName) {
|
||||
Executor executor(BeanFactory beanFactory, Executor executor, String beanName) {
|
||||
return supplier.get();
|
||||
}
|
||||
});
|
||||
@@ -304,23 +278,19 @@ class ExecutorBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
private SleuthAsyncProperties asyncConfigurationProperties() {
|
||||
if (this.sleuthAsyncProperties == null) {
|
||||
this.sleuthAsyncProperties = this.beanFactory
|
||||
.getBean(SleuthAsyncProperties.class);
|
||||
this.sleuthAsyncProperties = this.beanFactory.getBean(SleuthAsyncProperties.class);
|
||||
}
|
||||
return this.sleuthAsyncProperties;
|
||||
}
|
||||
|
||||
private static <T> boolean anyFinalMethods(T object) {
|
||||
try {
|
||||
for (Method method : ReflectionUtils
|
||||
.getAllDeclaredMethods(object.getClass())) {
|
||||
for (Method method : ReflectionUtils.getAllDeclaredMethods(object.getClass())) {
|
||||
if (method.getDeclaringClass().equals(Object.class)) {
|
||||
continue;
|
||||
}
|
||||
Method m = ReflectionUtils.findMethod(object.getClass(), method.getName(),
|
||||
method.getParameterTypes());
|
||||
if (m != null && Modifier.isPublic(m.getModifiers())
|
||||
&& Modifier.isFinal(m.getModifiers())) {
|
||||
Method m = ReflectionUtils.findMethod(object.getClass(), method.getName(), method.getParameterTypes());
|
||||
if (m != null && Modifier.isPublic(m.getModifiers()) && Modifier.isFinal(m.getModifiers())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -375,8 +345,7 @@ class ExecutorMethodInterceptor<T extends Executor> implements MethodInterceptor
|
||||
|
||||
private Method getMethod(MethodInvocation invocation, Object object) {
|
||||
Method method = invocation.getMethod();
|
||||
return ReflectionUtils.findMethod(object.getClass(), method.getName(),
|
||||
method.getParameterTypes());
|
||||
return ReflectionUtils.findMethod(object.getClass(), method.getName(), method.getParameterTypes());
|
||||
}
|
||||
|
||||
T executor(BeanFactory beanFactory, T executor, String beanName) {
|
||||
|
||||
@@ -51,15 +51,13 @@ public class LazyTraceAsyncTaskExecutor implements AsyncTaskExecutor {
|
||||
|
||||
private SpanNamer spanNamer;
|
||||
|
||||
public LazyTraceAsyncTaskExecutor(BeanFactory beanFactory,
|
||||
AsyncTaskExecutor delegate) {
|
||||
public LazyTraceAsyncTaskExecutor(BeanFactory beanFactory, AsyncTaskExecutor delegate) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = null;
|
||||
}
|
||||
|
||||
public LazyTraceAsyncTaskExecutor(BeanFactory beanFactory, AsyncTaskExecutor delegate,
|
||||
String beanName) {
|
||||
public LazyTraceAsyncTaskExecutor(BeanFactory beanFactory, AsyncTaskExecutor delegate, String beanName) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
@@ -108,8 +106,7 @@ public class LazyTraceAsyncTaskExecutor implements AsyncTaskExecutor {
|
||||
this.spanNamer = this.beanFactory.getBean(SpanNamer.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
log.warn(
|
||||
"SpanNamer bean not found - will provide a manually created instance");
|
||||
log.warn("SpanNamer bean not found - will provide a manually created instance");
|
||||
return new DefaultSpanNamer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,7 @@ public class LazyTraceExecutor implements Executor {
|
||||
this.beanName = null;
|
||||
}
|
||||
|
||||
public LazyTraceExecutor(BeanFactory beanFactory, Executor delegate,
|
||||
String beanName) {
|
||||
public LazyTraceExecutor(BeanFactory beanFactory, Executor delegate, String beanName) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
@@ -76,8 +75,7 @@ public class LazyTraceExecutor implements Executor {
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.delegate.execute(
|
||||
new TraceRunnable(this.tracing, spanNamer(), command, this.beanName));
|
||||
this.delegate.execute(new TraceRunnable(this.tracing, spanNamer(), command, this.beanName));
|
||||
}
|
||||
|
||||
// due to some race conditions trace keys might not be ready yet
|
||||
@@ -87,8 +85,7 @@ public class LazyTraceExecutor implements Executor {
|
||||
this.spanNamer = this.beanFactory.getBean(SpanNamer.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
log.warn(
|
||||
"SpanNamer bean not found - will provide a manually created instance");
|
||||
log.warn("SpanNamer bean not found - will provide a manually created instance");
|
||||
return new DefaultSpanNamer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@ import org.springframework.util.ReflectionUtils;
|
||||
// TODO: Think of a better solution than this
|
||||
class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(LazyTraceScheduledThreadPoolExecutor.class);
|
||||
private static final Log log = LogFactory.getLog(LazyTraceScheduledThreadPoolExecutor.class);
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -88,33 +87,25 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
this.decorateTaskRunnable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "decorateTask", Runnable.class,
|
||||
RunnableScheduledFuture.class);
|
||||
this.decorateTaskRunnable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "decorateTask",
|
||||
Runnable.class, RunnableScheduledFuture.class);
|
||||
makeAccessibleIfNotNull(this.decorateTaskRunnable);
|
||||
this.decorateTaskCallable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "decorateTaskCallable", Callable.class,
|
||||
RunnableScheduledFuture.class);
|
||||
this.decorateTaskCallable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"decorateTaskCallable", Callable.class, RunnableScheduledFuture.class);
|
||||
makeAccessibleIfNotNull(this.decorateTaskCallable);
|
||||
this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"finalize", null);
|
||||
this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "finalize", null);
|
||||
makeAccessibleIfNotNull(this.finalize);
|
||||
this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"beforeExecute", null);
|
||||
this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "beforeExecute", null);
|
||||
makeAccessibleIfNotNull(this.beforeExecute);
|
||||
this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"afterExecute", null);
|
||||
this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "afterExecute", null);
|
||||
makeAccessibleIfNotNull(this.afterExecute);
|
||||
this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"terminated", null);
|
||||
this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "terminated", null);
|
||||
makeAccessibleIfNotNull(this.terminated);
|
||||
this.newTaskForRunnable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "newTaskFor", Runnable.class,
|
||||
Object.class);
|
||||
this.newTaskForRunnable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "newTaskFor",
|
||||
Runnable.class, Object.class);
|
||||
makeAccessibleIfNotNull(this.newTaskForRunnable);
|
||||
this.newTaskForCallable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "newTaskFor", Callable.class,
|
||||
Object.class);
|
||||
this.newTaskForCallable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "newTaskFor",
|
||||
Callable.class, Object.class);
|
||||
makeAccessibleIfNotNull(this.newTaskForCallable);
|
||||
}
|
||||
|
||||
@@ -125,114 +116,89 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
}
|
||||
|
||||
LazyTraceScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler handler, BeanFactory beanFactory,
|
||||
ScheduledThreadPoolExecutor delegate, String beanName) {
|
||||
RejectedExecutionHandler handler, BeanFactory beanFactory, ScheduledThreadPoolExecutor delegate,
|
||||
String beanName) {
|
||||
super(corePoolSize, threadFactory, handler);
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
this.decorateTaskRunnable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "decorateTask", Runnable.class,
|
||||
RunnableScheduledFuture.class);
|
||||
this.decorateTaskRunnable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "decorateTask",
|
||||
Runnable.class, RunnableScheduledFuture.class);
|
||||
makeAccessibleIfNotNull(this.decorateTaskRunnable);
|
||||
this.decorateTaskCallable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "decorateTaskCallable", Callable.class,
|
||||
RunnableScheduledFuture.class);
|
||||
this.decorateTaskCallable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"decorateTaskCallable", Callable.class, RunnableScheduledFuture.class);
|
||||
makeAccessibleIfNotNull(this.decorateTaskCallable);
|
||||
this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"finalize", null);
|
||||
this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "finalize", null);
|
||||
makeAccessibleIfNotNull(this.finalize);
|
||||
this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"beforeExecute", null);
|
||||
this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "beforeExecute", null);
|
||||
makeAccessibleIfNotNull(this.beforeExecute);
|
||||
this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"afterExecute", null);
|
||||
this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "afterExecute", null);
|
||||
makeAccessibleIfNotNull(this.afterExecute);
|
||||
this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class,
|
||||
"terminated");
|
||||
this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "terminated");
|
||||
makeAccessibleIfNotNull(this.terminated);
|
||||
this.newTaskForRunnable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "newTaskFor", Runnable.class,
|
||||
Object.class);
|
||||
this.newTaskForRunnable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "newTaskFor",
|
||||
Runnable.class, Object.class);
|
||||
makeAccessibleIfNotNull(this.newTaskForRunnable);
|
||||
this.newTaskForCallable = ReflectionUtils.findMethod(
|
||||
ScheduledThreadPoolExecutor.class, "newTaskFor", Callable.class,
|
||||
Object.class);
|
||||
this.newTaskForCallable = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "newTaskFor",
|
||||
Callable.class, Object.class);
|
||||
makeAccessibleIfNotNull(this.newTaskForCallable);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable,
|
||||
RunnableScheduledFuture<V> task) {
|
||||
return (RunnableScheduledFuture<V>) ReflectionUtils.invokeMethod(
|
||||
this.decorateTaskRunnable, this.delegate,
|
||||
public <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
|
||||
return (RunnableScheduledFuture<V>) ReflectionUtils.invokeMethod(this.decorateTaskRunnable, this.delegate,
|
||||
new TraceRunnable(tracing(), spanNamer(), runnable, this.beanName), task);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable,
|
||||
RunnableScheduledFuture<V> task) {
|
||||
return (RunnableScheduledFuture<V>) ReflectionUtils.invokeMethod(
|
||||
this.decorateTaskCallable, this.delegate,
|
||||
new TraceCallable<>(tracing(), spanNamer(), callable, this.beanName),
|
||||
task);
|
||||
public <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {
|
||||
return (RunnableScheduledFuture<V>) ReflectionUtils.invokeMethod(this.decorateTaskCallable, this.delegate,
|
||||
new TraceCallable<>(tracing(), spanNamer(), callable, this.beanName), task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
|
||||
return this.delegate.schedule(
|
||||
new TraceRunnable(tracing(), spanNamer(), command, this.beanName), delay,
|
||||
return this.delegate.schedule(new TraceRunnable(tracing(), spanNamer(), command, this.beanName), delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
|
||||
return this.delegate.schedule(new TraceCallable<>(tracing(), spanNamer(), callable, this.beanName), delay,
|
||||
unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
|
||||
TimeUnit unit) {
|
||||
return this.delegate.schedule(
|
||||
new TraceCallable<>(tracing(), spanNamer(), callable, this.beanName),
|
||||
delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
|
||||
long period, TimeUnit unit) {
|
||||
return this.delegate.scheduleAtFixedRate(
|
||||
new TraceRunnable(tracing(), spanNamer(), command, this.beanName),
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
|
||||
return this.delegate.scheduleAtFixedRate(new TraceRunnable(tracing(), spanNamer(), command, this.beanName),
|
||||
initialDelay, period, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
|
||||
long delay, TimeUnit unit) {
|
||||
return this.delegate.scheduleWithFixedDelay(
|
||||
new TraceRunnable(tracing(), spanNamer(), command, this.beanName),
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
|
||||
return this.delegate.scheduleWithFixedDelay(new TraceRunnable(tracing(), spanNamer(), command, this.beanName),
|
||||
initialDelay, delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Runnable command) {
|
||||
this.delegate.execute(
|
||||
new TraceRunnable(tracing(), spanNamer(), command, this.beanName));
|
||||
this.delegate.execute(new TraceRunnable(tracing(), spanNamer(), command, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<?> submit(Runnable task) {
|
||||
return this.delegate
|
||||
.submit(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submit(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Runnable task, T result) {
|
||||
return this.delegate.submit(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), result);
|
||||
return this.delegate.submit(new TraceRunnable(tracing(), spanNamer(), task, this.beanName), result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Callable<T> task) {
|
||||
return this.delegate
|
||||
.submit(new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submit(new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -296,8 +262,7 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean awaitTermination(long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return this.delegate.awaitTermination(timeout, unit);
|
||||
}
|
||||
|
||||
@@ -435,28 +400,23 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
|
||||
return (RunnableFuture<T>) ReflectionUtils.invokeMethod(this.newTaskForRunnable,
|
||||
this.delegate,
|
||||
new TraceRunnable(tracing(), spanNamer(), runnable, this.beanName),
|
||||
value);
|
||||
return (RunnableFuture<T>) ReflectionUtils.invokeMethod(this.newTaskForRunnable, this.delegate,
|
||||
new TraceRunnable(tracing(), spanNamer(), runnable, this.beanName), value);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
|
||||
return (RunnableFuture<T>) ReflectionUtils.invokeMethod(this.newTaskForCallable,
|
||||
this.delegate,
|
||||
return (RunnableFuture<T>) ReflectionUtils.invokeMethod(this.newTaskForCallable, this.delegate,
|
||||
new TraceCallable<>(tracing(), spanNamer(), callable, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
|
||||
throws InterruptedException, ExecutionException {
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
|
||||
return this.delegate.invokeAny(wrapCallableCollection(tasks));
|
||||
}
|
||||
|
||||
private <T> Collection<? extends Callable<T>> wrapCallableCollection(
|
||||
Collection<? extends Callable<T>> tasks) {
|
||||
private <T> Collection<? extends Callable<T>> wrapCallableCollection(Collection<? extends Callable<T>> tasks) {
|
||||
List<Callable<T>> ts = new ArrayList<>();
|
||||
for (Callable<T> task : tasks) {
|
||||
if (!(task instanceof TraceCallable)) {
|
||||
@@ -467,21 +427,19 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout,
|
||||
TimeUnit unit)
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException, ExecutionException, TimeoutException {
|
||||
return this.delegate.invokeAny(wrapCallableCollection(tasks), timeout, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
|
||||
throws InterruptedException {
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
|
||||
return this.delegate.invokeAll(wrapCallableCollection(tasks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
|
||||
long timeout, TimeUnit unit) throws InterruptedException {
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
return this.delegate.invokeAll(wrapCallableCollection(tasks), timeout, unit);
|
||||
}
|
||||
|
||||
@@ -498,8 +456,7 @@ class LazyTraceScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
|
||||
this.spanNamer = this.beanFactory.getBean(SpanNamer.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
log.warn(
|
||||
"SpanNamer bean not found - will provide a manually created instance");
|
||||
log.warn("SpanNamer bean not found - will provide a manually created instance");
|
||||
return new DefaultSpanNamer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +44,7 @@ import org.springframework.util.concurrent.ListenableFuture;
|
||||
// public as most types in this package were documented for use
|
||||
public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(LazyTraceThreadPoolTaskExecutor.class);
|
||||
private static final Log log = LogFactory.getLog(LazyTraceThreadPoolTaskExecutor.class);
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -57,15 +56,13 @@ public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
|
||||
private SpanNamer spanNamer;
|
||||
|
||||
public LazyTraceThreadPoolTaskExecutor(BeanFactory beanFactory,
|
||||
ThreadPoolTaskExecutor delegate) {
|
||||
public LazyTraceThreadPoolTaskExecutor(BeanFactory beanFactory, ThreadPoolTaskExecutor delegate) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = null;
|
||||
}
|
||||
|
||||
public LazyTraceThreadPoolTaskExecutor(BeanFactory beanFactory,
|
||||
ThreadPoolTaskExecutor delegate, String beanName) {
|
||||
public LazyTraceThreadPoolTaskExecutor(BeanFactory beanFactory, ThreadPoolTaskExecutor delegate, String beanName) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
@@ -79,10 +76,8 @@ public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
|
||||
@Override
|
||||
public void execute(Runnable task, long startTimeout) {
|
||||
this.delegate.execute(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTimeout);
|
||||
this.delegate.execute(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTimeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -99,17 +94,14 @@ public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
|
||||
@Override
|
||||
public ListenableFuture<?> submitListenable(Runnable task) {
|
||||
return this.delegate
|
||||
.submitListenable(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submitListenable(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
|
||||
return this.delegate
|
||||
.submitListenable(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceCallable<>(tracing(), spanNamer(), task,
|
||||
this.beanName));
|
||||
return this.delegate.submitListenable(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -123,16 +115,13 @@ public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRejectedExecutionHandler(
|
||||
RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
this.delegate.setRejectedExecutionHandler(rejectedExecutionHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWaitForTasksToCompleteOnShutdown(
|
||||
boolean waitForJobsToCompleteOnShutdown) {
|
||||
this.delegate
|
||||
.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown);
|
||||
public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
|
||||
this.delegate.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -296,8 +285,7 @@ public class LazyTraceThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
this.spanNamer = this.beanFactory.getBean(SpanNamer.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
log.warn(
|
||||
"SpanNamer bean not found - will provide a manually created instance");
|
||||
log.warn("SpanNamer bean not found - will provide a manually created instance");
|
||||
return new DefaultSpanNamer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,8 +55,7 @@ import org.springframework.util.concurrent.ListenableFuture;
|
||||
// TODO: Think of a better solution than this
|
||||
class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(LazyTraceThreadPoolTaskScheduler.class);
|
||||
private static final Log log = LogFactory.getLog(LazyTraceThreadPoolTaskScheduler.class);
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -78,25 +77,21 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
|
||||
private SpanNamer spanNamer;
|
||||
|
||||
LazyTraceThreadPoolTaskScheduler(BeanFactory beanFactory,
|
||||
ThreadPoolTaskScheduler delegate, String beanName) {
|
||||
LazyTraceThreadPoolTaskScheduler(BeanFactory beanFactory, ThreadPoolTaskScheduler delegate, String beanName) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.delegate = delegate;
|
||||
this.beanName = beanName;
|
||||
this.initializeExecutor = ReflectionUtils
|
||||
.findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null);
|
||||
this.initializeExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "initializeExecutor", null);
|
||||
makeAccessibleIfNotNull(this.initializeExecutor);
|
||||
this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
|
||||
"createExecutor", null);
|
||||
this.createExecutor = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "createExecutor", null);
|
||||
makeAccessibleIfNotNull(this.createExecutor);
|
||||
this.cancelRemainingTask = ReflectionUtils
|
||||
.findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask", null);
|
||||
this.cancelRemainingTask = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "cancelRemainingTask",
|
||||
null);
|
||||
makeAccessibleIfNotNull(this.cancelRemainingTask);
|
||||
this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class,
|
||||
"nextThreadName", null);
|
||||
this.nextThreadName = ReflectionUtils.findMethod(ThreadPoolTaskScheduler.class, "nextThreadName", null);
|
||||
makeAccessibleIfNotNull(this.nextThreadName);
|
||||
this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod(
|
||||
CustomizableThreadCreator.class, "getDefaultThreadNamePrefix", null);
|
||||
this.getDefaultThreadNamePrefix = ReflectionUtils.findMethod(CustomizableThreadCreator.class,
|
||||
"getDefaultThreadNamePrefix", null);
|
||||
makeAccessibleIfNotNull(this.getDefaultThreadNamePrefix);
|
||||
}
|
||||
|
||||
@@ -124,54 +119,45 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
@Override
|
||||
public ExecutorService initializeExecutor(ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
ExecutorService executorService = (ExecutorService) ReflectionUtils.invokeMethod(
|
||||
this.initializeExecutor, this.delegate, traceThreadFactory(threadFactory),
|
||||
ExecutorService executorService = (ExecutorService) ReflectionUtils.invokeMethod(this.initializeExecutor,
|
||||
this.delegate, traceThreadFactory(threadFactory), rejectedExecutionHandler);
|
||||
if (executorService instanceof TraceableScheduledExecutorService) {
|
||||
return executorService;
|
||||
}
|
||||
return new TraceableExecutorService(this.beanFactory, executorService, this.beanName);
|
||||
}
|
||||
|
||||
private ThreadFactory traceThreadFactory(ThreadFactory threadFactory) {
|
||||
return r -> threadFactory.newThread(new TraceRunnable(tracing(), spanNamer(), r, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
ScheduledExecutorService executorService = (ScheduledExecutorService) ReflectionUtils.invokeMethod(
|
||||
this.createExecutor, this.delegate, poolSize, traceThreadFactory(threadFactory),
|
||||
rejectedExecutionHandler);
|
||||
if (executorService instanceof TraceableScheduledExecutorService) {
|
||||
return executorService;
|
||||
}
|
||||
return new TraceableExecutorService(this.beanFactory, executorService,
|
||||
this.beanName);
|
||||
}
|
||||
|
||||
private ThreadFactory traceThreadFactory(ThreadFactory threadFactory) {
|
||||
return r -> threadFactory
|
||||
.newThread(new TraceRunnable(tracing(), spanNamer(), r, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledExecutorService createExecutor(int poolSize,
|
||||
ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
ScheduledExecutorService executorService = (ScheduledExecutorService) ReflectionUtils
|
||||
.invokeMethod(this.createExecutor, this.delegate, poolSize,
|
||||
traceThreadFactory(threadFactory), rejectedExecutionHandler);
|
||||
if (executorService instanceof TraceableScheduledExecutorService) {
|
||||
return executorService;
|
||||
}
|
||||
return new TraceableScheduledExecutorService(this.beanFactory, executorService,
|
||||
this.beanName);
|
||||
return new TraceableScheduledExecutorService(this.beanFactory, executorService, this.beanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException {
|
||||
ScheduledExecutorService executor = this.delegate.getScheduledExecutor();
|
||||
return executor instanceof TraceableScheduledExecutorService ? executor
|
||||
: new TraceableScheduledExecutorService(this.beanFactory, executor,
|
||||
this.beanName);
|
||||
: new TraceableScheduledExecutorService(this.beanFactory, executor, this.beanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor()
|
||||
throws IllegalStateException {
|
||||
ScheduledThreadPoolExecutor executor = this.delegate
|
||||
.getScheduledThreadPoolExecutor();
|
||||
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() throws IllegalStateException {
|
||||
ScheduledThreadPoolExecutor executor = this.delegate.getScheduledThreadPoolExecutor();
|
||||
if (executor instanceof LazyTraceScheduledThreadPoolExecutor) {
|
||||
return executor;
|
||||
}
|
||||
return new LazyTraceScheduledThreadPoolExecutor(executor.getCorePoolSize(),
|
||||
executor.getThreadFactory(), executor.getRejectedExecutionHandler(),
|
||||
this.beanFactory, executor, this.beanName);
|
||||
return new LazyTraceScheduledThreadPoolExecutor(executor.getCorePoolSize(), executor.getThreadFactory(),
|
||||
executor.getRejectedExecutionHandler(), this.beanFactory, executor, this.beanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -191,39 +177,32 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
|
||||
@Override
|
||||
public void execute(Runnable task) {
|
||||
this.delegate
|
||||
.execute(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
this.delegate.execute(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Runnable task, long startTimeout) {
|
||||
this.delegate.execute(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTimeout);
|
||||
this.delegate.execute(new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTimeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<?> submit(Runnable task) {
|
||||
return this.delegate
|
||||
.submit(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submit(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Callable<T> task) {
|
||||
return this.delegate
|
||||
.submit(new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submit(new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<?> submitListenable(Runnable task) {
|
||||
return this.delegate.submitListenable(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submitListenable(new TraceRunnable(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
|
||||
return this.delegate.submitListenable(
|
||||
new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
return this.delegate.submitListenable(new TraceCallable<>(tracing(), spanNamer(), task, this.beanName));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -240,43 +219,36 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
@Override
|
||||
@Nullable
|
||||
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
|
||||
return this.delegate.schedule(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), trigger);
|
||||
return this.delegate.schedule(new TraceRunnable(tracing(), spanNamer(), task, this.beanName), trigger);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
|
||||
return this.delegate.schedule(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime);
|
||||
return this.delegate.schedule(new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime,
|
||||
long period) {
|
||||
return this.delegate.scheduleAtFixedRate(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime,
|
||||
period);
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
|
||||
return this.delegate.scheduleAtFixedRate(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime, period);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
|
||||
return this.delegate.scheduleAtFixedRate(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), period);
|
||||
return this.delegate.scheduleAtFixedRate(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
period);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime,
|
||||
long delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime,
|
||||
delay);
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime, delay);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), delay);
|
||||
return this.delegate.scheduleWithFixedDelay(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
delay);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -290,16 +262,13 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRejectedExecutionHandler(
|
||||
RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) {
|
||||
this.delegate.setRejectedExecutionHandler(rejectedExecutionHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWaitForTasksToCompleteOnShutdown(
|
||||
boolean waitForJobsToCompleteOnShutdown) {
|
||||
this.delegate
|
||||
.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown);
|
||||
public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
|
||||
this.delegate.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -393,43 +362,36 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
if (this.delegate == null) {
|
||||
return super.getDefaultThreadNamePrefix();
|
||||
}
|
||||
return (String) ReflectionUtils.invokeMethod(this.getDefaultThreadNamePrefix,
|
||||
this.delegate);
|
||||
return (String) ReflectionUtils.invokeMethod(this.getDefaultThreadNamePrefix, this.delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable task, Instant startTime) {
|
||||
return this.delegate.schedule(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime);
|
||||
return this.delegate.schedule(new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime,
|
||||
Duration period) {
|
||||
return this.delegate.scheduleAtFixedRate(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime,
|
||||
period);
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) {
|
||||
return this.delegate.scheduleAtFixedRate(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime, period);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period) {
|
||||
return this.delegate.scheduleAtFixedRate(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), period);
|
||||
return this.delegate.scheduleAtFixedRate(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
period);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
|
||||
Duration delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), startTime,
|
||||
delay);
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
startTime, delay);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) {
|
||||
return this.delegate.scheduleWithFixedDelay(
|
||||
new TraceRunnable(tracing(), spanNamer(), task, this.beanName), delay);
|
||||
return this.delegate.scheduleWithFixedDelay(new TraceRunnable(tracing(), spanNamer(), task, this.beanName),
|
||||
delay);
|
||||
}
|
||||
|
||||
private Tracing tracing() {
|
||||
@@ -445,8 +407,7 @@ class LazyTraceThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
|
||||
this.spanNamer = this.beanFactory.getBean(SpanNamer.class);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
log.warn(
|
||||
"SpanNamer bean not found - will provide a manually created instance");
|
||||
log.warn("SpanNamer bean not found - will provide a manually created instance");
|
||||
return new DefaultSpanNamer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,8 +67,7 @@ class SleuthContextListener implements SmartApplicationListener {
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
if (event instanceof ContextRefreshedEvent
|
||||
|| event instanceof ContextClosedEvent) {
|
||||
if (event instanceof ContextRefreshedEvent || event instanceof ContextClosedEvent) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Context refreshed or closed [" + event + "]");
|
||||
}
|
||||
@@ -79,8 +78,7 @@ class SleuthContextListener implements SmartApplicationListener {
|
||||
beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory();
|
||||
}
|
||||
SleuthContextListener listener = CACHE.getOrDefault(beanFactory, this);
|
||||
listener.refreshed.compareAndSet(false,
|
||||
event instanceof ContextRefreshedEvent);
|
||||
listener.refreshed.compareAndSet(false, event instanceof ContextRefreshedEvent);
|
||||
listener.closed.compareAndSet(false, event instanceof ContextClosedEvent);
|
||||
CACHE.put(beanFactory, listener);
|
||||
}
|
||||
|
||||
@@ -79,8 +79,7 @@ class TraceAsyncAspect {
|
||||
private Method getMethod(ProceedingJoinPoint pjp, Object object) {
|
||||
MethodSignature signature = (MethodSignature) pjp.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
return ReflectionUtils.findMethod(object.getClass(), method.getName(),
|
||||
method.getParameterTypes());
|
||||
return ReflectionUtils.findMethod(object.getClass(), method.getName(), method.getParameterTypes());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,28 +40,24 @@ public class TraceAsyncListenableTaskExecutor implements AsyncListenableTaskExec
|
||||
|
||||
private final Tracing tracing;
|
||||
|
||||
TraceAsyncListenableTaskExecutor(AsyncListenableTaskExecutor delegate,
|
||||
Tracing tracing) {
|
||||
TraceAsyncListenableTaskExecutor(AsyncListenableTaskExecutor delegate, Tracing tracing) {
|
||||
this.delegate = delegate;
|
||||
this.tracing = tracing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<?> submitListenable(Runnable task) {
|
||||
return this.delegate
|
||||
.submitListenable(this.tracing.currentTraceContext().wrap(task));
|
||||
return this.delegate.submitListenable(this.tracing.currentTraceContext().wrap(task));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
|
||||
return this.delegate
|
||||
.submitListenable(this.tracing.currentTraceContext().wrap(task));
|
||||
return this.delegate.submitListenable(this.tracing.currentTraceContext().wrap(task));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Runnable task, long startTimeout) {
|
||||
this.delegate.execute(this.tracing.currentTraceContext().wrap(task),
|
||||
startTimeout);
|
||||
this.delegate.execute(this.tracing.currentTraceContext().wrap(task), startTimeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -55,8 +55,7 @@ public class TraceCallable<V> implements Callable<V> {
|
||||
this(tracing, spanNamer, delegate, null);
|
||||
}
|
||||
|
||||
public TraceCallable(Tracing tracing, SpanNamer spanNamer, Callable<V> delegate,
|
||||
String name) {
|
||||
public TraceCallable(Tracing tracing, SpanNamer spanNamer, Callable<V> delegate, String name) {
|
||||
this.tracer = tracing.tracer();
|
||||
this.delegate = delegate;
|
||||
this.parent = tracing.currentTraceContext().get();
|
||||
@@ -65,8 +64,7 @@ public class TraceCallable<V> implements Callable<V> {
|
||||
|
||||
@Override
|
||||
public V call() throws Exception {
|
||||
ScopedSpan span = this.tracer.startScopedSpanWithParent(this.spanName,
|
||||
this.parent);
|
||||
ScopedSpan span = this.tracer.startScopedSpanWithParent(this.spanName, this.parent);
|
||||
try {
|
||||
return this.delegate.call();
|
||||
}
|
||||
|
||||
@@ -52,8 +52,7 @@ public class TraceRunnable implements Runnable {
|
||||
this(tracing, spanNamer, delegate, null);
|
||||
}
|
||||
|
||||
public TraceRunnable(Tracing tracing, SpanNamer spanNamer, Runnable delegate,
|
||||
String name) {
|
||||
public TraceRunnable(Tracing tracing, SpanNamer spanNamer, Runnable delegate, String name) {
|
||||
this.tracer = tracing.tracer();
|
||||
this.delegate = delegate;
|
||||
this.parent = tracing.currentTraceContext().get();
|
||||
@@ -62,8 +61,7 @@ public class TraceRunnable implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
ScopedSpan span = this.tracer.startScopedSpanWithParent(this.spanName,
|
||||
this.parent);
|
||||
ScopedSpan span = this.tracer.startScopedSpanWithParent(this.spanName, this.parent);
|
||||
try {
|
||||
this.delegate.run();
|
||||
}
|
||||
|
||||
@@ -50,13 +50,11 @@ public class TraceableExecutorService implements ExecutorService {
|
||||
|
||||
BeanFactory beanFactory;
|
||||
|
||||
public TraceableExecutorService(BeanFactory beanFactory,
|
||||
final ExecutorService delegate) {
|
||||
public TraceableExecutorService(BeanFactory beanFactory, final ExecutorService delegate) {
|
||||
this(beanFactory, delegate, null);
|
||||
}
|
||||
|
||||
public TraceableExecutorService(BeanFactory beanFactory,
|
||||
final ExecutorService delegate, String spanName) {
|
||||
public TraceableExecutorService(BeanFactory beanFactory, final ExecutorService delegate, String spanName) {
|
||||
this.delegate = delegate;
|
||||
this.beanFactory = beanFactory;
|
||||
this.spanName = spanName;
|
||||
@@ -89,8 +87,7 @@ public class TraceableExecutorService implements ExecutorService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean awaitTermination(long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return this.delegate.awaitTermination(timeout, unit);
|
||||
}
|
||||
|
||||
@@ -102,10 +99,8 @@ public class TraceableExecutorService implements ExecutorService {
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Runnable task, T result) {
|
||||
return this.delegate.submit(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.spanName),
|
||||
result);
|
||||
return this.delegate.submit(ContextUtil.isContextUnusable(this.beanFactory) ? task
|
||||
: new TraceRunnable(tracing(), spanNamer(), task, this.spanName), result);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -115,36 +110,32 @@ public class TraceableExecutorService implements ExecutorService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
|
||||
return this.delegate
|
||||
.invokeAll(ContextUtil.isContextUnusable(this.beanFactory) ? tasks : wrapCallableCollection(tasks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
return this.delegate.invokeAll(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? tasks : wrapCallableCollection(tasks));
|
||||
return this.delegate.invokeAll(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? tasks : wrapCallableCollection(tasks), timeout, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
|
||||
long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return this.delegate.invokeAll(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? tasks : wrapCallableCollection(tasks), timeout, unit);
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
|
||||
return this.delegate
|
||||
.invokeAny(ContextUtil.isContextUnusable(this.beanFactory) ? tasks : wrapCallableCollection(tasks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
|
||||
throws InterruptedException, ExecutionException {
|
||||
return this.delegate.invokeAny(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? tasks : wrapCallableCollection(tasks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout,
|
||||
TimeUnit unit)
|
||||
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
|
||||
throws InterruptedException, ExecutionException, TimeoutException {
|
||||
return this.delegate.invokeAny(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? tasks : wrapCallableCollection(tasks), timeout, unit);
|
||||
return this.delegate.invokeAny(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? tasks : wrapCallableCollection(tasks), timeout, unit);
|
||||
}
|
||||
|
||||
private <T> Collection<? extends Callable<T>> wrapCallableCollection(
|
||||
Collection<? extends Callable<T>> tasks) {
|
||||
private <T> Collection<? extends Callable<T>> wrapCallableCollection(Collection<? extends Callable<T>> tasks) {
|
||||
List<Callable<T>> ts = new ArrayList<>();
|
||||
for (Callable<T> task : tasks) {
|
||||
if (!(task instanceof TraceCallable)) {
|
||||
|
||||
@@ -31,16 +31,13 @@ import org.springframework.beans.factory.BeanFactory;
|
||||
* @since 1.0.0
|
||||
*/
|
||||
// public as most types in this package were documented for use
|
||||
public class TraceableScheduledExecutorService extends TraceableExecutorService
|
||||
implements ScheduledExecutorService {
|
||||
public class TraceableScheduledExecutorService extends TraceableExecutorService implements ScheduledExecutorService {
|
||||
|
||||
public TraceableScheduledExecutorService(BeanFactory beanFactory,
|
||||
final ExecutorService delegate) {
|
||||
public TraceableScheduledExecutorService(BeanFactory beanFactory, final ExecutorService delegate) {
|
||||
super(beanFactory, delegate);
|
||||
}
|
||||
|
||||
public TraceableScheduledExecutorService(BeanFactory beanFactory,
|
||||
final ExecutorService delegate, String beanName) {
|
||||
public TraceableScheduledExecutorService(BeanFactory beanFactory, final ExecutorService delegate, String beanName) {
|
||||
super(beanFactory, delegate, beanName);
|
||||
}
|
||||
|
||||
@@ -50,40 +47,30 @@ public class TraceableScheduledExecutorService extends TraceableExecutorService
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
|
||||
return getScheduledExecutorService()
|
||||
.schedule(ContextUtil.isContextUnusable(this.beanFactory) ? command
|
||||
: new TraceRunnable(tracing(), spanNamer(), command,
|
||||
this.spanName),
|
||||
delay, unit);
|
||||
return getScheduledExecutorService().schedule(ContextUtil.isContextUnusable(this.beanFactory) ? command
|
||||
: new TraceRunnable(tracing(), spanNamer(), command, this.spanName), delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
|
||||
TimeUnit unit) {
|
||||
return getScheduledExecutorService()
|
||||
.schedule(ContextUtil.isContextUnusable(this.beanFactory) ? callable
|
||||
: new TraceCallable<>(tracing(), spanNamer(), callable,
|
||||
this.spanName),
|
||||
delay, unit);
|
||||
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
|
||||
return getScheduledExecutorService().schedule(ContextUtil.isContextUnusable(this.beanFactory) ? callable
|
||||
: new TraceCallable<>(tracing(), spanNamer(), callable, this.spanName), delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
|
||||
long period, TimeUnit unit) {
|
||||
return getScheduledExecutorService()
|
||||
.scheduleAtFixedRate(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? command : new TraceRunnable(tracing(), spanNamer(), command,
|
||||
this.spanName),
|
||||
initialDelay, period, unit);
|
||||
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
|
||||
return getScheduledExecutorService().scheduleAtFixedRate(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? command
|
||||
: new TraceRunnable(tracing(), spanNamer(), command, this.spanName),
|
||||
initialDelay, period, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
|
||||
long delay, TimeUnit unit) {
|
||||
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
|
||||
return getScheduledExecutorService()
|
||||
.scheduleWithFixedDelay(ContextUtil.isContextUnusable(this.beanFactory)
|
||||
? command : new TraceRunnable(tracing(), spanNamer(), command,
|
||||
this.spanName),
|
||||
.scheduleWithFixedDelay(
|
||||
ContextUtil.isContextUnusable(this.beanFactory) ? command
|
||||
: new TraceRunnable(tracing(), spanNamer(), command, this.spanName),
|
||||
initialDelay, delay, unit);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
@AutoConfigureAfter(TraceAutoConfiguration.class)
|
||||
@ConditionalOnClass(CircuitBreaker.class)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.circuitbreaker.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.circuitbreaker.enabled", matchIfMissing = true)
|
||||
@EnableConfigurationProperties(SleuthCircuitBreakerProperties.class)
|
||||
class SleuthCircuitBreakerAutoConfiguration {
|
||||
|
||||
@@ -93,8 +92,7 @@ class TraceCircuitBreaker implements CircuitBreaker {
|
||||
|
||||
@Override
|
||||
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
|
||||
return this.delegate.run(new TraceSupplier<>(this.tracer, toRun),
|
||||
new TraceFunction<>(this.tracer, fallback));
|
||||
return this.delegate.run(new TraceSupplier<>(this.tracer, toRun), new TraceFunction<>(this.tracer, fallback));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -56,8 +56,7 @@ class TraceFunction<T> implements Function<Throwable, T> {
|
||||
}
|
||||
finally {
|
||||
if (tr != null) {
|
||||
String message = tr.getMessage() == null ? tr.getClass().getSimpleName()
|
||||
: tr.getMessage();
|
||||
String message = tr.getMessage() == null ? tr.getClass().getSimpleName() : tr.getMessage();
|
||||
span.tag("error", message);
|
||||
}
|
||||
span.finish();
|
||||
|
||||
@@ -56,8 +56,7 @@ class TraceSupplier<T> implements Supplier<T> {
|
||||
}
|
||||
finally {
|
||||
if (tr != null) {
|
||||
String message = tr.getMessage() == null ? tr.getClass().getSimpleName()
|
||||
: tr.getMessage();
|
||||
String message = tr.getMessage() == null ? tr.getClass().getSimpleName() : tr.getMessage();
|
||||
span.tag("error", message);
|
||||
}
|
||||
span.finish();
|
||||
|
||||
@@ -40,8 +40,7 @@ public class SpringAwareManagedChannelBuilder {
|
||||
|
||||
private List<GrpcManagedChannelBuilderCustomizer> customizers;
|
||||
|
||||
public SpringAwareManagedChannelBuilder(
|
||||
Optional<List<GrpcManagedChannelBuilderCustomizer>> customizers) {
|
||||
public SpringAwareManagedChannelBuilder(Optional<List<GrpcManagedChannelBuilderCustomizer>> customizers) {
|
||||
this.customizers = customizers.orElse(null);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,8 +68,7 @@ class TraceGrpcAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
GrpcManagedChannelBuilderCustomizer tracingManagedChannelBuilderCustomizer(
|
||||
GrpcTracing grpcTracing) {
|
||||
GrpcManagedChannelBuilderCustomizer tracingManagedChannelBuilderCustomizer(GrpcTracing grpcTracing) {
|
||||
return new TracingManagedChannelBuilderCustomizer(grpcTracing);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ import io.grpc.ManagedChannelBuilder;
|
||||
/**
|
||||
* @author Tyler Van Gorder
|
||||
*/
|
||||
public class TracingManagedChannelBuilderCustomizer
|
||||
implements GrpcManagedChannelBuilderCustomizer {
|
||||
public class TracingManagedChannelBuilderCustomizer implements GrpcManagedChannelBuilderCustomizer {
|
||||
|
||||
GrpcTracing grpcTracing;
|
||||
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -37,16 +37,14 @@ import org.springframework.util.StringUtils;
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*/
|
||||
enum MessageHeaderPropagation
|
||||
implements Propagation.Setter<MessageHeaderAccessor, String>,
|
||||
enum MessageHeaderPropagation implements Propagation.Setter<MessageHeaderAccessor, String>,
|
||||
Propagation.Getter<MessageHeaderAccessor, String> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
private static final Log log = LogFactory.getLog(MessageHeaderPropagation.class);
|
||||
|
||||
static Map<String, ?> propagationHeaders(Map<String, ?> headers,
|
||||
List<String> propagationHeaders) {
|
||||
static Map<String, ?> propagationHeaders(Map<String, ?> headers, List<String> propagationHeaders) {
|
||||
Map<String, Object> headersToCopy = new HashMap<>();
|
||||
for (Map.Entry<String, ?> entry : headers.entrySet()) {
|
||||
if (propagationHeaders.contains(entry.getKey())) {
|
||||
@@ -56,21 +54,18 @@ enum MessageHeaderPropagation
|
||||
return headersToCopy;
|
||||
}
|
||||
|
||||
static void removeAnyTraceHeaders(MessageHeaderAccessor accessor,
|
||||
List<String> keysToRemove) {
|
||||
static void removeAnyTraceHeaders(MessageHeaderAccessor accessor, List<String> keysToRemove) {
|
||||
for (String keyToRemove : keysToRemove) {
|
||||
accessor.removeHeader(keyToRemove);
|
||||
if (accessor instanceof NativeMessageHeaderAccessor) {
|
||||
NativeMessageHeaderAccessor nativeAccessor = (NativeMessageHeaderAccessor) accessor;
|
||||
if (accessor.isMutable()) {
|
||||
// 1184 native headers can be an immutable map
|
||||
ensureNativeHeadersAreMutable(nativeAccessor)
|
||||
.removeNativeHeader(keyToRemove);
|
||||
ensureNativeHeadersAreMutable(nativeAccessor).removeNativeHeader(keyToRemove);
|
||||
}
|
||||
}
|
||||
else {
|
||||
Object nativeHeaders = accessor
|
||||
.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
Object nativeHeaders = accessor.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
if (nativeHeaders instanceof Map) {
|
||||
((Map) nativeHeaders).remove(keyToRemove);
|
||||
}
|
||||
@@ -93,8 +88,7 @@ enum MessageHeaderPropagation
|
||||
nativeHeaderMap = nativeHeaderMap instanceof LinkedMultiValueMap ? nativeHeaderMap
|
||||
: new LinkedMultiValueMap<>(nativeHeaderMap);
|
||||
nativeAccessor.removeHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
nativeAccessor.setHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS,
|
||||
nativeHeaderMap);
|
||||
nativeAccessor.setHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaderMap);
|
||||
return nativeAccessor;
|
||||
}
|
||||
|
||||
@@ -105,8 +99,7 @@ enum MessageHeaderPropagation
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("An exception happened when we tried to retrieve the [" + key
|
||||
+ "] from message", ex);
|
||||
log.debug("An exception happened when we tried to retrieve the [" + key + "] from message", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,16 +111,13 @@ enum MessageHeaderPropagation
|
||||
ensureNativeHeadersAreMutable(nativeAccessor).setNativeHeader(key, value);
|
||||
}
|
||||
else {
|
||||
Object nativeHeaders = accessor
|
||||
.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
Object nativeHeaders = accessor.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
if (nativeHeaders == null) {
|
||||
nativeHeaders = new LinkedMultiValueMap<>();
|
||||
accessor.setHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS,
|
||||
nativeHeaders);
|
||||
accessor.setHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaders);
|
||||
}
|
||||
if (nativeHeaders instanceof Map<?, ?>) {
|
||||
Map<String, List<String>> copy = toNativeHeaderMap(
|
||||
(Map<String, List<String>>) nativeHeaders);
|
||||
Map<String, List<String>> copy = toNativeHeaderMap((Map<String, List<String>>) nativeHeaders);
|
||||
copy.put(key, Collections.singletonList(value));
|
||||
accessor.setHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS, copy);
|
||||
}
|
||||
@@ -148,8 +138,7 @@ enum MessageHeaderPropagation
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("An exception happened when we tried to retrieve the [" + key
|
||||
+ "] from message", ex);
|
||||
log.debug("An exception happened when we tried to retrieve the [" + key + "] from message", ex);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -164,8 +153,7 @@ enum MessageHeaderPropagation
|
||||
}
|
||||
}
|
||||
else {
|
||||
Object nativeHeaders = accessor
|
||||
.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
Object nativeHeaders = accessor.getHeader(NativeMessageHeaderAccessor.NATIVE_HEADERS);
|
||||
if (nativeHeaders instanceof Map) {
|
||||
Object result = ((Map) nativeHeaders).get(key);
|
||||
if (result instanceof List && !((List) result).isEmpty()) {
|
||||
|
||||
@@ -64,17 +64,14 @@ public final class MessagingSleuthOperators {
|
||||
*/
|
||||
public static <T> Message<T> forInputMessage(Tracing tracing, Message<T> message,
|
||||
Consumer<Message<T>> withSpanInScope) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(tracing);
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler
|
||||
.wrapInputMessage(message, "");
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(tracing);
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler.wrapInputMessage(message, "");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Wrapped input msg " + wrappedInputMessage);
|
||||
}
|
||||
Tracer tracer = tracing.tracer();
|
||||
Throwable t = null;
|
||||
try (Tracer.SpanInScope ws = tracer
|
||||
.withSpanInScope(wrappedInputMessage.childSpan.start())) {
|
||||
try (Tracer.SpanInScope ws = tracer.withSpanInScope(wrappedInputMessage.childSpan.start())) {
|
||||
withSpanInScope.accept(wrappedInputMessage.msg);
|
||||
}
|
||||
catch (Exception e) {
|
||||
@@ -95,10 +92,8 @@ public final class MessagingSleuthOperators {
|
||||
* @return message with tracing context
|
||||
*/
|
||||
public static <T> Message<T> forInputMessage(Tracing tracing, Message<T> message) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(tracing);
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler
|
||||
.wrapInputMessage(message, "");
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(tracing);
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler.wrapInputMessage(message, "");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Wrapped input msg " + wrappedInputMessage);
|
||||
}
|
||||
@@ -112,10 +107,8 @@ public final class MessagingSleuthOperators {
|
||||
* @param <T> input message type
|
||||
* @return function representation of input message with tracing context
|
||||
*/
|
||||
public static <T> Function<Message<T>, Message<T>> asFunction(Tracing tracing,
|
||||
Message<T> inputMessage) {
|
||||
return stringMessage -> MessagingSleuthOperators.forInputMessage(tracing,
|
||||
inputMessage);
|
||||
public static <T> Function<Message<T>, Message<T>> asFunction(Tracing tracing, Message<T> inputMessage) {
|
||||
return stringMessage -> MessagingSleuthOperators.forInputMessage(tracing, inputMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,8 +119,7 @@ public final class MessagingSleuthOperators {
|
||||
* @return span retrieved from message or {@code null} if there was no span
|
||||
*/
|
||||
public static <T> Span spanFromMessage(Tracing tracing, Message<T> message) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(tracing);
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(tracing);
|
||||
Span span = traceMessageHandler.spanFromMessage(message);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found the following span in message " + span);
|
||||
@@ -143,8 +135,7 @@ public final class MessagingSleuthOperators {
|
||||
* be reported
|
||||
* @param <T> - payload type
|
||||
*/
|
||||
public static <T> void withSpanInScope(Tracing tracing, Message<T> message,
|
||||
Consumer<Message<T>> withSpanInScope) {
|
||||
public static <T> void withSpanInScope(Tracing tracing, Message<T> message, Consumer<Message<T>> withSpanInScope) {
|
||||
Span span = spanFromMessage(tracing, message);
|
||||
Tracer tracer = tracing.tracer();
|
||||
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
|
||||
@@ -179,8 +170,7 @@ public final class MessagingSleuthOperators {
|
||||
* @param <T> - message payload
|
||||
* @return instrumented message
|
||||
*/
|
||||
public static <T> Message<T> handleOutputMessage(Tracing tracing,
|
||||
Message<T> message) {
|
||||
public static <T> Message<T> handleOutputMessage(Tracing tracing, Message<T> message) {
|
||||
return handleOutputMessage(tracing, message, null);
|
||||
}
|
||||
|
||||
@@ -194,10 +184,8 @@ public final class MessagingSleuthOperators {
|
||||
* @param <T> - message payload
|
||||
* @return instrumented message
|
||||
*/
|
||||
public static <T> Message<T> handleOutputMessage(Tracing tracing, Message<T> message,
|
||||
Throwable throwable) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(tracing);
|
||||
public static <T> Message<T> handleOutputMessage(Tracing tracing, Message<T> message, Throwable throwable) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(tracing);
|
||||
Span span = traceMessageHandler.parentSpan(message);
|
||||
span = span != null ? span : traceMessageHandler.consumerSpan(message);
|
||||
if (span == null) {
|
||||
@@ -220,10 +208,8 @@ public final class MessagingSleuthOperators {
|
||||
* @param <T> - message payload
|
||||
* @return instrumented message
|
||||
*/
|
||||
public static <T> Message<T> afterMessageHandled(Tracing tracing, Message<T> message,
|
||||
Throwable ex) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(tracing);
|
||||
public static <T> Message<T> afterMessageHandled(Tracing tracing, Message<T> message, Throwable ex) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(tracing);
|
||||
Span span = traceMessageHandler.spanFromMessage(message);
|
||||
traceMessageHandler.afterMessageHandled(span, ex);
|
||||
return message;
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -45,8 +45,7 @@ import org.springframework.kafka.config.StreamsBuilderFactoryBean;
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@AutoConfigureAfter({ TraceAutoConfiguration.class })
|
||||
@OnMessagingEnabled
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.kafka.streams.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.kafka.streams.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(KafkaStreams.class)
|
||||
class SleuthKafkaStreamsConfiguration {
|
||||
|
||||
@@ -91,29 +90,23 @@ class SleuthKafkaStreamsConfiguration {
|
||||
*/
|
||||
class KafkaStreamsBuilderFactoryBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(KafkaStreamsBuilderFactoryBeanPostProcessor.class);
|
||||
private static final Log log = LogFactory.getLog(KafkaStreamsBuilderFactoryBeanPostProcessor.class);
|
||||
|
||||
private final ObjectProvider<KafkaStreamsTracing> objectProvider;
|
||||
|
||||
KafkaStreamsBuilderFactoryBeanPostProcessor(
|
||||
ObjectProvider<KafkaStreamsTracing> objectProvider) {
|
||||
KafkaStreamsBuilderFactoryBeanPostProcessor(ObjectProvider<KafkaStreamsTracing> objectProvider) {
|
||||
this.objectProvider = objectProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof StreamsBuilderFactoryBean) {
|
||||
// KafkaStreamsTracing is created in SleuthKafkaStreamsConfiguration above, so
|
||||
// should not be null here
|
||||
KafkaStreamsTracing kafkaStreamsTracing = this.objectProvider
|
||||
.getIfAvailable();
|
||||
((StreamsBuilderFactoryBean) bean)
|
||||
.setClientSupplier(kafkaStreamsTracing.kafkaClientSupplier());
|
||||
KafkaStreamsTracing kafkaStreamsTracing = this.objectProvider.getIfAvailable();
|
||||
((StreamsBuilderFactoryBean) bean).setClientSupplier(kafkaStreamsTracing.kafkaClientSupplier());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"StreamsBuilderFactoryBean bean is auto-configured to enable tracing.");
|
||||
log.debug("StreamsBuilderFactoryBean bean is auto-configured to enable tracing.");
|
||||
}
|
||||
}
|
||||
return bean;
|
||||
|
||||
@@ -60,8 +60,7 @@ class SleuthMessagingProperties {
|
||||
* Defaults to any channel name not matching the Hystrix Stream and functional
|
||||
* Stream channel names.
|
||||
*/
|
||||
private String[] patterns = new String[] { "!hystrixStreamOutput*", "*",
|
||||
"!channel*" };
|
||||
private String[] patterns = new String[] { "!hystrixStreamOutput*", "*", "!channel*" };
|
||||
|
||||
/**
|
||||
* Enable Spring Integration sleuth instrumentation.
|
||||
|
||||
@@ -56,8 +56,7 @@ import org.springframework.messaging.support.MessageBuilder;
|
||||
class TraceFunctionAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
TraceFunctionAroundWrapper traceFunctionAroundWrapper(Environment environment,
|
||||
Tracing tracing) {
|
||||
TraceFunctionAroundWrapper traceFunctionAroundWrapper(Environment environment, Tracing tracing) {
|
||||
return new TraceFunctionAroundWrapper(environment, tracing);
|
||||
}
|
||||
|
||||
@@ -80,23 +79,20 @@ class TraceFunctionAroundWrapper extends FunctionAroundWrapper
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object doApply(Message<byte[]> message,
|
||||
SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler
|
||||
.forNonSpringIntegration(this.tracing);
|
||||
protected Object doApply(Message<byte[]> message, SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
TraceMessageHandler traceMessageHandler = TraceMessageHandler.forNonSpringIntegration(this.tracing);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will retrieve the tracing headers from the message");
|
||||
}
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler
|
||||
.wrapInputMessage(message, inputDestination(targetFunction));
|
||||
MessageAndSpans wrappedInputMessage = traceMessageHandler.wrapInputMessage(message,
|
||||
inputDestination(targetFunction));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Wrapped input msg " + wrappedInputMessage);
|
||||
}
|
||||
Tracer tracer = this.tracing.tracer();
|
||||
Object result;
|
||||
Throwable throwable = null;
|
||||
try (Tracer.SpanInScope ws = tracer
|
||||
.withSpanInScope(wrappedInputMessage.childSpan.start())) {
|
||||
try (Tracer.SpanInScope ws = tracer.withSpanInScope(wrappedInputMessage.childSpan.start())) {
|
||||
result = targetFunction.apply(wrappedInputMessage.msg);
|
||||
}
|
||||
catch (Exception e) {
|
||||
@@ -104,8 +100,7 @@ class TraceFunctionAroundWrapper extends FunctionAroundWrapper
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
traceMessageHandler.afterMessageHandled(wrappedInputMessage.childSpan,
|
||||
throwable);
|
||||
traceMessageHandler.afterMessageHandled(wrappedInputMessage.childSpan, throwable);
|
||||
}
|
||||
if (result == null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
@@ -114,10 +109,8 @@ class TraceFunctionAroundWrapper extends FunctionAroundWrapper
|
||||
return null;
|
||||
}
|
||||
Message msgResult = toMessage(result);
|
||||
MessageAndSpan wrappedOutputMessage = traceMessageHandler.wrapOutputMessage(
|
||||
msgResult,
|
||||
TraceContextOrSamplingFlags
|
||||
.create(wrappedInputMessage.parentSpan.context()),
|
||||
MessageAndSpan wrappedOutputMessage = traceMessageHandler.wrapOutputMessage(msgResult,
|
||||
TraceContextOrSamplingFlags.create(wrappedInputMessage.parentSpan.context()),
|
||||
outputDestination(targetFunction));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Wrapped output msg " + wrappedOutputMessage);
|
||||
@@ -133,22 +126,16 @@ class TraceFunctionAroundWrapper extends FunctionAroundWrapper
|
||||
return (Message) result;
|
||||
}
|
||||
|
||||
private String inputDestination(
|
||||
SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
private String inputDestination(SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
String functionDefinition = targetFunction.getFunctionDefinition();
|
||||
return this.functionToDestinationCache
|
||||
.computeIfAbsent(functionDefinition,
|
||||
s -> this.environment.getProperty(
|
||||
"spring.cloud.stream.bindings." + s + "-in-0.destination",
|
||||
s));
|
||||
return this.functionToDestinationCache.computeIfAbsent(functionDefinition,
|
||||
s -> this.environment.getProperty("spring.cloud.stream.bindings." + s + "-in-0.destination", s));
|
||||
}
|
||||
|
||||
private String outputDestination(
|
||||
SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
private String outputDestination(SimpleFunctionRegistry.FunctionInvocationWrapper targetFunction) {
|
||||
String functionDefinition = targetFunction.getFunctionDefinition();
|
||||
return functionToDestinationCache.computeIfAbsent(functionDefinition,
|
||||
s -> this.environment.getProperty(
|
||||
"spring.cloud.stream.bindings." + s + "-out-0.destination", s));
|
||||
s -> this.environment.getProperty("spring.cloud.stream.bindings." + s + "-out-0.destination", s));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -86,8 +86,7 @@ class TraceMessageHandler {
|
||||
this.tracing = tracing;
|
||||
this.tracer = tracing.tracer();
|
||||
this.injector = tracing.propagation().injector(MessageHeaderPropagation.INSTANCE);
|
||||
this.extractor = tracing.propagation()
|
||||
.extractor(MessageHeaderPropagation.INSTANCE);
|
||||
this.extractor = tracing.propagation().extractor(MessageHeaderPropagation.INSTANCE);
|
||||
// TODO: Abstractions to reuse in TraceChannelInterceptors?
|
||||
this.preSendFunction = preSendFunction;
|
||||
this.preSendMessageManipulator = preSendMessageManipulator;
|
||||
@@ -96,17 +95,15 @@ class TraceMessageHandler {
|
||||
|
||||
static TraceMessageHandler forNonSpringIntegration(Tracing tracing) {
|
||||
Tracer tracer = tracing.tracer();
|
||||
Function<TraceContext, Span> preSendFunction = ctx -> tracer
|
||||
.nextSpan(TraceContextOrSamplingFlags.create(ctx)).name("handle").start();
|
||||
TriConsumer<MessageHeaderAccessor, Span, Span> preSendMessageManipulator = (
|
||||
headers, parentSpan, childSpan) -> {
|
||||
Function<TraceContext, Span> preSendFunction = ctx -> tracer.nextSpan(TraceContextOrSamplingFlags.create(ctx))
|
||||
.name("handle").start();
|
||||
TriConsumer<MessageHeaderAccessor, Span, Span> preSendMessageManipulator = (headers, parentSpan, childSpan) -> {
|
||||
headers.setHeader("traceHandlerParentSpan", parentSpan);
|
||||
headers.setHeader(Span.class.getName(), childSpan);
|
||||
};
|
||||
Function<TraceContext, Span> postReceiveFunction = ctx -> tracer
|
||||
.nextSpan(TraceContextOrSamplingFlags.create(ctx));
|
||||
return new TraceMessageHandler(tracing, preSendFunction,
|
||||
preSendMessageManipulator, postReceiveFunction);
|
||||
return new TraceMessageHandler(tracing, preSendFunction, preSendMessageManipulator, postReceiveFunction);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,16 +132,14 @@ class TraceMessageHandler {
|
||||
clearTracingHeaders(headers);
|
||||
this.preSendMessageManipulator.accept(headers, consumerSpan, span);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Created a handle span after retrieving the message " + consumerSpan);
|
||||
log.debug("Created a handle span after retrieving the message " + consumerSpan);
|
||||
}
|
||||
if (message instanceof ErrorMessage) {
|
||||
return new MessageAndSpans(new ErrorMessage((Throwable) message.getPayload(),
|
||||
headers.getMessageHeaders()), consumerSpan, span);
|
||||
return new MessageAndSpans(new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders()),
|
||||
consumerSpan, span);
|
||||
}
|
||||
headers.setImmutable();
|
||||
return new MessageAndSpans(
|
||||
new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()),
|
||||
return new MessageAndSpans(new GenericMessage<>(message.getPayload(), headers.getMessageHeaders()),
|
||||
consumerSpan, span);
|
||||
}
|
||||
|
||||
@@ -202,8 +197,8 @@ class TraceMessageHandler {
|
||||
* @param destinationName - destination to which the message should be sent
|
||||
* @return a tuple with the wrapped message and a corresponding span
|
||||
*/
|
||||
MessageAndSpan wrapOutputMessage(Message<?> message,
|
||||
TraceContextOrSamplingFlags parentSpan, String destinationName) {
|
||||
MessageAndSpan wrapOutputMessage(Message<?> message, TraceContextOrSamplingFlags parentSpan,
|
||||
String destinationName) {
|
||||
Message<?> retrievedMessage = getMessage(message);
|
||||
MessageHeaderAccessor headers = mutableHeaderAccessor(retrievedMessage);
|
||||
Span span = this.outputMessageSpanFunction.apply(parentSpan.context());
|
||||
@@ -213,12 +208,10 @@ class TraceMessageHandler {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Created a new span output message " + span);
|
||||
}
|
||||
return new MessageAndSpan(outputMessage(message, retrievedMessage, headers),
|
||||
span);
|
||||
return new MessageAndSpan(outputMessage(message, retrievedMessage, headers), span);
|
||||
}
|
||||
|
||||
private void markProducerSpan(MessageHeaderAccessor headers, Span span,
|
||||
String destinationName) {
|
||||
private void markProducerSpan(MessageHeaderAccessor headers, Span span, String destinationName) {
|
||||
if (!span.isNoop()) {
|
||||
span.kind(Span.Kind.PRODUCER).name("send").start();
|
||||
span.remoteServiceName(toRemoteServiceName(headers));
|
||||
@@ -238,25 +231,20 @@ class TraceMessageHandler {
|
||||
return REMOTE_SERVICE_NAME;
|
||||
}
|
||||
|
||||
private Message<?> outputMessage(Message<?> originalMessage,
|
||||
Message<?> retrievedMessage, MessageHeaderAccessor additionalHeaders) {
|
||||
MessageHeaderAccessor headers = MessageHeaderAccessor
|
||||
.getMutableAccessor(originalMessage);
|
||||
private Message<?> outputMessage(Message<?> originalMessage, Message<?> retrievedMessage,
|
||||
MessageHeaderAccessor additionalHeaders) {
|
||||
MessageHeaderAccessor headers = MessageHeaderAccessor.getMutableAccessor(originalMessage);
|
||||
clearTechnicalTracingHeaders(headers);
|
||||
if (originalMessage instanceof ErrorMessage) {
|
||||
ErrorMessage errorMessage = (ErrorMessage) originalMessage;
|
||||
headers.copyHeaders(MessageHeaderPropagation.propagationHeaders(
|
||||
additionalHeaders.getMessageHeaders(),
|
||||
headers.copyHeaders(MessageHeaderPropagation.propagationHeaders(additionalHeaders.getMessageHeaders(),
|
||||
this.tracing.propagation().keys()));
|
||||
return new ErrorMessage(errorMessage.getPayload(),
|
||||
isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()),
|
||||
errorMessage.getOriginalMessage());
|
||||
return new ErrorMessage(errorMessage.getPayload(), isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()), errorMessage.getOriginalMessage());
|
||||
}
|
||||
headers.copyHeaders(additionalHeaders.getMessageHeaders());
|
||||
return new GenericMessage<>(retrievedMessage.getPayload(),
|
||||
isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()));
|
||||
isWebSockets(headers) ? headers.getMessageHeaders() : new MessageHeaders(headers.getMessageHeaders()));
|
||||
}
|
||||
|
||||
private boolean isWebSockets(MessageHeaderAccessor headerAccessor) {
|
||||
@@ -342,8 +330,7 @@ class MessageAndSpans {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MessageAndSpans{" + "msg=" + msg + ", parentSpan=" + parentSpan
|
||||
+ ", childSpan=" + childSpan + '}';
|
||||
return "MessageAndSpans{" + "msg=" + msg + ", parentSpan=" + parentSpan + ", childSpan=" + childSpan + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -61,8 +61,8 @@ public final class TraceMessageHeaders {
|
||||
*/
|
||||
public static final String SPAN_FLAGS_NAME = "spanFlags";
|
||||
|
||||
static List<String> HEADERS = Arrays.asList(SAMPLED_NAME, SPAN_FLAGS_NAME,
|
||||
SPAN_ID_NAME, SPAN_NAME_NAME, TRACE_ID_NAME, PARENT_ID_NAME);
|
||||
static List<String> HEADERS = Arrays.asList(SAMPLED_NAME, SPAN_FLAGS_NAME, SPAN_ID_NAME, SPAN_NAME_NAME,
|
||||
TRACE_ID_NAME, PARENT_ID_NAME);
|
||||
|
||||
private TraceMessageHeaders() {
|
||||
}
|
||||
|
||||
@@ -82,8 +82,7 @@ import org.springframework.util.ReflectionUtils;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnClass(MessagingTracing.class)
|
||||
@AutoConfigureAfter({ TraceAutoConfiguration.class,
|
||||
TraceSpringMessagingAutoConfiguration.class })
|
||||
@AutoConfigureAfter({ TraceAutoConfiguration.class, TraceSpringMessagingAutoConfiguration.class })
|
||||
@OnMessagingEnabled
|
||||
@EnableConfigurationProperties(SleuthMessagingProperties.class)
|
||||
// public allows @AutoConfigureAfter(TraceMessagingAutoConfiguration)
|
||||
@@ -114,16 +113,14 @@ public class TraceMessagingAutoConfiguration {
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.rabbit.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.rabbit.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(RabbitTemplate.class)
|
||||
protected static class SleuthRabbitConfiguration {
|
||||
|
||||
@Bean
|
||||
// for tests
|
||||
@ConditionalOnMissingBean
|
||||
static SleuthRabbitBeanPostProcessor sleuthRabbitBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
static SleuthRabbitBeanPostProcessor sleuthRabbitBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new SleuthRabbitBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
@@ -132,27 +129,21 @@ public class TraceMessagingAutoConfiguration {
|
||||
SpringRabbitTracing springRabbitTracing(MessagingTracing messagingTracing,
|
||||
SleuthMessagingProperties properties) {
|
||||
return SpringRabbitTracing.newBuilder(messagingTracing)
|
||||
.remoteServiceName(
|
||||
properties.getMessaging().getRabbit().getRemoteServiceName())
|
||||
.build();
|
||||
.remoteServiceName(properties.getMessaging().getRabbit().getRemoteServiceName()).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.kafka.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.kafka.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(ProducerFactory.class)
|
||||
protected static class SleuthKafkaConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
KafkaTracing kafkaTracing(MessagingTracing messagingTracing,
|
||||
SleuthMessagingProperties properties) {
|
||||
KafkaTracing kafkaTracing(MessagingTracing messagingTracing, SleuthMessagingProperties properties) {
|
||||
return KafkaTracing.newBuilder(messagingTracing)
|
||||
.remoteServiceName(
|
||||
properties.getMessaging().getKafka().getRemoteServiceName())
|
||||
.build();
|
||||
.remoteServiceName(properties.getMessaging().getKafka().getRemoteServiceName()).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -163,16 +154,14 @@ public class TraceMessagingAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
KafkaFactoryBeanPostProcessor kafkaFactoryBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
KafkaFactoryBeanPostProcessor kafkaFactoryBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new KafkaFactoryBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.jms.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.messaging.jms.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(JmsListenerConfigurer.class)
|
||||
@ConditionalOnBean(JmsListenerEndpointRegistry.class)
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
@@ -180,31 +169,25 @@ public class TraceMessagingAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
JmsTracing jmsTracing(MessagingTracing messagingTracing,
|
||||
SleuthMessagingProperties properties) {
|
||||
JmsTracing jmsTracing(MessagingTracing messagingTracing, SleuthMessagingProperties properties) {
|
||||
return JmsTracing.newBuilder(messagingTracing)
|
||||
.remoteServiceName(
|
||||
properties.getMessaging().getJms().getRemoteServiceName())
|
||||
.build();
|
||||
.remoteServiceName(properties.getMessaging().getJms().getRemoteServiceName()).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
// for tests
|
||||
@ConditionalOnMissingBean
|
||||
TracingConnectionFactoryBeanPostProcessor tracingConnectionFactoryBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
TracingConnectionFactoryBeanPostProcessor tracingConnectionFactoryBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new TracingConnectionFactoryBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JmsListenerConfigurer configureTracing(BeanFactory beanFactory,
|
||||
JmsListenerEndpointRegistry defaultRegistry) {
|
||||
JmsListenerConfigurer configureTracing(BeanFactory beanFactory, JmsListenerEndpointRegistry defaultRegistry) {
|
||||
return registrar -> {
|
||||
TracingJmsBeanPostProcessor processor = beanFactory
|
||||
.getBean(TracingJmsBeanPostProcessor.class);
|
||||
TracingJmsBeanPostProcessor processor = beanFactory.getBean(TracingJmsBeanPostProcessor.class);
|
||||
JmsListenerEndpointRegistry registry = registrar.getEndpointRegistry();
|
||||
registrar.setEndpointRegistry((JmsListenerEndpointRegistry) processor
|
||||
.wrap(registry == null ? defaultRegistry : registry));
|
||||
registrar.setEndpointRegistry(
|
||||
(JmsListenerEndpointRegistry) processor.wrap(registry == null ? defaultRegistry : registry));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -229,14 +212,13 @@ class SleuthRabbitBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof RabbitTemplate) {
|
||||
return rabbitTracing().decorateRabbitTemplate((RabbitTemplate) bean);
|
||||
}
|
||||
else if (bean instanceof SimpleRabbitListenerContainerFactory) {
|
||||
return rabbitTracing().decorateSimpleRabbitListenerContainerFactory(
|
||||
(SimpleRabbitListenerContainerFactory) bean);
|
||||
return rabbitTracing()
|
||||
.decorateSimpleRabbitListenerContainerFactory((SimpleRabbitListenerContainerFactory) bean);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
@@ -260,22 +242,17 @@ class KafkaFactoryBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof ConsumerFactory) {
|
||||
ConsumerFactory factory = (ConsumerFactory) bean;
|
||||
if (factory.getPostProcessors().stream()
|
||||
.noneMatch(o -> o instanceof TraceConsumerPostProcessor)) {
|
||||
factory.addPostProcessor(
|
||||
new TraceConsumerPostProcessor(this.beanFactory));
|
||||
if (factory.getPostProcessors().stream().noneMatch(o -> o instanceof TraceConsumerPostProcessor)) {
|
||||
factory.addPostProcessor(new TraceConsumerPostProcessor(this.beanFactory));
|
||||
}
|
||||
}
|
||||
else if (bean instanceof ProducerFactory) {
|
||||
ProducerFactory factory = (ProducerFactory) bean;
|
||||
if (factory.getPostProcessors().stream()
|
||||
.noneMatch(o -> o instanceof TraceProducerPostProcessor)) {
|
||||
factory.addPostProcessor(
|
||||
new TraceProducerPostProcessor(this.beanFactory));
|
||||
if (factory.getPostProcessors().stream().noneMatch(o -> o instanceof TraceProducerPostProcessor)) {
|
||||
factory.addPostProcessor(new TraceProducerPostProcessor(this.beanFactory));
|
||||
}
|
||||
}
|
||||
return bean;
|
||||
@@ -345,8 +322,8 @@ class SleuthKafkaAspect {
|
||||
SleuthKafkaAspect(KafkaTracing kafkaTracing, Tracer tracer) {
|
||||
this.kafkaTracing = kafkaTracing;
|
||||
this.tracer = tracer;
|
||||
this.recordMessageConverter = ReflectionUtils.findField(
|
||||
MessagingMessageListenerAdapter.class, "recordMessageConverter");
|
||||
this.recordMessageConverter = ReflectionUtils.findField(MessagingMessageListenerAdapter.class,
|
||||
"recordMessageConverter");
|
||||
}
|
||||
|
||||
@Pointcut("execution(public * org.springframework.kafka.core.ProducerFactory.createProducer(..))")
|
||||
@@ -378,13 +355,11 @@ class SleuthKafkaAspect {
|
||||
}
|
||||
|
||||
@Around("anyCreateListenerContainer() || anyCreateContainer()")
|
||||
public Object wrapListenerContainerCreation(ProceedingJoinPoint pjp)
|
||||
throws Throwable {
|
||||
public Object wrapListenerContainerCreation(ProceedingJoinPoint pjp) throws Throwable {
|
||||
MessageListenerContainer listener = (MessageListenerContainer) pjp.proceed();
|
||||
if (listener instanceof AbstractMessageListenerContainer) {
|
||||
AbstractMessageListenerContainer container = (AbstractMessageListenerContainer) listener;
|
||||
Object someMessageListener = container.getContainerProperties()
|
||||
.getMessageListener();
|
||||
Object someMessageListener = container.getContainerProperties().getMessageListener();
|
||||
if (someMessageListener == null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("No message listener to wrap. Proceeding");
|
||||
@@ -411,19 +386,16 @@ class SleuthKafkaAspect {
|
||||
Object createProxy(Object bean) {
|
||||
ProxyFactoryBean factory = new ProxyFactoryBean();
|
||||
factory.setProxyTargetClass(true);
|
||||
factory.addAdvice(
|
||||
new MessageListenerMethodInterceptor(this.kafkaTracing, this.tracer));
|
||||
factory.addAdvice(new MessageListenerMethodInterceptor(this.kafkaTracing, this.tracer));
|
||||
factory.setTarget(bean);
|
||||
return factory.getObject();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class MessageListenerMethodInterceptor<T extends MessageListener>
|
||||
implements MethodInterceptor {
|
||||
class MessageListenerMethodInterceptor<T extends MessageListener> implements MethodInterceptor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(MessageListenerMethodInterceptor.class);
|
||||
private static final Log log = LogFactory.getLog(MessageListenerMethodInterceptor.class);
|
||||
|
||||
private final KafkaTracing kafkaTracing;
|
||||
|
||||
@@ -447,8 +419,7 @@ class MessageListenerMethodInterceptor<T extends MessageListener>
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Wrapping onMessage call");
|
||||
}
|
||||
Span span = this.kafkaTracing.nextSpan((ConsumerRecord<?, ?>) record)
|
||||
.name("on-message").start();
|
||||
Span span = this.kafkaTracing.nextSpan((ConsumerRecord<?, ?>) record).name("on-message").start();
|
||||
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
|
||||
return invocation.proceed();
|
||||
}
|
||||
@@ -485,22 +456,19 @@ class TracingJmsBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
return wrap(bean);
|
||||
}
|
||||
|
||||
Object wrap(Object bean) {
|
||||
if (typeMatches(bean)) {
|
||||
return new TracingJmsListenerEndpointRegistry(
|
||||
(JmsListenerEndpointRegistry) bean, this.beanFactory);
|
||||
return new TracingJmsListenerEndpointRegistry((JmsListenerEndpointRegistry) bean, this.beanFactory);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
private boolean typeMatches(Object bean) {
|
||||
return bean instanceof JmsListenerEndpointRegistry
|
||||
&& !(bean instanceof TracingJmsListenerEndpointRegistry);
|
||||
return bean instanceof JmsListenerEndpointRegistry && !(bean instanceof TracingJmsListenerEndpointRegistry);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -51,29 +51,26 @@ import org.springframework.util.ObjectUtils;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(GlobalChannelInterceptor.class)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@AutoConfigureAfter({ TraceAutoConfiguration.class,
|
||||
TraceSpringMessagingAutoConfiguration.class })
|
||||
@AutoConfigureAfter({ TraceAutoConfiguration.class, TraceSpringMessagingAutoConfiguration.class })
|
||||
@OnMessagingEnabled
|
||||
@EnableConfigurationProperties(SleuthMessagingProperties.class)
|
||||
@Conditional(TracingChannelInterceptorCondition.class)
|
||||
class TraceSpringIntegrationAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public GlobalChannelInterceptorWrapper tracingGlobalChannelInterceptorWrapper(
|
||||
TracingChannelInterceptor interceptor, SleuthMessagingProperties properties) {
|
||||
GlobalChannelInterceptorWrapper wrapper = new GlobalChannelInterceptorWrapper(
|
||||
interceptor);
|
||||
public GlobalChannelInterceptorWrapper tracingGlobalChannelInterceptorWrapper(TracingChannelInterceptor interceptor,
|
||||
SleuthMessagingProperties properties) {
|
||||
GlobalChannelInterceptorWrapper wrapper = new GlobalChannelInterceptorWrapper(interceptor);
|
||||
wrapper.setPatterns(properties.getIntegration().getPatterns());
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
@Bean
|
||||
TracingChannelInterceptor traceChannelInterceptor(Tracing tracing,
|
||||
SleuthMessagingProperties properties,
|
||||
TracingChannelInterceptor traceChannelInterceptor(Tracing tracing, SleuthMessagingProperties properties,
|
||||
Propagation.Setter<MessageHeaderAccessor, String> traceMessagePropagationSetter,
|
||||
Propagation.Getter<MessageHeaderAccessor, String> traceMessagePropagationGetter) {
|
||||
return new TracingChannelInterceptor(tracing, properties,
|
||||
traceMessagePropagationSetter, traceMessagePropagationGetter);
|
||||
return new TracingChannelInterceptor(tracing, properties, traceMessagePropagationSetter,
|
||||
traceMessagePropagationGetter);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -85,24 +82,21 @@ final class TracingChannelInterceptorCondition extends AnyNestedCondition {
|
||||
}
|
||||
|
||||
@ConditionalOnMissingClass("org.springframework.cloud.function.context.FunctionCatalog")
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled", matchIfMissing = true)
|
||||
static class OnFunctionMissing {
|
||||
|
||||
}
|
||||
|
||||
@ConditionalOnClass(FunctionCatalog.class)
|
||||
@Conditional(OnEnableBindingCondition.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled", matchIfMissing = true)
|
||||
static class OnFunctionPresentAndEnableBinding {
|
||||
|
||||
}
|
||||
|
||||
@ConditionalOnClass(FunctionCatalog.class)
|
||||
@Conditional(OnEnableBindingMissingCondition.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled",
|
||||
havingValue = "true")
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.enabled", havingValue = "true")
|
||||
static class OnFunctionPresentEnableBindingOffAndIntegrationExplicitlyOn {
|
||||
|
||||
}
|
||||
@@ -120,14 +114,12 @@ class OnEnableBindingCondition implements ConfigurationCondition {
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
Class clazz;
|
||||
try {
|
||||
clazz = Class
|
||||
.forName("org.springframework.cloud.stream.annotation.EnableBinding");
|
||||
clazz = Class.forName("org.springframework.cloud.stream.annotation.EnableBinding");
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
return !ObjectUtils
|
||||
.isEmpty(context.getBeanFactory().getBeanNamesForAnnotation(clazz));
|
||||
return !ObjectUtils.isEmpty(context.getBeanFactory().getBeanNamesForAnnotation(clazz));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,8 +40,7 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(DelegatingWebSocketMessageBrokerConfiguration.class)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.websockets.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.integration.websockets.enabled", matchIfMissing = true)
|
||||
class TraceWebSocketAutoConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Autowired
|
||||
@@ -57,20 +56,18 @@ class TraceWebSocketAutoConfiguration extends AbstractWebSocketMessageBrokerConf
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
registry.configureBrokerChannel().setInterceptors(
|
||||
TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
registry.configureBrokerChannel()
|
||||
.setInterceptors(TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureClientOutboundChannel(ChannelRegistration registration) {
|
||||
registration.setInterceptors(
|
||||
TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
registration.setInterceptors(TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureClientInboundChannel(ChannelRegistration registration) {
|
||||
registration.setInterceptors(
|
||||
TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
registration.setInterceptors(TracingChannelInterceptor.create(this.tracing, this.properties));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -57,8 +57,7 @@ import org.springframework.util.ClassUtils;
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
*/
|
||||
final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
implements ExecutorChannelInterceptor {
|
||||
final class TracingChannelInterceptor extends ChannelInterceptorAdapter implements ExecutorChannelInterceptor {
|
||||
|
||||
/**
|
||||
* Name of the class in Spring Cloud Stream that is a direct channel.
|
||||
@@ -109,8 +108,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
|
||||
@Autowired
|
||||
TracingChannelInterceptor(Tracing tracing, SleuthMessagingProperties properties) {
|
||||
this(tracing, properties, MessageHeaderPropagation.INSTANCE,
|
||||
MessageHeaderPropagation.INSTANCE);
|
||||
this(tracing, properties, MessageHeaderPropagation.INSTANCE, MessageHeaderPropagation.INSTANCE);
|
||||
}
|
||||
|
||||
TracingChannelInterceptor(Tracing tracing, SleuthMessagingProperties properties,
|
||||
@@ -122,17 +120,15 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
this.threadLocalSpan = ThreadLocalSpan.create(this.tracer);
|
||||
this.injector = tracing.propagation().injector(setter);
|
||||
this.extractor = tracing.propagation().extractor(getter);
|
||||
this.integrationObjectSupportPresent = ClassUtils.isPresent(
|
||||
"org.springframework.integration.context.IntegrationObjectSupport", null);
|
||||
this.hasDirectChannelClass = ClassUtils
|
||||
.isPresent("org.springframework.integration.channel.DirectChannel", null);
|
||||
this.directWithAttributesChannelClass = ClassUtils
|
||||
.isPresent(STREAM_DIRECT_CHANNEL, null)
|
||||
? ClassUtils.resolveClassName(STREAM_DIRECT_CHANNEL, null) : null;
|
||||
this.integrationObjectSupportPresent = ClassUtils
|
||||
.isPresent("org.springframework.integration.context.IntegrationObjectSupport", null);
|
||||
this.hasDirectChannelClass = ClassUtils.isPresent("org.springframework.integration.channel.DirectChannel",
|
||||
null);
|
||||
this.directWithAttributesChannelClass = ClassUtils.isPresent(STREAM_DIRECT_CHANNEL, null)
|
||||
? ClassUtils.resolveClassName(STREAM_DIRECT_CHANNEL, null) : null;
|
||||
}
|
||||
|
||||
public static TracingChannelInterceptor create(Tracing tracing,
|
||||
SleuthMessagingProperties properties) {
|
||||
public static TracingChannelInterceptor create(Tracing tracing, SleuthMessagingProperties properties) {
|
||||
return new TracingChannelInterceptor(tracing, properties);
|
||||
}
|
||||
|
||||
@@ -169,8 +165,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
MessageHeaderAccessor headers = mutableHeaderAccessor(retrievedMessage);
|
||||
TraceContextOrSamplingFlags extracted = this.extractor.extract(headers);
|
||||
Span span = this.threadLocalSpan.next(extracted);
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers,
|
||||
this.tracing.propagation().keys());
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys());
|
||||
this.injector.inject(span.context(), headers);
|
||||
if (!span.isNoop()) {
|
||||
span.kind(Span.Kind.PRODUCER).name("send").start();
|
||||
@@ -199,24 +194,19 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
return REMOTE_SERVICE_NAME;
|
||||
}
|
||||
|
||||
private Message<?> outputMessage(Message<?> originalMessage,
|
||||
Message<?> retrievedMessage, MessageHeaderAccessor additionalHeaders) {
|
||||
MessageHeaderAccessor headers = MessageHeaderAccessor
|
||||
.getMutableAccessor(originalMessage);
|
||||
private Message<?> outputMessage(Message<?> originalMessage, Message<?> retrievedMessage,
|
||||
MessageHeaderAccessor additionalHeaders) {
|
||||
MessageHeaderAccessor headers = MessageHeaderAccessor.getMutableAccessor(originalMessage);
|
||||
if (originalMessage instanceof ErrorMessage) {
|
||||
ErrorMessage errorMessage = (ErrorMessage) originalMessage;
|
||||
headers.copyHeaders(MessageHeaderPropagation.propagationHeaders(
|
||||
additionalHeaders.getMessageHeaders(),
|
||||
headers.copyHeaders(MessageHeaderPropagation.propagationHeaders(additionalHeaders.getMessageHeaders(),
|
||||
this.tracing.propagation().keys()));
|
||||
return new ErrorMessage(errorMessage.getPayload(),
|
||||
isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()),
|
||||
errorMessage.getOriginalMessage());
|
||||
return new ErrorMessage(errorMessage.getPayload(), isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()), errorMessage.getOriginalMessage());
|
||||
}
|
||||
headers.copyHeaders(additionalHeaders.getMessageHeaders());
|
||||
return new GenericMessage<>(retrievedMessage.getPayload(),
|
||||
isWebSockets(headers) ? headers.getMessageHeaders()
|
||||
: new MessageHeaders(headers.getMessageHeaders()));
|
||||
isWebSockets(headers) ? headers.getMessageHeaders() : new MessageHeaders(headers.getMessageHeaders()));
|
||||
}
|
||||
|
||||
private boolean isWebSockets(MessageHeaderAccessor headerAccessor) {
|
||||
@@ -226,8 +216,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
|
||||
private boolean isDirectChannel(MessageChannel channel) {
|
||||
Class<?> targetClass = AopUtils.getTargetClass(channel);
|
||||
boolean directChannel = this.hasDirectChannelClass
|
||||
&& DirectChannel.class.isAssignableFrom(targetClass);
|
||||
boolean directChannel = this.hasDirectChannelClass && DirectChannel.class.isAssignableFrom(targetClass);
|
||||
if (!directChannel) {
|
||||
return false;
|
||||
}
|
||||
@@ -242,8 +231,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSendCompletion(Message<?> message, MessageChannel channel,
|
||||
boolean sent, Exception ex) {
|
||||
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
|
||||
if (emptyMessage(message)) {
|
||||
return;
|
||||
}
|
||||
@@ -251,8 +239,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
afterMessageHandled(message, channel, null, ex);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will finish the current span after completion "
|
||||
+ this.tracer.currentSpan());
|
||||
log.debug("Will finish the current span after completion " + this.tracer.currentSpan());
|
||||
}
|
||||
finishSpan(ex);
|
||||
}
|
||||
@@ -269,8 +256,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
MessageHeaderAccessor headers = mutableHeaderAccessor(message);
|
||||
TraceContextOrSamplingFlags extracted = this.extractor.extract(headers);
|
||||
Span span = this.threadLocalSpan.next(extracted);
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers,
|
||||
this.tracing.propagation().keys());
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys());
|
||||
this.injector.inject(span.context(), headers);
|
||||
if (!span.isNoop()) {
|
||||
span.kind(Span.Kind.CONSUMER).name("receive").start();
|
||||
@@ -283,21 +269,19 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
headers.setImmutable();
|
||||
if (message instanceof ErrorMessage) {
|
||||
ErrorMessage errorMessage = (ErrorMessage) message;
|
||||
return new ErrorMessage(errorMessage.getPayload(),
|
||||
headers.getMessageHeaders(), errorMessage.getOriginalMessage());
|
||||
return new ErrorMessage(errorMessage.getPayload(), headers.getMessageHeaders(),
|
||||
errorMessage.getOriginalMessage());
|
||||
}
|
||||
return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReceiveCompletion(Message<?> message, MessageChannel channel,
|
||||
Exception ex) {
|
||||
public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
|
||||
if (emptyMessage(message)) {
|
||||
return;
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will finish the current span after receive completion "
|
||||
+ this.tracer.currentSpan());
|
||||
log.debug("Will finish the current span after receive completion " + this.tracer.currentSpan());
|
||||
}
|
||||
finishSpan(ex);
|
||||
}
|
||||
@@ -307,8 +291,7 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
* context. It then creates a span for the handler, placing it in scope.
|
||||
*/
|
||||
@Override
|
||||
public Message<?> beforeHandle(Message<?> message, MessageChannel channel,
|
||||
MessageHandler handler) {
|
||||
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
|
||||
if (emptyMessage(message)) {
|
||||
return message;
|
||||
}
|
||||
@@ -323,34 +306,28 @@ final class TracingChannelInterceptor extends ChannelInterceptorAdapter
|
||||
consumerSpan.finish();
|
||||
}
|
||||
// create and scope a span for the message processor
|
||||
this.threadLocalSpan
|
||||
.next(TraceContextOrSamplingFlags.create(consumerSpan.context()))
|
||||
.name("handle").start();
|
||||
this.threadLocalSpan.next(TraceContextOrSamplingFlags.create(consumerSpan.context())).name("handle").start();
|
||||
// remove any trace headers, but don't re-inject as we are synchronously
|
||||
// processing the
|
||||
// message and can rely on scoping to access this span later.
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers,
|
||||
this.tracing.propagation().keys());
|
||||
MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Created a new span in before handle" + consumerSpan);
|
||||
}
|
||||
if (message instanceof ErrorMessage) {
|
||||
return new ErrorMessage((Throwable) message.getPayload(),
|
||||
headers.getMessageHeaders());
|
||||
return new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders());
|
||||
}
|
||||
headers.setImmutable();
|
||||
return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterMessageHandled(Message<?> message, MessageChannel channel,
|
||||
MessageHandler handler, Exception ex) {
|
||||
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
|
||||
if (emptyMessage(message)) {
|
||||
return;
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will finish the current span after message handled "
|
||||
+ this.tracer.currentSpan());
|
||||
log.debug("Will finish the current span after message handled " + this.tracer.currentSpan());
|
||||
}
|
||||
finishSpan(ex);
|
||||
}
|
||||
|
||||
@@ -51,38 +51,33 @@ class TracingConnectionFactoryBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
// Wrap the caching connection factories instead of its target, because it catches
|
||||
// callbacks
|
||||
// such as ExceptionListener. If we don't wrap, cached callbacks like this won't
|
||||
// be traced.
|
||||
if (bean instanceof CachingConnectionFactory) {
|
||||
return new LazyConnectionFactory(this.beanFactory,
|
||||
(CachingConnectionFactory) bean);
|
||||
return new LazyConnectionFactory(this.beanFactory, (CachingConnectionFactory) bean);
|
||||
}
|
||||
if (bean instanceof JmsMessageEndpointManager) {
|
||||
JmsMessageEndpointManager manager = (JmsMessageEndpointManager) bean;
|
||||
MessageListener listener = manager.getMessageListener();
|
||||
if (listener != null) {
|
||||
manager.setMessageListener(
|
||||
new LazyMessageListener(this.beanFactory, listener));
|
||||
manager.setMessageListener(new LazyMessageListener(this.beanFactory, listener));
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
if (bean instanceof XAConnectionFactory && bean instanceof ConnectionFactory) {
|
||||
return new LazyConnectionAndXaConnectionFactory(this.beanFactory,
|
||||
(ConnectionFactory) bean, (XAConnectionFactory) bean);
|
||||
return new LazyConnectionAndXaConnectionFactory(this.beanFactory, (ConnectionFactory) bean,
|
||||
(XAConnectionFactory) bean);
|
||||
}
|
||||
// We check XA first in case the ConnectionFactory also implements
|
||||
// XAConnectionFactory
|
||||
else if (bean instanceof XAConnectionFactory) {
|
||||
return new LazyXAConnectionFactory(this.beanFactory,
|
||||
(XAConnectionFactory) bean);
|
||||
return new LazyXAConnectionFactory(this.beanFactory, (XAConnectionFactory) bean);
|
||||
}
|
||||
else if (bean instanceof TopicConnectionFactory) {
|
||||
return new LazyTopicConnectionFactory(this.beanFactory,
|
||||
(TopicConnectionFactory) bean);
|
||||
return new LazyTopicConnectionFactory(this.beanFactory, (TopicConnectionFactory) bean);
|
||||
}
|
||||
else if (bean instanceof ConnectionFactory) {
|
||||
return new LazyConnectionFactory(this.beanFactory, (ConnectionFactory) bean);
|
||||
@@ -167,8 +162,7 @@ class LazyTopicConnectionFactory implements TopicConnectionFactory {
|
||||
}
|
||||
|
||||
@Override
|
||||
public TopicConnection createTopicConnection(String s, String s1)
|
||||
throws JMSException {
|
||||
public TopicConnection createTopicConnection(String s, String s1) throws JMSException {
|
||||
return jmsTracing().topicConnection(this.delegate.createTopicConnection(s, s1));
|
||||
}
|
||||
|
||||
@@ -275,20 +269,16 @@ class LazyConnectionFactory implements ConnectionFactory {
|
||||
|
||||
}
|
||||
|
||||
class LazyConnectionAndXaConnectionFactory
|
||||
implements ConnectionFactory, XAConnectionFactory {
|
||||
class LazyConnectionAndXaConnectionFactory implements ConnectionFactory, XAConnectionFactory {
|
||||
|
||||
private final ConnectionFactory connectionFactoryDelegate;
|
||||
|
||||
private final XAConnectionFactory xaConnectionFactoryDelegate;
|
||||
|
||||
LazyConnectionAndXaConnectionFactory(BeanFactory beanFactory,
|
||||
ConnectionFactory connectionFactoryDelegate,
|
||||
LazyConnectionAndXaConnectionFactory(BeanFactory beanFactory, ConnectionFactory connectionFactoryDelegate,
|
||||
XAConnectionFactory xaConnectionFactoryDelegate) {
|
||||
this.connectionFactoryDelegate = new LazyConnectionFactory(beanFactory,
|
||||
connectionFactoryDelegate);
|
||||
this.xaConnectionFactoryDelegate = new LazyXAConnectionFactory(beanFactory,
|
||||
xaConnectionFactoryDelegate);
|
||||
this.connectionFactoryDelegate = new LazyConnectionFactory(beanFactory, connectionFactoryDelegate);
|
||||
this.xaConnectionFactoryDelegate = new LazyXAConnectionFactory(beanFactory, xaConnectionFactoryDelegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -297,8 +287,7 @@ class LazyConnectionAndXaConnectionFactory
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection createConnection(String userName, String password)
|
||||
throws JMSException {
|
||||
public Connection createConnection(String userName, String password) throws JMSException {
|
||||
return this.connectionFactoryDelegate.createConnection(userName, password);
|
||||
}
|
||||
|
||||
@@ -314,8 +303,7 @@ class LazyConnectionAndXaConnectionFactory
|
||||
|
||||
@Override
|
||||
public JMSContext createContext(String userName, String password, int sessionMode) {
|
||||
return this.connectionFactoryDelegate.createContext(userName, password,
|
||||
sessionMode);
|
||||
return this.connectionFactoryDelegate.createContext(userName, password, sessionMode);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -329,8 +317,7 @@ class LazyConnectionAndXaConnectionFactory
|
||||
}
|
||||
|
||||
@Override
|
||||
public XAConnection createXAConnection(String userName, String password)
|
||||
throws JMSException {
|
||||
public XAConnection createXAConnection(String userName, String password) throws JMSException {
|
||||
return this.xaConnectionFactoryDelegate.createXAConnection(userName, password);
|
||||
}
|
||||
|
||||
|
||||
@@ -77,8 +77,7 @@ class TracingMethodMessageHandlerAdapter {
|
||||
}
|
||||
|
||||
// incur timestamp overhead only once
|
||||
long timestamp = tracing.clock(consumerSpan.context())
|
||||
.currentTimeMicroseconds();
|
||||
long timestamp = tracing.clock(consumerSpan.context()).currentTimeMicroseconds();
|
||||
consumerSpan.start(timestamp);
|
||||
long consumerFinish = timestamp + 1L; // save a clock reading
|
||||
consumerSpan.finish(consumerFinish);
|
||||
@@ -99,8 +98,7 @@ class TracingMethodMessageHandlerAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
private TraceContextOrSamplingFlags extractAndClearHeaders(
|
||||
MessageConsumerRequest request) {
|
||||
private TraceContextOrSamplingFlags extractAndClearHeaders(MessageConsumerRequest request) {
|
||||
TraceContextOrSamplingFlags extracted = extractor.extract(request);
|
||||
|
||||
for (String propagationKey : tracing.propagation().keys()) {
|
||||
@@ -134,8 +132,7 @@ final class MessageConsumerRequest extends ConsumerRequest {
|
||||
|
||||
final Getter<MessageHeaderAccessor, String> getter;
|
||||
|
||||
MessageConsumerRequest(Message delegate,
|
||||
Getter<MessageHeaderAccessor, String> getter) {
|
||||
MessageConsumerRequest(Message delegate, Getter<MessageHeaderAccessor, String> getter) {
|
||||
this.delegate = delegate;
|
||||
this.mutableHeaders = MessageHeaderAccessor.getMutableAccessor(delegate);
|
||||
this.getter = getter;
|
||||
|
||||
@@ -50,15 +50,13 @@ class TraceMongoDbAutoConfiguration {
|
||||
@Bean
|
||||
// for tests
|
||||
@ConditionalOnMissingBean(TraceMongoClientSettingsBuilderCustomizer.class)
|
||||
MongoClientSettingsBuilderCustomizer traceMongoClientSettingsBuilderCustomizer(
|
||||
Tracing tracing) {
|
||||
MongoClientSettingsBuilderCustomizer traceMongoClientSettingsBuilderCustomizer(Tracing tracing) {
|
||||
return new TraceMongoClientSettingsBuilderCustomizer(tracing);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TraceMongoClientSettingsBuilderCustomizer
|
||||
implements MongoClientSettingsBuilderCustomizer {
|
||||
class TraceMongoClientSettingsBuilderCustomizer implements MongoClientSettingsBuilderCustomizer {
|
||||
|
||||
private final Tracing tracing;
|
||||
|
||||
@@ -68,8 +66,7 @@ class TraceMongoClientSettingsBuilderCustomizer
|
||||
|
||||
@Override
|
||||
public void customize(MongoClientSettings.Builder clientSettingsBuilder) {
|
||||
clientSettingsBuilder.addCommandListener(
|
||||
MongoDBTracing.create(this.tracing).commandListener());
|
||||
clientSettingsBuilder.addCommandListener(MongoDBTracing.create(this.tracing).commandListener());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -62,8 +62,7 @@ class TraceQuartzAutoConfiguration implements InitializingBean {
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
TracingJobListener tracingJobListener = beanFactory
|
||||
.getBean(TracingJobListener.class);
|
||||
TracingJobListener tracingJobListener = beanFactory.getBean(TracingJobListener.class);
|
||||
scheduler.getListenerManager().addTriggerListener(tracingJobListener);
|
||||
scheduler.getListenerManager().addJobListener(tracingJobListener);
|
||||
}
|
||||
|
||||
@@ -67,12 +67,10 @@ class TracingJobListener implements JobListener, TriggerListener {
|
||||
public void triggerFired(Trigger trigger, JobExecutionContext context) {
|
||||
TraceContextOrSamplingFlags extracted = tracing.propagation().extractor(GETTER)
|
||||
.extract(context.getMergedJobDataMap());
|
||||
Span span = tracing.tracer().nextSpan(extracted)
|
||||
.name(context.getTrigger().getJobKey().toString())
|
||||
Span span = tracing.tracer().nextSpan(extracted).name(context.getTrigger().getJobKey().toString())
|
||||
.tag(TRIGGER_TAG_KEY, context.getTrigger().getKey().toString());
|
||||
context.put(CONTEXT_SPAN_KEY, span);
|
||||
context.put(CONTEXT_SPAN_IN_SCOPE_KEY,
|
||||
tracing.tracer().withSpanInScope(span.start()));
|
||||
context.put(CONTEXT_SPAN_IN_SCOPE_KEY, tracing.tracer().withSpanInScope(span.start()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -102,8 +100,7 @@ class TracingJobListener implements JobListener, TriggerListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void jobWasExecuted(JobExecutionContext context,
|
||||
JobExecutionException jobException) {
|
||||
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
|
||||
}
|
||||
|
||||
private void closeTrace(JobExecutionContext context) {
|
||||
|
||||
@@ -75,8 +75,8 @@ public abstract class ReactorSleuth {
|
||||
|
||||
// keep a reference outside the lambda so that any caching will be visible to
|
||||
// all publishers
|
||||
LazyBean<CurrentTraceContext> lazyCurrentTraceContext = LazyBean
|
||||
.create(springContext, CurrentTraceContext.class);
|
||||
LazyBean<CurrentTraceContext> lazyCurrentTraceContext = LazyBean.create(springContext,
|
||||
CurrentTraceContext.class);
|
||||
|
||||
return Operators.liftPublisher((p, sub) -> {
|
||||
// We don't scope scalar results as they happen in an instant. This prevents
|
||||
@@ -90,8 +90,8 @@ public abstract class ReactorSleuth {
|
||||
assert assertOn = true; // gives a message in unit test failures
|
||||
if (log.isTraceEnabled() || assertOn) {
|
||||
String message = "Spring Context [" + springContext
|
||||
+ "] is not yet refreshed. This is unexpected. Reactor Context is ["
|
||||
+ sub.currentContext() + "] and name is [" + name(sub) + "]";
|
||||
+ "] is not yet refreshed. This is unexpected. Reactor Context is [" + sub.currentContext()
|
||||
+ "] and name is [" + name(sub) + "]";
|
||||
log.trace(message);
|
||||
assert false : message; // should never happen, but don't break.
|
||||
}
|
||||
@@ -105,8 +105,8 @@ public abstract class ReactorSleuth {
|
||||
assert assertOn = true; // gives a message in unit test failures
|
||||
if (log.isTraceEnabled() || assertOn) {
|
||||
String message = "Spring Context [" + springContext
|
||||
+ "] did not return a CurrentTraceContext. Reactor Context is ["
|
||||
+ sub.currentContext() + "] and name is [" + name(sub) + "]";
|
||||
+ "] did not return a CurrentTraceContext. Reactor Context is [" + sub.currentContext()
|
||||
+ "] and name is [" + name(sub) + "]";
|
||||
log.trace(message);
|
||||
assert false : message; // should never happen, but don't break.
|
||||
}
|
||||
@@ -115,8 +115,8 @@ public abstract class ReactorSleuth {
|
||||
|
||||
Context context = contextWithBeans(springContext, sub);
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Spring context [" + springContext + "], Reactor context ["
|
||||
+ context + "], name [" + name(sub) + "]");
|
||||
log.trace("Spring context [" + springContext + "], Reactor context [" + context + "], name ["
|
||||
+ name(sub) + "]");
|
||||
}
|
||||
|
||||
TraceContext parent = traceContext(context, currentTraceContext);
|
||||
@@ -125,26 +125,24 @@ public abstract class ReactorSleuth {
|
||||
}
|
||||
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Creating a scope passing span subscriber with Reactor Context "
|
||||
+ "[" + context + "] and name [" + name(sub) + "]");
|
||||
log.trace("Creating a scope passing span subscriber with Reactor Context " + "[" + context
|
||||
+ "] and name [" + name(sub) + "]");
|
||||
}
|
||||
// if (runStyle == Scannable.Attr.RunStyle.SYNC) {
|
||||
// return sub;
|
||||
// }
|
||||
return new ScopePassingSpanSubscriber<>(sub, context, currentTraceContext,
|
||||
parent);
|
||||
return new ScopePassingSpanSubscriber<>(sub, context, currentTraceContext, parent);
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> Context contextWithBeans(
|
||||
ConfigurableApplicationContext springContext, CoreSubscriber<? super T> sub) {
|
||||
private static <T> Context contextWithBeans(ConfigurableApplicationContext springContext,
|
||||
CoreSubscriber<? super T> sub) {
|
||||
Context context = sub.currentContext();
|
||||
if (!context.hasKey(Tracing.class)) {
|
||||
context = context.put(Tracing.class, springContext.getBean(Tracing.class));
|
||||
}
|
||||
if (!context.hasKey(CurrentTraceContext.class)) {
|
||||
context = context.put(CurrentTraceContext.class,
|
||||
springContext.getBean(CurrentTraceContext.class));
|
||||
context = context.put(CurrentTraceContext.class, springContext.getBean(CurrentTraceContext.class));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -49,14 +49,13 @@ final class ScopePassingSpanSubscriber<T> implements SpanSubscription<T>, Scanna
|
||||
|
||||
private Subscription s;
|
||||
|
||||
ScopePassingSpanSubscriber(Subscriber<? super T> subscriber, Context ctx,
|
||||
CurrentTraceContext currentTraceContext, @Nullable TraceContext parent) {
|
||||
ScopePassingSpanSubscriber(Subscriber<? super T> subscriber, Context ctx, CurrentTraceContext currentTraceContext,
|
||||
@Nullable TraceContext parent) {
|
||||
this.subscriber = subscriber;
|
||||
this.currentTraceContext = currentTraceContext;
|
||||
this.parent = parent;
|
||||
this.context = parent != null
|
||||
&& !parent.equals(ctx.getOrDefault(TraceContext.class, null))
|
||||
? ctx.put(TraceContext.class, parent) : ctx;
|
||||
this.context = parent != null && !parent.equals(ctx.getOrDefault(TraceContext.class, null))
|
||||
? ctx.put(TraceContext.class, parent) : ctx;
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Parent span [" + parent + "], context [" + this.context + "]");
|
||||
}
|
||||
@@ -122,8 +121,7 @@ final class ScopePassingSpanSubscriber<T> implements SpanSubscription<T>, Scanna
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ScopePassingSpanSubscriber{" + "subscriber=" + this.subscriber
|
||||
+ ", parent=" + this.parent + "}";
|
||||
return "ScopePassingSpanSubscriber{" + "subscriber=" + this.subscriber + ", parent=" + this.parent + "}";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,8 +28,7 @@ import reactor.core.Fuseable;
|
||||
* @param <T> - type of the subscription
|
||||
* @author Marcin Grzejszczak
|
||||
*/
|
||||
interface SpanSubscription<T>
|
||||
extends Subscription, CoreSubscriber<T>, Fuseable.QueueSubscription<T> {
|
||||
interface SpanSubscription<T> extends Subscription, CoreSubscriber<T>, Fuseable.QueueSubscription<T> {
|
||||
|
||||
@Override
|
||||
default T poll() {
|
||||
|
||||
@@ -62,8 +62,7 @@ import static org.springframework.cloud.sleuth.instrument.reactor.TraceReactorAu
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.reactor.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(Mono.class)
|
||||
@AutoConfigureAfter(
|
||||
name = "org.springframework.cloud.sleuth.instrument.web.TraceWebFluxAutoConfiguration")
|
||||
@AutoConfigureAfter(name = "org.springframework.cloud.sleuth.instrument.web.TraceWebFluxAutoConfiguration")
|
||||
@EnableConfigurationProperties(SleuthReactorProperties.class)
|
||||
class TraceReactorAutoConfiguration {
|
||||
|
||||
@@ -73,8 +72,7 @@ class TraceReactorAutoConfiguration {
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
static class TraceReactorConfiguration {
|
||||
|
||||
static final String SLEUTH_TRACE_REACTOR_KEY = TraceReactorConfiguration.class
|
||||
.getName();
|
||||
static final String SLEUTH_TRACE_REACTOR_KEY = TraceReactorConfiguration.class.getName();
|
||||
|
||||
private static final Log log = LogFactory.getLog(TraceReactorConfiguration.class);
|
||||
|
||||
@@ -86,9 +84,7 @@ class TraceReactorAutoConfiguration {
|
||||
HookRegisteringBeanDefinitionRegistryPostProcessor traceHookRegisteringBeanDefinitionRegistryPostProcessor(
|
||||
ConfigurableApplicationContext context) {
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace(
|
||||
"Registering bean definition registry post processor for context ["
|
||||
+ context + "]");
|
||||
log.trace("Registering bean definition registry post processor for context [" + context + "]");
|
||||
}
|
||||
return new HookRegisteringBeanDefinitionRegistryPostProcessor(context);
|
||||
}
|
||||
@@ -117,8 +113,7 @@ class HooksRefresher implements ApplicationListener<RefreshScopeRefreshedEvent>
|
||||
|
||||
private final ConfigurableApplicationContext context;
|
||||
|
||||
HooksRefresher(SleuthReactorProperties reactorProperties,
|
||||
ConfigurableApplicationContext context) {
|
||||
HooksRefresher(SleuthReactorProperties reactorProperties, ConfigurableApplicationContext context) {
|
||||
this.reactorProperties = reactorProperties;
|
||||
this.context = context;
|
||||
}
|
||||
@@ -135,35 +130,29 @@ class HooksRefresher implements ApplicationListener<RefreshScopeRefreshedEvent>
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Decorating onEach operator instrumentation");
|
||||
}
|
||||
Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY,
|
||||
scopePassingSpanOperator(this.context));
|
||||
Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY, scopePassingSpanOperator(this.context));
|
||||
break;
|
||||
case DECORATE_ON_LAST:
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Decorating onLast operator instrumentation");
|
||||
}
|
||||
Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY,
|
||||
scopePassingSpanOperator(this.context));
|
||||
Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY, scopePassingSpanOperator(this.context));
|
||||
break;
|
||||
case MANUAL:
|
||||
Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY,
|
||||
springContextSpanOperator(this.context));
|
||||
Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY, springContextSpanOperator(this.context));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class HookRegisteringBeanDefinitionRegistryPostProcessor
|
||||
implements BeanDefinitionRegistryPostProcessor, Closeable {
|
||||
class HookRegisteringBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Closeable {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(HookRegisteringBeanDefinitionRegistryPostProcessor.class);
|
||||
private static final Log log = LogFactory.getLog(HookRegisteringBeanDefinitionRegistryPostProcessor.class);
|
||||
|
||||
final ConfigurableApplicationContext springContext;
|
||||
|
||||
HookRegisteringBeanDefinitionRegistryPostProcessor(
|
||||
ConfigurableApplicationContext springContext) {
|
||||
HookRegisteringBeanDefinitionRegistryPostProcessor(ConfigurableApplicationContext springContext) {
|
||||
this.springContext = springContext;
|
||||
}
|
||||
|
||||
@@ -179,11 +168,9 @@ class HookRegisteringBeanDefinitionRegistryPostProcessor
|
||||
static void setupHooks(ConfigurableApplicationContext springContext) {
|
||||
ConfigurableEnvironment environment = springContext.getEnvironment();
|
||||
SleuthReactorProperties.InstrumentationType property = environment.getProperty(
|
||||
"spring.sleuth.reactor.instrumentation-type",
|
||||
SleuthReactorProperties.InstrumentationType.class,
|
||||
"spring.sleuth.reactor.instrumentation-type", SleuthReactorProperties.InstrumentationType.class,
|
||||
SleuthReactorProperties.InstrumentationType.DECORATE_ON_EACH);
|
||||
Boolean decorateOnEach = environment.getProperty(
|
||||
"spring.sleuth.reactor.decorate-on-each", Boolean.class, true);
|
||||
Boolean decorateOnEach = environment.getProperty("spring.sleuth.reactor.decorate-on-each", Boolean.class, true);
|
||||
if (!decorateOnEach) {
|
||||
log.warn(
|
||||
"You're using the deprecated [spring.sleuth.reactor.decorate-on-each] property. Please use the [spring.sleuth.reactor.instrumentation-type] one instead.");
|
||||
@@ -198,15 +185,12 @@ class HookRegisteringBeanDefinitionRegistryPostProcessor
|
||||
else if (property == SleuthReactorProperties.InstrumentationType.MANUAL) {
|
||||
decorateOnLast(springContextSpanOperator(springContext));
|
||||
}
|
||||
Schedulers.setExecutorServiceDecorator(
|
||||
TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY,
|
||||
(scheduler,
|
||||
scheduledExecutorService) -> new TraceableScheduledExecutorService(
|
||||
springContext, scheduledExecutorService));
|
||||
Schedulers.setExecutorServiceDecorator(TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY,
|
||||
(scheduler, scheduledExecutorService) -> new TraceableScheduledExecutorService(springContext,
|
||||
scheduledExecutorService));
|
||||
}
|
||||
|
||||
private static void decorateOnLast(
|
||||
Function<? super Publisher<Object>, ? extends Publisher<Object>> function) {
|
||||
private static void decorateOnLast(Function<? super Publisher<Object>, ? extends Publisher<Object>> function) {
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Decorating onLast operator instrumentation");
|
||||
}
|
||||
@@ -217,8 +201,7 @@ class HookRegisteringBeanDefinitionRegistryPostProcessor
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Decorating onEach operator instrumentation");
|
||||
}
|
||||
Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY,
|
||||
scopePassingSpanOperator(springContext));
|
||||
Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY, scopePassingSpanOperator(springContext));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -228,8 +211,7 @@ class HookRegisteringBeanDefinitionRegistryPostProcessor
|
||||
}
|
||||
Hooks.resetOnEachOperator(SLEUTH_TRACE_REACTOR_KEY);
|
||||
Hooks.resetOnLastOperator(SLEUTH_TRACE_REACTOR_KEY);
|
||||
Schedulers.removeExecutorServiceDecorator(
|
||||
TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY);
|
||||
Schedulers.removeExecutorServiceDecorator(TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@ class TraceRedisAutoConfiguration {
|
||||
@Bean
|
||||
static TraceLettuceClientResourcesBeanPostProcessor traceLettuceClientResourcesBeanPostProcessor(
|
||||
BeanFactory beanFactory, TraceRedisProperties traceRedisProperties) {
|
||||
return new TraceLettuceClientResourcesBeanPostProcessor(beanFactory,
|
||||
traceRedisProperties);
|
||||
return new TraceLettuceClientResourcesBeanPostProcessor(beanFactory, traceRedisProperties);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -63,8 +62,7 @@ class TraceRedisAutoConfiguration {
|
||||
|
||||
class TraceLettuceClientResourcesBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(TraceLettuceClientResourcesBeanPostProcessor.class);
|
||||
private static final Log log = LogFactory.getLog(TraceLettuceClientResourcesBeanPostProcessor.class);
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -72,30 +70,25 @@ class TraceLettuceClientResourcesBeanPostProcessor implements BeanPostProcessor
|
||||
|
||||
private Tracing tracing;
|
||||
|
||||
TraceLettuceClientResourcesBeanPostProcessor(BeanFactory beanFactory,
|
||||
TraceRedisProperties traceRedisProperties) {
|
||||
TraceLettuceClientResourcesBeanPostProcessor(BeanFactory beanFactory, TraceRedisProperties traceRedisProperties) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.traceRedisProperties = traceRedisProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof ClientResources) {
|
||||
ClientResources cr = (ClientResources) bean;
|
||||
if (!cr.tracing().isEnabled()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Lettuce ClientResources bean is auto-configured to enable tracing.");
|
||||
log.debug("Lettuce ClientResources bean is auto-configured to enable tracing.");
|
||||
}
|
||||
BraveTracing lettuceTracing = BraveTracing.builder().tracing(tracing())
|
||||
.excludeCommandArgsFromSpanTags()
|
||||
BraveTracing lettuceTracing = BraveTracing.builder().tracing(tracing()).excludeCommandArgsFromSpanTags()
|
||||
.serviceName(traceRedisProperties.getRemoteServiceName()).build();
|
||||
return cr.mutate().tracing(lettuceTracing).build();
|
||||
}
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -41,8 +41,7 @@ import org.springframework.lang.Nullable;
|
||||
* @since 2.2.0
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(name = "spring.sleuth.rpc.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(name = "spring.sleuth.rpc.enabled", havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnClass(RpcTracing.class)
|
||||
@AutoConfigureAfter(TraceAutoConfiguration.class)
|
||||
@@ -53,8 +52,7 @@ public class TraceRpcAutoConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
// NOTE: stable bean name as might be used outside sleuth
|
||||
RpcTracing rpcTracing(Tracing tracing,
|
||||
@Nullable @RpcClientSampler SamplerFunction<RpcRequest> clientSampler,
|
||||
RpcTracing rpcTracing(Tracing tracing, @Nullable @RpcClientSampler SamplerFunction<RpcRequest> clientSampler,
|
||||
@Nullable @RpcServerSampler SamplerFunction<RpcRequest> serverSampler,
|
||||
@Nullable List<RpcTracingCustomizer> rpcTracingCustomizers) {
|
||||
|
||||
|
||||
@@ -42,8 +42,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
@AutoConfigureAfter(TraceAutoConfiguration.class)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnClass(RxJavaSchedulersHook.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.rxjava.schedulers.hook.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.rxjava.schedulers.hook.enabled", matchIfMissing = true)
|
||||
@EnableConfigurationProperties(SleuthRxJavaSchedulersProperties.class)
|
||||
class RxJavaAutoConfiguration {
|
||||
|
||||
|
||||
@@ -55,16 +55,14 @@ class SleuthRxJavaSchedulersHook extends RxJavaSchedulersHook {
|
||||
if (this.delegate instanceof SleuthRxJavaSchedulersHook) {
|
||||
return;
|
||||
}
|
||||
RxJavaErrorHandler errorHandler = RxJavaPlugins.getInstance()
|
||||
.getErrorHandler();
|
||||
RxJavaObservableExecutionHook observableExecutionHook = RxJavaPlugins
|
||||
.getInstance().getObservableExecutionHook();
|
||||
RxJavaErrorHandler errorHandler = RxJavaPlugins.getInstance().getErrorHandler();
|
||||
RxJavaObservableExecutionHook observableExecutionHook = RxJavaPlugins.getInstance()
|
||||
.getObservableExecutionHook();
|
||||
logCurrentStateOfRxJavaPlugins(errorHandler, observableExecutionHook);
|
||||
RxJavaPlugins.getInstance().reset();
|
||||
RxJavaPlugins.getInstance().registerSchedulersHook(this);
|
||||
RxJavaPlugins.getInstance().registerErrorHandler(errorHandler);
|
||||
RxJavaPlugins.getInstance()
|
||||
.registerObservableExecutionHook(observableExecutionHook);
|
||||
RxJavaPlugins.getInstance().registerObservableExecutionHook(observableExecutionHook);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
log.error("Failed to register Sleuth RxJava SchedulersHook", ex);
|
||||
@@ -74,9 +72,9 @@ class SleuthRxJavaSchedulersHook extends RxJavaSchedulersHook {
|
||||
private void logCurrentStateOfRxJavaPlugins(RxJavaErrorHandler errorHandler,
|
||||
RxJavaObservableExecutionHook observableExecutionHook) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current RxJava plugins configuration is [" + "schedulersHook ["
|
||||
+ this.delegate + "]," + "errorHandler [" + errorHandler + "],"
|
||||
+ "observableExecutionHook [" + observableExecutionHook + "]," + "]");
|
||||
log.debug("Current RxJava plugins configuration is [" + "schedulersHook [" + this.delegate + "],"
|
||||
+ "errorHandler [" + errorHandler + "]," + "observableExecutionHook [" + observableExecutionHook
|
||||
+ "]," + "]");
|
||||
log.debug("Registering Sleuth RxJava Schedulers Hook.");
|
||||
}
|
||||
}
|
||||
@@ -86,13 +84,11 @@ class SleuthRxJavaSchedulersHook extends RxJavaSchedulersHook {
|
||||
if (action instanceof TraceAction) {
|
||||
return action;
|
||||
}
|
||||
Action0 wrappedAction = this.delegate != null ? this.delegate.onSchedule(action)
|
||||
: action;
|
||||
Action0 wrappedAction = this.delegate != null ? this.delegate.onSchedule(action) : action;
|
||||
if (wrappedAction instanceof TraceAction) {
|
||||
return action;
|
||||
}
|
||||
return super.onSchedule(
|
||||
new TraceAction(this.tracer, wrappedAction, this.threadsToSample));
|
||||
return super.onSchedule(new TraceAction(this.tracer, wrappedAction, this.threadsToSample));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -61,8 +61,7 @@ class TraceSchedulingAspect {
|
||||
|
||||
@Around("execution (@org.springframework.scheduling.annotation.Scheduled * *.*(..))")
|
||||
public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable {
|
||||
if (this.skipPattern != null && this.skipPattern
|
||||
.matcher(pjp.getTarget().getClass().getName()).matches()) {
|
||||
if (this.skipPattern != null && this.skipPattern.matcher(pjp.getTarget().getClass().getName()).matches()) {
|
||||
// we might have a span in context due to wrapping of runnables
|
||||
// we want to clear that context
|
||||
this.tracer.withSpanInScope(null);
|
||||
@@ -76,8 +75,7 @@ class TraceSchedulingAspect {
|
||||
return pjp.proceed();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
String message = ex.getMessage() == null ? ex.getClass().getSimpleName()
|
||||
: ex.getMessage();
|
||||
String message = ex.getMessage() == null ? ex.getClass().getSimpleName() : ex.getMessage();
|
||||
span.tag("error", message);
|
||||
throw ex;
|
||||
}
|
||||
|
||||
@@ -50,8 +50,7 @@ class TraceSchedulingAutoConfiguration {
|
||||
public TraceSchedulingAspect traceSchedulingAspect(Tracer tracer,
|
||||
SleuthSchedulingProperties sleuthSchedulingProperties) {
|
||||
String skipPatternString = sleuthSchedulingProperties.getSkipPattern();
|
||||
Pattern skipPattern = skipPatternString != null
|
||||
? Pattern.compile(skipPatternString) : null;
|
||||
Pattern skipPattern = skipPatternString != null ? Pattern.compile(skipPatternString) : null;
|
||||
return new TraceSchedulingAspect(tracer, skipPattern);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @see Qualifier
|
||||
* @since 2.2.2
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @see Qualifier
|
||||
* @since 2.2.2
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @see Qualifier
|
||||
* @since 2.2.2
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @see Qualifier
|
||||
* @since 2.2.2
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -34,8 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
* @since 2.2.0
|
||||
* @see Qualifier
|
||||
*/
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
|
||||
ElementType.ANNOTATION_TYPE })
|
||||
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -31,8 +31,7 @@ final class ServletUtils {
|
||||
|
||||
}
|
||||
|
||||
static String getHeader(HttpServletRequest request, HttpServletResponse response,
|
||||
String name) {
|
||||
static String getHeader(HttpServletRequest request, HttpServletResponse response, String name) {
|
||||
String value = request.getHeader(name);
|
||||
return value != null ? value : response.getHeader(name);
|
||||
}
|
||||
|
||||
@@ -64,8 +64,7 @@ class SkipPatternConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
SkipPatternProvider sleuthSkipPatternProvider(
|
||||
@Nullable List<SingleSkipPattern> patterns) {
|
||||
SkipPatternProvider sleuthSkipPatternProvider(@Nullable List<SingleSkipPattern> patterns) {
|
||||
if (patterns == null || patterns.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
@@ -96,9 +95,8 @@ class SkipPatternConfiguration {
|
||||
|
||||
@Nullable
|
||||
static Pattern consolidateSkipPatterns(List<SingleSkipPattern> patterns) {
|
||||
List<Pattern> presentPatterns = patterns.stream()
|
||||
.map(SingleSkipPattern::skipPattern).filter(Optional::isPresent)
|
||||
.map(Optional::get).collect(Collectors.toList());
|
||||
List<Pattern> presentPatterns = patterns.stream().map(SingleSkipPattern::skipPattern)
|
||||
.filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
|
||||
if (presentPatterns.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
@@ -116,8 +114,8 @@ class SkipPatternConfiguration {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(ManagementServerProperties.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.ignoreAutoConfiguredSkipPatterns",
|
||||
havingValue = "false", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.ignoreAutoConfiguredSkipPatterns", havingValue = "false",
|
||||
matchIfMissing = true)
|
||||
protected static class ManagementSkipPatternProviderConfig {
|
||||
|
||||
/**
|
||||
@@ -126,38 +124,33 @@ class SkipPatternConfiguration {
|
||||
* @param managementServerProperties properties
|
||||
* @return optional skip pattern
|
||||
*/
|
||||
static Optional<Pattern> getPatternForManagementServerProperties(
|
||||
Environment environment,
|
||||
static Optional<Pattern> getPatternForManagementServerProperties(Environment environment,
|
||||
ManagementServerProperties managementServerProperties) {
|
||||
String contextPath = managementServerProperties.getServlet().getContextPath();
|
||||
if (StringUtils.hasText(contextPath)) {
|
||||
return Optional.of(Pattern
|
||||
.compile(environment.resolvePlaceholders(contextPath) + ".*"));
|
||||
return Optional.of(Pattern.compile(environment.resolvePlaceholders(contextPath) + ".*"));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(ManagementServerProperties.class)
|
||||
public SingleSkipPattern skipPatternForManagementServerProperties(
|
||||
Environment environment,
|
||||
public SingleSkipPattern skipPatternForManagementServerProperties(Environment environment,
|
||||
final ManagementServerProperties managementServerProperties) {
|
||||
return () -> getPatternForManagementServerProperties(environment,
|
||||
managementServerProperties);
|
||||
return () -> getPatternForManagementServerProperties(environment, managementServerProperties);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass({ ServerProperties.class, EndpointsSupplier.class,
|
||||
ExposableWebEndpoint.class })
|
||||
@ConditionalOnClass({ ServerProperties.class, EndpointsSupplier.class, ExposableWebEndpoint.class })
|
||||
@ConditionalOnBean(ServerProperties.class)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.ignoreAutoConfiguredSkipPatterns",
|
||||
havingValue = "false", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.ignoreAutoConfiguredSkipPatterns", havingValue = "false",
|
||||
matchIfMissing = true)
|
||||
protected static class ActuatorSkipPatternProviderConfig {
|
||||
|
||||
static Optional<Pattern> getEndpointsPatterns(Environment environment,
|
||||
String contextPath, WebEndpointProperties webEndpointProperties,
|
||||
static Optional<Pattern> getEndpointsPatterns(Environment environment, String contextPath,
|
||||
WebEndpointProperties webEndpointProperties,
|
||||
EndpointsSupplier<ExposableWebEndpoint> endpointsSupplier) {
|
||||
Collection<ExposableWebEndpoint> endpoints = endpointsSupplier.getEndpoints();
|
||||
if (endpoints.isEmpty()) {
|
||||
@@ -166,16 +159,14 @@ class SkipPatternConfiguration {
|
||||
String basePath = webEndpointProperties.getBasePath();
|
||||
String pattern = patternFromEndpoints(contextPath, endpoints, basePath);
|
||||
if (StringUtils.hasText(pattern)) {
|
||||
return Optional
|
||||
.of(Pattern.compile(environment.resolvePlaceholders(pattern)));
|
||||
return Optional.of(Pattern.compile(environment.resolvePlaceholders(pattern)));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static String patternFromEndpoints(String contextPath,
|
||||
Collection<ExposableWebEndpoint> endpoints, String basePath) {
|
||||
StringJoiner joiner = new StringJoiner("|",
|
||||
getPathPrefix(contextPath, basePath),
|
||||
private static String patternFromEndpoints(String contextPath, Collection<ExposableWebEndpoint> endpoints,
|
||||
String basePath) {
|
||||
StringJoiner joiner = new StringJoiner("|", getPathPrefix(contextPath, basePath),
|
||||
getPathSuffix(contextPath, basePath));
|
||||
for (ExposableWebEndpoint endpoint : endpoints) {
|
||||
String path = endpoint.getRootPath();
|
||||
@@ -203,8 +194,8 @@ class SkipPatternConfiguration {
|
||||
|
||||
private static String getPathSuffix(String contextPath, String actuatorBasePath) {
|
||||
String result = ")";
|
||||
if (StringUtils.hasText(contextPath) || (StringUtils.hasText(actuatorBasePath)
|
||||
&& !"/".equals(actuatorBasePath))) {
|
||||
if (StringUtils.hasText(contextPath)
|
||||
|| (StringUtils.hasText(actuatorBasePath) && !"/".equals(actuatorBasePath))) {
|
||||
result += ")?";
|
||||
}
|
||||
return result;
|
||||
@@ -212,25 +203,21 @@ class SkipPatternConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnManagementPort(ManagementPortType.SAME)
|
||||
public SingleSkipPattern skipPatternForActuatorEndpointsSamePort(
|
||||
Environment environment, final ServerProperties serverProperties,
|
||||
final WebEndpointProperties webEndpointProperties,
|
||||
public SingleSkipPattern skipPatternForActuatorEndpointsSamePort(Environment environment,
|
||||
final ServerProperties serverProperties, final WebEndpointProperties webEndpointProperties,
|
||||
final EndpointsSupplier<ExposableWebEndpoint> endpointsSupplier) {
|
||||
return () -> getEndpointsPatterns(environment,
|
||||
serverProperties.getServlet().getContextPath(), webEndpointProperties,
|
||||
endpointsSupplier);
|
||||
return () -> getEndpointsPatterns(environment, serverProperties.getServlet().getContextPath(),
|
||||
webEndpointProperties, endpointsSupplier);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnManagementPort(ManagementPortType.DIFFERENT)
|
||||
@ConditionalOnProperty(name = "management.server.servlet.context-path",
|
||||
havingValue = "/", matchIfMissing = true)
|
||||
public SingleSkipPattern skipPatternForActuatorEndpointsDifferentPort(
|
||||
Environment environment, final ServerProperties serverProperties,
|
||||
final WebEndpointProperties webEndpointProperties,
|
||||
@ConditionalOnProperty(name = "management.server.servlet.context-path", havingValue = "/",
|
||||
matchIfMissing = true)
|
||||
public SingleSkipPattern skipPatternForActuatorEndpointsDifferentPort(Environment environment,
|
||||
final ServerProperties serverProperties, final WebEndpointProperties webEndpointProperties,
|
||||
final EndpointsSupplier<ExposableWebEndpoint> endpointsSupplier) {
|
||||
return () -> getEndpointsPatterns(environment, null, webEndpointProperties,
|
||||
endpointsSupplier);
|
||||
return () -> getEndpointsPatterns(environment, null, webEndpointProperties, endpointsSupplier);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -239,15 +226,12 @@ class SkipPatternConfiguration {
|
||||
static class DefaultSkipPatternConfig {
|
||||
|
||||
@Bean
|
||||
SingleSkipPattern defaultSkipPatternBean(Environment environment,
|
||||
SleuthWebProperties sleuthWebProperties) {
|
||||
SingleSkipPattern defaultSkipPatternBean(Environment environment, SleuthWebProperties sleuthWebProperties) {
|
||||
String skipPattern = sleuthWebProperties.getSkipPattern();
|
||||
String left = StringUtils.hasText(skipPattern)
|
||||
? environment.resolvePlaceholders(skipPattern) : skipPattern;
|
||||
String left = StringUtils.hasText(skipPattern) ? environment.resolvePlaceholders(skipPattern) : skipPattern;
|
||||
String additionalSkipPattern = sleuthWebProperties.getAdditionalSkipPattern();
|
||||
String right = StringUtils.hasText(additionalSkipPattern)
|
||||
? environment.resolvePlaceholders(additionalSkipPattern)
|
||||
: additionalSkipPattern;
|
||||
? environment.resolvePlaceholders(additionalSkipPattern) : additionalSkipPattern;
|
||||
Pattern pattern = combinePatterns(left, right);
|
||||
return () -> Optional.ofNullable(pattern);
|
||||
}
|
||||
|
||||
@@ -107,8 +107,7 @@ class SleuthWebProperties {
|
||||
return ignoreAutoConfiguredSkipPatterns;
|
||||
}
|
||||
|
||||
public void setIgnoreAutoConfiguredSkipPatterns(
|
||||
boolean ignoreAutoConfiguredSkipPatterns) {
|
||||
public void setIgnoreAutoConfiguredSkipPatterns(boolean ignoreAutoConfiguredSkipPatterns) {
|
||||
this.ignoreAutoConfiguredSkipPatterns = ignoreAutoConfiguredSkipPatterns;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,8 @@ import org.springframework.lang.Nullable;
|
||||
// conditional on "spring.sleuth.web.enabled". As this is conditional on
|
||||
// "spring.sleuth.http.enabled", to be compatible with old behavior we have
|
||||
// to be conditional on two properties.
|
||||
@ConditionalOnProperty(
|
||||
name = { "spring.sleuth.http.enabled", "spring.sleuth.web.enabled" },
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(name = { "spring.sleuth.http.enabled", "spring.sleuth.web.enabled" }, havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnBean(Tracing.class)
|
||||
@ConditionalOnClass(HttpTracing.class)
|
||||
@AutoConfigureAfter(TraceAutoConfiguration.class)
|
||||
@@ -80,8 +79,8 @@ public class TraceHttpAutoConfiguration {
|
||||
@Nullable List<HttpTracingCustomizer> httpTracingCustomizers) {
|
||||
SamplerFunction<HttpRequest> combinedSampler = combineUserProvidedSamplerWithSkipPatternSampler(
|
||||
httpServerSampler, provider);
|
||||
HttpTracing.Builder builder = HttpTracing.newBuilder(tracing)
|
||||
.clientSampler(httpClientSampler).serverSampler(combinedSampler);
|
||||
HttpTracing.Builder builder = HttpTracing.newBuilder(tracing).clientSampler(httpClientSampler)
|
||||
.serverSampler(combinedSampler);
|
||||
|
||||
if (httpClientRequestParser != null || httpClientResponseParser != null) {
|
||||
if (httpClientRequestParser != null) {
|
||||
@@ -116,10 +115,9 @@ public class TraceHttpAutoConfiguration {
|
||||
}
|
||||
|
||||
private SamplerFunction<HttpRequest> combineUserProvidedSamplerWithSkipPatternSampler(
|
||||
@Nullable SamplerFunction<HttpRequest> serverSampler,
|
||||
@Nullable SkipPatternProvider provider) {
|
||||
SamplerFunction<HttpRequest> skipPatternSampler = provider != null
|
||||
? new SkipPatternHttpServerSampler(provider) : null;
|
||||
@Nullable SamplerFunction<HttpRequest> serverSampler, @Nullable SkipPatternProvider provider) {
|
||||
SamplerFunction<HttpRequest> skipPatternSampler = provider != null ? new SkipPatternHttpServerSampler(provider)
|
||||
: null;
|
||||
if (serverSampler == null && skipPatternSampler == null) {
|
||||
return SamplerFunctions.deferDecision();
|
||||
}
|
||||
@@ -134,8 +132,7 @@ public class TraceHttpAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = HttpClientSampler.NAME)
|
||||
SamplerFunction<HttpRequest> sleuthHttpClientSampler(
|
||||
SleuthWebProperties sleuthWebProperties) {
|
||||
SamplerFunction<HttpRequest> sleuthHttpClientSampler(SleuthWebProperties sleuthWebProperties) {
|
||||
String skipPattern = sleuthWebProperties.getClient().getSkipPattern();
|
||||
if (skipPattern == null) {
|
||||
return SamplerFunctions.deferDecision();
|
||||
@@ -157,8 +154,7 @@ final class CompositeHttpSampler implements SamplerFunction<HttpRequest> {
|
||||
|
||||
final SamplerFunction<HttpRequest> right;
|
||||
|
||||
CompositeHttpSampler(SamplerFunction<HttpRequest> left,
|
||||
SamplerFunction<HttpRequest> right) {
|
||||
CompositeHttpSampler(SamplerFunction<HttpRequest> left, SamplerFunction<HttpRequest> right) {
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ import org.springframework.web.context.request.async.WebAsyncTask;
|
||||
@Aspect
|
||||
class TraceWebAspect {
|
||||
|
||||
private static final Log log = org.apache.commons.logging.LogFactory
|
||||
.getLog(TraceWebAspect.class);
|
||||
private static final Log log = org.apache.commons.logging.LogFactory.getLog(TraceWebAspect.class);
|
||||
|
||||
private final Tracing tracing;
|
||||
|
||||
@@ -107,8 +106,7 @@ class TraceWebAspect {
|
||||
}
|
||||
|
||||
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()")
|
||||
public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp)
|
||||
throws Throwable {
|
||||
public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp) throws Throwable {
|
||||
final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) pjp.proceed();
|
||||
TraceContext currentSpan = this.tracing.currentTraceContext().get();
|
||||
if (currentSpan == null) {
|
||||
@@ -120,8 +118,8 @@ class TraceWebAspect {
|
||||
}
|
||||
Field callableField = WebAsyncTask.class.getDeclaredField("callable");
|
||||
callableField.setAccessible(true);
|
||||
callableField.set(webAsyncTask, new TraceCallable<>(this.tracing,
|
||||
this.spanNamer, webAsyncTask.getCallable()));
|
||||
callableField.set(webAsyncTask,
|
||||
new TraceCallable<>(this.tracing, this.spanNamer, webAsyncTask.getCallable()));
|
||||
}
|
||||
catch (NoSuchFieldException ex) {
|
||||
log.warn("Cannot wrap webAsyncTask's callable with TraceCallable", ex);
|
||||
|
||||
@@ -74,8 +74,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
|
||||
private static final String STATUS_CODE_KEY = "http.status_code";
|
||||
|
||||
private static final String TRACE_SPAN_WITHOUT_PARENT = TraceWebFilter.class.getName()
|
||||
+ ".SPAN_WITH_NO_PARENT";
|
||||
private static final String TRACE_SPAN_WITHOUT_PARENT = TraceWebFilter.class.getName() + ".SPAN_WITH_NO_PARENT";
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -98,8 +97,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
@SuppressWarnings("unchecked")
|
||||
HttpServerHandler<HttpServerRequest, HttpServerResponse> handler() {
|
||||
if (this.handler == null) {
|
||||
this.handler = HttpServerHandler
|
||||
.create(this.beanFactory.getBean(HttpTracing.class));
|
||||
this.handler = HttpServerHandler.create(this.beanFactory.getBean(HttpTracing.class));
|
||||
}
|
||||
return this.handler;
|
||||
}
|
||||
@@ -120,8 +118,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
|
||||
SleuthReactorProperties sleuthReactorProperties() {
|
||||
if (this.sleuthReactorProperties == null) {
|
||||
this.sleuthReactorProperties = this.beanFactory
|
||||
.getBean(SleuthReactorProperties.class);
|
||||
this.sleuthReactorProperties = this.beanFactory.getBean(SleuthReactorProperties.class);
|
||||
}
|
||||
return this.sleuthReactorProperties;
|
||||
}
|
||||
@@ -138,8 +135,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
}
|
||||
|
||||
private boolean isTracePresent() {
|
||||
if (sleuthReactorProperties()
|
||||
.getInstrumentationType() == SleuthReactorProperties.InstrumentationType.MANUAL) {
|
||||
if (sleuthReactorProperties().getInstrumentationType() == SleuthReactorProperties.InstrumentationType.MANUAL) {
|
||||
return false;
|
||||
}
|
||||
boolean tracePresent = tracer().currentSpan() != null;
|
||||
@@ -169,8 +165,8 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
|
||||
final boolean initialTracePresent;
|
||||
|
||||
MonoWebFilterTrace(Mono<? extends Void> source, ServerWebExchange exchange,
|
||||
boolean initialTracePresent, TraceWebFilter parent) {
|
||||
MonoWebFilterTrace(Mono<? extends Void> source, ServerWebExchange exchange, boolean initialTracePresent,
|
||||
TraceWebFilter parent) {
|
||||
super(source);
|
||||
this.tracer = parent.tracer();
|
||||
this.handler = parent.handler();
|
||||
@@ -182,8 +178,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
@Override
|
||||
public void subscribe(CoreSubscriber<? super Void> subscriber) {
|
||||
Context context = contextWithoutInitialSpan(subscriber.currentContext());
|
||||
this.source.subscribe(new WebFilterTraceSubscriber(subscriber, context,
|
||||
findOrCreateSpan(context), this));
|
||||
this.source.subscribe(new WebFilterTraceSubscriber(subscriber, context, findOrCreateSpan(context), this));
|
||||
}
|
||||
|
||||
private Context contextWithoutInitialSpan(Context context) {
|
||||
@@ -205,15 +200,13 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
}
|
||||
else {
|
||||
if (this.traceContext != null) {
|
||||
span = this.tracer.nextSpan(
|
||||
TraceContextOrSamplingFlags.create(this.traceContext));
|
||||
span = this.tracer.nextSpan(TraceContextOrSamplingFlags.create(this.traceContext));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found span in attribute " + span);
|
||||
}
|
||||
}
|
||||
else {
|
||||
span = this.handler.handleReceive(
|
||||
new WrappedRequest(this.exchange.getRequest()));
|
||||
span = this.handler.handleReceive(new WrappedRequest(this.exchange.getRequest()));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Handled receive of span " + span);
|
||||
}
|
||||
@@ -235,8 +228,8 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
|
||||
final HttpServerHandler<HttpServerRequest, HttpServerResponse> handler;
|
||||
|
||||
WebFilterTraceSubscriber(CoreSubscriber<? super Void> actual, Context context,
|
||||
Span span, MonoWebFilterTrace parent) {
|
||||
WebFilterTraceSubscriber(CoreSubscriber<? super Void> actual, Context context, Span span,
|
||||
MonoWebFilterTrace parent) {
|
||||
this.actual = actual;
|
||||
this.span = span;
|
||||
this.context = context.put(TraceContext.class, span.context());
|
||||
@@ -272,17 +265,13 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
}
|
||||
|
||||
private void terminateSpan(@Nullable Throwable t) {
|
||||
Object attribute = this.exchange
|
||||
.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
|
||||
Object attribute = this.exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
|
||||
addClassMethodTag(attribute, this.span);
|
||||
addClassNameTag(attribute, this.span);
|
||||
Object pattern = this.exchange
|
||||
.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
Object pattern = this.exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
String httpRoute = pattern != null ? pattern.toString() : "";
|
||||
addResponseTagsForSpanWithoutParent(this.exchange,
|
||||
this.exchange.getResponse(), this.span);
|
||||
WrappedResponse response = new WrappedResponse(
|
||||
this.exchange.getResponse(),
|
||||
addResponseTagsForSpanWithoutParent(this.exchange, this.exchange.getResponse(), this.span);
|
||||
WrappedResponse response = new WrappedResponse(this.exchange.getResponse(),
|
||||
this.exchange.getRequest().getMethodValue(), httpRoute);
|
||||
this.handler.handleSend(response, t, this.span);
|
||||
if (log.isDebugEnabled()) {
|
||||
@@ -295,8 +284,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
String methodName = ((HandlerMethod) handler).getMethod().getName();
|
||||
span.tag(MVC_CONTROLLER_METHOD_KEY, methodName);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Adding a method tag with value [" + methodName
|
||||
+ "] to a span " + span);
|
||||
log.debug("Adding a method tag with value [" + methodName + "] to a span " + span);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,18 +301,15 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
className = handler.getClass().getSimpleName();
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Adding a class tag with value [" + className
|
||||
+ "] to a span " + span);
|
||||
log.debug("Adding a class tag with value [" + className + "] to a span " + span);
|
||||
}
|
||||
span.tag(MVC_CONTROLLER_CLASS_KEY, className);
|
||||
}
|
||||
|
||||
private void addResponseTagsForSpanWithoutParent(ServerWebExchange exchange,
|
||||
ServerHttpResponse response, Span span) {
|
||||
if (spanWithoutParent(exchange) && response.getStatusCode() != null
|
||||
&& span != null) {
|
||||
span.tag(STATUS_CODE_KEY,
|
||||
String.valueOf(response.getStatusCode().value()));
|
||||
private void addResponseTagsForSpanWithoutParent(ServerWebExchange exchange, ServerHttpResponse response,
|
||||
Span span) {
|
||||
if (spanWithoutParent(exchange) && response.getStatusCode() != null && span != null) {
|
||||
span.tag(STATUS_CODE_KEY, String.valueOf(response.getStatusCode().value()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,8 +348,7 @@ final class TraceWebFilter implements WebFilter, Ordered {
|
||||
if (addr == null) {
|
||||
return false;
|
||||
}
|
||||
return span.remoteIpAndPort(addr.getAddress().getHostAddress(),
|
||||
addr.getPort());
|
||||
return span.remoteIpAndPort(addr.getAddress().getHostAddress(), addr.getPort());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -40,8 +40,7 @@ class TraceWebMvcConfigurer implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(this.applicationContext
|
||||
.getBean(SpanCustomizingAsyncHandlerInterceptor.class));
|
||||
registry.addInterceptor(this.applicationContext.getBean(SpanCustomizingAsyncHandlerInterceptor.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -74,13 +74,10 @@ class TraceWebServletAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean traceWebFilter(BeanFactory beanFactory,
|
||||
SleuthWebProperties webProperties) {
|
||||
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
|
||||
new LazyTracingFilter(beanFactory));
|
||||
filterRegistrationBean.setDispatcherTypes(DispatcherType.ASYNC,
|
||||
DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE,
|
||||
DispatcherType.REQUEST);
|
||||
public FilterRegistrationBean traceWebFilter(BeanFactory beanFactory, SleuthWebProperties webProperties) {
|
||||
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new LazyTracingFilter(beanFactory));
|
||||
filterRegistrationBean.setDispatcherTypes(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD,
|
||||
DispatcherType.INCLUDE, DispatcherType.REQUEST);
|
||||
filterRegistrationBean.setOrder(webProperties.getFilterOrder());
|
||||
return filterRegistrationBean;
|
||||
}
|
||||
@@ -120,8 +117,8 @@ final class LazyTracingFilter implements Filter {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
tracingFilter().doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,8 +51,7 @@ public final class WebFluxSleuthOperators {
|
||||
* @param runnable - lambda to execute within the tracing context
|
||||
* @return consumer of a signal
|
||||
*/
|
||||
public static Consumer<Signal> withSpanInScope(SignalType signalType,
|
||||
Runnable runnable) {
|
||||
public static Consumer<Signal> withSpanInScope(SignalType signalType, Runnable runnable) {
|
||||
return signal -> {
|
||||
if (signalType != signal.getType()) {
|
||||
return;
|
||||
@@ -67,8 +66,7 @@ public final class WebFluxSleuthOperators {
|
||||
* @param consumer - lambda to execute within the tracing context
|
||||
* @return consumer of a signal
|
||||
*/
|
||||
public static Consumer<Signal> withSpanInScope(SignalType signalType,
|
||||
Consumer<Signal> consumer) {
|
||||
public static Consumer<Signal> withSpanInScope(SignalType signalType, Consumer<Signal> consumer) {
|
||||
return signal -> {
|
||||
if (signalType != signal.getType()) {
|
||||
return;
|
||||
@@ -97,8 +95,7 @@ public final class WebFluxSleuthOperators {
|
||||
public static void withSpanInScope(Context context, Runnable runnable) {
|
||||
CurrentTraceContext currentTraceContext = context.get(CurrentTraceContext.class);
|
||||
TraceContext traceContext = traceContextOrNew(context);
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext
|
||||
.maybeScope(traceContext)) {
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext.maybeScope(traceContext)) {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
@@ -134,12 +131,10 @@ public final class WebFluxSleuthOperators {
|
||||
* its attribute
|
||||
* @param runnable - lambda to execute within the tracing context
|
||||
*/
|
||||
public static void withSpanInScope(Tracing tracing, ServerWebExchange exchange,
|
||||
Runnable runnable) {
|
||||
public static void withSpanInScope(Tracing tracing, ServerWebExchange exchange, Runnable runnable) {
|
||||
CurrentTraceContext currentTraceContext = tracing.currentTraceContext();
|
||||
TraceContext traceContext = traceContextFromExchangeOrNew(tracing, exchange);
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext
|
||||
.maybeScope(traceContext)) {
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext.maybeScope(traceContext)) {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
@@ -153,8 +148,7 @@ public final class WebFluxSleuthOperators {
|
||||
* @param <T> callable's return type
|
||||
* @return value from the callable
|
||||
*/
|
||||
public static <T> T withSpanInScope(Tracing tracing, ServerWebExchange exchange,
|
||||
Callable<T> callable) {
|
||||
public static <T> T withSpanInScope(Tracing tracing, ServerWebExchange exchange, Callable<T> callable) {
|
||||
CurrentTraceContext currentTraceContext = tracing.currentTraceContext();
|
||||
TraceContext traceContext = traceContextFromExchangeOrNew(tracing, exchange);
|
||||
return withContext(callable, currentTraceContext, traceContext);
|
||||
@@ -189,10 +183,9 @@ public final class WebFluxSleuthOperators {
|
||||
return currentTraceContext(signal.getContext());
|
||||
}
|
||||
|
||||
private static <T> T withContext(Callable<T> callable,
|
||||
CurrentTraceContext currentTraceContext, TraceContext traceContext) {
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext
|
||||
.maybeScope(traceContext)) {
|
||||
private static <T> T withContext(Callable<T> callable, CurrentTraceContext currentTraceContext,
|
||||
TraceContext traceContext) {
|
||||
try (CurrentTraceContext.Scope scope = currentTraceContext.maybeScope(traceContext)) {
|
||||
try {
|
||||
return callable.call();
|
||||
}
|
||||
@@ -202,8 +195,7 @@ public final class WebFluxSleuthOperators {
|
||||
}
|
||||
}
|
||||
|
||||
private static TraceContext traceContextFromExchangeOrNew(Tracing tracing,
|
||||
ServerWebExchange exchange) {
|
||||
private static TraceContext traceContextFromExchangeOrNew(Tracing tracing, ServerWebExchange exchange) {
|
||||
TraceContext traceContext = exchange.getAttribute(TraceContext.class.getName());
|
||||
if (traceContext == null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
|
||||
@@ -50,10 +50,8 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
LazyBean<HttpTracing> httpTracing = LazyBean.create(this.springContext,
|
||||
HttpTracing.class);
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
LazyBean<HttpTracing> httpTracing = LazyBean.create(this.springContext, HttpTracing.class);
|
||||
if (bean instanceof HttpClient) {
|
||||
// This adds handlers to manage the span lifecycle. All require explicit
|
||||
// propagation of the current span as a reactor context property.
|
||||
@@ -63,15 +61,12 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
// In our case, we treat a normal response no differently than one in
|
||||
// preparation of a redirect follow-up.
|
||||
TracingDoOnResponse doOnResponse = new TracingDoOnResponse(httpTracing);
|
||||
return ((HttpClient) bean)
|
||||
.doOnResponseError(new TracingDoOnErrorResponse(httpTracing))
|
||||
return ((HttpClient) bean).doOnResponseError(new TracingDoOnErrorResponse(httpTracing))
|
||||
.doOnRedirect(doOnResponse).doOnResponse(doOnResponse)
|
||||
.doOnRequestError(new TracingDoOnErrorRequest(httpTracing))
|
||||
.doOnRequest(new TracingDoOnRequest(httpTracing))
|
||||
.mapConnect(new TracingMapConnect(() -> {
|
||||
.doOnRequest(new TracingDoOnRequest(httpTracing)).mapConnect(new TracingMapConnect(() -> {
|
||||
HttpTracing ref = httpTracing.get();
|
||||
return ref != null ? ref.tracing().currentTraceContext().get()
|
||||
: null;
|
||||
return ref != null ? ref.tracing().currentTraceContext().get() : null;
|
||||
}));
|
||||
}
|
||||
return bean;
|
||||
@@ -82,8 +77,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
}
|
||||
|
||||
static class TracingMapConnect
|
||||
implements Function<Mono<? extends Connection>, Mono<? extends Connection>> {
|
||||
static class TracingMapConnect implements Function<Mono<? extends Connection>, Mono<? extends Connection>> {
|
||||
|
||||
static final Exception CANCELLED_ERROR = new CancellationException("CANCELLED") {
|
||||
@Override
|
||||
@@ -123,8 +117,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
}
|
||||
|
||||
private static class TracingDoOnRequest
|
||||
implements BiConsumer<HttpClientRequest, Connection> {
|
||||
private static class TracingDoOnRequest implements BiConsumer<HttpClientRequest, Connection> {
|
||||
|
||||
final LazyBean<HttpTracing> httpTracing;
|
||||
|
||||
@@ -143,8 +136,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
@Override
|
||||
public void accept(HttpClientRequest req, Connection connection) {
|
||||
PendingSpan pendingSpan = req.currentContext().getOrDefault(PendingSpan.class,
|
||||
null);
|
||||
PendingSpan pendingSpan = req.currentContext().getOrDefault(PendingSpan.class, null);
|
||||
if (pendingSpan == null) {
|
||||
return; // Somehow TracingMapConnect was not invoked.. skip out
|
||||
}
|
||||
@@ -159,8 +151,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
// Start a new client span with the appropriate parent
|
||||
TraceContext parent = req.currentContext().getOrDefault(TraceContext.class,
|
||||
null);
|
||||
TraceContext parent = req.currentContext().getOrDefault(TraceContext.class, null);
|
||||
HttpClientRequestWrapper request = new HttpClientRequestWrapper(req);
|
||||
|
||||
span = handler().handleSendWithParent(request, parent);
|
||||
@@ -175,8 +166,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
SocketAddress socketAddress = connection.address();
|
||||
if (socketAddress instanceof InetSocketAddress) {
|
||||
InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
|
||||
span.remoteIpAndPort(inetSocketAddress.getHostString(),
|
||||
inetSocketAddress.getPort());
|
||||
span.remoteIpAndPort(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,8 +231,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
return this.handler;
|
||||
}
|
||||
|
||||
void handle(Context context, @Nullable HttpClientResponse resp,
|
||||
@Nullable Throwable error) {
|
||||
void handle(Context context, @Nullable HttpClientResponse resp, @Nullable Throwable error) {
|
||||
PendingSpan pendingSpan = context.getOrDefault(PendingSpan.class, null);
|
||||
if (pendingSpan == null) {
|
||||
return; // Somehow TracingMapConnect was not invoked.. skip out
|
||||
@@ -252,8 +241,7 @@ class HttpClientBeanPostProcessor implements BeanPostProcessor {
|
||||
if (span == null) {
|
||||
return; // Unexpected. In the handle method, without a span to finish!
|
||||
}
|
||||
HttpClientResponseWrapper response = resp != null
|
||||
? new HttpClientResponseWrapper(resp) : null;
|
||||
HttpClientResponseWrapper response = resp != null ? new HttpClientResponseWrapper(resp) : null;
|
||||
handler().handleReceive(response, error, span);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,27 +39,22 @@ import org.springframework.util.StringUtils;
|
||||
*/
|
||||
class TraceGatewayEnvironmentPostProcessor implements EnvironmentPostProcessor {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(TraceGatewayEnvironmentPostProcessor.class);
|
||||
private static final Log log = LogFactory.getLog(TraceGatewayEnvironmentPostProcessor.class);
|
||||
|
||||
private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment,
|
||||
SpringApplication application) {
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
if (sleuthEnabled(environment) && isGatewayOnTheClasspath()) {
|
||||
String instrumentationType = environment
|
||||
.getProperty("spring.sleuth.reactor.instrumentation-type");
|
||||
String instrumentationType = environment.getProperty("spring.sleuth.reactor.instrumentation-type");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found the following instrumentation type ["
|
||||
+ instrumentationType + "]");
|
||||
log.debug("Found the following instrumentation type [" + instrumentationType + "]");
|
||||
}
|
||||
if (StringUtils.isEmpty(instrumentationType)) {
|
||||
instrumentationType = "manual";
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("No instrumentation type passed, will force it to ["
|
||||
+ instrumentationType + "]");
|
||||
log.debug("No instrumentation type passed, will force it to [" + instrumentationType + "]");
|
||||
}
|
||||
}
|
||||
map.put("spring.sleuth.reactor.instrumentation-type", instrumentationType);
|
||||
@@ -68,14 +63,12 @@ class TraceGatewayEnvironmentPostProcessor implements EnvironmentPostProcessor {
|
||||
}
|
||||
|
||||
private boolean sleuthEnabled(ConfigurableEnvironment environment) {
|
||||
return Boolean
|
||||
.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"));
|
||||
return Boolean.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"));
|
||||
}
|
||||
|
||||
private boolean isGatewayOnTheClasspath() {
|
||||
try {
|
||||
ClassUtils.forName("org.springframework.cloud.gateway.filter.GatewayFilter",
|
||||
null);
|
||||
ClassUtils.forName("org.springframework.cloud.gateway.filter.GatewayFilter", null);
|
||||
return true;
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
@@ -83,8 +76,7 @@ class TraceGatewayEnvironmentPostProcessor implements EnvironmentPostProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private void addOrReplace(MutablePropertySources propertySources,
|
||||
Map<String, Object> map) {
|
||||
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
|
||||
MapPropertySource target = null;
|
||||
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
|
||||
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
|
||||
|
||||
@@ -52,16 +52,14 @@ final class TraceRequestHttpHeadersFilter extends AbstractHttpHeadersFilter {
|
||||
@Override
|
||||
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Will instrument the HTTP request headers ["
|
||||
+ exchange.getRequest().getHeaders() + "]");
|
||||
log.debug("Will instrument the HTTP request headers [" + exchange.getRequest().getHeaders() + "]");
|
||||
}
|
||||
HttpClientRequest request = new HttpClientRequest(exchange.getRequest(), input);
|
||||
Span currentSpan = currentSpan(exchange, request);
|
||||
Span span = injectedSpan(request, currentSpan);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Client span " + span + " created for the request. New headers are "
|
||||
+ request.filteredHeaders.toSingleValueMap());
|
||||
log.debug("Client span " + span + " created for the request. New headers are "
|
||||
+ request.filteredHeaders.toSingleValueMap());
|
||||
}
|
||||
exchange.getAttributes().put(SPAN_ATTRIBUTE, span);
|
||||
HttpHeaders headersWithInput = new HttpHeaders();
|
||||
@@ -90,8 +88,7 @@ final class TraceRequestHttpHeadersFilter extends AbstractHttpHeadersFilter {
|
||||
Object attribute = exchange.getAttribute(TRACE_REQUEST_ATTR);
|
||||
if (attribute instanceof Span) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Found trace request attribute in the server web exchange ["
|
||||
+ attribute + "]");
|
||||
log.debug("Found trace request attribute in the server web exchange [" + attribute + "]");
|
||||
}
|
||||
return (Span) attribute;
|
||||
}
|
||||
@@ -106,8 +103,7 @@ final class TraceRequestHttpHeadersFilter extends AbstractHttpHeadersFilter {
|
||||
return this.handler.handleSend(request, clientSpan);
|
||||
}
|
||||
|
||||
private void addHeadersWithInput(HttpHeaders filteredHeaders,
|
||||
HttpHeaders headersWithInput) {
|
||||
private void addHeadersWithInput(HttpHeaders filteredHeaders, HttpHeaders headersWithInput) {
|
||||
for (Map.Entry<String, List<String>> entry : filteredHeaders.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
List<String> value = entry.getValue();
|
||||
@@ -124,8 +120,7 @@ final class TraceRequestHttpHeadersFilter extends AbstractHttpHeadersFilter {
|
||||
|
||||
final class TraceResponseHttpHeadersFilter extends AbstractHttpHeadersFilter {
|
||||
|
||||
private static final Log log = LogFactory
|
||||
.getLog(TraceResponseHttpHeadersFilter.class);
|
||||
private static final Log log = LogFactory.getLog(TraceResponseHttpHeadersFilter.class);
|
||||
|
||||
private TraceResponseHttpHeadersFilter(HttpTracing httpTracing) {
|
||||
super(httpTracing);
|
||||
@@ -173,8 +168,7 @@ abstract class AbstractHttpHeadersFilter implements HttpHeadersFilter {
|
||||
|
||||
AbstractHttpHeadersFilter(HttpTracing httpTracing) {
|
||||
this.tracer = httpTracing.tracing().tracer();
|
||||
this.extractor = httpTracing.tracing().propagation()
|
||||
.extractor(HttpClientRequest::header);
|
||||
this.extractor = httpTracing.tracing().propagation().extractor(HttpClientRequest::header);
|
||||
this.handler = HttpClientHandler.create(httpTracing);
|
||||
this.httpTracing = httpTracing;
|
||||
}
|
||||
@@ -237,8 +231,7 @@ abstract class AbstractHttpHeadersFilter implements HttpHeadersFilter {
|
||||
|
||||
@Override
|
||||
public int statusCode() {
|
||||
return delegate.getStatusCode() != null ? delegate.getStatusCode().value()
|
||||
: 0;
|
||||
return delegate.getStatusCode() != null ? delegate.getStatusCode().value() : 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -47,8 +47,7 @@ import org.springframework.web.client.AsyncRestTemplate;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@SleuthWebClientEnabled
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.async.client.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.sleuth.web.async.client.enabled", matchIfMissing = true)
|
||||
@ConditionalOnClass(AsyncRestTemplate.class)
|
||||
@ConditionalOnBean(HttpTracing.class)
|
||||
@AutoConfigureAfter(TraceHttpAutoConfiguration.class)
|
||||
|
||||
@@ -75,10 +75,8 @@ class TraceWebClientAutoConfiguration {
|
||||
static class RestTemplateConfig {
|
||||
|
||||
@Bean
|
||||
public TracingClientHttpRequestInterceptor tracingClientHttpRequestInterceptor(
|
||||
HttpTracing httpTracing) {
|
||||
return (TracingClientHttpRequestInterceptor) TracingClientHttpRequestInterceptor
|
||||
.create(httpTracing);
|
||||
public TracingClientHttpRequestInterceptor tracingClientHttpRequestInterceptor(HttpTracing httpTracing) {
|
||||
return (TracingClientHttpRequestInterceptor) TracingClientHttpRequestInterceptor.create(httpTracing);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@@ -96,8 +94,7 @@ class TraceWebClientAutoConfiguration {
|
||||
@Bean
|
||||
@Order
|
||||
RestTemplateCustomizer traceRestTemplateCustomizer() {
|
||||
return new TraceRestTemplateCustomizer(
|
||||
new LazyTracingClientHttpRequestInterceptor(this.beanFactory));
|
||||
return new TraceRestTemplateCustomizer(new LazyTracingClientHttpRequestInterceptor(this.beanFactory));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -161,16 +158,14 @@ class TraceWebClientAutoConfiguration {
|
||||
static class NettyConfiguration {
|
||||
|
||||
@Bean
|
||||
static HttpClientBeanPostProcessor httpClientBeanPostProcessor(
|
||||
ConfigurableApplicationContext springContext) {
|
||||
static HttpClientBeanPostProcessor httpClientBeanPostProcessor(ConfigurableApplicationContext springContext) {
|
||||
return new HttpClientBeanPostProcessor(springContext);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass({ UserInfoRestTemplateCustomizer.class,
|
||||
OAuth2RestTemplate.class })
|
||||
@ConditionalOnClass({ UserInfoRestTemplateCustomizer.class, OAuth2RestTemplate.class })
|
||||
protected static class TraceOAuthConfiguration {
|
||||
|
||||
@Bean
|
||||
@@ -181,13 +176,11 @@ class TraceWebClientAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
static UserInfoRestTemplateCustomizer traceUserInfoRestTemplateCustomizer(
|
||||
BeanFactory beanFactory) {
|
||||
static UserInfoRestTemplateCustomizer traceUserInfoRestTemplateCustomizer(BeanFactory beanFactory) {
|
||||
return new TraceUserInfoRestTemplateCustomizer(beanFactory);
|
||||
}
|
||||
|
||||
private static class UserInfoRestTemplateCustomizerBPP
|
||||
implements BeanPostProcessor {
|
||||
private static class UserInfoRestTemplateCustomizerBPP implements BeanPostProcessor {
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -196,14 +189,12 @@ class TraceWebClientAutoConfiguration {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(final Object bean,
|
||||
String beanName) throws BeansException {
|
||||
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
|
||||
final BeanFactory beanFactory = this.beanFactory;
|
||||
if (bean instanceof UserInfoRestTemplateCustomizer
|
||||
&& !(bean instanceof TraceUserInfoRestTemplateCustomizer)) {
|
||||
@@ -272,14 +263,12 @@ class TraceRestTemplateBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof RestTemplate) {
|
||||
RestTemplate rt = (RestTemplate) bean;
|
||||
new RestTemplateInterceptorInjector(interceptor()).inject(rt);
|
||||
@@ -304,15 +293,14 @@ class LazyTracingClientHttpRequestInterceptor implements ClientHttpRequestInterc
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
|
||||
ClientHttpRequestExecution execution) throws IOException {
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
|
||||
throws IOException {
|
||||
return interceptor().intercept(request, body, execution);
|
||||
}
|
||||
|
||||
private TracingClientHttpRequestInterceptor interceptor() {
|
||||
if (this.interceptor == null) {
|
||||
this.interceptor = this.beanFactory
|
||||
.getBean(TracingClientHttpRequestInterceptor.class);
|
||||
this.interceptor = this.beanFactory.getBean(TracingClientHttpRequestInterceptor.class);
|
||||
}
|
||||
return this.interceptor;
|
||||
}
|
||||
|
||||
@@ -97,8 +97,7 @@ final class TraceWebClientBeanPostProcessor implements BeanPostProcessor {
|
||||
};
|
||||
}
|
||||
|
||||
private boolean noneMatchTraceExchangeFunction(
|
||||
List<ExchangeFilterFunction> functions) {
|
||||
private boolean noneMatchTraceExchangeFunction(List<ExchangeFilterFunction> functions) {
|
||||
for (ExchangeFilterFunction function : functions) {
|
||||
if (function instanceof TraceExchangeFilterFunction) {
|
||||
return false;
|
||||
@@ -127,8 +126,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
this.scopePassingTransformer = scopePassingSpanOperator(springContext);
|
||||
}
|
||||
|
||||
public static ExchangeFilterFunction create(
|
||||
ConfigurableApplicationContext springContext) {
|
||||
public static ExchangeFilterFunction create(ConfigurableApplicationContext springContext) {
|
||||
return new TraceExchangeFilterFunction(springContext);
|
||||
}
|
||||
|
||||
@@ -161,8 +159,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
|
||||
final CurrentTraceContext currentTraceContext;
|
||||
|
||||
MonoWebClientTrace(ExchangeFunction next, ClientRequest request,
|
||||
TraceExchangeFilterFunction filterFunction) {
|
||||
MonoWebClientTrace(ExchangeFunction next, ClientRequest request, TraceExchangeFilterFunction filterFunction) {
|
||||
this.next = next;
|
||||
this.request = request;
|
||||
this.handler = filterFunction.handler();
|
||||
@@ -176,8 +173,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
log.trace("Got the following context [" + context + "]");
|
||||
}
|
||||
ClientRequestWrapper wrapper = new ClientRequestWrapper(request);
|
||||
TraceContext parent = context.hasKey(TraceContext.class)
|
||||
? context.get(TraceContext.class) : null;
|
||||
TraceContext parent = context.hasKey(TraceContext.class) ? context.get(TraceContext.class) : null;
|
||||
Span span = handler.handleSendWithParent(wrapper, parent);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("HttpClientHandler::handleSend: " + span);
|
||||
@@ -186,8 +182,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
// canceled prior to actually being invoked. TraceWebClientSubscription will
|
||||
// abandon this span, if cancel() happens before request().
|
||||
this.next.exchange(wrapper.buildRequest())
|
||||
.subscribe(new TraceWebClientSubscriber(subscriber, context, span,
|
||||
parent, this));
|
||||
.subscribe(new TraceWebClientSubscriber(subscriber, context, span, parent, this));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -206,16 +201,14 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
|
||||
final CurrentTraceContext currentTraceContext;
|
||||
|
||||
TraceWebClientSubscriber(CoreSubscriber<? super ClientResponse> actual,
|
||||
Context ctx, Span clientSpan, TraceContext parent,
|
||||
MonoWebClientTrace mono) {
|
||||
TraceWebClientSubscriber(CoreSubscriber<? super ClientResponse> actual, Context ctx, Span clientSpan,
|
||||
TraceContext parent, MonoWebClientTrace mono) {
|
||||
this.actual = actual;
|
||||
this.parent = parent;
|
||||
this.handler = mono.handler;
|
||||
this.currentTraceContext = mono.currentTraceContext;
|
||||
this.context = this.parent != null
|
||||
&& !this.parent.equals(ctx.getOrDefault(TraceContext.class, null))
|
||||
? ctx.put(TraceContext.class, this.parent) : ctx;
|
||||
this.context = this.parent != null && !this.parent.equals(ctx.getOrDefault(TraceContext.class, null))
|
||||
? ctx.put(TraceContext.class, this.parent) : ctx;
|
||||
set(clientSpan);
|
||||
}
|
||||
|
||||
@@ -234,8 +227,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
Span span = getAndSet(null);
|
||||
if (span != null) {
|
||||
// TODO: is there a way to read the request at response time?
|
||||
this.handler.handleReceive(new ClientResponseWrapper(response), null,
|
||||
span);
|
||||
this.handler.handleReceive(new ClientResponseWrapper(response), null, span);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -294,8 +286,7 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
|
||||
volatile boolean requested;
|
||||
|
||||
TraceWebClientSubscription(Subscription delegate,
|
||||
AtomicReference<Span> pendingSpan) {
|
||||
TraceWebClientSubscription(Subscription delegate, AtomicReference<Span> pendingSpan) {
|
||||
this.delegate = delegate;
|
||||
this.pendingSpan = pendingSpan;
|
||||
}
|
||||
@@ -315,9 +306,8 @@ final class TraceExchangeFilterFunction implements ExchangeFilterFunction {
|
||||
Span span = pendingSpan.getAndSet(null);
|
||||
if (span != null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Subscription was cancelled. TraceWebClientBeanPostProcessor Will close the span ["
|
||||
+ span + "]");
|
||||
log.debug("Subscription was cancelled. TraceWebClientBeanPostProcessor Will close the span [" + span
|
||||
+ "]");
|
||||
}
|
||||
|
||||
if (!requested) { // Abandon the span.
|
||||
|
||||
@@ -36,14 +36,12 @@ final class FeignContextBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof FeignContext && !(bean instanceof TraceFeignContext)) {
|
||||
return new TraceFeignContext(traceFeignObjectWrapper(), (FeignContext) bean);
|
||||
}
|
||||
|
||||
@@ -59,8 +59,7 @@ class LazyClient implements Client {
|
||||
this.delegate = this.beanFactory.getBean(Client.class);
|
||||
}
|
||||
catch (BeansException ex) {
|
||||
this.delegate = TracingFeignClient.create(
|
||||
beanFactory.getBean(HttpTracing.class),
|
||||
this.delegate = TracingFeignClient.create(beanFactory.getBean(HttpTracing.class),
|
||||
new Client.Default(null, null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,17 +53,15 @@ class LazyTracingFeignClient implements Client {
|
||||
@Override
|
||||
public Response execute(Request request, Request.Options options) throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Sending a request via tracing feign client [" + tracingFeignClient()
|
||||
+ "] " + "and the delegate [" + this.delegate + "]");
|
||||
log.debug("Sending a request via tracing feign client [" + tracingFeignClient() + "] "
|
||||
+ "and the delegate [" + this.delegate + "]");
|
||||
}
|
||||
return tracingFeignClient().execute(request, options);
|
||||
}
|
||||
|
||||
private Client tracingFeignClient() {
|
||||
if (this.tracingFeignClient == null) {
|
||||
this.tracingFeignClient = TracingFeignClient.create(httpTracing(),
|
||||
this.delegate);
|
||||
this.tracingFeignClient = TracingFeignClient.create(httpTracing(), this.delegate);
|
||||
}
|
||||
return this.tracingFeignClient;
|
||||
}
|
||||
|
||||
@@ -38,8 +38,7 @@ final class OkHttpFeignClientBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof OkHttpClient && !(bean instanceof LazyClient)) {
|
||||
return new LazyClient(this.beanFactory, (Client) bean);
|
||||
}
|
||||
@@ -47,8 +46,7 @@ final class OkHttpFeignClientBeanPostProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,7 @@ class TraceFeignAspect {
|
||||
return pjp.proceed();
|
||||
}
|
||||
|
||||
Object executeTraceFeignClient(Object bean, ProceedingJoinPoint pjp)
|
||||
throws IOException {
|
||||
Object executeTraceFeignClient(Object bean, ProceedingJoinPoint pjp) throws IOException {
|
||||
Object[] args = pjp.getArgs();
|
||||
Request request = (Request) args[0];
|
||||
Request.Options options = (Request.Options) args[1];
|
||||
|
||||
@@ -40,8 +40,7 @@ import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalance
|
||||
*/
|
||||
class TraceFeignBlockingLoadBalancerClient extends FeignBlockingLoadBalancerClient {
|
||||
|
||||
private static final Log LOG = LogFactory
|
||||
.getLog(TraceFeignBlockingLoadBalancerClient.class);
|
||||
private static final Log LOG = LogFactory.getLog(TraceFeignBlockingLoadBalancerClient.class);
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
|
||||
@@ -51,8 +50,8 @@ class TraceFeignBlockingLoadBalancerClient extends FeignBlockingLoadBalancerClie
|
||||
|
||||
TracingFeignClient tracingFeignClient;
|
||||
|
||||
TraceFeignBlockingLoadBalancerClient(Client delegate,
|
||||
LoadBalancerClient loadBalancerClient, BeanFactory beanFactory) {
|
||||
TraceFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
|
||||
BeanFactory beanFactory) {
|
||||
super(delegate, loadBalancerClient);
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
@@ -91,8 +90,7 @@ class TraceFeignBlockingLoadBalancerClient extends FeignBlockingLoadBalancerClie
|
||||
LOG.debug(
|
||||
"General exception was thrown, so most likely the traced client wasn't called. Falling back to a manual span");
|
||||
}
|
||||
tracingFeignClient().handleSendAndReceive(fallbackSpan, request, response,
|
||||
e);
|
||||
tracingFeignClient().handleSendAndReceive(fallbackSpan, request, response, e);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -121,8 +119,7 @@ class TraceFeignBlockingLoadBalancerClient extends FeignBlockingLoadBalancerClie
|
||||
|
||||
private TracingFeignClient tracingFeignClient() {
|
||||
if (tracingFeignClient == null) {
|
||||
tracingFeignClient = (TracingFeignClient) TracingFeignClient
|
||||
.create(httpTracing(), getDelegate());
|
||||
tracingFeignClient = (TracingFeignClient) TracingFeignClient.create(httpTracing(), getDelegate());
|
||||
}
|
||||
return tracingFeignClient;
|
||||
}
|
||||
|
||||
@@ -68,13 +68,11 @@ class TraceFeignClientAutoConfiguration {
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(name = "spring.sleuth.feign.processor.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(name = "spring.sleuth.feign.processor.enabled", matchIfMissing = true)
|
||||
protected static class FeignBeanPostProcessorConfiguration {
|
||||
|
||||
@Bean
|
||||
static FeignContextBeanPostProcessor feignContextBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
static FeignContextBeanPostProcessor feignContextBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new FeignContextBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
@@ -85,8 +83,7 @@ class TraceFeignClientAutoConfiguration {
|
||||
protected static class OkHttpClientFeignBeanPostProcessorConfiguration {
|
||||
|
||||
@Bean
|
||||
static OkHttpFeignClientBeanPostProcessor okHttpFeignClientBeanPostProcessor(
|
||||
BeanFactory beanFactory) {
|
||||
static OkHttpFeignClientBeanPostProcessor okHttpFeignClientBeanPostProcessor(BeanFactory beanFactory) {
|
||||
return new OkHttpFeignClientBeanPostProcessor(beanFactory);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,8 +34,7 @@ class TraceFeignContext extends FeignContext {
|
||||
|
||||
private final FeignContext delegate;
|
||||
|
||||
TraceFeignContext(TraceFeignObjectWrapper traceFeignObjectWrapper,
|
||||
FeignContext delegate) {
|
||||
TraceFeignContext(TraceFeignObjectWrapper traceFeignObjectWrapper, FeignContext delegate) {
|
||||
this.traceFeignObjectWrapper = traceFeignObjectWrapper;
|
||||
this.delegate = delegate;
|
||||
}
|
||||
@@ -59,8 +58,7 @@ class TraceFeignContext extends FeignContext {
|
||||
}
|
||||
Map<String, T> convertedInstances = new HashMap<>();
|
||||
for (Map.Entry<String, T> entry : instances.entrySet()) {
|
||||
convertedInstances.put(entry.getKey(),
|
||||
(T) this.traceFeignObjectWrapper.wrap(entry.getValue()));
|
||||
convertedInstances.put(entry.getKey(), (T) this.traceFeignObjectWrapper.wrap(entry.getValue()));
|
||||
}
|
||||
return convertedInstances;
|
||||
}
|
||||
|
||||
@@ -47,12 +47,10 @@ final class TraceFeignObjectWrapper {
|
||||
private static final String DELEGATE = "delegate";
|
||||
|
||||
static {
|
||||
loadBalancerPresent = ClassUtils.isPresent(
|
||||
"org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient",
|
||||
null)
|
||||
loadBalancerPresent = ClassUtils
|
||||
.isPresent("org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient", null)
|
||||
&& ClassUtils.isPresent(
|
||||
"org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient",
|
||||
null);
|
||||
"org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient", null);
|
||||
}
|
||||
|
||||
private final BeanFactory beanFactory;
|
||||
@@ -78,25 +76,21 @@ final class TraceFeignObjectWrapper {
|
||||
if (AopUtils.getTargetClass(bean).equals(FeignBlockingLoadBalancerClient.class)) {
|
||||
FeignBlockingLoadBalancerClient client = ProxyUtils.getTargetObject(bean);
|
||||
return new TraceFeignBlockingLoadBalancerClient(
|
||||
(Client) new TraceFeignObjectWrapper(this.beanFactory)
|
||||
.wrap(client.getDelegate()),
|
||||
(Client) new TraceFeignObjectWrapper(this.beanFactory).wrap(client.getDelegate()),
|
||||
(LoadBalancerClient) loadBalancerClient(), this.beanFactory);
|
||||
}
|
||||
else {
|
||||
FeignBlockingLoadBalancerClient client = ProxyUtils.getTargetObject(bean);
|
||||
try {
|
||||
Field delegate = FeignBlockingLoadBalancerClient.class
|
||||
.getDeclaredField(DELEGATE);
|
||||
Field delegate = FeignBlockingLoadBalancerClient.class.getDeclaredField(DELEGATE);
|
||||
delegate.setAccessible(true);
|
||||
delegate.set(client, new TraceFeignObjectWrapper(this.beanFactory)
|
||||
.wrap(client.getDelegate()));
|
||||
delegate.set(client, new TraceFeignObjectWrapper(this.beanFactory).wrap(client.getDelegate()));
|
||||
}
|
||||
catch (NoSuchFieldException | IllegalArgumentException
|
||||
| IllegalAccessException | SecurityException e) {
|
||||
catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException | SecurityException e) {
|
||||
log.warn(EXCEPTION_WARNING, e);
|
||||
}
|
||||
return new TraceFeignBlockingLoadBalancerClient(client,
|
||||
(LoadBalancerClient) loadBalancerClient(), this.beanFactory);
|
||||
return new TraceFeignBlockingLoadBalancerClient(client, (LoadBalancerClient) loadBalancerClient(),
|
||||
this.beanFactory);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ final class TracingFeignClient implements Client {
|
||||
this.currentTraceContext = httpTracing.tracing().currentTraceContext();
|
||||
this.handler = HttpClientHandler.create(httpTracing);
|
||||
Client delegateTarget = ProxyUtils.getTargetObject(delegate);
|
||||
this.delegate = delegateTarget instanceof TracingFeignClient
|
||||
? ((TracingFeignClient) delegateTarget).delegate : delegateTarget;
|
||||
this.delegate = delegateTarget instanceof TracingFeignClient ? ((TracingFeignClient) delegateTarget).delegate
|
||||
: delegateTarget;
|
||||
}
|
||||
|
||||
static Client create(HttpTracing httpTracing, Client delegate) {
|
||||
@@ -89,8 +89,7 @@ final class TracingFeignClient implements Client {
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
ResponseWrapper response = res != null
|
||||
? new ResponseWrapper(request, res, error) : null;
|
||||
ResponseWrapper response = res != null ? new ResponseWrapper(request, res, error) : null;
|
||||
this.handler.handleReceive(response, error, span);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
@@ -99,12 +98,10 @@ final class TracingFeignClient implements Client {
|
||||
}
|
||||
}
|
||||
|
||||
void handleSendAndReceive(Span span, Request req, @Nullable Response res,
|
||||
@Nullable Throwable error) {
|
||||
void handleSendAndReceive(Span span, Request req, @Nullable Response res, @Nullable Throwable error) {
|
||||
RequestWrapper request = new RequestWrapper(req);
|
||||
this.handler.handleSend(request, span);
|
||||
ResponseWrapper response = res != null ? new ResponseWrapper(request, res, error)
|
||||
: null;
|
||||
ResponseWrapper response = res != null ? new ResponseWrapper(request, res, error) : null;
|
||||
this.handler.handleReceive(response, error, span);
|
||||
}
|
||||
|
||||
@@ -145,8 +142,7 @@ final class TracingFeignClient implements Client {
|
||||
@Override
|
||||
public String header(String name) {
|
||||
Collection<String> result = delegate.headers().get(name);
|
||||
return result != null && result.iterator().hasNext()
|
||||
? result.iterator().next() : null;
|
||||
return result != null && result.iterator().hasNext() ? result.iterator().next() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -157,8 +153,7 @@ final class TracingFeignClient implements Client {
|
||||
if (!headers.containsKey(name)) {
|
||||
headers.put(name, Collections.singletonList(value));
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace(
|
||||
"Added key [" + name + "] and header value [" + value + "]");
|
||||
log.trace("Added key [" + name + "] and header value [" + value + "]");
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -176,8 +171,7 @@ final class TracingFeignClient implements Client {
|
||||
String url = delegate.url();
|
||||
byte[] body = delegate.body();
|
||||
Charset charset = delegate.charset();
|
||||
return Request.create(delegate.httpMethod(), url, headers, body, charset,
|
||||
delegate.requestTemplate());
|
||||
return Request.create(delegate.httpMethod(), url, headers, body, charset, delegate.requestTemplate());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -191,8 +185,7 @@ final class TracingFeignClient implements Client {
|
||||
@Nullable
|
||||
final Throwable error;
|
||||
|
||||
ResponseWrapper(RequestWrapper request, Response response,
|
||||
@Nullable Throwable error) {
|
||||
ResponseWrapper(RequestWrapper request, Response response, @Nullable Throwable error) {
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
this.error = error;
|
||||
|
||||
@@ -45,8 +45,7 @@ public class DefaultSpanNamer implements SpanNamer {
|
||||
if (delegate instanceof Method) {
|
||||
return delegate.toString().equals(spanName);
|
||||
}
|
||||
return (delegate.getClass().getName() + "@"
|
||||
+ Integer.toHexString(delegate.hashCode())).equals(spanName);
|
||||
return (delegate.getClass().getName() + "@" + Integer.toHexString(delegate.hashCode())).equals(spanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -31,8 +31,7 @@ import org.springframework.lang.Nullable;
|
||||
*/
|
||||
public final class LazyBean<T> {
|
||||
|
||||
public static <T> LazyBean<T> create(ConfigurableApplicationContext springContext,
|
||||
Class<T> requiredType) {
|
||||
public static <T> LazyBean<T> create(ConfigurableApplicationContext springContext, Class<T> requiredType) {
|
||||
return new LazyBean<>(springContext, requiredType);
|
||||
}
|
||||
|
||||
@@ -65,8 +64,7 @@ public final class LazyBean<T> {
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Spring context [" + springContext + "] error getting ["
|
||||
+ requiredType + "].", ex);
|
||||
log.debug("Spring context [" + springContext + "] error getting [" + requiredType + "].", ex);
|
||||
}
|
||||
}
|
||||
return this.value;
|
||||
|
||||
@@ -36,8 +36,7 @@ public final class SpanNameUtil {
|
||||
if (StringUtils.isEmpty(name)) {
|
||||
return name;
|
||||
}
|
||||
int maxLength = name.length() > MAX_NAME_LENGTH ? (MAX_NAME_LENGTH)
|
||||
: (name.length());
|
||||
int maxLength = name.length() > MAX_NAME_LENGTH ? (MAX_NAME_LENGTH) : (name.length());
|
||||
return name.substring(0, maxLength);
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user