You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by GitBox <gi...@apache.org> on 2022/05/27 07:39:59 UTC

[GitHub] [iotdb] SzyWilliam commented on a diff in pull request #5939: [IOTDB-3188] Multi leader consensus algorithm implementation

SzyWilliam commented on code in PR #5939:
URL: https://github.com/apache/iotdb/pull/5939#discussion_r883299526


##########
consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensus.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.iotdb.consensus.multileader;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.exception.StartupException;
+import org.apache.iotdb.commons.service.RegisterManager;
+import org.apache.iotdb.consensus.IConsensus;
+import org.apache.iotdb.consensus.IStateMachine;
+import org.apache.iotdb.consensus.IStateMachine.Registry;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.response.ConsensusGenericResponse;
+import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
+import org.apache.iotdb.consensus.common.response.ConsensusWriteResponse;
+import org.apache.iotdb.consensus.exception.ConsensusGroupAlreadyExistException;
+import org.apache.iotdb.consensus.exception.ConsensusGroupNotExistException;
+import org.apache.iotdb.consensus.exception.IllegalPeerNumException;
+import org.apache.iotdb.consensus.multileader.service.MultiLeaderRPCService;
+import org.apache.iotdb.consensus.multileader.service.MultiLeaderRPCServiceProcessor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class MultiLeaderConsensus implements IConsensus {
+
+  private final Logger logger = LoggerFactory.getLogger(MultiLeaderConsensus.class);
+
+  private final TEndPoint thisNode;
+  private final File storageDir;
+  private final IStateMachine.Registry registry;
+  private final Map<ConsensusGroupId, MultiLeaderServerImpl> stateMachineMap =
+      new ConcurrentHashMap<>();
+  private final MultiLeaderRPCService service;
+  private final RegisterManager registerManager = new RegisterManager();
+
+  public MultiLeaderConsensus(TEndPoint thisNode, File storageDir, Registry registry) {
+    this.thisNode = thisNode;
+    this.storageDir = storageDir;
+    this.registry = registry;
+    this.service = new MultiLeaderRPCService(thisNode);
+  }
+
+  @Override
+  public void start() throws IOException {
+    initAndRecover();
+    service.initSyncedServiceImpl(new MultiLeaderRPCServiceProcessor(this));
+    try {
+      registerManager.register(service);
+    } catch (StartupException e) {
+      throw new IOException(e);
+    }
+  }
+
+  private void initAndRecover() throws IOException {
+    if (!storageDir.exists()) {
+      if (!storageDir.mkdirs()) {
+        logger.warn("Unable to create consensus dir at {}", storageDir);
+      }
+    } else {
+      try (DirectoryStream<Path> stream = Files.newDirectoryStream(storageDir.toPath())) {
+        for (Path path : stream) {
+          String[] items = path.getFileName().toString().split("_");
+          ConsensusGroupId consensusGroupId =
+              ConsensusGroupId.Factory.create(
+                  Integer.parseInt(items[0]), Integer.parseInt(items[1]));
+          MultiLeaderServerImpl consensus =
+              new MultiLeaderServerImpl(
+                  path.toString(),
+                  new Peer(consensusGroupId, thisNode),
+                  new ArrayList<>(),
+                  registry.apply(consensusGroupId));
+          stateMachineMap.put(consensusGroupId, consensus);
+          consensus.start();
+        }
+      }
+    }
+  }
+
+  @Override
+  public void stop() {
+    stateMachineMap.values().parallelStream().forEach(MultiLeaderServerImpl::stop);
+    registerManager.deregisterAll();
+  }
+
+  @Override
+  public ConsensusWriteResponse write(ConsensusGroupId groupId, IConsensusRequest request) {
+    MultiLeaderServerImpl impl = stateMachineMap.get(groupId);
+    if (impl == null) {
+      return ConsensusWriteResponse.newBuilder()
+          .setException(new ConsensusGroupNotExistException(groupId))
+          .build();
+    }
+    return ConsensusWriteResponse.newBuilder().setStatus(impl.write(request)).build();
+  }
+
+  @Override
+  public ConsensusReadResponse read(ConsensusGroupId groupId, IConsensusRequest request) {
+    MultiLeaderServerImpl impl = stateMachineMap.get(groupId);
+    if (impl == null) {
+      return ConsensusReadResponse.newBuilder()
+          .setException(new ConsensusGroupNotExistException(groupId))
+          .build();
+    }
+    return ConsensusReadResponse.newBuilder().setDataSet(impl.read(request)).build();
+  }
+
+  @Override
+  public ConsensusGenericResponse addConsensusGroup(ConsensusGroupId groupId, List<Peer> peers) {

Review Comment:
   Is is possible that `thisNode` is not contained in `peers`?



##########
consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/DispatchLogHandler.java:
##########
@@ -0,0 +1,100 @@
+/*
+ * 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.iotdb.consensus.multileader.client;
+
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+import org.apache.iotdb.consensus.multileader.logdispatcher.LogDispatcher.LogDispatcherThread;
+import org.apache.iotdb.consensus.multileader.logdispatcher.PendingBatch;
+import org.apache.iotdb.consensus.multileader.thrift.TSyncLogRes;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.thrift.async.AsyncMethodCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+
+public class DispatchLogHandler implements AsyncMethodCallback<TSyncLogRes> {
+
+  private final Logger logger = LoggerFactory.getLogger(DispatchLogHandler.class);
+
+  private final LogDispatcherThread thread;
+  private final PendingBatch batch;
+  private int retryCount;
+
+  public DispatchLogHandler(LogDispatcherThread thread, PendingBatch batch) {
+    this.thread = thread;
+    this.batch = batch;
+  }
+
+  @Override
+  public void onComplete(TSyncLogRes response) {
+    if (response.getStatus().size() == 1
+        && response.getStatus().get(0).getCode()
+            == TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode()) {
+      logger.warn(
+          "Can not send {} to peer {} for {} times because {}",
+          batch,
+          thread.getPeer(),
+          ++retryCount,
+          response.getStatus().get(0).getMessage());
+      sleepCorrespondingTimeAndRetryAsynchronous();
+    } else {
+      thread.getSyncStatus().removeBatch(batch);
+    }
+  }
+
+  @Override
+  public void onError(Exception exception) {
+    logger.warn(
+        "Can not send {} to peer for {} times {} because {}",
+        batch,
+        thread.getPeer(),
+        ++retryCount,
+        exception);
+    sleepCorrespondingTimeAndRetryAsynchronous();
+  }
+
+  private void sleepCorrespondingTimeAndRetryAsynchronous() {
+    // TODO handle forever retry
+    CompletableFuture.runAsync(
+        () -> {
+          try {
+            long defaultSleepTime =
+                (long)
+                    (MultiLeaderConsensusConfig.BASIC_RETRY_WAIT_TIME_MS * Math.pow(2, retryCount));

Review Comment:
   Should we add an upper-limit on defaultSleepTime, like 2 ^ 16 ms?



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org