2 * Copyright (c) 2014 Cisco 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
9 package org.opendaylight.controller.cluster.raft;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.japi.Procedure;
14 import akka.persistence.SnapshotSelectionCriteria;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Objects;
17 import com.google.common.base.Optional;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Lists;
20 import java.io.Serializable;
21 import java.util.Collection;
22 import java.util.List;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.apache.commons.lang3.time.DurationFormatUtils;
27 import org.opendaylight.controller.cluster.DataPersistenceProvider;
28 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
29 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
30 import org.opendaylight.controller.cluster.PersistentDataProvider;
31 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
32 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
33 import org.opendaylight.controller.cluster.notifications.RoleChanged;
34 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
35 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
36 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
37 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
38 import org.opendaylight.controller.cluster.raft.behaviors.DelegatingRaftActorBehavior;
39 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
40 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
41 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
42 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
43 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
44 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
45 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
46 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * RaftActor encapsulates a state machine that needs to be kept synchronized
52 * in a cluster. It implements the RAFT algorithm as described in the paper
53 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
54 * In Search of an Understandable Consensus Algorithm</a>
56 * RaftActor has 3 states and each state has a certain behavior associated
57 * with it. A Raft actor can behave as,
60 * <li> A Follower (or) </li>
61 * <li> A Candidate </li>
65 * A RaftActor MUST be a Leader in order to accept requests from clients to
66 * change the state of it's encapsulated state machine. Once a RaftActor becomes
67 * a Leader it is also responsible for ensuring that all followers ultimately
68 * have the same log and therefore the same state machine as itself.
71 * The current behavior of a RaftActor determines how election for leadership
72 * is initiated and how peer RaftActors react to request for votes.
75 * Each RaftActor also needs to know the current election term. It uses this
76 * information for a couple of things. One is to simply figure out who it
77 * voted for in the last election. Another is to figure out if the message
78 * it received to update it's state is stale.
81 * The RaftActor uses akka-persistence to store it's replicated log.
82 * Furthermore through it's behaviors a Raft Actor determines
85 * <li> when a log entry should be persisted </li>
86 * <li> when a log entry should be applied to the state machine (and) </li>
87 * <li> when a snapshot should be saved </li>
90 public abstract class RaftActor extends AbstractUntypedPersistentActor {
92 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
94 protected final Logger LOG = LoggerFactory.getLogger(getClass());
97 * The current state determines the current behavior of a RaftActor
98 * A Raft Actor always starts off in the Follower State
100 private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
103 * This context should NOT be passed directly to any other actor it is
104 * only to be consumed by the RaftActorBehaviors
106 private final RaftActorContextImpl context;
108 private final DelegatingPersistentDataProvider delegatingPersistenceProvider = new DelegatingPersistentDataProvider(null);
110 private RaftActorRecoverySupport raftRecovery;
112 private RaftActorSnapshotMessageSupport snapshotSupport;
114 private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
116 public RaftActor(String id, Map<String, String> peerAddresses) {
117 this(id, peerAddresses, Optional.<ConfigParams>absent());
120 public RaftActor(String id, Map<String, String> peerAddresses,
121 Optional<ConfigParams> configParams) {
123 context = new RaftActorContextImpl(this.getSelf(),
124 this.getContext(), id, new ElectionTermImpl(delegatingPersistenceProvider, id, LOG),
125 -1, -1, peerAddresses,
126 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()), LOG);
128 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, delegatingPersistenceProvider, currentBehavior));
132 public void preStart() throws Exception {
133 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
134 context.getConfigParams().getJournalRecoveryLogBatchSize());
140 public void postStop() {
141 if(currentBehavior.getDelegate() != null) {
143 currentBehavior.close();
144 } catch (Exception e) {
145 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
153 public void handleRecover(Object message) {
154 if(raftRecovery == null) {
155 raftRecovery = new RaftActorRecoverySupport(delegatingPersistenceProvider, context, currentBehavior,
156 getRaftActorRecoveryCohort());
159 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message);
160 if(recoveryComplete) {
161 if(!persistence().isRecoveryApplicable()) {
162 // Delete all the messages from the akka journal so that we do not end up with consistency issues
163 // Note I am not using the dataPersistenceProvider and directly using the akka api here
164 deleteMessages(lastSequenceNr());
166 // Delete all the akka snapshots as they will not be needed
167 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
170 onRecoveryComplete();
172 initializeBehavior();
178 protected void initializeBehavior(){
179 changeCurrentBehavior(new Follower(context));
182 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
183 reusableBehaviorStateHolder.init(getCurrentBehavior());
184 setCurrentBehavior(newBehavior);
185 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
189 public void handleCommand(Object message) {
190 if(snapshotSupport == null) {
191 snapshotSupport = new RaftActorSnapshotMessageSupport(delegatingPersistenceProvider, context,
192 currentBehavior, getRaftActorSnapshotCohort(), self());
195 boolean handled = snapshotSupport.handleSnapshotMessage(message);
200 if (message instanceof ApplyState){
201 ApplyState applyState = (ApplyState) message;
203 long elapsedTime = (System.nanoTime() - applyState.getStartTime());
204 if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
205 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
206 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
209 if(LOG.isDebugEnabled()) {
210 LOG.debug("{}: Applying state for log index {} data {}",
211 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
212 applyState.getReplicatedLogEntry().getData());
215 applyState(applyState.getClientActor(), applyState.getIdentifier(),
216 applyState.getReplicatedLogEntry().getData());
218 } else if (message instanceof ApplyJournalEntries){
219 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
220 if(LOG.isDebugEnabled()) {
221 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
224 persistence().persist(applyEntries, NoopProcedure.instance());
226 } else if (message instanceof FindLeader) {
228 new FindLeaderReply(getLeaderAddress()),
231 } else if(message instanceof GetOnDemandRaftState) {
232 onGetOnDemandRaftStats();
234 reusableBehaviorStateHolder.init(getCurrentBehavior());
236 setCurrentBehavior(currentBehavior.handleMessage(getSender(), message));
238 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
242 private void onGetOnDemandRaftStats() {
243 // Debugging message to retrieve raft stats.
245 OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
246 .commitIndex(context.getCommitIndex())
247 .currentTerm(context.getTermInformation().getCurrentTerm())
248 .inMemoryJournalDataSize(replicatedLog().dataSize())
249 .inMemoryJournalLogSize(replicatedLog().size())
250 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
251 .lastApplied(context.getLastApplied())
252 .lastIndex(replicatedLog().lastIndex())
253 .lastTerm(replicatedLog().lastTerm())
254 .leader(getLeaderId())
255 .raftState(currentBehavior.state().toString())
256 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
257 .snapshotIndex(replicatedLog().getSnapshotIndex())
258 .snapshotTerm(replicatedLog().getSnapshotTerm())
259 .votedFor(context.getTermInformation().getVotedFor())
260 .peerAddresses(ImmutableMap.copyOf(context.getPeerAddresses()));
262 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
263 if (lastLogEntry != null) {
264 builder.lastLogIndex(lastLogEntry.getIndex());
265 builder.lastLogTerm(lastLogEntry.getTerm());
268 if(getCurrentBehavior() instanceof AbstractLeader) {
269 AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
270 Collection<String> followerIds = leader.getFollowerIds();
271 List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
272 for(String id: followerIds) {
273 final FollowerLogInformation info = leader.getFollower(id);
274 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
275 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
278 builder.followerInfoList(followerInfoList);
281 sender().tell(builder.build(), self());
285 private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
286 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
288 if (oldBehavior != currentBehavior){
292 String oldBehaviorLeaderId = oldBehavior == null ? null : oldBehaviorState.getLeaderId();
293 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
295 // it can happen that the state has not changed but the leader has changed.
296 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
297 if(!Objects.equal(oldBehaviorLeaderId, currentBehavior.getLeaderId())) {
298 if(roleChangeNotifier.isPresent()) {
299 roleChangeNotifier.get().tell(new LeaderStateChanged(getId(), currentBehavior.getLeaderId()), getSelf());
302 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
305 if (roleChangeNotifier.isPresent() &&
306 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
307 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
308 currentBehavior.state().name()), getSelf());
313 * When a derived RaftActor needs to persist something it must call
320 protected void persistData(final ActorRef clientActor, final String identifier,
321 final Payload data) {
323 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
324 context.getReplicatedLog().lastIndex() + 1,
325 context.getTermInformation().getCurrentTerm(), data);
327 if(LOG.isDebugEnabled()) {
328 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
331 final RaftActorContext raftContext = getRaftActorContext();
333 replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
335 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
337 // Increment the Commit Index and the Last Applied values
338 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
339 raftContext.setLastApplied(replicatedLogEntry.getIndex());
341 // Apply the state immediately
342 applyState(clientActor, identifier, data);
344 // Send a ApplyJournalEntries message so that we write the fact that we applied
345 // the state to durable storage
346 self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
348 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
350 } else if (clientActor != null) {
351 // Send message for replication
352 currentBehavior.handleMessage(getSelf(),
353 new Replicate(clientActor, identifier, replicatedLogEntry));
359 private ReplicatedLog replicatedLog() {
360 return context.getReplicatedLog();
363 protected String getId() {
364 return context.getId();
368 void setCurrentBehavior(RaftActorBehavior behavior) {
369 currentBehavior.setDelegate(behavior);
372 protected RaftActorBehavior getCurrentBehavior() {
373 return currentBehavior.getDelegate();
377 * Derived actors can call the isLeader method to check if the current
378 * RaftActor is the Leader or not
380 * @return true it this RaftActor is a Leader false otherwise
382 protected boolean isLeader() {
383 return context.getId().equals(currentBehavior.getLeaderId());
387 * Derived actor can call getLeader if they need a reference to the Leader.
388 * This would be useful for example in forwarding a request to an actor
389 * which is the leader
391 * @return A reference to the leader if known, null otherwise
393 protected ActorSelection getLeader(){
394 String leaderAddress = getLeaderAddress();
396 if(leaderAddress == null){
400 return context.actorSelection(leaderAddress);
405 * @return the current leader's id
407 protected String getLeaderId(){
408 return currentBehavior.getLeaderId();
411 protected RaftState getRaftState() {
412 return currentBehavior.state();
415 protected ReplicatedLogEntry getLastLogEntry() {
416 return replicatedLog().last();
419 protected Long getCurrentTerm(){
420 return context.getTermInformation().getCurrentTerm();
423 protected Long getCommitIndex(){
424 return context.getCommitIndex();
427 protected Long getLastApplied(){
428 return context.getLastApplied();
431 protected RaftActorContext getRaftActorContext() {
435 protected void updateConfigParams(ConfigParams configParams) {
436 context.setConfigParams(configParams);
439 public final DataPersistenceProvider persistence() {
440 return delegatingPersistenceProvider.getDelegate();
443 public void setPersistence(DataPersistenceProvider provider) {
444 delegatingPersistenceProvider.setDelegate(provider);
447 protected void setPersistence(boolean persistent) {
449 setPersistence(new PersistentDataProvider(this));
451 setPersistence(new NonPersistentDataProvider() {
453 * The way snapshotting works is,
455 * <li> RaftActor calls createSnapshot on the Shard
456 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
457 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
458 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
459 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
460 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
464 public void saveSnapshot(Object o) {
465 // Make saving Snapshot successful
466 // Committing the snapshot here would end up calling commit in the creating state which would
467 // be a state violation. That's why now we send a message to commit the snapshot.
468 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
475 * setPeerAddress sets the address of a known peer at a later time.
477 * This is to account for situations where a we know that a peer
478 * exists but we do not know an address up-front. This may also be used in
479 * situations where a known peer starts off in a different location and we
480 * need to change it's address
482 * Note that if the peerId does not match the list of peers passed to
483 * this actor during construction an IllegalStateException will be thrown.
488 protected void setPeerAddress(String peerId, String peerAddress){
489 context.setPeerAddress(peerId, peerAddress);
493 * The applyState method will be called by the RaftActor when some data
494 * needs to be applied to the actor's state
496 * @param clientActor A reference to the client who sent this message. This
497 * is the same reference that was passed to persistData
498 * by the derived actor. clientActor may be null when
499 * the RaftActor is behaving as a follower or during
501 * @param identifier The identifier of the persisted data. This is also
502 * the same identifier that was passed to persistData by
503 * the derived actor. identifier may be null when
504 * the RaftActor is behaving as a follower or during
506 * @param data A piece of data that was persisted by the persistData call.
507 * This should NEVER be null.
509 protected abstract void applyState(ActorRef clientActor, String identifier,
513 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
516 protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
519 * This method is called when recovery is complete.
521 protected abstract void onRecoveryComplete();
524 * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
527 protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
530 * This method will be called by the RaftActor when the state of the
531 * RaftActor changes. The derived actor can then use methods like
532 * isLeader or getLeader to do something useful
534 protected abstract void onStateChanged();
537 * Notifier Actor for this RaftActor to notify when a role change happens
538 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
540 protected abstract Optional<ActorRef> getRoleChangeNotifier();
542 protected void onLeaderChanged(String oldLeader, String newLeader){};
544 private String getLeaderAddress(){
546 return getSelf().path().toString();
548 String leaderId = currentBehavior.getLeaderId();
549 if (leaderId == null) {
552 String peerAddress = context.getPeerAddress(leaderId);
553 if(LOG.isDebugEnabled()) {
554 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
555 persistenceId(), leaderId, peerAddress);
561 protected boolean hasFollowers(){
562 return getRaftActorContext().hasFollowers();
565 static class DeleteEntries implements Serializable {
566 private static final long serialVersionUID = 1L;
567 private final int fromIndex;
569 public DeleteEntries(int fromIndex) {
570 this.fromIndex = fromIndex;
573 public int getFromIndex() {
578 static class UpdateElectionTerm implements Serializable {
579 private static final long serialVersionUID = 1L;
580 private final long currentTerm;
581 private final String votedFor;
583 public UpdateElectionTerm(long currentTerm, String votedFor) {
584 this.currentTerm = currentTerm;
585 this.votedFor = votedFor;
588 public long getCurrentTerm() {
592 public String getVotedFor() {
597 private static class BehaviorStateHolder {
598 private RaftActorBehavior behavior;
599 private String leaderId;
601 void init(RaftActorBehavior behavior) {
602 this.behavior = behavior;
603 this.leaderId = behavior != null ? behavior.getLeaderId() : null;
606 RaftActorBehavior getBehavior() {
610 String getLeaderId() {