Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Read c3p0 pool stats from the pool objects instead of JMX (#82760)

John Swanson22b1a393dc69
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e14553953ef..0c8b898e758 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -909,7 +909,6 @@
metabase.driver.settings
metabase.driver.sql
metabase.driver.sql-jdbc
- metabase.driver.sql-jdbc.connection.pool-lock
metabase.driver.sql-jdbc.execute
metabase.driver.sql-jdbc.execute.diagnostic
metabase.driver.sql-jdbc.sync
diff --git a/resources/c3p0.properties b/resources/c3p0.properties
index 77c1c0e291e..e36510fc7cd 100644
--- a/resources/c3p0.properties
+++ b/resources/c3p0.properties
@@ -3,3 +3,7 @@ c3p0.minPoolSize=1
com.mchange.v2.c3p0.impl.DefaultConnectionTester.isValidTimeout=6
c3p0.unreturnedConnectionTimeout=300
c3p0.debugUnreturnedConnectionStackTraces=true
+# Register no JMX MBeans (per pool, or the registry bean). Reading a pool's MBean while that pool is being built
+# deadlocks inside c3p0 (https://github.com/swaldman/c3p0/issues/95); Metabase reads pool stats from the pool objects
+# instead.
+com.mchange.v2.c3p0.management.ManagementCoordinator=com.mchange.v2.c3p0.management.NullManagementCoordinator
diff --git a/src/metabase/analytics/prometheus.clj b/src/metabase/analytics/prometheus.clj
index d2904c2029f..9d031f47a9d 100644
--- a/src/metabase/analytics/prometheus.clj
+++ b/src/metabase/analytics/prometheus.clj
@@ -6,7 +6,6 @@
Api is quite simple: [[setup!]] and [[shutdown!]]. After that you can retrieve metrics from
http://localhost:<prometheus-server-port>/metrics."
(:require
- [clojure.java.jmx :as jmx]
[clojure.string :as str]
[iapetos.collector :as collector]
[iapetos.collector.ring :as collector.ring]
@@ -15,8 +14,6 @@
[jvm-alloc-rate-meter.core :as alloc-rate-meter]
[jvm-hiccup-meter.core :as hiccup-meter]
[metabase.analytics-interface.core :as analytics.interface]
- ;; We should not be using specific driver implementations
- [metabase.driver.sql-jdbc.connection.pool-lock :as pool-lock]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]
[metabase.util.log :as log]
@@ -24,6 +21,7 @@
[potemkin.types :as p.types]
[ring.adapter.jetty :as ring-jetty])
(:import
+ (com.mchange.v2.c3p0 C3P0Registry PoolBackedDataSource WrapperConnectionPoolDataSource)
(io.prometheus.client Collector GaugeMetricFamily SimpleCollector)
(io.prometheus.client.hotspot
GarbageCollectorExports
@@ -31,7 +29,6 @@
StandardExports
ThreadExports)
(java.util ArrayList List)
- (javax.management ObjectName)
(org.eclipse.jetty.server Server)))
(set! *warn-on-reflection* true)
@@ -136,24 +133,40 @@
(log/warnf "Unrecognized measurement %s in prometheus stats" raw-label)))
arr))
-(defn- conn-pool-bean-diag-info [acc ^ObjectName jmx-bean]
- ;; Using this `locking` is non-obvious but absolutely required to avoid the deadlock inside c3p0 implementation. The
- ;; act of JMX attribute reading first locks a DynamicPooledDataSourceManagerMBean object, and then a
- ;; PoolBackedDataSource object. Conversely, the act of creating a pool (with
- ;; com.mchange.v2.c3p0.DataSources/pooledDataSource) first locks PoolBackedDataSource and then
- ;; DynamicPooledDataSourceManagerMBean. We have to lock a common monitor (which `pool-lock/monitor` is)
- ;; to prevent the deadlock. Hopefully.
- ;; Issue against c3p0: https://github.com/swaldman/c3p0/issues/95
- (locking pool-lock/monitor
- (let [bean-id (.getCanonicalName jmx-bean)
- props [:numConnections :numIdleConnections :numBusyConnections
- :minPoolSize :maxPoolSize :numThreadsAwaitingCheckoutDefaultUser]]
- (assoc acc (jmx/read bean-id :dataSourceName) (jmx/read bean-id props)))))
+(defn- pool-stats
+ "The stats for one c3p0 pool, read with its default-user getters."
+ [^PoolBackedDataSource pool]
+ ;; The pool-size bounds live on the wrapped ConnectionPoolDataSource, not on the pool itself.
+ (let [cpds (.getConnectionPoolDataSource pool)]
+ (cond-> {:numConnections (.getNumConnections pool)
+ :numIdleConnections (.getNumIdleConnections pool)
+ :numBusyConnections (.getNumBusyConnections pool)
+ :numThreadsAwaitingCheckoutDefaultUser (.getNumThreadsAwaitingCheckoutDefaultUser pool)}
+ (instance? WrapperConnectionPoolDataSource cpds)
+ (assoc :minPoolSize (.getMinPoolSize ^WrapperConnectionPoolDataSource cpds)
+ :maxPoolSize (.getMaxPoolSize ^WrapperConnectionPoolDataSource cpds)))))
(defn connection-pool-info
- "Builds a map of info about the current c3p0 connection pools managed by this Metabase instance."
+ "Builds a map of info about the current c3p0 connection pools managed by this Metabase instance: every unclosed pool
+ of every kind (warehouse, application, Quartz, semantic search), keyed by pool name (the c3p0 `dataSourceName`). A
+ pool closed while this runs is skipped for this call and logged at debug."
[]
- (reduce conn-pool-bean-diag-info {} (jmx/mbean-names "com.mchange.v2.c3p0:type=PooledDataSource,*")))
+ ;; Read the stats from the pool objects, never through their JMX MBeans. A JMX attribute read locks the MBean and
+ ;; then the pool, while pool construction locks the pool and then the MBean (its property-change listener), so a
+ ;; scrape that overlapped a pool build deadlocked: https://github.com/swaldman/c3p0/issues/95. Reading the pool
+ ;; directly takes the pool's own monitors in the same order construction does, so the cycle cannot form; a scrape
+ ;; only waits while that one pool is mid-construction. `getPooledDataSources` returns a copy made under the
+ ;; registry lock, which is released before any pool is touched.
+ (into {}
+ (keep (fn [pool]
+ (when (instance? PoolBackedDataSource pool)
+ (let [^PoolBackedDataSource pool pool]
+ (try
+ [(.getDataSourceName pool) (pool-stats pool)]
+ (catch Exception e
+ (log/debugf e "Skipping c3p0 pool %s in this scrape" (.getDataSourceName pool))
+ nil))))))
+ (C3P0Registry/getPooledDataSources)))
(def ^:private c3p0-collector
"c3p0 collector delay"
@@ -340,7 +353,7 @@
:labels [:storage]})
;; Probed hourly, so an outage takes up to that long to show up. The dedicated probe opens its own
;; connection, so a store that is up but whose pool is saturated still reads as connected --
- ;; metabase_database_c3p0_* covers that. The app-db probe shares the application pool, and does not.
+ ;; c3p0_* covers that. The app-db probe shares the application pool, and does not.
(prometheus/gauge :metabase-pgvector/store-connected
{:description "Whether the last connection probe to the given pgvector storage succeeded."
:labels [:storage]})
diff --git a/src/metabase/driver/sql_jdbc/connection.clj b/src/metabase/driver/sql_jdbc/connection.clj
index 0317aa1ba3d..676e348c2b9 100644
--- a/src/metabase/driver/sql_jdbc/connection.clj
+++ b/src/metabase/driver/sql_jdbc/connection.clj
@@ -133,6 +133,22 @@
:catalog)
details))
+(def ^:private pool-type->name-suffix
+ "Suffix appended to the pool name for each non-default [[driver.conn/connection-pool-type]]."
+ {:write-data "-write"
+ :admin "-admin"
+ :transform "-transform"})
+
+(defn- pool-data-source-name
+ "The c3p0 `dataSourceName` for `database`'s pool of the current connection type: `db-<id>-<driver>-<name>`, with
+ `-write` (or the other suffixes in [[pool-type->name-suffix]]) appended for a non-default pool type."
+ [driver database]
+ (str (format "db-%d-%s-%s"
+ (u/the-id database)
+ (name driver)
+ (data-source-name driver (driver.conn/effective-details database)))
+ (pool-type->name-suffix (driver.conn/connection-pool-type database))))
+
(defmethod data-warehouse-connection-pool-properties :default
[driver database]
{;; only fetch one new connection at a time, rather than batching fetches (default = 3 at a time). This is done in
@@ -224,12 +240,10 @@
"com.mchange namespace. You must raise the log level for"
"com.mchange to INFO via a custom Log4j config in order to"
"see stacktraces in the logs.")))
- ;; Set the data source name so that the c3p0 JMX bean has a useful identifier, which incorporates the DB ID, driver,
- ;; and name from the details
- "dataSourceName" (format "db-%d-%s-%s"
- (u/the-id database)
- (name driver)
- (data-source-name driver (driver.conn/effective-details database)))})
+ ;; Set the data source name so that the pool has a useful identifier, which incorporates the DB ID, driver, and name
+ ;; from the details. It is the `database` label on the exported c3p0_* pool metrics, so a non-default pool type gets
+ ;; a suffix: otherwise the default and write pools of one warehouse would share a label and overwrite each other.
+ "dataSourceName" (pool-data-source-name driver database)})
(defn- connection-pool-spec
"Like [[connection-pool/connection-pool-spec]] but also handles situations when the unpooled spec is a `:datasource`."
diff --git a/src/metabase/driver/sql_jdbc/connection/pool_lock.clj b/src/metabase/driver/sql_jdbc/connection/pool_lock.clj
index 5d5d03ff258..db8d2beacd9 100644
--- a/src/metabase/driver/sql_jdbc/connection/pool_lock.clj
+++ b/src/metabase/driver/sql_jdbc/connection/pool_lock.clj
@@ -1,12 +1,7 @@
(ns metabase.driver.sql-jdbc.connection.pool-lock
- "The monitor serializing c3p0 pool creation against reads of c3p0's JMX attributes.
-
- Holding it on both sides is required to avoid a deadlock inside c3p0: reading a JMX attribute locks a
- DynamicPooledDataSourceManagerMBean and then a PoolBackedDataSource, while
- `com.mchange.v2.c3p0.DataSources/pooledDataSource` locks the two in the opposite order. See
- https://github.com/swaldman/c3p0/issues/95
-
- Carries no requires so that the JMX reader can take the same monitor without loading the driver.")
+ "The monitor that serializes warehouse pool creation, so two threads cannot build pools for the same database at
+ once. Query execution waits on it whenever a warehouse pool does not exist yet, so take it only around pool creation
+ and never around anything slow.")
(defonce ^{:doc "The monitor object. Take it with `locking`."} monitor
(Object.))
diff --git a/test/metabase/analytics/prometheus_test.clj b/test/metabase/analytics/prometheus_test.clj
index 3b689466183..5e118befb46 100644
--- a/test/metabase/analytics/prometheus_test.clj
+++ b/test/metabase/analytics/prometheus_test.clj
@@ -6,12 +6,17 @@
[clojure.test :refer :all]
[iapetos.registry :as registry]
[metabase.analytics.prometheus :as prometheus]
+ [metabase.app-db.connection-pool-setup :as mdb.connection-pool-setup]
+ [metabase.app-db.data-source :as mdb.data-source]
+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.search.engine :as search.engine]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u])
(:import
- (io.prometheus.client Collector GaugeMetricFamily)))
+ (com.mchange.v2.c3p0 DataSources)
+ (io.prometheus.client Collector GaugeMetricFamily)
+ (java.lang.management ManagementFactory)))
(set! *warn-on-reflection* true)
@@ -144,6 +149,73 @@
(is (seq (set/intersection expected-lines actual-lines))
"Registry does not have c3p0 metrics in it")))))
+(defn- start-daemon-thread! ^Thread [^String thread-name f]
+ (doto (Thread. ^Runnable f thread-name)
+ (.setDaemon true)
+ (.start)))
+
+(deftest connection-pool-info-does-not-deadlock-pool-construction-test
+ (testing "reading pool stats while another thread builds a pool must not deadlock (swaldman/c3p0#95)"
+ ;; The application, Quartz and semantic-search pools are built outside the warehouse pool guard. A scrape that
+ ;; overlapped one of those constructions used to deadlock inside c3p0 (JMX read locks the pool MBean then the
+ ;; pool; construction locks them the other way round) and then hold the guard forever, so no warehouse pool could
+ ;; be built afterwards. One thread scrapes continuously, one builds and destroys a fixed number of pools through
+ ;; the app-db path, and a third builds a warehouse pool through the guarded path. All three must finish.
+ (let [num-builds 25
+ timeout-ms 10000
+ stop? (atom false)
+ errors (atom [])
+ scrapes (atom 0)
+ first-scrape (promise)
+ builds-done (promise)
+ warehouse-built (promise)]
+ (mt/with-temp [:model/Database db {:engine :h2, :details {:db (str "mem:" (mt/random-name))}}]
+ (try
+ (start-daemon-thread!
+ "prometheus-test-scraper"
+ (fn []
+ (while (not @stop?)
+ (try
+ (prometheus/connection-pool-info)
+ (swap! scrapes inc)
+ (deliver first-scrape true)
+ (catch Exception e
+ (swap! errors conj e))))))
+ (start-daemon-thread!
+ "prometheus-test-app-pool-builder"
+ (fn []
+ (dotimes [_ num-builds]
+ (try
+ (let [pool (mdb.connection-pool-setup/connection-pool-data-source
+ :h2
+ (mdb.data-source/raw-connection-string->DataSource
+ (format "jdbc:h2:mem:%s" (mt/random-name))))]
+ (DataSources/destroy pool))
+ (catch Exception e
+ (swap! errors conj e))))
+ (deliver builds-done true)))
+ (start-daemon-thread!
+ "prometheus-test-warehouse-pool-builder"
+ (fn []
+ ;; start once scraping is under way, so a wedged guard is what this thread would run into
+ (when (true? (deref first-scrape timeout-ms false))
+ (try
+ (sql-jdbc.conn/db->pooled-connection-spec db)
+ (deliver warehouse-built true)
+ (catch Exception e
+ (swap! errors conj e))))))
+ (is (true? (deref builds-done timeout-ms false))
+ "the pool-building thread did not finish its builds: a build deadlocked with a scrape")
+ (is (nil? (.findDeadlockedThreads (ManagementFactory/getThreadMXBean)))
+ "a scrape deadlocked with a pool construction")
+ (is (pos? @scrapes) "the scrape thread never completed a read")
+ (is (true? (deref warehouse-built timeout-ms false))
+ "the warehouse pool build did not complete: the pool guard is wedged")
+ (is (empty? @errors))
+ (finally
+ (reset! stop? true)
+ (sql-jdbc.conn/invalidate-pool-for-db! db)))))))
+
(deftest email-collector-test
(testing "Registry has email metrics registered"
(mt/with-prometheus-system! [port _]
diff --git a/test/metabase/app_db/connection_pool_setup_test.clj b/test/metabase/app_db/connection_pool_setup_test.clj
index 6a4ef45e3e2..91f151bdf0a 100644
--- a/test/metabase/app_db/connection_pool_setup_test.clj
+++ b/test/metabase/app_db/connection_pool_setup_test.clj
@@ -8,12 +8,15 @@
[metabase.app-db.data-source :as mdb.data-source]
[metabase.config.core :as config]
[metabase.connection-pool :as connection-pool]
+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan2.core :as t2])
(:import
(com.mchange.v2.c3p0 C3P0Registry ConnectionCustomizer DataSources PoolBackedDataSource WrapperConnectionPoolDataSource)
+ (java.lang.management ManagementFactory)
+ (javax.management ObjectName)
(metabase.app_db.connection_pool_setup MetabaseConnectionCustomizer)))
(set! *warn-on-reflection* true)
@@ -49,6 +52,28 @@
(dotimes [_ 5]
(t2/count :model/Database)))
+(deftest no-c3p0-mbeans-test
+ (testing "c3p0 registers no JMX MBeans for its pools (resources/c3p0.properties turns its management off)"
+ ;; see the comment in resources/c3p0.properties for why
+ (let [c3p0-beans #(.queryNames (ManagementFactory/getPlatformMBeanServer) (ObjectName. "com.mchange.v2.c3p0:*") nil)
+ app-pool (mdb.connection-pool-setup/connection-pool-data-source
+ :h2
+ (mdb.data-source/raw-connection-string->DataSource
+ (format "jdbc:h2:mem:%s" (mt/random-name))))]
+ (try
+ (testing "after building the application pool"
+ (is (empty? (c3p0-beans))))
+ (testing "after building a warehouse pool"
+ ;; a fresh database, so this builds a pool rather than finding a cached one
+ (mt/with-temp [:model/Database db {:engine :h2, :details {:db (str "mem:" (mt/random-name))}}]
+ (try
+ (sql-jdbc.conn/db->pooled-connection-spec db)
+ (is (empty? (c3p0-beans)))
+ (finally
+ (sql-jdbc.conn/invalidate-pool-for-db! db)))))
+ (finally
+ (connection-pool/destroy-connection-pool! app-pool))))))
+
(deftest MetabaseConnectionCustomizer-test
(testing "connection customizer is registered"
(let [customizer (C3P0Registry/getConnectionCustomizer (.getName MetabaseConnectionCustomizer))]
diff --git a/test/metabase/driver/sql_jdbc/connection_test.clj b/test/metabase/driver/sql_jdbc/connection_test.clj
index 6b7dd463f67..98ad3efdca0 100644
--- a/test/metabase/driver/sql_jdbc/connection_test.clj
+++ b/test/metabase/driver/sql_jdbc/connection_test.clj
@@ -235,6 +235,35 @@
;; ensure that, for any sql-jdbc driver anyway, we found *some* DB name to use in this String
(is (not= "null" db-nm))))))
+(deftest ^:parallel c3p0-pool-type-suffix-covers-every-non-default-type-test
+ (testing "every non-default connection type has a pool-name suffix, or two of its pools would share a metrics label"
+ (is (= (disj (set driver.conn/connection-types) :default)
+ (set (keys @#'sql-jdbc.conn/pool-type->name-suffix))))))
+
+(deftest c3p0-datasource-name-pool-type-suffix-test
+ (mt/test-driver :h2
+ (when config/ee-available?
+ (mt/with-premium-features #{:writable-connection}
+ (testing "a non-default pool type gets a name suffix, so two pools of one warehouse never share a metrics label"
+ (mt/with-temp [:model/Database database {:engine :h2
+ :details {:db "mem:pool_name_default_db"}
+ :write_data_details {:db "mem:pool_name_write_db"}}]
+ (let [pool-name #(get (sql-jdbc.conn/data-warehouse-connection-pool-properties :h2 database) "dataSourceName")
+ db-id (u/the-id database)]
+ (is (= (format "db-%d-h2-mem:pool_name_default_db" db-id)
+ (pool-name)))
+ (is (= (format "db-%d-h2-mem:pool_name_write_db-write" db-id)
+ (driver.conn/with-write-connection (pool-name)))))))
+ (testing "a write connection without write details resolves to the default pool, so its name has no suffix"
+ (mt/with-temp [:model/Database database {:engine :h2, :details {:db "mem:pool_name_default_only_db"}}]
+ (let [pool-name #(get (sql-jdbc.conn/data-warehouse-connection-pool-properties :h2 database) "dataSourceName")
+ db-id (u/the-id database)]
+ (is (= (format "db-%d-h2-mem:pool_name_default_only_db" db-id)
+ (driver.conn/with-write-connection (pool-name))))
+ (testing "but the transform pool is always separate, so its name always carries the suffix"
+ (is (= (format "db-%d-h2-mem:pool_name_default_only_db-transform" db-id)
+ (driver.conn/with-transform-connection (pool-name))))))))))))
+
(deftest ^:parallel same-connection-details-result-in-equal-specs-test
(testing "Two JDBC specs created with the same details must be considered equal for the connection pool cache to work correctly"
;; this is only really a concern for drivers like Spark SQL that create custom DataSources instead of plain details