GH-3376: Remove gauges on application ctx close (#3377)

* GH-3376: Remove gauges on application ctx close

Fixes https://github.com/spring-projects/spring-integration/issues/3376

The `MeterRegistry` may request meters on application shutdown.
The gauges for channels, handlers and message sources don't make sense
at the moment since all those beans are going to be destroyed.

* Remove gauges for channel, handler and message source numbers from the
`IntegrationManagementConfigurer.destroy()`

**Cherry-pick to 5.3.x & 5.2.x**

* * Add `MicrometerImportSelector` to conditionally load
a  `MicrometerMetricsCaptorConfiguration` when `MeterRegistry`
is on class path.
* Make `MicrometerMetricsCaptorConfiguration.integrationMicrometerMetricsCaptor()`
 bean dependant on the `ObjectProvider<MeterRegistry>`
* Make `IntegrationManagementConfiguration.managementConfigurer()`
dependant on the `ObjectProvider<MetricsCaptor>`.
This way the `IntegrationManagementConfigurer` is destroyed before
`MeterRegistry` when application context is closed
* Deprecate `MicrometerMetricsCaptor.loadCaptor()` in favor of
`@Import(MicrometerImportSelector.class)`

* * Add `MicrometerMetricsCaptorRegistrar` to register a `MICROMETER_CAPTOR_NAME`
bean when `MeterRegistry` is on class path and no `MICROMETER_CAPTOR_NAME` bean yet.
* Make `IntegrationManagementConfiguration.managementConfigurer()`
dependant on the `ObjectProvider<MetricsCaptor>`.
This way the `IntegrationManagementConfigurer` is destroyed before
`MeterRegistry` when application context is closed
* Deprecate `MicrometerMetricsCaptor.loadCaptor()` in favor of
`@Import(MicrometerMetricsCaptorRegistrar.class)`
* Fix test to make a `MeterRegistry` bean as `static` since
`@EnableIntegrationManagement` depends on this bean definition now

# Conflicts:
#	spring-integration-core/src/main/java/org/springframework/integration/config/EnableIntegrationManagement.java
#	spring-integration-core/src/main/java/org/springframework/integration/config/IntegrationManagementConfiguration.java
#	spring-integration-core/src/main/java/org/springframework/integration/config/IntegrationManagementConfigurer.java

* Fix some deprecation warnings
This commit is contained in:
Artem Bilan
2020-09-16 10:32:39 -04:00
parent 411e9945c3
commit d0cab670eb
12 changed files with 146 additions and 52 deletions

View File

@@ -24,6 +24,7 @@ import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;
import org.springframework.integration.support.management.micrometer.MicrometerMetricsCaptorRegistrar;
/**
* Enables default configuring of management in Spring Integration components in an existing application.
@@ -32,13 +33,14 @@ import org.springframework.core.annotation.AliasFor;
* bean is defined under the name {@code integrationManagementConfigurer}.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 4.2
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(IntegrationManagementConfiguration.class)
@Import({ MicrometerMetricsCaptorRegistrar.class, IntegrationManagementConfiguration.class })
public @interface EnableIntegrationManagement {
/**

View File

@@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
@@ -30,6 +31,7 @@ import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.integration.support.management.metrics.MetricsCaptor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -67,13 +69,15 @@ public class IntegrationManagementConfiguration implements ImportAware, Environm
@SuppressWarnings("deprecation")
@Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public IntegrationManagementConfigurer managementConfigurer() {
public IntegrationManagementConfigurer managementConfigurer(ObjectProvider<MetricsCaptor> metricsCaptorProvider) {
IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer();
setupCountsEnabledNamePatterns(configurer);
setupStatsEnabledNamePatterns(configurer);
configurer.setDefaultLoggingEnabled(
Boolean.parseBoolean(this.environment.resolvePlaceholders(
(String) this.attributes.get("defaultLoggingEnabled"))));
configurer.setMetricsCaptor(metricsCaptorProvider.getIfUnique());
configurer.setDefaultCountsEnabled(
Boolean.parseBoolean(this.environment.resolvePlaceholders(
(String) this.attributes.get("defaultCountsEnabled"))));

View File

@@ -18,14 +18,17 @@ package org.springframework.integration.config;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.context.ApplicationContext;
@@ -33,13 +36,13 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.support.management.IntegrationManagement;
import org.springframework.integration.support.management.IntegrationManagement.ManagementOverrides;
import org.springframework.integration.support.management.metrics.MeterFacade;
import org.springframework.integration.support.management.metrics.MetricsCaptor;
import org.springframework.integration.support.management.micrometer.MicrometerMetricsCaptor;
import org.springframework.integration.support.utils.PatternMatchUtils;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
@@ -58,12 +61,14 @@ import org.springframework.util.StringUtils;
@SuppressWarnings("deprecation")
public class IntegrationManagementConfigurer
implements SmartInitializingSingleton, ApplicationContextAware, BeanNameAware,
DestructionAwareBeanPostProcessor {
DestructionAwareBeanPostProcessor, DisposableBean {
private static final Log LOGGER = LogFactory.getLog(IntegrationManagementConfigurer.class);
public static final String MANAGEMENT_CONFIGURER_NAME = "integrationManagementConfigurer";
private final Set<MeterFacade> gauges = new HashSet<>();
private final Map<String, org.springframework.integration.support.management.MessageChannelMetrics>
channelsByName = new HashMap<>();
@@ -241,15 +246,15 @@ public class IntegrationManagementConfigurer
this.defaultLoggingEnabled = defaultLoggingEnabled;
}
public void setMetricsCaptor(@Nullable MetricsCaptor metricsCaptor) {
this.metricsCaptor = metricsCaptor;
}
@Override
public void afterSingletonsInstantiated() {
Assert.state(this.applicationContext != null, "'applicationContext' must not be null");
Assert.state(MANAGEMENT_CONFIGURER_NAME.equals(this.beanName), getClass().getSimpleName()
+ " bean name must be " + MANAGEMENT_CONFIGURER_NAME);
if (ClassUtils.isPresent("io.micrometer.core.instrument.MeterRegistry",
this.applicationContext.getClassLoader())) {
this.metricsCaptor = MicrometerMetricsCaptor.loadCaptor(this.applicationContext);
}
if (this.metricsCaptor != null) {
injectCaptor();
registerComponentGauges();
@@ -386,7 +391,7 @@ public class IntegrationManagementConfigurer
&& !overrides.metricsConfigured) {
((org.springframework.integration.support.management.ConfigurableMetricsAware<
org.springframework.integration.support.management.AbstractMessageChannelMetrics>) bean)
.configureMetrics(metrics);
.configureMetrics(metrics);
}
this.channelsByName.put(name, bean);
}
@@ -422,7 +427,7 @@ public class IntegrationManagementConfigurer
&& !overrides.metricsConfigured) {
((org.springframework.integration.support.management.ConfigurableMetricsAware<
org.springframework.integration.support.management.AbstractMessageHandlerMetrics>) bean)
.configureMetrics(metrics);
.configureMetrics(metrics);
}
this.handlersByName.put(bean.getManagedName() != null ? bean.getManagedName() : name, bean);
@@ -444,20 +449,23 @@ public class IntegrationManagementConfigurer
}
private void registerComponentGauges() {
this.metricsCaptor.gaugeBuilder("spring.integration.channels", this,
(c) -> this.applicationContext.getBeansOfType(MessageChannel.class).size())
.description("The number of message channels")
.build();
this.gauges.add(
this.metricsCaptor.gaugeBuilder("spring.integration.channels", this,
(c) -> this.applicationContext.getBeansOfType(MessageChannel.class).size())
.description("The number of message channels")
.build());
this.metricsCaptor.gaugeBuilder("spring.integration.handlers", this,
(c) -> this.applicationContext.getBeansOfType(MessageHandler.class).size())
.description("The number of message handlers")
.build();
this.gauges.add(
this.metricsCaptor.gaugeBuilder("spring.integration.handlers", this,
(c) -> this.applicationContext.getBeansOfType(MessageHandler.class).size())
.description("The number of message handlers")
.build());
this.metricsCaptor.gaugeBuilder("spring.integration.sources", this,
(c) -> this.applicationContext.getBeansOfType(MessageSource.class).size())
.description("The number of message sources")
.build();
this.gauges.add(
this.metricsCaptor.gaugeBuilder("spring.integration.sources", this,
(c) -> this.applicationContext.getBeansOfType(MessageSource.class).size())
.description("The number of message sources")
.build());
}
public String[] getChannelNames() {
@@ -510,6 +518,13 @@ public class IntegrationManagementConfigurer
return null;
}
@Override
public void destroy() {
this.gauges.forEach(MeterFacade::remove);
this.gauges.clear();
}
private static ManagementOverrides getOverrides(IntegrationManagement bean) {
return bean.getOverrides() != null ? bean.getOverrides() : new ManagementOverrides();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -86,7 +86,10 @@ public class MicrometerMetricsCaptor implements MetricsCaptor {
* there's already a {@link MetricsCaptor} bean, return that.
* @param applicationContext the application context.
* @return the instance.
* @deprecated since 5.2.9 in favor of {@code @Import(MicrometerMetricsCaptorRegistrar.class)};
* will be removed in 6.0.
*/
@Deprecated
public static MetricsCaptor loadCaptor(ApplicationContext applicationContext) {
try {
MeterRegistry registry = applicationContext.getBean(MeterRegistry.class);

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.support.management.micrometer;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
/**
* An {@link ImportBeanDefinitionRegistrar} to conditionally add a {@link MicrometerMetricsCaptor}
* bean when {@code io.micrometer.core.instrument.MeterRegistry} is present in classpath and
* no {@link MicrometerMetricsCaptor#MICROMETER_CAPTOR_NAME} bean present yet.
*
* @author Artem Bilan
*
* @since 5.2.9
*/
public class MicrometerMetricsCaptorRegistrar implements ImportBeanDefinitionRegistrar {
private static final Class<?> METER_REGISTRY_CLASS;
static {
Class<?> aClass = null;
try {
aClass = ClassUtils.forName("io.micrometer.core.instrument.MeterRegistry",
ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException e) {
// Ignore - no Micrometer in classpath
}
METER_REGISTRY_CLASS = aClass;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (METER_REGISTRY_CLASS != null
&& !registry.containsBeanDefinition(MicrometerMetricsCaptor.MICROMETER_CAPTOR_NAME)) {
String[] beanNamesForType =
((ListableBeanFactory) registry).getBeanNamesForType(METER_REGISTRY_CLASS, false, false);
for (String beanName : beanNamesForType) {
registry.registerBeanDefinition(MicrometerMetricsCaptor.MICROMETER_CAPTOR_NAME,
BeanDefinitionBuilder.genericBeanDefinition(MicrometerMetricsCaptor.class)
.addConstructorArgReference(beanName)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.getBeanDefinition());
return;
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -112,7 +112,7 @@ public class BeanNameTests {
public static class Config {
@Bean
public MeterRegistry meterRegistry() {
public static MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}

View File

@@ -264,6 +264,11 @@ public class IntegrationGraphServerTests {
@ImportResource("org/springframework/integration/graph/integration-graph-context.xml")
public static class Config {
@Bean
public static MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
public IntegrationGraphServer server() {
IntegrationGraphServer server = new IntegrationGraphServer();
@@ -281,11 +286,6 @@ public class IntegrationGraphServerTests {
return server;
}
@Bean
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
public MessageProducer producer() {
MessageProducerSupport producer = new MessageProducerSupport() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,9 @@
package org.springframework.integration.support.management.micrometer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
@@ -32,7 +31,7 @@ import org.springframework.integration.config.EnableIntegrationManagement;
import org.springframework.integration.support.management.metrics.MetricsCaptor;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import io.micrometer.core.instrument.MeterRegistry;
@@ -46,7 +45,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
* @since 5.1
*
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)
public class MicrometerCustomMetricsTests {
@@ -81,20 +80,18 @@ public class MicrometerCustomMetricsTests {
// Test meter removal
this.context.close();
try {
registry.get("myTimer").timers();
fail("Expected MeterNotFoundException");
}
catch (MeterNotFoundException e) {
assertThat(e).hasMessageContaining("No meter with name 'myTimer' was found");
}
try {
registry.get("myCounter").counters();
fail("Expected MeterNotFoundException");
}
catch (MeterNotFoundException e) {
assertThat(e).hasMessageContaining("No meter with name 'myCounter' was found");
}
assertThatExceptionOfType(MeterNotFoundException.class)
.isThrownBy(() -> registry.get("myTimer").timers())
.withMessageContaining("No meter with name 'myTimer' was found");
assertThatExceptionOfType(MeterNotFoundException.class)
.isThrownBy(() -> registry.get("myCounter").counters())
.withMessageContaining("No meter with name 'myCounter' was found");
assertThatExceptionOfType(MeterNotFoundException.class)
.isThrownBy(() -> registry.get("spring.integration.channels").gauge())
.withMessageContaining("No meter with name 'spring.integration.channels' was found");
}
@Configuration

View File

@@ -226,7 +226,7 @@ public class MicrometerMetricsTests {
public static class Config {
@Bean
public MeterRegistry meterRegistry() {
public static MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}

View File

@@ -97,6 +97,7 @@ public abstract class MongoDbAvailableTests {
protected void cleanupCollections(MongoDatabaseFactory mongoDbFactory, String... additionalCollectionsToDrop) {
MongoTemplate template = new MongoTemplate(mongoDbFactory);
template.dropCollection("messages");
template.dropCollection("channelMessages");
template.dropCollection("configurableStoreMessages");
template.dropCollection("data");
for (String additionalCollection : additionalCollectionsToDrop) {

View File

@@ -58,6 +58,7 @@ public abstract class AbstractMongoDbMessageGroupStoreTests extends MongoDbAvail
@Before
public void setup() {
cleanupCollections(MONGO_DATABASE_FACTORY);
this.testApplicationContext.refresh();
}

View File

@@ -69,6 +69,7 @@ public class SftpTests extends SftpTestSupport {
private IntegrationFlowContext flowContext;
@Test
@SuppressWarnings("unchecked")
public void testSftpInboundFlow() {
QueueChannel out = new QueueChannel();
IntegrationFlow flow = IntegrationFlows