2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft;
10 import akka.actor.ActorRef;
11 import akka.actor.ActorSelection;
12 import akka.actor.Cancellable;
13 import com.google.common.base.Preconditions;
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.Queue;
21 import java.util.UUID;
22 import javax.annotation.Nullable;
23 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload.ServerInfo;
24 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
25 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
26 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
27 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
28 import org.opendaylight.controller.cluster.raft.messages.AddServer;
29 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
30 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
31 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
32 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
33 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
34 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
35 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
36 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
37 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
38 import org.opendaylight.yangtools.concepts.Identifier;
39 import org.opendaylight.yangtools.util.UUIDIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import scala.concurrent.duration.FiniteDuration;
45 * Handles server configuration related messages for a RaftActor.
47 * @author Thomas Pantelis
49 class RaftActorServerConfigurationSupport {
50 private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupport.class);
52 private final OperationState IDLE = new Idle();
54 private final RaftActor raftActor;
56 private final RaftActorContext raftContext;
58 private final Queue<ServerOperationContext<?>> pendingOperationsQueue = new ArrayDeque<>();
60 private OperationState currentOperationState = IDLE;
62 RaftActorServerConfigurationSupport(RaftActor raftActor) {
63 this.raftActor = raftActor;
64 this.raftContext = raftActor.getRaftActorContext();
67 boolean handleMessage(Object message, ActorRef sender) {
68 if(message instanceof AddServer) {
69 onAddServer((AddServer) message, sender);
71 } else if(message instanceof RemoveServer) {
72 onRemoveServer((RemoveServer) message, sender);
74 } else if(message instanceof ChangeServersVotingStatus) {
75 onChangeServersVotingStatus((ChangeServersVotingStatus) message, sender);
77 } else if (message instanceof ServerOperationTimeout) {
78 currentOperationState.onServerOperationTimeout((ServerOperationTimeout) message);
80 } else if (message instanceof UnInitializedFollowerSnapshotReply) {
81 currentOperationState.onUnInitializedFollowerSnapshotReply((UnInitializedFollowerSnapshotReply) message);
83 } else if(message instanceof ApplyState) {
84 return onApplyState((ApplyState) message);
85 } else if(message instanceof SnapshotComplete) {
86 currentOperationState.onSnapshotComplete();
93 void onNewLeader(String leaderId) {
94 currentOperationState.onNewLeader(leaderId);
97 private void onChangeServersVotingStatus(ChangeServersVotingStatus message, ActorRef sender) {
98 LOG.debug("{}: onChangeServersVotingStatus: {}, state: {}", raftContext.getId(), message,
99 currentOperationState);
101 // The following check is a special case. Normally we fail an operation if there's no leader.
102 // Consider a scenario where one has 2 geographically-separated 3-node clusters, one a primary and
103 // the other a backup such that if the primary cluster is lost, the backup can take over. In this
104 // scenario, we have a logical 6-node cluster where the primary sub-cluster is configured as voting
105 // and the backup sub-cluster as non-voting such that the primary cluster can make progress without
106 // consensus from the backup cluster while still replicating to the backup. On fail-over to the backup,
107 // a request would be sent to a member of the backup cluster to flip the voting states, ie make the
108 // backup sub-cluster voting and the lost primary non-voting. However since the primary majority
109 // cluster is lost, there would be no leader to apply, persist and replicate the server config change.
110 // Therefore, if the local server is currently non-voting and is to be changed to voting and there is
111 // no current leader, we will try to elect a leader using the new server config in order to replicate
112 // the change and progress.
113 boolean localServerChangingToVoting = Boolean.TRUE.equals(message.
114 getServerVotingStatusMap().get(raftActor.getRaftActorContext().getId()));
115 boolean hasNoLeader = raftActor.getLeaderId() == null;
116 if(localServerChangingToVoting && !raftContext.isVotingMember() && hasNoLeader) {
117 currentOperationState.onNewOperation(new ChangeServersVotingStatusContext(message, sender, true));
119 onNewOperation(new ChangeServersVotingStatusContext(message, sender, false));
123 private void onRemoveServer(RemoveServer removeServer, ActorRef sender) {
124 LOG.debug("{}: onRemoveServer: {}, state: {}", raftContext.getId(), removeServer, currentOperationState);
125 boolean isSelf = removeServer.getServerId().equals(raftContext.getId());
126 if(isSelf && !raftContext.hasFollowers()) {
127 sender.tell(new RemoveServerReply(ServerChangeStatus.NOT_SUPPORTED, raftActor.getLeaderId()),
128 raftActor.getSelf());
129 } else if(!isSelf && !raftContext.getPeerIds().contains(removeServer.getServerId())) {
130 sender.tell(new RemoveServerReply(ServerChangeStatus.DOES_NOT_EXIST, raftActor.getLeaderId()),
131 raftActor.getSelf());
133 String serverAddress = isSelf ? raftActor.self().path().toString() :
134 raftContext.getPeerAddress(removeServer.getServerId());
135 onNewOperation(new RemoveServerContext(removeServer, serverAddress, sender));
139 private boolean onApplyState(ApplyState applyState) {
140 Payload data = applyState.getReplicatedLogEntry().getData();
141 if(data instanceof ServerConfigurationPayload) {
142 currentOperationState.onApplyState(applyState);
150 * The algorithm for AddServer is as follows:
152 * <li>Add the new server as a peer.</li>
153 * <li>Add the new follower to the leader.</li>
154 * <li>If new server should be voting member</li>
156 * <li>Initialize FollowerState to VOTING_NOT_INITIALIZED.</li>
157 * <li>Initiate install snapshot to the new follower.</li>
158 * <li>When install snapshot complete, mark the follower as VOTING and re-calculate majority vote count.</li>
160 * <li>Persist and replicate ServerConfigurationPayload with the new server list.</li>
161 * <li>On replication consensus, respond to caller with OK.</li>
163 * If the install snapshot times out after a period of 2 * election time out
165 * <li>Remove the new server as a peer.</li>
166 * <li>Remove the new follower from the leader.</li>
167 * <li>Respond to caller with TIMEOUT.</li>
170 private void onAddServer(AddServer addServer, ActorRef sender) {
171 LOG.debug("{}: onAddServer: {}, state: {}", raftContext.getId(), addServer, currentOperationState);
173 onNewOperation(new AddServerContext(addServer, sender));
176 private void onNewOperation(ServerOperationContext<?> operationContext) {
177 if (raftActor.isLeader()) {
178 currentOperationState.onNewOperation(operationContext);
180 ActorSelection leader = raftActor.getLeader();
181 if (leader != null) {
182 LOG.debug("{}: Not leader - forwarding to leader {}", raftContext.getId(), leader);
183 leader.tell(operationContext.getOperation(), operationContext.getClientRequestor());
185 LOG.debug("{}: No leader - returning NO_LEADER reply", raftContext.getId());
186 operationContext.getClientRequestor().tell(operationContext.newReply(
187 ServerChangeStatus.NO_LEADER, null), raftActor.self());
193 * Interface for the initial state for a server operation.
195 private interface InitialOperationState {
200 * Abstract base class for a server operation FSM state. Handles common behavior for all states.
202 private abstract class OperationState {
203 void onNewOperation(ServerOperationContext<?> operationContext) {
204 // We're currently processing another operation so queue it to be processed later.
206 LOG.debug("{}: Server operation already in progress - queueing {}", raftContext.getId(),
207 operationContext.getOperation());
209 pendingOperationsQueue.add(operationContext);
212 void onServerOperationTimeout(ServerOperationTimeout timeout) {
213 LOG.debug("onServerOperationTimeout should not be called in state {}", this);
216 void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
217 LOG.debug("onUnInitializedFollowerSnapshotReply was called in state {}", this);
220 void onApplyState(ApplyState applyState) {
221 LOG.debug("onApplyState was called in state {}", this);
224 void onSnapshotComplete() {
228 void onNewLeader(String newLeader) {
231 protected void persistNewServerConfiguration(ServerOperationContext<?> operationContext){
232 raftContext.setDynamicServerConfigurationInUse();
234 ServerConfigurationPayload payload = raftContext.getPeerServerInfo(
235 operationContext.includeSelfInNewConfiguration(raftActor));
236 LOG.debug("{}: New server configuration : {}", raftContext.getId(), payload.getServerConfig());
238 raftActor.persistData(operationContext.getClientRequestor(), operationContext.getContextId(), payload);
240 currentOperationState = new Persisting(operationContext, newTimer(new ServerOperationTimeout(
241 operationContext.getLoggingContext())));
243 sendReply(operationContext, ServerChangeStatus.OK);
246 protected void operationComplete(ServerOperationContext<?> operationContext, @Nullable ServerChangeStatus replyStatus) {
247 if(replyStatus != null) {
248 sendReply(operationContext, replyStatus);
251 operationContext.operationComplete(raftActor, replyStatus == null || replyStatus == ServerChangeStatus.OK);
256 protected void changeToIdleState() {
257 currentOperationState = IDLE;
259 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
260 if(nextOperation != null) {
261 RaftActorServerConfigurationSupport.this.onNewOperation(nextOperation);
265 protected void sendReply(ServerOperationContext<?> operationContext, ServerChangeStatus status) {
266 LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status, operationContext.getOperation());
268 operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
272 Cancellable newTimer(Object message) {
273 return newTimer(raftContext.getConfigParams().getElectionTimeOutInterval().$times(2), message);
276 Cancellable newTimer(FiniteDuration timeout, Object message) {
277 return raftContext.getActorSystem().scheduler().scheduleOnce(
278 timeout, raftContext.getActor(), message,
279 raftContext.getActorSystem().dispatcher(), raftContext.getActor());
283 public String toString() {
284 return getClass().getSimpleName();
289 * The state when no server operation is in progress. It immediately initiates new server operations.
291 private final class Idle extends OperationState {
293 public void onNewOperation(ServerOperationContext<?> operationContext) {
294 operationContext.newInitialOperationState(RaftActorServerConfigurationSupport.this).initiate();
298 public void onApplyState(ApplyState applyState) {
299 // Noop - we override b/c ApplyState is called normally for followers in the idle state.
304 * The state when a new server configuration is being persisted and replicated.
306 private final class Persisting extends OperationState {
307 private final ServerOperationContext<?> operationContext;
308 private final Cancellable timer;
309 private boolean timedOut = false;
311 Persisting(ServerOperationContext<?> operationContext, Cancellable timer) {
312 this.operationContext = operationContext;
317 public void onApplyState(ApplyState applyState) {
318 // Sanity check - we could get an ApplyState from a previous operation that timed out so make
319 // sure it's meant for us.
320 if(operationContext.getContextId().equals(applyState.getIdentifier())) {
321 LOG.info("{}: {} has been successfully replicated to a majority of followers", raftContext.getId(),
322 applyState.getReplicatedLogEntry().getData());
325 operationComplete(operationContext, null);
330 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
331 LOG.warn("{}: Timeout occured while replicating the new server configuration for {}", raftContext.getId(),
332 timeout.getLoggingContext());
336 // Fail any pending operations
337 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
338 while(nextOperation != null) {
339 sendReply(nextOperation, ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT);
340 nextOperation = pendingOperationsQueue.poll();
345 public void onNewOperation(ServerOperationContext<?> operationContext) {
347 sendReply(operationContext, ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT);
349 super.onNewOperation(operationContext);
355 * Abstract base class for an AddServer operation state.
357 private abstract class AddServerState extends OperationState {
358 private final AddServerContext addServerContext;
360 AddServerState(AddServerContext addServerContext) {
361 this.addServerContext = addServerContext;
364 AddServerContext getAddServerContext() {
365 return addServerContext;
368 Cancellable newInstallSnapshotTimer() {
369 return newTimer(new ServerOperationTimeout(addServerContext.getOperation().getNewServerId()));
372 void handleInstallSnapshotTimeout(ServerOperationTimeout timeout) {
373 String serverId = timeout.getLoggingContext();
375 LOG.debug("{}: handleInstallSnapshotTimeout for new server {}", raftContext.getId(), serverId);
378 raftContext.removePeer(serverId);
380 boolean isLeader = raftActor.isLeader();
382 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
383 leader.removeFollower(serverId);
386 operationComplete(getAddServerContext(), isLeader ? ServerChangeStatus.TIMEOUT : ServerChangeStatus.NO_LEADER);
392 * The initial state for the AddServer operation. It adds the new follower as a peer and initiates
393 * snapshot capture, if necessary.
395 private final class InitialAddServerState extends AddServerState implements InitialOperationState {
396 InitialAddServerState(AddServerContext addServerContext) {
397 super(addServerContext);
401 public void initiate() {
402 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
403 AddServer addServer = getAddServerContext().getOperation();
405 LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);
407 if(raftContext.getPeerInfo(addServer.getNewServerId()) != null) {
408 operationComplete(getAddServerContext(), ServerChangeStatus.ALREADY_EXISTS);
412 VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
413 VotingState.NON_VOTING;
414 raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);
416 leader.addFollower(addServer.getNewServerId());
418 if(votingState == VotingState.VOTING_NOT_INITIALIZED){
419 // schedule the install snapshot timeout timer
420 Cancellable installSnapshotTimer = newInstallSnapshotTimer();
421 if(leader.initiateCaptureSnapshot(addServer.getNewServerId())) {
422 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
423 addServer.getNewServerId());
425 currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
427 LOG.debug("{}: Snapshot already in progress - waiting for completion", raftContext.getId());
429 currentOperationState = new WaitingForPriorSnapshotComplete(getAddServerContext(),
430 installSnapshotTimer);
433 LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
434 raftContext.getId());
436 persistNewServerConfiguration(getAddServerContext());
442 * The AddServer operation state for when the catch-up snapshot is being installed. It handles successful
445 private final class InstallingSnapshot extends AddServerState {
446 private final Cancellable installSnapshotTimer;
448 InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) {
449 super(addServerContext);
450 this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer);
454 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
455 handleInstallSnapshotTimeout(timeout);
457 LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(),
458 timeout.getLoggingContext());
462 public void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
463 LOG.debug("{}: onUnInitializedFollowerSnapshotReply: {}", raftContext.getId(), reply);
465 String followerId = reply.getFollowerId();
467 // Sanity check to guard against receiving an UnInitializedFollowerSnapshotReply from a prior
468 // add server operation that timed out.
469 if(getAddServerContext().getOperation().getNewServerId().equals(followerId) && raftActor.isLeader()) {
470 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
471 raftContext.getPeerInfo(followerId).setVotingState(VotingState.VOTING);
472 leader.updateMinReplicaCount();
474 persistNewServerConfiguration(getAddServerContext());
476 installSnapshotTimer.cancel();
478 LOG.debug("{}: Dropping UnInitializedFollowerSnapshotReply for server {}: {}",
479 raftContext.getId(), followerId,
480 !raftActor.isLeader() ? "not leader" : "server Id doesn't match");
486 * The AddServer operation state for when there is a snapshot already in progress. When the current
487 * snapshot completes, it initiates an install snapshot.
489 private final class WaitingForPriorSnapshotComplete extends AddServerState {
490 private final Cancellable snapshotTimer;
492 WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) {
493 super(addServerContext);
494 this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer);
498 public void onSnapshotComplete() {
499 LOG.debug("{}: onSnapshotComplete", raftContext.getId());
501 if(!raftActor.isLeader()) {
502 LOG.debug("{}: No longer the leader", raftContext.getId());
506 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
507 if(leader.initiateCaptureSnapshot(getAddServerContext().getOperation().getNewServerId())) {
508 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
509 getAddServerContext().getOperation().getNewServerId());
511 currentOperationState = new InstallingSnapshot(getAddServerContext(),
512 newInstallSnapshotTimer());
514 snapshotTimer.cancel();
519 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
520 handleInstallSnapshotTimeout(timeout);
522 LOG.warn("{}: Timeout occured for new server {} while waiting for prior snapshot to complete",
523 raftContext.getId(), timeout.getLoggingContext());
528 * Stores context information for a server operation.
530 * @param <T> the operation type
532 private static abstract class ServerOperationContext<T> {
533 private final T operation;
534 private final ActorRef clientRequestor;
535 private final Identifier contextId;
537 ServerOperationContext(T operation, ActorRef clientRequestor){
538 this.operation = operation;
539 this.clientRequestor = clientRequestor;
540 contextId = new UUIDIdentifier(UUID.randomUUID());
543 Identifier getContextId() {
551 ActorRef getClientRequestor() {
552 return clientRequestor;
555 void operationComplete(RaftActor raftActor, boolean succeeded) {
558 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
562 abstract Object newReply(ServerChangeStatus status, String leaderId);
564 abstract InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support);
566 abstract String getLoggingContext();
570 * Stores context information for an AddServer operation.
572 private static class AddServerContext extends ServerOperationContext<AddServer> {
573 AddServerContext(AddServer addServer, ActorRef clientRequestor) {
574 super(addServer, clientRequestor);
578 Object newReply(ServerChangeStatus status, String leaderId) {
579 return new AddServerReply(status, leaderId);
583 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
584 return support.new InitialAddServerState(this);
588 String getLoggingContext() {
589 return getOperation().getNewServerId();
593 private abstract class RemoveServerState extends OperationState {
594 private final RemoveServerContext removeServerContext;
596 protected RemoveServerState(RemoveServerContext removeServerContext) {
597 this.removeServerContext = Preconditions.checkNotNull(removeServerContext);
601 public RemoveServerContext getRemoveServerContext() {
602 return removeServerContext;
606 private final class InitialRemoveServerState extends RemoveServerState implements InitialOperationState{
608 protected InitialRemoveServerState(RemoveServerContext removeServerContext) {
609 super(removeServerContext);
613 public void initiate() {
614 String serverId = getRemoveServerContext().getOperation().getServerId();
615 raftContext.removePeer(serverId);
616 ((AbstractLeader)raftActor.getCurrentBehavior()).removeFollower(serverId);
618 persistNewServerConfiguration(getRemoveServerContext());
622 private static class RemoveServerContext extends ServerOperationContext<RemoveServer> {
623 private final String peerAddress;
625 RemoveServerContext(RemoveServer operation, String peerAddress, ActorRef clientRequestor) {
626 super(operation, clientRequestor);
627 this.peerAddress = peerAddress;
631 Object newReply(ServerChangeStatus status, String leaderId) {
632 return new RemoveServerReply(status, leaderId);
636 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
637 return support.new InitialRemoveServerState(this);
641 void operationComplete(RaftActor raftActor, boolean succeeded) {
642 if(peerAddress != null) {
643 raftActor.context().actorSelection(peerAddress).tell(new ServerRemoved(getOperation().getServerId()), raftActor.getSelf());
648 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
649 return !getOperation().getServerId().equals(raftActor.getId());
653 String getLoggingContext() {
654 return getOperation().getServerId();
658 private static class ChangeServersVotingStatusContext extends ServerOperationContext<ChangeServersVotingStatus> {
659 private final boolean tryToElectLeader;
661 ChangeServersVotingStatusContext(ChangeServersVotingStatus convertMessage, ActorRef clientRequestor,
662 boolean tryToElectLeader) {
663 super(convertMessage, clientRequestor);
664 this.tryToElectLeader = tryToElectLeader;
668 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
669 return support.new ChangeServersVotingStatusState(this, tryToElectLeader);
673 Object newReply(ServerChangeStatus status, String leaderId) {
674 return new ServerChangeReply(status, leaderId);
678 void operationComplete(final RaftActor raftActor, boolean succeeded) {
679 // If this leader changed to non-voting we need to step down as leader so we'll try to transfer
681 boolean localServerChangedToNonVoting = Boolean.FALSE.equals(getOperation().
682 getServerVotingStatusMap().get(raftActor.getRaftActorContext().getId()));
683 if (succeeded && localServerChangedToNonVoting) {
684 raftActor.becomeNonVoting();
689 String getLoggingContext() {
690 return getOperation().toString();
694 private class ChangeServersVotingStatusState extends OperationState implements InitialOperationState {
695 private final ChangeServersVotingStatusContext changeVotingStatusContext;
696 private final boolean tryToElectLeader;
698 ChangeServersVotingStatusState(ChangeServersVotingStatusContext changeVotingStatusContext,
699 boolean tryToElectLeader) {
700 this.changeVotingStatusContext = changeVotingStatusContext;
701 this.tryToElectLeader = tryToElectLeader;
705 public void initiate() {
706 LOG.debug("Initiating ChangeServersVotingStatusState");
708 if(tryToElectLeader) {
709 initiateLocalLeaderElection();
711 updateLocalPeerInfo();
713 persistNewServerConfiguration(changeVotingStatusContext);
717 private void initiateLocalLeaderElection() {
718 LOG.debug("{}: Sending local ElectionTimeout to start leader election", raftContext.getId());
720 ServerConfigurationPayload previousServerConfig = raftContext.getPeerServerInfo(true);
721 updateLocalPeerInfo();
723 raftContext.getActor().tell(ElectionTimeout.INSTANCE, raftContext.getActor());
725 currentOperationState = new WaitingForLeaderElected(changeVotingStatusContext, previousServerConfig);
728 private void updateLocalPeerInfo() {
729 List<ServerInfo> newServerInfoList = newServerInfoList();
731 raftContext.updatePeerIds(new ServerConfigurationPayload(newServerInfoList));
732 if(raftActor.getCurrentBehavior() instanceof AbstractLeader) {
733 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
734 leader.updateMinReplicaCount();
738 private List<ServerInfo> newServerInfoList() {
739 Map<String, Boolean> serverVotingStatusMap = changeVotingStatusContext.getOperation().getServerVotingStatusMap();
740 List<ServerInfo> newServerInfoList = new ArrayList<>();
741 for(String peerId: raftContext.getPeerIds()) {
742 newServerInfoList.add(new ServerInfo(peerId, serverVotingStatusMap.containsKey(peerId) ?
743 serverVotingStatusMap.get(peerId) : raftContext.getPeerInfo(peerId).isVoting()));
746 newServerInfoList.add(new ServerInfo(raftContext.getId(), serverVotingStatusMap.containsKey(
747 raftContext.getId()) ? serverVotingStatusMap.get(raftContext.getId()) : raftContext.isVotingMember()));
749 return newServerInfoList;
753 private class WaitingForLeaderElected extends OperationState {
754 private final ServerConfigurationPayload previousServerConfig;
755 private final ChangeServersVotingStatusContext operationContext;
756 private final Cancellable timer;
758 WaitingForLeaderElected(ChangeServersVotingStatusContext operationContext,
759 ServerConfigurationPayload previousServerConfig) {
760 this.operationContext = operationContext;
761 this.previousServerConfig = previousServerConfig;
763 timer = newTimer(raftContext.getConfigParams().getElectionTimeOutInterval(),
764 new ServerOperationTimeout(operationContext.getLoggingContext()));
768 void onNewLeader(String newLeader) {
769 LOG.debug("{}: New leader {} elected", raftContext.getId(), newLeader);
773 if(raftActor.isLeader()) {
774 persistNewServerConfiguration(operationContext);
776 // Edge case - some other node became leader so forward the operation.
777 LOG.debug("{}: Forwarding {} to new leader", raftContext.getId(), operationContext.getOperation());
779 // Revert the local server config change.
780 raftContext.updatePeerIds(previousServerConfig);
783 RaftActorServerConfigurationSupport.this.onNewOperation(operationContext);
788 void onServerOperationTimeout(ServerOperationTimeout timeout) {
789 LOG.warn("{}: Leader election timed out - cannot apply operation {}",
790 raftContext.getId(), timeout.getLoggingContext());
792 // Revert the local server config change.
793 raftContext.updatePeerIds(previousServerConfig);
794 raftActor.initializeBehavior();
796 tryToForwardOperationToAnotherServer();
799 private void tryToForwardOperationToAnotherServer() {
800 Collection<String> serversVisited = new HashSet<>(operationContext.getOperation().getServersVisited());
802 LOG.debug("{}: tryToForwardOperationToAnotherServer - servers already visited {}", raftContext.getId(),
805 serversVisited.add(raftContext.getId());
807 // Try to find another whose state is being changed from non-voting to voting and that we haven't
809 Map<String, Boolean> serverVotingStatusMap = operationContext.getOperation().getServerVotingStatusMap();
810 ActorSelection forwardToPeerActor = null;
811 for(Map.Entry<String, Boolean> e: serverVotingStatusMap.entrySet()) {
812 Boolean isVoting = e.getValue();
813 String serverId = e.getKey();
814 PeerInfo peerInfo = raftContext.getPeerInfo(serverId);
815 if(isVoting && peerInfo != null && !peerInfo.isVoting() && !serversVisited.contains(serverId)) {
816 ActorSelection actor = raftContext.getPeerActorSelection(serverId);
818 forwardToPeerActor = actor;
824 if(forwardToPeerActor != null) {
825 LOG.debug("{}: Found server {} to forward to", raftContext.getId(), forwardToPeerActor);
827 forwardToPeerActor.tell(new ChangeServersVotingStatus(serverVotingStatusMap, serversVisited),
828 operationContext.getClientRequestor());
831 operationComplete(operationContext, ServerChangeStatus.NO_LEADER);
836 static class ServerOperationTimeout {
837 private final String loggingContext;
839 ServerOperationTimeout(String loggingContext){
840 this.loggingContext = Preconditions.checkNotNull(loggingContext, "loggingContext should not be null");
843 String getLoggingContext() {
844 return loggingContext;