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