JingsongLi commented on code in PR #10156:
URL: https://github.com/apache/paimon/pull/10156#discussion_r4253846999


##########
paimon-core/pom.xml:
##########
@@ -79,8 +79,55 @@ under the License.
             </exclusions>
         </dependency>
 
+        <dependency>
+            <groupId>org.apache.curator</groupId>
+            <artifactId>curator-recipes</artifactId>
+            <version>${curator.version}</version>
+            <scope>provided</scope>

Review Comment:
   [P2] Make the compatible Curator runtime available to engine users
   
   These new dependencies are provided, so the published engine artifacts 
neither include nor transitively supply the Curator version used by the new 
lock. Supported Spark 3.4.3 supplies curator-recipes 2.13.0 (the default Hadoop 
2.8.5 stack also has 2.7.1); isOwnedByCurrentThread is package-private in those 
versions, whereas this implementation invokes it from outside that package. 
Against the same real ZooKeeper server, the production factory/runWithLock 
probe succeeds with the PR test classpath (Curator 5.6.0) but fails with the 
Curator client/framework/recipes 2.13.0 set: IllegalAccessError at 
runWithLock:154 and again at close:247. Core tests pin the newer libraries and 
do not exercise that engine runtime. Flink relocated classes also cannot 
satisfy these unrelocated imports. Please ship an isolated compatible 
dependency set, or provide explicit compatible-library installation 
requirements and engine-classpath tests, so enabling lock.type=zookeeper on a 
supported distribution ac
 tually works.



##########
paimon-core/src/main/java/org/apache/paimon/zookeeper/ZooKeeperCatalogLock.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.paimon.zookeeper;
+
+import org.apache.paimon.catalog.CatalogLock;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.recipes.locks.InterProcessMutex;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+/** ZooKeeper catalog lock, backed by a Curator {@link InterProcessMutex} per 
znode path. */
+public class ZooKeeperCatalogLock implements CatalogLock {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ZooKeeperCatalogLock.class);
+
+    private final CuratorFramework client;
+
+    // Shared with every lock built from the same client; bumped on session 
loss. See
+    // ZooKeeperCatalogLockFactory#newClient. isAcquiredInThisProcess() alone 
cannot detect a
+    // session expiry, since Curator never updates it on connection loss, so 
runWithLock also
+    // checks this epoch and does a synchronous checkExists() round trip.
+    private final AtomicLong sessionEpoch;
+    private final Runnable releaseClient;
+    private final AtomicBoolean closed = new AtomicBoolean();
+
+    private final String warehouseHash;
+    private final long acquireTimeoutMillis;
+
+    private final ConcurrentHashMap<String, TrackedMutex> mutexes = new 
ConcurrentHashMap<>();
+
+    /** Exposes the mutex's lock-node path so {@link #runWithLock} can 
re-verify it exists. */
+    private static final class TrackedMutex extends InterProcessMutex {
+        TrackedMutex(CuratorFramework client, String path) {
+            super(client, path);
+        }
+
+        String heldNode() {
+            return getLockPath();
+        }
+    }
+
+    ZooKeeperCatalogLock(
+            CuratorFramework client,
+            AtomicLong sessionEpoch,
+            Runnable releaseClient,
+            String warehouse,
+            long acquireTimeoutMillis) {
+        this.client = client;
+        this.sessionEpoch = sessionEpoch;
+        this.releaseClient = releaseClient;
+        this.warehouseHash = hashWarehouse(warehouse);
+        this.acquireTimeoutMillis = acquireTimeoutMillis;
+    }
+
+    @Override
+    public <T> T runWithLock(String database, String table, Callable<T> 
callable) throws Exception {
+        String path = lockPath(database, table);
+        TrackedMutex mutex = mutexes.computeIfAbsent(path, p -> new 
TrackedMutex(client, p));
+
+        boolean acquired;
+        try {
+            acquired = mutex.acquire(acquireTimeoutMillis, 
TimeUnit.MILLISECONDS);
+        } catch (Exception e) {
+            LOG.error(
+                    "paimon_lock_acquire_error acquiring lock '{}' for {}.{}",
+                    path,
+                    database,
+                    table,
+                    e);
+            throw e;
+        }
+
+        if (!acquired) {
+            LOG.error(
+                    "paimon_lock_acquire_timeout Timed out after {}ms 
acquiring lock '{}' for {}.{}",
+                    acquireTimeoutMillis,
+                    path,
+                    database,
+                    table);
+            throw new IllegalStateException(
+                    String.format(
+                            "Timed out after %dms acquiring ZooKeeper lock 
'%s' for %s.%s",
+                            acquireTimeoutMillis, path, database, table));
+        }
+
+        long acquiredEpoch = sessionEpoch.get();
+        String heldNode = mutex.heldNode();
+
+        try {
+            T result = callable.call();
+
+            boolean epochChanged = sessionEpoch.get() != acquiredEpoch;
+            boolean nodeGone;
+            try {
+                nodeGone = heldNode == null || 
client.checkExists().forPath(heldNode) == null;
+            } catch (Exception e) {
+                nodeGone = true;
+                LOG.warn(
+                        "paimon_lock_verify_failed could not re-verify lock 
node '{}'",
+                        heldNode,
+                        e);
+            }
+
+            if (!mutex.isOwnedByCurrentThread() || epochChanged || nodeGone) {
+                String reason =
+                        nodeGone
+                                ? "lock_node_gone"
+                                : epochChanged ? "session_epoch_changed" : 
"local_record_cleared";
+                LOG.error(
+                        "paimon_lock_lost Lost lock '{}' for {}.{} inside the 
commit critical"
+                                + " section (reason={})",
+                        path,
+                        database,
+                        table,
+                        reason);
+                throw new IllegalStateException(
+                        String.format(
+                                "Lost ZooKeeper lock '%s' for %s.%s while 
inside the commit"
+                                        + " critical section (%s)",
+                                path, database, table, reason));
+            }
+            return result;
+        } finally {
+            try {
+                if (mutex.isOwnedByCurrentThread()) {
+                    mutex.release();
+                }
+            } catch (Exception e) {
+                LOG.warn(
+                        "paimon_lock_release_failed releasing lock '{}' for 
{}.{}",
+                        path,
+                        database,
+                        table,
+                        e);
+            }
+        }
+    }
+
+    private String lockPath(String database, String table) {
+        return "/" + warehouseHash + "/" + sanitize(database) + "/" + 
sanitize(table);
+    }
+
+    /** A warehouse URI cannot appear in a znode path literally, so it is 
hashed. */
+    static String hashWarehouse(String warehouse) {
+        String normalized = normalizeS3Path(warehouse.trim());

Review Comment:
   [P1] Normalize the physical warehouse before deriving its lock namespace
   
   CatalogFactory normalizes the storage warehouse with Paimon Path, but passes 
the original options through CatalogLockContext. This hash handles S3 scheme 
aliases and trailing slashes, not the same Path normalization. Thus 
s3://test-bucket/a//b and s3://test-bucket/a/b address the identical physical 
warehouse but use different znodes (dot segments have the same problem). I 
verified Path equality and, with the real embedded ZooKeeper server and two 
factory-created locks, held the first table lock while a second thread 
successfully entered the same db/table through the other warehouse spelling. 
The new lock therefore does not serialize those two writers/compaction jobs, 
exposing the object-store snapshot overwrite risk it is intended to prevent. 
Please normalize with Paimon Path as CatalogFactory does before applying the S3 
alias folding and hashing; add an actual mutual-exclusion test for these 
physical path aliases.



-- 
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]

Reply via email to