diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/ElasticApmAgent.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/ElasticApmAgent.java index 45946dfda65..b1cddde999b 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/ElasticApmAgent.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/ElasticApmAgent.java @@ -38,8 +38,9 @@ import co.elastic.apm.agent.bci.methodmatching.TraceMethodInstrumentation; import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.configuration.CoreConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.util.DependencyInjectingServiceLoader; import co.elastic.apm.agent.util.ExecutorUtils; import co.elastic.apm.agent.util.ThreadUtils; @@ -84,7 +85,6 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import static co.elastic.apm.agent.bci.ElasticApmInstrumentation.tracer; import static co.elastic.apm.agent.bci.bytebuddy.ClassLoaderNameMatcher.classLoaderWithName; import static co.elastic.apm.agent.bci.bytebuddy.ClassLoaderNameMatcher.isReflectionClassLoader; import static co.elastic.apm.agent.bci.bytebuddy.CustomElementMatchers.anyMatch; @@ -174,7 +174,7 @@ public void run() { logger.warn("Instrumentation has already been initialized"); return; } - ElasticApmInstrumentation.staticInit(tracer); + GlobalTracer.set(tracer); // POOL_ONLY because we don't want to cause eager linking on startup as the class path may not be complete yet AgentBuilder agentBuilder = initAgentBuilder(tracer, instrumentation, instrumentations, logger, AgentBuilder.DescriptionStrategy.Default.POOL_ONLY, premain); resettableClassFileTransformer = agentBuilder.installOn(ElasticApmAgent.instrumentation); @@ -190,7 +190,7 @@ public void onChange(ConfigurationOption configurationOption, Object oldValue, O } public static synchronized Future reInitInstrumentation() { - final ElasticApmTracer tracer = ElasticApmInstrumentation.tracer; + final ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer == null || instrumentation == null) { throw new IllegalStateException("Can't re-init agent before it has been initialized"); } @@ -199,7 +199,7 @@ public static synchronized Future reInitInstrumentation() { return executor.submit(new Runnable() { @Override public void run() { - doReInitInstrumentation(loadInstrumentations(tracer)); + doReInitInstrumentation(loadInstrumentations(tracer), tracer); } }); } finally { @@ -207,7 +207,7 @@ public void run() { } } - static synchronized void doReInitInstrumentation(Iterable instrumentations) { + static synchronized void doReInitInstrumentation(Iterable instrumentations, ElasticApmTracer tracer) { final Logger logger = LoggerFactory.getLogger(ElasticApmAgent.class); logger.info("Re initializing instrumentation"); AgentBuilder agentBuilder = initAgentBuilder(tracer, instrumentation, instrumentations, logger, AgentBuilder.DescriptionStrategy.Default.POOL_ONLY, false); @@ -305,7 +305,7 @@ public boolean matches(TypeDescription typeDescription, ClassLoader classLoader, } }) .transform(new PatchBytecodeVersionTo51Transformer()) - .transform(getTransformer(tracer, instrumentation, logger, methodMatcher)) + .transform(getTransformer(instrumentation, logger, methodMatcher)) .transform(new AgentBuilder.Transformer() { @Override public DynamicType.Builder transform(DynamicType.Builder builder, TypeDescription typeDescription, @@ -315,7 +315,7 @@ public DynamicType.Builder transform(DynamicType.Builder builder, TypeDesc }); } - private static AgentBuilder.Transformer.ForAdvice getTransformer(final ElasticApmTracer tracer, final ElasticApmInstrumentation instrumentation, final Logger logger, final ElementMatcher methodMatcher) { + private static AgentBuilder.Transformer.ForAdvice getTransformer(final ElasticApmInstrumentation instrumentation, final Logger logger, final ElementMatcher methodMatcher) { Advice.WithCustomMapping withCustomMapping = Advice .withCustomMapping() .with(new AssignToPostProcessorFactory()) @@ -574,7 +574,7 @@ public static void ensureInstrumented(Class classToInstrument, Collection - *

- * The constructor can optionally have a {@link ElasticApmTracer} parameter. - *

