Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix netty 4.1 instrumentation not removing future listeners #2851

Merged
merged 3 commits into from
Apr 27, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@

import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.implementsInterface;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.ClassLoaderMatcher.hasClassesNamed;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.isArray;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;

import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge;
import io.opentelemetry.javaagent.tooling.TypeInstrumentation;
import java.util.HashMap;
import java.util.Map;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
Expand All @@ -35,18 +38,74 @@ public ElementMatcher<TypeDescription> typeMatcher() {

@Override
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
return singletonMap(
Map<ElementMatcher.Junction<MethodDescription>, String> transformers = new HashMap<>();
transformers.put(
isMethod()
.and(named("addListener"))
.and(takesArgument(0, named("io.netty.util.concurrent.GenericFutureListener"))),
ChannelFutureInstrumentation.class.getName() + "$AddListenerAdvice");
transformers.put(
isMethod().and(named("addListeners")).and(takesArgument(0, isArray())),
ChannelFutureInstrumentation.class.getName() + "$AddListenersAdvice");
transformers.put(
isMethod()
.and(named("removeListener"))
.and(takesArgument(0, named("io.netty.util.concurrent.GenericFutureListener"))),
ChannelFutureInstrumentation.class.getName() + "$RemoveListenerAdvice");
transformers.put(
isMethod().and(named("removeListeners")).and(takesArgument(0, isArray())),
ChannelFutureInstrumentation.class.getName() + "$RemoveListenersAdvice");
return transformers;
}

public static class AddListenerAdvice {
@Advice.OnMethodEnter
public static void wrapListener(
@Advice.Argument(value = 0, readOnly = false) GenericFutureListener listener) {
listener = new WrappedFutureListener(Java8BytecodeBridge.currentContext(), listener);
@Advice.Argument(value = 0, readOnly = false)
GenericFutureListener<? extends Future<? super Void>> listener) {
listener = WrappedFutureListener.wrap(Java8BytecodeBridge.currentContext(), listener);
mateuszrzeszutek marked this conversation as resolved.
Show resolved Hide resolved
}
}

public static class AddListenersAdvice {
@Advice.OnMethodEnter
public static void wrapListener(
@Advice.Argument(value = 0, readOnly = false)
GenericFutureListener<? extends Future<? super Void>>[] listeners) {

Context context = Java8BytecodeBridge.currentContext();
@SuppressWarnings("unchecked")
GenericFutureListener<? extends Future<? super Void>>[] wrappedListeners =
new GenericFutureListener[listeners.length];
for (int i = 0; i < listeners.length; ++i) {
wrappedListeners[i] = WrappedFutureListener.wrap(context, listeners[i]);
}
listeners = wrappedListeners;
}
}

public static class RemoveListenerAdvice {
@Advice.OnMethodEnter
public static void wrapListener(
@Advice.Argument(value = 0, readOnly = false)
GenericFutureListener<? extends Future<? super Void>> listener) {
listener = WrappedFutureListener.getWrapper(listener);
}
}

public static class RemoveListenersAdvice {
@Advice.OnMethodEnter
public static void wrapListener(
@Advice.Argument(value = 0, readOnly = false)
GenericFutureListener<? extends Future<? super Void>>[] listeners) {

@SuppressWarnings("unchecked")
GenericFutureListener<? extends Future<? super Void>>[] wrappedListeners =
new GenericFutureListener[listeners.length];
for (int i = 0; i < listeners.length; ++i) {
wrappedListeners[i] = WrappedFutureListener.getWrapper(listeners[i]);
}
listeners = wrappedListeners;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,41 @@
import io.netty.util.concurrent.GenericFutureListener;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.instrumentation.api.caching.Cache;

public final class WrappedFutureListener<F extends Future<? super Void>>
mateuszrzeszutek marked this conversation as resolved.
Show resolved Hide resolved
implements GenericFutureListener<F> {

private static final Cache<GenericFutureListener<?>, WrappedFutureListener<?>> wrappers =
Copy link
Contributor

Choose a reason for hiding this comment

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

This seems like it can be InstrumentationContext instead of a map right?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, I thought about it too - I don't know how it'd work with lambdas or method references, and how costly adding a field to lots of listener classes would be. (It's a good idea for a benchmark though)

Copy link
Contributor

Choose a reason for hiding this comment

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

But isn't the weakmap a subset of InstrumentationContext? We use weakmap behind the scenes when not being able to add a field, and I figure when we can add the field it should basically work better.

Copy link
Contributor

Choose a reason for hiding this comment

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

One problem with InstrumentationContext is that it is incapable of handling cases when the same object is used in different contexts e.g. same runnable is submitted to executor multiple times. With wrappers it should be possible to handle such cases, though the current solution doesn't.

Copy link
Member Author

Choose a reason for hiding this comment

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

Okay, changed to InstrumentationContext.

One problem with InstrumentationContext is that it is incapable of handling cases when the same object is used in different contexts e.g. same runnable is submitted to executor multiple times.

Hmm, I guess that it's a separate InstrumentationContext problem that applies to the whole javaagent. We'd probably like to get it solved separately.

Copy link
Member

Choose a reason for hiding this comment

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

One problem with InstrumentationContext is that it is incapable of handling cases when the same object is used in different contexts e.g. same runnable is submitted to executor multiple times.

Oh, that's an interesting problem, hadn't thought about that... have you seen this cause issues in real world apps (yet)?

Cache.newBuilder().setWeakKeys().build();

@SuppressWarnings("unchecked")
public static <F extends Future<? super Void>> GenericFutureListener<F> wrap(
Context context, GenericFutureListener<F> delegate) {
if (delegate instanceof WrappedFutureListener) {
return delegate;
}
return (GenericFutureListener<F>)
wrappers.computeIfAbsent(delegate, k -> new WrappedFutureListener<>(context, delegate));
}

@SuppressWarnings("unchecked")
public static <F extends Future<? super Void>> GenericFutureListener<F> getWrapper(
GenericFutureListener<F> delegate) {
WrappedFutureListener<F> wrapper = (WrappedFutureListener<F>) wrappers.get(delegate);
return wrapper == null ? delegate : wrapper;
}

public class WrappedFutureListener implements GenericFutureListener {
private final Context context;
private final GenericFutureListener delegate;
private final GenericFutureListener<F> delegate;

public WrappedFutureListener(Context context, GenericFutureListener delegate) {
private WrappedFutureListener(Context context, GenericFutureListener<F> delegate) {
this.context = context;
this.delegate = delegate;
}

@Override
public void operationComplete(Future future) throws Exception {
public void operationComplete(F future) throws Exception {
try (Scope ignored = context.makeCurrent()) {
delegate.operationComplete(future);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

import io.netty.channel.embedded.EmbeddedChannel
import io.netty.util.concurrent.Future
import io.netty.util.concurrent.GenericFutureListener
import io.opentelemetry.instrumentation.test.AgentInstrumentationSpecification
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger

class ChannelFutureTest extends AgentInstrumentationSpecification {
// regression test for https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/2705
def "should clean up wrapped listeners"() {
given:
def channel = new EmbeddedChannel()
def counter = new AtomicInteger()

def listener1 = newListener(counter)
channel.closeFuture().addListener(listener1)
channel.closeFuture().removeListener(listener1)

def listener2 = newListener(counter)
def listener3 = newListener(counter)
channel.closeFuture().addListeners(listener2, listener3)
channel.closeFuture().removeListeners(listener2, listener3)

when:
channel.close().await(5, TimeUnit.SECONDS)

then:
counter.get() == 0
}

private static GenericFutureListener newListener(AtomicInteger counter) {
new GenericFutureListener() {
void operationComplete(Future future) throws Exception {
counter.incrementAndGet()
}
}
}
}