This is an automated email from the ASF dual-hosted git repository.

sunnianjun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new bf9c50a6259 Refactor the acquisition of ContextManager in JDBC metrics 
(#31825)
bf9c50a6259 is described below

commit bf9c50a6259c6749037ebed4cd2557670a39d2eb
Author: jiangML <[email protected]>
AuthorDate: Mon Jun 24 16:19:26 2024 +0800

    Refactor the acquisition of ContextManager in JDBC metrics (#31825)
    
    * Add param length parameter for pointcut configuration
    
    * Refactor metrics of JDBC
    
    * Remove ShardingSphereDriverUtils
    
    * Fix test error
    
    * Fix JDBCMetaDataInfoExporterTest  error
    
    * Add test for ShardingSphereDataSourceAdvice
---
 .../yaml/entity/YamlPointcutConfiguration.java     |  2 +
 .../swapper/YamlPointcutConfigurationSwapper.java  |  3 +
 .../YamlAdvisorsConfigurationLoaderTest.java       | 20 +++---
 .../YamlAdvisorsConfigurationSwapperTest.java      |  4 +-
 .../src/test/resources/META-INF/conf/advisors.yaml |  1 +
 .../agent/plugin/core/context/PluginContext.java   | 10 ++-
 .../plugin/core/holder/ContextManagerHolder.java   | 62 +++++++++++++++++
 .../core/util/ShardingSphereDriverUtils.java       | 58 ----------------
 .../jdbc/ShardingSphereDataSourceAdvice.java       | 50 ++++++++++++++
 .../impl/jdbc/JDBCMetaDataInfoExporter.java        | 21 +++---
 .../core/exporter/impl/jdbc/JDBCStateExporter.java | 23 ++++---
 .../jdbc/ShardingSphereDataSourceAdviceTest.java   | 78 ++++++++++++++++++++++
 .../impl/jdbc/JDBCMetaDataInfoExporterTest.java    | 29 ++++++--
 .../exporter/impl/jdbc/JDBCStateExporterTest.java  |  2 +-
 .../config/driver/foo-driver-fixture.yaml          | 57 ----------------
 .../exoprter/PrometheusMetricsExporter.java        | 13 +++-
 .../META-INF/conf/prometheus-advisors.yaml         |  8 +++
 17 files changed, 280 insertions(+), 161 deletions(-)

diff --git 
a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/entity/YamlPointcutConfiguration.java
 
b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/entity/YamlPointcutConfiguration.java
index dce3e17ce4d..d3a7356bb47 100644
--- 
a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/entity/YamlPointcutConfiguration.java
+++ 
b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/entity/YamlPointcutConfiguration.java
@@ -34,5 +34,7 @@ public final class YamlPointcutConfiguration {
     
     private String type;
     
+    private Integer paramLength;
+    
     private Collection<YamlPointcutParameterConfiguration> params = new 
LinkedList<>();
 }
diff --git 
a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlPointcutConfigurationSwapper.java
 
b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlPointcutConfigurationSwapper.java
index 4620fe35333..a88032ebcbe 100644
--- 
a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlPointcutConfigurationSwapper.java
+++ 
b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlPointcutConfigurationSwapper.java
@@ -52,6 +52,9 @@ public final class YamlPointcutConfigurationSwapper {
     
     private static ElementMatcher<MethodDescription> appendParameters(final 
YamlPointcutConfiguration yamlConfig, final Junction<MethodDescription> 
pointcut) {
         Junction<MethodDescription> result = pointcut;
+        if (null != yamlConfig.getParamLength() && 0 <= 
yamlConfig.getParamLength()) {
+            result = 
result.and(ElementMatchers.takesArguments(yamlConfig.getParamLength()));
+        }
         for (YamlPointcutParameterConfiguration each : yamlConfig.getParams()) 
{
             result = result.and(ElementMatchers.takesArgument(each.getIndex(), 
ElementMatchers.named(each.getType())));
         }
diff --git 
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/loader/YamlAdvisorsConfigurationLoaderTest.java
 
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/loader/YamlAdvisorsConfigurationLoaderTest.java
index d34b45bab31..92529d337e8 100644
--- 
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/loader/YamlAdvisorsConfigurationLoaderTest.java
+++ 
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/loader/YamlAdvisorsConfigurationLoaderTest.java
@@ -48,20 +48,21 @@ class YamlAdvisorsConfigurationLoaderTest {
         assertThat(actual.getAdvice(), is(YamlAdviceFixture.class.getName()));
         assertThat(actual.getPointcuts().size(), is(8));
         List<YamlPointcutConfiguration> actualYamlPointcutConfigs = new 
ArrayList<>(actual.getPointcuts());
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(0), 
null, "constructor", Collections.emptyList());
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(1), 
null, "constructor", 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(2), 
"call", "method", Collections.emptyList());
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(3), 
"call", "method", 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(4), 
"call", "method",
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(0), 
null, "constructor", null, Collections.emptyList());
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(1), 
null, "constructor", null, 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(2), 
"call", "method", null, Collections.emptyList());
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(3), 
"call", "method", null, 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(4), 
"call", "method", null,
                 Arrays.asList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String"), createYamlPointcutParameterConfiguration(1, 
"java.lang.String")));
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(5), 
"staticCall", "method", Collections.emptyList());
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(6), 
"staticCall", "method", 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
-        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(7), 
"staticCall", "method",
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(5), 
"staticCall", "method", null, Collections.emptyList());
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(6), 
"staticCall", "method", null, 
Collections.singletonList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String")));
+        assertYamlPointcutConfiguration(actualYamlPointcutConfigs.get(7), 
"staticCall", "method", 2,
                 Arrays.asList(createYamlPointcutParameterConfiguration(0, 
"java.lang.String"), createYamlPointcutParameterConfiguration(1, 
"java.lang.String")));
     }
     
     private void assertYamlPointcutConfiguration(final 
YamlPointcutConfiguration actual,
-                                                 final String expectedName, 
final String expectedType, final List<YamlPointcutParameterConfiguration> 
expectedParams) {
+                                                 final String expectedName, 
final String expectedType, final Integer expectedParamsLength,
+                                                 final 
List<YamlPointcutParameterConfiguration> expectedParams) {
         assertThat(actual.getName(), is(expectedName));
         assertThat(actual.getType(), is(expectedType));
         assertThat(actual.getParams().size(), is(expectedParams.size()));
@@ -70,6 +71,7 @@ class YamlAdvisorsConfigurationLoaderTest {
             assertYamlPointcutParameterConfiguration(each, 
expectedParams.get(count));
             count++;
         }
+        assertThat(actual.getParamLength(), is(expectedParamsLength));
     }
     
     private void assertYamlPointcutParameterConfiguration(final 
YamlPointcutParameterConfiguration actual, final 
YamlPointcutParameterConfiguration expected) {
diff --git 
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlAdvisorsConfigurationSwapperTest.java
 
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlAdvisorsConfigurationSwapperTest.java
index 6b2a43e91f6..763de81d1b0 100644
--- 
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlAdvisorsConfigurationSwapperTest.java
+++ 
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/config/yaml/swapper/YamlAdvisorsConfigurationSwapperTest.java
@@ -58,7 +58,9 @@ class YamlAdvisorsConfigurationSwapperTest {
         assertThat(actualAdvisorConfigs.get(5).getPointcut(), 
is(ElementMatchers.named("staticCall")));
         assertThat(actualAdvisorConfigs.get(6).getPointcut(), 
is(ElementMatchers.named("staticCall").and(ElementMatchers.takesArgument(0, 
ElementMatchers.named("java.lang.String")))));
         assertThat(actualAdvisorConfigs.get(7).getPointcut(), 
is(ElementMatchers.named("staticCall")
-                .and(ElementMatchers.takesArgument(0, 
ElementMatchers.named("java.lang.String"))).and(ElementMatchers.takesArgument(1,
 ElementMatchers.named("java.lang.String")))));
+                .and(ElementMatchers.takesArguments(2))
+                .and(ElementMatchers.takesArgument(0, 
ElementMatchers.named("java.lang.String")))
+                .and(ElementMatchers.takesArgument(1, 
ElementMatchers.named("java.lang.String")))));
         actualAdvisorConfigs.forEach(each -> assertThat(each.getPluginType(), 
is("FIXTURE")));
     }
 }
