JTaky commented on code in PR #10156: URL: https://github.com/apache/paimon/pull/10156#discussion_r4270592163
########## 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: The warehouse path is normalized with Paimon Path before S3 alias folding and hashing. Added an embedded-ZooKeeper test that verifies equivalent paths contend for the same table lock. -- 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]
