Merge topic 'archetype'
[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.event.Logging;
14 import akka.event.LoggingAdapter;
15 import akka.japi.Procedure;
16 import akka.persistence.RecoveryCompleted;
17 import akka.persistence.SaveSnapshotFailure;
18 import akka.persistence.SaveSnapshotSuccess;
19 import akka.persistence.SnapshotOffer;
20 import akka.persistence.SnapshotSelectionCriteria;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Optional;
23 import com.google.common.base.Stopwatch;
24 import com.google.protobuf.ByteString;
25 import java.io.Serializable;
26 import java.util.Map;
27 import org.opendaylight.controller.cluster.DataPersistenceProvider;
28 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
29 import org.opendaylight.controller.cluster.notifications.RoleChanged;
30 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
32 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
33 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
34 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
35 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
36 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
37 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
38 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
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.messages.AppendEntriesReply;
44 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
45 import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
46
47 /**
48  * RaftActor encapsulates a state machine that needs to be kept synchronized
49  * in a cluster. It implements the RAFT algorithm as described in the paper
50  * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
51  * In Search of an Understandable Consensus Algorithm</a>
52  * <p/>
53  * RaftActor has 3 states and each state has a certain behavior associated
54  * with it. A Raft actor can behave as,
55  * <ul>
56  * <li> A Leader </li>
57  * <li> A Follower (or) </li>
58  * <li> A Candidate </li>
59  * </ul>
60  * <p/>
61  * <p/>
62  * A RaftActor MUST be a Leader in order to accept requests from clients to
63  * change the state of it's encapsulated state machine. Once a RaftActor becomes
64  * a Leader it is also responsible for ensuring that all followers ultimately
65  * have the same log and therefore the same state machine as itself.
66  * <p/>
67  * <p/>
68  * The current behavior of a RaftActor determines how election for leadership
69  * is initiated and how peer RaftActors react to request for votes.
70  * <p/>
71  * <p/>
72  * Each RaftActor also needs to know the current election term. It uses this
73  * information for a couple of things. One is to simply figure out who it
74  * voted for in the last election. Another is to figure out if the message
75  * it received to update it's state is stale.
76  * <p/>
77  * <p/>
78  * The RaftActor uses akka-persistence to store it's replicated log.
79  * Furthermore through it's behaviors a Raft Actor determines
80  * <p/>
81  * <ul>
82  * <li> when a log entry should be persisted </li>
83  * <li> when a log entry should be applied to the state machine (and) </li>
84  * <li> when a snapshot should be saved </li>
85  * </ul>
86  */
87 public abstract class RaftActor extends AbstractUntypedPersistentActor {
88     protected final LoggingAdapter LOG =
89         Logging.getLogger(getContext().system(), this);
90
91     /**
92      * The current state determines the current behavior of a RaftActor
93      * A Raft Actor always starts off in the Follower State
94      */
95     private RaftActorBehavior currentBehavior;
96
97     /**
98      * This context should NOT be passed directly to any other actor it is
99      * only to be consumed by the RaftActorBehaviors
100      */
101     private final RaftActorContext context;
102
103     /**
104      * The in-memory journal
105      */
106     private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
107
108     private CaptureSnapshot captureSnapshot = null;
109
110     private volatile boolean hasSnapshotCaptureInitiated = false;
111
112     private Stopwatch recoveryTimer;
113
114     private int currentRecoveryBatchCount;
115
116
117
118     public RaftActor(String id, Map<String, String> peerAddresses) {
119         this(id, peerAddresses, Optional.<ConfigParams>absent());
120     }
121
122     public RaftActor(String id, Map<String, String> peerAddresses,
123          Optional<ConfigParams> configParams) {
124
125         context = new RaftActorContextImpl(this.getSelf(),
126             this.getContext(), id, new ElectionTermImpl(),
127             -1, -1, replicatedLog, peerAddresses,
128             (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
129             LOG);
130     }
131
132     private void initRecoveryTimer() {
133         if(recoveryTimer == null) {
134             recoveryTimer = new Stopwatch();
135             recoveryTimer.start();
136         }
137     }
138
139     @Override
140     public void preStart() throws Exception {
141         LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
142                 context.getConfigParams().getJournalRecoveryLogBatchSize());
143
144         super.preStart();
145     }
146
147     @Override
148     public void handleRecover(Object message) {
149         if(persistence().isRecoveryApplicable()) {
150             if (message instanceof SnapshotOffer) {
151                 onRecoveredSnapshot((SnapshotOffer) message);
152             } else if (message instanceof ReplicatedLogEntry) {
153                 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
154             } else if (message instanceof ApplyLogEntries) {
155                 onRecoveredApplyLogEntries((ApplyLogEntries) message);
156             } else if (message instanceof DeleteEntries) {
157                 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
158             } else if (message instanceof UpdateElectionTerm) {
159                 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
160                         ((UpdateElectionTerm) message).getVotedFor());
161             } else if (message instanceof RecoveryCompleted) {
162                 onRecoveryCompletedMessage();
163             }
164         } else {
165             if (message instanceof RecoveryCompleted) {
166                 // Delete all the messages from the akka journal so that we do not end up with consistency issues
167                 // Note I am not using the dataPersistenceProvider and directly using the akka api here
168                 deleteMessages(lastSequenceNr());
169
170                 // Delete all the akka snapshots as they will not be needed
171                 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
172
173                 onRecoveryComplete();
174
175                 RaftActorBehavior oldBehavior = currentBehavior;
176                 currentBehavior = new Follower(context);
177                 handleBehaviorChange(oldBehavior, currentBehavior);
178             }
179         }
180     }
181
182     private void onRecoveredSnapshot(SnapshotOffer offer) {
183         if(LOG.isDebugEnabled()) {
184             LOG.debug("SnapshotOffer called..");
185         }
186
187         initRecoveryTimer();
188
189         Snapshot snapshot = (Snapshot) offer.snapshot();
190
191         // Create a replicated log with the snapshot information
192         // The replicated log can be used later on to retrieve this snapshot
193         // when we need to install it on a peer
194         replicatedLog = new ReplicatedLogImpl(snapshot);
195
196         context.setReplicatedLog(replicatedLog);
197         context.setLastApplied(snapshot.getLastAppliedIndex());
198         context.setCommitIndex(snapshot.getLastAppliedIndex());
199
200         Stopwatch timer = new Stopwatch();
201         timer.start();
202
203         // Apply the snapshot to the actors state
204         applyRecoverySnapshot(ByteString.copyFrom(snapshot.getState()));
205
206         timer.stop();
207         LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" +
208                 replicatedLog.size(), persistenceId(), timer.toString(),
209                 replicatedLog.snapshotIndex, replicatedLog.snapshotTerm);
210     }
211
212     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
213         if(LOG.isDebugEnabled()) {
214             LOG.debug("Received ReplicatedLogEntry for recovery: {}", logEntry.getIndex());
215         }
216
217         replicatedLog.append(logEntry);
218     }
219
220     private void onRecoveredApplyLogEntries(ApplyLogEntries ale) {
221         if(LOG.isDebugEnabled()) {
222             LOG.debug("Received ApplyLogEntries for recovery, applying to state: {} to {}",
223                     context.getLastApplied() + 1, ale.getToIndex());
224         }
225
226         for (long i = context.getLastApplied() + 1; i <= ale.getToIndex(); i++) {
227             batchRecoveredLogEntry(replicatedLog.get(i));
228         }
229
230         context.setLastApplied(ale.getToIndex());
231         context.setCommitIndex(ale.getToIndex());
232     }
233
234     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
235         initRecoveryTimer();
236
237         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
238         if(currentRecoveryBatchCount == 0) {
239             startLogRecoveryBatch(batchSize);
240         }
241
242         appendRecoveredLogEntry(logEntry.getData());
243
244         if(++currentRecoveryBatchCount >= batchSize) {
245             endCurrentLogRecoveryBatch();
246         }
247     }
248
249     private void endCurrentLogRecoveryBatch() {
250         applyCurrentLogRecoveryBatch();
251         currentRecoveryBatchCount = 0;
252     }
253
254     private void onRecoveryCompletedMessage() {
255         if(currentRecoveryBatchCount > 0) {
256             endCurrentLogRecoveryBatch();
257         }
258
259         onRecoveryComplete();
260
261         String recoveryTime = "";
262         if(recoveryTimer != null) {
263             recoveryTimer.stop();
264             recoveryTime = " in " + recoveryTimer.toString();
265             recoveryTimer = null;
266         }
267
268         LOG.info(
269             "Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
270                 "Persistence Id =  " + persistenceId() +
271                 " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " +
272                 "journal-size={}",
273             replicatedLog.lastIndex(), replicatedLog.snapshotIndex,
274             replicatedLog.snapshotTerm, replicatedLog.size());
275
276         RaftActorBehavior oldBehavior = currentBehavior;
277         currentBehavior = new Follower(context);
278         handleBehaviorChange(oldBehavior, currentBehavior);
279     }
280
281     @Override public void handleCommand(Object message) {
282         if (message instanceof ApplyState){
283             ApplyState applyState = (ApplyState) message;
284
285             if(LOG.isDebugEnabled()) {
286                 LOG.debug("Applying state for log index {} data {}",
287                     applyState.getReplicatedLogEntry().getIndex(),
288                     applyState.getReplicatedLogEntry().getData());
289             }
290
291             applyState(applyState.getClientActor(), applyState.getIdentifier(),
292                 applyState.getReplicatedLogEntry().getData());
293
294         } else if (message instanceof ApplyLogEntries){
295             ApplyLogEntries ale = (ApplyLogEntries) message;
296             if(LOG.isDebugEnabled()) {
297                 LOG.debug("Persisting ApplyLogEntries with index={}", ale.getToIndex());
298             }
299             persistence().persist(new ApplyLogEntries(ale.getToIndex()), new Procedure<ApplyLogEntries>() {
300                 @Override
301                 public void apply(ApplyLogEntries param) throws Exception {
302                 }
303             });
304
305         } else if(message instanceof ApplySnapshot ) {
306             Snapshot snapshot = ((ApplySnapshot) message).getSnapshot();
307
308             if(LOG.isDebugEnabled()) {
309                 LOG.debug("ApplySnapshot called on Follower Actor " +
310                         "snapshotIndex:{}, snapshotTerm:{}", snapshot.getLastAppliedIndex(),
311                     snapshot.getLastAppliedTerm()
312                 );
313             }
314             applySnapshot(ByteString.copyFrom(snapshot.getState()));
315
316             //clears the followers log, sets the snapshot index to ensure adjusted-index works
317             replicatedLog = new ReplicatedLogImpl(snapshot);
318             context.setReplicatedLog(replicatedLog);
319             context.setLastApplied(snapshot.getLastAppliedIndex());
320
321         } else if (message instanceof FindLeader) {
322             getSender().tell(
323                 new FindLeaderReply(getLeaderAddress()),
324                 getSelf()
325             );
326
327         } else if (message instanceof SaveSnapshotSuccess) {
328             SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
329             LOG.info("SaveSnapshotSuccess received for snapshot");
330
331             long sequenceNumber = success.metadata().sequenceNr();
332
333             commitSnapshot(sequenceNumber);
334
335         } else if (message instanceof SaveSnapshotFailure) {
336             SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message;
337
338             LOG.info("saveSnapshotFailure.metadata():{}", saveSnapshotFailure.metadata().toString());
339             LOG.error(saveSnapshotFailure.cause(), "SaveSnapshotFailure received for snapshot Cause:");
340
341             context.getReplicatedLog().snapshotRollback();
342
343             LOG.info("Replicated Log rollbacked. Snapshot will be attempted in the next cycle." +
344                 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}",
345                 context.getReplicatedLog().getSnapshotIndex(),
346                 context.getReplicatedLog().getSnapshotTerm(),
347                 context.getReplicatedLog().size());
348
349         } else if (message instanceof CaptureSnapshot) {
350             LOG.info("CaptureSnapshot received by actor");
351             CaptureSnapshot cs = (CaptureSnapshot)message;
352             captureSnapshot = cs;
353             createSnapshot();
354
355         } else if (message instanceof CaptureSnapshotReply){
356             LOG.info("CaptureSnapshotReply received by actor");
357             CaptureSnapshotReply csr = (CaptureSnapshotReply) message;
358
359             ByteString stateInBytes = csr.getSnapshot();
360             LOG.info("CaptureSnapshotReply stateInBytes size:{}", stateInBytes.size());
361             handleCaptureSnapshotReply(stateInBytes);
362
363         } else {
364             if (!(message instanceof AppendEntriesMessages.AppendEntries)
365                 && !(message instanceof AppendEntriesReply) && !(message instanceof SendHeartBeat)) {
366                 if(LOG.isDebugEnabled()) {
367                     LOG.debug("onReceiveCommand: message: {}", message.getClass());
368                 }
369             }
370
371             RaftActorBehavior oldBehavior = currentBehavior;
372             currentBehavior = currentBehavior.handleMessage(getSender(), message);
373
374             handleBehaviorChange(oldBehavior, currentBehavior);
375         }
376     }
377
378     private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) {
379         if (oldBehavior != currentBehavior){
380             onStateChanged();
381         }
382
383         String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId();
384         String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name();
385
386         // it can happen that the state has not changed but the leader has changed.
387         onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
388
389         if (getRoleChangeNotifier().isPresent() &&
390                 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
391             getRoleChangeNotifier().get().tell(
392                     new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()),
393                     getSelf());
394         }
395     }
396
397     /**
398      * When a derived RaftActor needs to persist something it must call
399      * persistData.
400      *
401      * @param clientActor
402      * @param identifier
403      * @param data
404      */
405     protected void persistData(final ActorRef clientActor, final String identifier,
406         final Payload data) {
407
408         ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
409             context.getReplicatedLog().lastIndex() + 1,
410             context.getTermInformation().getCurrentTerm(), data);
411
412         if(LOG.isDebugEnabled()) {
413             LOG.debug("Persist data {}", replicatedLogEntry);
414         }
415
416         final RaftActorContext raftContext = getRaftActorContext();
417
418         replicatedLog
419                 .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
420                     @Override
421                     public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
422                         if(!hasFollowers()){
423                             // Increment the Commit Index and the Last Applied values
424                             raftContext.setCommitIndex(replicatedLogEntry.getIndex());
425                             raftContext.setLastApplied(replicatedLogEntry.getIndex());
426
427                             // Apply the state immediately
428                             applyState(clientActor, identifier, data);
429
430                             // Send a ApplyLogEntries message so that we write the fact that we applied
431                             // the state to durable storage
432                             self().tell(new ApplyLogEntries((int) replicatedLogEntry.getIndex()), self());
433
434                             // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot
435                             if(!hasSnapshotCaptureInitiated){
436                                 raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(),
437                                         raftContext.getTermInformation().getCurrentTerm());
438                                 raftContext.getReplicatedLog().snapshotCommit();
439                             } else {
440                                 LOG.debug("Skipping fake snapshotting for {} because real snapshotting is in progress", getId());
441                             }
442                         } else if (clientActor != null) {
443                             // Send message for replication
444                             currentBehavior.handleMessage(getSelf(),
445                                     new Replicate(clientActor, identifier,
446                                             replicatedLogEntry)
447                             );
448                         }
449
450                     }
451                 });    }
452
453     protected String getId() {
454         return context.getId();
455     }
456
457     /**
458      * Derived actors can call the isLeader method to check if the current
459      * RaftActor is the Leader or not
460      *
461      * @return true it this RaftActor is a Leader false otherwise
462      */
463     protected boolean isLeader() {
464         return context.getId().equals(currentBehavior.getLeaderId());
465     }
466
467     /**
468      * Derived actor can call getLeader if they need a reference to the Leader.
469      * This would be useful for example in forwarding a request to an actor
470      * which is the leader
471      *
472      * @return A reference to the leader if known, null otherwise
473      */
474     protected ActorSelection getLeader(){
475         String leaderAddress = getLeaderAddress();
476
477         if(leaderAddress == null){
478             return null;
479         }
480
481         return context.actorSelection(leaderAddress);
482     }
483
484     /**
485      *
486      * @return the current leader's id
487      */
488     protected String getLeaderId(){
489         return currentBehavior.getLeaderId();
490     }
491
492     protected RaftState getRaftState() {
493         return currentBehavior.state();
494     }
495
496     protected ReplicatedLogEntry getLastLogEntry() {
497         return replicatedLog.last();
498     }
499
500     protected Long getCurrentTerm(){
501         return context.getTermInformation().getCurrentTerm();
502     }
503
504     protected Long getCommitIndex(){
505         return context.getCommitIndex();
506     }
507
508     protected Long getLastApplied(){
509         return context.getLastApplied();
510     }
511
512     protected RaftActorContext getRaftActorContext() {
513         return context;
514     }
515
516     /**
517      * setPeerAddress sets the address of a known peer at a later time.
518      * <p>
519      * This is to account for situations where a we know that a peer
520      * exists but we do not know an address up-front. This may also be used in
521      * situations where a known peer starts off in a different location and we
522      * need to change it's address
523      * <p>
524      * Note that if the peerId does not match the list of peers passed to
525      * this actor during construction an IllegalStateException will be thrown.
526      *
527      * @param peerId
528      * @param peerAddress
529      */
530     protected void setPeerAddress(String peerId, String peerAddress){
531         context.setPeerAddress(peerId, peerAddress);
532     }
533
534     protected void commitSnapshot(long sequenceNumber) {
535         context.getReplicatedLog().snapshotCommit();
536
537         // TODO: Not sure if we want to be this aggressive with trimming stuff
538         trimPersistentData(sequenceNumber);
539     }
540
541     /**
542      * The applyState method will be called by the RaftActor when some data
543      * needs to be applied to the actor's state
544      *
545      * @param clientActor A reference to the client who sent this message. This
546      *                    is the same reference that was passed to persistData
547      *                    by the derived actor. clientActor may be null when
548      *                    the RaftActor is behaving as a follower or during
549      *                    recovery.
550      * @param identifier  The identifier of the persisted data. This is also
551      *                    the same identifier that was passed to persistData by
552      *                    the derived actor. identifier may be null when
553      *                    the RaftActor is behaving as a follower or during
554      *                    recovery
555      * @param data        A piece of data that was persisted by the persistData call.
556      *                    This should NEVER be null.
557      */
558     protected abstract void applyState(ActorRef clientActor, String identifier,
559         Object data);
560
561     /**
562      * This method is called during recovery at the start of a batch of state entries. Derived
563      * classes should perform any initialization needed to start a batch.
564      */
565     protected abstract void startLogRecoveryBatch(int maxBatchSize);
566
567     /**
568      * This method is called during recovery to append state data to the current batch. This method
569      * is called 1 or more times after {@link #startLogRecoveryBatch}.
570      *
571      * @param data the state data
572      */
573     protected abstract void appendRecoveredLogEntry(Payload data);
574
575     /**
576      * This method is called during recovery to reconstruct the state of the actor.
577      *
578      * @param snapshot A snapshot of the state of the actor
579      */
580     protected abstract void applyRecoverySnapshot(ByteString snapshot);
581
582     /**
583      * This method is called during recovery at the end of a batch to apply the current batched
584      * log entries. This method is called after {@link #appendRecoveredLogEntry}.
585      */
586     protected abstract void applyCurrentLogRecoveryBatch();
587
588     /**
589      * This method is called when recovery is complete.
590      */
591     protected abstract void onRecoveryComplete();
592
593     /**
594      * This method will be called by the RaftActor when a snapshot needs to be
595      * created. The derived actor should respond with its current state.
596      * <p/>
597      * During recovery the state that is returned by the derived actor will
598      * be passed back to it by calling the applySnapshot  method
599      *
600      * @return The current state of the actor
601      */
602     protected abstract void createSnapshot();
603
604     /**
605      * This method can be called at any other point during normal
606      * operations when the derived actor is out of sync with it's peers
607      * and the only way to bring it in sync is by applying a snapshot
608      *
609      * @param snapshot A snapshot of the state of the actor
610      */
611     protected abstract void applySnapshot(ByteString snapshot);
612
613     /**
614      * This method will be called by the RaftActor when the state of the
615      * RaftActor changes. The derived actor can then use methods like
616      * isLeader or getLeader to do something useful
617      */
618     protected abstract void onStateChanged();
619
620     protected abstract DataPersistenceProvider persistence();
621
622     /**
623      * Notifier Actor for this RaftActor to notify when a role change happens
624      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
625      */
626     protected abstract Optional<ActorRef> getRoleChangeNotifier();
627
628     protected void onLeaderChanged(String oldLeader, String newLeader){};
629
630     private void trimPersistentData(long sequenceNumber) {
631         // Trim akka snapshots
632         // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
633         // For now guessing that it is ANDed.
634         persistence().deleteSnapshots(new SnapshotSelectionCriteria(
635             sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
636
637         // Trim akka journal
638         persistence().deleteMessages(sequenceNumber);
639     }
640
641     private String getLeaderAddress(){
642         if(isLeader()){
643             return getSelf().path().toString();
644         }
645         String leaderId = currentBehavior.getLeaderId();
646         if (leaderId == null) {
647             return null;
648         }
649         String peerAddress = context.getPeerAddress(leaderId);
650         if(LOG.isDebugEnabled()) {
651             LOG.debug("getLeaderAddress leaderId = {} peerAddress = {}",
652                     leaderId, peerAddress);
653         }
654
655         return peerAddress;
656     }
657
658     private void handleCaptureSnapshotReply(ByteString stateInBytes) {
659         // create a snapshot object from the state provided and save it
660         // when snapshot is saved async, SaveSnapshotSuccess is raised.
661
662         Snapshot sn = Snapshot.create(stateInBytes.toByteArray(),
663             context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1),
664             captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
665             captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
666
667         persistence().saveSnapshot(sn);
668
669         LOG.info("Persisting of snapshot done:{}", sn.getLogMessage());
670
671         //be greedy and remove entries from in-mem journal which are in the snapshot
672         // and update snapshotIndex and snapshotTerm without waiting for the success,
673
674         context.getReplicatedLog().snapshotPreCommit(
675             captureSnapshot.getLastAppliedIndex(),
676             captureSnapshot.getLastAppliedTerm());
677
678         LOG.info("Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
679             "and term:{}", captureSnapshot.getLastAppliedIndex(),
680             captureSnapshot.getLastAppliedTerm());
681
682         if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) {
683             // this would be call straight to the leader and won't initiate in serialization
684             currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(stateInBytes));
685         }
686
687         captureSnapshot = null;
688         hasSnapshotCaptureInitiated = false;
689     }
690
691     protected boolean hasFollowers(){
692         return getRaftActorContext().getPeerAddresses().keySet().size() > 0;
693     }
694
695     private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
696
697         private static final int DATA_SIZE_DIVIDER = 5;
698         private long dataSizeSinceLastSnapshot = 0;
699
700         public ReplicatedLogImpl(Snapshot snapshot) {
701             super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
702                 snapshot.getUnAppliedEntries());
703         }
704
705         public ReplicatedLogImpl() {
706             super();
707         }
708
709         @Override public void removeFromAndPersist(long logEntryIndex) {
710             int adjustedIndex = adjustedIndex(logEntryIndex);
711
712             if (adjustedIndex < 0) {
713                 return;
714             }
715
716             // FIXME: Maybe this should be done after the command is saved
717             journal.subList(adjustedIndex , journal.size()).clear();
718
719             persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>(){
720
721                 @Override public void apply(DeleteEntries param)
722                     throws Exception {
723                     //FIXME : Doing nothing for now
724                     dataSize = 0;
725                     for(ReplicatedLogEntry entry : journal){
726                         dataSize += entry.size();
727                     }
728                 }
729             });
730         }
731
732         @Override public void appendAndPersist(
733             final ReplicatedLogEntry replicatedLogEntry) {
734             appendAndPersist(replicatedLogEntry, null);
735         }
736
737         @Override
738         public int dataSize() {
739             return dataSize;
740         }
741
742         public void appendAndPersist(
743             final ReplicatedLogEntry replicatedLogEntry,
744             final Procedure<ReplicatedLogEntry> callback)  {
745
746             if(LOG.isDebugEnabled()) {
747                 LOG.debug("Append log entry and persist {} ", replicatedLogEntry);
748             }
749
750             // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
751             journal.add(replicatedLogEntry);
752
753             // When persisting events with persist it is guaranteed that the
754             // persistent actor will not receive further commands between the
755             // persist call and the execution(s) of the associated event
756             // handler. This also holds for multiple persist calls in context
757             // of a single command.
758             persistence().persist(replicatedLogEntry,
759                 new Procedure<ReplicatedLogEntry>() {
760                     @Override
761                     public void apply(ReplicatedLogEntry evt) throws Exception {
762                         int logEntrySize = replicatedLogEntry.size();
763
764                         dataSize += logEntrySize;
765                         long dataSizeForCheck = dataSize;
766
767                         dataSizeSinceLastSnapshot += logEntrySize;
768                         long journalSize = lastIndex()+1;
769
770                         if(!hasFollowers()) {
771                             // When we do not have followers we do not maintain an in-memory log
772                             // due to this the journalSize will never become anything close to the
773                             // snapshot batch count. In fact will mostly be 1.
774                             // Similarly since the journal's dataSize depends on the entries in the
775                             // journal the journal's dataSize will never reach a value close to the
776                             // memory threshold.
777                             // By maintaining the dataSize outside the journal we are tracking essentially
778                             // what we have written to the disk however since we no longer are in
779                             // need of doing a snapshot just for the sake of freeing up memory we adjust
780                             // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often
781                             // as if we were maintaining a real snapshot
782                             dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER;
783                         }
784
785                         long dataThreshold = Runtime.getRuntime().totalMemory() *
786                                 getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100;
787
788                         // when a snaphsot is being taken, captureSnapshot != null
789                         if (hasSnapshotCaptureInitiated == false &&
790                                 ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 ||
791                                         dataSizeForCheck > dataThreshold)) {
792
793                             dataSizeSinceLastSnapshot = 0;
794
795                             LOG.info("Initiating Snapshot Capture..");
796                             long lastAppliedIndex = -1;
797                             long lastAppliedTerm = -1;
798
799                             ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
800                             if (!hasFollowers()) {
801                                 lastAppliedIndex = replicatedLogEntry.getIndex();
802                                 lastAppliedTerm = replicatedLogEntry.getTerm();
803                             } else if (lastAppliedEntry != null) {
804                                 lastAppliedIndex = lastAppliedEntry.getIndex();
805                                 lastAppliedTerm = lastAppliedEntry.getTerm();
806                             }
807
808                             if(LOG.isDebugEnabled()) {
809                                 LOG.debug("Snapshot Capture logSize: {}", journal.size());
810                                 LOG.debug("Snapshot Capture lastApplied:{} ",
811                                     context.getLastApplied());
812                                 LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex);
813                                 LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm);
814                             }
815
816                             // send a CaptureSnapshot to self to make the expensive operation async.
817                             getSelf().tell(new CaptureSnapshot(
818                                 lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm),
819                                 null);
820                             hasSnapshotCaptureInitiated = true;
821                         }
822                         if(callback != null){
823                             callback.apply(replicatedLogEntry);
824                         }
825                     }
826                 }
827             );
828         }
829
830     }
831
832     static class DeleteEntries implements Serializable {
833         private static final long serialVersionUID = 1L;
834         private final int fromIndex;
835
836         public DeleteEntries(int fromIndex) {
837             this.fromIndex = fromIndex;
838         }
839
840         public int getFromIndex() {
841             return fromIndex;
842         }
843     }
844
845
846     private class ElectionTermImpl implements ElectionTerm {
847         /**
848          * Identifier of the actor whose election term information this is
849          */
850         private long currentTerm = 0;
851         private String votedFor = null;
852
853         @Override
854         public long getCurrentTerm() {
855             return currentTerm;
856         }
857
858         @Override
859         public String getVotedFor() {
860             return votedFor;
861         }
862
863         @Override public void update(long currentTerm, String votedFor) {
864             if(LOG.isDebugEnabled()) {
865                 LOG.debug("Set currentTerm={}, votedFor={}", currentTerm, votedFor);
866             }
867             this.currentTerm = currentTerm;
868             this.votedFor = votedFor;
869         }
870
871         @Override
872         public void updateAndPersist(long currentTerm, String votedFor){
873             update(currentTerm, votedFor);
874             // FIXME : Maybe first persist then update the state
875             persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
876
877                 @Override public void apply(UpdateElectionTerm param)
878                     throws Exception {
879
880                 }
881             });
882         }
883     }
884
885     static class UpdateElectionTerm implements Serializable {
886         private static final long serialVersionUID = 1L;
887         private final long currentTerm;
888         private final String votedFor;
889
890         public UpdateElectionTerm(long currentTerm, String votedFor) {
891             this.currentTerm = currentTerm;
892             this.votedFor = votedFor;
893         }
894
895         public long getCurrentTerm() {
896             return currentTerm;
897         }
898
899         public String getVotedFor() {
900             return votedFor;
901         }
902     }
903
904     protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider {
905
906         public NonPersistentRaftDataProvider(){
907
908         }
909
910         /**
911          * The way snapshotting works is,
912          * <ol>
913          * <li> RaftActor calls createSnapshot on the Shard
914          * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
915          * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot.
916          * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot
917          * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done
918          * in SaveSnapshotSuccess.
919          * </ol>
920          * @param o
921          */
922         @Override
923         public void saveSnapshot(Object o) {
924             // Make saving Snapshot successful
925             commitSnapshot(-1L);
926         }
927     }
928
929     @VisibleForTesting
930     void setCurrentBehavior(AbstractRaftActorBehavior behavior) {
931         currentBehavior = behavior;
932     }
933
934     protected RaftActorBehavior getCurrentBehavior() {
935         return currentBehavior;
936     }
937
938 }