Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
@@ -0,0 +1,78 @@
/*
* Copyright 2012-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.boot.actuate.autoconfigure.neo4j;

import io.micrometer.core.instrument.MeterRegistry;

import java.util.Collections;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.neo4j.driver.Driver;
import org.springframework.boot.actuate.neo4j.Neo4jDriverMetrics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.neo4j.Neo4jDriverAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* {@link EnableAutoConfiguration Auto-configuration} for metrics on all available
* {@link Driver drivers}.
* <p>
* The reason we are doing this dance with the manual binding is the fact that this
* autoconfiguration should work with more than one instance of the driver. If a user has
* multiple instances configured, than each instance should be bound via the binder to
* registry. Without that requirement, we could just add a {@link Bean @Bean} of type
* {@link Neo4jDriverMetrics} to the context and be done.
*
* @author Michael J. Simons
* @since 2.4.0
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({ MetricsAutoConfiguration.class, Neo4jDriverAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class })
@ConditionalOnClass({ Driver.class, MeterRegistry.class })
@ConditionalOnBean({ Driver.class, MeterRegistry.class })
public class Neo4jDriverMetricsAutoConfiguration {

private static final Log logger = LogFactory.getLog(Neo4jDriverMetricsAutoConfiguration.class);

@Autowired
public void bindDataSourcesToRegistry(Map<String, Driver> drivers, MeterRegistry registry) {

drivers.forEach((name, driver) -> {
if (!Neo4jDriverMetrics.metricsAreEnabled(driver)) {
return;
}
driver.verifyConnectivityAsync()
.thenRunAsync(() -> new Neo4jDriverMetrics(name, driver, Collections.emptyList()).bindTo(registry))
.exceptionally(e -> {
logger.warn("Could not verify connection for " + driver + " and thus not bind to metrics: "
+ e.getMessage());
return null;
});
});
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-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.
Expand All @@ -16,42 +16,77 @@

package org.springframework.boot.actuate.autoconfigure.neo4j;

import java.util.Map;

import org.neo4j.ogm.session.SessionFactory;

import org.springframework.boot.actuate.autoconfigure.health.CompositeHealthContributorConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.CompositeReactiveHealthContributorConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.health.HealthContributorAutoConfiguration;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthContributor;
import org.springframework.boot.actuate.health.ReactiveHealthContributor;
import org.springframework.boot.actuate.neo4j.Neo4jHealthIndicator;
import org.springframework.boot.actuate.neo4j.Neo4jReactiveHealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration;
import org.springframework.boot.autoconfigure.neo4j.Neo4jDriverAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Flux;

import java.util.Map;

import org.neo4j.driver.Driver;

/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link Neo4jHealthIndicator}.
* The auto-configuration here is responsible for both imperative and reactive health
* checks. The reactive health check has precedence over the imperative one.
*
* @author Eric Spiegelberg
* @author Stephane Nicoll
* @author Michael J. Simons
* @since 2.0.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(SessionFactory.class)
@ConditionalOnBean(SessionFactory.class)
@ConditionalOnClass({ Driver.class, Health.class })
@ConditionalOnBean(Driver.class)
@ConditionalOnEnabledHealthIndicator("neo4j")
@AutoConfigureAfter(Neo4jDataAutoConfiguration.class)
public class Neo4jHealthContributorAutoConfiguration
extends CompositeHealthContributorConfiguration<Neo4jHealthIndicator, SessionFactory> {

@Bean
@ConditionalOnMissingBean(name = { "neo4jHealthIndicator", "neo4jHealthContributor" })
public HealthContributor neo4jHealthContributor(Map<String, SessionFactory> sessionFactories) {
return createContributor(sessionFactories);
@AutoConfigureBefore(HealthContributorAutoConfiguration.class)
@AutoConfigureAfter({ Neo4jDriverAutoConfiguration.class, Neo4jDataAutoConfiguration.class })
public class Neo4jHealthContributorAutoConfiguration {

@Configuration(proxyBeanMethods = false)
@Order(-20)
static class Neo4jHealthIndicatorConfiguration
extends CompositeHealthContributorConfiguration<Neo4jHealthIndicator, Driver> {

@Bean
// If Neo4jReactiveHealthIndicatorConfiguration kicked in, don't add the
// imperative version as well
@ConditionalOnMissingBean(name = "neo4jHealthContributor")
public HealthContributor neo4jHealthContributor(Map<String, Driver> drivers) {
return createContributor(drivers);
}

}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Flux.class })
@Order(-30)
static class Neo4jReactiveHealthIndicatorConfiguration
extends CompositeReactiveHealthContributorConfiguration<Neo4jReactiveHealthIndicator, Driver> {

@Bean
@ConditionalOnMissingBean(name = "neo4jHealthContributor")
public ReactiveHealthContributor neo4jHealthContributor(Map<String, Driver> drivers) {
return createComposite(drivers);
}

}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* Copyright 2012-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.boot.actuate.autoconfigure.neo4j;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.neo4j.Neo4jDriverMetrics;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.neo4j.driver.Driver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.boot.actuate.autoconfigure.neo4j.Neo4jDriverMocks.mockDriverWithMetrics;
import static org.springframework.boot.actuate.autoconfigure.neo4j.Neo4jDriverMocks.mockDriverWithoutMetrics;

/**
* @author Michael J. Simons
*/
class Neo4jDriverMetricsAutoConfigurationTest {

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(MetricsAutoConfiguration.class, Neo4jDriverMetricsAutoConfiguration.class));

