Bug 2187: AddServer: check if already exists
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActorServerConfigurationSupport.java
index 7c37b2a68daa62768407bfd66365a2b0509f1b8e..258287a36ae1a95258b9eb2e258e8d5621c63399 100644 (file)
@@ -12,13 +12,16 @@ import akka.actor.ActorSelection;
 import akka.actor.Cancellable;
 import com.google.common.base.Preconditions;
 import java.util.ArrayList;
-import java.util.Collections;
+import java.util.Collection;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Queue;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload.ServerInfo;
 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
 import org.opendaylight.controller.cluster.raft.messages.AddServer;
 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
@@ -63,6 +66,9 @@ class RaftActorServerConfigurationSupport {
             return true;
         } else if(message instanceof ApplyState) {
             return onApplyState((ApplyState) message, raftActor);
+        } else if(message instanceof SnapshotComplete) {
+            currentOperationState.onSnapshotComplete(raftActor);
+            return false;
         } else {
             return false;
         }
@@ -132,6 +138,8 @@ class RaftActorServerConfigurationSupport {
         void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply);
 
         void onApplyState(RaftActor raftActor, ApplyState applyState);
+
+        void onSnapshotComplete(RaftActor raftActor);
     }
 
     /**
@@ -170,26 +178,35 @@ class RaftActorServerConfigurationSupport {
             LOG.debug("onApplyState was called in state {}", this);
         }
 
+        @Override
+        public void onSnapshotComplete(RaftActor raftActor) {
+        }
+
         protected void persistNewServerConfiguration(RaftActor raftActor, ServerOperationContext<?> operationContext){
-            List <String> newConfig = new ArrayList<String>(raftContext.getPeerIds());
-            newConfig.add(raftContext.getId());
+            Collection<PeerInfo> peers = raftContext.getPeers();
+            List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
+            for(PeerInfo peer: peers) {
+                newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
+            }
+
+            newConfig.add(new ServerInfo(raftContext.getId(), true));
 
-            LOG.debug("{}: New server configuration : {}", raftContext.getId(), newConfig);
+            LOG.debug("{}: Persisting new server configuration : {}", raftContext.getId(), newConfig);
 
-            ServerConfigurationPayload payload = new ServerConfigurationPayload(newConfig, Collections.<String>emptyList());
+            ServerConfigurationPayload payload = new ServerConfigurationPayload(newConfig);
 
             raftActor.persistData(operationContext.getClientRequestor(), operationContext.getContextId(), payload);
 
             currentOperationState = new Persisting(operationContext);
+
+            sendReply(raftActor, operationContext, ServerChangeStatus.OK);
         }
 
         protected void operationComplete(RaftActor raftActor, ServerOperationContext<?> operationContext,
-                ServerChangeStatus status) {
-
-            LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status, operationContext.getOperation());
-
-            operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
-                    raftActor.self());
+                @Nullable ServerChangeStatus replyStatus) {
+            if(replyStatus != null) {
+                sendReply(raftActor, operationContext, replyStatus);
+            }
 
             currentOperationState = IDLE;
 
@@ -199,6 +216,14 @@ class RaftActorServerConfigurationSupport {
             }
         }
 
+        private void sendReply(RaftActor raftActor, ServerOperationContext<?> operationContext,
+                ServerChangeStatus status) {
+            LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status, operationContext.getOperation());
+
+            operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
+                    raftActor.self());
+        }
+
         @Override
         public String toString() {
             return getClass().getSimpleName();
@@ -238,7 +263,7 @@ class RaftActorServerConfigurationSupport {
                 LOG.info("{}: {} has been successfully replicated to a majority of followers",
                         applyState.getReplicatedLogEntry().getData());
 
-                operationComplete(raftActor, operationContext, ServerChangeStatus.OK);
+                operationComplete(raftActor, operationContext, null);
             }
         }
     }
@@ -256,6 +281,32 @@ class RaftActorServerConfigurationSupport {
         AddServerContext getAddServerContext() {
             return addServerContext;
         }
+
+        Cancellable newInstallSnapshotTimer(RaftActor raftActor) {
+            return raftContext.getActorSystem().scheduler().scheduleOnce(
+                    new FiniteDuration(((raftContext.getConfigParams().getElectionTimeOutInterval().toMillis()) * 2),
+                            TimeUnit.MILLISECONDS), raftContext.getActor(),
+                            new FollowerCatchUpTimeout(addServerContext.getOperation().getNewServerId()),
+                            raftContext.getActorSystem().dispatcher(), raftContext.getActor());
+        }
+
+        void handleOnFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
+            String serverId = followerTimeout.getNewServerId();
+
+            LOG.debug("{}: onFollowerCatchupTimeout for new server {}", raftContext.getId(), serverId);
+
+            // cleanup
+            raftContext.removePeer(serverId);
+
+            boolean isLeader = raftActor.isLeader();
+            if(isLeader) {
+                AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
+                leader.removeFollower(serverId);
+            }
+
+            operationComplete(raftActor, getAddServerContext(),
+                    isLeader ? ServerChangeStatus.TIMEOUT : ServerChangeStatus.NO_LEADER);
+        }
     }
 
     /**
@@ -270,11 +321,15 @@ class RaftActorServerConfigurationSupport {
         @Override
         public void initiate(RaftActor raftActor) {
             AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
-
             AddServer addServer = getAddServerContext().getOperation();
 
             LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);
 
+            if(raftContext.getPeerInfo(addServer.getNewServerId()) != null) {
+                operationComplete(raftActor, getAddServerContext(), ServerChangeStatus.ALREADY_EXISTS);
+                return;
+            }
+
             VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
                     VotingState.NON_VOTING;
             raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);
@@ -282,19 +337,19 @@ class RaftActorServerConfigurationSupport {
             leader.addFollower(addServer.getNewServerId());
 
             if(votingState == VotingState.VOTING_NOT_INITIALIZED){
-                LOG.debug("{}: Leader sending initiate capture snapshot to new follower {}", raftContext.getId(),
-                        addServer.getNewServerId());
-
-                leader.initiateCaptureSnapshot(addServer.getNewServerId());
-
                 // schedule the install snapshot timeout timer
-                Cancellable installSnapshotTimer = raftContext.getActorSystem().scheduler().scheduleOnce(
-                        new FiniteDuration(((raftContext.getConfigParams().getElectionTimeOutInterval().toMillis()) * 2),
-                                TimeUnit.MILLISECONDS), raftContext.getActor(),
-                                new FollowerCatchUpTimeout(addServer.getNewServerId()),
-                                raftContext.getActorSystem().dispatcher(), raftContext.getActor());
-
-                currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
+                Cancellable installSnapshotTimer = newInstallSnapshotTimer(raftActor);
+                if(leader.initiateCaptureSnapshot(addServer.getNewServerId())) {
+                    LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
+                            addServer.getNewServerId());
+
+                    currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
+                } else {
+                    LOG.debug("{}: Snapshot already in progress - waiting for completion", raftContext.getId());
+
+                    currentOperationState = new WaitingForPriorSnapshotComplete(getAddServerContext(),
+                            installSnapshotTimer);
+                }
             } else {
                 LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
                         raftContext.getId());
@@ -318,19 +373,10 @@ class RaftActorServerConfigurationSupport {
 
         @Override
         public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
-            String serverId = followerTimeout.getNewServerId();
-
-            LOG.debug("{}: onFollowerCatchupTimeout: {}", raftContext.getId(), serverId);
-
-            AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
+            handleOnFollowerCatchupTimeout(raftActor, followerTimeout);
 
-            // cleanup
-            raftContext.removePeer(serverId);
-            leader.removeFollower(serverId);
-
-            LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(), serverId);
-
-            operationComplete(raftActor, getAddServerContext(), ServerChangeStatus.TIMEOUT);
+            LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(),
+                    followerTimeout.getNewServerId());
         }
 
         @Override
@@ -341,7 +387,7 @@ class RaftActorServerConfigurationSupport {
 
             // Sanity check to guard against receiving an UnInitializedFollowerSnapshotReply from a prior
             // add server operation that timed out.
-            if(getAddServerContext().getOperation().getNewServerId().equals(followerId)) {
+            if(getAddServerContext().getOperation().getNewServerId().equals(followerId) && raftActor.isLeader()) {
                 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
                 raftContext.getPeerInfo(followerId).setVotingState(VotingState.VOTING);
                 leader.updateMinReplicaCount();
@@ -349,8 +395,54 @@ class RaftActorServerConfigurationSupport {
                 persistNewServerConfiguration(raftActor, getAddServerContext());
 
                 installSnapshotTimer.cancel();
+            } else {
+                LOG.debug("{}: Dropping UnInitializedFollowerSnapshotReply for server {}: {}",
+                        raftContext.getId(), followerId,
+                        !raftActor.isLeader() ? "not leader" : "server Id doesn't match");
+            }
+        }
+    }
+
+    /**
+     * The AddServer operation state for when there is a snapshot already in progress. When the current
+     * snapshot completes, it initiates an install snapshot.
+     */
+    private class WaitingForPriorSnapshotComplete extends AddServerState {
+        private final Cancellable snapshotTimer;
+
+        WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) {
+            super(addServerContext);
+            this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer);
+        }
+
+        @Override
+        public void onSnapshotComplete(RaftActor raftActor) {
+            LOG.debug("{}: onSnapshotComplete", raftContext.getId());
+
+            if(!raftActor.isLeader()) {
+                LOG.debug("{}: No longer the leader", raftContext.getId());
+                return;
+            }
+
+            AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
+            if(leader.initiateCaptureSnapshot(getAddServerContext().getOperation().getNewServerId())) {
+                LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
+                        getAddServerContext().getOperation().getNewServerId());
+
+                currentOperationState = new InstallingSnapshot(getAddServerContext(),
+                        newInstallSnapshotTimer(raftActor));
+
+                snapshotTimer.cancel();
             }
         }
+
+        @Override
+        public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
+            handleOnFollowerCatchupTimeout(raftActor, followerTimeout);
+
+            LOG.warn("{}: Timeout occured for new server {} while waiting for prior snapshot to complete",
+                    raftContext.getId(), followerTimeout.getNewServerId());
+        }
     }
 
     /**