diff --git a/agent/core/src/test/resources/META-INF/conf/advisors.yaml 
b/agent/core/src/test/resources/META-INF/conf/advisors.yaml
index 946c222ed3d..cecf68b7ebb 100644
--- a/agent/core/src/test/resources/META-INF/conf/advisors.yaml
+++ b/agent/core/src/test/resources/META-INF/conf/advisors.yaml
@@ -47,6 +47,7 @@ advisors:
             type: java.lang.String
       - name: staticCall
         type: method
+        paramLength: 2
         params:
           - index: 0
             type: java.lang.String
diff --git 
a/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/context/PluginContext.java
 
b/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/context/PluginContext.java
index 50343128660..52cf4d12bcb 100644
--- 
a/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/context/PluginContext.java
+++ 
b/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/context/PluginContext.java
@@ -20,14 +20,11 @@ package org.apache.shardingsphere.agent.plugin.core.context;
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
-import org.apache.shardingsphere.agent.plugin.core.util.AgentReflectionUtils;
-import 
org.apache.shardingsphere.agent.plugin.core.util.ShardingSphereDriverUtils;
-import 
org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
 import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;
 import org.apache.shardingsphere.mode.manager.ContextManager;
 import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
 
-import java.util.Map;
 import java.util.Optional;
 
 /**
@@ -73,7 +70,8 @@ public final class PluginContext {
         if (isEnhancedForProxy) {
             return 
Optional.ofNullable(ProxyContext.getInstance().getContextManager());
         }
-        Map<String, ShardingSphereDataSource> dataSourceMap = 
ShardingSphereDriverUtils.findShardingSphereDataSources();
-        return dataSourceMap.isEmpty() ? Optional.empty() : 
Optional.ofNullable(AgentReflectionUtils.getFieldValue(dataSourceMap.values().iterator().next(),
 "contextManager"));
+        return ContextManagerHolder.getDatabaseContextManager().isEmpty()
+                ? Optional.empty()
+                : 
Optional.of(ContextManagerHolder.getDatabaseContextManager().values().iterator().next());
     }
 }
diff --git 
a/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/holder/ContextManagerHolder.java
 
b/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/holder/ContextManagerHolder.java
new file mode 100644
index 00000000000..48da2b43004
--- /dev/null
+++ 
b/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/holder/ContextManagerHolder.java
@@ -0,0 +1,62 @@
+/*
+ * 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.shardingsphere.agent.plugin.core.holder;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.shardingsphere.mode.manager.ContextManager;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Context manager holder.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class ContextManagerHolder {
+    
+    private static final Map<String, ContextManager> 
DATABASE_CONTEXT_MANAGER_CACHE = new ConcurrentHashMap<>();
+    
+    /**
+     * put.
+     *
+     * @param database database
+     * @param contextManager context manager
+     */
+    public static void put(final String database, final ContextManager 
contextManager) {
+        DATABASE_CONTEXT_MANAGER_CACHE.put(database, contextManager);
+    }
+    
+    /**
+     * remove.
+     *
+     * @param database database
+     */
+    public static void remove(final String database) {
+        DATABASE_CONTEXT_MANAGER_CACHE.remove(database);
+    }
+    
+    /**
+     * Get database context manager.
+     *
+     * @return database context manager
+     */
+    public static Map<String, ContextManager> getDatabaseContextManager() {
+        return DATABASE_CONTEXT_MANAGER_CACHE;
+    }
+}
diff --git 
a/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/util/ShardingSphereDriverUtils.java
 
b/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/util/ShardingSphereDriverUtils.java
deleted file mode 100644
index 020f3c6c362..00000000000
--- 
a/agent/plugins/core/src/main/java/org/apache/shardingsphere/agent/plugin/core/util/ShardingSphereDriverUtils.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.shardingsphere.agent.plugin.core.util;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-import org.apache.shardingsphere.driver.ShardingSphereDriver;
-import 
org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
-
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.Optional;
-
-/**
- * ShardingSphere driver utils.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class ShardingSphereDriverUtils {
-    
-    /**
-     * Find ShardingSphere data sources.
-     *
-     * @return found data source
-     */
-    public static Map<String, ShardingSphereDataSource> 
findShardingSphereDataSources() {
-        return 
findShardingSphereDriver().map(ShardingSphereDriver::getShardingSphereDataSources).orElse(Collections.emptyMap());
-    }
-    
-    @SuppressWarnings("UseOfJDBCDriverClass")
-    private static Optional<ShardingSphereDriver> findShardingSphereDriver() {
-        Enumeration<Driver> drivers = DriverManager.getDrivers();
-        while (drivers.hasMoreElements()) {
-            Driver driver = drivers.nextElement();
-            if (driver instanceof ShardingSphereDriver) {
-                return Optional.of((ShardingSphereDriver) driver);
-            }
-        }
-        return Optional.empty();
-    }
-}
diff --git 
a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdvice.java
 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdvice.java
new file mode 100644
index 00000000000..b7dada861c3
--- /dev/null
+++ 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdvice.java
@@ -0,0 +1,50 @@
+/*
+ * 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.shardingsphere.agent.plugin.metrics.core.advice.jdbc;
+
+import org.apache.shardingsphere.agent.api.advice.TargetAdviceObject;
+import 
org.apache.shardingsphere.agent.plugin.core.advice.AbstractInstanceMethodAdvice;
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
+import org.apache.shardingsphere.agent.plugin.core.util.AgentReflectionUtils;
+import org.apache.shardingsphere.mode.manager.ContextManager;
+
+import java.lang.reflect.Method;
+
+/**
+ * ShardingSphere data source advice.
+ */
+public final class ShardingSphereDataSourceAdvice extends 
AbstractInstanceMethodAdvice {
+    
+    @Override
+    public void beforeMethod(final TargetAdviceObject target, final Method 
method, final Object[] args, final String pluginType) {
+        if ("close".equals(method.getName())) {
+            ContextManagerHolder.remove(getDatabaseName(target));
+        }
+    }
+    
+    @Override
+    public void afterMethod(final TargetAdviceObject target, final Method 
method, final Object[] args, final Object result, final String pluginType) {
+        if ("createContextManager".equals(method.getName())) {
+            ContextManagerHolder.put(getDatabaseName(target), (ContextManager) 
result);
+        }
+    }
+    
+    private String getDatabaseName(final TargetAdviceObject target) {
+        return AgentReflectionUtils.getFieldValue(target, "databaseName");
+    }
+}
diff --git 
a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporter.java
 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporter.java
index ef47df7f6b3..fe30e08745e 100644
--- 
a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporter.java
+++ 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporter.java
@@ -17,19 +17,17 @@
 
 package org.apache.shardingsphere.agent.plugin.metrics.core.exporter.impl.jdbc;
 
-import org.apache.shardingsphere.agent.plugin.core.util.AgentReflectionUtils;
-import 
org.apache.shardingsphere.agent.plugin.core.util.ShardingSphereDriverUtils;
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.MetricsCollectorRegistry;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.type.GaugeMetricFamilyMetricsCollector;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricCollectorType;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.exporter.MetricsExporter;
-import 
org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
+import 
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
 import org.apache.shardingsphere.mode.manager.ContextManager;
 
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 
@@ -44,15 +42,18 @@ public final class JDBCMetaDataInfoExporter implements 
MetricsExporter {
     
     @Override
     public Optional<GaugeMetricFamilyMetricsCollector> export(final String 
pluginType) {
-        Map<String, ShardingSphereDataSource> dataSourceMap = 
ShardingSphereDriverUtils.findShardingSphereDataSources();
         GaugeMetricFamilyMetricsCollector result = 
MetricsCollectorRegistry.get(config, pluginType);
         result.cleanMetrics();
-        for (Entry<String, ShardingSphereDataSource> entry : 
dataSourceMap.entrySet()) {
-            ShardingSphereDataSource dataSource = entry.getValue();
-            String databaseName = 
AgentReflectionUtils.getFieldValue(dataSource, "databaseName");
-            ContextManager contextManager = 
AgentReflectionUtils.getFieldValue(dataSource, "contextManager");
-            result.addMetric(Arrays.asList(databaseName, 
"storage_unit_count"), contextManager.getStorageUnits(databaseName).size());
+        for (Entry<String, ContextManager> entry : 
ContextManagerHolder.getDatabaseContextManager().entrySet()) {
+            addMetric(result, entry.getKey(), entry.getValue());
         }
         return Optional.of(result);
     }
+    
+    private void addMetric(final GaugeMetricFamilyMetricsCollector collector, 
final String database, final ContextManager contextManager) {
+        ShardingSphereDatabase shardingSphereDatabase = 
contextManager.getDatabase(database);
+        if (null != shardingSphereDatabase) {
+            collector.addMetric(Arrays.asList(database, "storage_unit_count"), 
shardingSphereDatabase.getResourceMetaData().getStorageUnits().size());
+        }
+    }
 }
diff --git 
a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporter.java
 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporter.java
index e60b2dd3c01..452c7c92af7 100644
--- 
a/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporter.java
+++ 
b/agent/plugins/metrics/core/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporter.java
@@ -17,18 +17,16 @@
 
 package org.apache.shardingsphere.agent.plugin.metrics.core.exporter.impl.jdbc;
 
-import org.apache.shardingsphere.agent.plugin.core.util.AgentReflectionUtils;
-import 
org.apache.shardingsphere.agent.plugin.core.util.ShardingSphereDriverUtils;
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.MetricsCollectorRegistry;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.type.GaugeMetricFamilyMetricsCollector;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricCollectorType;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.exporter.MetricsExporter;
-import 
org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
+import 
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
 import org.apache.shardingsphere.mode.manager.ContextManager;
 
 import java.util.Collections;
-import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 
@@ -37,18 +35,23 @@ import java.util.Optional;
  */
 public final class JDBCStateExporter implements MetricsExporter {
     
-    private final MetricConfiguration config = new 
MetricConfiguration("jdbc_state", MetricCollectorType.GAUGE_METRIC_FAMILY, 
"State of ShardingSphere-JDBC. 0 is OK; 1 is CIRCUIT BREAK; 2 is LOCK");
+    private final MetricConfiguration config = new 
MetricConfiguration("jdbc_state", MetricCollectorType.GAUGE_METRIC_FAMILY,
+            "State of ShardingSphere-JDBC. 0 is OK; 1 is CIRCUIT BREAK", 
Collections.singletonList("database"));
     
     @Override
     public Optional<GaugeMetricFamilyMetricsCollector> export(final String 
pluginType) {
-        Map<String, ShardingSphereDataSource> dataSourceMap = 
ShardingSphereDriverUtils.findShardingSphereDataSources();
         GaugeMetricFamilyMetricsCollector result = 
MetricsCollectorRegistry.get(config, pluginType);
         result.cleanMetrics();
-        for (Entry<String, ShardingSphereDataSource> entry : 
dataSourceMap.entrySet()) {
-            ShardingSphereDataSource dataSource = entry.getValue();
-            ContextManager contextManager = 
AgentReflectionUtils.getFieldValue(dataSource, "contextManager");
-            result.addMetric(Collections.emptyList(), 
contextManager.getComputeNodeInstanceContext().getInstance().getState().getCurrentState().ordinal());
+        for (Entry<String, ContextManager> entry : 
ContextManagerHolder.getDatabaseContextManager().entrySet()) {
+            addMetric(result, entry.getKey(), entry.getValue());
         }
         return Optional.of(result);
     }
+    
+    private void addMetric(final GaugeMetricFamilyMetricsCollector collector, 
final String database, final ContextManager contextManager) {
+        ShardingSphereDatabase shardingSphereDatabase = 
contextManager.getDatabase(database);
+        if (null != shardingSphereDatabase) {
+            collector.addMetric(Collections.singletonList(database), 
contextManager.getComputeNodeInstanceContext().getInstance().getState().getCurrentState().ordinal());
+        }
+    }
 }
diff --git 
a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdviceTest.java
 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdviceTest.java
new file mode 100644
index 00000000000..f77162e8d1e
--- /dev/null
+++ 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/advice/jdbc/ShardingSphereDataSourceAdviceTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.agent.plugin.metrics.core.advice.jdbc;
+
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
+import org.apache.shardingsphere.agent.plugin.core.util.AgentReflectionUtils;
+import 
org.apache.shardingsphere.agent.plugin.metrics.core.fixture.TargetAdviceObjectFixture;
+import org.apache.shardingsphere.mode.manager.ContextManager;
+import org.apache.shardingsphere.test.mock.AutoMockExtension;
+import org.apache.shardingsphere.test.mock.StaticMockSettings;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import java.lang.reflect.Method;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(AutoMockExtension.class)
+@StaticMockSettings(AgentReflectionUtils.class)
+class ShardingSphereDataSourceAdviceTest {
+    
+    private final TargetAdviceObjectFixture fixture = new 
TargetAdviceObjectFixture();
+    
+    private final String databaseName = "sharding_db";
+    
+    @BeforeEach
+    void setup() {
+        when(AgentReflectionUtils.getFieldValue(fixture, 
"databaseName")).thenReturn(databaseName);
+    }
+    
+    @AfterEach
+    void clean() {
+        ContextManagerHolder.getDatabaseContextManager().clear();
+    }
+    
+    @Test
+    void assertBeforeMethod() {
+        ContextManagerHolder.put(databaseName, mock(ContextManager.class, 
RETURNS_DEEP_STUBS));
+        assertThat(ContextManagerHolder.getDatabaseContextManager().size(), 
is(1));
+        Method method = mock(Method.class);
+        when(method.getName()).thenReturn("close");
+        ShardingSphereDataSourceAdvice advice = new 
ShardingSphereDataSourceAdvice();
+        advice.beforeMethod(fixture, method, new Object[]{}, "FIXTURE");
+        assertThat(ContextManagerHolder.getDatabaseContextManager().size(), 
is(0));
+    }
+    
+    @Test
+    void assertAfterMethod() {
+        assertThat(ContextManagerHolder.getDatabaseContextManager().size(), 
is(0));
+        Method method = mock(Method.class);
+        when(method.getName()).thenReturn("createContextManager");
+        ShardingSphereDataSourceAdvice advice = new 
ShardingSphereDataSourceAdvice();
+        advice.afterMethod(fixture, method, new Object[]{}, 
mock(ContextManager.class, RETURNS_DEEP_STUBS), "FIXTURE");
+        assertThat(ContextManagerHolder.getDatabaseContextManager().size(), 
is(1));
+        
assertThat(ContextManagerHolder.getDatabaseContextManager().keySet().iterator().next(),
 is(databaseName));
+    }
+}
diff --git 
a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java
 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java
index 89c4f6d481e..c954d12db8c 100644
--- 
a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java
+++ 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java
@@ -17,17 +17,19 @@
 
 package org.apache.shardingsphere.agent.plugin.metrics.core.exporter.impl.jdbc;
 
+import org.apache.shardingsphere.agent.plugin.core.holder.ContextManagerHolder;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.MetricsCollectorRegistry;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.collector.type.GaugeMetricFamilyMetricsCollector;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricCollectorType;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.fixture.collector.MetricsCollectorFixture;
-import org.apache.shardingsphere.driver.ShardingSphereDriver;
+import 
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import 
org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData;
+import 
org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit;
+import org.apache.shardingsphere.mode.manager.ContextManager;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
 
-import java.sql.DriverManager;
-import java.sql.SQLException;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Optional;
@@ -35,6 +37,9 @@ import java.util.Optional;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 class JDBCMetaDataInfoExporterTest {
     
@@ -44,14 +49,24 @@ class JDBCMetaDataInfoExporterTest {
                 MetricCollectorType.GAUGE_METRIC_FAMILY, "Meta data 
information of ShardingSphere-JDBC",
                 Arrays.asList("database", "type"), Collections.emptyMap());
         ((MetricsCollectorFixture) MetricsCollectorRegistry.get(config, 
"FIXTURE")).reset();
+        ContextManagerHolder.remove("sharding_db");
     }
     
     @Test
-    void assertExport() throws SQLException {
-        DriverManager.registerDriver(new ShardingSphereDriver());
-        
DriverManager.getConnection("jdbc:shardingsphere:classpath:config/driver/foo-driver-fixture.yaml");
+    void assertExport() {
+        ContextManagerHolder.put("sharding_db", 
mockContextManager("sharding_db"));
         Optional<GaugeMetricFamilyMetricsCollector> collector = new 
JDBCMetaDataInfoExporter().export("FIXTURE");
         assertTrue(collector.isPresent());
-        assertThat(collector.get().toString(), is("foo_driver_fixture_db=2, 
storage_unit_count=2"));
+        assertThat(collector.get().toString(), is("sharding_db=1, 
storage_unit_count=1"));
+    }
+    
+    private ContextManager mockContextManager(final String databaseName) {
+        ResourceMetaData resourceMetaData = mock(ResourceMetaData.class);
+        
when(resourceMetaData.getStorageUnits()).thenReturn(Collections.singletonMap("ds_0",
 mock(StorageUnit.class)));
+        ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, 
RETURNS_DEEP_STUBS);
+        when(database.getResourceMetaData()).thenReturn(resourceMetaData);
+        ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
+        when(result.getDatabase(databaseName)).thenReturn(database);
+        return result;
     }
 }
diff --git 
a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java
 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java
index 0be1c7f7b83..bbbb49a99b2 100644
--- 
a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java
+++ 
b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java
@@ -38,7 +38,7 @@ class JDBCStateExporterTest {
     
     @AfterEach
     void reset() {
-        MetricConfiguration config = new MetricConfiguration("jdbc_state", 
MetricCollectorType.GAUGE_METRIC_FAMILY, "State of ShardingSphere-JDBC. 0 is 
OK; 1 is CIRCUIT BREAK; 2 is LOCK");
+        MetricConfiguration config = new MetricConfiguration("jdbc_state", 
MetricCollectorType.GAUGE_METRIC_FAMILY, "State of ShardingSphere-JDBC. 0 is 
OK; 1 is CIRCUIT BREAK");
         ((MetricsCollectorFixture) MetricsCollectorRegistry.get(config, 
"FIXTURE")).reset();
     }
     
diff --git 
a/agent/plugins/metrics/core/src/test/resources/config/driver/foo-driver-fixture.yaml
 
b/agent/plugins/metrics/core/src/test/resources/config/driver/foo-driver-fixture.yaml
deleted file mode 100644
index 026cec85155..00000000000
--- 
a/agent/plugins/metrics/core/src/test/resources/config/driver/foo-driver-fixture.yaml
+++ /dev/null
@@ -1,57 +0,0 @@
-#
-# 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.
-#
-
-databaseName: foo_driver_fixture_db
-
-dataSources:
-  ds_0:
-    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
-    driverClassName: org.h2.Driver
-    jdbcUrl: 
jdbc:h2:mem:foo_ds_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL
-    username: sa
-    password:
-  ds_1:
-    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
-    driverClassName: org.h2.Driver
-    jdbcUrl: 
jdbc:h2:mem:foo_ds_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL
-    username: sa
-    password:
-
-rules:
-  - !SHARDING
-    autoTables:
-      t_order:
-        actualDataSources: ds_0,ds_1
-        shardingStrategy:
-          standard:
-            shardingColumn: order_id
-            shardingAlgorithmName: auto_mod
-        keyGenerateStrategy:
-          column: user_id
-          keyGeneratorName: snowflake
-    shardingAlgorithms:
-      auto_mod:
-        type: HASH_MOD
-        props:
-          sharding-count: 2
-    
-    keyGenerators:
-      snowflake:
-        type: SNOWFLAKE
-
-props:
-  sql-show: true
diff --git 
a/agent/plugins/metrics/type/prometheus/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/prometheus/exoprter/PrometheusMetricsExporter.java
 
b/agent/plugins/metrics/type/prometheus/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/prometheus/exoprter/PrometheusMetricsExporter.java
index f0cf50abc87..b2d1c30e5d7 100644
--- 
a/agent/plugins/metrics/type/prometheus/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/prometheus/exoprter/PrometheusMetricsExporter.java
+++ 
b/agent/plugins/metrics/type/prometheus/src/main/java/org/apache/shardingsphere/agent/plugin/metrics/prometheus/exoprter/PrometheusMetricsExporter.java
@@ -20,6 +20,7 @@ package 
org.apache.shardingsphere.agent.plugin.metrics.prometheus.exoprter;
 import io.prometheus.client.Collector;
 import io.prometheus.client.GaugeMetricFamily;
 import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import 
org.apache.shardingsphere.agent.plugin.metrics.core.exporter.MetricsExporter;
 
 import java.util.Collections;
@@ -29,13 +30,21 @@ import java.util.List;
  * Metrics exporter of Prometheus.
  */
 @RequiredArgsConstructor
+@Slf4j
 public final class PrometheusMetricsExporter extends Collector {
     
     private final MetricsExporter exporter;
     
     @Override
     public List<MetricFamilySamples> collect() {
-        return exporter.export("Prometheus")
-                .<List<MetricFamilySamples>>map(optional -> 
Collections.singletonList((GaugeMetricFamily) 
optional.getRawMetricFamilyObject())).orElse(Collections.emptyList());
+        try {
+            return exporter.export("Prometheus")
+                    .<List<MetricFamilySamples>>map(optional -> 
Collections.singletonList((GaugeMetricFamily) 
optional.getRawMetricFamilyObject())).orElse(Collections.emptyList());
+            // CHECKSTYLE:OFF
+        } catch (final Exception ex) {
+            // CHECKSTYLE:ON
+            log.warn("Collect metrics error: {}", ex.getMessage());
+        }
+        return Collections.emptyList();
     }
 }
diff --git 
a/agent/plugins/metrics/type/prometheus/src/main/resources/META-INF/conf/prometheus-advisors.yaml
 
b/agent/plugins/metrics/type/prometheus/src/main/resources/META-INF/conf/prometheus-advisors.yaml
index 6c9872bb64a..4becda5b19a 100644
--- 
a/agent/plugins/metrics/type/prometheus/src/main/resources/META-INF/conf/prometheus-advisors.yaml
+++ 
b/agent/plugins/metrics/type/prometheus/src/main/resources/META-INF/conf/prometheus-advisors.yaml
@@ -139,3 +139,11 @@ advisors:
     pointcuts:
       - name: rollback
         type: method
+  - target: 
org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource
+    advice: 
org.apache.shardingsphere.agent.plugin.metrics.core.advice.jdbc.ShardingSphereDataSourceAdvice
+    pointcuts:
+      - name: createContextManager
+        type: method
+      - name: close
+        type: method
+        paramLength: 0


Reply via email to