|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.javaagent.instrumentation.v23_11; |
| 7 | + |
| 8 | +import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasClassesNamed; |
| 9 | +import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasSuperType; |
| 10 | +import static net.bytebuddy.matcher.ElementMatchers.isMethod; |
| 11 | +import static net.bytebuddy.matcher.ElementMatchers.named; |
| 12 | + |
| 13 | +import io.opentelemetry.context.Context; |
| 14 | +import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; |
| 15 | +import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; |
| 16 | +import net.bytebuddy.asm.Advice; |
| 17 | +import net.bytebuddy.description.type.TypeDescription; |
| 18 | +import net.bytebuddy.matcher.ElementMatcher; |
| 19 | + |
| 20 | +public class GenStreamingServerDispatcherInstrumentation implements TypeInstrumentation { |
| 21 | + @Override |
| 22 | + public ElementMatcher<TypeDescription> typeMatcher() { |
| 23 | + return hasSuperType(named("com.twitter.finagle.http.GenStreamingSerialServerDispatcher")); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public ElementMatcher<ClassLoader> classLoaderOptimization() { |
| 28 | + return hasClassesNamed("com.twitter.finagle.http.GenStreamingSerialServerDispatcher"); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public void transform(TypeTransformer transformer) { |
| 33 | + transformer.applyAdviceToMethod( |
| 34 | + isMethod().and(named("loop")), |
| 35 | + GenStreamingServerDispatcherInstrumentation.class.getName() + "$LoopAdvice"); |
| 36 | + } |
| 37 | + |
| 38 | + @SuppressWarnings("unused") |
| 39 | + public static class LoopAdvice { |
| 40 | + |
| 41 | + @Advice.OnMethodEnter(suppress = Throwable.class) |
| 42 | + public static void methodEnter() { |
| 43 | + // this works bc at this point in the server evaluation, the netty |
| 44 | + // instrumentation has already gone to work and assigned the context to the |
| 45 | + // local thread; |
| 46 | + // |
| 47 | + // this works specifically in finagle's netty stack bc at this point the loop() |
| 48 | + // method is running on a netty thread with the necessary access to the |
| 49 | + // java-native ThreadLocal where the Context is stored |
| 50 | + Helpers.CONTEXT_LOCAL.update(Context.current()); |
| 51 | + } |
| 52 | + |
| 53 | + @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class) |
| 54 | + public static void methodExit(@Advice.Thrown Throwable thrown) { |
| 55 | + // always clear this |
| 56 | + Helpers.CONTEXT_LOCAL.clear(); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments