zcoo commented on code in PR #2780:
URL: https://github.com/apache/fluss/pull/2780#discussion_r2999964377


##########
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorLeaderElection.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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;
+
+import org.apache.fluss.server.zk.ZooKeeperClient;
+import org.apache.fluss.server.zk.data.ZkData;
+import 
org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatch;
+import 
org.apache.fluss.shaded.curator5.org.apache.curator.framework.recipes.leader.LeaderLatchListener;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** Using by coordinator server. Coordinator servers listen ZK node and elect 
leadership. */
+public class CoordinatorLeaderElection implements AutoCloseable {
+    private static final Logger LOG = 
LoggerFactory.getLogger(CoordinatorLeaderElection.class);
+
+    private final String serverId;
+    private final LeaderLatch leaderLatch;
+    private final AtomicBoolean isLeader = new AtomicBoolean(false);
+    private final CompletableFuture<Void> leaderReadyFuture = new 
CompletableFuture<>();
+    private volatile Thread electionThread;
+
+    public CoordinatorLeaderElection(ZooKeeperClient zkClient, String 
serverId) {
+        this.serverId = serverId;
+        this.leaderLatch =
+                new LeaderLatch(
+                        zkClient.getCuratorClient(),
+                        ZkData.CoordinatorElectionZNode.path(),
+                        String.valueOf(serverId));
+    }
+
+    /**
+     * Starts the leader election process asynchronously. The returned future 
completes when this
+     * server becomes the leader and initializes the leader services.
+     *
+     * @param initLeaderServices the runnable to initialize leader services 
once elected
+     * @return a CompletableFuture that completes when this server becomes 
leader
+     */
+    public CompletableFuture<Void> startElectLeaderAsync(Runnable 
initLeaderServices) {
+        leaderLatch.addListener(
+                new LeaderLatchListener() {
+                    @Override
+                    public void isLeader() {
+                        LOG.info("Coordinator server {} has become the 
leader.", serverId);
+                        isLeader.set(true);
+                    }
+
+                    @Override
+                    public void notLeader() {
+                        relinquishLeadership();
+                        LOG.warn("Coordinator server {} has lost the 
leadership.", serverId);
+                    }
+                });
+
+        try {
+            leaderLatch.start();
+            LOG.info("Coordinator server {} started leader election.", 
serverId);
+        } catch (Exception e) {
+            LOG.error("Failed to start LeaderLatch for server {}", serverId, 
e);
+            leaderReadyFuture.completeExceptionally(
+                    new RuntimeException("Leader election start failed", e));
+            return leaderReadyFuture;
+        }
+
+        // Run the await and initialization in a separate thread to avoid 
blocking
+        electionThread =
+                new Thread(
+                        () -> {
+                            try {
+                                // todo: Currently, we await the leader latch 
and do nothing until
+                                // it becomes leader.
+                                // Later we can make it as a hot backup server 
to continuously
+                                // synchronize metadata from
+                                // Zookeeper, which save time from recovering 
context
+                                leaderLatch.await();
+                                doInitLeaderServices(initLeaderServices);

Review Comment:
   In my first design, I didn't create a election thread. However, I encounter 
a ZK deadlock problem. It happened like this:
   Curator event thread 
   → LeaderLatchListener.isLeader()
     → initLeaderServices.run()
       → initCoordinatorLeader()
         → coordinatorEventProcessor.startup()
           → initCoordinatorContext()
             → zooKeeperClient.getSortedTabletServerList() and other ZK request
   
   LeaderLatchListener callback run in Curator inner event process thread. In 
this thread, execute ZK requests(like getData、getChildren) need the event 
thread itself to process response, thus cause deadlock. 
   
   So I think creating a new thread to process "initLeaderServices" and 
"cleanupLeaderServices" is necessary.



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