JTaky commented on code in PR #10156: URL: https://github.com/apache/paimon/pull/10156#discussion_r4316210448
########## paimon-core/src/main/java/org/apache/paimon/zookeeper/ZooKeeperCatalogLock.java: ########## @@ -0,0 +1,301 @@ +/* + * 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.Identifier; +import org.apache.paimon.fs.Path; +import org.apache.paimon.operation.Lock; + +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 Lock { + + 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 ensureValid 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 Identifier identifier; + + private final ConcurrentHashMap<String, TrackedMutex> mutexes = new ConcurrentHashMap<>(); + private final ThreadLocal<HeldLock> heldLock = new ThreadLocal<>(); + + private static final class HeldLock { + final TrackedMutex mutex; + final String path; + final String node; + final long epoch; + final HeldLock previous; + + HeldLock(TrackedMutex mutex, String path, String node, long epoch, HeldLock previous) { + this.mutex = mutex; + this.path = path; + this.node = node; + this.epoch = epoch; + this.previous = previous; + } + } + + /** Exposes the mutex's lock-node path so {@link #ensureValid} 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, + Identifier identifier) { + this.client = client; + this.sessionEpoch = sessionEpoch; + this.releaseClient = releaseClient; + this.warehouseHash = hashWarehouse(warehouse); + this.acquireTimeoutMillis = acquireTimeoutMillis; + this.identifier = identifier; + } + + @Override + public AutoCloseable acquire() throws Exception { + if (identifier == null) { + throw new IllegalStateException("A table identifier is required to acquire the lock."); + } + return acquire(identifier.getDatabaseName(), identifier.getTableName()); + } + + private AutoCloseable acquire(String database, String table) 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)); + } + + HeldLock acquiredLock = + new HeldLock(mutex, path, mutex.heldNode(), sessionEpoch.get(), heldLock.get()); + heldLock.set(acquiredLock); + return () -> { + heldLock.set(acquiredLock.previous); + try { + if (mutex.heldNode() != null) { + mutex.release(); + } + } catch (Exception e) { + LOG.warn( + "paimon_lock_release_failed releasing lock '{}' for {}.{}", + path, + database, + table, + e); + } + }; + } + + <T> T runWithLock(String database, String table, Callable<T> callable) throws Exception { + AutoCloseable scope = acquire(database, table); + Throwable failure = null; + try { + return callable.call(); + } catch (Exception | Error e) { + failure = e; + throw e; + } finally { + Lock.release(scope, failure); + } + } + + @Override + public void ensureValid() { + HeldLock current = heldLock.get(); + if (current == null) { + throw new IllegalStateException("No ZooKeeper lock is held by this thread."); + } + + boolean epochChanged = sessionEpoch.get() != current.epoch; + boolean nodeGone; + try { + nodeGone = current.node == null || client.checkExists().forPath(current.node) == null; + } catch (Exception e) { Review Comment: Thanks for the point. Fixed. Interrupted `checkExists()` now restores the thread’s interrupt flag and throws with the InterruptedException retained as the cause, instead of treating it as a missing lock node. Scope release now passes exceptions to Lock.release, which preserves interruption and suppresses release errors onto the operation failure. I also restored interruption during explicit `close()`. Added focused tests for all three paths, including a check that interrupted verification does not reach publication. -- 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]
