Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.micrometer.v1_5;

import io.opentelemetry.instrumentation.micrometer.v1_5.internal.MetricCallbackRegistrar;
import io.opentelemetry.javaagent.bootstrap.WeakRefConsumer;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

final class ClassLoaderScopedCallbackRegistrar implements MetricCallbackRegistrar {

static final ClassLoaderScopedCallbackRegistrar INSTANCE =
new ClassLoaderScopedCallbackRegistrar();

// Keep callbacks alive with the instrumentation module, not with the SDK.
private static final Set<Consumer<?>> retainedCallbacks =
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));

private ClassLoaderScopedCallbackRegistrar() {}

@Override
public <T> AutoCloseable register(
Consumer<T> callback, Function<Consumer<T>, AutoCloseable> buildWithCallback) {
WeakReference<Consumer<T>> callbackRef = new WeakReference<>(callback);
WeakRefConsumer<T> weakCallback = new WeakRefConsumer<>(callbackRef);
AutoCloseable sdkHandle = buildWithCallback.apply(weakCallback);
weakCallback.closeWhenCollected(sdkHandle);
retainedCallbacks.add(callback);
return () -> closeAndReleaseCallback(sdkHandle, callbackRef);
}

private static void closeAndReleaseCallback(
AutoCloseable sdkHandle, WeakReference<? extends Consumer<?>> callbackRef) throws Exception {
try {
sdkHandle.close();
} finally {
Consumer<?> callback = callbackRef.get();
if (callback != null) {
retainedCallbacks.remove(callback);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class MicrometerSingletons {
// The agent exposes this shared registry as a Spring Boot bean.
// Shutting down one Spring context must not close it for others.
Internal.setCloseDisabled(builder, true);
Internal.setMetricCallbackRegistrar(builder, ClassLoaderScopedCallbackRegistrar.INSTANCE);
Experimental.setPrometheusMode(
builder, config.get("prometheus_mode").getBoolean("enabled", false));
Experimental.setBaseTimeUnit(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.micrometer.v1_5;

import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat;

import io.micrometer.core.instrument.Metrics;
import io.opentelemetry.instrumentation.test.utils.GcUtils;
import io.opentelemetry.instrumentation.testing.junit.AgentInstrumentationExtension;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.time.Duration;
import org.assertj.core.api.AbstractIterableAssert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

class MicrometerCallbackGcCloseTest {

private static final String INSTRUMENTATION_NAME = "io.opentelemetry.micrometer-1.5";

@RegisterExtension
static final InstrumentationExtension testing = AgentInstrumentationExtension.create();

@Test
void callbackDoesNotRetainBundledMicrometerClassLoader() throws Exception {
String metricName = "test.micrometer.gc.close";
WeakReference<ClassLoader> loaderReference = registerGaugeInDisposableApp(metricName);

GcUtils.awaitGc(loaderReference, Duration.ofSeconds(10));
assertThat(loaderReference.get()).isNull();

testing.clearData();
testing.waitAndAssertMetrics(INSTRUMENTATION_NAME, metricName, AbstractIterableAssert::isEmpty);
}

@Test
void removingFunctionCounterReleasesCapturedObject() throws Exception {
String metricName = "test.micrometer.function-counter.release";
try (URLClassLoader appLoader = newAppClassLoader()) {
Class<?> registrar = appLoader.loadClass(MicrometerTestApp.class.getName());
Object[] registration;
Thread thread = Thread.currentThread();
ClassLoader originalContextClassLoader = thread.getContextClassLoader();
try {
thread.setContextClassLoader(null);
registration =
(Object[])
registrar
.getMethod("registerFunctionCounter", String.class)
.invoke(null, metricName);
} finally {
thread.setContextClassLoader(originalContextClassLoader);
}

Object meter = registration[0];
WeakReference<?> captured = (WeakReference<?>) registration[1];
testing.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
metric ->
metric.hasName(metricName).hasDoubleSumPointsSatisfying(point -> point.hasValue(42)));
assertThat(captured.get()).isNotNull();
assertThat(registrar.getMethod("remove", Object.class).invoke(null, meter)).isSameAs(meter);

GcUtils.awaitGc(captured, Duration.ofSeconds(10));
assertThat(meter).isNotNull();
assertThat(registrar.getClassLoader()).isSameAs(appLoader);
assertThat(appLoader.loadClass("io.micrometer.core.instrument.Metrics").getClassLoader())
.isSameAs(appLoader);

testing.clearData();
testing.waitAndAssertMetrics(
INSTRUMENTATION_NAME, metricName, AbstractIterableAssert::isEmpty);
}
}

private static WeakReference<ClassLoader> registerGaugeInDisposableApp(String metricName)
throws Exception {
try (URLClassLoader appLoader = newAppClassLoader()) {
Class<?> registrar = appLoader.loadClass(MicrometerTestApp.class.getName());
assertThat(registrar.getClassLoader()).isSameAs(appLoader);
assertThat(
Class.forName("io.micrometer.core.instrument.Metrics", false, appLoader)
.getClassLoader())
.isSameAs(appLoader);

Thread thread = Thread.currentThread();
ClassLoader originalContextClassLoader = thread.getContextClassLoader();
try {
thread.setContextClassLoader(null);
registrar.getMethod("registerGlobalGauge", String.class).invoke(null, metricName);
} finally {
thread.setContextClassLoader(originalContextClassLoader);
}

GcUtils.awaitGc(Duration.ofSeconds(10));
testing.clearData();
testing.waitAndAssertMetrics(
INSTRUMENTATION_NAME,
metric ->
metric
.hasName(metricName)
.hasDoubleGaugeSatisfying(
gauge -> gauge.hasPointsSatisfying(point -> point.hasValue(42))));

return new WeakReference<>(appLoader);
}
}

private static URLClassLoader newAppClassLoader() {
URL micrometerJar = Metrics.class.getProtectionDomain().getCodeSource().getLocation();
URL testClasses = MicrometerTestApp.class.getProtectionDomain().getCodeSource().getLocation();
return new ChildFirstAppClassLoader(
new URL[] {micrometerJar, testClasses},
MicrometerCallbackGcCloseTest.class.getClassLoader());
}

private static class ChildFirstAppClassLoader extends URLClassLoader {

ChildFirstAppClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}

@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loaded = findLoadedClass(name);
if (loaded != null) {
return loaded;
}
if (name.startsWith("io.micrometer.") || name.equals(MicrometerTestApp.class.getName())) {
try {
Class<?> type = findClass(name);
if (resolve) {
resolveClass(type);
}
return type;
} catch (ClassNotFoundException ignored) {
// fall through to parent
}
}
return super.loadClass(name, resolve);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.micrometer.v1_5;

import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicLong;

public final class MicrometerTestApp {

private static final AtomicLong VALUE = new AtomicLong(42);

public static void registerGlobalGauge(String metricName) {
// The global composite keeps its own strong reference to the gauge function.
Gauge.builder(metricName, VALUE, AtomicLong::doubleValue).register(Metrics.globalRegistry);
}

public static Object[] registerFunctionCounter(String metricName) {
MeterRegistry registry = Metrics.globalRegistry.getRegistries().iterator().next();
AtomicLong captured = new AtomicLong(42);
FunctionCounter counter =
FunctionCounter.builder(metricName, VALUE, ignored -> captured.get()).register(registry);
return new Object[] {counter, new WeakReference<>(captured)};
}

public static Object remove(Object meter) {
MeterRegistry registry = Metrics.globalRegistry.getRegistries().iterator().next();
return registry.remove((Meter) meter);
}

private MicrometerTestApp() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,17 @@
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.Measurement;
import io.micrometer.core.instrument.config.NamingConvention;
import io.opentelemetry.api.metrics.DoubleCounterBuilder;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.ObservableDoubleCounter;
import io.opentelemetry.instrumentation.micrometer.v1_5.internal.MetricCallbackRegistrar;
import io.opentelemetry.instrumentation.micrometer.v1_5.internal.OpenTelemetryInstrument;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.ToDoubleFunction;

final class OpenTelemetryFunctionCounter<T> extends AbstractMeter
implements FunctionCounter, RemovableMeter, OpenTelemetryInstrument {

private final ObservableDoubleCounter observableCount;
private final AutoCloseable countRegistration;
private final AtomicBoolean removed = new AtomicBoolean();

OpenTelemetryFunctionCounter(
Expand All @@ -32,19 +33,20 @@ final class OpenTelemetryFunctionCounter<T> extends AbstractMeter
T obj,
ToDoubleFunction<T> countFunction,
Meter otelMeter,
Bridging bridging) {
Bridging bridging,
MetricCallbackRegistrar callbackRegistrar) {
super(id);

String name = name(id, namingConvention);
observableCount =
DoubleCounterBuilder builder =
otelMeter
.counterBuilder(name)
.ofDoubles()
.setDescription(bridging.description(name, id))
.setUnit(baseUnit(id))
.buildWithCallback(
new DoubleMeasurementRecorder<>(
obj, countFunction, tagsAsAttributes(id, namingConvention)));
.setUnit(baseUnit(id));
DoubleMeasurementRecorder<T> callback =
new DoubleMeasurementRecorder<>(obj, countFunction, tagsAsAttributes(id, namingConvention));
countRegistration = callbackRegistrar.register(callback, builder::buildWithCallback);
}

@Override
Expand All @@ -64,6 +66,6 @@ public void onRemove() {
if (!removed.compareAndSet(false, true)) {
return;
}
observableCount.close();
RemovableMeter.close(countRegistration);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.TimeUtils;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleCounterBuilder;
import io.opentelemetry.api.metrics.LongCounterBuilder;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.ObservableDoubleCounter;
import io.opentelemetry.api.metrics.ObservableLongCounter;
import io.opentelemetry.instrumentation.micrometer.v1_5.internal.MetricCallbackRegistrar;
import io.opentelemetry.instrumentation.micrometer.v1_5.internal.OpenTelemetryInstrument;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
Expand All @@ -25,8 +26,8 @@
final class OpenTelemetryFunctionTimer<T> extends AbstractMeter
implements FunctionTimer, RemovableMeter, OpenTelemetryInstrument {
private final TimeUnit baseTimeUnit;
private final ObservableLongCounter observableCount;
private final ObservableDoubleCounter observableTotalTime;
private final AutoCloseable countRegistration;
private final AutoCloseable totalTimeRegistration;
private final AtomicBoolean removed = new AtomicBoolean();

OpenTelemetryFunctionTimer(
Expand All @@ -38,35 +39,39 @@ final class OpenTelemetryFunctionTimer<T> extends AbstractMeter
TimeUnit totalTimeFunctionUnit,
TimeUnit baseTimeUnit,
Meter otelMeter,
Bridging bridging) {
Bridging bridging,
MetricCallbackRegistrar callbackRegistrar) {
super(id);
this.baseTimeUnit = baseTimeUnit;

String name = Bridging.name(id, namingConvention);
Attributes attributes = Bridging.tagsAsAttributes(id, namingConvention);

this.observableCount =
LongCounterBuilder countBuilder =
otelMeter
.counterBuilder(name + ".count")
.setDescription(bridging.description(name + ".count", id))
.setUnit("{invocation}")
.buildWithCallback(new LongMeasurementRecorder<>(obj, countFunction, attributes));
.setUnit("{invocation}");
countRegistration =
callbackRegistrar.register(
new LongMeasurementRecorder<>(obj, countFunction, attributes),
countBuilder::buildWithCallback);

this.observableTotalTime =
DoubleCounterBuilder totalTimeBuilder =
otelMeter
.counterBuilder(name + ".sum")
.ofDoubles()
.setDescription(bridging.description(name + ".sum", id))
.setUnit(TimeUnitHelper.getUnitString(baseTimeUnit))
.buildWithCallback(
new DoubleMeasurementRecorder<>(
obj,
val ->
TimeUtils.convert(
totalTimeFunction.applyAsDouble(val),
totalTimeFunctionUnit,
baseTimeUnit),
attributes));
.setUnit(TimeUnitHelper.getUnitString(baseTimeUnit));
totalTimeRegistration =
callbackRegistrar.register(
new DoubleMeasurementRecorder<>(
obj,
val ->
TimeUtils.convert(
totalTimeFunction.applyAsDouble(val), totalTimeFunctionUnit, baseTimeUnit),
attributes),
totalTimeBuilder::buildWithCallback);
}

@Override
Expand Down Expand Up @@ -103,7 +108,7 @@ public void onRemove() {
if (!removed.compareAndSet(false, true)) {
return;
}
observableCount.close();
observableTotalTime.close();
RemovableMeter.close(countRegistration);
RemovableMeter.close(totalTimeRegistration);
}
}
Loading
Loading