Skip to content

Commit

Permalink
Apply micrometer instrumentation to spring-boot-actuator apps (#5666)
Browse files Browse the repository at this point in the history
* Apply micrometer instrumentation to spring-boot-actuator apps

* fix a bug

* code review comments
  • Loading branch information
Mateusz Rzeszutek authored Mar 23, 2022
1 parent 990dad8 commit f2587ba
Show file tree
Hide file tree
Showing 15 changed files with 360 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.extendsClass;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.returns;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

import io.opentelemetry.javaagent.bootstrap.HelperResources;
Expand All @@ -24,9 +25,6 @@
/**
* Instruments {@link ClassLoader} to have calls to get resources intercepted and check our map of
* helper resources that is filled by instrumentation when they need helpers.
*
* <p>We currently only intercept {@link ClassLoader#getResources(String)} because this is the case
* we are currently always interested in, where it's used for service loading.
*/
public class ResourceInjectionInstrumentation implements TypeInstrumentation {

Expand All @@ -38,10 +36,35 @@ public ElementMatcher<TypeDescription> typeMatcher() {
@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
isMethod().and(named("getResources")).and(takesArguments(String.class)),
isMethod()
.and(named("getResource"))
.and(takesArguments(String.class))
.and(returns(URL.class)),
ResourceInjectionInstrumentation.class.getName() + "$GetResourceAdvice");
transformer.applyAdviceToMethod(
isMethod()
.and(named("getResources"))
.and(takesArguments(String.class))
.and(returns(Enumeration.class)),
ResourceInjectionInstrumentation.class.getName() + "$GetResourcesAdvice");
}

@SuppressWarnings("unused")
public static class GetResourceAdvice {

@Advice.OnMethodExit(suppress = Throwable.class)
public static void onExit(
@Advice.This ClassLoader classLoader,
@Advice.Argument(0) String name,
@Advice.Return(readOnly = false) URL resource) {

URL helper = HelperResources.load(classLoader, name);
if (helper != null) {
resource = helper;
}
}
}

@SuppressWarnings("unused")
public static class GetResourcesAdvice {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
plugins {
id("otel.javaagent-instrumentation")
}

muzzle {
pass {
group.set("org.springframework.boot")
module.set("spring-boot-actuator-autoconfigure")
versions.set("[2.0.0.RELEASE,)")
extraDependency("io.micrometer:micrometer-core:1.5.0")
assertInverse.set(true)
}
}

dependencies {
library("org.springframework.boot:spring-boot-actuator-autoconfigure:2.0.0.RELEASE")
library("io.micrometer:micrometer-core:1.5.0")

implementation(project(":instrumentation:micrometer:micrometer-1.5:javaagent"))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.returns;

import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import java.util.ArrayList;
import java.util.List;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

public class AutoConfigurationImportSelectorInstrumentation implements TypeInstrumentation {

@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("org.springframework.boot.autoconfigure.AutoConfigurationImportSelector");
}

@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
named("getCandidateConfigurations").and(returns(List.class)),
getClass().getName() + "$GetCandidateConfigurationsAdvice");
}

@SuppressWarnings("unused")
public static class GetCandidateConfigurationsAdvice {

@Advice.OnMethodExit(suppress = Throwable.class)
public static void onExit(@Advice.Return(readOnly = false) List<String> configurations) {
if (configurations.contains(
"org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration")) {
List<String> configs = new ArrayList<>(configurations.size() + 1);
configs.addAll(configurations);
// using class reference here so that muzzle will consider it a dependency of this advice
// and capture all references to spring & micrometer classes that it makes
configs.add(OpenTelemetryMeterRegistryAutoConfiguration.class.getName());
configurations = configs;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.opentelemetry.javaagent.instrumentation.micrometer.v1_5.MicrometerSingletons;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// CompositeMeterRegistryAutoConfiguration configures the "final" composite registry
@AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class)
// configure after the SimpleMeterRegistry has initialized; it is normally the last MeterRegistry
// implementation to be configured, as it's used as a fallback
// the OTel registry should be added in addition to that fallback and not replace it
@AutoConfigureAfter(SimpleMetricsExportAutoConfiguration.class)
@ConditionalOnBean(Clock.class)
@ConditionalOnClass(MeterRegistry.class)
public class OpenTelemetryMeterRegistryAutoConfiguration {

@Bean
public MeterRegistry otelMeterRegistry() {
return MicrometerSingletons.meterRegistry();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

import com.google.auto.service.AutoService;
import io.opentelemetry.instrumentation.api.config.Config;
import io.opentelemetry.javaagent.extension.ignore.IgnoredTypesBuilder;
import io.opentelemetry.javaagent.extension.ignore.IgnoredTypesConfigurer;

@AutoService(IgnoredTypesConfigurer.class)
public class SpringBootActuatorIgnoredTypesConfigurer implements IgnoredTypesConfigurer {

@Override
public void configure(Config config, IgnoredTypesBuilder builder) {
builder.allowClass("org.springframework.boot.autoconfigure.AutoConfigurationImportSelector");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

import static java.util.Collections.singletonList;

import com.google.auto.service.AutoService;
import io.opentelemetry.javaagent.extension.instrumentation.HelperResourceBuilder;
import io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import java.util.List;

@AutoService(InstrumentationModule.class)
public class SpringBootActuatorInstrumentationModule extends InstrumentationModule {

public SpringBootActuatorInstrumentationModule() {
super("spring-boot-actuator-autoconfigure", "spring-boot-actuator-autoconfigure-2.0");
}

@Override
public void registerHelperResources(HelperResourceBuilder helperResourceBuilder) {
// autoconfigure classes are loaded as resources using ClassPathResource
// this line will make OpenTelemetryMeterRegistryAutoConfiguration available to all
// classloaders, so that the bean classloader (different than the instrumented classloader) can
// load it
helperResourceBuilder.registerForAllClassLoaders(
"io/opentelemetry/javaagent/instrumentation/spring/actuator/OpenTelemetryMeterRegistryAutoConfiguration.class");
}

@Override
public List<TypeInstrumentation> typeInstrumentations() {
return singletonList(new AutoConfigurationImportSelectorInstrumentation());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

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

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.opentelemetry.instrumentation.testing.internal.AutoCleanupExtension;
import io.opentelemetry.instrumentation.testing.junit.AgentInstrumentationExtension;
import io.opentelemetry.instrumentation.testing.junit.InstrumentationExtension;
import io.opentelemetry.javaagent.instrumentation.spring.actuator.SpringApp.TestBean;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;

class ActuatorTest {

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

@RegisterExtension static final AutoCleanupExtension cleanup = AutoCleanupExtension.create();

@Test
void shouldInjectOtelMeterRegistry() {
SpringApplication app = new SpringApplication(SpringApp.class);
ConfigurableApplicationContext context = app.run();
cleanup.deferCleanup(context);

TestBean testBean = context.getBean(TestBean.class);
testBean.inc();

testing.waitAndAssertMetrics(
"io.opentelemetry.micrometer-1.5",
"test-counter",
metrics ->
metrics.anySatisfy(
metric ->
assertThat(metric)
.hasUnit("thingies")
.hasDoubleSum()
.isMonotonic()
.points()
.satisfiesExactly(
point ->
assertThat(point)
.hasValue(1)
.attributes()
.containsOnly(attributeEntry("tag", "value")))));

MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
assertThat(meterRegistry).isNotNull().isInstanceOf(CompositeMeterRegistry.class);
assertThat(((CompositeMeterRegistry) meterRegistry).getRegistries())
.anyMatch(r -> r.getClass().getSimpleName().equals("OpenTelemetryMeterRegistry"))
.anyMatch(r -> r.getClass().getSimpleName().equals("SimpleMeterRegistry"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.javaagent.instrumentation.spring.actuator;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringApp {

@Bean
public TestBean testBean(MeterRegistry meterRegistry) {
return new TestBean(meterRegistry);
}

public static class TestBean {
private final Counter counter;

public TestBean(MeterRegistry registry) {
this.counter =
Counter.builder("test-counter")
.baseUnit("thingies")
.tags("tag", "value")
.register(registry);
}

public void inc() {
counter.increment();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,35 @@
public final class HelperResources {

private static final Cache<ClassLoader, Map<String, URL>> RESOURCES = Cache.weak();
private static final Map<String, URL> ALL_CLASSLOADERS_RESOURCES = new ConcurrentHashMap<>();

/** Registers the {@code payload} to be available to instrumentation at {@code path}. */
/**
* Registers the {@code url} to be available to instrumentation at {@code path}, when given {@code
* classLoader} attempts to load that resource.
*/
public static void register(ClassLoader classLoader, String path, URL url) {
RESOURCES.computeIfAbsent(classLoader, unused -> new ConcurrentHashMap<>()).put(path, url);
}

/** Registers the {@code url} to be available to instrumentation at {@code path}. */
public static void registerForAllClassLoaders(String path, URL url) {
ALL_CLASSLOADERS_RESOURCES.putIfAbsent(path, url);
}

/**
* Returns a {@link URL} that can be used to retrieve the content of the resource at {@code path},
* or {@code null} if no resource could be found at {@code path}.
*/
public static URL load(ClassLoader classLoader, String path) {
Map<String, URL> map = RESOURCES.get(classLoader);
if (map == null) {
return null;
URL resource = null;
if (map != null) {
resource = map.get(path);
}

return map.get(path);
if (resource == null) {
resource = ALL_CLASSLOADERS_RESOURCES.get(path);
}
return resource;
}

private HelperResources() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,29 @@ default void register(String resourcePath) {
* the resource
*/
void register(String applicationResourcePath, String agentResourcePath);

/**
* Registers a resource to be injected into all class loaders in the instrumented application.
*
* <p>This is a convenience method for {@code registerForAllClassLoaders(resourcePath,
* resourcePath)}.
*/
default void registerForAllClassLoaders(String resourcePath) {
registerForAllClassLoaders(resourcePath, resourcePath);
}

/**
* Registers a resource to be injected into all class loaders in the instrumented application.
*
* <p>{@code agentResourcePath} can be the same as {@code applicationResourcePath}, but it is
* often desirable to use a slightly different path for {@code agentResourcePath}, so that
* multiple versions of an instrumentation (each injecting their own version of the resource) can
* co-exist inside the agent jar file.
*
* @param applicationResourcePath the path in the user's class loader at which to inject the
* resource
* @param agentResourcePath the path in the agent class loader from which to get the content for
* the resource
*/
void registerForAllClassLoaders(String applicationResourcePath, String agentResourcePath);
}
Loading

0 comments on commit f2587ba

Please sign in to comment.