Skip to content

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

Test for concurrent cluster lock creation with fix for postgres (#62204)

Chris Trutercd2b8d5ba807
diff --git a/src/metabase/app_db/cluster_lock.clj b/src/metabase/app_db/cluster_lock.clj
index 6e6857c1a2b..666af7a638d 100644
--- a/src/metabase/app_db/cluster_lock.clj
+++ b/src/metabase/app_db/cluster_lock.clj
@@ -1,6 +1,7 @@
(ns metabase.app-db.cluster-lock
"Utility for taking a cluster wide lock using the application database"
(:require
+ [clojure.string :as str]
[metabase.app-db.connection :as mdb.connection]
[metabase.app-db.query :as mdb.query]
[metabase.app-db.query-cancelation :as app-db.query-cancelation]
@@ -22,6 +23,8 @@
;; was cancelled via timeout waiting to get the SELECT FOR UPDATE lock
(or (instance? SQLIntegrityConstraintViolationException e)
(instance? SQLIntegrityConstraintViolationException (ex-cause e))
+ ;; Postgres does just uses PSQLException, so we need to fall back to checking the message.
+ (str/includes? (ex-message e) "duplicate key value violates unique constraint \"metabase_cluster_lock_pkey\"")
(app-db.query-cancelation/query-canceled-exception? (mdb.connection/db-type) e)))
(def ^:private default-retry-config
@@ -54,6 +57,8 @@
(with-open [stmt (prepare-statement conn lock-name-str timeout-seconds)
result-set (.executeQuery stmt)]
(when-not (.next result-set)
+ ;; this record will not be visible until the tx commits, so there's no need to lock it
+ ;; we instead rely on concurrent threads having constraint violation trying to insert their own record
(t2/query-one {:insert-into [:metabase_cluster_lock]
:columns [:lock_name]
:values [[lock-name-str]]})))
@@ -71,7 +76,9 @@
[:retry-config {:optional true} [:ref ::retry/retry-overrides]]]]
thunk :- ifn?]
(cond
- (= (mdb.connection/db-type) :h2) (thunk) ;; h2 does not respect the query timeout when taking the lock
+ ;; h2 does not respect the query timeout when taking the lock
+ ;; we do not support multiple instances for h2 however, so an in-process lock is sufficient.
+ (= (mdb.connection/db-type) :h2) (locking do-with-cluster-lock (thunk))
(keyword? opts) (do-with-cluster-lock {:lock-name opts} thunk)
:else (let [{:keys [timeout-seconds retry-config lock-name] :or {timeout-seconds cluster-lock-timeout-seconds}} opts
lock-name-str (str (namespace lock-name) "/" (name lock-name))
diff --git a/test/metabase/app_db/cluster_lock_test.clj b/test/metabase/app_db/cluster_lock_test.clj
index 47603f659a1..8414400f0cb 100644
--- a/test/metabase/app_db/cluster_lock_test.clj
+++ b/test/metabase/app_db/cluster_lock_test.clj
@@ -4,7 +4,11 @@
[clojure.test :refer :all]
[metabase.app-db.cluster-lock :as sut]
[metabase.app-db.core :as mdb]
- [metabase.test.fixtures :as fixtures]))
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [toucan2.core :as t2])
+ (:import
+ (java.util.concurrent CountDownLatch TimeUnit)))
(set! *warn-on-reflection* true)
@@ -35,3 +39,42 @@
(future (sut/with-cluster-lock ::test-lock (a/<!! fin-chan)))
(future (Thread/sleep 500) (a/>!! fin-chan :done))
(is (nil? (sut/with-cluster-lock ::test-lock (Thread/sleep 1))))))))
+
+(deftest concurrent-lock-creation-race-test
+ (testing "Two threads racing to create the same lock for the first time"
+ ;; h2 is not race-proof, but it is also not cross-process
+ (when (not= (mdb/db-type) :h2)
+ ;; Ensure that we are creating the lock for the first time
+ (t2/delete! :metabase_cluster_lock :lock_name (u/qualified-name ::race-test-lock))
+
+ (let [results (atom [])
+ result! (partial swap! results conj)
+ thread! (fn [id ^CountDownLatch start-latch ^CountDownLatch end-latch thunk]
+ (future
+ (try
+ (sut/with-cluster-lock ::race-test-lock
+ (try
+ (.countDown start-latch)
+ (thunk)
+ (result! [id :done])
+ (catch Exception e
+ (result! [id :failed (:reason (ex-data e) :unknown)]))))
+ (catch Exception e
+ (result! [:a :locking-failed e]))
+ (finally
+ (.countDown end-latch)))))
+ a-started (CountDownLatch. 1)
+ b-started (CountDownLatch. 1)
+ a-ended (CountDownLatch. 1)
+ b-ended (CountDownLatch. 1)]
+
+ (thread! :a a-started a-ended
+ #(when-not (.await b-started 1 TimeUnit/SECONDS)
+ (throw (ex-info "B did not start while A was still running" {:reason :timeout}))))
+ (.await a-started)
+ (thread! :b b-started b-ended
+ #(.await a-ended))
+ (.await b-ended)
+ (is (= [[:a :failed :timeout]
+ [:b :done]]
+ @results))))))