Add unit tests for RaftActorRecoverySupport
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActor.java
1 /*
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.
4  *
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
8  */
9
10 package org.opendaylight.controller.cluster.raft;
11
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;
24 import java.util.Map;
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;
50
51 /**
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>
56  * <p/>
57  * RaftActor has 3 states and each state has a certain behavior associated
58  * with it. A Raft actor can behave as,
59  * <ul>
60  * <li> A Leader </li>
61  * <li> A Follower (or) </li>
62  * <li> A Candidate </li>
63  * </ul>
64  * <p/>
65  * <p/>
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.
70  * <p/>
71  * <p/>
72  * The current behavior of a RaftActor determines how election for leadership
73  * is initiated and how peer RaftActors react to request for votes.
74  * <p/>
75  * <p/>
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.
80  * <p/>
81  * <p/>
82  * The RaftActor uses akka-persistence to store it's replicated log.
83  * Furthermore through it's behaviors a Raft Actor determines
84  * <p/>
85  * <ul>
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>
89  * </ul>
90  */
91 public abstract class RaftActor extends AbstractUntypedPersistentActor {
92
93     private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
94
95     protected final Logger LOG = LoggerFactory.getLogger(getClass());
96
97     /**
98      * The current state determines the current behavior of a RaftActor
99      * A Raft Actor always starts off in the Follower State
100      */
101     private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
102
103     /**
104      * This context should NOT be passed directly to any other actor it is
105      * only to be consumed by the RaftActorBehaviors
106      */
107     private final RaftActorContextImpl context;
108
109     private final DelegatingPersistentDataProvider delegatingPersistenceProvider = new DelegatingPersistentDataProvider(null);
110
111     private RaftActorRecoverySupport raftRecovery;
112
113     private RaftActorSnapshotMessageSupport snapshotSupport;
114
115     private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
116
117     public RaftActor(String id, Map<String, String> peerAddresses) {
118         this(id, peerAddresses, Optional.<ConfigParams>absent());
119     }
120
121     public RaftActor(String id, Map<String, String> peerAddresses,
122          Optional<ConfigParams> configParams) {
123
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);
128
129         context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, delegatingPersistenceProvider, currentBehavior));
130     }
131
132     @Override
133     public void preStart() throws Exception {
134         LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
135                 context.getConfigParams().getJournalRecoveryLogBatchSize());
136
137         super.preStart();
138     }
139
140     @Override
141     public void postStop() {
142         if(currentBehavior.getDelegate() != null) {
143             try {
144                 currentBehavior.close();
145             } catch (Exception e) {
146                 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
147             }
148         }
149
150         super.postStop();
151     }
152
153     @Override
154     public void handleRecover(Object message) {
155         if(raftRecovery == null) {
156             raftRecovery = newRaftActorRecoverySupport();
157         }
158
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());
165
166                 // Delete all the akka snapshots as they will not be needed
167                 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
168             }
169
170             onRecoveryComplete();
171
172             initializeBehavior();
173
174             raftRecovery = null;
175         }
176     }
177
178     protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
179         return new RaftActorRecoverySupport(delegatingPersistenceProvider, context, currentBehavior,
180                 getRaftActorRecoveryCohort());
181     }
182
183     protected void initializeBehavior(){
184         changeCurrentBehavior(new Follower(context));
185     }
186
187     protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
188         reusableBehaviorStateHolder.init(getCurrentBehavior());
189         setCurrentBehavior(newBehavior);
190         handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
191     }
192
193     @Override
194     public void handleCommand(Object message) {
195         if(snapshotSupport == null) {
196             snapshotSupport = new RaftActorSnapshotMessageSupport(delegatingPersistenceProvider, context,
197                     currentBehavior, getRaftActorSnapshotCohort(), self());
198         }
199
200         boolean handled = snapshotSupport.handleSnapshotMessage(message);
201         if(handled) {
202             return;
203         }
204
205         if (message instanceof ApplyState){
206             ApplyState applyState = (ApplyState) message;
207
208             long elapsedTime = (System.nanoTime() - applyState.getStartTime());
209             if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
210                 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
211                         TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
212             }
213
214             if(LOG.isDebugEnabled()) {
215                 LOG.debug("{}: Applying state for log index {} data {}",
216                     persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
217                     applyState.getReplicatedLogEntry().getData());
218             }
219
220             applyState(applyState.getClientActor(), applyState.getIdentifier(),
221                 applyState.getReplicatedLogEntry().getData());
222
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());
227             }
228
229             persistence().persist(applyEntries, NoopProcedure.instance());
230
231         } else if (message instanceof FindLeader) {
232             getSender().tell(
233                 new FindLeaderReply(getLeaderAddress()),
234                 getSelf()
235             );
236         } else if(message instanceof GetOnDemandRaftState) {
237             onGetOnDemandRaftStats();
238         } else {
239             reusableBehaviorStateHolder.init(getCurrentBehavior());
240
241             setCurrentBehavior(currentBehavior.handleMessage(getSender(), message));
242
243             handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
244         }
245     }
246
247     private void onGetOnDemandRaftStats() {
248         // Debugging message to retrieve raft stats.
249
250         OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
251                 .commitIndex(context.getCommitIndex())
252                 .currentTerm(context.getTermInformation().getCurrentTerm())
253                 .inMemoryJournalDataSize(replicatedLog().dataSize())
254                 .inMemoryJournalLogSize(replicatedLog().size())
255                 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
256                 .lastApplied(context.getLastApplied())
257                 .lastIndex(replicatedLog().lastIndex())
258                 .lastTerm(replicatedLog().lastTerm())
259                 .leader(getLeaderId())
260                 .raftState(currentBehavior.state().toString())
261                 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
262                 .snapshotIndex(replicatedLog().getSnapshotIndex())
263                 .snapshotTerm(replicatedLog().getSnapshotTerm())
264                 .votedFor(context.getTermInformation().getVotedFor())
265                 .peerAddresses(ImmutableMap.copyOf(context.getPeerAddresses()));
266
267         ReplicatedLogEntry lastLogEntry = getLastLogEntry();
268         if (lastLogEntry != null) {
269             builder.lastLogIndex(lastLogEntry.getIndex());
270             builder.lastLogTerm(lastLogEntry.getTerm());
271         }
272
273         if(getCurrentBehavior() instanceof AbstractLeader) {
274             AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
275             Collection<String> followerIds = leader.getFollowerIds();
276             List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
277             for(String id: followerIds) {
278                 final FollowerLogInformation info = leader.getFollower(id);
279                 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
280                         info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
281             }
282
283             builder.followerInfoList(followerInfoList);
284         }
285
286         sender().tell(builder.build(), self());
287
288     }
289
290     private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
291         RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
292
293         if (oldBehavior != currentBehavior){
294             onStateChanged();
295         }
296
297         String oldBehaviorLeaderId = oldBehavior == null ? null : oldBehaviorState.getLeaderId();
298         String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
299
300         // it can happen that the state has not changed but the leader has changed.
301         Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
302         if(!Objects.equal(oldBehaviorLeaderId, currentBehavior.getLeaderId())) {
303             if(roleChangeNotifier.isPresent()) {
304                 roleChangeNotifier.get().tell(new LeaderStateChanged(getId(), currentBehavior.getLeaderId()), getSelf());
305             }
306
307             onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
308         }
309
310         if (roleChangeNotifier.isPresent() &&
311                 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
312             roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
313                     currentBehavior.state().name()), getSelf());
314         }
315     }
316
317     /**
318      * When a derived RaftActor needs to persist something it must call
319      * persistData.
320      *
321      * @param clientActor
322      * @param identifier
323      * @param data
324      */
325     protected void persistData(final ActorRef clientActor, final String identifier,
326         final Payload data) {
327
328         ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
329             context.getReplicatedLog().lastIndex() + 1,
330             context.getTermInformation().getCurrentTerm(), data);
331
332         if(LOG.isDebugEnabled()) {
333             LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
334         }
335
336         final RaftActorContext raftContext = getRaftActorContext();
337
338         replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
339             @Override
340             public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
341                 if(!hasFollowers()){
342                     // Increment the Commit Index and the Last Applied values
343                     raftContext.setCommitIndex(replicatedLogEntry.getIndex());
344                     raftContext.setLastApplied(replicatedLogEntry.getIndex());
345
346                     // Apply the state immediately
347                     applyState(clientActor, identifier, data);
348
349                     // Send a ApplyJournalEntries message so that we write the fact that we applied
350                     // the state to durable storage
351                     self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
352
353                     context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
354
355                 } else if (clientActor != null) {
356                     // Send message for replication
357                     currentBehavior.handleMessage(getSelf(),
358                             new Replicate(clientActor, identifier, replicatedLogEntry));
359                 }
360             }
361         });
362     }
363
364     private ReplicatedLog replicatedLog() {
365         return context.getReplicatedLog();
366     }
367
368     protected String getId() {
369         return context.getId();
370     }
371
372     @VisibleForTesting
373     void setCurrentBehavior(RaftActorBehavior behavior) {
374         currentBehavior.setDelegate(behavior);
375     }
376
377     protected RaftActorBehavior getCurrentBehavior() {
378         return currentBehavior.getDelegate();
379     }
380
381     /**
382      * Derived actors can call the isLeader method to check if the current
383      * RaftActor is the Leader or not
384      *
385      * @return true it this RaftActor is a Leader false otherwise
386      */
387     protected boolean isLeader() {
388         return context.getId().equals(currentBehavior.getLeaderId());
389     }
390
391     /**
392      * Derived actor can call getLeader if they need a reference to the Leader.
393      * This would be useful for example in forwarding a request to an actor
394      * which is the leader
395      *
396      * @return A reference to the leader if known, null otherwise
397      */
398     protected ActorSelection getLeader(){
399         String leaderAddress = getLeaderAddress();
400
401         if(leaderAddress == null){
402             return null;
403         }
404
405         return context.actorSelection(leaderAddress);
406     }
407
408     /**
409      *
410      * @return the current leader's id
411      */
412     protected String getLeaderId(){
413         return currentBehavior.getLeaderId();
414     }
415
416     protected RaftState getRaftState() {
417         return currentBehavior.state();
418     }
419
420     protected ReplicatedLogEntry getLastLogEntry() {
421         return replicatedLog().last();
422     }
423
424     protected Long getCurrentTerm(){
425         return context.getTermInformation().getCurrentTerm();
426     }
427
428     protected Long getCommitIndex(){
429         return context.getCommitIndex();
430     }
431
432     protected Long getLastApplied(){
433         return context.getLastApplied();
434     }
435
436     protected RaftActorContext getRaftActorContext() {
437         return context;
438     }
439
440     protected void updateConfigParams(ConfigParams configParams) {
441         context.setConfigParams(configParams);
442     }
443
444     public final DataPersistenceProvider persistence() {
445         return delegatingPersistenceProvider.getDelegate();
446     }
447
448     public void setPersistence(DataPersistenceProvider provider) {
449         delegatingPersistenceProvider.setDelegate(provider);
450     }
451
452     protected void setPersistence(boolean persistent) {
453         if(persistent) {
454             setPersistence(new PersistentDataProvider(this));
455         } else {
456             setPersistence(new NonPersistentDataProvider() {
457                 /**
458                  * The way snapshotting works is,
459                  * <ol>
460                  * <li> RaftActor calls createSnapshot on the Shard
461                  * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
462                  * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
463                  * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
464                  * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
465                  * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
466                  * </ol>
467                  */
468                 @Override
469                 public void saveSnapshot(Object o) {
470                     // Make saving Snapshot successful
471                     // Committing the snapshot here would end up calling commit in the creating state which would
472                     // be a state violation. That's why now we send a message to commit the snapshot.
473                     self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
474                 }
475             });
476         }
477     }
478
479     /**
480      * setPeerAddress sets the address of a known peer at a later time.
481      * <p>
482      * This is to account for situations where a we know that a peer
483      * exists but we do not know an address up-front. This may also be used in
484      * situations where a known peer starts off in a different location and we
485      * need to change it's address
486      * <p>
487      * Note that if the peerId does not match the list of peers passed to
488      * this actor during construction an IllegalStateException will be thrown.
489      *
490      * @param peerId
491      * @param peerAddress
492      */
493     protected void setPeerAddress(String peerId, String peerAddress){
494         context.setPeerAddress(peerId, peerAddress);
495     }
496
497     /**
498      * The applyState method will be called by the RaftActor when some data
499      * needs to be applied to the actor's state
500      *
501      * @param clientActor A reference to the client who sent this message. This
502      *                    is the same reference that was passed to persistData
503      *                    by the derived actor. clientActor may be null when
504      *                    the RaftActor is behaving as a follower or during
505      *                    recovery.
506      * @param identifier  The identifier of the persisted data. This is also
507      *                    the same identifier that was passed to persistData by
508      *                    the derived actor. identifier may be null when
509      *                    the RaftActor is behaving as a follower or during
510      *                    recovery
511      * @param data        A piece of data that was persisted by the persistData call.
512      *                    This should NEVER be null.
513      */
514     protected abstract void applyState(ActorRef clientActor, String identifier,
515         Object data);
516
517     /**
518      * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
519      */
520     @Nonnull
521     protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
522
523     /**
524      * This method is called when recovery is complete.
525      */
526     protected abstract void onRecoveryComplete();
527
528     /**
529      * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
530      */
531     @Nonnull
532     protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
533
534     /**
535      * This method will be called by the RaftActor when the state of the
536      * RaftActor changes. The derived actor can then use methods like
537      * isLeader or getLeader to do something useful
538      */
539     protected abstract void onStateChanged();
540
541     /**
542      * Notifier Actor for this RaftActor to notify when a role change happens
543      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
544      */
545     protected abstract Optional<ActorRef> getRoleChangeNotifier();
546
547     protected void onLeaderChanged(String oldLeader, String newLeader){};
548
549     private String getLeaderAddress(){
550         if(isLeader()){
551             return getSelf().path().toString();
552         }
553         String leaderId = currentBehavior.getLeaderId();
554         if (leaderId == null) {
555             return null;
556         }
557         String peerAddress = context.getPeerAddress(leaderId);
558         if(LOG.isDebugEnabled()) {
559             LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
560                     persistenceId(), leaderId, peerAddress);
561         }
562
563         return peerAddress;
564     }
565
566     protected boolean hasFollowers(){
567         return getRaftActorContext().hasFollowers();
568     }
569
570     static class DeleteEntries implements Serializable {
571         private static final long serialVersionUID = 1L;
572         private final int fromIndex;
573
574         public DeleteEntries(int fromIndex) {
575             this.fromIndex = fromIndex;
576         }
577
578         public int getFromIndex() {
579             return fromIndex;
580         }
581     }
582
583     static class UpdateElectionTerm implements Serializable {
584         private static final long serialVersionUID = 1L;
585         private final long currentTerm;
586         private final String votedFor;
587
588         public UpdateElectionTerm(long currentTerm, String votedFor) {
589             this.currentTerm = currentTerm;
590             this.votedFor = votedFor;
591         }
592
593         public long getCurrentTerm() {
594             return currentTerm;
595         }
596
597         public String getVotedFor() {
598             return votedFor;
599         }
600     }
601
602     private static class BehaviorStateHolder {
603         private RaftActorBehavior behavior;
604         private String leaderId;
605
606         void init(RaftActorBehavior behavior) {
607             this.behavior = behavior;
608             this.leaderId = behavior != null ? behavior.getLeaderId() : null;
609         }
610
611         RaftActorBehavior getBehavior() {
612             return behavior;
613         }
614
615         String getLeaderId() {
616             return leaderId;
617         }
618     }
619 }