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.ArrayList;
15 import java.util.Collection;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Queue;
19 import java.util.UUID;
20 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload.ServerInfo;
22 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
23 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
24 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
25 import org.opendaylight.controller.cluster.raft.messages.AddServer;
26 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
27 import org.opendaylight.controller.cluster.raft.messages.FollowerCatchUpTimeout;
28 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
29 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
30 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import scala.concurrent.duration.FiniteDuration;
36 * Handles server configuration related messages for a RaftActor.
38 * @author Thomas Pantelis
40 class RaftActorServerConfigurationSupport {
41 private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupport.class);
43 private final OperationState IDLE = new Idle();
45 private final RaftActorContext raftContext;
47 private final Queue<ServerOperationContext<?>> pendingOperationsQueue = new LinkedList<>();
49 private OperationState currentOperationState = IDLE;
51 RaftActorServerConfigurationSupport(RaftActorContext context) {
52 this.raftContext = context;
55 boolean handleMessage(Object message, RaftActor raftActor, ActorRef sender) {
56 if(message instanceof AddServer) {
57 onAddServer((AddServer)message, raftActor, sender);
59 } else if (message instanceof FollowerCatchUpTimeout) {
60 currentOperationState.onFollowerCatchupTimeout(raftActor, (FollowerCatchUpTimeout)message);
62 } else if (message instanceof UnInitializedFollowerSnapshotReply) {
63 currentOperationState.onUnInitializedFollowerSnapshotReply(raftActor,
64 (UnInitializedFollowerSnapshotReply)message);
66 } else if(message instanceof ApplyState) {
67 return onApplyState((ApplyState) message, raftActor);
68 } else if(message instanceof SnapshotComplete) {
69 currentOperationState.onSnapshotComplete(raftActor);
76 private boolean onApplyState(ApplyState applyState, RaftActor raftActor) {
77 Payload data = applyState.getReplicatedLogEntry().getData();
78 if(data instanceof ServerConfigurationPayload) {
79 currentOperationState.onApplyState(raftActor, applyState);
87 * The algorithm for AddServer is as follows:
89 * <li>Add the new server as a peer.</li>
90 * <li>Add the new follower to the leader.</li>
91 * <li>If new server should be voting member</li>
93 * <li>Initialize FollowerState to VOTING_NOT_INITIALIZED.</li>
94 * <li>Initiate install snapshot to the new follower.</li>
95 * <li>When install snapshot complete, mark the follower as VOTING and re-calculate majority vote count.</li>
97 * <li>Persist and replicate ServerConfigurationPayload with the new server list.</li>
98 * <li>On replication consensus, respond to caller with OK.</li>
100 * If the install snapshot times out after a period of 2 * election time out
102 * <li>Remove the new server as a peer.</li>
103 * <li>Remove the new follower from the leader.</li>
104 * <li>Respond to caller with TIMEOUT.</li>
107 private void onAddServer(AddServer addServer, RaftActor raftActor, ActorRef sender) {
108 LOG.debug("{}: onAddServer: {}", raftContext.getId(), addServer);
110 onNewOperation(raftActor, new AddServerContext(addServer, sender));
113 private void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
114 if (raftActor.isLeader()) {
115 currentOperationState.onNewOperation(raftActor, operationContext);
117 ActorSelection leader = raftActor.getLeader();
118 if (leader != null) {
119 LOG.debug("{}: Not leader - forwarding to leader {}", raftContext.getId(), leader);
120 leader.forward(operationContext.getOperation(), raftActor.getContext());
122 LOG.debug("{}: No leader - returning NO_LEADER reply", raftContext.getId());
123 operationContext.getClientRequestor().tell(operationContext.newReply(
124 ServerChangeStatus.NO_LEADER, null), raftActor.self());
130 * Interface for a server operation FSM state.
132 private interface OperationState {
133 void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext);
135 void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout);
137 void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply);
139 void onApplyState(RaftActor raftActor, ApplyState applyState);
141 void onSnapshotComplete(RaftActor raftActor);
145 * Interface for the initial state for a server operation.
147 private interface InitialOperationState {
148 void initiate(RaftActor raftActor);
152 * Abstract base class for server operation FSM state. Handles common behavior for all states.
154 private abstract class AbstractOperationState implements OperationState {
156 public void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
157 // We're currently processing another operation so queue it to be processed later.
159 LOG.debug("{}: Server operation already in progress - queueing {}", raftContext.getId(),
160 operationContext.getOperation());
162 pendingOperationsQueue.add(operationContext);
166 public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
167 LOG.debug("onFollowerCatchupTimeout should not be called in state {}", this);
171 public void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply) {
172 LOG.debug("onUnInitializedFollowerSnapshotReply was called in state {}", this);
176 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
177 LOG.debug("onApplyState was called in state {}", this);
181 public void onSnapshotComplete(RaftActor raftActor) {
184 protected void persistNewServerConfiguration(RaftActor raftActor, ServerOperationContext<?> operationContext){
185 Collection<PeerInfo> peers = raftContext.getPeers();
186 List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
187 for(PeerInfo peer: peers) {
188 newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
191 newConfig.add(new ServerInfo(raftContext.getId(), true));
193 LOG.debug("{}: New server configuration : {}", raftContext.getId(), newConfig);
195 ServerConfigurationPayload payload = new ServerConfigurationPayload(newConfig);
197 raftActor.persistData(operationContext.getClientRequestor(), operationContext.getContextId(), payload);
199 currentOperationState = new Persisting(operationContext);
202 protected void operationComplete(RaftActor raftActor, ServerOperationContext<?> operationContext,
203 ServerChangeStatus status) {
205 LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status, operationContext.getOperation());
207 operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
210 currentOperationState = IDLE;
212 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
213 if(nextOperation != null) {
214 RaftActorServerConfigurationSupport.this.onNewOperation(raftActor, nextOperation);
219 public String toString() {
220 return getClass().getSimpleName();
225 * The state when no server operation is in progress. It immediately initiates new server operations.
227 private class Idle extends AbstractOperationState {
229 public void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
230 operationContext.newInitialOperationState(RaftActorServerConfigurationSupport.this).initiate(raftActor);
234 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
235 // Noop - we override b/c ApplyState is called normally for followers in the idle state.
240 * The state when a new server configuration is being persisted and replicated.
242 private class Persisting extends AbstractOperationState {
243 private final ServerOperationContext<?> operationContext;
245 Persisting(ServerOperationContext<?> operationContext) {
246 this.operationContext = operationContext;
250 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
251 // Sanity check - we could get an ApplyState from a previous operation that timed out so make
252 // sure it's meant for us.
253 if(operationContext.getContextId().equals(applyState.getIdentifier())) {
254 LOG.info("{}: {} has been successfully replicated to a majority of followers",
255 applyState.getReplicatedLogEntry().getData());
257 operationComplete(raftActor, operationContext, ServerChangeStatus.OK);
263 * Abstract base class for an AddServer operation state.
265 private abstract class AddServerState extends AbstractOperationState {
266 private final AddServerContext addServerContext;
268 AddServerState(AddServerContext addServerContext) {
269 this.addServerContext = addServerContext;
272 AddServerContext getAddServerContext() {
273 return addServerContext;
276 Cancellable newInstallSnapshotTimer(RaftActor raftActor) {
277 return raftContext.getActorSystem().scheduler().scheduleOnce(
278 new FiniteDuration(((raftContext.getConfigParams().getElectionTimeOutInterval().toMillis()) * 2),
279 TimeUnit.MILLISECONDS), raftContext.getActor(),
280 new FollowerCatchUpTimeout(addServerContext.getOperation().getNewServerId()),
281 raftContext.getActorSystem().dispatcher(), raftContext.getActor());
284 void handleOnFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
285 String serverId = followerTimeout.getNewServerId();
287 LOG.debug("{}: onFollowerCatchupTimeout for new server {}", raftContext.getId(), serverId);
290 raftContext.removePeer(serverId);
292 boolean isLeader = raftActor.isLeader();
294 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
295 leader.removeFollower(serverId);
298 operationComplete(raftActor, getAddServerContext(),
299 isLeader ? ServerChangeStatus.TIMEOUT : ServerChangeStatus.NO_LEADER);
304 * The initial state for the AddServer operation. It adds the new follower as a peer and initiates
305 * snapshot capture, if necessary.
307 private class InitialAddServerState extends AddServerState implements InitialOperationState {
308 InitialAddServerState(AddServerContext addServerContext) {
309 super(addServerContext);
313 public void initiate(RaftActor raftActor) {
314 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
316 AddServer addServer = getAddServerContext().getOperation();
318 LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);
320 VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
321 VotingState.NON_VOTING;
322 raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);
324 leader.addFollower(addServer.getNewServerId());
326 if(votingState == VotingState.VOTING_NOT_INITIALIZED){
327 // schedule the install snapshot timeout timer
328 Cancellable installSnapshotTimer = newInstallSnapshotTimer(raftActor);
329 if(leader.initiateCaptureSnapshot(addServer.getNewServerId())) {
330 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
331 addServer.getNewServerId());
333 currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
335 LOG.debug("{}: Snapshot already in progress - waiting for completion", raftContext.getId());
337 currentOperationState = new WaitingForPriorSnapshotComplete(getAddServerContext(),
338 installSnapshotTimer);
341 LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
342 raftContext.getId());
344 persistNewServerConfiguration(raftActor, getAddServerContext());
350 * The AddServer operation state for when the catch-up snapshot is being installed. It handles successful
353 private class InstallingSnapshot extends AddServerState {
354 private final Cancellable installSnapshotTimer;
356 InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) {
357 super(addServerContext);
358 this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer);
362 public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
363 handleOnFollowerCatchupTimeout(raftActor, followerTimeout);
365 LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(),
366 followerTimeout.getNewServerId());
370 public void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply) {
371 LOG.debug("{}: onUnInitializedFollowerSnapshotReply: {}", raftContext.getId(), reply);
373 String followerId = reply.getFollowerId();
375 // Sanity check to guard against receiving an UnInitializedFollowerSnapshotReply from a prior
376 // add server operation that timed out.
377 if(getAddServerContext().getOperation().getNewServerId().equals(followerId) && raftActor.isLeader()) {
378 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
379 raftContext.getPeerInfo(followerId).setVotingState(VotingState.VOTING);
380 leader.updateMinReplicaCount();
382 persistNewServerConfiguration(raftActor, getAddServerContext());
384 installSnapshotTimer.cancel();
386 LOG.debug("{}: Dropping UnInitializedFollowerSnapshotReply for server {}: {}",
387 raftContext.getId(), followerId,
388 !raftActor.isLeader() ? "not leader" : "server Id doesn't match");
394 * The AddServer operation state for when there is a snapshot already in progress. When the current
395 * snapshot completes, it initiates an install snapshot.
397 private class WaitingForPriorSnapshotComplete extends AddServerState {
398 private final Cancellable snapshotTimer;
400 WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) {
401 super(addServerContext);
402 this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer);
406 public void onSnapshotComplete(RaftActor raftActor) {
407 LOG.debug("{}: onSnapshotComplete", raftContext.getId());
409 if(!raftActor.isLeader()) {
410 LOG.debug("{}: No longer the leader", raftContext.getId());
414 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
415 if(leader.initiateCaptureSnapshot(getAddServerContext().getOperation().getNewServerId())) {
416 LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
417 getAddServerContext().getOperation().getNewServerId());
419 currentOperationState = new InstallingSnapshot(getAddServerContext(),
420 newInstallSnapshotTimer(raftActor));
422 snapshotTimer.cancel();
427 public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
428 handleOnFollowerCatchupTimeout(raftActor, followerTimeout);
430 LOG.warn("{}: Timeout occured for new server {} while waiting for prior snapshot to complete",
431 raftContext.getId(), followerTimeout.getNewServerId());
436 * Stores context information for a server operation.
438 * @param <T> the operation type
440 private static abstract class ServerOperationContext<T> {
441 private final T operation;
442 private final ActorRef clientRequestor;
443 private final String contextId;
445 ServerOperationContext(T operation, ActorRef clientRequestor){
446 this.operation = operation;
447 this.clientRequestor = clientRequestor;
448 contextId = UUID.randomUUID().toString();
451 String getContextId() {
459 ActorRef getClientRequestor() {
460 return clientRequestor;
463 abstract Object newReply(ServerChangeStatus status, String leaderId);
465 abstract InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support);
469 * Stores context information for an AddServer operation.
471 private static class AddServerContext extends ServerOperationContext<AddServer> {
472 AddServerContext(AddServer addServer, ActorRef clientRequestor) {
473 super(addServer, clientRequestor);
477 Object newReply(ServerChangeStatus status, String leaderId) {
478 return new AddServerReply(status, leaderId);
482 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
483 return support.new InitialAddServerState(this);