gnodet commented on code in PR #26845: URL: https://github.com/apache/camel/pull/26845#discussion_r4112541238
########## core/camel-support/src/main/java/org/apache/camel/support/DataSourceHelper.java: ########## @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.support; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import javax.sql.DataSource; + +import org.apache.camel.spi.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility methods for working with JDBC {@link DataSource} instances. + */ +public final class DataSourceHelper { + + private static final Logger LOG = LoggerFactory.getLogger(DataSourceHelper.class); + + private DataSourceHelper() { + } + + /** + * Evicts stale connections from the given DataSource so that the pool rebuilds them with the rotated credentials. + * <p/> + * HikariCP is tried first via reflection (so the caller does not need a compile-time dependency on it). Any + * DataSource that does not expose {@code getHikariPoolMXBean()} is left untouched — the pool will pick up the new + * credentials on its own reconnect cycle when existing connections expire. + * + * @param ds the DataSource whose connections should be evicted + * @param source an opaque label for the rotation event (used in log messages only) + */ + public static void evictDataSourceConnections(DataSource ds, Object source) { + // HikariCP: softEvictConnections() is defined on HikariPoolMXBean, not on HikariDataSource directly. + // We retrieve the MXBean via getHikariPoolMXBean() (a public method on HikariDataSource) using reflection + // so that the caller does not need a compile-time dependency on HikariCP. + try { + Method getPoolMXBean = ds.getClass().getMethod("getHikariPoolMXBean"); + getPoolMXBean.setAccessible(true); + Object poolMXBean = getPoolMXBean.invoke(ds); + if (poolMXBean != null) { Review Comment: Fixed in bd4bc274615e. When `getHikariPoolMXBean()` returns null (pool not started yet), we now log at DEBUG level: "HikariCP pool on {} is not started yet; nothing to evict" instead of the misleading fallback message. ########## core/camel-support/src/main/java/org/apache/camel/support/DataSourceHelper.java: ########## @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.support; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import javax.sql.DataSource; + +import org.apache.camel.spi.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility methods for working with JDBC {@link DataSource} instances. + */ +public final class DataSourceHelper { + + private static final Logger LOG = LoggerFactory.getLogger(DataSourceHelper.class); + + private DataSourceHelper() { + } + + /** + * Evicts stale connections from the given DataSource so that the pool rebuilds them with the rotated credentials. + * <p/> + * HikariCP is tried first via reflection (so the caller does not need a compile-time dependency on it). Any + * DataSource that does not expose {@code getHikariPoolMXBean()} is left untouched — the pool will pick up the new + * credentials on its own reconnect cycle when existing connections expire. + * + * @param ds the DataSource whose connections should be evicted + * @param source an opaque label for the rotation event (used in log messages only) + */ + public static void evictDataSourceConnections(DataSource ds, Object source) { + // HikariCP: softEvictConnections() is defined on HikariPoolMXBean, not on HikariDataSource directly. + // We retrieve the MXBean via getHikariPoolMXBean() (a public method on HikariDataSource) using reflection + // so that the caller does not need a compile-time dependency on HikariCP. + try { + Method getPoolMXBean = ds.getClass().getMethod("getHikariPoolMXBean"); + getPoolMXBean.setAccessible(true); Review Comment: Fixed in bd4bc274615e. Dropped `setAccessible(true)` from production code. Replaced anonymous test stubs with public static nested classes (`MockPoolMXBean`, `HikariLikeDataSource`, `NoOpDataSource`) so reflection works without accessibility overrides. ########## core/camel-support/src/main/java/org/apache/camel/support/DataSourceHelper.java: ########## @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.support; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import javax.sql.DataSource; + +import org.apache.camel.spi.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility methods for working with JDBC {@link DataSource} instances. + */ +public final class DataSourceHelper { + + private static final Logger LOG = LoggerFactory.getLogger(DataSourceHelper.class); + + private DataSourceHelper() { + } + + /** + * Evicts stale connections from the given DataSource so that the pool rebuilds them with the rotated credentials. + * <p/> + * HikariCP is tried first via reflection (so the caller does not need a compile-time dependency on it). Any + * DataSource that does not expose {@code getHikariPoolMXBean()} is left untouched — the pool will pick up the new + * credentials on its own reconnect cycle when existing connections expire. + * + * @param ds the DataSource whose connections should be evicted + * @param source an opaque label for the rotation event (used in log messages only) + */ + public static void evictDataSourceConnections(DataSource ds, Object source) { + // HikariCP: softEvictConnections() is defined on HikariPoolMXBean, not on HikariDataSource directly. + // We retrieve the MXBean via getHikariPoolMXBean() (a public method on HikariDataSource) using reflection + // so that the caller does not need a compile-time dependency on HikariCP. + try { + Method getPoolMXBean = ds.getClass().getMethod("getHikariPoolMXBean"); + getPoolMXBean.setAccessible(true); + Object poolMXBean = getPoolMXBean.invoke(ds); + if (poolMXBean != null) { + Method softEvict = poolMXBean.getClass().getMethod("softEvictConnections"); + softEvict.setAccessible(true); + softEvict.invoke(poolMXBean); + LOG.info("Secret rotation (source={}): HikariCP softEvictConnections() called on {}", source, ds); + return; + } + } catch (NoSuchMethodException e) { + // Not a HikariCP DataSource — fall through to generic handling + } catch (Exception e) { + LOG.warn("Secret rotation (source={}): softEvictConnections() failed on {}: {}", source, ds, e.getMessage()); + } + + // Generic fallback: log that the pool was not explicitly evicted. + // The pool will pick up the new credentials when existing connections expire naturally. + LOG.info( + "Secret rotation (source={}): DataSource {} does not support HikariCP pool eviction; " + + "existing connections will be replaced as they expire or are validated", + source, ds.getClass().getName()); + } + + /** + * Evicts stale connections from all {@link DataSource} instances visible to the given registry plus the optional + * component-owned data source. + * <p/> + * Uses identity-based deduplication to avoid double-eviction when the same {@code DataSource} object is both + * registered in the registry and injected directly on the component (the common Spring/Quarkus setup). + * + * @param registry the Camel registry to scan for {@link DataSource} beans + * @param componentDataSource an optional DataSource injected directly on the component; may be {@code null} + * @param source an opaque label for the rotation event (used in log messages only) + */ + public static void evictAllDataSourceConnections(Registry registry, DataSource componentDataSource, Object source) { + // Use identity-based deduplication to avoid double-eviction when componentDataSource + // is the same object instance as a bean registered in the registry. + // (equals/hashCode on DataSource wrappers may delegate to the wrapped instance, + // causing a regular HashSet to miss duplicates or collapse distinct pools.) + Set<DataSource> dataSources = Collections.newSetFromMap(new IdentityHashMap<>()); + dataSources.addAll(registry.findByType(DataSource.class)); Review Comment: Fixed in bd4bc274615e. Eviction is now restricted to the component's own `dataSource` field only. Removed `evictAllDataSourceConnections()` and the registry scan entirely. Each component only evicts its own DataSource, so when both jdbc and sql are in use with different DataSources, there's no cross-eviction or double-eviction. ########## components/camel-sql/src/main/java/org/apache/camel/component/sql/SqlComponent.java: ########## @@ -151,6 +153,11 @@ protected Endpoint createEndpoint(String uri, String remaining, Map<String, Obje return endpoint; } + @Override + public void onSecretRotation(Object source) throws Exception { Review Comment: Fixed in bd4bc274615e. Documented the limitation in the Javadoc of `evictDataSourceConnections()` and in both component docs (jdbc-component.adoc, sql-component.adoc). The docs now clearly state that eviction only helps pools that resolve credentials dynamically (HikariCredentialsProvider, AWS JDBC wrapper, custom vault-aware DataSource). Pools with static passwords will re-open connections with the old credentials. ########## components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlComponentSecretRotationAwareTest.java: ########## @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.component.sql; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Logger; + +import javax.sql.DataSource; + +import org.apache.camel.spi.SecretRotationAware; +import org.apache.camel.support.DataSourceHelper; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Verifies that {@link SqlComponent} implements {@link SecretRotationAware} and correctly evicts stale connections on + * rotation. + */ +class SqlComponentSecretRotationAwareTest { + + @Test + void implementsSecretRotationAware() { + assertInstanceOf(SecretRotationAware.class, new SqlComponent()); + } + + @Test + void evictDataSourceConnections_hikariCpPool_callsSoftEvict() throws Exception { + // Arrange: a DataSource that simulates HikariDataSource by exposing getHikariPoolMXBean(), + // which returns a mock MXBean with softEvictConnections(). This matches the real HikariCP API + // where softEvictConnections() lives on HikariPoolMXBean, not on HikariDataSource itself. + AtomicBoolean softEvictCalled = new AtomicBoolean(false); + Object mockMXBean = new Object() { + @SuppressWarnings("unused") + public void softEvictConnections() { + softEvictCalled.set(true); + } + }; + DataSource hikariLike = new HikariLikeDataSource() { + @SuppressWarnings("unused") + public Object getHikariPoolMXBean() { + return mockMXBean; + } + }; + + // Act + DataSourceHelper.evictDataSourceConnections(hikariLike, "test"); + + // Assert + assertTrue(softEvictCalled.get(), "softEvictConnections() should have been called via HikariPoolMXBean"); + } + + @Test + void evictDataSourceConnections_genericPool_doesNotThrow() { + // Arrange: a DataSource without getHikariPoolMXBean() — the generic fallback path + DataSource generic = new NoOpDataSource(); + + // Act — must not throw + DataSourceHelper.evictDataSourceConnections(generic, "test"); + } + + @Test + void onSecretRotation_withRegistryDataSource_evictsConnections() throws Exception { + // Arrange + AtomicBoolean softEvictCalled = new AtomicBoolean(false); + Object mockMXBean = new Object() { + @SuppressWarnings("unused") + public void softEvictConnections() { + softEvictCalled.set(true); + } + }; + DataSource hikariLike = new HikariLikeDataSource() { + @SuppressWarnings("unused") + public Object getHikariPoolMXBean() { + return mockMXBean; + } + }; + + SqlComponent component = new SqlComponent(); + // Use a real CamelContext so we can bind the DataSource to the registry + org.apache.camel.impl.DefaultCamelContext ctx = new org.apache.camel.impl.DefaultCamelContext(); Review Comment: Fixed in bd4bc274615e. Imported `DefaultCamelContext` properly in both test files. Also replaced all anonymous inner classes with public static nested classes, which eliminated the FQCN usage entirely. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
