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.base.messages.ApplyState;
24 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
25 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
26 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
27 import org.opendaylight.controller.cluster.raft.messages.AddServer;
28 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
29 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
30 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
31 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
32 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
33 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
34 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
35 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
36 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
37 import org.opendaylight.controller.cluster.raft.persisted.ServerInfo;
38 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
39 import org.opendaylight.yangtools.concepts.Identifier;
40 import org.opendaylight.yangtools.util.AbstractUUIDIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import scala.concurrent.duration.FiniteDuration;
46 * Handles server configuration related messages for a RaftActor.
48 * @author Thomas Pantelis
50 class RaftActorServerConfigurationSupport {
51 private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupport.class);
53 @SuppressWarnings("checkstyle:MemberName")
54 private final OperationState IDLE = new Idle();
56 private final RaftActor raftActor;
58 private final RaftActorContext raftContext;
60 private final Queue<ServerOperationContext<?>> pendingOperationsQueue = new ArrayDeque<>();
62 private OperationState currentOperationState = IDLE;
64 RaftActorServerConfigurationSupport(RaftActor raftActor) {
65 this.raftActor = raftActor;
66 this.raftContext = raftActor.getRaftActorContext();
69 boolean handleMessage(Object message, ActorRef sender) {
70 if (message instanceof AddServer) {
71 onAddServer((AddServer) message, sender);
73 } else if (message instanceof RemoveServer) {
74 onRemoveServer((RemoveServer) message, sender);
76 } else if (message instanceof ChangeServersVotingStatus) {
77 onChangeServersVotingStatus((ChangeServersVotingStatus) message, sender);
79 } else if (message instanceof ServerOperationTimeout) {
80 currentOperationState.onServerOperationTimeout((ServerOperationTimeout) message);
82 } else if (message instanceof UnInitializedFollowerSnapshotReply) {
83 currentOperationState.onUnInitializedFollowerSnapshotReply((UnInitializedFollowerSnapshotReply) message);
85 } else if (message instanceof ApplyState) {
86 return onApplyState((ApplyState) message);
87 } else if (message instanceof SnapshotComplete) {
88 currentOperationState.onSnapshotComplete();
95 void onNewLeader(String leaderId) {
96 currentOperationState.onNewLeader(leaderId);
99 private void onChangeServersVotingStatus(ChangeServersVotingStatus message, ActorRef sender) {
100 LOG.debug("{}: onChangeServersVotingStatus: {}, state: {}", raftContext.getId(), message,
101 currentOperationState);
103 // The following check is a special case. Normally we fail an operation if there's no leader.
104 // Consider a scenario where one has 2 geographically-separated 3-node clusters, one a primary and
105 // the other a backup such that if the primary cluster is lost, the backup can take over. In this
106 // scenario, we have a logical 6-node cluster where the primary sub-cluster is configured as voting
107 // and the backup sub-cluster as non-voting such that the primary cluster can make progress without
108 // consensus from the backup cluster while still replicating to the backup. On fail-over to the backup,
109 // a request would be sent to a member of the backup cluster to flip the voting states, ie make the
110 // backup sub-cluster voting and the lost primary non-voting. However since the primary majority
111 // cluster is lost, there would be no leader to apply, persist and replicate the server config change.
112 // Therefore, if the local server is currently non-voting and is to be changed to voting and there is
113 // no current leader, we will try to elect a leader using the new server config in order to replicate
114 // the change and progress.
115 boolean localServerChangingToVoting = Boolean.TRUE.equals(message
116 .getServerVotingStatusMap().get(raftActor.getRaftActorContext().getId()));
117 boolean hasNoLeader = raftActor.getLeaderId() == null;
118 if (localServerChangingToVoting && !raftContext.isVotingMember() && hasNoLeader) {
119 currentOperationState.onNewOperation(new ChangeServersVotingStatusContext(message, sender, true));
121 onNewOperation(new ChangeServersVotingStatusContext(message, sender, false));
125 private void onRemoveServer(RemoveServer removeServer, ActorRef sender) {
126 LOG.debug("{}: onRemoveServer: {}, state: {}", raftContext.getId(), removeServer, currentOperationState);
127 boolean isSelf = removeServer.getServerId().equals(raftContext.getId());
128 if (isSelf && !raftContext.hasFollowers()) {
129 sender.tell(new RemoveServerReply(ServerChangeStatus.NOT_SUPPORTED, raftActor.getLeaderId()),
130 raftActor.getSelf());
131 } else if (!isSelf && !raftContext.getPeerIds().contains(removeServer.getServerId())) {
132 sender.tell(new RemoveServerReply(ServerChangeStatus.DOES_NOT_EXIST, raftActor.getLeaderId()),
133 raftActor.getSelf());
135 String serverAddress = isSelf ? raftActor.self().path().toString() :
136 raftContext.getPeerAddress(removeServer.getServerId());
137 onNewOperation(new RemoveServerContext(removeServer, serverAddress, sender));
141 private boolean onApplyState(ApplyState applyState) {
142 Payload data = applyState.getReplicatedLogEntry().getData();
143 if (data instanceof ServerConfigurationPayload) {
144 currentOperationState.onApplyState(applyState);
152 * The algorithm for AddServer is as follows:
154 * <li>Add the new server as a peer.</li>
155 * <li>Add the new follower to the leader.</li>
156 * <li>If new server should be voting member</li>
158 * <li>Initialize FollowerState to VOTING_NOT_INITIALIZED.</li>
159 * <li>Initiate install snapshot to the new follower.</li>
160 * <li>When install snapshot complete, mark the follower as VOTING and re-calculate majority vote count.</li>
162 * <li>Persist and replicate ServerConfigurationPayload with the new server list.</li>
163 * <li>On replication consensus, respond to caller with OK.</li>
165 * If the install snapshot times out after a period of 2 * election time out
167 * <li>Remove the new server as a peer.</li>
168 * <li>Remove the new follower from the leader.</li>
169 * <li>Respond to caller with TIMEOUT.</li>
172 private void onAddServer(AddServer addServer, ActorRef sender) {
173 LOG.debug("{}: onAddServer: {}, state: {}", raftContext.getId(), addServer, currentOperationState);
175 onNewOperation(new AddServerContext(addServer, sender));
178 private void onNewOperation(ServerOperationContext<?> operationContext) {
179 if (raftActor.isLeader()) {
180 currentOperationState.onNewOperation(operationContext);
182 ActorSelection leader = raftActor.getLeader();
183 if (leader != null) {
184 LOG.debug("{}: Not leader - forwarding to leader {}", raftContext.getId(), leader);
185 leader.tell(operationContext.getOperation(), operationContext.getClientRequestor());
187 LOG.debug("{}: No leader - returning NO_LEADER reply", raftContext.getId());
188 operationContext.getClientRequestor().tell(operationContext.newReply(
189 ServerChangeStatus.NO_LEADER, null), raftActor.self());
195 * Interface for the initial state for a server operation.
197 private interface InitialOperationState {
202 * Abstract base class for a server operation FSM state. Handles common behavior for all states.
204 private abstract class OperationState {
205 void onNewOperation(ServerOperationContext<?> operationContext) {
206 // We're currently processing another operation so queue it to be processed later.
208 LOG.debug("{}: Server operation already in progress - queueing {}", raftContext.getId(),
209 operationContext.getOperation());
211 pendingOperationsQueue.add(operationContext);
214 void onServerOperationTimeout(ServerOperationTimeout timeout) {
215 LOG.debug("onServerOperationTimeout should not be called in state {}", this);
218 void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
219 LOG.debug("onUnInitializedFollowerSnapshotReply was called in state {}", this);
222 void onApplyState(ApplyState applyState) {
223 LOG.debug("onApplyState was called in state {}", this);
226 void onSnapshotComplete() {
230 void onNewLeader(String newLeader) {
233 protected void persistNewServerConfiguration(ServerOperationContext<?> operationContext) {
234 raftContext.setDynamicServerConfigurationInUse();
236 ServerConfigurationPayload payload = raftContext.getPeerServerInfo(
237 operationContext.includeSelfInNewConfiguration(raftActor));
238 LOG.debug("{}: New server configuration : {}", raftContext.getId(), payload.getServerConfig());
240 raftActor.persistData(operationContext.getClientRequestor(), operationContext.getContextId(),
243 currentOperationState = new Persisting(operationContext, newTimer(new ServerOperationTimeout(
244 operationContext.getLoggingContext())));
246 sendReply(operationContext, ServerChangeStatus.OK);
249 protected void operationComplete(ServerOperationContext<?> operationContext,
250 @Nullable ServerChangeStatus replyStatus) {
251 if (replyStatus != null) {
252 sendReply(operationContext, replyStatus);
255 operationContext.operationComplete(raftActor, replyStatus == null || replyStatus == ServerChangeStatus.OK);
260 protected void changeToIdleState() {
261 currentOperationState = IDLE;
263 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
264 if (nextOperation != null) {
265 RaftActorServerConfigurationSupport.this.onNewOperation(nextOperation);
269 protected void sendReply(ServerOperationContext<?> operationContext, ServerChangeStatus status) {
270 LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status,
271 operationContext.getOperation());
273 operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
277 Cancellable newTimer(Object message) {
278 return newTimer(raftContext.getConfigParams().getElectionTimeOutInterval().$times(2), message);
281 Cancellable newTimer(FiniteDuration timeout, Object message) {
282 return raftContext.getActorSystem().scheduler().scheduleOnce(
283 timeout, raftContext.getActor(), message,
284 raftContext.getActorSystem().dispatcher(), raftContext.getActor());
288 public String toString() {
289 return getClass().getSimpleName();
294 * The state when no server operation is in progress. It immediately initiates new server operations.
296 private final class Idle extends OperationState {
298 public void onNewOperation(ServerOperationContext<?> operationContext) {
299 operationContext.newInitialOperationState(RaftActorServerConfigurationSupport.this).initiate();
303 public void onApplyState(ApplyState applyState) {
304 // Noop - we override b/c ApplyState is called normally for followers in the idle state.
309 * The state when a new server configuration is being persisted and replicated.
311 private final class Persisting extends OperationState {
312 private final ServerOperationContext<?> operationContext;
313 private final Cancellable timer;
314 private boolean timedOut = false;
316 Persisting(ServerOperationContext<?> operationContext, Cancellable timer) {
317 this.operationContext = operationContext;
322 public void onApplyState(ApplyState applyState) {
323 // Sanity check - we could get an ApplyState from a previous operation that timed out so make
324 // sure it's meant for us.
325 if (operationContext.getContextId().equals(applyState.getIdentifier())) {
326 LOG.info("{}: {} has been successfully replicated to a majority of followers", raftContext.getId(),
327 applyState.getReplicatedLogEntry().getData());
330 operationComplete(operationContext, null);
335 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
336 LOG.warn("{}: Timeout occured while replicating the new server configuration for {}", raftContext.getId(),
337 timeout.getLoggingContext());
341 // Fail any pending operations
342 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
343 while (nextOperation != null) {
344 sendReply(nextOperation, ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT);
345 nextOperation = pendingOperationsQueue.poll();
350 public void onNewOperation(ServerOperationContext<?> newOperationContext) {
352 sendReply(newOperationContext, ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT);
354 super.onNewOperation(newOperationContext);
360 * Abstract base class for an AddServer operation state.
362 private abstract class AddServerState extends OperationState {
363 private final AddServerContext addServerContext;
365 AddServerState(AddServerContext addServerContext) {
366 this.addServerContext = addServerContext;
369 AddServerContext getAddServerContext() {
370 return addServerContext;
373 Cancellable newInstallSnapshotTimer() {
374 return newTimer(new ServerOperationTimeout(addServerContext.getOperation().getNewServerId()));
377 void handleInstallSnapshotTimeout(ServerOperationTimeout timeout) {
378 String serverId = timeout.getLoggingContext();
380 LOG.debug("{}: handleInstallSnapshotTimeout for new server {}", raftContext.getId(), serverId);
383 raftContext.removePeer(serverId);
385 boolean isLeader = raftActor.isLeader();
387 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
388 leader.removeFollower(serverId);
391 operationComplete(getAddServerContext(), isLeader ? ServerChangeStatus.TIMEOUT
392 : ServerChangeStatus.NO_LEADER);
398 * The initial state for the AddServer operation. It adds the new follower as a peer and initiates
399 * snapshot capture, if necessary.
401 private final class InitialAddServerState extends AddServerState implements InitialOperationState {
402 InitialAddServerState(AddServerContext addServerContext) {
403 super(addServerContext);
407 public void initiate() {
408 final AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
409 AddServer addServer = getAddServerContext().getOperation();
411 LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);
413 if (raftContext.getPeerInfo(addServer.getNewServerId()) != null) {
414 operationComplete(getAddServerContext(), ServerChangeStatus.ALREADY_EXISTS);
418 VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
419 VotingState.NON_VOTING;
420 raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);
422 leader.addFollower(addServer.getNewServerId());
424 if (votingState == VotingState.VOTING_NOT_INITIALIZED) {
425 // schedule the install snapshot timeout timer
426 Cancellable installSnapshotTimer = newInstallSnapshotTimer();
427 if (leader.initiateCaptureSnapshot(addServer.getNewServerId())) {
428 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
429 addServer.getNewServerId());
431 currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
433 LOG.debug("{}: Snapshot already in progress - waiting for completion", raftContext.getId());
435 currentOperationState = new WaitingForPriorSnapshotComplete(getAddServerContext(),
436 installSnapshotTimer);
439 LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
440 raftContext.getId());
442 persistNewServerConfiguration(getAddServerContext());
448 * The AddServer operation state for when the catch-up snapshot is being installed. It handles successful
451 private final class InstallingSnapshot extends AddServerState {
452 private final Cancellable installSnapshotTimer;
454 InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) {
455 super(addServerContext);
456 this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer);
460 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
461 handleInstallSnapshotTimeout(timeout);
463 LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(),
464 timeout.getLoggingContext());
468 public void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
469 LOG.debug("{}: onUnInitializedFollowerSnapshotReply: {}", raftContext.getId(), reply);
471 String followerId = reply.getFollowerId();
473 // Sanity check to guard against receiving an UnInitializedFollowerSnapshotReply from a prior
474 // add server operation that timed out.
475 if (getAddServerContext().getOperation().getNewServerId().equals(followerId) && raftActor.isLeader()) {
476 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
477 raftContext.getPeerInfo(followerId).setVotingState(VotingState.VOTING);
478 leader.updateMinReplicaCount();
480 persistNewServerConfiguration(getAddServerContext());
482 installSnapshotTimer.cancel();
484 LOG.debug("{}: Dropping UnInitializedFollowerSnapshotReply for server {}: {}",
485 raftContext.getId(), followerId,
486 !raftActor.isLeader() ? "not leader" : "server Id doesn't match");
492 * The AddServer operation state for when there is a snapshot already in progress. When the current
493 * snapshot completes, it initiates an install snapshot.
495 private final class WaitingForPriorSnapshotComplete extends AddServerState {
496 private final Cancellable snapshotTimer;
498 WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) {
499 super(addServerContext);
500 this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer);
504 public void onSnapshotComplete() {
505 LOG.debug("{}: onSnapshotComplete", raftContext.getId());
507 if (!raftActor.isLeader()) {
508 LOG.debug("{}: No longer the leader", raftContext.getId());
512 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
513 if (leader.initiateCaptureSnapshot(getAddServerContext().getOperation().getNewServerId())) {
514 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
515 getAddServerContext().getOperation().getNewServerId());
517 currentOperationState = new InstallingSnapshot(getAddServerContext(),
518 newInstallSnapshotTimer());
520 snapshotTimer.cancel();
525 public void onServerOperationTimeout(ServerOperationTimeout timeout) {
526 handleInstallSnapshotTimeout(timeout);
528 LOG.warn("{}: Timeout occured for new server {} while waiting for prior snapshot to complete",
529 raftContext.getId(), timeout.getLoggingContext());
533 private static final class ServerOperationContextIdentifier
534 extends AbstractUUIDIdentifier<ServerOperationContextIdentifier> {
535 private static final long serialVersionUID = 1L;
537 ServerOperationContextIdentifier() {
538 super(UUID.randomUUID());
543 * Stores context information for a server operation.
545 * @param <T> the operation type
547 private abstract static class ServerOperationContext<T> {
548 private final T operation;
549 private final ActorRef clientRequestor;
550 private final Identifier contextId;
552 ServerOperationContext(T operation, ActorRef clientRequestor) {
553 this.operation = operation;
554 this.clientRequestor = clientRequestor;
555 contextId = new ServerOperationContextIdentifier();
558 Identifier getContextId() {
566 ActorRef getClientRequestor() {
567 return clientRequestor;
570 void operationComplete(RaftActor raftActor, boolean succeeded) {
573 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
577 abstract Object newReply(ServerChangeStatus status, String leaderId);
579 abstract InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support);
581 abstract String getLoggingContext();
585 * Stores context information for an AddServer operation.
587 private static class AddServerContext extends ServerOperationContext<AddServer> {
588 AddServerContext(AddServer addServer, ActorRef clientRequestor) {
589 super(addServer, clientRequestor);
593 Object newReply(ServerChangeStatus status, String leaderId) {
594 return new AddServerReply(status, leaderId);
598 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
599 return support.new InitialAddServerState(this);
603 String getLoggingContext() {
604 return getOperation().getNewServerId();
608 private abstract class RemoveServerState extends OperationState {
609 private final RemoveServerContext removeServerContext;
611 protected RemoveServerState(RemoveServerContext removeServerContext) {
612 this.removeServerContext = Preconditions.checkNotNull(removeServerContext);
616 public RemoveServerContext getRemoveServerContext() {
617 return removeServerContext;
621 private final class InitialRemoveServerState extends RemoveServerState implements InitialOperationState {
623 protected InitialRemoveServerState(RemoveServerContext removeServerContext) {
624 super(removeServerContext);
628 public void initiate() {
629 String serverId = getRemoveServerContext().getOperation().getServerId();
630 raftContext.removePeer(serverId);
631 AbstractLeader leader = (AbstractLeader)raftActor.getCurrentBehavior();
632 leader.removeFollower(serverId);
633 leader.updateMinReplicaCount();
635 persistNewServerConfiguration(getRemoveServerContext());
639 private static class RemoveServerContext extends ServerOperationContext<RemoveServer> {
640 private final String peerAddress;
642 RemoveServerContext(RemoveServer operation, String peerAddress, ActorRef clientRequestor) {
643 super(operation, clientRequestor);
644 this.peerAddress = peerAddress;
648 Object newReply(ServerChangeStatus status, String leaderId) {
649 return new RemoveServerReply(status, leaderId);
653 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
654 return support.new InitialRemoveServerState(this);
658 void operationComplete(RaftActor raftActor, boolean succeeded) {
659 if (peerAddress != null) {
660 raftActor.context().actorSelection(peerAddress).tell(
661 new ServerRemoved(getOperation().getServerId()), raftActor.getSelf());
666 boolean includeSelfInNewConfiguration(RaftActor raftActor) {
667 return !getOperation().getServerId().equals(raftActor.getId());
671 String getLoggingContext() {
672 return getOperation().getServerId();
676 private static class ChangeServersVotingStatusContext extends ServerOperationContext<ChangeServersVotingStatus> {
677 private final boolean tryToElectLeader;
679 ChangeServersVotingStatusContext(ChangeServersVotingStatus convertMessage, ActorRef clientRequestor,
680 boolean tryToElectLeader) {
681 super(convertMessage, clientRequestor);
682 this.tryToElectLeader = tryToElectLeader;
686 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
687 return support.new ChangeServersVotingStatusState(this, tryToElectLeader);
691 Object newReply(ServerChangeStatus status, String leaderId) {
692 return new ServerChangeReply(status, leaderId);
696 void operationComplete(final RaftActor raftActor, boolean succeeded) {
697 // If this leader changed to non-voting we need to step down as leader so we'll try to transfer
699 boolean localServerChangedToNonVoting = Boolean.FALSE.equals(getOperation()
700 .getServerVotingStatusMap().get(raftActor.getRaftActorContext().getId()));
701 if (succeeded && localServerChangedToNonVoting) {
702 LOG.debug("Leader changed to non-voting - trying leadership transfer");
703 raftActor.becomeNonVoting();
708 String getLoggingContext() {
709 return getOperation().toString();
713 private class ChangeServersVotingStatusState extends OperationState implements InitialOperationState {
714 private final ChangeServersVotingStatusContext changeVotingStatusContext;
715 private final boolean tryToElectLeader;
717 ChangeServersVotingStatusState(ChangeServersVotingStatusContext changeVotingStatusContext,
718 boolean tryToElectLeader) {
719 this.changeVotingStatusContext = changeVotingStatusContext;
720 this.tryToElectLeader = tryToElectLeader;
724 public void initiate() {
725 LOG.debug("Initiating ChangeServersVotingStatusState");
727 if (tryToElectLeader) {
728 initiateLocalLeaderElection();
729 } else if (updateLocalPeerInfo()) {
730 persistNewServerConfiguration(changeVotingStatusContext);
734 private void initiateLocalLeaderElection() {
735 LOG.debug("{}: Sending local ElectionTimeout to start leader election", raftContext.getId());
737 ServerConfigurationPayload previousServerConfig = raftContext.getPeerServerInfo(true);
738 if (!updateLocalPeerInfo()) {
742 raftContext.getActor().tell(TimeoutNow.INSTANCE, raftContext.getActor());
744 currentOperationState = new WaitingForLeaderElected(changeVotingStatusContext, previousServerConfig);
747 private boolean updateLocalPeerInfo() {
748 List<ServerInfo> newServerInfoList = newServerInfoList();
750 // Check if new voting state would leave us with no voting members.
751 boolean atLeastOneVoting = false;
752 for (ServerInfo info: newServerInfoList) {
753 if (info.isVoting()) {
754 atLeastOneVoting = true;
759 if (!atLeastOneVoting) {
760 operationComplete(changeVotingStatusContext, ServerChangeStatus.INVALID_REQUEST);
764 raftContext.updatePeerIds(new ServerConfigurationPayload(newServerInfoList));
765 if (raftActor.getCurrentBehavior() instanceof AbstractLeader) {
766 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
767 leader.updateMinReplicaCount();
773 private List<ServerInfo> newServerInfoList() {
774 Map<String, Boolean> serverVotingStatusMap = changeVotingStatusContext.getOperation()
775 .getServerVotingStatusMap();
776 List<ServerInfo> newServerInfoList = new ArrayList<>();
777 for (String peerId: raftContext.getPeerIds()) {
778 newServerInfoList.add(new ServerInfo(peerId, serverVotingStatusMap.containsKey(peerId)
779 ? serverVotingStatusMap.get(peerId) : raftContext.getPeerInfo(peerId).isVoting()));
782 newServerInfoList.add(new ServerInfo(raftContext.getId(), serverVotingStatusMap.containsKey(
783 raftContext.getId()) ? serverVotingStatusMap.get(raftContext.getId())
784 : raftContext.isVotingMember()));
786 return newServerInfoList;
790 private class WaitingForLeaderElected extends OperationState {
791 private final ServerConfigurationPayload previousServerConfig;
792 private final ChangeServersVotingStatusContext operationContext;
793 private final Cancellable timer;
795 WaitingForLeaderElected(ChangeServersVotingStatusContext operationContext,
796 ServerConfigurationPayload previousServerConfig) {
797 this.operationContext = operationContext;
798 this.previousServerConfig = previousServerConfig;
800 timer = newTimer(raftContext.getConfigParams().getElectionTimeOutInterval(),
801 new ServerOperationTimeout(operationContext.getLoggingContext()));
805 void onNewLeader(String newLeader) {
806 if (newLeader == null) {
810 LOG.debug("{}: New leader {} elected", raftContext.getId(), newLeader);
814 if (raftActor.isLeader()) {
815 persistNewServerConfiguration(operationContext);
817 // Edge case - some other node became leader so forward the operation.
818 LOG.debug("{}: Forwarding {} to new leader", raftContext.getId(), operationContext.getOperation());
820 // Revert the local server config change.
821 raftContext.updatePeerIds(previousServerConfig);
824 RaftActorServerConfigurationSupport.this.onNewOperation(operationContext);
829 void onServerOperationTimeout(ServerOperationTimeout timeout) {
830 LOG.warn("{}: Leader election timed out - cannot apply operation {}",
831 raftContext.getId(), timeout.getLoggingContext());
833 // Revert the local server config change.
834 raftContext.updatePeerIds(previousServerConfig);
835 raftActor.initializeBehavior();
837 tryToForwardOperationToAnotherServer();
840 private void tryToForwardOperationToAnotherServer() {
841 Collection<String> serversVisited = new HashSet<>(operationContext.getOperation().getServersVisited());
843 LOG.debug("{}: tryToForwardOperationToAnotherServer - servers already visited {}", raftContext.getId(),
846 serversVisited.add(raftContext.getId());
848 // Try to find another whose state is being changed from non-voting to voting and that we haven't
850 Map<String, Boolean> serverVotingStatusMap = operationContext.getOperation().getServerVotingStatusMap();
851 ActorSelection forwardToPeerActor = null;
852 for (Map.Entry<String, Boolean> e: serverVotingStatusMap.entrySet()) {
853 Boolean isVoting = e.getValue();
854 String serverId = e.getKey();
855 PeerInfo peerInfo = raftContext.getPeerInfo(serverId);
856 if (isVoting && peerInfo != null && !peerInfo.isVoting() && !serversVisited.contains(serverId)) {
857 ActorSelection actor = raftContext.getPeerActorSelection(serverId);
859 forwardToPeerActor = actor;
865 if (forwardToPeerActor != null) {
866 LOG.debug("{}: Found server {} to forward to", raftContext.getId(), forwardToPeerActor);
868 forwardToPeerActor.tell(new ChangeServersVotingStatus(serverVotingStatusMap, serversVisited),
869 operationContext.getClientRequestor());
872 operationComplete(operationContext, ServerChangeStatus.NO_LEADER);
877 static class ServerOperationTimeout {
878 private final String loggingContext;
880 ServerOperationTimeout(String loggingContext) {
881 this.loggingContext = Preconditions.checkNotNull(loggingContext, "loggingContext should not be null");
884 String getLoggingContext() {
885 return loggingContext;