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.behaviors.AbstractLeader;
24 import org.opendaylight.controller.cluster.raft.messages.AddServer;
25 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
26 import org.opendaylight.controller.cluster.raft.messages.FollowerCatchUpTimeout;
27 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
28 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
29 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import scala.concurrent.duration.FiniteDuration;
35 * Handles server configuration related messages for a RaftActor.
37 * @author Thomas Pantelis
39 class RaftActorServerConfigurationSupport {
40 private static final Logger LOG = LoggerFactory.getLogger(RaftActorServerConfigurationSupport.class);
42 private final OperationState IDLE = new Idle();
44 private final RaftActorContext raftContext;
46 private final Queue<ServerOperationContext<?>> pendingOperationsQueue = new LinkedList<>();
48 private OperationState currentOperationState = IDLE;
50 RaftActorServerConfigurationSupport(RaftActorContext context) {
51 this.raftContext = context;
54 boolean handleMessage(Object message, RaftActor raftActor, ActorRef sender) {
55 if(message instanceof AddServer) {
56 onAddServer((AddServer)message, raftActor, sender);
58 } else if (message instanceof FollowerCatchUpTimeout) {
59 currentOperationState.onFollowerCatchupTimeout(raftActor, (FollowerCatchUpTimeout)message);
61 } else if (message instanceof UnInitializedFollowerSnapshotReply) {
62 currentOperationState.onUnInitializedFollowerSnapshotReply(raftActor,
63 (UnInitializedFollowerSnapshotReply)message);
65 } else if(message instanceof ApplyState) {
66 return onApplyState((ApplyState) message, raftActor);
72 private boolean onApplyState(ApplyState applyState, RaftActor raftActor) {
73 Payload data = applyState.getReplicatedLogEntry().getData();
74 if(data instanceof ServerConfigurationPayload) {
75 currentOperationState.onApplyState(raftActor, applyState);
83 * The algorithm for AddServer is as follows:
85 * <li>Add the new server as a peer.</li>
86 * <li>Add the new follower to the leader.</li>
87 * <li>If new server should be voting member</li>
89 * <li>Initialize FollowerState to VOTING_NOT_INITIALIZED.</li>
90 * <li>Initiate install snapshot to the new follower.</li>
91 * <li>When install snapshot complete, mark the follower as VOTING and re-calculate majority vote count.</li>
93 * <li>Persist and replicate ServerConfigurationPayload with the new server list.</li>
94 * <li>On replication consensus, respond to caller with OK.</li>
96 * If the install snapshot times out after a period of 2 * election time out
98 * <li>Remove the new server as a peer.</li>
99 * <li>Remove the new follower from the leader.</li>
100 * <li>Respond to caller with TIMEOUT.</li>
103 private void onAddServer(AddServer addServer, RaftActor raftActor, ActorRef sender) {
104 LOG.debug("{}: onAddServer: {}", raftContext.getId(), addServer);
106 onNewOperation(raftActor, new AddServerContext(addServer, sender));
109 private void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
110 if (raftActor.isLeader()) {
111 currentOperationState.onNewOperation(raftActor, operationContext);
113 ActorSelection leader = raftActor.getLeader();
114 if (leader != null) {
115 LOG.debug("{}: Not leader - forwarding to leader {}", raftContext.getId(), leader);
116 leader.forward(operationContext.getOperation(), raftActor.getContext());
118 LOG.debug("{}: No leader - returning NO_LEADER reply", raftContext.getId());
119 operationContext.getClientRequestor().tell(operationContext.newReply(
120 ServerChangeStatus.NO_LEADER, null), raftActor.self());
126 * Interface for a server operation FSM state.
128 private interface OperationState {
129 void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext);
131 void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout);
133 void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply);
135 void onApplyState(RaftActor raftActor, ApplyState applyState);
139 * Interface for the initial state for a server operation.
141 private interface InitialOperationState {
142 void initiate(RaftActor raftActor);
146 * Abstract base class for server operation FSM state. Handles common behavior for all states.
148 private abstract class AbstractOperationState implements OperationState {
150 public void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
151 // We're currently processing another operation so queue it to be processed later.
153 LOG.debug("{}: Server operation already in progress - queueing {}", raftContext.getId(),
154 operationContext.getOperation());
156 pendingOperationsQueue.add(operationContext);
160 public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
161 LOG.debug("onFollowerCatchupTimeout should not be called in state {}", this);
165 public void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply) {
166 LOG.debug("onUnInitializedFollowerSnapshotReply was called in state {}", this);
170 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
171 LOG.debug("onApplyState was called in state {}", this);
174 protected void persistNewServerConfiguration(RaftActor raftActor, ServerOperationContext<?> operationContext){
175 Collection<PeerInfo> peers = raftContext.getPeers();
176 List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
177 for(PeerInfo peer: peers) {
178 newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
181 newConfig.add(new ServerInfo(raftContext.getId(), true));
183 LOG.debug("{}: New server configuration : {}", raftContext.getId(), newConfig);
185 ServerConfigurationPayload payload = new ServerConfigurationPayload(newConfig);
187 raftActor.persistData(operationContext.getClientRequestor(), operationContext.getContextId(), payload);
189 currentOperationState = new Persisting(operationContext);
192 protected void operationComplete(RaftActor raftActor, ServerOperationContext<?> operationContext,
193 ServerChangeStatus status) {
195 LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status, operationContext.getOperation());
197 operationContext.getClientRequestor().tell(operationContext.newReply(status, raftActor.getLeaderId()),
200 currentOperationState = IDLE;
202 ServerOperationContext<?> nextOperation = pendingOperationsQueue.poll();
203 if(nextOperation != null) {
204 RaftActorServerConfigurationSupport.this.onNewOperation(raftActor, nextOperation);
209 public String toString() {
210 return getClass().getSimpleName();
215 * The state when no server operation is in progress. It immediately initiates new server operations.
217 private class Idle extends AbstractOperationState {
219 public void onNewOperation(RaftActor raftActor, ServerOperationContext<?> operationContext) {
220 operationContext.newInitialOperationState(RaftActorServerConfigurationSupport.this).initiate(raftActor);
224 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
225 // Noop - we override b/c ApplyState is called normally for followers in the idle state.
230 * The state when a new server configuration is being persisted and replicated.
232 private class Persisting extends AbstractOperationState {
233 private final ServerOperationContext<?> operationContext;
235 Persisting(ServerOperationContext<?> operationContext) {
236 this.operationContext = operationContext;
240 public void onApplyState(RaftActor raftActor, ApplyState applyState) {
241 // Sanity check - we could get an ApplyState from a previous operation that timed out so make
242 // sure it's meant for us.
243 if(operationContext.getContextId().equals(applyState.getIdentifier())) {
244 LOG.info("{}: {} has been successfully replicated to a majority of followers",
245 applyState.getReplicatedLogEntry().getData());
247 operationComplete(raftActor, operationContext, ServerChangeStatus.OK);
253 * Abstract base class for an AddServer operation state.
255 private abstract class AddServerState extends AbstractOperationState {
256 private final AddServerContext addServerContext;
258 AddServerState(AddServerContext addServerContext) {
259 this.addServerContext = addServerContext;
262 AddServerContext getAddServerContext() {
263 return addServerContext;
268 * The initial state for the AddServer operation. It adds the new follower as a peer and initiates
269 * snapshot capture, if necessary.
271 private class InitialAddServerState extends AddServerState implements InitialOperationState {
272 InitialAddServerState(AddServerContext addServerContext) {
273 super(addServerContext);
277 public void initiate(RaftActor raftActor) {
278 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
280 AddServer addServer = getAddServerContext().getOperation();
282 LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);
284 VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
285 VotingState.NON_VOTING;
286 raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);
288 leader.addFollower(addServer.getNewServerId());
290 if(votingState == VotingState.VOTING_NOT_INITIALIZED){
291 LOG.debug("{}: Leader sending initiate capture snapshot to new follower {}", raftContext.getId(),
292 addServer.getNewServerId());
294 leader.initiateCaptureSnapshot(addServer.getNewServerId());
296 // schedule the install snapshot timeout timer
297 Cancellable installSnapshotTimer = raftContext.getActorSystem().scheduler().scheduleOnce(
298 new FiniteDuration(((raftContext.getConfigParams().getElectionTimeOutInterval().toMillis()) * 2),
299 TimeUnit.MILLISECONDS), raftContext.getActor(),
300 new FollowerCatchUpTimeout(addServer.getNewServerId()),
301 raftContext.getActorSystem().dispatcher(), raftContext.getActor());
303 currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
305 LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
306 raftContext.getId());
308 persistNewServerConfiguration(raftActor, getAddServerContext());
314 * The AddServer operation state for when the catch-up snapshot is being installed. It handles successful
317 private class InstallingSnapshot extends AddServerState {
318 private final Cancellable installSnapshotTimer;
320 InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) {
321 super(addServerContext);
322 this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer);
326 public void onFollowerCatchupTimeout(RaftActor raftActor, FollowerCatchUpTimeout followerTimeout) {
327 String serverId = followerTimeout.getNewServerId();
329 LOG.debug("{}: onFollowerCatchupTimeout: {}", raftContext.getId(), serverId);
331 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
334 raftContext.removePeer(serverId);
335 leader.removeFollower(serverId);
337 LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(), serverId);
339 operationComplete(raftActor, getAddServerContext(), ServerChangeStatus.TIMEOUT);
343 public void onUnInitializedFollowerSnapshotReply(RaftActor raftActor, UnInitializedFollowerSnapshotReply reply) {
344 LOG.debug("{}: onUnInitializedFollowerSnapshotReply: {}", raftContext.getId(), reply);
346 String followerId = reply.getFollowerId();
348 // Sanity check to guard against receiving an UnInitializedFollowerSnapshotReply from a prior
349 // add server operation that timed out.
350 if(getAddServerContext().getOperation().getNewServerId().equals(followerId)) {
351 AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
352 raftContext.getPeerInfo(followerId).setVotingState(VotingState.VOTING);
353 leader.updateMinReplicaCount();
355 persistNewServerConfiguration(raftActor, getAddServerContext());
357 installSnapshotTimer.cancel();
363 * Stores context information for a server operation.
365 * @param <T> the operation type
367 private static abstract class ServerOperationContext<T> {
368 private final T operation;
369 private final ActorRef clientRequestor;
370 private final String contextId;
372 ServerOperationContext(T operation, ActorRef clientRequestor){
373 this.operation = operation;
374 this.clientRequestor = clientRequestor;
375 contextId = UUID.randomUUID().toString();
378 String getContextId() {
386 ActorRef getClientRequestor() {
387 return clientRequestor;
390 abstract Object newReply(ServerChangeStatus status, String leaderId);
392 abstract InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support);
396 * Stores context information for an AddServer operation.
398 private static class AddServerContext extends ServerOperationContext<AddServer> {
399 AddServerContext(AddServer addServer, ActorRef clientRequestor) {
400 super(addServer, clientRequestor);
404 Object newReply(ServerChangeStatus status, String leaderId) {
405 return new AddServerReply(status, leaderId);
409 InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
410 return support.new InitialAddServerState(this);