private final ContextConsumer<AssertableApplicationContext> assertNoInteractionsWithRegistry = ctx -> {

if (ctx.getBeansOfType(MeterRegistry.class).isEmpty()) {
return;
}

MeterRegistry mockedRegistry = ctx.getBean(MeterRegistry.class);
verify(mockedRegistry).config();
verifyNoMoreInteractions(mockedRegistry);
};

@Nested
class NoMatches {

@Test
void shouldRequireAllNeededClasses() {
contextRunner.withUserConfiguration(WithMeterRegistry.class)
.withClassLoader(new FilteredClassLoader(Driver.class)).run(assertNoInteractionsWithRegistry);

contextRunner.withUserConfiguration(WithDriverWithMetrics.class)
.withClassLoader(new FilteredClassLoader(MeterRegistry.class))
.run(assertNoInteractionsWithRegistry);
}

@Test
void shouldRequireAllNeededBeans() {
contextRunner.withUserConfiguration(WithDriverWithMetrics.class).run(assertNoInteractionsWithRegistry);

contextRunner.withUserConfiguration(WithMeterRegistry.class).run(assertNoInteractionsWithRegistry);
}

@Test
void shouldRequireDriverWithMetrics() {
contextRunner.withUserConfiguration(WithDriverWithoutMetrics.class, WithMeterRegistry.class)
.run(assertNoInteractionsWithRegistry);

}

}

@Nested
class Matches {

@Test
void shouldRequireDriverWithMetrics() {
contextRunner.withUserConfiguration(WithDriverWithMetrics.class, WithMeterRegistry.class).run(ctx -> {

// Wait a bit to let the completable future of the test that mocks
// connectiviy complete.
Thread.sleep(500L);

MeterRegistry meterRegistry = ctx.getBean(MeterRegistry.class);
assertThat(meterRegistry.getMeters()).extracting(m -> m.getId().getName())
.filteredOn(s -> s.startsWith(Neo4jDriverMetrics.PREFIX)).isNotEmpty();
});
}

}

@Configuration(proxyBeanMethods = false)
static class WithDriverWithMetrics {

@Bean
Driver driver() {
return mockDriverWithMetrics();
}

}

@Configuration(proxyBeanMethods = false)
static class WithDriverWithoutMetrics {

@Bean
Driver driver() {
return mockDriverWithoutMetrics();
}

}

@Configuration(proxyBeanMethods = false)
static class WithMeterRegistry {

@Bean
MeterRegistry meterRegistry() {

MeterRegistry meterRegistry = spy(SimpleMeterRegistry.class);
return meterRegistry;
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2012-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.boot.actuate.autoconfigure.neo4j;

import java.util.Collections;
import java.util.concurrent.CompletableFuture;

import org.neo4j.driver.ConnectionPoolMetrics;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Metrics;
import org.neo4j.driver.exceptions.ClientException;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
* Some predefined mocks, only to be used internally for tests.
*
* @author Michael J. Simons
*/
final class Neo4jDriverMocks {

public static Driver mockDriverWithMetrics() {
ConnectionPoolMetrics p1 = mock(ConnectionPoolMetrics.class);
when(p1.id()).thenReturn("p1");

Metrics metrics = mock(Metrics.class);
when(metrics.connectionPoolMetrics()).thenReturn(Collections.singletonList(p1));

Driver driver = mock(Driver.class);
when(driver.metrics()).thenReturn(metrics);

when(driver.verifyConnectivityAsync()).thenReturn(CompletableFuture.completedFuture(null));

return driver;
}

public static Driver mockDriverWithoutMetrics() {

Driver driver = mock(Driver.class);
when(driver.metrics()).thenThrow(ClientException.class);
return driver;
}

private Neo4jDriverMocks() {
}

}
Loading