Skip to content

Commit

Permalink
Use app's thread context class loader for callbacks into app (#9000)
Browse files Browse the repository at this point in the history
  • Loading branch information
trask authored Aug 9, 2023
1 parent bf000fe commit aab8817
Show file tree
Hide file tree
Showing 6 changed files with 229 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@ final class DoubleMeasurementRecorder<T> implements Consumer<ObservableDoubleMea
private final WeakReference<T> objWeakRef;
private final ToDoubleFunction<T> metricFunction;
private final Attributes attributes;
private final WeakReference<ClassLoader> contextClassLoader;

DoubleMeasurementRecorder(
@Nullable T obj, ToDoubleFunction<T> metricFunction, Attributes attributes) {
this.objWeakRef = new WeakReference<>(obj);
this.metricFunction = metricFunction;
this.attributes = attributes;
contextClassLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader());
}

@Override
public void accept(ObservableDoubleMeasurement measurement) {
T obj = objWeakRef.get();
if (obj != null) {
measurement.record(metricFunction.applyAsDouble(obj), attributes);
MeasurementRecorderUtil.runInThreadContextClassLoader(
contextClassLoader.get(),
() -> measurement.record(metricFunction.applyAsDouble(obj), attributes));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@ final class LongMeasurementRecorder<T> implements Consumer<ObservableLongMeasure
private final WeakReference<T> objWeakRef;
private final ToLongFunction<T> metricFunction;
private final Attributes attributes;
private final WeakReference<ClassLoader> contextClassLoader;

LongMeasurementRecorder(
@Nullable T obj, ToLongFunction<T> metricFunction, Attributes attributes) {
this.objWeakRef = new WeakReference<>(obj);
this.metricFunction = metricFunction;
this.attributes = attributes;
contextClassLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader());
}

@Override
public void accept(ObservableLongMeasurement measurement) {
T obj = objWeakRef.get();
if (obj != null) {
measurement.record(metricFunction.applyAsLong(obj), attributes);
MeasurementRecorderUtil.runInThreadContextClassLoader(
contextClassLoader.get(),
() -> measurement.record(metricFunction.applyAsLong(obj), attributes));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.micrometer.v1_5;

class MeasurementRecorderUtil {

static void runInThreadContextClassLoader(ClassLoader loader, Runnable runnable) {
ClassLoader prior = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(loader);
try {
runnable.run();
} finally {
Thread.currentThread().setContextClassLoader(prior);
}
}

private MeasurementRecorderUtil() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.Metrics;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.atomic.AtomicLong;
import org.assertj.core.api.AbstractIterableAssert;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -30,7 +32,7 @@ void cleanupMeters() {
final AtomicLong anotherNum = new AtomicLong(13);

@Test
void testFunctionCounter() throws InterruptedException {
void testFunctionCounter() {
// given
FunctionCounter counter =
FunctionCounter.builder("testFunctionCounter", num, AtomicLong::get)
Expand Down Expand Up @@ -68,6 +70,61 @@ void testFunctionCounter() throws InterruptedException {
INSTRUMENTATION_NAME, "testFunctionCounter", AbstractIterableAssert::isEmpty);
}

@Test
void testFunctionCounterDependingOnThreadContextClassLoader() {
// given
ClassLoader dummy = new URLClassLoader(new URL[0]);
ClassLoader prior = Thread.currentThread().getContextClassLoader();
FunctionCounter counter;
try {
Thread.currentThread().setContextClassLoader(dummy);
counter =
FunctionCounter.builder(
"testFunctionCounter",
num,
num -> {
// will throw an exception before value is reported if assertion fails
// then we assert below that value was reported
assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(dummy);
return num.get();
})
.description("This is a test function counter")
.tags("tag", "value")
.baseUnit("items")
.register(Metrics.globalRegistry);
} finally {
Thread.currentThread().setContextClassLoader(prior);
}

// then
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
"testFunctionCounter",
metrics ->
metrics.anySatisfy(
metric ->
assertThat(metric)
.hasDescription("This is a test function counter")
.hasUnit("items")
.hasDoubleSumSatisfying(
sum ->
sum.hasPointsSatisfying(
point ->
point
.hasValue(12)
.hasAttributes(attributeEntry("tag", "value"))))));

// when
Metrics.globalRegistry.remove(counter);
testing().clearData();

// then
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME, "testFunctionCounter", AbstractIterableAssert::isEmpty);
}

@Test
void functionCountersWithSameNameAndDifferentTags() {
// given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import io.micrometer.core.instrument.Metrics;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.TimeUnit;
import org.assertj.core.api.AbstractIterableAssert;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -97,6 +99,89 @@ void testFunctionTimer() {
INSTRUMENTATION_NAME, "testFunctionTimer.count", AbstractIterableAssert::isEmpty);
}

@Test
void testFunctionTimerDependingOnThreadContextClassLoader() {
// given
ClassLoader dummy = new URLClassLoader(new URL[0]);
ClassLoader prior = Thread.currentThread().getContextClassLoader();
FunctionTimer functionTimer;
try {
Thread.currentThread().setContextClassLoader(dummy);
functionTimer =
FunctionTimer.builder(
"testFunctionTimer",
timerObj,
timerObj -> {
// will throw an exception before value is reported if assertion fails
// then we assert below that value was reported
assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(dummy);
return timerObj.getCount();
},
timerObj -> {
// will throw an exception before value is reported if assertion fails
// then we assert below that value was reported
assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(dummy);
return timerObj.getTotalTimeNanos();
},
TimeUnit.NANOSECONDS)
.description("This is a test function timer")
.tags("tag", "value")
.register(Metrics.globalRegistry);
} finally {
Thread.currentThread().setContextClassLoader(prior);
}

// when
timerObj.add(42, TimeUnit.SECONDS);

// then
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
"testFunctionTimer.count",
metrics ->
metrics.anySatisfy(
metric ->
assertThat(metric)
.hasDescription("This is a test function timer")
.hasUnit("{invocation}")
.hasLongSumSatisfying(
sum ->
sum.isMonotonic()
.hasPointsSatisfying(
point ->
point
.hasValue(1)
.hasAttributes(
attributeEntry("tag", "value"))))));
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
"testFunctionTimer.sum",
metrics ->
metrics.anySatisfy(
metric ->
assertThat(metric)
.hasDescription("This is a test function timer")
.hasUnit("s")
.hasDoubleSumSatisfying(
sum ->
sum.hasPointsSatisfying(
point ->
point
.hasValue(42)
.hasAttributes(attributeEntry("tag", "value"))))));

// when
Metrics.globalRegistry.remove(functionTimer);
testing().clearData();

// then
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME, "testFunctionTimer.count", AbstractIterableAssert::isEmpty);
}

@Test
void testNanoPrecision() {
// given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import io.micrometer.core.instrument.Metrics;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.atomic.AtomicLong;
import org.assertj.core.api.AbstractIterableAssert;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -59,6 +61,59 @@ void testGauge() {
.waitAndAssertMetrics(INSTRUMENTATION_NAME, "testGauge", AbstractIterableAssert::isEmpty);
}

@Test
void testGaugeDependingOnThreadContextClassLoader() {
// given
ClassLoader dummy = new URLClassLoader(new URL[0]);
ClassLoader prior = Thread.currentThread().getContextClassLoader();
Gauge gauge;
try {
Thread.currentThread().setContextClassLoader(dummy);
gauge =
Gauge.builder(
"testGauge",
() -> {
// will throw an exception before value is reported if assertion fails
// then we assert below that value was reported
assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(dummy);
return 42;
})
.description("This is a test gauge")
.tags("tag", "value")
.baseUnit("items")
.register(Metrics.globalRegistry);
} finally {
Thread.currentThread().setContextClassLoader(prior);
}

// then
testing()
.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
"testGauge",
metrics ->
metrics.anySatisfy(
metric ->
assertThat(metric)
.hasDescription("This is a test gauge")
.hasUnit("items")
.hasDoubleGaugeSatisfying(
doubleGauge ->
doubleGauge.hasPointsSatisfying(
point ->
point
.hasValue(42)
.hasAttributes(attributeEntry("tag", "value"))))));

// when
Metrics.globalRegistry.remove(gauge);
testing().clearData();

// then
testing()
.waitAndAssertMetrics(INSTRUMENTATION_NAME, "testGauge", AbstractIterableAssert::isEmpty);
}

@Test
void gaugesWithSameNameAndDifferentTags() {
// given
Expand Down

0 comments on commit aab8817

Please sign in to comment.