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.SnapshotComplete;
26 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
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.AbstractUUIDIdentifier;
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());
527 private static final class ServerOperationContextIdentifier extends AbstractUUIDIdentifier<ServerOperationContextIdentifier> {
528 private static final long serialVersionUID = 1L;
530 ServerOperationContextIdentifier() {
531 super(UUID.randomUUID());
536 * Stores context information for a server operation.
538 * @param <T> the operation type
540 private static abstract class ServerOperationContext<T> {
541 private final T operation;
542 private final ActorRef clientRequestor;
543 private final Identifier contextId;
545 ServerOperationContext(T operation, ActorRef clientRequestor){
546 this.operation = operation;
547 this.clientRequestor = clientRequestor;
548 contextId = new ServerOperationContextIdentifier();
551 Identifier getContextId() {
559 ActorRef getClientRequestor() {
560 return clientRequestor;
563 void operationComplete(RaftActor raftActor, boolean succeeded) {
566 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
570 abstract Object newReply(ServerChangeStatus status, String leaderId);
572 abstract InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support);
574 abstract String getLoggingContext();
578 * Stores context information for an AddServer operation.
580 private static class AddServerContext extends ServerOperationContext<AddServer> {
581 AddServerContext(AddServer addServer, ActorRef clientRequestor) {
582 super(addServer, clientRequestor);
586 Object newReply(ServerChangeStatus status, String leaderId) {
587 return new AddServerReply(status, leaderId);
591 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
592 return support.new InitialAddServerState(this);
596 String getLoggingContext() {
597 return getOperation().getNewServerId();
601 private abstract class RemoveServerState extends OperationState {
602 private final RemoveServerContext removeServerContext;
604 protected RemoveServerState(RemoveServerContext removeServerContext) {
605 this.removeServerContext = Preconditions.checkNotNull(removeServerContext);
609 public RemoveServerContext getRemoveServerContext() {
610 return removeServerContext;
614 private final class InitialRemoveServerState extends RemoveServerState implements InitialOperationState{
616 protected InitialRemoveServerState(RemoveServerContext removeServerContext) {
617 super(removeServerContext);
621 public void initiate() {
622 String serverId = getRemoveServerContext().getOperation().getServerId();
623 raftContext.removePeer(serverId);
624 ((AbstractLeader)raftActor.getCurrentBehavior()).removeFollower(serverId);
626 persistNewServerConfiguration(getRemoveServerContext());
630 private static class RemoveServerContext extends ServerOperationContext<RemoveServer> {
631 private final String peerAddress;
633 RemoveServerContext(RemoveServer operation, String peerAddress, ActorRef clientRequestor) {
634 super(operation, clientRequestor);
635 this.peerAddress = peerAddress;
639 Object newReply(ServerChangeStatus status, String leaderId) {
640 return new RemoveServerReply(status, leaderId);
644 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
645 return support.new InitialRemoveServerState(this);
649 void operationComplete(RaftActor raftActor, boolean succeeded) {
650 if(peerAddress != null) {
651 raftActor.context().actorSelection(peerAddress).tell(new ServerRemoved(getOperation().getServerId()), raftActor.getSelf());
656 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
657 return !getOperation().getServerId().equals(raftActor.getId());
661 String getLoggingContext() {
662 return getOperation().getServerId();
666 private static class ChangeServersVotingStatusContext extends ServerOperationContext<ChangeServersVotingStatus> {
667 private final boolean tryToElectLeader;
669 ChangeServersVotingStatusContext(ChangeServersVotingStatus convertMessage, ActorRef clientRequestor,
670 boolean tryToElectLeader) {
671 super(convertMessage, clientRequestor);
672 this.tryToElectLeader = tryToElectLeader;
676 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
677 return support.new ChangeServersVotingStatusState(this, tryToElectLeader);
681 Object newReply(ServerChangeStatus status, String leaderId) {
682 return new ServerChangeReply(status, leaderId);
686 void operationComplete(final RaftActor raftActor, boolean succeeded) {
687 // If this leader changed to non-voting we need to step down as leader so we'll try to transfer
689 boolean localServerChangedToNonVoting = Boolean.FALSE.equals(getOperation().
690 getServerVotingStatusMap().get(raftActor.getRaftActorContext().getId()));
691 if (succeeded && localServerChangedToNonVoting) {
692 LOG.debug("Leader changed to non-voting - trying leadership transfer");
693 raftActor.becomeNonVoting();
698 String getLoggingContext() {
699 return getOperation().toString();
703 private class ChangeServersVotingStatusState extends OperationState implements InitialOperationState {
704 private final ChangeServersVotingStatusContext changeVotingStatusContext;
705 private final boolean tryToElectLeader;
707 ChangeServersVotingStatusState(ChangeServersVotingStatusContext changeVotingStatusContext,
708 boolean tryToElectLeader) {
709 this.changeVotingStatusContext = changeVotingStatusContext;
710 this.tryToElectLeader = tryToElectLeader;
714 public void initiate() {
715 LOG.debug("Initiating ChangeServersVotingStatusState");
717 if(tryToElectLeader) {
718 initiateLocalLeaderElection();
719 } else if(updateLocalPeerInfo()) {
720 persistNewServerConfiguration(changeVotingStatusContext);
724 private void initiateLocalLeaderElection() {
725 LOG.debug("{}: Sending local ElectionTimeout to start leader election", raftContext.getId());
727 ServerConfigurationPayload previousServerConfig = raftContext.getPeerServerInfo(true);
728 if(!updateLocalPeerInfo()) {
732 raftContext.getActor().tell(TimeoutNow.INSTANCE, raftContext.getActor());
734 currentOperationState = new WaitingForLeaderElected(changeVotingStatusContext, previousServerConfig);
737 private boolean updateLocalPeerInfo() {
738 List<ServerInfo> newServerInfoList = newServerInfoList();
740 // Check if new voting state would leave us with no voting members.
741 boolean atLeastOneVoting = false;
742 for(ServerInfo info: newServerInfoList) {
743 if(info.isVoting()) {
744 atLeastOneVoting = true;
749 if(!atLeastOneVoting) {
750 operationComplete(changeVotingStatusContext, ServerChangeStatus.INVALID_REQUEST);
754 raftContext.updatePeerIds(new ServerConfigurationPayload(newServerInfoList));
755 if(raftActor.getCurrentBehavior() instanceof AbstractLeader) {
756 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
757 leader.updateMinReplicaCount();
763 private List<ServerInfo> newServerInfoList() {
764 Map<String, Boolean> serverVotingStatusMap = changeVotingStatusContext.getOperation().getServerVotingStatusMap();
765 List<ServerInfo> newServerInfoList = new ArrayList<>();
766 for(String peerId: raftContext.getPeerIds()) {
767 newServerInfoList.add(new ServerInfo(peerId, serverVotingStatusMap.containsKey(peerId) ?
768 serverVotingStatusMap.get(peerId) : raftContext.getPeerInfo(peerId).isVoting()));
771 newServerInfoList.add(new ServerInfo(raftContext.getId(), serverVotingStatusMap.containsKey(
772 raftContext.getId()) ? serverVotingStatusMap.get(raftContext.getId()) : raftContext.isVotingMember()));
774 return newServerInfoList;
778 private class WaitingForLeaderElected extends OperationState {
779 private final ServerConfigurationPayload previousServerConfig;
780 private final ChangeServersVotingStatusContext operationContext;
781 private final Cancellable timer;
783 WaitingForLeaderElected(ChangeServersVotingStatusContext operationContext,
784 ServerConfigurationPayload previousServerConfig) {
785 this.operationContext = operationContext;
786 this.previousServerConfig = previousServerConfig;
788 timer = newTimer(raftContext.getConfigParams().getElectionTimeOutInterval(),
789 new ServerOperationTimeout(operationContext.getLoggingContext()));
793 void onNewLeader(String newLeader) {
794 if(newLeader == null) {
798 LOG.debug("{}: New leader {} elected", raftContext.getId(), newLeader);
802 if(raftActor.isLeader()) {
803 persistNewServerConfiguration(operationContext);
805 // Edge case - some other node became leader so forward the operation.
806 LOG.debug("{}: Forwarding {} to new leader", raftContext.getId(), operationContext.getOperation());
808 // Revert the local server config change.
809 raftContext.updatePeerIds(previousServerConfig);
812 RaftActorServerConfigurationSupport.this.onNewOperation(operationContext);
817 void onServerOperationTimeout(ServerOperationTimeout timeout) {
818 LOG.warn("{}: Leader election timed out - cannot apply operation {}",
819 raftContext.getId(), timeout.getLoggingContext());
821 // Revert the local server config change.
822 raftContext.updatePeerIds(previousServerConfig);
823 raftActor.initializeBehavior();
825 tryToForwardOperationToAnotherServer();
828 private void tryToForwardOperationToAnotherServer() {
829 Collection<String> serversVisited = new HashSet<>(operationContext.getOperation().getServersVisited());
831 LOG.debug("{}: tryToForwardOperationToAnotherServer - servers already visited {}", raftContext.getId(),
834 serversVisited.add(raftContext.getId());
836 // Try to find another whose state is being changed from non-voting to voting and that we haven't
838 Map<String, Boolean> serverVotingStatusMap = operationContext.getOperation().getServerVotingStatusMap();
839 ActorSelection forwardToPeerActor = null;
840 for(Map.Entry<String, Boolean> e: serverVotingStatusMap.entrySet()) {
841 Boolean isVoting = e.getValue();
842 String serverId = e.getKey();
843 PeerInfo peerInfo = raftContext.getPeerInfo(serverId);
844 if(isVoting && peerInfo != null && !peerInfo.isVoting() && !serversVisited.contains(serverId)) {
845 ActorSelection actor = raftContext.getPeerActorSelection(serverId);
847 forwardToPeerActor = actor;
853 if(forwardToPeerActor != null) {
854 LOG.debug("{}: Found server {} to forward to", raftContext.getId(), forwardToPeerActor);
856 forwardToPeerActor.tell(new ChangeServersVotingStatus(serverVotingStatusMap, serversVisited),
857 operationContext.getClientRequestor());
860 operationComplete(operationContext, ServerChangeStatus.NO_LEADER);
865 static class ServerOperationTimeout {
866 private final String loggingContext;
868 ServerOperationTimeout(String loggingContext){
869 this.loggingContext = Preconditions.checkNotNull(loggingContext, "loggingContext should not be null");
872 String getLoggingContext() {
873 return loggingContext;