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.ImmutableMap;
20 import com.google.common.collect.Lists;
21 import java.io.Serializable;
22 import java.util.Collection;
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.Replicate;
38 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
39 import org.opendaylight.controller.cluster.raft.behaviors.DelegatingRaftActorBehavior;
40 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
41 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
42 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
43 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
44 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
45 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
46 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
47 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * RaftActor encapsulates a state machine that needs to be kept synchronized
53 * in a cluster. It implements the RAFT algorithm as described in the paper
54 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
55 * In Search of an Understandable Consensus Algorithm</a>
57 * RaftActor has 3 states and each state has a certain behavior associated
58 * with it. A Raft actor can behave as,
61 * <li> A Follower (or) </li>
62 * <li> A Candidate </li>
66 * A RaftActor MUST be a Leader in order to accept requests from clients to
67 * change the state of it's encapsulated state machine. Once a RaftActor becomes
68 * a Leader it is also responsible for ensuring that all followers ultimately
69 * have the same log and therefore the same state machine as itself.
72 * The current behavior of a RaftActor determines how election for leadership
73 * is initiated and how peer RaftActors react to request for votes.
76 * Each RaftActor also needs to know the current election term. It uses this
77 * information for a couple of things. One is to simply figure out who it
78 * voted for in the last election. Another is to figure out if the message
79 * it received to update it's state is stale.
82 * The RaftActor uses akka-persistence to store it's replicated log.
83 * Furthermore through it's behaviors a Raft Actor determines
86 * <li> when a log entry should be persisted </li>
87 * <li> when a log entry should be applied to the state machine (and) </li>
88 * <li> when a snapshot should be saved </li>
91 public abstract class RaftActor extends AbstractUntypedPersistentActor {
93 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
95 protected final Logger LOG = LoggerFactory.getLogger(getClass());
98 * The current state determines the current behavior of a RaftActor
99 * A Raft Actor always starts off in the Follower State
101 private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
104 * This context should NOT be passed directly to any other actor it is
105 * only to be consumed by the RaftActorBehaviors
107 private final RaftActorContextImpl context;
109 private final DelegatingPersistentDataProvider delegatingPersistenceProvider = new DelegatingPersistentDataProvider(null);
111 private RaftActorRecoverySupport raftRecovery;
113 private RaftActorSnapshotMessageSupport snapshotSupport;
115 private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
117 public RaftActor(String id, Map<String, String> peerAddresses) {
118 this(id, peerAddresses, Optional.<ConfigParams>absent());
121 public RaftActor(String id, Map<String, String> peerAddresses,
122 Optional<ConfigParams> configParams) {
124 context = new RaftActorContextImpl(this.getSelf(),
125 this.getContext(), id, new ElectionTermImpl(delegatingPersistenceProvider, id, LOG),
126 -1, -1, peerAddresses,
127 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()), LOG);
129 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, delegatingPersistenceProvider, currentBehavior));
133 public void preStart() throws Exception {
134 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
135 context.getConfigParams().getJournalRecoveryLogBatchSize());
141 public void postStop() {
142 if(currentBehavior.getDelegate() != null) {
144 currentBehavior.close();
145 } catch (Exception e) {
146 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
154 public void handleRecover(Object message) {
155 if(raftRecovery == null) {
156 raftRecovery = newRaftActorRecoverySupport();
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 RaftActorRecoverySupport newRaftActorRecoverySupport() {
179 return new RaftActorRecoverySupport(delegatingPersistenceProvider, context, currentBehavior,
180 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(snapshotSupport == null) {
196 snapshotSupport = newRaftActorSnapshotMessageSupport();
199 boolean handled = snapshotSupport.handleSnapshotMessage(message);
204 if (message instanceof ApplyState){
205 ApplyState applyState = (ApplyState) message;
207 long elapsedTime = (System.nanoTime() - applyState.getStartTime());
208 if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
209 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
210 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
213 if(LOG.isDebugEnabled()) {
214 LOG.debug("{}: Applying state for log index {} data {}",
215 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
216 applyState.getReplicatedLogEntry().getData());
219 applyState(applyState.getClientActor(), applyState.getIdentifier(),
220 applyState.getReplicatedLogEntry().getData());
222 } else if (message instanceof ApplyJournalEntries){
223 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
224 if(LOG.isDebugEnabled()) {
225 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
228 persistence().persist(applyEntries, NoopProcedure.instance());
230 } else if (message instanceof FindLeader) {
232 new FindLeaderReply(getLeaderAddress()),
235 } else if(message instanceof GetOnDemandRaftState) {
236 onGetOnDemandRaftStats();
238 reusableBehaviorStateHolder.init(getCurrentBehavior());
240 setCurrentBehavior(currentBehavior.handleMessage(getSender(), message));
242 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
246 protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
247 return new RaftActorSnapshotMessageSupport(delegatingPersistenceProvider, context,
248 currentBehavior, getRaftActorSnapshotCohort());
251 private void onGetOnDemandRaftStats() {
252 // Debugging message to retrieve raft stats.
254 OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
255 .commitIndex(context.getCommitIndex())
256 .currentTerm(context.getTermInformation().getCurrentTerm())
257 .inMemoryJournalDataSize(replicatedLog().dataSize())
258 .inMemoryJournalLogSize(replicatedLog().size())
259 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
260 .lastApplied(context.getLastApplied())
261 .lastIndex(replicatedLog().lastIndex())
262 .lastTerm(replicatedLog().lastTerm())
263 .leader(getLeaderId())
264 .raftState(currentBehavior.state().toString())
265 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
266 .snapshotIndex(replicatedLog().getSnapshotIndex())
267 .snapshotTerm(replicatedLog().getSnapshotTerm())
268 .votedFor(context.getTermInformation().getVotedFor())
269 .peerAddresses(ImmutableMap.copyOf(context.getPeerAddresses()));
271 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
272 if (lastLogEntry != null) {
273 builder.lastLogIndex(lastLogEntry.getIndex());
274 builder.lastLogTerm(lastLogEntry.getTerm());
277 if(getCurrentBehavior() instanceof AbstractLeader) {
278 AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
279 Collection<String> followerIds = leader.getFollowerIds();
280 List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
281 for(String id: followerIds) {
282 final FollowerLogInformation info = leader.getFollower(id);
283 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
284 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
287 builder.followerInfoList(followerInfoList);
290 sender().tell(builder.build(), self());
294 private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
295 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
297 if (oldBehavior != currentBehavior){
301 String oldBehaviorLeaderId = oldBehavior == null ? null : oldBehaviorState.getLeaderId();
302 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
304 // it can happen that the state has not changed but the leader has changed.
305 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
306 if(!Objects.equal(oldBehaviorLeaderId, currentBehavior.getLeaderId())) {
307 if(roleChangeNotifier.isPresent()) {
308 roleChangeNotifier.get().tell(new LeaderStateChanged(getId(), currentBehavior.getLeaderId()), getSelf());
311 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
314 if (roleChangeNotifier.isPresent() &&
315 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
316 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
317 currentBehavior.state().name()), getSelf());
322 * When a derived RaftActor needs to persist something it must call
329 protected void persistData(final ActorRef clientActor, final String identifier,
330 final Payload data) {
332 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
333 context.getReplicatedLog().lastIndex() + 1,
334 context.getTermInformation().getCurrentTerm(), data);
336 if(LOG.isDebugEnabled()) {
337 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
340 final RaftActorContext raftContext = getRaftActorContext();
342 replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
344 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
346 // Increment the Commit Index and the Last Applied values
347 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
348 raftContext.setLastApplied(replicatedLogEntry.getIndex());
350 // Apply the state immediately
351 applyState(clientActor, identifier, data);
353 // Send a ApplyJournalEntries message so that we write the fact that we applied
354 // the state to durable storage
355 self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
357 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
359 } else if (clientActor != null) {
360 // Send message for replication
361 currentBehavior.handleMessage(getSelf(),
362 new Replicate(clientActor, identifier, replicatedLogEntry));
368 private ReplicatedLog replicatedLog() {
369 return context.getReplicatedLog();
372 protected String getId() {
373 return context.getId();
377 void setCurrentBehavior(RaftActorBehavior behavior) {
378 currentBehavior.setDelegate(behavior);
381 protected RaftActorBehavior getCurrentBehavior() {
382 return currentBehavior.getDelegate();
386 * Derived actors can call the isLeader method to check if the current
387 * RaftActor is the Leader or not
389 * @return true it this RaftActor is a Leader false otherwise
391 protected boolean isLeader() {
392 return context.getId().equals(currentBehavior.getLeaderId());
396 * Derived actor can call getLeader if they need a reference to the Leader.
397 * This would be useful for example in forwarding a request to an actor
398 * which is the leader
400 * @return A reference to the leader if known, null otherwise
402 protected ActorSelection getLeader(){
403 String leaderAddress = getLeaderAddress();
405 if(leaderAddress == null){
409 return context.actorSelection(leaderAddress);
414 * @return the current leader's id
416 protected String getLeaderId(){
417 return currentBehavior.getLeaderId();
420 protected RaftState getRaftState() {
421 return currentBehavior.state();
424 protected ReplicatedLogEntry getLastLogEntry() {
425 return replicatedLog().last();
428 protected Long getCurrentTerm(){
429 return context.getTermInformation().getCurrentTerm();
432 protected Long getCommitIndex(){
433 return context.getCommitIndex();
436 protected Long getLastApplied(){
437 return context.getLastApplied();
440 protected RaftActorContext getRaftActorContext() {
444 protected void updateConfigParams(ConfigParams configParams) {
445 context.setConfigParams(configParams);
448 public final DataPersistenceProvider persistence() {
449 return delegatingPersistenceProvider.getDelegate();
452 public void setPersistence(DataPersistenceProvider provider) {
453 delegatingPersistenceProvider.setDelegate(provider);
456 protected void setPersistence(boolean persistent) {
458 setPersistence(new PersistentDataProvider(this));
460 setPersistence(new NonPersistentDataProvider() {
462 * The way snapshotting works is,
464 * <li> RaftActor calls createSnapshot on the Shard
465 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
466 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
467 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
468 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
469 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
473 public void saveSnapshot(Object o) {
474 // Make saving Snapshot successful
475 // Committing the snapshot here would end up calling commit in the creating state which would
476 // be a state violation. That's why now we send a message to commit the snapshot.
477 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
484 * setPeerAddress sets the address of a known peer at a later time.
486 * This is to account for situations where a we know that a peer
487 * exists but we do not know an address up-front. This may also be used in
488 * situations where a known peer starts off in a different location and we
489 * need to change it's address
491 * Note that if the peerId does not match the list of peers passed to
492 * this actor during construction an IllegalStateException will be thrown.
497 protected void setPeerAddress(String peerId, String peerAddress){
498 context.setPeerAddress(peerId, peerAddress);
502 * The applyState method will be called by the RaftActor when some data
503 * needs to be applied to the actor's state
505 * @param clientActor A reference to the client who sent this message. This
506 * is the same reference that was passed to persistData
507 * by the derived actor. clientActor may be null when
508 * the RaftActor is behaving as a follower or during
510 * @param identifier The identifier of the persisted data. This is also
511 * the same identifier that was passed to persistData by
512 * the derived actor. identifier may be null when
513 * the RaftActor is behaving as a follower or during
515 * @param data A piece of data that was persisted by the persistData call.
516 * This should NEVER be null.
518 protected abstract void applyState(ActorRef clientActor, String identifier,
522 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
525 protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
528 * This method is called when recovery is complete.
530 protected abstract void onRecoveryComplete();
533 * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
536 protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
539 * This method will be called by the RaftActor when the state of the
540 * RaftActor changes. The derived actor can then use methods like
541 * isLeader or getLeader to do something useful
543 protected abstract void onStateChanged();
546 * Notifier Actor for this RaftActor to notify when a role change happens
547 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
549 protected abstract Optional<ActorRef> getRoleChangeNotifier();
551 protected void onLeaderChanged(String oldLeader, String newLeader){};
553 private String getLeaderAddress(){
555 return getSelf().path().toString();
557 String leaderId = currentBehavior.getLeaderId();
558 if (leaderId == null) {
561 String peerAddress = context.getPeerAddress(leaderId);
562 if(LOG.isDebugEnabled()) {
563 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
564 persistenceId(), leaderId, peerAddress);
570 protected boolean hasFollowers(){
571 return getRaftActorContext().hasFollowers();
575 * @deprecated Deprecated in favor of {@link org.opendaylight.controller.cluster.raft.base.messages.DeleteEntriesTest}
576 * whose type for fromIndex is long instead of int. This class was kept for backwards
577 * compatibility with Helium.
580 static class DeleteEntries implements Serializable {
581 private static final long serialVersionUID = 1L;
582 private final int fromIndex;
584 public DeleteEntries(int fromIndex) {
585 this.fromIndex = fromIndex;
588 public int getFromIndex() {
593 static class UpdateElectionTerm implements Serializable {
594 private static final long serialVersionUID = 1L;
595 private final long currentTerm;
596 private final String votedFor;
598 public UpdateElectionTerm(long currentTerm, String votedFor) {
599 this.currentTerm = currentTerm;
600 this.votedFor = votedFor;
603 public long getCurrentTerm() {
607 public String getVotedFor() {
612 private static class BehaviorStateHolder {
613 private RaftActorBehavior behavior;
614 private String leaderId;
616 void init(RaftActorBehavior behavior) {
617 this.behavior = behavior;
618 this.leaderId = behavior != null ? behavior.getLeaderId() : null;
621 RaftActorBehavior getBehavior() {
625 String getLeaderId() {