swuferhong commented on code in PR #2179:
URL: https://github.com/apache/fluss/pull/2179#discussion_r2780266369


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/lease/KvSnapshotLeaseManager.java:
##########
@@ -0,0 +1,427 @@
+/*
+ * 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.fluss.server.coordinator.lease;
+
+import org.apache.fluss.annotation.VisibleForTesting;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableBucketSnapshot;
+import org.apache.fluss.metrics.MetricNames;
+import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup;
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.lease.KvSnapshotTableLease;
+import org.apache.fluss.utils.MapUtils;
+import org.apache.fluss.utils.clock.Clock;
+import org.apache.fluss.utils.concurrent.ExecutorThreadFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.utils.concurrent.LockUtils.inReadLock;
+import static org.apache.fluss.utils.concurrent.LockUtils.inWriteLock;
+
+/** A manager to manage kv snapshot lease acquire, renew, release and drop. */
+@ThreadSafe
+public class KvSnapshotLeaseManager {
+    private static final Logger LOG = 
LoggerFactory.getLogger(KvSnapshotLeaseManager.class);
+
+    private final KvSnapshotLeaseMetadataManager metadataManager;
+    private final Clock clock;
+    private final ScheduledExecutorService scheduledExecutor;
+    private final long leaseExpirationCheckInterval;
+
+    private final ReadWriteLock managerLock = new ReentrantReadWriteLock();
+
+    /** lease id to kv snapshot lease. */
+    @GuardedBy("managerLock")
+    private final ConcurrentHashMap<String, KvSnapshotLeaseHandler> 
kvSnapshotLeaseMap =
+            MapUtils.newConcurrentHashMap();
+
+    /**
+     * KvSnapshotLeaseForBucket to the ref count, which means this table 
bucket + snapshotId has
+     * been leased by how many lease id.
+     */
+    @GuardedBy("managerLock")
+    private final Map<TableBucketSnapshot, AtomicInteger> refCount =
+            MapUtils.newConcurrentHashMap();
+
+    /** For metrics. */
+    private final AtomicInteger leasedBucketCount = new AtomicInteger(0);
+
+    public KvSnapshotLeaseManager(
+            long leaseExpirationCheckInterval,
+            ZooKeeperClient zkClient,
+            String remoteDataDir,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this(
+                leaseExpirationCheckInterval,
+                zkClient,
+                remoteDataDir,
+                Executors.newScheduledThreadPool(
+                        1, new 
ExecutorThreadFactory("kv-snapshot-lease-cleaner")),
+                clock,
+                coordinatorMetricGroup);
+    }
+
+    @VisibleForTesting
+    public KvSnapshotLeaseManager(
+            long leaseExpirationCheckInterval,
+            ZooKeeperClient zkClient,
+            String remoteDataDir,
+            ScheduledExecutorService scheduledExecutor,
+            Clock clock,
+            CoordinatorMetricGroup coordinatorMetricGroup) {
+        this.metadataManager = new KvSnapshotLeaseMetadataManager(zkClient, 
remoteDataDir);
+        this.leaseExpirationCheckInterval = leaseExpirationCheckInterval;
+        this.scheduledExecutor = scheduledExecutor;
+        this.clock = clock;
+
+        registerMetrics(coordinatorMetricGroup);
+    }
+
+    public void start() {
+        LOG.info("kv snapshot lease manager has been started.");
+
+        List<String> leasesList = new ArrayList<>();
+        try {
+            leasesList = metadataManager.getLeasesList();
+        } catch (Exception e) {
+            LOG.error("Failed to get leases list from zookeeper.", e);
+        }
+
+        for (String leaseId : leasesList) {
+            Optional<KvSnapshotLeaseHandler> kvSnapshotLeaseOpt = 
Optional.empty();
+            try {
+                kvSnapshotLeaseOpt = metadataManager.getLease(leaseId);
+            } catch (Exception e) {
+                LOG.error("Failed to get kv snapshot lease from zookeeper.", 
e);
+            }
+
+            if (kvSnapshotLeaseOpt.isPresent()) {
+                KvSnapshotLeaseHandler kvSnapshotLeasehandle = 
kvSnapshotLeaseOpt.get();
+                this.kvSnapshotLeaseMap.put(leaseId, kvSnapshotLeasehandle);
+
+                initializeRefCount(kvSnapshotLeasehandle);
+
+                
leasedBucketCount.addAndGet(kvSnapshotLeasehandle.getLeasedSnapshotCount());
+            }
+        }
+
+        scheduledExecutor.scheduleWithFixedDelay(
+                this::expireLeases, 0L, leaseExpirationCheckInterval, 
TimeUnit.MILLISECONDS);
+    }
+
+    public boolean snapshotLeaseNotExist(TableBucketSnapshot 
tableBucketSnapshot) {
+        return inReadLock(
+                managerLock,
+                () -> {
+                    AtomicInteger count = refCount.get(tableBucketSnapshot);
+                    return count == null || count.get() <= 0;
+                });
+    }
+
+    /**
+     * Acquire kv snapshot lease.
+     *
+     * @param leaseId the lease id
+     * @param leaseDuration the lease duration
+     * @param tableIdToLeaseBucket the table id to lease bucket
+     * @return the map of unavailable snapshots that failed to be leased
+     */
+    public Map<TableBucket, Long> acquireLease(

Review Comment:
   trace by: https://github.com/apache/fluss/issues/2603



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