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