*/ public abstract class ElasticApmInstrumentation { - - @Nullable - @VisibleForAdvice - public static ElasticApmTracer tracer; - - /** - * Initializes the advice with the {@link ElasticApmTracer} - *

- * This enables tests to register a custom instance with a {@link co.elastic.apm.agent.impl.ElasticApmTracerBuilder#configurationRegistry} - * and {@link co.elastic.apm.agent.impl.ElasticApmTracerBuilder#reporter} which is specific to a particular test or test class. - *

- * - * @param tracer the tracer to use for this advice. - */ - static void staticInit(ElasticApmTracer tracer) { - // allow re-init with a different tracer - ElasticApmInstrumentation.tracer = tracer; - } - - @Nullable - @VisibleForAdvice - public static AbstractSpan getActive() { - if (tracer != null) { - return tracer.getActive(); - } - return null; - } - - @Nullable - @VisibleForAdvice - public static Span getActiveSpan() { - if (tracer != null) { - final AbstractSpan active = tracer.getActive(); - if (active instanceof Span) { - return (Span) active; - } - } - return null; - } - - - @Nullable - @VisibleForAdvice - public static Span getActiveExitSpan() { - final Span span = getActiveSpan(); - if (span != null && span.isExit()) { - return span; - } - return null; - } - - @Nullable - @VisibleForAdvice - public static Span createExitSpan() { - final AbstractSpan activeSpan = getActive(); - if (activeSpan == null || activeSpan.isExit()) { - return null; - } - - return activeSpan.createExitSpan(); - } - /** * Pre-select candidates solely based on the class name for the slower {@link #getTypeMatcher()}, * at the expense of potential false negative matches. @@ -167,7 +100,6 @@ public Class getAdviceClass() { return getClass(); } - /** * Return {@code true}, * if this instrumentation should even be applied when @@ -218,8 +150,7 @@ public void onTypeMatch(TypeDescription typeDescription, ClassLoader classLoader *
  • * Both the return type and the arguments of advice methods must not contain types from the agent. * If you'd like to return a {@link Span} from an advice, for example, return an {@link Object} instead. - * When using an {@link net.bytebuddy.asm.Advice.Enter} argument on the - * {@linkplain net.bytebuddy.asm.Advice.OnMethodExit exit advice}, + * When using an {@link Advice.Enter} argument on the {@linkplain Advice.OnMethodExit exit advice}, * that argument also has to be of type {@link Object} and you have to cast it within the method body. * The reason is that the return value will become a local variable in the instrumented method. * Due to OSGi, those methods may not have access to agent types. diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/HelperClassManager.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/HelperClassManager.java index 8a43e02c56f..35e3848199e 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/HelperClassManager.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/HelperClassManager.java @@ -24,6 +24,7 @@ */ package co.elastic.apm.agent.bci; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap; import net.bytebuddy.description.type.TypeDescription; diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/MatcherTimerLifecycleListener.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/MatcherTimerLifecycleListener.java index d5f427c1784..9a3e995eafd 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/MatcherTimerLifecycleListener.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/MatcherTimerLifecycleListener.java @@ -26,7 +26,6 @@ import co.elastic.apm.agent.bci.bytebuddy.MatcherTimer; import co.elastic.apm.agent.context.AbstractLifecycleListener; -import co.elastic.apm.agent.impl.ElasticApmTracer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/TracerAwareElasticApmInstrumentation.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/TracerAwareElasticApmInstrumentation.java new file mode 100644 index 00000000000..eb158aa3927 --- /dev/null +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/TracerAwareElasticApmInstrumentation.java @@ -0,0 +1,39 @@ +/*- + * #%L + * Elastic APM Java agent + * %% + * Copyright (C) 2018 - 2020 Elastic and contributors + * %% + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * #L% + */ +package co.elastic.apm.agent.bci; + +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; +import co.elastic.apm.agent.impl.Tracer; + +/** + * The constructor can optionally have a {@link ElasticApmTracer} parameter. + */ +public abstract class TracerAwareElasticApmInstrumentation extends ElasticApmInstrumentation { + + @VisibleForAdvice + public static final Tracer tracer = GlobalTracer.get(); + +} diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/methodmatching/TraceMethodInstrumentation.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/methodmatching/TraceMethodInstrumentation.java index 9966711ea9e..67b6b45ea0a 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/methodmatching/TraceMethodInstrumentation.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/bci/methodmatching/TraceMethodInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.bci.methodmatching; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory; import co.elastic.apm.agent.configuration.CoreConfiguration; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -51,38 +51,37 @@ import static net.bytebuddy.matcher.ElementMatchers.isSynthetic; import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer; import static net.bytebuddy.matcher.ElementMatchers.nameContains; -import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; import static net.bytebuddy.matcher.ElementMatchers.not; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public class TraceMethodInstrumentation extends ElasticApmInstrumentation { +public class TraceMethodInstrumentation extends TracerAwareElasticApmInstrumentation { public static long traceMethodThresholdMicros; protected final MethodMatcher methodMatcher; + private final CoreConfiguration config; public TraceMethodInstrumentation(ElasticApmTracer tracer, MethodMatcher methodMatcher) { this.methodMatcher = methodMatcher; - traceMethodThresholdMicros = tracer.getConfig(CoreConfiguration.class).getTraceMethodsDurationThreshold().getMillis() * 1000; + config = tracer.getConfig(CoreConfiguration.class); + traceMethodThresholdMicros = config.getTraceMethodsDurationThreshold().getMillis() * 1000; } @Advice.OnMethodEnter(suppress = Throwable.class) public static void onMethodEnter(@Advice.Origin Class clazz, @SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature String signature, @Advice.Local("span") AbstractSpan span) { - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent == null) { - span = tracer.startRootTransaction(clazz.getClassLoader()); - if (span != null) { - span.withName(signature).activate(); - } - } else if (parent.isSampled()) { - span = parent.createSpan() - .withName(signature) - .activate(); + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { + span = tracer.startRootTransaction(clazz.getClassLoader()); + if (span != null) { + span.withName(signature).activate(); } + } else if (parent.isSampled()) { + span = parent.createSpan() + .withName(signature) + .activate(); } } @@ -118,9 +117,8 @@ public ElementMatcher getTypeMatcher() { public ElementMatcher getMethodMatcher() { ElementMatcher.Junction matcher = matches(methodMatcher.getMethodMatcher()); - final List methodsExcludedFromInstrumentation = - (tracer != null)? tracer.getConfig(CoreConfiguration.class).getMethodsExcludedFromInstrumentation(): null; - if (methodsExcludedFromInstrumentation != null && !methodsExcludedFromInstrumentation.isEmpty()) { + final List methodsExcludedFromInstrumentation = config.getMethodsExcludedFromInstrumentation(); + if (!methodsExcludedFromInstrumentation.isEmpty()) { matcher = matcher.and(not(new ElementMatcher() { @Override public boolean matches(MethodDescription target) { diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/context/LifecycleListener.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/context/LifecycleListener.java index ebf7ae32bc9..48a967928ad 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/context/LifecycleListener.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/context/LifecycleListener.java @@ -26,8 +26,6 @@ import co.elastic.apm.agent.impl.ElasticApmTracer; -import java.io.Closeable; - /** * A {@link LifecycleListener} notifies about the start and stop event of the {@link ElasticApmTracer}. *

    diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/ElasticApmTracer.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/ElasticApmTracer.java index 3f96b01397e..68f49cd2d03 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/ElasticApmTracer.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/ElasticApmTracer.java @@ -34,7 +34,6 @@ import co.elastic.apm.agent.impl.stacktrace.StacktraceConfiguration; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.BinaryHeaderGetter; -import co.elastic.apm.agent.impl.transaction.HeaderGetter; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.impl.transaction.TextHeaderGetter; import co.elastic.apm.agent.impl.transaction.TraceContext; @@ -69,7 +68,7 @@ * Note that this is a internal API, so there are no guarantees in terms of backwards compatibility. *

    */ -public class ElasticApmTracer { +public class ElasticApmTracer implements Tracer { private static final Logger logger = LoggerFactory.getLogger(ElasticApmTracer.class); private static final WeakConcurrentMap serviceNameByClassLoader = WeakMapSupplier.createMap(); @@ -151,28 +150,13 @@ public void onChange(ConfigurationOption configurationOption, Double oldValue assert assertionsEnabled = true; } - /** - * Starts a trace-root transaction - * - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name. - * @return a transaction that will be the root of the current trace if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startRootTransaction(@Nullable ClassLoader initiatingClassLoader) { return startRootTransaction(sampler, -1, initiatingClassLoader); } - /** - * Starts a trace-root transaction with a specified sampler and start timestamp - * - * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction - * @param epochMicros the start timestamp - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, - * for log correlation. - * @return a transaction that will be the root of the current trace if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startRootTransaction(Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { Transaction transaction = null; @@ -183,36 +167,13 @@ public Transaction startRootTransaction(Sampler sampler, long epochMicros, @Null return transaction; } - /** - * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. - * If the created transaction cannot be started as a child transaction (for example - if no parent context header is - * available), then it will be started as the root transaction of the trace. - * - * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message - * @param textHeadersGetter provides the trace context headers required in order to create a child transaction - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name. - * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { return startChildTransaction(headerCarrier, textHeadersGetter, sampler, -1, initiatingClassLoader); } - /** - * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. - * If the created transaction cannot be started as a child transaction (for example - if no parent context header is - * available), then it will be started as the root transaction of the trace. - * - * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message - * @param textHeadersGetter provides the trace context headers required in order to create a child transaction - * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction - * @param epochMicros the start timestamp - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, - * for log correlation. - * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { @@ -225,36 +186,13 @@ public Transaction startChildTransaction(@Nullable C headerCarrier, TextHead return transaction; } - /** - * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. - * If the created transaction cannot be started as a child transaction (for example - if no parent context header is - * available), then it will be started as the root transaction of the trace. - * - * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message - * @param binaryHeadersGetter provides the trace context headers required in order to create a child transaction - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name. - * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { return startChildTransaction(headerCarrier, binaryHeadersGetter, sampler, -1, initiatingClassLoader); } - /** - * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. - * If the created transaction cannot be started as a child transaction (for example - if no parent context header is - * available), then it will be started as the root transaction of the trace. - * - * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message - * @param binaryHeadersGetter provides the trace context headers required in order to create a child transaction - * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction - * @param epochMicros the start timestamp - * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. - * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, - * for log correlation. - * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise - */ + @Override @Nullable public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { @@ -294,6 +232,7 @@ private Transaction createTransaction() { return transaction; } + @Override @Nullable public Transaction currentTransaction() { final AbstractSpan bottomOfStack = activeStack.get().peekLast(); @@ -336,12 +275,7 @@ private Span createSpan() { return span; } - /** - * Captures an exception without providing an explicit reference to a parent {@link AbstractSpan} - * - * @param e the exception to capture - * @param initiatingClassLoader the class - */ + @Override public void captureAndReportException(@Nullable Throwable e, ClassLoader initiatingClassLoader) { ErrorCapture errorCapture = captureException(System.currentTimeMillis() * 1000, e, getActive(), initiatingClassLoader); if (errorCapture != null) { @@ -349,6 +283,7 @@ public void captureAndReportException(@Nullable Throwable e, ClassLoader initiat } } + @Override @Nullable public String captureAndReportException(long epochMicros, @Nullable Throwable e, @Nullable AbstractSpan parent) { String id = null; @@ -360,6 +295,7 @@ public String captureAndReportException(long epochMicros, @Nullable Throwable e, return id; } + @Override @Nullable public ErrorCapture captureException(@Nullable Throwable e, @Nullable AbstractSpan parent, @Nullable ClassLoader initiatingClassLoader) { return captureException(System.currentTimeMillis() * 1000, e, parent, initiatingClassLoader); @@ -474,10 +410,6 @@ public void recycle(ErrorCapture error) { errorPool.recycle(error); } - /** - * Called when the container shuts down. - * Cleans up thread pools and other resources. - */ public synchronized void stop() { tracerState = TracerState.STOPPED; logger.info("Tracer switched to STOPPED state"); @@ -509,11 +441,32 @@ public ObjectPoolFactory getObjectPoolFactory() { return objectPoolFactory; } + @Override @Nullable public AbstractSpan getActive() { return activeStack.get().peek(); } + @Nullable + @Override + public Span getActiveSpan() { + final AbstractSpan active = getActive(); + if (active instanceof Span) { + return (Span) active; + } + return null; + } + + @Nullable + @Override + public Span getActiveExitSpan() { + final Span span = getActiveSpan(); + if (span != null && span.isExit()) { + return span; + } + return null; + } + public void registerSpanListener(ActivationListener activationListener) { this.activationListeners.add(activationListener); } @@ -649,10 +602,12 @@ synchronized void resume() { logger.info("Tracer switched to RUNNING state"); } + @Override public boolean isRunning() { return tracerState == TracerState.RUNNING; } + @Override public TracerState getState() { return tracerState; } @@ -723,16 +678,7 @@ public MetricRegistry getMetricRegistry() { return metricRegistry; } - /** - * Overrides the service name for all {@link Transaction}s, - * {@link Span}s and {@link ErrorCapture}s which are created by the service which corresponds to the provided {@link ClassLoader}. - *

    - * The main use case is being able to differentiate between multiple services deployed to the same application server. - *

    - * - * @param classLoader the class loader which corresponds to a particular service - * @param serviceName the service name for this class loader - */ + @Override public void overrideServiceNameForClassLoader(@Nullable ClassLoader classLoader, @Nullable String serviceName) { // overriding the service name for the bootstrap class loader is not an actual use-case // null may also mean we don't know about the initiating class loader @@ -767,31 +713,4 @@ public MetaData getMetaData() { return metaData; } - /** - * An enumeration used to represent the current tracer state. - */ - public enum TracerState { - /** - * The agent's state before it has been started for the first time. - */ - UNINITIALIZED, - - /** - * Indicates that the agent is currently fully functional - tracing, monitoring and sending data to the APM server. - */ - RUNNING, - - /** - * The agent is mostly idle, consuming minimal resources, ready to quickly resume back to RUNNING. When the agent - * is PAUSED, it is not tracing and not communicating with the APM server. However, classes are still instrumented - * and threads are still alive. - */ - PAUSED, - - /** - * Indicates that the agent had been stopped. - * NOTE: this state is irreversible- the agent cannot resume if it has already been stopped. - */ - STOPPED - } } diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/GlobalTracer.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/GlobalTracer.java new file mode 100644 index 00000000000..be2b8729133 --- /dev/null +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/GlobalTracer.java @@ -0,0 +1,166 @@ +/*- + * #%L + * Elastic APM Java agent + * %% + * Copyright (C) 2018 - 2020 Elastic and contributors + * %% + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * #L% + */ +package co.elastic.apm.agent.impl; + +import co.elastic.apm.agent.impl.error.ErrorCapture; +import co.elastic.apm.agent.impl.sampling.Sampler; +import co.elastic.apm.agent.impl.transaction.AbstractSpan; +import co.elastic.apm.agent.impl.transaction.BinaryHeaderGetter; +import co.elastic.apm.agent.impl.transaction.Span; +import co.elastic.apm.agent.impl.transaction.TextHeaderGetter; +import co.elastic.apm.agent.impl.transaction.Transaction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.util.Objects; + +public class GlobalTracer implements Tracer { + + private static final Logger logger = LoggerFactory.getLogger(GlobalTracer.class); + + private static final GlobalTracer INSTANCE = new GlobalTracer(); + private volatile Tracer tracer = NoopTracer.INSTANCE; + + private GlobalTracer() { + } + + public static Tracer get() { + return INSTANCE; + } + + @Nullable + public static ElasticApmTracer getTracerImpl() { + Tracer tracer = INSTANCE.tracer; + if (tracer instanceof ElasticApmTracer) { + return ((ElasticApmTracer) tracer); + } + return null; + } + + public static ElasticApmTracer requireTracerImpl() { + return Objects.requireNonNull(getTracerImpl()); + } + + public static void setNoop() { + set(NoopTracer.INSTANCE); + } + + public static void set(Tracer tracer) { + TracerState currentTracerState = INSTANCE.tracer.getState(); + if (currentTracerState != TracerState.UNINITIALIZED && currentTracerState != TracerState.STOPPED) { + logger.warn("Overriding running tracer"); + //throw new IllegalStateException("Can't override tracer as current tracer is already running"); + } + INSTANCE.tracer = tracer; + } + + @Nullable + public Transaction startRootTransaction(@Nullable ClassLoader initiatingClassLoader) { + return tracer.startRootTransaction(initiatingClassLoader); + } + + @Nullable + public Transaction startRootTransaction(Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return tracer.startRootTransaction(sampler, epochMicros, initiatingClassLoader); + } + + @Nullable + public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { + return tracer.startChildTransaction(headerCarrier, textHeadersGetter, initiatingClassLoader); + } + + @Nullable + public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return tracer.startChildTransaction(headerCarrier, textHeadersGetter, sampler, epochMicros, initiatingClassLoader); + } + + @Nullable + public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { + return tracer.startChildTransaction(headerCarrier, binaryHeadersGetter, initiatingClassLoader); + } + + @Nullable + public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return tracer.startChildTransaction(headerCarrier, binaryHeadersGetter, sampler, epochMicros, initiatingClassLoader); + } + + @Nullable + public Transaction currentTransaction() { + return tracer.currentTransaction(); + } + + @Nullable + @Override + public AbstractSpan getActive() { + return tracer.getActive(); + } + + @Nullable + @Override + public Span getActiveSpan() { + return tracer.getActiveSpan(); + } + + public void captureAndReportException(@Nullable Throwable e, ClassLoader initiatingClassLoader) { + tracer.captureAndReportException(e, initiatingClassLoader); + } + + @Nullable + public String captureAndReportException(long epochMicros, @Nullable Throwable e, @Nullable AbstractSpan parent) { + return tracer.captureAndReportException(epochMicros, e, parent); + } + + @Nullable + public ErrorCapture captureException(@Nullable Throwable e, @Nullable AbstractSpan parent, @Nullable ClassLoader initiatingClassLoader) { + return tracer.captureException(e, parent, initiatingClassLoader); + } + + @Nullable + @Override + public Span getActiveExitSpan() { + return tracer.getActiveExitSpan(); + } + + @Override + public TracerState getState() { + return tracer.getState(); + } + + @Override + public void overrideServiceNameForClassLoader(@Nullable ClassLoader classLoader, @Nullable String serviceName) { + tracer.overrideServiceNameForClassLoader(classLoader, serviceName); + } + + @Override + public void stop() { + tracer.stop(); + } + + @Override + public boolean isRunning() { + return tracer.isRunning(); + } +} diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/NoopTracer.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/NoopTracer.java new file mode 100644 index 00000000000..fecb117d8bd --- /dev/null +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/NoopTracer.java @@ -0,0 +1,138 @@ +/*- + * #%L + * Elastic APM Java agent + * %% + * Copyright (C) 2018 - 2020 Elastic and contributors + * %% + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * #L% + */ +package co.elastic.apm.agent.impl; + +import co.elastic.apm.agent.impl.error.ErrorCapture; +import co.elastic.apm.agent.impl.sampling.Sampler; +import co.elastic.apm.agent.impl.transaction.AbstractSpan; +import co.elastic.apm.agent.impl.transaction.BinaryHeaderGetter; +import co.elastic.apm.agent.impl.transaction.Span; +import co.elastic.apm.agent.impl.transaction.TextHeaderGetter; +import co.elastic.apm.agent.impl.transaction.Transaction; + +import javax.annotation.Nullable; + +class NoopTracer implements Tracer { + + static final Tracer INSTANCE = new NoopTracer(); + + private NoopTracer() { + } + + @Nullable + @Override + public Transaction startRootTransaction(@Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction startRootTransaction(Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Transaction currentTransaction() { + return null; + } + + @Nullable + @Override + public AbstractSpan getActive() { + return null; + } + + @Nullable + @Override + public Span getActiveSpan() { + return null; + } + + @Override + public void captureAndReportException(@Nullable Throwable e, ClassLoader initiatingClassLoader) { + + } + + @Nullable + @Override + public String captureAndReportException(long epochMicros, @Nullable Throwable e, @Nullable AbstractSpan parent) { + return null; + } + + @Nullable + @Override + public ErrorCapture captureException(@Nullable Throwable e, @Nullable AbstractSpan parent, @Nullable ClassLoader initiatingClassLoader) { + return null; + } + + @Nullable + @Override + public Span getActiveExitSpan() { + return null; + } + + @Override + public TracerState getState() { + return TracerState.UNINITIALIZED; + } + + @Override + public void overrideServiceNameForClassLoader(@Nullable ClassLoader classLoader, @Nullable String serviceName) { + } + + @Override + public void stop() { + } + + @Override + public boolean isRunning() { + return false; + } +} diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/Tracer.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/Tracer.java new file mode 100644 index 00000000000..2824cfae1de --- /dev/null +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/Tracer.java @@ -0,0 +1,202 @@ +/*- + * #%L + * Elastic APM Java agent + * %% + * Copyright (C) 2018 - 2020 Elastic and contributors + * %% + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * #L% + */ +package co.elastic.apm.agent.impl; + +import co.elastic.apm.agent.impl.error.ErrorCapture; +import co.elastic.apm.agent.impl.sampling.Sampler; +import co.elastic.apm.agent.impl.transaction.AbstractSpan; +import co.elastic.apm.agent.impl.transaction.BinaryHeaderGetter; +import co.elastic.apm.agent.impl.transaction.HeaderGetter; +import co.elastic.apm.agent.impl.transaction.Span; +import co.elastic.apm.agent.impl.transaction.TextHeaderGetter; +import co.elastic.apm.agent.impl.transaction.Transaction; + +import javax.annotation.Nullable; + +public interface Tracer { + + /** + * Starts a trace-root transaction + * + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name. + * @return a transaction that will be the root of the current trace if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startRootTransaction(@Nullable ClassLoader initiatingClassLoader); + + /** + * Starts a trace-root transaction with a specified sampler and start timestamp + * + * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction + * @param epochMicros the start timestamp + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, + * for log correlation. + * @return a transaction that will be the root of the current trace if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startRootTransaction(Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader); + + /** + * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. + * If the created transaction cannot be started as a child transaction (for example - if no parent context header is + * available), then it will be started as the root transaction of the trace. + * + * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message + * @param textHeadersGetter provides the trace context headers required in order to create a child transaction + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name. + * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, @Nullable ClassLoader initiatingClassLoader); + + /** + * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. + * If the created transaction cannot be started as a child transaction (for example - if no parent context header is + * available), then it will be started as the root transaction of the trace. + * + * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message + * @param textHeadersGetter provides the trace context headers required in order to create a child transaction + * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction + * @param epochMicros the start timestamp + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, + * for log correlation. + * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startChildTransaction(@Nullable C headerCarrier, TextHeaderGetter textHeadersGetter, Sampler sampler, + long epochMicros, @Nullable ClassLoader initiatingClassLoader); + + /** + * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. + * If the created transaction cannot be started as a child transaction (for example - if no parent context header is + * available), then it will be started as the root transaction of the trace. + * + * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message + * @param binaryHeadersGetter provides the trace context headers required in order to create a child transaction + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name. + * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, @Nullable ClassLoader initiatingClassLoader); + + /** + * Starts a transaction as a child of the context headers obtained through the provided {@link HeaderGetter}. + * If the created transaction cannot be started as a child transaction (for example - if no parent context header is + * available), then it will be started as the root transaction of the trace. + * + * @param headerCarrier the Object from which context headers can be obtained, typically a request or a message + * @param binaryHeadersGetter provides the trace context headers required in order to create a child transaction + * @param sampler the {@link Sampler} instance which is responsible for determining the sampling decision if this is a root transaction + * @param epochMicros the start timestamp + * @param initiatingClassLoader the class loader corresponding to the service which initiated the creation of the transaction. + * Used to determine the service name and to load application-scoped classes like the {@link org.slf4j.MDC}, + * for log correlation. + * @return a transaction which is a child of the provided parent if the agent is currently RUNNING; null otherwise + */ + @Nullable + Transaction startChildTransaction(@Nullable C headerCarrier, BinaryHeaderGetter binaryHeadersGetter, + Sampler sampler, long epochMicros, @Nullable ClassLoader initiatingClassLoader); + + @Nullable + Transaction currentTransaction(); + + @Nullable + AbstractSpan getActive(); + + @Nullable + Span getActiveSpan(); + + /** + * Captures an exception without providing an explicit reference to a parent {@link AbstractSpan} + * + * @param e the exception to capture + * @param initiatingClassLoader the class + */ + void captureAndReportException(@Nullable Throwable e, ClassLoader initiatingClassLoader); + + @Nullable + String captureAndReportException(long epochMicros, @Nullable Throwable e, @Nullable AbstractSpan parent); + + @Nullable + ErrorCapture captureException(@Nullable Throwable e, @Nullable AbstractSpan parent, @Nullable ClassLoader initiatingClassLoader); + + @Nullable + Span getActiveExitSpan(); + + ElasticApmTracer.TracerState getState(); + + /** + * Overrides the service name for all {@link Transaction}s, + * {@link Span}s and {@link ErrorCapture}s which are created by the service which corresponds to the provided {@link ClassLoader}. + *

    + * The main use case is being able to differentiate between multiple services deployed to the same application server. + *

    + * + * @param classLoader the class loader which corresponds to a particular service + * @param serviceName the service name for this class loader + */ + void overrideServiceNameForClassLoader(@Nullable ClassLoader classLoader, @Nullable String serviceName); + + /** + * Called when the container shuts down. + * Cleans up thread pools and other resources. + */ + void stop(); + + boolean isRunning(); + + /** + * An enumeration used to represent the current tracer state. + */ + enum TracerState { + /** + * The agent's state before it has been started for the first time. + */ + UNINITIALIZED, + + /** + * Indicates that the agent is currently fully functional - tracing, monitoring and sending data to the APM server. + */ + RUNNING, + + /** + * The agent is mostly idle, consuming minimal resources, ready to quickly resume back to RUNNING. When the agent + * is PAUSED, it is not tracing and not communicating with the APM server. However, classes are still instrumented + * and threads are still alive. + */ + PAUSED, + + /** + * Indicates that the agent had been stopped. + * NOTE: this state is irreversible- the agent cannot resume if it has already been stopped. + */ + STOPPED + } +} diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/transaction/TraceContext.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/transaction/TraceContext.java index 52a43714663..997e8a8fc33 100644 --- a/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/transaction/TraceContext.java +++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/impl/transaction/TraceContext.java @@ -26,6 +26,7 @@ import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.configuration.CoreConfiguration; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.sampling.Sampler; import co.elastic.apm.agent.objectpool.Recyclable; @@ -170,9 +171,9 @@ public boolean asChildOf(TraceContext child, @Nullable Object carrier, BinaryHea return false; } }; - private static final ChildContextCreator FROM_ACTIVE = new ChildContextCreator() { + private static final ChildContextCreator FROM_ACTIVE = new ChildContextCreator() { @Override - public boolean asChildOf(TraceContext child, ElasticApmTracer tracer) { + public boolean asChildOf(TraceContext child, Tracer tracer) { final AbstractSpan active = tracer.getActive(); if (active != null) { return fromParent().asChildOf(child, active); @@ -281,7 +282,7 @@ public static ChildContextCreatorTwoArg> getFromTra return (ChildContextCreatorTwoArg>) FROM_TRACE_CONTEXT_BINARY_HEADERS; } - public static ChildContextCreator fromActive() { + public static ChildContextCreator fromActive() { return FROM_ACTIVE; } diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/AbstractInstrumentationTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/AbstractInstrumentationTest.java index 1dfa92caf0b..b81e3133589 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/AbstractInstrumentationTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/AbstractInstrumentationTest.java @@ -26,6 +26,7 @@ import co.elastic.apm.agent.bci.ElasticApmAgent; import co.elastic.apm.agent.configuration.SpyConfiguration; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.TracerInternalApiUtils; import co.elastic.apm.agent.objectpool.TestObjectPoolFactory; @@ -77,7 +78,7 @@ public static synchronized void staticReset() { } } - public static ElasticApmTracer getTracer() { + public static Tracer getTracer() { return tracer; } diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/MockTracer.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/MockTracer.java index 363ae8e1a2d..63cb20b7f44 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/MockTracer.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/MockTracer.java @@ -25,11 +25,12 @@ package co.elastic.apm.agent; import co.elastic.apm.agent.bci.ElasticApmAgent; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.configuration.SpyConfiguration; import co.elastic.apm.agent.context.ClosableLifecycleListenerAdapter; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.TracerInternalApiUtils; import co.elastic.apm.agent.objectpool.TestObjectPoolFactory; import co.elastic.apm.agent.report.Reporter; @@ -89,14 +90,14 @@ public static ElasticApmTracer createRealTracer(Reporter reporter, Configuration /** * If an instrumentation has already been initialized by some other test, returns the static - * {@link co.elastic.apm.agent.bci.ElasticApmInstrumentation#tracer}. + * {@link GlobalTracer#getTracerImpl()}. * Otherwise, Creates a real tracer with a {@link MockReporter} and a mock configuration which returns default * values that can be customized by mocking the configuration. */ public static synchronized MockInstrumentationSetup getOrCreateInstrumentationTracer() { - ElasticApmTracer tracer = ElasticApmInstrumentation.tracer; - if (tracer == null || tracer.getState() == ElasticApmTracer.TracerState.STOPPED || + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); + if (tracer == null || tracer.getState() == Tracer.TracerState.STOPPED || !(tracer.getReporter() instanceof MockReporter) || !(tracer.getObjectPoolFactory() instanceof TestObjectPoolFactory)) { // use an object pool that does bookkeeping to allow for extra usage checks @@ -133,11 +134,10 @@ public static synchronized MockInstrumentationSetup getOrCreateInstrumentationTr } public static synchronized void resetTracer() { - ElasticApmTracer tracer = ElasticApmInstrumentation.tracer; + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer != null) { ElasticApmAgent.reset(); tracer.stop(); - ElasticApmInstrumentation.tracer = null; } } diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/InstrumentationTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/InstrumentationTest.java index 686340b1641..cda78deadcf 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/InstrumentationTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/InstrumentationTest.java @@ -29,8 +29,9 @@ import co.elastic.apm.agent.bci.subpackage.AdviceInSubpackageInstrumentation; import co.elastic.apm.agent.configuration.CoreConfiguration; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.matcher.WildcardMatcher; @@ -80,9 +81,9 @@ class InstrumentationTest { @BeforeEach void setup() { - tracer = MockTracer.create(); configurationRegistry = SpyConfiguration.createSpyConfig(); coreConfig = configurationRegistry.getConfig(CoreConfiguration.class); + tracer = MockTracer.create(configurationRegistry); } @AfterEach @@ -166,7 +167,7 @@ void testReInitEnableOneInstrumentation() { assertThat(interceptMe()).isEmpty(); doReturn(List.of()).when(coreConfig).getDisabledInstrumentations(); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEqualTo("intercepted"); } @@ -176,7 +177,7 @@ void testDefaultDisabledInstrumentation() { assertThat(interceptMe()).isEqualTo("intercepted"); doReturn(Collections.singletonList("experimental")).when(coreConfig).getDisabledInstrumentations(); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -185,7 +186,7 @@ void testExcludedClassesFromInstrumentation() { doReturn(List.of(WildcardMatcher.valueOf("co.elastic.apm.agent.bci.InstrumentationTest"))) .when(coreConfig).getClassesExcludedFromInstrumentation(); init(configurationRegistry, List.of(new TestInstrumentation())); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -194,7 +195,7 @@ void testExcludedPackageFromInstrumentation() { doReturn(List.of(WildcardMatcher.valueOf("co.elastic.apm.agent.bci.*"))) .when(coreConfig).getClassesExcludedFromInstrumentation(); init(configurationRegistry, List.of(new TestInstrumentation())); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -203,7 +204,7 @@ void testExcludedDefaultClassesFromInstrumentation() { doReturn(List.of(WildcardMatcher.valueOf("co.elastic.apm.agent.bci.InstrumentationTest"))) .when(coreConfig).getDefaultClassesExcludedFromInstrumentation(); init(configurationRegistry, List.of(new TestInstrumentation())); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -212,7 +213,7 @@ void testExcludedDefaultPackageFromInstrumentation() { doReturn(List.of(WildcardMatcher.valueOf("co.elastic.apm.agent.bci.*"))) .when(coreConfig).getDefaultClassesExcludedFromInstrumentation(); init(configurationRegistry, List.of(new TestInstrumentation())); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -222,7 +223,7 @@ void testLegacyDefaultDisabledInstrumentation() { assertThat(interceptMe()).isEqualTo("intercepted"); doReturn(Collections.singletonList("incubating")).when(coreConfig).getDisabledInstrumentations(); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -232,7 +233,7 @@ void testReInitDisableAllInstrumentations() { assertThat(interceptMe()).isEqualTo("intercepted"); doReturn(false).when(coreConfig).isInstrument(); - ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation())); + ElasticApmAgent.doReInitInstrumentation(List.of(new TestInstrumentation()), tracer); assertThat(interceptMe()).isEmpty(); } @@ -945,7 +946,7 @@ public boolean indyPlugin() { } } - public static class UsingThreadLocal extends ElasticApmInstrumentation { + public static class UsingThreadLocal extends TracerAwareElasticApmInstrumentation { private static final ThreadLocal> localSpan = new ThreadLocal<>() { @Override diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/methodmatching/MethodMatcherInstrumentationTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/methodmatching/MethodMatcherInstrumentationTest.java index 1ff4b56bfae..436054b7100 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/methodmatching/MethodMatcherInstrumentationTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/bci/methodmatching/MethodMatcherInstrumentationTest.java @@ -26,8 +26,8 @@ import co.elastic.apm.agent.MockReporter; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import org.junit.jupiter.api.BeforeAll; diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/LifecycleTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/LifecycleTest.java index 4730418432e..6f92e2c387c 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/LifecycleTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/LifecycleTest.java @@ -40,9 +40,9 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import static co.elastic.apm.agent.impl.ElasticApmTracer.TracerState.PAUSED; -import static co.elastic.apm.agent.impl.ElasticApmTracer.TracerState.RUNNING; -import static co.elastic.apm.agent.impl.ElasticApmTracer.TracerState.STOPPED; +import static co.elastic.apm.agent.impl.Tracer.TracerState.PAUSED; +import static co.elastic.apm.agent.impl.Tracer.TracerState.RUNNING; +import static co.elastic.apm.agent.impl.Tracer.TracerState.STOPPED; import static org.assertj.core.api.Assertions.assertThat; public class LifecycleTest { diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/CircuitBreakerTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/CircuitBreakerTest.java index 877d0d6c060..2761d40af6a 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/CircuitBreakerTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/CircuitBreakerTest.java @@ -26,8 +26,8 @@ import co.elastic.apm.agent.MockReporter; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.TracerInternalApiUtils; import org.awaitility.core.ConditionFactory; import org.awaitility.core.ThrowingRunnable; @@ -43,8 +43,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import static co.elastic.apm.agent.impl.ElasticApmTracer.TracerState.PAUSED; -import static co.elastic.apm.agent.impl.ElasticApmTracer.TracerState.RUNNING; +import static co.elastic.apm.agent.impl.Tracer.TracerState.PAUSED; +import static co.elastic.apm.agent.impl.Tracer.TracerState.RUNNING; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.doReturn; diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/SystemCpuStressMonitorTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/SystemCpuStressMonitorTest.java index c1dd63678a0..c14097377b5 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/SystemCpuStressMonitorTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/circuitbreaker/SystemCpuStressMonitorTest.java @@ -26,8 +26,8 @@ import co.elastic.apm.agent.MockReporter; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/context/SanitizingWebProcessorTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/context/SanitizingWebProcessorTest.java index e9e579600bd..4942a59a7c0 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/context/SanitizingWebProcessorTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/context/SanitizingWebProcessorTest.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/SpanTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/SpanTest.java index b898550a1ef..3cce3528c91 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/SpanTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/SpanTest.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -25,11 +25,9 @@ package co.elastic.apm.agent.impl.transaction; import co.elastic.apm.agent.MockTracer; -import co.elastic.apm.agent.impl.ElasticApmTracer; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; class SpanTest { diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextTest.java index f1b98a54110..6446bb387f7 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextTest.java @@ -28,8 +28,8 @@ import co.elastic.apm.agent.configuration.CoreConfiguration; import co.elastic.apm.agent.configuration.SpyConfiguration; import co.elastic.apm.agent.impl.BinaryHeaderMapAccessor; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.MultiValueMapAccessor; import co.elastic.apm.agent.impl.TextHeaderMapAccessor; import co.elastic.apm.agent.impl.sampling.ConstantSampler; diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextW3CTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextW3CTest.java index 25671800538..a1d6b38bae5 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextW3CTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/impl/transaction/TraceContextW3CTest.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/report/ApmServerClientTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/report/ApmServerClientTest.java index 5268512e627..66ccb4cd651 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/report/ApmServerClientTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/report/ApmServerClientTest.java @@ -25,8 +25,8 @@ package co.elastic.apm.agent.report; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.util.Version; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; diff --git a/apm-agent-core/src/test/java/co/elastic/apm/agent/report/serialize/DslJsonSerializerTest.java b/apm-agent-core/src/test/java/co/elastic/apm/agent/report/serialize/DslJsonSerializerTest.java index 3b0f1fbdbaf..a9a0f00bea7 100644 --- a/apm-agent-core/src/test/java/co/elastic/apm/agent/report/serialize/DslJsonSerializerTest.java +++ b/apm-agent-core/src/test/java/co/elastic/apm/agent/report/serialize/DslJsonSerializerTest.java @@ -29,6 +29,7 @@ import co.elastic.apm.agent.collections.LongList; import co.elastic.apm.agent.configuration.CoreConfiguration; import co.elastic.apm.agent.configuration.SpyConfiguration; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.MetaData; import co.elastic.apm.agent.impl.context.AbstractContext; @@ -140,7 +141,7 @@ void testErrorSerialization() { @Test void testErrorSerializationOutsideTrace() { MockReporter reporter = new MockReporter(); - ElasticApmTracer tracer = MockTracer.createRealTracer(reporter); + Tracer tracer = MockTracer.createRealTracer(reporter); tracer.captureAndReportException(new Exception("test"), getClass().getClassLoader()); String errorJson = serializer.toJsonString(reporter.getFirstError()); @@ -161,7 +162,7 @@ void testErrorSerializationOutsideTrace() { void testErrorSerializationWithExceptionCause() throws JsonProcessingException { // testing outside trace is enough to test exception serialization logic MockReporter reporter = new MockReporter(); - ElasticApmTracer tracer = MockTracer.createRealTracer(reporter); + Tracer tracer = MockTracer.createRealTracer(reporter); Exception cause2 = new IllegalStateException("second cause"); Exception cause1 = new RuntimeException("first cause", cause2); diff --git a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientInstrumentation.java b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientInstrumentation.java index abb4a2ab1f6..dfb3b207c5d 100644 --- a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientInstrumentation.java +++ b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientInstrumentation.java @@ -111,10 +111,10 @@ public static class ApacheHttpAsyncClientAdvice { public static Object[] onBeforeExecute(@Advice.Argument(value = 0) HttpAsyncRequestProducer requestProducer, @Advice.Argument(2) HttpContext context, @Advice.Argument(value = 3) FutureCallback futureCallback) { - if (tracer == null || tracer.getActive() == null) { + AbstractSpan parent = tracer.getActive(); + if (parent == null) { return null; } - final AbstractSpan parent = tracer.getActive(); Span span = parent.createExitSpan(); HttpAsyncRequestProducer wrappedProducer = requestProducer; FutureCallback wrappedFutureCallback = futureCallback; diff --git a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientRedirectInstrumentation.java b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientRedirectInstrumentation.java index 74ecdc3d6a4..469bfc504d4 100644 --- a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientRedirectInstrumentation.java +++ b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpAsyncClientRedirectInstrumentation.java @@ -57,7 +57,7 @@ private static class ApacheHttpAsyncClientRedirectAdvice { @Advice.OnMethodExit(suppress = Throwable.class) private static void onAfterExecute(@Advice.Argument(value = 0) HttpRequest original, @Advice.Return(typing = Assigner.Typing.DYNAMIC) @Nullable HttpRequest redirect) { - if (tracer == null || redirect == null) { + if (redirect == null) { return; } // org.apache.http.HttpMessage#containsHeader implementations do not allocate iterator since 4.0.1 diff --git a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpClientInstrumentation.java b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpClientInstrumentation.java index c9f61cf5ca4..988d801261b 100644 --- a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/ApacheHttpClientInstrumentation.java @@ -65,10 +65,10 @@ private static class ApacheHttpClientAdvice { private static void onBeforeExecute(@Advice.Argument(0) HttpRoute route, @Advice.Argument(1) HttpRequestWrapper request, @Advice.Local("span") Span span) { - if (tracer == null || tracer.getActive() == null) { + AbstractSpan parent = tracer.getActive(); + if (parent == null) { return; } - final AbstractSpan parent = tracer.getActive(); span = HttpClientHelper.startHttpClientSpan(parent, request.getMethod(), request.getURI(), route.getTargetHost().getHostName()); TextHeaderSetter headerSetter = headerSetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class); TextHeaderGetter headerGetter = headerGetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class); @@ -77,8 +77,7 @@ private static void onBeforeExecute(@Advice.Argument(0) HttpRoute route, if (headerSetter != null) { span.propagateTraceContext(request, headerSetter); } - } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter) - && headerSetter != null && parent != null) { + } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter) && headerSetter != null) { // re-adds the header on redirects parent.propagateTraceContext(request, headerSetter); } diff --git a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/BaseApacheHttpClientInstrumentation.java b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/BaseApacheHttpClientInstrumentation.java index 0b2463ef8e8..67b9bed458e 100644 --- a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/BaseApacheHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/BaseApacheHttpClientInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.httpclient; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.transaction.TextHeaderGetter; @@ -36,7 +36,7 @@ import java.util.Arrays; import java.util.Collection; -public abstract class BaseApacheHttpClientInstrumentation extends ElasticApmInstrumentation { +public abstract class BaseApacheHttpClientInstrumentation extends TracerAwareElasticApmInstrumentation { // Referencing specific Apache HTTP client classes are allowed due to type erasure @VisibleForAdvice diff --git a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/LegacyApacheHttpClientInstrumentation.java b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/LegacyApacheHttpClientInstrumentation.java index 503dc15a6c1..fc9340accdd 100644 --- a/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/LegacyApacheHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-apache-httpclient-plugin/src/main/java/co/elastic/apm/agent/httpclient/LegacyApacheHttpClientInstrumentation.java @@ -62,10 +62,10 @@ private static class LegacyApacheHttpClientAdvice { private static void onBeforeExecute(@Advice.Argument(0) HttpHost host, @Advice.Argument(1) HttpRequest request, @Advice.Local("span") Span span) { - if (tracer == null || tracer.getActive() == null) { + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { return; } - final AbstractSpan parent = tracer.getActive(); String method; if (request instanceof HttpUriRequest) { HttpUriRequest uriRequest = (HttpUriRequest) request; @@ -77,8 +77,7 @@ private static void onBeforeExecute(@Advice.Argument(0) HttpHost host, if (headerSetter != null) { span.propagateTraceContext(request, headerSetter); } - } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter) - && headerSetter != null && parent != null) { + } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter) && headerSetter != null) { // re-adds the header on redirects parent.propagateTraceContext(request, headerSetter); } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ApiInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ApiInstrumentation.java index 7fa2ed32c5b..03ada43c57b 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ApiInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ApiInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,14 +24,14 @@ */ package co.elastic.apm.agent.plugin.api; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import java.util.Collection; import java.util.Collections; import static co.elastic.apm.agent.plugin.api.ElasticApmApiInstrumentation.PUBLIC_API_INSTRUMENTATION_GROUP; -public abstract class ApiInstrumentation extends ElasticApmInstrumentation { +public abstract class ApiInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public boolean includeWhenInstrumentationIsDisabled() { return true; diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureExceptionInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureExceptionInstrumentation.java index 5166568044c..1c1e6225f3d 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureExceptionInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureExceptionInstrumentation.java @@ -36,9 +36,7 @@ public class CaptureExceptionInstrumentation extends ApiInstrumentation { @Advice.OnMethodEnter(suppress = Throwable.class) public static void captureException(@Advice.Origin Class clazz, @Advice.Argument(0) Throwable t) { - if (tracer != null) { - tracer.captureAndReportException(t, clazz.getClassLoader()); - } + tracer.captureAndReportException(t, clazz.getClassLoader()); } @Override diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureSpanInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureSpanInstrumentation.java index deae0ca03bc..cbeca50a1cb 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureSpanInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureSpanInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.plugin.api; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.AnnotationValueOffsetMappingFactory; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory; @@ -52,7 +52,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; import static net.bytebuddy.matcher.ElementMatchers.named; -public class CaptureSpanInstrumentation extends ElasticApmInstrumentation { +public class CaptureSpanInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice public static final Logger logger = LoggerFactory.getLogger(CaptureSpanInstrumentation.class); @@ -71,16 +71,14 @@ public static void onMethodEnter( @Nullable @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "subtype") String subtype, @Nullable @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "action") String action, @Advice.Local("span") Span span) { - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent != null) { - span = parent.createSpan(); - span.setType(type, subtype, action); - span.withName(spanName.isEmpty() ? signature : spanName) - .activate(); - } else { - logger.debug("Not creating span for {} because there is no currently active span.", signature); - } + final AbstractSpan parent = tracer.getActive(); + if (parent != null) { + span = parent.createSpan(); + span.setType(type, subtype, action); + span.withName(spanName.isEmpty() ? signature : spanName) + .activate(); + } else { + logger.debug("Not creating span for {} because there is no currently active span.", signature); } } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureTransactionInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureTransactionInstrumentation.java index b40c62167e9..5530f010a70 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureTransactionInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/CaptureTransactionInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.plugin.api; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.AnnotationValueOffsetMappingFactory.AnnotationValueExtractor; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature; @@ -54,7 +54,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; import static net.bytebuddy.matcher.ElementMatchers.named; -public class CaptureTransactionInstrumentation extends ElasticApmInstrumentation { +public class CaptureTransactionInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice public static final Logger logger = LoggerFactory.getLogger(CaptureTransactionInstrumentation.class); @@ -71,23 +71,21 @@ public static void onMethodEnter(@Advice.Origin Class clazz, @AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureTransaction", method = "value") String transactionName, @AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureTransaction", method = "type") String type, @Advice.Local("transaction") Transaction transaction) { - if (tracer != null) { - final Object active = tracer.getActive(); - if (active == null) { - transaction = tracer.startRootTransaction(clazz.getClassLoader()); - if (transaction != null) { - if (transactionName.isEmpty()) { - transaction.withName(signature, PRIO_METHOD_SIGNATURE); - } else { - transaction.withName(transactionName, PRIO_USER_SUPPLIED); - } - transaction.withType(type) - .activate(); - transaction.setFrameworkName(FRAMEWORK_NAME); + final Object active = tracer.getActive(); + if (active == null) { + transaction = tracer.startRootTransaction(clazz.getClassLoader()); + if (transaction != null) { + if (transactionName.isEmpty()) { + transaction.withName(signature, PRIO_METHOD_SIGNATURE); + } else { + transaction.withName(transactionName, PRIO_USER_SUPPLIED); } - } else { - logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); + transaction.withType(type) + .activate(); + transaction.setFrameworkName(FRAMEWORK_NAME); } + } else { + logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); } } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ElasticApmApiInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ElasticApmApiInstrumentation.java index c41b5eb0ac3..016d6beb4e3 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ElasticApmApiInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/ElasticApmApiInstrumentation.java @@ -70,9 +70,6 @@ public StartTransactionInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static Object doStartTransaction(@Advice.Origin Class clazz) { - if (tracer == null) { - return null; - } Transaction transaction = tracer.startRootTransaction(clazz.getClassLoader()); if (transaction != null) { transaction.setFrameworkName(FRAMEWORK_NAME); @@ -97,9 +94,6 @@ public static Transaction doStartTransaction(@Advice.Origin Class clazz, @Advice.Argument(1) @Nullable Object headerExtractor, @Advice.Argument(2) MethodHandle getAllHeaders, @Advice.Argument(3) @Nullable Object headersExtractor) { - if (tracer == null) { - return null; - } Transaction transaction = null; if (headersExtractor != null) { HeadersExtractorBridge headersExtractorBridge = HeadersExtractorBridge.get(getFirstHeader, getAllHeaders); @@ -127,9 +121,6 @@ public CurrentTransactionInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static Object doGetCurrentTransaction() { - if (tracer == null) { - return null; - } return tracer.currentTransaction(); } } @@ -144,9 +135,6 @@ public CurrentSpanInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static Object doGetCurrentSpan() { - if (tracer == null) { - return null; - } return tracer.getActive(); } } @@ -159,9 +147,7 @@ public CaptureExceptionInstrumentation() { @VisibleForAdvice @Advice.OnMethodEnter(suppress = Throwable.class) public static void captureException(@Advice.Origin Class clazz, @Advice.Argument(0) @Nullable Throwable e) { - if (tracer != null) { - tracer.captureAndReportException(e, clazz.getClassLoader()); - } + tracer.captureAndReportException(e, clazz.getClassLoader()); } } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/LegacySpanInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/LegacySpanInstrumentation.java index 64e93ce19cd..821228e5cdb 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/LegacySpanInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/LegacySpanInstrumentation.java @@ -146,9 +146,6 @@ public GetIdInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(inline = false) public static String getId(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) AbstractSpan span) { - if (tracer == null) { - return null; - } return span.getTraceContext().getId().toString(); } } @@ -163,9 +160,6 @@ public GetTraceIdInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(inline = false) public static String getTraceId(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) AbstractSpan span) { - if (tracer == null) { - return null; - } return span.getTraceContext().getTraceId().toString(); } } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TracedInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TracedInstrumentation.java index b464dab52ee..0ec09ba76b3 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TracedInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TracedInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.plugin.api; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.AnnotationValueOffsetMappingFactory; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -53,7 +53,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; import static net.bytebuddy.matcher.ElementMatchers.named; -public class TracedInstrumentation extends ElasticApmInstrumentation { +public class TracedInstrumentation extends TracerAwareElasticApmInstrumentation { private final StacktraceConfiguration config; @@ -71,30 +71,28 @@ public static void onMethodEnter( @Nullable @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.Traced", method = "action") String action, @Advice.Local("span") AbstractSpan abstractSpan) { - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent != null) { - Span span = parent.createSpan(); - span.withType(type.isEmpty() ? "app" : type); - span.withSubtype(subtype); - span.withAction(action); - span.withName(spanName.isEmpty() ? signature : spanName) - .activate(); - abstractSpan = span; - } else { - Transaction transaction = tracer.startRootTransaction(clazz.getClassLoader()); - if (transaction != null) { - if (spanName.isEmpty()) { - transaction.withName(signature, PRIO_METHOD_SIGNATURE); - } else { - transaction.withName(spanName, PRIO_USER_SUPPLIED); - } - transaction.withType(type.isEmpty() ? Transaction.TYPE_REQUEST : type) - .activate(); - transaction.setFrameworkName(FRAMEWORK_NAME); + final AbstractSpan parent = tracer.getActive(); + if (parent != null) { + Span span = parent.createSpan(); + span.withType(type.isEmpty() ? "app" : type); + span.withSubtype(subtype); + span.withAction(action); + span.withName(spanName.isEmpty() ? signature : spanName) + .activate(); + abstractSpan = span; + } else { + Transaction transaction = tracer.startRootTransaction(clazz.getClassLoader()); + if (transaction != null) { + if (spanName.isEmpty()) { + transaction.withName(signature, PRIO_METHOD_SIGNATURE); + } else { + transaction.withName(spanName, PRIO_USER_SUPPLIED); } - abstractSpan = transaction; + transaction.withType(type.isEmpty() ? Transaction.TYPE_REQUEST : type) + .activate(); + transaction.setFrameworkName(FRAMEWORK_NAME); } + abstractSpan = transaction; } } diff --git a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TransactionInstrumentation.java b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TransactionInstrumentation.java index 57e20b16392..935a0db712d 100644 --- a/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TransactionInstrumentation.java +++ b/apm-agent-plugins/apm-api-plugin/src/main/java/co/elastic/apm/agent/plugin/api/TransactionInstrumentation.java @@ -82,9 +82,6 @@ public EnsureParentIdInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static String ensureParentId(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) Transaction transaction) { - if (tracer == null) { - return null; - } final TraceContext traceContext = transaction.getTraceContext(); if (traceContext.getParentId().isEmpty()) { traceContext.getParentId().setToRandomValue(); diff --git a/apm-agent-plugins/apm-asynchttpclient-plugin/src/main/java/co/elastic/apm/agent/asynchttpclient/AbstractAsyncHttpClientInstrumentation.java b/apm-agent-plugins/apm-asynchttpclient-plugin/src/main/java/co/elastic/apm/agent/asynchttpclient/AbstractAsyncHttpClientInstrumentation.java index 6a8c17383db..708ad239839 100644 --- a/apm-agent-plugins/apm-asynchttpclient-plugin/src/main/java/co/elastic/apm/agent/asynchttpclient/AbstractAsyncHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-asynchttpclient-plugin/src/main/java/co/elastic/apm/agent/asynchttpclient/AbstractAsyncHttpClientInstrumentation.java @@ -27,9 +27,12 @@ import co.elastic.apm.agent.bci.ElasticApmAgent; import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.http.client.HttpClientHelper; +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.impl.transaction.TextHeaderSetter; @@ -56,7 +59,7 @@ import static net.bytebuddy.matcher.ElementMatchers.takesArgument; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public abstract class AbstractAsyncHttpClientInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractAsyncHttpClientInstrumentation extends TracerAwareElasticApmInstrumentation { // Referencing specific AsyncHttpClient classes are allowed due to type erasure @VisibleForAdvice @@ -73,7 +76,7 @@ public abstract class AbstractAsyncHttpClientInstrumentation extends ElasticApmI AsyncHandlerOnStatusReceivedInstrumentation.class, StreamedAsyncHandlerOnStreamInstrumentation.class); - public AbstractAsyncHttpClientInstrumentation() { + public AbstractAsyncHttpClientInstrumentation(ElasticApmTracer tracer) { if (headerSetterManager == null) { synchronized (AbstractAsyncHandlerInstrumentation.class) { if (headerSetterManager == null) { @@ -98,16 +101,20 @@ public ElementMatcher.Junction getClassLoaderMatcher() { public static class AsyncHttpClientInstrumentation extends AbstractAsyncHttpClientInstrumentation { + public AsyncHttpClientInstrumentation(ElasticApmTracer tracer) { + super(tracer); + } + @Advice.OnMethodEnter(suppress = Throwable.class) private static void onBeforeExecute(@Advice.Argument(value = 0) Request request, @Advice.Argument(value = 1) AsyncHandler asyncHandler, @Advice.Local("span") Span span) { - if (tracer == null || tracer.getActive() == null) { + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { return; } ElasticApmAgent.ensureInstrumented(asyncHandler.getClass(), ASYNC_HANDLER_INSTRUMENTATIONS); - final AbstractSpan parent = tracer.getActive(); Uri uri = request.getUri(); span = HttpClientHelper.startHttpClientSpan(parent, request.getMethod(), uri.toUrl(), uri.getScheme(), uri.getHost(), uri.getPort()); @@ -154,7 +161,8 @@ public abstract static class AbstractAsyncHandlerInstrumentation extends Abstrac private final ElementMatcher methodMatcher; - protected AbstractAsyncHandlerInstrumentation(ElementMatcher methodMatcher) { + protected AbstractAsyncHandlerInstrumentation(ElasticApmTracer tracer, ElementMatcher methodMatcher) { + super(tracer); this.methodMatcher = methodMatcher; } @@ -175,8 +183,8 @@ public ElementMatcher getMethodMatcher() { public static class AsyncHandlerOnCompletedInstrumentation extends AbstractAsyncHandlerInstrumentation { - public AsyncHandlerOnCompletedInstrumentation() { - super(named("onCompleted").and(takesArguments(0))); + public AsyncHandlerOnCompletedInstrumentation(ElasticApmTracer tracer) { + super(tracer, named("onCompleted").and(takesArguments(0))); } @Advice.OnMethodEnter(suppress = Throwable.class) @@ -198,8 +206,8 @@ private static void onMethodExit(@Nullable @Advice.Local("span") Span span) { public static class AsyncHandlerOnThrowableInstrumentation extends AbstractAsyncHandlerInstrumentation { - public AsyncHandlerOnThrowableInstrumentation() { - super(named("onThrowable").and(takesArguments(Throwable.class))); + public AsyncHandlerOnThrowableInstrumentation(ElasticApmTracer tracer) { + super(tracer, named("onThrowable").and(takesArguments(Throwable.class))); } @Advice.OnMethodEnter(suppress = Throwable.class) @@ -221,8 +229,8 @@ private static void onMethodExit(@Nullable @Advice.Local("span") Span span, @Adv public static class AsyncHandlerOnStatusReceivedInstrumentation extends AbstractAsyncHandlerInstrumentation { - public AsyncHandlerOnStatusReceivedInstrumentation() { - super(named("onStatusReceived").and(takesArgument(0, named("org.asynchttpclient.HttpResponseStatus")))); + public AsyncHandlerOnStatusReceivedInstrumentation(ElasticApmTracer tracer) { + super(tracer, named("onStatusReceived").and(takesArgument(0, named("org.asynchttpclient.HttpResponseStatus")))); } @Advice.OnMethodEnter(suppress = Throwable.class) @@ -244,8 +252,8 @@ private static void onMethodExit(@Nullable @Advice.Local("span") Span span, @Adv public static class StreamedAsyncHandlerOnStreamInstrumentation extends AbstractAsyncHandlerInstrumentation { - public StreamedAsyncHandlerOnStreamInstrumentation() { - super(named("onStream").and(takesArgument(0, named("org.reactivestreams.Publisher")))); + public StreamedAsyncHandlerOnStreamInstrumentation(ElasticApmTracer tracer) { + super(tracer, named("onStream").and(takesArgument(0, named("org.reactivestreams.Publisher")))); } @Advice.OnMethodEnter(suppress = Throwable.class) diff --git a/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AbstractDubboInstrumentation.java b/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AbstractDubboInstrumentation.java index 1480820827d..3a7363d82d9 100644 --- a/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AbstractDubboInstrumentation.java +++ b/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AbstractDubboInstrumentation.java @@ -24,12 +24,12 @@ */ package co.elastic.apm.agent.dubbo; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import java.util.Arrays; import java.util.Collection; -public abstract class AbstractDubboInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractDubboInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public Collection getInstrumentationGroupNames() { diff --git a/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AlibabaResponseFutureInstrumentation.java b/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AlibabaResponseFutureInstrumentation.java index ba0e760992c..b0607ce50b8 100644 --- a/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AlibabaResponseFutureInstrumentation.java +++ b/apm-agent-plugins/apm-dubbo-plugin/src/main/java/co/elastic/apm/agent/dubbo/AlibabaResponseFutureInstrumentation.java @@ -74,9 +74,6 @@ public static class AlibabaResponseFutureAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) private static void onEnter(@Advice.Argument(value = 0, readOnly = false) ResponseCallback callback) { - if (tracer == null) { - return; - } AbstractSpan active = tracer.getActive(); if (active == null) { return; diff --git a/apm-agent-plugins/apm-error-logging-plugin/src/main/java/co/elastic/apm/agent/error/logging/AbstractLoggerErrorCapturingInstrumentation.java b/apm-agent-plugins/apm-error-logging-plugin/src/main/java/co/elastic/apm/agent/error/logging/AbstractLoggerErrorCapturingInstrumentation.java index 2c19b0c7dbb..fb801a36bef 100644 --- a/apm-agent-plugins/apm-error-logging-plugin/src/main/java/co/elastic/apm/agent/error/logging/AbstractLoggerErrorCapturingInstrumentation.java +++ b/apm-agent-plugins/apm-error-logging-plugin/src/main/java/co/elastic/apm/agent/error/logging/AbstractLoggerErrorCapturingInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.error.logging; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.error.ErrorCapture; import net.bytebuddy.asm.Advice; @@ -40,7 +40,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; -public abstract class AbstractLoggerErrorCapturingInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractLoggerErrorCapturingInstrumentation extends TracerAwareElasticApmInstrumentation { @SuppressWarnings({"WeakerAccess"}) @VisibleForAdvice @@ -63,12 +63,12 @@ public static void logEnter(@Advice.Argument(1) Throwable exception, @Advice.Local("nested") boolean nested, @Advice.Origin Class clazz, @Advice.Local("error") @Nullable ErrorCapture error) { - if (tracer == null) { - return; - } nested = nestedThreadLocal.get(); if (!nested) { - error = tracer.captureException(exception, tracer.getActive(), clazz.getClassLoader()).activate(); + error = tracer.captureException(exception, tracer.getActive(), clazz.getClassLoader()); + if (error != null) { + error.activate(); + } nestedThreadLocal.set(Boolean.TRUE); } } diff --git a/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-6_4/src/test/java/co/elastic/apm/agent/es/restclient/v6_4/ElasticsearchRestClientInstrumentationIT_RealReporter.java b/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-6_4/src/test/java/co/elastic/apm/agent/es/restclient/v6_4/ElasticsearchRestClientInstrumentationIT_RealReporter.java index 9b4eae35cad..d03765bffcf 100644 --- a/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-6_4/src/test/java/co/elastic/apm/agent/es/restclient/v6_4/ElasticsearchRestClientInstrumentationIT_RealReporter.java +++ b/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-6_4/src/test/java/co/elastic/apm/agent/es/restclient/v6_4/ElasticsearchRestClientInstrumentationIT_RealReporter.java @@ -26,8 +26,8 @@ import co.elastic.apm.agent.bci.ElasticApmAgent; import co.elastic.apm.agent.configuration.SpyConfiguration; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.MetaData; import co.elastic.apm.agent.impl.payload.Agent; import co.elastic.apm.agent.impl.payload.ProcessInfo; diff --git a/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-common/src/main/java/co/elastic/apm/agent/es/restclient/ElasticsearchRestClientInstrumentation.java b/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-common/src/main/java/co/elastic/apm/agent/es/restclient/ElasticsearchRestClientInstrumentation.java index 1dd8e949c02..d2a6cc065a5 100644 --- a/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-common/src/main/java/co/elastic/apm/agent/es/restclient/ElasticsearchRestClientInstrumentation.java +++ b/apm-agent-plugins/apm-es-restclient-plugin/apm-es-restclient-plugin-common/src/main/java/co/elastic/apm/agent/es/restclient/ElasticsearchRestClientInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.es.restclient; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.ElasticApmTracer; import org.apache.http.HttpEntity; @@ -37,7 +37,7 @@ import java.util.Collections; -public abstract class ElasticsearchRestClientInstrumentation extends ElasticApmInstrumentation { +public abstract class ElasticsearchRestClientInstrumentation extends TracerAwareElasticApmInstrumentation { @Nullable @VisibleForAdvice diff --git a/apm-agent-plugins/apm-grails-plugin/src/main/java/co/elastic/apm/agent/grails/GrailsTransactionNameInstrumentation.java b/apm-agent-plugins/apm-grails-plugin/src/main/java/co/elastic/apm/agent/grails/GrailsTransactionNameInstrumentation.java index 4fe5cc95597..615f78aa67e 100644 --- a/apm-agent-plugins/apm-grails-plugin/src/main/java/co/elastic/apm/agent/grails/GrailsTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-grails-plugin/src/main/java/co/elastic/apm/agent/grails/GrailsTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.grails; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.transaction.Transaction; import grails.core.GrailsControllerClass; @@ -49,7 +49,7 @@ import static net.bytebuddy.matcher.ElementMatchers.returns; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; -public class GrailsTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class GrailsTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcher() { @@ -90,9 +90,6 @@ public static class HandlerAdapterAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) static void setTransactionName(@Advice.Argument(2) Object handler) { - if (tracer == null) { - return; - } final Transaction transaction = tracer.currentTransaction(); if (transaction == null) { return; diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/BaseInstrumentation.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/BaseInstrumentation.java index a32b6c0b88a..44f783c78f0 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/BaseInstrumentation.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/BaseInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.grpc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.grpc.helper.GrpcHelper; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -38,7 +38,7 @@ import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; -public abstract class BaseInstrumentation extends ElasticApmInstrumentation { +public abstract class BaseInstrumentation extends TracerAwareElasticApmInstrumentation { @Nullable @VisibleForAdvice diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ChannelInstrumentation.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ChannelInstrumentation.java index 240d1861bc7..19e8ff1a94d 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ChannelInstrumentation.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ChannelInstrumentation.java @@ -75,7 +75,7 @@ private static void onEnter(@Advice.This Channel channel, @Advice.Argument(0) MethodDescriptor method, @Advice.Local("span") Span span) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ClientCallImplInstrumentation.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ClientCallImplInstrumentation.java index c2e00f8a9b0..700a88b6b7f 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ClientCallImplInstrumentation.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ClientCallImplInstrumentation.java @@ -106,7 +106,7 @@ private static void onEnter(@Advice.This ClientCall clientCall, @Advice.Argument(1) Metadata headers, @Advice.Local("span") Span span) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } @@ -172,7 +172,7 @@ public ElementMatcher getMethodMatcher() { private static void onEnter(@Advice.This ClientCall.Listener listener, @Advice.Local("span") Span span) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } @@ -226,7 +226,7 @@ public ElementMatcher getMethodMatcher() { private static void onEnter(@Advice.This ClientCall.Listener listener, @Advice.Local("span") Span span) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallHandlerInstrumentation.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallHandlerInstrumentation.java index 976ef5f82f5..5854f4a036d 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallHandlerInstrumentation.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallHandlerInstrumentation.java @@ -73,7 +73,7 @@ private static void onEnter(@Advice.Origin Class clazz, @Advice.Argument(1) Metadata headers, @Advice.Local("transaction") Transaction transaction) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallInstrumentation.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallInstrumentation.java index 6b9de8c4921..8b3fb0d24e5 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallInstrumentation.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/ServerCallInstrumentation.java @@ -74,7 +74,7 @@ private static void onExit(@Advice.Thrown @Nullable Throwable thrown, @Advice.This ServerCall serverCall, @Advice.Argument(0) Status status) { - if (tracer == null || grpcHelperManager == null) { + if (grpcHelperManager == null) { return; } diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelper.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelper.java index ba9c6fcc75d..efcf97abad1 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelper.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelper.java @@ -25,7 +25,7 @@ package co.elastic.apm.agent.grpc.helper; import co.elastic.apm.agent.bci.VisibleForAdvice; -import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.impl.transaction.Transaction; @@ -54,7 +54,7 @@ public interface GrpcHelper { * @return transaction, or {@literal null} if none has been created */ @Nullable - Transaction startTransaction(ElasticApmTracer tracer, + Transaction startTransaction(Tracer tracer, ClassLoader cl, ServerCall serverCall, Metadata headers); @@ -112,7 +112,7 @@ void exitServerListenerMethod(@Nullable Throwable thrown, *
    * This is the first method called during a client call execution, the next is {@link #registerSpan(ClientCall, Span)}. * - * @param parent parent transaction, or parent span provided by {@link ElasticApmTracer#getActive()}. + * @param parent parent transaction, or parent span provided by {@link Tracer#getActive()}. * @param method method descriptor * @param authority channel authority string (host+port) * @return client call span (activated) or {@literal null} if not within an exit span. diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelperImpl.java b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelperImpl.java index 1d92fbedea2..8110a60574d 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelperImpl.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/main/java/co/elastic/apm/agent/grpc/helper/GrpcHelperImpl.java @@ -25,7 +25,7 @@ package co.elastic.apm.agent.grpc.helper; import co.elastic.apm.agent.collections.WeakMapSupplier; -import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.context.Destination; import co.elastic.apm.agent.impl.transaction.AbstractHeaderGetter; import co.elastic.apm.agent.impl.transaction.AbstractSpan; @@ -100,7 +100,7 @@ public class GrpcHelperImpl implements GrpcHelper { @Nullable @Override - public Transaction startTransaction(ElasticApmTracer tracer, ClassLoader cl, ServerCall serverCall, Metadata headers) { + public Transaction startTransaction(Tracer tracer, ClassLoader cl, ServerCall serverCall, Metadata headers) { MethodDescriptor methodDescriptor = serverCall.getMethodDescriptor(); // ignore non-unary method calls for now diff --git a/apm-agent-plugins/apm-grpc/apm-grpc-test-latest/src/test/java/co/elastic/apm/agent/grpc/latest/testapp/generated/HelloGrpc.java b/apm-agent-plugins/apm-grpc/apm-grpc-test-latest/src/test/java/co/elastic/apm/agent/grpc/latest/testapp/generated/HelloGrpc.java index fa8230dc1ac..4d134c457ce 100644 --- a/apm-agent-plugins/apm-grpc/apm-grpc-test-latest/src/test/java/co/elastic/apm/agent/grpc/latest/testapp/generated/HelloGrpc.java +++ b/apm-agent-plugins/apm-grpc/apm-grpc-test-latest/src/test/java/co/elastic/apm/agent/grpc/latest/testapp/generated/HelloGrpc.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-5_x/src/main/java/co/elastic/apm/agent/hibernate/search/v5_x/HibernateSearch5Instrumentation.java b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-5_x/src/main/java/co/elastic/apm/agent/hibernate/search/v5_x/HibernateSearch5Instrumentation.java index 2f22a442a1f..964a73b1f31 100644 --- a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-5_x/src/main/java/co/elastic/apm/agent/hibernate/search/v5_x/HibernateSearch5Instrumentation.java +++ b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-5_x/src/main/java/co/elastic/apm/agent/hibernate/search/v5_x/HibernateSearch5Instrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -29,7 +29,7 @@ import javax.annotation.Nullable; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.hibernate.search.HibernateSearchConstants; import co.elastic.apm.agent.hibernate.search.HibernateSearchHelper; import co.elastic.apm.agent.impl.transaction.Span; @@ -48,7 +48,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.not; -public class HibernateSearch5Instrumentation extends ElasticApmInstrumentation { +public class HibernateSearch5Instrumentation extends TracerAwareElasticApmInstrumentation { @Override public Class getAdviceClass() { diff --git a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-6_x/src/main/java/co/elastic/apm/agent/hibernate/search/v6_x/HibernateSearch6Instrumentation.java b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-6_x/src/main/java/co/elastic/apm/agent/hibernate/search/v6_x/HibernateSearch6Instrumentation.java index dc45ee5a30a..c3d551d7cb1 100644 --- a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-6_x/src/main/java/co/elastic/apm/agent/hibernate/search/v6_x/HibernateSearch6Instrumentation.java +++ b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-6_x/src/main/java/co/elastic/apm/agent/hibernate/search/v6_x/HibernateSearch6Instrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.hibernate.search.v6_x; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.hibernate.search.HibernateSearchConstants; import co.elastic.apm.agent.hibernate.search.HibernateSearchHelper; import co.elastic.apm.agent.impl.transaction.Span; @@ -48,7 +48,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.not; -public class HibernateSearch6Instrumentation extends ElasticApmInstrumentation { +public class HibernateSearch6Instrumentation extends TracerAwareElasticApmInstrumentation { @Override public Class getAdviceClass() { diff --git a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-common/src/main/java/co/elastic/apm/agent/hibernate/search/HibernateSearchHelper.java b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-common/src/main/java/co/elastic/apm/agent/hibernate/search/HibernateSearchHelper.java index 37cbeeaf1ce..25d22109203 100644 --- a/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-common/src/main/java/co/elastic/apm/agent/hibernate/search/HibernateSearchHelper.java +++ b/apm-agent-plugins/apm-hibernate-search-plugin/apm-hibernate-search-plugin-common/src/main/java/co/elastic/apm/agent/hibernate/search/HibernateSearchHelper.java @@ -25,7 +25,7 @@ package co.elastic.apm.agent.hibernate.search; import co.elastic.apm.agent.bci.VisibleForAdvice; -import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; @@ -37,29 +37,26 @@ private HibernateSearchHelper() { } @VisibleForAdvice - public static Span createAndActivateSpan(final ElasticApmTracer tracer, final String methodName, + public static Span createAndActivateSpan(final Tracer tracer, final String methodName, final String query) { - Span span = null; - if (tracer != null) { - AbstractSpan active = tracer.getActive(); - // avoid creating the same span twice for example, when an instrumented API is wrapped - if (active == null || active instanceof Span && HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE - .equals(((Span) active).getSubtype())) { - return null; - } + AbstractSpan active = tracer.getActive(); + // avoid creating the same span twice for example, when an instrumented API is wrapped + if (active == null || active instanceof Span && HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE + .equals(((Span) active).getSubtype())) { + return null; + } - span = active.createSpan().activate(); + Span span = active.createSpan().activate(); - span.withType(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_SPAN_TYPE) - .withSubtype(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE) - .withAction(methodName); - span.getContext().getDb() - .withType(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE) - .withStatement(query); - span.withName(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_SPAN_NAME) - .appendToName(" ").appendToName(methodName).appendToName("()"); - } + span.withType(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_SPAN_TYPE) + .withSubtype(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE) + .withAction(methodName); + span.getContext().getDb() + .withType(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_TYPE) + .withStatement(query); + span.withName(HibernateSearchConstants.HIBERNATE_SEARCH_ORM_SPAN_NAME) + .appendToName(" ").appendToName(methodName).appendToName("()"); return span; } } diff --git a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ExecutorInstrumentation.java b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ExecutorInstrumentation.java index 582f0f90fbb..5578a6a1edc 100644 --- a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ExecutorInstrumentation.java +++ b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ExecutorInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.concurrent; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; import co.elastic.apm.agent.util.GlobalVariables; import net.bytebuddy.asm.Advice; @@ -62,7 +62,7 @@ import static net.bytebuddy.matcher.ElementMatchers.takesArgument; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public abstract class ExecutorInstrumentation extends ElasticApmInstrumentation { +public abstract class ExecutorInstrumentation extends TracerAwareElasticApmInstrumentation { static final Set excludedClasses = GlobalVariables.get(ExecutorInstrumentation.class, "excludedClasses", new HashSet()); diff --git a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ForkJoinTaskInstrumentation.java b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ForkJoinTaskInstrumentation.java index 316f91d8e20..502001f5cab 100644 --- a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ForkJoinTaskInstrumentation.java +++ b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/ForkJoinTaskInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.concurrent; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; @@ -42,7 +42,7 @@ /** * Instruments {@link ForkJoinTask#fork()} to support parallel streams. */ -public class ForkJoinTaskInstrumentation extends ElasticApmInstrumentation { +public class ForkJoinTaskInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcher() { return is(ForkJoinTask.class); diff --git a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/JavaConcurrent.java b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/JavaConcurrent.java index f8dd90a6a94..4ed27f92ce6 100644 --- a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/JavaConcurrent.java +++ b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/JavaConcurrent.java @@ -27,7 +27,7 @@ import co.elastic.apm.agent.bci.ElasticApmAgent; import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.collections.WeakMapSupplier; -import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap; @@ -54,10 +54,7 @@ private static void removeContext(Object o) { } @Nullable - public static AbstractSpan restoreContext(Object o, @Nullable ElasticApmTracer tracer) { - if (tracer == null) { - return null; - } + public static AbstractSpan restoreContext(Object o, Tracer tracer) { // When an Executor executes directly on the current thread we need to enable this thread for context propagation again needsContext.set(Boolean.TRUE); AbstractSpan context = contextMap.remove(o); @@ -78,8 +75,8 @@ public static AbstractSpan restoreContext(Object o, @Nullable ElasticApmTrace * Instruments or wraps the provided runnable and makes this {@link AbstractSpan} active in the {@link Runnable#run()} method. */ @Nullable - public static Runnable withContext(@Nullable Runnable runnable, @Nullable ElasticApmTracer tracer) { - if (runnable instanceof RunnableLambdaWrapper || runnable == null || tracer == null || needsContext.get() == Boolean.FALSE) { + public static Runnable withContext(@Nullable Runnable runnable, Tracer tracer) { + if (runnable instanceof RunnableLambdaWrapper || runnable == null || needsContext.get() == Boolean.FALSE) { return runnable; } needsContext.set(Boolean.FALSE); @@ -106,8 +103,8 @@ private static void captureContext(Object task, AbstractSpan active) { * Instruments or wraps the provided runnable and makes this {@link AbstractSpan} active in the {@link Runnable#run()} method. */ @Nullable - public static Callable withContext(@Nullable Callable callable, @Nullable ElasticApmTracer tracer) { - if (callable instanceof CallableLambdaWrapper || callable == null || tracer == null || needsContext.get() == Boolean.FALSE) { + public static Callable withContext(@Nullable Callable callable, Tracer tracer) { + if (callable instanceof CallableLambdaWrapper || callable == null || needsContext.get() == Boolean.FALSE) { return callable; } needsContext.set(Boolean.FALSE); @@ -123,8 +120,8 @@ public static Callable withContext(@Nullable Callable callable, @Nulla } @Nullable - public static ForkJoinTask withContext(@Nullable ForkJoinTask task, @Nullable ElasticApmTracer tracer) { - if (task == null || tracer == null || needsContext.get() == Boolean.FALSE) { + public static ForkJoinTask withContext(@Nullable ForkJoinTask task, Tracer tracer) { + if (task == null || needsContext.get() == Boolean.FALSE) { return task; } needsContext.set(Boolean.FALSE); @@ -157,8 +154,8 @@ private static boolean isLambda(Object o) { } @Nullable - public static Collection> withContext(@Nullable Collection> callables, @Nullable ElasticApmTracer tracer) { - if (callables == null || tracer == null) { + public static Collection> withContext(@Nullable Collection> callables, Tracer tracer) { + if (callables == null) { return null; } if (callables.isEmpty()) { diff --git a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/RunnableCallableForkJoinTaskInstrumentation.java b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/RunnableCallableForkJoinTaskInstrumentation.java index adacb0d36d3..842acbfb95c 100644 --- a/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/RunnableCallableForkJoinTaskInstrumentation.java +++ b/apm-agent-plugins/apm-java-concurrent-plugin/src/main/java/co/elastic/apm/agent/concurrent/RunnableCallableForkJoinTaskInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.concurrent; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; @@ -48,7 +48,7 @@ * {@linkplain co.elastic.apm.agent.bci.ElasticApmAgent#ensureInstrumented(Class, Collection) ensure} * that particular {@link Callable}, {@link Runnable} and {@link ForkJoinTask} classes are instrumented. */ -public class RunnableCallableForkJoinTaskInstrumentation extends ElasticApmInstrumentation { +public class RunnableCallableForkJoinTaskInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcher() { diff --git a/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsOffsetMappingFactory.java b/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsOffsetMappingFactory.java index e1e88f2ce3d..3f7c9c18bb1 100644 --- a/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsOffsetMappingFactory.java +++ b/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsOffsetMappingFactory.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsTransactionNameInstrumentation.java b/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsTransactionNameInstrumentation.java index 37d3c6b58eb..8d6d899da01 100644 --- a/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-jaxrs-plugin/src/main/java/co/elastic/apm/agent/jaxrs/JaxRsTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.jaxrs; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.stacktrace.StacktraceConfiguration; @@ -54,14 +54,16 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.not; -public class JaxRsTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class JaxRsTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { public static boolean useAnnotationValueForTransactionName; private final Collection applicationPackages; private final JaxRsConfiguration configuration; + private final ElasticApmTracer tracer; public JaxRsTransactionNameInstrumentation(ElasticApmTracer tracer) { + this.tracer = tracer; applicationPackages = tracer.getConfig(StacktraceConfiguration.class).getApplicationPackages(); configuration = tracer.getConfig(JaxRsConfiguration.class); useAnnotationValueForTransactionName = configuration.isUseJaxRsPathForTransactionName(); @@ -70,19 +72,17 @@ public JaxRsTransactionNameInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class) private static void setTransactionName(@SimpleMethodSignature String signature, @JaxRsPath @Nullable String pathAnnotationValue) { - if (tracer != null) { - final Transaction transaction = tracer.currentTransaction(); - if (transaction != null) { - String transactionName = signature; - if (useAnnotationValueForTransactionName) { - if (pathAnnotationValue != null) { - transactionName = pathAnnotationValue; - } + final Transaction transaction = TracerAwareElasticApmInstrumentation.tracer.currentTransaction(); + if (transaction != null) { + String transactionName = signature; + if (useAnnotationValueForTransactionName) { + if (pathAnnotationValue != null) { + transactionName = pathAnnotationValue; } - transaction.withName(transactionName, PRIO_HIGH_LEVEL_FRAMEWORK, false); - transaction.setFrameworkName("JAX-RS"); - transaction.setFrameworkVersion(VersionUtils.getVersion(javax.ws.rs.GET.class, "javax.ws.rs", "javax.ws.rs-api")); } + transaction.withName(transactionName, PRIO_HIGH_LEVEL_FRAMEWORK, false); + transaction.setFrameworkName("JAX-RS"); + transaction.setFrameworkVersion(VersionUtils.getVersion(javax.ws.rs.GET.class, "javax.ws.rs", "javax.ws.rs-api")); } } diff --git a/apm-agent-plugins/apm-jaxws-plugin/src/main/java/co/elastic/apm/agent/jaxws/JaxWsTransactionNameInstrumentation.java b/apm-agent-plugins/apm-jaxws-plugin/src/main/java/co/elastic/apm/agent/jaxws/JaxWsTransactionNameInstrumentation.java index 3d2712bda24..33d25cfff97 100644 --- a/apm-agent-plugins/apm-jaxws-plugin/src/main/java/co/elastic/apm/agent/jaxws/JaxWsTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-jaxws-plugin/src/main/java/co/elastic/apm/agent/jaxws/JaxWsTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.jaxws; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.stacktrace.StacktraceConfiguration; @@ -49,7 +49,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.not; -public class JaxWsTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class JaxWsTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String FRAMEWORK_NAME = "JAX-WS"; @@ -61,12 +61,10 @@ public JaxWsTransactionNameInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class) private static void setTransactionName(@SimpleMethodSignature String signature) { - if (tracer != null) { - final Transaction transaction = tracer.currentTransaction(); - if (transaction != null) { - transaction.withName(signature, PRIO_HIGH_LEVEL_FRAMEWORK); - transaction.setFrameworkName(FRAMEWORK_NAME); - } + final Transaction transaction = tracer.currentTransaction(); + if (transaction != null) { + transaction.withName(signature, PRIO_HIGH_LEVEL_FRAMEWORK); + transaction.setFrameworkName(FRAMEWORK_NAME); } } diff --git a/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/JdbcInstrumentation.java b/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/JdbcInstrumentation.java index 1761409a1ef..1ca73e6385d 100644 --- a/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/JdbcInstrumentation.java +++ b/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/JdbcInstrumentation.java @@ -24,13 +24,13 @@ */ package co.elastic.apm.agent.jdbc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.jdbc.helper.JdbcHelper; import java.util.Collection; import java.util.Collections; -public abstract class JdbcInstrumentation extends ElasticApmInstrumentation { +public abstract class JdbcInstrumentation extends TracerAwareElasticApmInstrumentation { private static final Collection JDBC_GROUPS = Collections.singleton("jdbc"); diff --git a/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/StatementInstrumentation.java b/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/StatementInstrumentation.java index 00bfcf5f02f..567c2d7704f 100644 --- a/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/StatementInstrumentation.java +++ b/apm-agent-plugins/apm-jdbc-plugin/src/main/java/co/elastic/apm/agent/jdbc/StatementInstrumentation.java @@ -100,10 +100,6 @@ public ExecuteWithQueryInstrumentation(ElasticApmTracer tracer) { public static Object onBeforeExecute(@Advice.This Statement statement, @Advice.Argument(0) String sql) { - if (tracer == null) { - return null; - } - return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), false); } @@ -150,9 +146,6 @@ public ExecuteUpdateWithQueryInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class, inline = false) public static Object onBeforeExecute(@Advice.This Statement statement, @Advice.Argument(0) String sql) { - if (tracer == null) { - return null; - } return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), false); } @@ -219,9 +212,6 @@ public ExecuteBatchInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class, inline = false) @SuppressWarnings("DuplicatedCode") public static Object onBeforeExecute(@Advice.This Statement statement) { - if (tracer == null) { - return null; - } String sql = jdbcHelper.retrieveSqlForStatement(statement); return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), true); @@ -282,9 +272,6 @@ public ExecuteUpdateNoQueryInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class, inline = false) @SuppressWarnings("DuplicatedCode") public static Object onBeforeExecute(@Advice.This Statement statement) { - if (tracer == null) { - return null; - } String sql = jdbcHelper.retrieveSqlForStatement(statement); return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), true); @@ -330,11 +317,8 @@ public ExecutePreparedStatementInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class, inline = false) @SuppressWarnings("DuplicatedCode") public static Object onBeforeExecute(@Advice.This Statement statement) { - if (tracer != null) { - @Nullable String sql = jdbcHelper.retrieveSqlForStatement(statement); - return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), true); - } - return null; + @Nullable String sql = jdbcHelper.retrieveSqlForStatement(statement); + return jdbcHelper.createJdbcSpan(sql, statement, tracer.getActive(), true); } @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false) diff --git a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/BaseJmsInstrumentation.java b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/BaseJmsInstrumentation.java index bc8b0e44e2f..5a9ccde7ea3 100644 --- a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/BaseJmsInstrumentation.java +++ b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/BaseJmsInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.jms; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.configuration.MessagingConfiguration; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -42,7 +42,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isBootstrapClassLoader; import static net.bytebuddy.matcher.ElementMatchers.not; -public abstract class BaseJmsInstrumentation extends ElasticApmInstrumentation { +public abstract class BaseJmsInstrumentation extends TracerAwareElasticApmInstrumentation { @SuppressWarnings("WeakerAccess") @Nullable @VisibleForAdvice diff --git a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageConsumerInstrumentation.java b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageConsumerInstrumentation.java index 8976b7b8ce8..af62c272fc0 100644 --- a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageConsumerInstrumentation.java +++ b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageConsumerInstrumentation.java @@ -102,70 +102,68 @@ public static class MessageConsumerAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) @Nullable - public static AbstractSpan beforeReceive(@Advice.Origin Class clazz, + public static AbstractSpan beforeReceive(@Advice.Origin Class clazz, @Advice.Origin("#m") String methodName) { - AbstractSpan createdSpan = null; + AbstractSpan createdSpan = null; boolean createPollingTransaction = false; boolean createPollingSpan = false; - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent == null) { - createPollingTransaction = true; - } else { - if (parent instanceof Transaction) { - Transaction transaction = (Transaction) parent; - if (MESSAGE_POLLING.equals(transaction.getType())) { - // Avoid duplications for nested calls - return null; - } else if (MESSAGE_HANDLING.equals(transaction.getType())) { - // A transaction created in the OnMethodExit of the poll- end it here - // Type must be changed to "messaging" - transaction.withType(MESSAGING_TYPE); - transaction.deactivate().end(); - createPollingTransaction = true; - } else { - createPollingSpan = true; - } - } else if (parent instanceof Span) { - Span parentSpan = (Span) parent; - if (MESSAGING_TYPE.equals(parentSpan.getType()) && "receive".equals(parentSpan.getAction())) { - // Avoid duplication for nested calls - return null; - } + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { + createPollingTransaction = true; + } else { + if (parent instanceof Transaction) { + Transaction transaction = (Transaction) parent; + if (MESSAGE_POLLING.equals(transaction.getType())) { + // Avoid duplications for nested calls + return null; + } else if (MESSAGE_HANDLING.equals(transaction.getType())) { + // A transaction created in the OnMethodExit of the poll- end it here + // Type must be changed to "messaging" + transaction.withType(MESSAGING_TYPE); + transaction.deactivate().end(); + createPollingTransaction = true; + } else { createPollingSpan = true; } - } - - if (messagingConfiguration != null) { - createPollingTransaction &= messagingConfiguration.getMessagePollingTransactionStrategy() != MessagingConfiguration.Strategy.HANDLING; - createPollingTransaction |= "receiveNoWait".equals(methodName); - } - - if (createPollingSpan) { - createdSpan = parent.createSpan() - .withType(MESSAGING_TYPE) - .withSubtype("jms") - .withAction("receive"); - } else if (createPollingTransaction) { - createdSpan = tracer.startRootTransaction(clazz.getClassLoader()); - if (createdSpan != null) { - ((Transaction) createdSpan).withType(MESSAGE_POLLING); + } else if (parent instanceof Span) { + Span parentSpan = (Span) parent; + if (MESSAGING_TYPE.equals(parentSpan.getType()) && "receive".equals(parentSpan.getAction())) { + // Avoid duplication for nested calls + return null; } + createPollingSpan = true; } + } + + if (messagingConfiguration != null) { + createPollingTransaction &= messagingConfiguration.getMessagePollingTransactionStrategy() != MessagingConfiguration.Strategy.HANDLING; + createPollingTransaction |= "receiveNoWait".equals(methodName); + } + if (createPollingSpan) { + createdSpan = parent.createSpan() + .withType(MESSAGING_TYPE) + .withSubtype("jms") + .withAction("receive"); + } else if (createPollingTransaction) { + createdSpan = tracer.startRootTransaction(clazz.getClassLoader()); if (createdSpan != null) { - createdSpan.withName(RECEIVE_NAME_PREFIX); - createdSpan.activate(); + ((Transaction) createdSpan).withType(MESSAGE_POLLING); } } + + if (createdSpan != null) { + createdSpan.withName(RECEIVE_NAME_PREFIX); + createdSpan.activate(); + } return createdSpan; } @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static void afterReceive(@Advice.Origin Class clazz, @Advice.Origin("#m") String methodName, - @Advice.Enter @Nullable final AbstractSpan abstractSpan, + @Advice.Enter @Nullable final AbstractSpan abstractSpan, @Advice.Return @Nullable final Message message, @Advice.Thrown final Throwable throwable) { @@ -221,7 +219,7 @@ public static void afterReceive(@Advice.Origin Class clazz, } } - if (!discard && tracer != null && tracer.currentTransaction() == null && helper != null + if (!discard && tracer.currentTransaction() == null && helper != null && message != null && messagingConfiguration != null && messagingConfiguration.getMessagePollingTransactionStrategy() != MessagingConfiguration.Strategy.POLLING && !"receiveNoWait".equals(methodName)) { diff --git a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageListenerInstrumentation.java b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageListenerInstrumentation.java index 552dfae2b56..c8f74e584c7 100644 --- a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageListenerInstrumentation.java +++ b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageListenerInstrumentation.java @@ -87,7 +87,7 @@ public static class MessageListenerAdvice { public static Transaction beforeOnMessage(@Advice.Argument(0) @Nullable final Message message, @Advice.Origin Class clazz) { - if (message == null || tracer == null || tracer.currentTransaction() != null) { + if (message == null || tracer.currentTransaction() != null) { return null; } diff --git a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageProducerInstrumentation.java b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageProducerInstrumentation.java index ef618014836..1c8043b4756 100644 --- a/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageProducerInstrumentation.java +++ b/apm-agent-plugins/apm-jms-plugin/src/main/java/co/elastic/apm/agent/jms/JmsMessageProducerInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-jmx-plugin/src/test/java/co/elastic/apm/agent/jmx/JmxMetricTrackerTest.java b/apm-agent-plugins/apm-jmx-plugin/src/test/java/co/elastic/apm/agent/jmx/JmxMetricTrackerTest.java index 43ec8b37f65..743d13bbae4 100644 --- a/apm-agent-plugins/apm-jmx-plugin/src/test/java/co/elastic/apm/agent/jmx/JmxMetricTrackerTest.java +++ b/apm-agent-plugins/apm-jmx-plugin/src/test/java/co/elastic/apm/agent/jmx/JmxMetricTrackerTest.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-jsf-plugin/src/main/java/co/elastic/apm/agent/jsf/JsfLifecycleInstrumentation.java b/apm-agent-plugins/apm-jsf-plugin/src/main/java/co/elastic/apm/agent/jsf/JsfLifecycleInstrumentation.java index 9e03d7b4f2c..2c66da3fe68 100644 --- a/apm-agent-plugins/apm-jsf-plugin/src/main/java/co/elastic/apm/agent/jsf/JsfLifecycleInstrumentation.java +++ b/apm-agent-plugins/apm-jsf-plugin/src/main/java/co/elastic/apm/agent/jsf/JsfLifecycleInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.jsf; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.impl.transaction.Transaction; @@ -35,7 +35,6 @@ import net.bytebuddy.matcher.ElementMatcher; import javax.annotation.Nullable; -import javax.faces.context.FacesContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -55,7 +54,7 @@ * Instruments javax.faces.lifecycle.Lifecycle#execute and javax.faces.lifecycle.Lifecycle#render. * Code is duplicated because it is injected inline */ -public abstract class JsfLifecycleInstrumentation extends ElasticApmInstrumentation { +public abstract class JsfLifecycleInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String SPAN_TYPE = "template"; private static final String SPAN_SUBTYPE = "jsf"; private static final String FRAMEWORK_NAME = "JavaServer Faces"; @@ -101,40 +100,38 @@ public static class JsfLifecycleExecuteAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static void createExecuteSpan(@Advice.Argument(0) javax.faces.context.FacesContext facesContext, @Advice.Local("span") Span span) { - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent == null) { + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { + return; + } + if (parent instanceof Span) { + Span parentSpan = (Span)parent; + if (SPAN_SUBTYPE.equals(parentSpan.getSubtype()) && SPAN_ACTION.equals(parentSpan.getAction())) { return; } - if (parent instanceof Span) { - Span parentSpan = (Span)parent; - if (SPAN_SUBTYPE.equals(parentSpan.getSubtype()) && SPAN_ACTION.equals(parentSpan.getAction())) { - return; - } - } - Transaction transaction = tracer.currentTransaction(); - if (transaction != null) { - try { - javax.faces.context.ExternalContext externalContext = facesContext.getExternalContext(); - if (externalContext != null) { - transaction.withName(externalContext.getRequestServletPath(), PRIO_HIGH_LEVEL_FRAMEWORK); - String pathInfo = externalContext.getRequestPathInfo(); - if (pathInfo != null) { - transaction.appendToName(pathInfo, PRIO_HIGH_LEVEL_FRAMEWORK); - } + } + Transaction transaction = tracer.currentTransaction(); + if (transaction != null) { + try { + javax.faces.context.ExternalContext externalContext = facesContext.getExternalContext(); + if (externalContext != null) { + transaction.withName(externalContext.getRequestServletPath(), PRIO_HIGH_LEVEL_FRAMEWORK); + String pathInfo = externalContext.getRequestPathInfo(); + if (pathInfo != null) { + transaction.appendToName(pathInfo, PRIO_HIGH_LEVEL_FRAMEWORK); } - transaction.setFrameworkName(FRAMEWORK_NAME); - } catch (Exception e) { - // do nothing- rely on the default servlet name logic } + transaction.setFrameworkName(FRAMEWORK_NAME); + } catch (Exception e) { + // do nothing- rely on the default servlet name logic } - span = parent.createSpan() - .withType(SPAN_TYPE) - .withSubtype(SPAN_SUBTYPE) - .withAction(SPAN_ACTION) - .withName("JSF Execute"); - span.activate(); } + span = parent.createSpan() + .withType(SPAN_TYPE) + .withSubtype(SPAN_SUBTYPE) + .withAction(SPAN_ACTION) + .withName("JSF Execute"); + span.activate(); } @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) @@ -179,24 +176,22 @@ public static class JsfLifecycleRenderAdvice { @SuppressWarnings("Duplicates") @Advice.OnMethodEnter(suppress = Throwable.class) public static void createRenderSpan(@Advice.Local("span") Span span) { - if (tracer != null) { - final AbstractSpan parent = tracer.getActive(); - if (parent == null) { + final AbstractSpan parent = tracer.getActive(); + if (parent == null) { + return; + } + if (parent instanceof Span) { + Span parentSpan = (Span)parent; + if (SPAN_SUBTYPE.equals(parentSpan.getSubtype()) && SPAN_ACTION.equals(parentSpan.getAction())) { return; } - if (parent instanceof Span) { - Span parentSpan = (Span)parent; - if (SPAN_SUBTYPE.equals(parentSpan.getSubtype()) && SPAN_ACTION.equals(parentSpan.getAction())) { - return; - } - } - span = parent.createSpan() - .withType(SPAN_TYPE) - .withSubtype(SPAN_SUBTYPE) - .withAction(SPAN_ACTION) - .withName("JSF Render"); - span.activate(); } + span = parent.createSpan() + .withType(SPAN_TYPE) + .withSubtype(SPAN_SUBTYPE) + .withAction(SPAN_ACTION) + .withName("JSF Render"); + span.activate(); } @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/BaseKafkaInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/BaseKafkaInstrumentation.java index c46ec4bba09..8b7699ba267 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/BaseKafkaInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/BaseKafkaInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.kafka; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.configuration.MessagingConfiguration; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -44,7 +44,7 @@ import static net.bytebuddy.matcher.ElementMatchers.not; @SuppressWarnings("rawtypes") -public abstract class BaseKafkaInstrumentation extends ElasticApmInstrumentation { +public abstract class BaseKafkaInstrumentation extends TracerAwareElasticApmInstrumentation { @SuppressWarnings({"WeakerAccess"}) @Nullable diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaConsumerInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaConsumerInstrumentation.java index 9450a9fcf44..0f9f6f2e949 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaConsumerInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaConsumerInstrumentation.java @@ -64,9 +64,6 @@ public static class KafkaConsumerAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) @Nullable public static Span pollStart() { - if (tracer == null) { - return null; - } final AbstractSpan activeSpan = tracer.getActive(); if (activeSpan == null) { diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerInstrumentation.java index 0c6173edc51..d01f3bfcbfe 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-base-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerInstrumentation.java @@ -79,9 +79,6 @@ public static class KafkaProducerAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static Callback beforeSend(@Advice.Argument(0) final ProducerRecord record, @Advice.Argument(1) @Nullable Callback callback) { - if (tracer == null) { - return callback; - } Span span = null; //noinspection ConstantConditions @@ -101,7 +98,7 @@ public static Callback beforeSend(@Advice.Argument(0) final ProducerRecord recor public static void afterSend(@Advice.Argument(0) final ProducerRecord record, @Advice.This final KafkaProducer thiz, @Advice.Thrown final Throwable throwable) { - final Span span = getActiveExitSpan(); + final Span span = tracer.getActiveExitSpan(); //noinspection ConstantConditions KafkaInstrumentationHelper helper = kafkaInstrHelperManager.getForClassLoaderOfClass(KafkaProducer.class); if (helper != null && span != null) { diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsIteratorInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsIteratorInstrumentation.java index 18dc0e1083c..dbeee66996e 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsIteratorInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsIteratorInstrumentation.java @@ -71,7 +71,7 @@ public static class ConsumerRecordsAdvice { @AssignTo.Return @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static Iterator wrapIterator(@Nullable @Advice.Return final Iterator iterator) { - if (tracer == null || !tracer.isRunning() || tracer.currentTransaction() != null) { + if (!tracer.isRunning() || tracer.currentTransaction() != null) { return iterator; } diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordListInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordListInstrumentation.java index 0dcfbef4217..899eeae21ba 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordListInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordListInstrumentation.java @@ -72,7 +72,7 @@ public static class ConsumerRecordsAdvice { @AssignTo.Return @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static List wrapRecordList(@Nullable @Advice.Return final List list) { - if (tracer == null || !tracer.isRunning() || tracer.currentTransaction() != null) { + if (!tracer.isRunning() || tracer.currentTransaction() != null) { return list; } diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordsInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordsInstrumentation.java index 49c0545c44f..c32a026ecd4 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordsInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/ConsumerRecordsRecordsInstrumentation.java @@ -70,7 +70,7 @@ public static class ConsumerRecordsAdvice { @AssignTo.Return @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static Iterable wrapIterable(@Nullable @Advice.Return final Iterable iterable) { - if (tracer == null || !tracer.isRunning() || tracer.currentTransaction() != null) { + if (!tracer.isRunning() || tracer.currentTransaction() != null) { return iterable; } diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerHeadersInstrumentation.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerHeadersInstrumentation.java index f73bf8c3115..ddff42c20ab 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerHeadersInstrumentation.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/KafkaProducerHeadersInstrumentation.java @@ -84,9 +84,6 @@ public static class KafkaProducerHeadersAdvice { public static Span beforeSend(@Advice.FieldValue("apiVersions") final ApiVersions apiVersions, @Advice.Argument(0) final ProducerRecord record, @Nullable @Advice.Argument(value = 1, readOnly = false) Callback callback) { - if (tracer == null) { - return null; - } Span span = null; //noinspection ConstantConditions diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsIterableWrapper.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsIterableWrapper.java index a3132125581..4de1c8f34dc 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsIterableWrapper.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsIterableWrapper.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsListWrapper.java b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsListWrapper.java index 6f02f3dc064..9ba8e589c9c 100644 --- a/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsListWrapper.java +++ b/apm-agent-plugins/apm-kafka-plugin/apm-kafka-headers-plugin/src/main/java/co/elastic/apm/agent/kafka/helper/ConsumerRecordsListWrapper.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/apm-agent-plugins/apm-log-correlation-plugin/src/test/java/co/elastic/apm/agent/mdc/MdcActivationListenerIT.java b/apm-agent-plugins/apm-log-correlation-plugin/src/test/java/co/elastic/apm/agent/mdc/MdcActivationListenerIT.java index 9b6b6ab90a2..d38d2f04e2b 100644 --- a/apm-agent-plugins/apm-log-correlation-plugin/src/test/java/co/elastic/apm/agent/mdc/MdcActivationListenerIT.java +++ b/apm-agent-plugins/apm-log-correlation-plugin/src/test/java/co/elastic/apm/agent/mdc/MdcActivationListenerIT.java @@ -29,8 +29,8 @@ import co.elastic.apm.agent.configuration.SpyConfiguration; import co.elastic.apm.agent.error.logging.Log4j2LoggerErrorCapturingInstrumentation; import co.elastic.apm.agent.error.logging.Slf4jLoggerErrorCapturingInstrumentation; -import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.ElasticApmTracerBuilder; +import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.transaction.Transaction; import co.elastic.apm.agent.logging.LoggingConfiguration; import net.bytebuddy.agent.ByteBuddyAgent; diff --git a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionAdvice.java b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionAdvice.java index 99a90542a19..b23525826b2 100644 --- a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionAdvice.java +++ b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionAdvice.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,8 +24,9 @@ */ package co.elastic.apm.agent.mongoclient; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; +import co.elastic.apm.agent.impl.GlobalTracer; +import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import com.mongodb.MongoNamespace; import com.mongodb.ServerAddress; @@ -48,7 +49,11 @@ public class ConnectionAdvice { public static Span onEnter(@Advice.This Connection thiz, @Advice.Argument(0) Object databaseOrMongoNamespace, @Advice.Argument(1) BsonDocument command) { - Span span = ElasticApmInstrumentation.createExitSpan(); + Span span = null; + final AbstractSpan activeSpan = GlobalTracer.get().getActive(); + if (activeSpan != null && !activeSpan.isExit()) { + span = activeSpan.createExitSpan(); + } if (span == null) { return null; diff --git a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionInstrumentation.java b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionInstrumentation.java index 895ffb1be27..76d0dc87e26 100644 --- a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionInstrumentation.java +++ b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/ConnectionInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.mongoclient; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import com.mongodb.MongoNamespace; @@ -73,7 +73,11 @@ public ElementMatcher getMethodMatcher() { public static Span onEnter(@Advice.This Connection thiz, @Advice.Argument(0) MongoNamespace namespace, @Advice.Origin("#m") String methodName) { - Span span = ElasticApmInstrumentation.createExitSpan(); + Span span = null; + final AbstractSpan activeSpan = tracer.getActive(); + if (activeSpan != null && !activeSpan.isExit()) { + span = activeSpan.createExitSpan(); + } if (span == null) { return null; diff --git a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/MongoClientInstrumentation.java b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/MongoClientInstrumentation.java index 420b930fb4d..ce8c7b9be80 100644 --- a/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/MongoClientInstrumentation.java +++ b/apm-agent-plugins/apm-mongoclient-plugin/src/main/java/co/elastic/apm/agent/mongoclient/MongoClientInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.mongoclient; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; @@ -36,7 +36,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; -public abstract class MongoClientInstrumentation extends ElasticApmInstrumentation { +public abstract class MongoClientInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcher() { diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttp3ClientInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttp3ClientInstrumentation.java index f54f7b586aa..4c67e79608b 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttp3ClientInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttp3ClientInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.okhttp; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.transaction.TextHeaderSetter; @@ -35,7 +35,7 @@ import java.util.Arrays; import java.util.Collection; -public abstract class AbstractOkHttp3ClientInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractOkHttp3ClientInstrumentation extends TracerAwareElasticApmInstrumentation { // We can refer OkHttp types thanks to type erasure @VisibleForAdvice diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttpClientInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttpClientInstrumentation.java index 047fbc188ca..9b5267cd3a9 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/AbstractOkHttpClientInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.okhttp; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.transaction.TextHeaderSetter; @@ -35,7 +35,7 @@ import java.util.Arrays; import java.util.Collection; -public abstract class AbstractOkHttpClientInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractOkHttpClientInstrumentation extends TracerAwareElasticApmInstrumentation { // We can refer OkHttp types thanks to type erasure @VisibleForAdvice diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientAsyncInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientAsyncInstrumentation.java index fec1731d496..77a458f2a50 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientAsyncInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientAsyncInstrumentation.java @@ -89,7 +89,7 @@ public static class OkHttpClient3ExecuteAdvice { public static Object[] onBeforeEnqueue(final @Advice.Origin Class clazz, final @Advice.FieldValue("originalRequest") @Nullable okhttp3.Request originalRequest, final @Advice.Argument(0) @Nullable Callback originalCallback) { - if (tracer == null || tracer.getActive() == null || callbackWrapperCreator == null) { + if (tracer.getActive() == null || callbackWrapperCreator == null) { return null; } diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientInstrumentation.java index 314b0c08ef9..f2fca7f7ab9 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttp3ClientInstrumentation.java @@ -67,7 +67,7 @@ public static class OkHttpClient3ExecuteAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static Object onBeforeExecute(final @Advice.FieldValue("originalRequest") @Nullable Object originalRequest) { - if (tracer == null || tracer.getActive() == null || !(originalRequest instanceof Request)) { + if (tracer.getActive() == null || !(originalRequest instanceof Request)) { return originalRequest; } diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientAsyncInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientAsyncInstrumentation.java index 6250bb2d497..8f162e02faa 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientAsyncInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientAsyncInstrumentation.java @@ -87,7 +87,7 @@ public static class OkHttpClient3ExecuteAdvice { public static Object[] onBeforeEnqueue(final @Advice.Origin Class clazz, final @Advice.FieldValue("originalRequest") @Nullable Request originalRequest, final @Advice.Argument(0) @Nullable Callback originalCallback) { - if (tracer == null || tracer.getActive() == null || callbackWrapperCreator == null) { + if (tracer.getActive() == null || callbackWrapperCreator == null) { return null; } diff --git a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientInstrumentation.java b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientInstrumentation.java index 9b665eea24e..81e5467605e 100644 --- a/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientInstrumentation.java +++ b/apm-agent-plugins/apm-okhttp-plugin/src/main/java/co/elastic/apm/agent/okhttp/OkHttpClientInstrumentation.java @@ -66,7 +66,7 @@ public static class OkHttpClientExecuteAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static Object onBeforeExecute(@Advice.FieldValue("originalRequest") @Nullable Object originalRequest) { - if (tracer == null || tracer.getActive() == null || !(originalRequest instanceof com.squareup.okhttp.Request)) { + if (tracer.getActive() == null || !(originalRequest instanceof Request)) { return originalRequest; } diff --git a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ApmSpanBuilderInstrumentation.java b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ApmSpanBuilderInstrumentation.java index 568d76f3995..911458a15e6 100644 --- a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ApmSpanBuilderInstrumentation.java +++ b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ApmSpanBuilderInstrumentation.java @@ -27,6 +27,7 @@ import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.sampling.ConstantSampler; import co.elastic.apm.agent.impl.sampling.Sampler; import co.elastic.apm.agent.impl.transaction.AbstractSpan; @@ -92,6 +93,7 @@ public static AbstractSpan doCreateTransactionOrSpan(@Nullable AbstractSpan> baggage, ClassLoader applicationClassLoader) { AbstractSpan result = null; + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer != null) { if (parentContext == null) { result = createTransaction(tags, operationName, microseconds, baggage, tracer, applicationClassLoader); diff --git a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ElasticApmTracerInstrumentation.java b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ElasticApmTracerInstrumentation.java index b4020acf2ed..13e0bb99cff 100644 --- a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ElasticApmTracerInstrumentation.java +++ b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ElasticApmTracerInstrumentation.java @@ -35,9 +35,7 @@ public class ElasticApmTracerInstrumentation extends OpenTracingBridgeInstrument @Advice.OnMethodExit(suppress = Throwable.class) public static void close() { - if (tracer != null) { - tracer.stop(); - } + tracer.stop(); } @Override diff --git a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ExternalSpanContextInstrumentation.java b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ExternalSpanContextInstrumentation.java index a54a1cad9dd..031533e416f 100644 --- a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ExternalSpanContextInstrumentation.java +++ b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ExternalSpanContextInstrumentation.java @@ -26,6 +26,8 @@ import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.TraceContext; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; @@ -121,6 +123,7 @@ public static String onExit(@Advice.FieldValue(value = "childTraceContext", typi @VisibleForAdvice @Nullable public static TraceContext parseTextMap(Iterable> textMap) { + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer != null) { TraceContext childTraceContext = TraceContext.with64BitId(tracer); if (TraceContext.>>getFromTraceContextTextHeaders().asChildOf(childTraceContext, textMap, OpenTracingTextMapBridge.instance())) { diff --git a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/OpenTracingBridgeInstrumentation.java b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/OpenTracingBridgeInstrumentation.java index be824970783..a838c99adb1 100644 --- a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/OpenTracingBridgeInstrumentation.java +++ b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/OpenTracingBridgeInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,12 +24,12 @@ */ package co.elastic.apm.agent.opentracing.impl; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import java.util.Collection; import java.util.Collections; -public abstract class OpenTracingBridgeInstrumentation extends ElasticApmInstrumentation { +public abstract class OpenTracingBridgeInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public boolean includeWhenInstrumentationIsDisabled() { return true; diff --git a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ScopeManagerInstrumentation.java b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ScopeManagerInstrumentation.java index f537aa52dae..ce8af3419f1 100644 --- a/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ScopeManagerInstrumentation.java +++ b/apm-agent-plugins/apm-opentracing-plugin/src/main/java/co/elastic/apm/agent/opentracing/impl/ScopeManagerInstrumentation.java @@ -26,6 +26,7 @@ import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; @@ -81,9 +82,6 @@ public CurrentSpanInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static Object getCurrentSpan() { - if (tracer == null) { - return null; - } return tracer.getActive(); } @@ -100,9 +98,6 @@ public CurrentTraceContextInstrumentation() { @VisibleForAdvice @Advice.OnMethodExit(suppress = Throwable.class) public static Object getCurrentTraceContext() { - if (tracer == null) { - return null; - } return tracer.getActive(); } diff --git a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/BaseProcessInstrumentation.java b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/BaseProcessInstrumentation.java index 4c4e6649861..62ba291bd95 100644 --- a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/BaseProcessInstrumentation.java +++ b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/BaseProcessInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.process; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import net.bytebuddy.matcher.ElementMatcher; import java.util.Collection; @@ -32,7 +32,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isBootstrapClassLoader; -public abstract class BaseProcessInstrumentation extends ElasticApmInstrumentation { +public abstract class BaseProcessInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public final ElementMatcher.Junction getClassLoaderMatcher() { diff --git a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/CommonsExecAsyncInstrumentation.java b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/CommonsExecAsyncInstrumentation.java index 4a26b800119..0df57b6233f 100644 --- a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/CommonsExecAsyncInstrumentation.java +++ b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/CommonsExecAsyncInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.process; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; import co.elastic.apm.agent.concurrent.JavaConcurrent; import net.bytebuddy.asm.Advice; @@ -49,7 +49,7 @@ * Instruments {@code org.apache.commons.exec.DefaultExecutor#createThread(Runnable, String)} and any direct subclass * that overrides it. */ -public class CommonsExecAsyncInstrumentation extends ElasticApmInstrumentation { +public class CommonsExecAsyncInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String DEFAULT_EXECUTOR_CLASS = "org.apache.commons.exec.DefaultExecutor"; // only known subclass of default implementation diff --git a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessExitInstrumentation.java b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessExitInstrumentation.java index e00f03e218b..4c777455996 100644 --- a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessExitInstrumentation.java +++ b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessExitInstrumentation.java @@ -24,6 +24,7 @@ */ package co.elastic.apm.agent.process; +import co.elastic.apm.agent.impl.GlobalTracer; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; @@ -74,7 +75,7 @@ public static class WaitForAdvice { @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false) public static void onExit(@Advice.This Process process) { - if (tracer == null || tracer.getActive() == null) { + if (tracer.getActive() == null) { return; } @@ -112,7 +113,7 @@ public static class DestroyAdvice { @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false) public static void onExit(@Advice.This Process process) { - if (tracer == null || tracer.getActive() == null) { + if (tracer.getActive() == null) { return; } diff --git a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessStartInstrumentation.java b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessStartInstrumentation.java index 5c7134e936e..530b63d98ce 100644 --- a/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessStartInstrumentation.java +++ b/apm-agent-plugins/apm-process-plugin/src/main/java/co/elastic/apm/agent/process/ProcessStartInstrumentation.java @@ -24,6 +24,7 @@ */ package co.elastic.apm.agent.process; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; @@ -63,9 +64,6 @@ public static void onExit(@Advice.This ProcessBuilder processBuilder, @Advice.Return Process process, @Advice.Thrown @Nullable Throwable t) { - if (tracer == null) { - return; - } AbstractSpan parentSpan = tracer.getActive(); if (parentSpan == null) { return; diff --git a/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameAdvice.java b/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameAdvice.java index 4af1d96b13c..60e4306ba99 100644 --- a/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameAdvice.java +++ b/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameAdvice.java @@ -24,9 +24,9 @@ */ package co.elastic.apm.agent.quartz.job; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Transaction; import co.elastic.apm.agent.util.VersionUtils; @@ -45,18 +45,18 @@ public class JobTransactionNameAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) private static void setTransactionName(@Advice.Argument(value = 0) @Nullable JobExecutionContext context, @SimpleMethodSignature String signature, @Advice.Origin Class clazz, @Advice.Local("transaction") Transaction transaction) { - if (ElasticApmInstrumentation.tracer != null) { - AbstractSpan active = ElasticApmInstrumentation.tracer.getActive(); + if (GlobalTracer.get() != null) { + AbstractSpan active = GlobalTracer.get().getActive(); if (context == null) { logger.warn("Cannot correctly name transaction for method {} because JobExecutionContext is null", signature); - transaction = ElasticApmInstrumentation.tracer.startRootTransaction(clazz.getClassLoader()); + transaction = GlobalTracer.get().startRootTransaction(clazz.getClassLoader()); if (transaction != null) { transaction.withName(signature) .withType(JobTransactionNameInstrumentation.TRANSACTION_TYPE) .activate(); } } else if (active == null) { - transaction = ElasticApmInstrumentation.tracer.startRootTransaction(clazz.getClassLoader()); + transaction = GlobalTracer.get().startRootTransaction(clazz.getClassLoader()); if (transaction != null) { transaction.withName(context.getJobDetail().getKey().toString()) .withType(JobTransactionNameInstrumentation.TRANSACTION_TYPE) diff --git a/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameInstrumentation.java b/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameInstrumentation.java index 09a95a58ac5..fb0573731e5 100644 --- a/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-quartz-job-plugin/src/main/java/co/elastic/apm/agent/quartz/job/JobTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.quartz.job; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.stacktrace.StacktraceConfiguration; import net.bytebuddy.description.NamedElement; @@ -44,7 +44,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; -public class JobTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class JobTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { public static final String TRANSACTION_TYPE = "scheduled"; public static final String INSTRUMENTATION_TYPE = "quartz"; diff --git a/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisInstrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisInstrumentation.java index 2a751519023..5632f38b33e 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisInstrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.jedis; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.redis.RedisSpanUtils; import net.bytebuddy.asm.Advice; @@ -45,7 +45,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.not; -public class JedisInstrumentation extends ElasticApmInstrumentation { +public class JedisInstrumentation extends TracerAwareElasticApmInstrumentation { @Advice.OnMethodEnter(suppress = Throwable.class) private static void beforeSendCommand(@Advice.This(typing = Assigner.Typing.DYNAMIC) BinaryJedis thiz, diff --git a/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisSpanNameInstrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisSpanNameInstrumentation.java index d4d0aaab127..d7c7812d358 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisSpanNameInstrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-jedis-plugin/src/main/java/co/elastic/apm/agent/redis/jedis/JedisSpanNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.jedis; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; import net.bytebuddy.asm.Advice; @@ -46,7 +46,7 @@ * it would otherwise be set to the {@link redis.clients.jedis.Jedis} client method name. * This is good enough as a default but we want all Redis clients to produce the same span names. */ -public class JedisSpanNameInstrumentation extends ElasticApmInstrumentation { +public class JedisSpanNameInstrumentation extends TracerAwareElasticApmInstrumentation { @Advice.OnMethodEnter private static void setSpanNameToRedisProtocolCommand(@Advice.Argument(1) Object command) { diff --git a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce34Instrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce34Instrumentation.java index cef7234f8e3..a453c4ee8a7 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce34Instrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce34Instrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.lettuce; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.impl.transaction.Span; @@ -37,7 +37,7 @@ import static co.elastic.apm.agent.bci.bytebuddy.CustomElementMatchers.classLoaderCanLoadClass; -public abstract class Lettuce34Instrumentation extends ElasticApmInstrumentation { +public abstract class Lettuce34Instrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice @SuppressWarnings("WeakerAccess") public static final WeakConcurrentMap, Span> commandToSpan = WeakMapSupplier.createMap(); diff --git a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StartSpanInstrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StartSpanInstrumentation.java index 46a022c8804..e3df3a6e0a1 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StartSpanInstrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StartSpanInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.lettuce; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.impl.transaction.Span; @@ -51,7 +51,7 @@ * * The context will be propagated via the Netty instrumentation */ -public class Lettuce5StartSpanInstrumentation extends ElasticApmInstrumentation { +public class Lettuce5StartSpanInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice @SuppressWarnings("WeakerAccess") diff --git a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StopSpanInstrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StopSpanInstrumentation.java index 31b16a7e0a3..993c1af61fc 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StopSpanInstrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-lettuce-plugin/src/main/java/co/elastic/apm/agent/redis/lettuce/Lettuce5StopSpanInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.lettuce; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.transaction.Span; import io.lettuce.core.protocol.RedisCommand; @@ -54,7 +54,7 @@ *
  • {@link RedisCommand#cancel()}
  • * */ -public abstract class Lettuce5StopSpanInstrumentation extends ElasticApmInstrumentation { +public abstract class Lettuce5StopSpanInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice public static final Logger logger = LoggerFactory.getLogger(Lettuce5StopSpanInstrumentation.class); diff --git a/apm-agent-plugins/apm-redis-plugin/apm-redis-common/src/main/java/co/elastic/apm/agent/redis/RedisSpanUtils.java b/apm-agent-plugins/apm-redis-plugin/apm-redis-common/src/main/java/co/elastic/apm/agent/redis/RedisSpanUtils.java index fa0ce888436..1d6e919ec5d 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-redis-common/src/main/java/co/elastic/apm/agent/redis/RedisSpanUtils.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-redis-common/src/main/java/co/elastic/apm/agent/redis/RedisSpanUtils.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; @@ -33,8 +33,8 @@ public class RedisSpanUtils { @Nullable public static Span createRedisSpan(String command) { - if (ElasticApmInstrumentation.tracer != null) { - AbstractSpan activeSpan = ElasticApmInstrumentation.tracer.getActive(); + if (GlobalTracer.get() != null) { + AbstractSpan activeSpan = GlobalTracer.get().getActive(); if (activeSpan != null) { if (activeSpan.isExit()) { return null; diff --git a/apm-agent-plugins/apm-redis-plugin/apm-redisson-plugin/src/main/java/co/elastic/apm/agent/redis/redisson/RedisConnectionInstrumentation.java b/apm-agent-plugins/apm-redis-plugin/apm-redisson-plugin/src/main/java/co/elastic/apm/agent/redis/redisson/RedisConnectionInstrumentation.java index 7adfe336385..b8c0365a418 100644 --- a/apm-agent-plugins/apm-redis-plugin/apm-redisson-plugin/src/main/java/co/elastic/apm/agent/redis/redisson/RedisConnectionInstrumentation.java +++ b/apm-agent-plugins/apm-redis-plugin/apm-redisson-plugin/src/main/java/co/elastic/apm/agent/redis/redisson/RedisConnectionInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.redis.redisson; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.impl.transaction.Span; import co.elastic.apm.agent.redis.RedisSpanUtils; import io.netty.channel.Channel; @@ -46,7 +46,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; -public class RedisConnectionInstrumentation extends ElasticApmInstrumentation { +public class RedisConnectionInstrumentation extends TracerAwareElasticApmInstrumentation { @Advice.OnMethodEnter private static void beforeSend(@Advice.This RedisConnection connection, diff --git a/apm-agent-plugins/apm-scala-concurrent-plugin/src/main/java/co/elastic/apm/agent/scala/concurrent/FutureInstrumentation.java b/apm-agent-plugins/apm-scala-concurrent-plugin/src/main/java/co/elastic/apm/agent/scala/concurrent/FutureInstrumentation.java index d40e56c57fe..5b468b16f71 100644 --- a/apm-agent-plugins/apm-scala-concurrent-plugin/src/main/java/co/elastic/apm/agent/scala/concurrent/FutureInstrumentation.java +++ b/apm-agent-plugins/apm-scala-concurrent-plugin/src/main/java/co/elastic/apm/agent/scala/concurrent/FutureInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.scala.concurrent; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentMap; @@ -40,7 +40,7 @@ import static net.bytebuddy.matcher.ElementMatchers.*; -public abstract class FutureInstrumentation extends ElasticApmInstrumentation { +public abstract class FutureInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice @SuppressWarnings("WeakerAccess") @@ -67,7 +67,7 @@ public ElementMatcher getMethodMatcher() { @Advice.OnMethodExit(suppress = Throwable.class) public static void onExit(@Advice.This Object thiz) { - final AbstractSpan context = getActive(); + final AbstractSpan context = tracer.getActive(); if (context != null) { promisesToContext.put(thiz, context); // this span might be ended before the Promise$Transformation#run method starts @@ -94,8 +94,8 @@ public ElementMatcher getMethodMatcher() { @Advice.OnMethodEnter(suppress = Throwable.class) public static void onEnter(@Advice.This Object thiz, @Nullable @Advice.Local("context") AbstractSpan context) { context = promisesToContext.remove(thiz); - if (tracer != null && context != null) { - tracer.activate(context); + if (context != null) { + context.activate(); // decrements the reference we incremented to avoid that the parent context gets recycled before the promise is run // because we have activated it, we can be sure it doesn't get recycled until we deactivate in the OnMethodExit advice context.decrementReferences(); @@ -104,8 +104,8 @@ public static void onEnter(@Advice.This Object thiz, @Nullable @Advice.Local("co @Advice.OnMethodExit(suppress = Throwable.class) public static void onExit(@Nullable @Advice.Local("context") AbstractSpan context) { - if (tracer != null && context != null) { - tracer.deactivate(context); + if (context != null) { + context.deactivate(); } } diff --git a/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/ScheduledTransactionNameInstrumentation.java b/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/ScheduledTransactionNameInstrumentation.java index 2b299194105..a47d602f1fe 100644 --- a/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/ScheduledTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/ScheduledTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.scheduled; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -49,7 +49,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; import static net.bytebuddy.matcher.ElementMatchers.named; -public class ScheduledTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class ScheduledTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice public static final Logger logger = LoggerFactory.getLogger(ScheduledTransactionNameInstrumentation.class); @@ -62,19 +62,17 @@ public ScheduledTransactionNameInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class) private static void setTransactionName(@SimpleMethodSignature String signature, @Advice.Origin Class clazz, @Advice.Local("transaction") Transaction transaction) { - if (tracer != null) { - AbstractSpan active = tracer.getActive(); - if (active == null) { - transaction = tracer.startRootTransaction(clazz.getClassLoader()); - if (transaction != null) { - transaction.withName(signature) - .withType("scheduled") - .activate(); - } - - } else { - logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); + AbstractSpan active = tracer.getActive(); + if (active == null) { + transaction = tracer.startRootTransaction(clazz.getClassLoader()); + if (transaction != null) { + transaction.withName(signature) + .withType("scheduled") + .activate(); } + + } else { + logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); } } diff --git a/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/TimerTaskInstrumentation.java b/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/TimerTaskInstrumentation.java index 411650273df..37cf2e6bce9 100644 --- a/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/TimerTaskInstrumentation.java +++ b/apm-agent-plugins/apm-scheduled-annotation-plugin/src/main/java/co/elastic/apm/agent/spring/scheduled/TimerTaskInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.scheduled; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -48,7 +48,7 @@ import static net.bytebuddy.matcher.ElementMatchers.hasSuperClass; import static net.bytebuddy.matcher.ElementMatchers.named; -public class TimerTaskInstrumentation extends ElasticApmInstrumentation { +public class TimerTaskInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String FRAMEWORK_NAME = "TimerTask"; @VisibleForAdvice @@ -62,19 +62,17 @@ public TimerTaskInstrumentation(ElasticApmTracer tracer) { @Advice.OnMethodEnter(suppress = Throwable.class) private static void setTransactionName(@SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature String signature, @Advice.Origin Class clazz, @Advice.Local("transaction") Transaction transaction) { - if (tracer != null) { - AbstractSpan active = tracer.getActive(); - if (active == null) { - transaction = tracer.startRootTransaction(clazz.getClassLoader()); - if (transaction != null) { - transaction.withName(signature) - .withType("scheduled") - .activate(); - transaction.setFrameworkName(FRAMEWORK_NAME); - } - } else { - logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); + AbstractSpan active = tracer.getActive(); + if (active == null) { + transaction = tracer.startRootTransaction(clazz.getClassLoader()); + if (transaction != null) { + transaction.withName(signature) + .withType("scheduled") + .activate(); + transaction.setFrameworkName(FRAMEWORK_NAME); } + } else { + logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active); } } diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AbstractServletInstrumentation.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AbstractServletInstrumentation.java index 72a40218a3b..2863600e257 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AbstractServletInstrumentation.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AbstractServletInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.servlet; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.bytebuddy.CustomElementMatchers; import net.bytebuddy.matcher.ElementMatcher; @@ -33,7 +33,7 @@ import static co.elastic.apm.agent.servlet.ServletInstrumentation.SERVLET_API; -public abstract class AbstractServletInstrumentation extends ElasticApmInstrumentation { +public abstract class AbstractServletInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public Collection getInstrumentationGroupNames() { diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AsyncInstrumentation.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AsyncInstrumentation.java index d2c889f497b..5d8add8b919 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AsyncInstrumentation.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/AsyncInstrumentation.java @@ -26,6 +26,7 @@ import co.elastic.apm.agent.bci.bytebuddy.postprocessor.AssignTo; import co.elastic.apm.agent.concurrent.JavaConcurrent; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.servlet.helper.AsyncContextAdviceHelperImpl; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.NamedElement; @@ -39,6 +40,7 @@ import javax.servlet.ServletResponse; import java.util.Arrays; import java.util.Collection; +import java.util.Objects; import static net.bytebuddy.matcher.ElementMatchers.hasSuperType; import static net.bytebuddy.matcher.ElementMatchers.isInterface; @@ -104,7 +106,7 @@ public Class getAdviceClass() { } public static class StartAsyncAdvice { - private static final AsyncContextAdviceHelper asyncHelper = new AsyncContextAdviceHelperImpl(tracer); + private static final AsyncContextAdviceHelper asyncHelper = new AsyncContextAdviceHelperImpl(GlobalTracer.requireTracerImpl()); @Advice.OnMethodExit(suppress = Throwable.class, inline = false) public static void onExitStartAsync(@Advice.Return AsyncContext asyncContext) { diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/RequestStreamRecordingInstrumentation.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/RequestStreamRecordingInstrumentation.java index 3f249ca45ed..fb61ca3e77d 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/RequestStreamRecordingInstrumentation.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/RequestStreamRecordingInstrumentation.java @@ -87,7 +87,7 @@ public static void onReadEnter(@Advice.This Object thiz) { @AssignTo.Return @Advice.OnMethodExit(suppress = Throwable.class, inline = false, onThrowable = Throwable.class) public static ServletInputStream afterGetInputStream(@Advice.Return @Nullable ServletInputStream inputStream) { - if (callDepth.isNestedCallAndDecrement() || tracer == null || inputStream == null) { + if (callDepth.isNestedCallAndDecrement() || inputStream == null) { return inputStream; } final Transaction transaction = tracer.currentTransaction(); diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletApiAdvice.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletApiAdvice.java index 1ddd6b51e04..192891f7a3d 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletApiAdvice.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletApiAdvice.java @@ -25,6 +25,8 @@ package co.elastic.apm.agent.servlet; import co.elastic.apm.agent.configuration.CoreConfiguration; +import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.Scope; import co.elastic.apm.agent.impl.context.Request; import co.elastic.apm.agent.impl.context.Response; @@ -48,7 +50,6 @@ import java.util.List; import java.util.Map; -import static co.elastic.apm.agent.bci.ElasticApmInstrumentation.tracer; import static co.elastic.apm.agent.servlet.ServletTransactionHelper.TRANSACTION_ATTRIBUTE; import static co.elastic.apm.agent.servlet.ServletTransactionHelper.determineServiceName; import static java.lang.Boolean.FALSE; @@ -60,8 +61,8 @@ public class ServletApiAdvice { private static final ServletTransactionCreationHelper servletTransactionCreationHelper; static { - servletTransactionHelper = new ServletTransactionHelper(tracer); - servletTransactionCreationHelper = new ServletTransactionCreationHelper(tracer); + servletTransactionHelper = new ServletTransactionHelper(GlobalTracer.requireTracerImpl()); + servletTransactionCreationHelper = new ServletTransactionCreationHelper(GlobalTracer.requireTracerImpl()); } private static final GlobalThreadLocal excluded = GlobalThreadLocal.get(ServletApiAdvice.class, "excluded", false); @@ -70,6 +71,7 @@ public class ServletApiAdvice { @Nullable @Advice.OnMethodEnter(suppress = Throwable.class, inline = false) public static Object onEnterServletService(@Advice.Argument(0) ServletRequest servletRequest) { + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer == null) { return null; } @@ -128,6 +130,7 @@ public static void onExitServletService(@Advice.Argument(0) ServletRequest servl @Advice.Enter @Nullable Object transactionOrScope, @Advice.Thrown @Nullable Throwable t, @Advice.This Object thiz) { + ElasticApmTracer tracer = GlobalTracer.getTracerImpl(); if (tracer == null) { return; } diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletTransactionHelper.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletTransactionHelper.java index e79361d6936..f91292127f3 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletTransactionHelper.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/ServletTransactionHelper.java @@ -24,9 +24,9 @@ */ package co.elastic.apm.agent.servlet; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.configuration.CoreConfiguration; import co.elastic.apm.agent.impl.ElasticApmTracer; +import co.elastic.apm.agent.impl.GlobalTracer; import co.elastic.apm.agent.impl.context.Request; import co.elastic.apm.agent.impl.context.Response; import co.elastic.apm.agent.impl.context.TransactionContext; @@ -70,7 +70,7 @@ public ServletTransactionHelper(ElasticApmTracer tracer) { } public static void determineServiceName(@Nullable String servletContextName, ClassLoader servletContextClassLoader, @Nullable String contextPath) { - if (ElasticApmInstrumentation.tracer == null || !nameInitialized.add(contextPath == null ? "null" : contextPath)) { + if (GlobalTracer.get() == null || !nameInitialized.add(contextPath == null ? "null" : contextPath)) { return; } @@ -88,7 +88,7 @@ public static void determineServiceName(@Nullable String servletContextName, Cla serviceName = contextPath.substring(1); } if (serviceName != null) { - ElasticApmInstrumentation.tracer.overrideServiceNameForClassLoader(servletContextClassLoader, serviceName); + GlobalTracer.get().overrideServiceNameForClassLoader(servletContextClassLoader, serviceName); } } diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/AsyncContextAdviceHelperImpl.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/AsyncContextAdviceHelperImpl.java index f3cc7926cf6..e5383d6e21c 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/AsyncContextAdviceHelperImpl.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/AsyncContextAdviceHelperImpl.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,6 +24,7 @@ */ package co.elastic.apm.agent.servlet.helper; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.transaction.Transaction; import co.elastic.apm.agent.objectpool.Allocator; @@ -48,7 +49,7 @@ public class AsyncContextAdviceHelperImpl implements AsyncInstrumentation.AsyncC private final ObjectPool asyncListenerObjectPool; private final ServletTransactionHelper servletTransactionHelper; - private final ElasticApmTracer tracer; + private final Tracer tracer; public AsyncContextAdviceHelperImpl(ElasticApmTracer tracer) { this.tracer = tracer; diff --git a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/ServletTransactionCreationHelper.java b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/ServletTransactionCreationHelper.java index 5f6b35cc70d..0af311f10b7 100644 --- a/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/ServletTransactionCreationHelper.java +++ b/apm-agent-plugins/apm-servlet-plugin/src/main/java/co/elastic/apm/agent/servlet/helper/ServletTransactionCreationHelper.java @@ -24,6 +24,7 @@ */ package co.elastic.apm.agent.servlet.helper; +import co.elastic.apm.agent.impl.Tracer; import co.elastic.apm.agent.impl.ElasticApmTracer; import co.elastic.apm.agent.impl.context.web.WebConfiguration; import co.elastic.apm.agent.impl.transaction.Transaction; @@ -39,7 +40,7 @@ public class ServletTransactionCreationHelper { private static final Logger logger = LoggerFactory.getLogger(ServletTransactionCreationHelper.class); - private final ElasticApmTracer tracer; + private final Tracer tracer; private final WebConfiguration webConfiguration; public ServletTransactionCreationHelper(ElasticApmTracer tracer) { diff --git a/apm-agent-plugins/apm-spring-resttemplate-plugin/src/main/java/co/elastic/apm/agent/resttemplate/SpringRestTemplateInstrumentation.java b/apm-agent-plugins/apm-spring-resttemplate-plugin/src/main/java/co/elastic/apm/agent/resttemplate/SpringRestTemplateInstrumentation.java index 2deadfc23a1..7298e1e20fe 100644 --- a/apm-agent-plugins/apm-spring-resttemplate-plugin/src/main/java/co/elastic/apm/agent/resttemplate/SpringRestTemplateInstrumentation.java +++ b/apm-agent-plugins/apm-spring-resttemplate-plugin/src/main/java/co/elastic/apm/agent/resttemplate/SpringRestTemplateInstrumentation.java @@ -24,8 +24,8 @@ */ package co.elastic.apm.agent.resttemplate; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; import co.elastic.apm.agent.bci.HelperClassManager; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.http.client.HttpClientHelper; import co.elastic.apm.agent.impl.ElasticApmTracer; @@ -55,7 +55,7 @@ import static net.bytebuddy.matcher.ElementMatchers.returns; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public class SpringRestTemplateInstrumentation extends ElasticApmInstrumentation { +public class SpringRestTemplateInstrumentation extends TracerAwareElasticApmInstrumentation { // We can refer Spring type thanks to type erasure @VisibleForAdvice @@ -102,7 +102,7 @@ public static class SpringRestTemplateAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) private static void beforeExecute(@Advice.This ClientHttpRequest request, @Advice.Local("span") Span span) { - if (tracer == null || tracer.getActive() == null) { + if (tracer.getActive() == null) { return; } final AbstractSpan parent = tracer.getActive(); diff --git a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ExceptionHandlerInstrumentation.java b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ExceptionHandlerInstrumentation.java index 4e1bc79042f..720f27a7983 100644 --- a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ExceptionHandlerInstrumentation.java +++ b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ExceptionHandlerInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.webmvc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; @@ -38,7 +38,7 @@ import static net.bytebuddy.matcher.ElementMatchers.returns; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; -public class ExceptionHandlerInstrumentation extends ElasticApmInstrumentation { +public class ExceptionHandlerInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public Class getAdviceClass() { diff --git a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringServiceNameInstrumentation.java b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringServiceNameInstrumentation.java index 9324d3ec724..4e93edcb5ce 100644 --- a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringServiceNameInstrumentation.java +++ b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringServiceNameInstrumentation.java @@ -11,9 +11,9 @@ * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.webmvc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.NamedElement; import net.bytebuddy.description.method.MethodDescription; @@ -40,7 +40,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public class SpringServiceNameInstrumentation extends ElasticApmInstrumentation { +public class SpringServiceNameInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcherPreFilter() { @@ -71,7 +71,7 @@ public static class SpringServiceNameAdvice { @Advice.OnMethodExit(suppress = Throwable.class) public static void afterInitPropertySources(@Advice.This WebApplicationContext applicationContext) { - if (tracer != null && applicationContext.getServletContext() != null) { + if (applicationContext.getServletContext() != null) { tracer.overrideServiceNameForClassLoader(applicationContext.getServletContext().getClassLoader(), applicationContext.getEnvironment().getProperty("spring.application.name")); } } diff --git a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringTransactionNameInstrumentation.java b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringTransactionNameInstrumentation.java index ac5a68e3b92..82541ff7ae4 100644 --- a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringTransactionNameInstrumentation.java +++ b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/SpringTransactionNameInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.webmvc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.transaction.Transaction; import co.elastic.apm.agent.util.VersionUtils; @@ -61,7 +61,7 @@ * Supports Spring MVC 3.x-5.x *

    */ -public class SpringTransactionNameInstrumentation extends ElasticApmInstrumentation { +public class SpringTransactionNameInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String FRAMEWORK_NAME = "Spring Web MVC"; @@ -108,9 +108,6 @@ public static class HandlerAdapterAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) static void setTransactionName(@Advice.Argument(2) Object handler) { - if (tracer == null) { - return; - } final Transaction transaction = tracer.currentTransaction(); if (transaction == null) { return; diff --git a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ViewRenderInstrumentation.java b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ViewRenderInstrumentation.java index e15894c356f..c9df39d695f 100644 --- a/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ViewRenderInstrumentation.java +++ b/apm-agent-plugins/apm-spring-webmvc-plugin/src/main/java/co/elastic/apm/agent/spring/webmvc/ViewRenderInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.spring.webmvc; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.impl.transaction.Span; @@ -46,7 +46,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; -public class ViewRenderInstrumentation extends ElasticApmInstrumentation { +public class ViewRenderInstrumentation extends TracerAwareElasticApmInstrumentation { private static final String SPAN_TYPE = "template"; private static final String SPAN_ACTION = "render"; @@ -63,7 +63,7 @@ public static class ViewRenderAdviceService { @Advice.OnMethodEnter(suppress = Throwable.class) public static void beforeExecute(@Advice.Local("span") @Nullable Span span, @Advice.This @Nullable Object thiz) { - if (tracer == null || tracer.getActive() == null) { + if (tracer.getActive() == null) { return; } final AbstractSpan parent = tracer.getActive(); diff --git a/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/HttpUrlConnectionInstrumentation.java b/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/HttpUrlConnectionInstrumentation.java index 554206c459d..b26b0b8a1a8 100644 --- a/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/HttpUrlConnectionInstrumentation.java +++ b/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/HttpUrlConnectionInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.urlconnection; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.bci.VisibleForAdvice; import co.elastic.apm.agent.collections.WeakMapSupplier; import co.elastic.apm.agent.http.client.HttpClientHelper; @@ -49,7 +49,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArguments; -public abstract class HttpUrlConnectionInstrumentation extends ElasticApmInstrumentation { +public abstract class HttpUrlConnectionInstrumentation extends TracerAwareElasticApmInstrumentation { @VisibleForAdvice public static final WeakConcurrentMap inFlightSpans = WeakMapSupplier.createMap(); @@ -81,7 +81,7 @@ public static class CreateSpanInstrumentation extends HttpUrlConnectionInstrumen public static Object enter(@Advice.This HttpURLConnection thiz, @Advice.FieldValue("connected") boolean connected, @Advice.Origin String signature) { - if (tracer == null || tracer.getActive() == null) { + if (tracer.getActive() == null) { return null; } Span span = inFlightSpans.get(thiz); diff --git a/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/SSLContextInstrumentation.java b/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/SSLContextInstrumentation.java index 04cc7e58879..1a36590ca52 100644 --- a/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/SSLContextInstrumentation.java +++ b/apm-agent-plugins/apm-urlconnection-plugin/src/main/java/co/elastic/apm/agent/urlconnection/SSLContextInstrumentation.java @@ -24,7 +24,7 @@ */ package co.elastic.apm.agent.urlconnection; -import co.elastic.apm.agent.bci.ElasticApmInstrumentation; +import co.elastic.apm.agent.bci.TracerAwareElasticApmInstrumentation; import co.elastic.apm.agent.util.ThreadUtils; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.method.MethodDescription; @@ -55,7 +55,7 @@ *
  • {@link SSLSocketFactory#getDefault()}
  • * */ -public class SSLContextInstrumentation extends ElasticApmInstrumentation { +public class SSLContextInstrumentation extends TracerAwareElasticApmInstrumentation { @Override public ElementMatcher getTypeMatcher() {