2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.cluster.raft;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.japi.Procedure;
15 import akka.persistence.SnapshotSelectionCriteria;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Objects;
18 import com.google.common.base.Optional;
19 import com.google.common.collect.Lists;
20 import java.io.Serializable;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.apache.commons.lang3.time.DurationFormatUtils;
28 import org.opendaylight.controller.cluster.DataPersistenceProvider;
29 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
30 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
31 import org.opendaylight.controller.cluster.PersistentDataProvider;
32 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
33 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
34 import org.opendaylight.controller.cluster.notifications.RoleChanged;
35 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
36 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
37 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
39 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
40 import org.opendaylight.controller.cluster.raft.behaviors.DelegatingRaftActorBehavior;
41 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
42 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
43 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
44 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
45 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
46 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
47 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
48 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * RaftActor encapsulates a state machine that needs to be kept synchronized
54 * in a cluster. It implements the RAFT algorithm as described in the paper
55 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
56 * In Search of an Understandable Consensus Algorithm</a>
58 * RaftActor has 3 states and each state has a certain behavior associated
59 * with it. A Raft actor can behave as,
62 * <li> A Follower (or) </li>
63 * <li> A Candidate </li>
67 * A RaftActor MUST be a Leader in order to accept requests from clients to
68 * change the state of it's encapsulated state machine. Once a RaftActor becomes
69 * a Leader it is also responsible for ensuring that all followers ultimately
70 * have the same log and therefore the same state machine as itself.
73 * The current behavior of a RaftActor determines how election for leadership
74 * is initiated and how peer RaftActors react to request for votes.
77 * Each RaftActor also needs to know the current election term. It uses this
78 * information for a couple of things. One is to simply figure out who it
79 * voted for in the last election. Another is to figure out if the message
80 * it received to update it's state is stale.
83 * The RaftActor uses akka-persistence to store it's replicated log.
84 * Furthermore through it's behaviors a Raft Actor determines
87 * <li> when a log entry should be persisted </li>
88 * <li> when a log entry should be applied to the state machine (and) </li>
89 * <li> when a snapshot should be saved </li>
92 public abstract class RaftActor extends AbstractUntypedPersistentActor {
94 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
96 protected final Logger LOG = LoggerFactory.getLogger(getClass());
99 * The current state determines the current behavior of a RaftActor
100 * A Raft Actor always starts off in the Follower State
102 private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
105 * This context should NOT be passed directly to any other actor it is
106 * only to be consumed by the RaftActorBehaviors
108 private final RaftActorContextImpl context;
110 private final DelegatingPersistentDataProvider delegatingPersistenceProvider = new DelegatingPersistentDataProvider(null);
112 private RaftActorRecoverySupport raftRecovery;
114 private RaftActorSnapshotMessageSupport snapshotSupport;
116 private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
118 public RaftActor(String id, Map<String, String> peerAddresses,
119 Optional<ConfigParams> configParams, short payloadVersion) {
121 context = new RaftActorContextImpl(this.getSelf(),
122 this.getContext(), id, new ElectionTermImpl(delegatingPersistenceProvider, id, LOG),
123 -1, -1, peerAddresses,
124 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
125 delegatingPersistenceProvider, LOG);
127 context.setPayloadVersion(payloadVersion);
128 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, currentBehavior));
132 public void preStart() throws Exception {
133 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
134 context.getConfigParams().getJournalRecoveryLogBatchSize());
138 snapshotSupport = newRaftActorSnapshotMessageSupport();
142 public void postStop() {
143 if(currentBehavior.getDelegate() != null) {
145 currentBehavior.close();
146 } catch (Exception e) {
147 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
155 public void handleRecover(Object message) {
156 if(raftRecovery == null) {
157 raftRecovery = newRaftActorRecoverySupport();
160 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message);
161 if(recoveryComplete) {
162 if(!persistence().isRecoveryApplicable()) {
163 // Delete all the messages from the akka journal so that we do not end up with consistency issues
164 // Note I am not using the dataPersistenceProvider and directly using the akka api here
165 deleteMessages(lastSequenceNr());
167 // Delete all the akka snapshots as they will not be needed
168 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
171 onRecoveryComplete();
173 initializeBehavior();
179 protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
180 return new RaftActorRecoverySupport(context, currentBehavior, getRaftActorRecoveryCohort());
183 protected void initializeBehavior(){
184 changeCurrentBehavior(new Follower(context));
187 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
188 reusableBehaviorStateHolder.init(getCurrentBehavior());
189 setCurrentBehavior(newBehavior);
190 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
194 public void handleCommand(Object message) {
195 if (message instanceof ApplyState){
196 ApplyState applyState = (ApplyState) message;
198 long elapsedTime = (System.nanoTime() - applyState.getStartTime());
199 if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
200 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
201 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
204 if(LOG.isDebugEnabled()) {
205 LOG.debug("{}: Applying state for log index {} data {}",
206 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
207 applyState.getReplicatedLogEntry().getData());
210 applyState(applyState.getClientActor(), applyState.getIdentifier(),
211 applyState.getReplicatedLogEntry().getData());
213 if (!hasFollowers()) {
214 // for single node, the capture should happen after the apply state
215 // as we delete messages from the persistent journal which have made it to the snapshot
216 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
217 // and recovery shows data missing
218 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
220 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
223 } else if (message instanceof ApplyJournalEntries){
224 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
225 if(LOG.isDebugEnabled()) {
226 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
229 persistence().persist(applyEntries, NoopProcedure.instance());
231 } else if (message instanceof FindLeader) {
233 new FindLeaderReply(getLeaderAddress()),
236 } else if(message instanceof GetOnDemandRaftState) {
237 onGetOnDemandRaftStats();
238 } else if(message instanceof InitiateCaptureSnapshot) {
240 } else if(!snapshotSupport.handleSnapshotMessage(message)) {
241 reusableBehaviorStateHolder.init(getCurrentBehavior());
243 setCurrentBehavior(currentBehavior.handleMessage(getSender(), message));
245 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
249 protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
250 return new RaftActorSnapshotMessageSupport(context, currentBehavior,
251 getRaftActorSnapshotCohort());
254 private void onGetOnDemandRaftStats() {
255 // Debugging message to retrieve raft stats.
257 OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
258 .commitIndex(context.getCommitIndex())
259 .currentTerm(context.getTermInformation().getCurrentTerm())
260 .inMemoryJournalDataSize(replicatedLog().dataSize())
261 .inMemoryJournalLogSize(replicatedLog().size())
262 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
263 .lastApplied(context.getLastApplied())
264 .lastIndex(replicatedLog().lastIndex())
265 .lastTerm(replicatedLog().lastTerm())
266 .leader(getLeaderId())
267 .raftState(currentBehavior.state().toString())
268 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
269 .snapshotIndex(replicatedLog().getSnapshotIndex())
270 .snapshotTerm(replicatedLog().getSnapshotTerm())
271 .votedFor(context.getTermInformation().getVotedFor())
272 .peerAddresses(new HashMap<>(context.getPeerAddresses()));
274 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
275 if (lastLogEntry != null) {
276 builder.lastLogIndex(lastLogEntry.getIndex());
277 builder.lastLogTerm(lastLogEntry.getTerm());
280 if(getCurrentBehavior() instanceof AbstractLeader) {
281 AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
282 Collection<String> followerIds = leader.getFollowerIds();
283 List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
284 for(String id: followerIds) {
285 final FollowerLogInformation info = leader.getFollower(id);
286 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
287 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
290 builder.followerInfoList(followerInfoList);
293 sender().tell(builder.build(), self());
297 private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
298 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
300 if (oldBehavior != currentBehavior){
304 String oldBehaviorLeaderId = oldBehavior == null ? null : oldBehaviorState.getLeaderId();
305 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
307 // it can happen that the state has not changed but the leader has changed.
308 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
309 if(!Objects.equal(oldBehaviorLeaderId, currentBehavior.getLeaderId()) ||
310 oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
311 if(roleChangeNotifier.isPresent()) {
312 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
313 currentBehavior.getLeaderPayloadVersion()), getSelf());
316 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
319 if (roleChangeNotifier.isPresent() &&
320 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
321 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
322 currentBehavior.state().name()), getSelf());
326 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
327 return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
331 public long snapshotSequenceNr() {
332 // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
333 // so that we can delete the persistent journal based on the saved sequence-number
334 // However , when akka replays the journal during recovery, it replays it from the sequence number when the snapshot
335 // was saved and not the number we saved.
336 // We would want to override it , by asking akka to use the last-sequence number known to us.
337 return context.getSnapshotManager().getLastSequenceNumber();
341 * When a derived RaftActor needs to persist something it must call
348 protected void persistData(final ActorRef clientActor, final String identifier,
349 final Payload data) {
351 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
352 context.getReplicatedLog().lastIndex() + 1,
353 context.getTermInformation().getCurrentTerm(), data);
355 if(LOG.isDebugEnabled()) {
356 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
359 final RaftActorContext raftContext = getRaftActorContext();
361 replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
363 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
364 if (!hasFollowers()){
365 // Increment the Commit Index and the Last Applied values
366 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
367 raftContext.setLastApplied(replicatedLogEntry.getIndex());
369 // Apply the state immediately.
370 self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry), self());
372 // Send a ApplyJournalEntries message so that we write the fact that we applied
373 // the state to durable storage
374 self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
376 } else if (clientActor != null) {
377 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
379 // Send message for replication
380 currentBehavior.handleMessage(getSelf(),
381 new Replicate(clientActor, identifier, replicatedLogEntry));
387 private ReplicatedLog replicatedLog() {
388 return context.getReplicatedLog();
391 protected String getId() {
392 return context.getId();
396 void setCurrentBehavior(RaftActorBehavior behavior) {
397 currentBehavior.setDelegate(behavior);
400 protected RaftActorBehavior getCurrentBehavior() {
401 return currentBehavior.getDelegate();
405 * Derived actors can call the isLeader method to check if the current
406 * RaftActor is the Leader or not
408 * @return true it this RaftActor is a Leader false otherwise
410 protected boolean isLeader() {
411 return context.getId().equals(currentBehavior.getLeaderId());
415 * Derived actor can call getLeader if they need a reference to the Leader.
416 * This would be useful for example in forwarding a request to an actor
417 * which is the leader
419 * @return A reference to the leader if known, null otherwise
421 protected ActorSelection getLeader(){
422 String leaderAddress = getLeaderAddress();
424 if(leaderAddress == null){
428 return context.actorSelection(leaderAddress);
433 * @return the current leader's id
435 protected String getLeaderId(){
436 return currentBehavior.getLeaderId();
439 protected RaftState getRaftState() {
440 return currentBehavior.state();
443 protected ReplicatedLogEntry getLastLogEntry() {
444 return replicatedLog().last();
447 protected Long getCurrentTerm(){
448 return context.getTermInformation().getCurrentTerm();
451 protected Long getCommitIndex(){
452 return context.getCommitIndex();
455 protected Long getLastApplied(){
456 return context.getLastApplied();
459 protected RaftActorContext getRaftActorContext() {
463 protected void updateConfigParams(ConfigParams configParams) {
464 context.setConfigParams(configParams);
467 public final DataPersistenceProvider persistence() {
468 return delegatingPersistenceProvider.getDelegate();
471 public void setPersistence(DataPersistenceProvider provider) {
472 delegatingPersistenceProvider.setDelegate(provider);
475 protected void setPersistence(boolean persistent) {
477 setPersistence(new PersistentDataProvider(this));
479 setPersistence(new NonPersistentDataProvider() {
481 * The way snapshotting works is,
483 * <li> RaftActor calls createSnapshot on the Shard
484 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
485 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
486 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
487 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
488 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
492 public void saveSnapshot(Object o) {
493 // Make saving Snapshot successful
494 // Committing the snapshot here would end up calling commit in the creating state which would
495 // be a state violation. That's why now we send a message to commit the snapshot.
496 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
503 * setPeerAddress sets the address of a known peer at a later time.
505 * This is to account for situations where a we know that a peer
506 * exists but we do not know an address up-front. This may also be used in
507 * situations where a known peer starts off in a different location and we
508 * need to change it's address
510 * Note that if the peerId does not match the list of peers passed to
511 * this actor during construction an IllegalStateException will be thrown.
516 protected void setPeerAddress(String peerId, String peerAddress){
517 context.setPeerAddress(peerId, peerAddress);
521 * The applyState method will be called by the RaftActor when some data
522 * needs to be applied to the actor's state
524 * @param clientActor A reference to the client who sent this message. This
525 * is the same reference that was passed to persistData
526 * by the derived actor. clientActor may be null when
527 * the RaftActor is behaving as a follower or during
529 * @param identifier The identifier of the persisted data. This is also
530 * the same identifier that was passed to persistData by
531 * the derived actor. identifier may be null when
532 * the RaftActor is behaving as a follower or during
534 * @param data A piece of data that was persisted by the persistData call.
535 * This should NEVER be null.
537 protected abstract void applyState(ActorRef clientActor, String identifier,
541 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
544 protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
547 * This method is called when recovery is complete.
549 protected abstract void onRecoveryComplete();
552 * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
555 protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
558 * This method will be called by the RaftActor when the state of the
559 * RaftActor changes. The derived actor can then use methods like
560 * isLeader or getLeader to do something useful
562 protected abstract void onStateChanged();
565 * Notifier Actor for this RaftActor to notify when a role change happens
566 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
568 protected abstract Optional<ActorRef> getRoleChangeNotifier();
570 protected void onLeaderChanged(String oldLeader, String newLeader){};
572 private String getLeaderAddress(){
574 return getSelf().path().toString();
576 String leaderId = currentBehavior.getLeaderId();
577 if (leaderId == null) {
580 String peerAddress = context.getPeerAddress(leaderId);
581 if(LOG.isDebugEnabled()) {
582 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
583 persistenceId(), leaderId, peerAddress);
589 protected boolean hasFollowers(){
590 return getRaftActorContext().hasFollowers();
593 private void captureSnapshot() {
594 SnapshotManager snapshotManager = context.getSnapshotManager();
596 if(!snapshotManager.isCapturing()) {
597 LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
598 replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
600 snapshotManager.capture(replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
605 * @deprecated Deprecated in favor of {@link org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries}
606 * whose type for fromIndex is long instead of int. This class was kept for backwards
607 * compatibility with Helium.
609 // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
610 @SuppressWarnings("serial")
612 static class DeleteEntries implements Serializable {
613 private final int fromIndex;
615 public DeleteEntries(int fromIndex) {
616 this.fromIndex = fromIndex;
619 public int getFromIndex() {
625 * @deprecated Deprecated in favor of non-inner class {@link org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm}
626 * which has serialVersionUID set. This class was kept for backwards compatibility with Helium.
628 // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
629 @SuppressWarnings("serial")
631 static class UpdateElectionTerm implements Serializable {
632 private final long currentTerm;
633 private final String votedFor;
635 public UpdateElectionTerm(long currentTerm, String votedFor) {
636 this.currentTerm = currentTerm;
637 this.votedFor = votedFor;
640 public long getCurrentTerm() {
644 public String getVotedFor() {
649 private static class BehaviorStateHolder {
650 private RaftActorBehavior behavior;
651 private String leaderId;
652 private short leaderPayloadVersion;
654 void init(RaftActorBehavior behavior) {
655 this.behavior = behavior;
656 this.leaderId = behavior != null ? behavior.getLeaderId() : null;
657 this.leaderPayloadVersion = behavior != null ? behavior.getLeaderPayloadVersion() : -1;
660 RaftActorBehavior getBehavior() {
664 String getLeaderId() {
668 short getLeaderPayloadVersion() {
669 return leaderPayloadVersion;