Merge "BUG 2518 : Throttle operations in a transaction"
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / AbstractLeader.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.behaviors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Optional;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableMap.Builder;
19 import com.google.protobuf.ByteString;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.concurrent.TimeUnit;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
31 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
33 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
34 import org.opendaylight.controller.cluster.raft.RaftActorContext;
35 import org.opendaylight.controller.cluster.raft.RaftState;
36 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
37 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot;
39 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
40 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
41 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
43 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
45 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
46 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
47 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
48 import scala.concurrent.duration.FiniteDuration;
49
50 /**
51  * The behavior of a RaftActor when it is in the Leader state
52  * <p/>
53  * Leaders:
54  * <ul>
55  * <li> Upon election: send initial empty AppendEntries RPCs
56  * (heartbeat) to each server; repeat during idle periods to
57  * prevent election timeouts (§5.2)
58  * <li> If command received from client: append entry to local log,
59  * respond after entry applied to state machine (§5.3)
60  * <li> If last log index ≥ nextIndex for a follower: send
61  * AppendEntries RPC with log entries starting at nextIndex
62  * <ul>
63  * <li> If successful: update nextIndex and matchIndex for
64  * follower (§5.3)
65  * <li> If AppendEntries fails because of log inconsistency:
66  * decrement nextIndex and retry (§5.3)
67  * </ul>
68  * <li> If there exists an N such that N > commitIndex, a majority
69  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
70  * set commitIndex = N (§5.3, §5.4).
71  */
72 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
73
74     // The index of the first chunk that is sent when installing a snapshot
75     public static final int FIRST_CHUNK_INDEX = 1;
76
77     // The index that the follower should respond with if it needs the install snapshot to be reset
78     public static final int INVALID_CHUNK_INDEX = -1;
79
80     // This would be passed as the hash code of the last chunk when sending the first chunk
81     public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
82
83     private final Map<String, FollowerLogInformation> followerToLog;
84     private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
85
86     private Cancellable heartbeatSchedule = null;
87
88     private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
89
90     protected final int minReplicationCount;
91
92     protected final int minIsolatedLeaderPeerCount;
93
94     private Optional<ByteString> snapshot;
95
96     public AbstractLeader(RaftActorContext context) {
97         super(context);
98
99         final Builder<String, FollowerLogInformation> ftlBuilder = ImmutableMap.builder();
100         for (String followerId : context.getPeerAddresses().keySet()) {
101             FollowerLogInformation followerLogInformation =
102                 new FollowerLogInformationImpl(followerId,
103                     context.getCommitIndex(), -1,
104                     context.getConfigParams().getElectionTimeOutInterval());
105
106             ftlBuilder.put(followerId, followerLogInformation);
107         }
108         followerToLog = ftlBuilder.build();
109
110         leaderId = context.getId();
111
112         LOG.debug("Election:Leader has following peers: {}", getFollowerIds());
113
114         minReplicationCount = getMajorityVoteCount(getFollowerIds().size());
115
116         // the isolated Leader peer count will be 1 less than the majority vote count.
117         // this is because the vote count has the self vote counted in it
118         // for e.g
119         // 0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
120         // 2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
121         // 4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
122         minIsolatedLeaderPeerCount = minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
123
124         snapshot = Optional.absent();
125
126         // Immediately schedule a heartbeat
127         // Upon election: send initial empty AppendEntries RPCs
128         // (heartbeat) to each server; repeat during idle periods to
129         // prevent election timeouts (§5.2)
130         scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS));
131     }
132
133     /**
134      * Return an immutable collection of follower identifiers.
135      *
136      * @return Collection of follower IDs
137      */
138     protected final Collection<String> getFollowerIds() {
139         return followerToLog.keySet();
140     }
141
142     private Optional<ByteString> getSnapshot() {
143         return snapshot;
144     }
145
146     @VisibleForTesting
147     void setSnapshot(Optional<ByteString> snapshot) {
148         this.snapshot = snapshot;
149     }
150
151     @Override
152     protected RaftActorBehavior handleAppendEntries(ActorRef sender,
153         AppendEntries appendEntries) {
154
155         if(LOG.isDebugEnabled()) {
156             LOG.debug(appendEntries.toString());
157         }
158
159         return this;
160     }
161
162     @Override
163     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
164         AppendEntriesReply appendEntriesReply) {
165
166         if(! appendEntriesReply.isSuccess()) {
167             if(LOG.isDebugEnabled()) {
168                 LOG.debug(appendEntriesReply.toString());
169             }
170         }
171
172         // Update the FollowerLogInformation
173         String followerId = appendEntriesReply.getFollowerId();
174         FollowerLogInformation followerLogInformation =
175             followerToLog.get(followerId);
176
177         if(followerLogInformation == null){
178             LOG.error("Unknown follower {}", followerId);
179             return this;
180         }
181
182         followerLogInformation.markFollowerActive();
183
184         if (appendEntriesReply.isSuccess()) {
185             followerLogInformation
186                 .setMatchIndex(appendEntriesReply.getLogLastIndex());
187             followerLogInformation
188                 .setNextIndex(appendEntriesReply.getLogLastIndex() + 1);
189         } else {
190
191             // TODO: When we find that the follower is out of sync with the
192             // Leader we simply decrement that followers next index by 1.
193             // Would it be possible to do better than this? The RAFT spec
194             // does not explicitly deal with it but may be something for us to
195             // think about
196
197             followerLogInformation.decrNextIndex();
198         }
199
200         // Now figure out if this reply warrants a change in the commitIndex
201         // If there exists an N such that N > commitIndex, a majority
202         // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
203         // set commitIndex = N (§5.3, §5.4).
204         for (long N = context.getCommitIndex() + 1; ; N++) {
205             int replicatedCount = 1;
206
207             for (FollowerLogInformation info : followerToLog.values()) {
208                 if (info.getMatchIndex() >= N) {
209                     replicatedCount++;
210                 }
211             }
212
213             if (replicatedCount >= minReplicationCount) {
214                 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
215                 if (replicatedLogEntry != null &&
216                     replicatedLogEntry.getTerm() == currentTerm()) {
217                     context.setCommitIndex(N);
218                 }
219             } else {
220                 break;
221             }
222         }
223
224         // Apply the change to the state machine
225         if (context.getCommitIndex() > context.getLastApplied()) {
226             applyLogToStateMachine(context.getCommitIndex());
227         }
228
229         return this;
230     }
231
232     @Override
233     protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
234         final Iterator<ClientRequestTracker> it = trackerList.iterator();
235         while (it.hasNext()) {
236             final ClientRequestTracker t = it.next();
237             if (t.getIndex() == logIndex) {
238                 it.remove();
239                 return t;
240             }
241         }
242
243         return null;
244     }
245
246     @Override
247     protected ClientRequestTracker findClientRequestTracker(long logIndex) {
248         for (ClientRequestTracker tracker : trackerList) {
249             if (tracker.getIndex() == logIndex) {
250                 return tracker;
251             }
252         }
253         return null;
254     }
255
256     @Override
257     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
258         RequestVoteReply requestVoteReply) {
259         return this;
260     }
261
262     @Override
263     public RaftState state() {
264         return RaftState.Leader;
265     }
266
267     @Override
268     public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
269         Preconditions.checkNotNull(sender, "sender should not be null");
270
271         Object message = fromSerializableMessage(originalMessage);
272
273         if (message instanceof RaftRPC) {
274             RaftRPC rpc = (RaftRPC) message;
275             // If RPC request or response contains term T > currentTerm:
276             // set currentTerm = T, convert to follower (§5.1)
277             // This applies to all RPC messages and responses
278             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
279                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
280
281                 return switchBehavior(new Follower(context));
282             }
283         }
284
285         try {
286             if (message instanceof SendHeartBeat) {
287                 sendHeartBeat();
288                 return this;
289
290             } else if(message instanceof InitiateInstallSnapshot) {
291                 installSnapshotIfNeeded();
292
293             } else if(message instanceof SendInstallSnapshot) {
294                 // received from RaftActor
295                 setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
296                 sendInstallSnapshot();
297
298             } else if (message instanceof Replicate) {
299                 replicate((Replicate) message);
300
301             } else if (message instanceof InstallSnapshotReply){
302                 handleInstallSnapshotReply((InstallSnapshotReply) message);
303
304             }
305         } finally {
306             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
307         }
308
309         return super.handleMessage(sender, message);
310     }
311
312     private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
313         String followerId = reply.getFollowerId();
314         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
315         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
316         followerLogInformation.markFollowerActive();
317
318         if (followerToSnapshot != null &&
319             followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
320
321             if (reply.isSuccess()) {
322                 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
323                     //this was the last chunk reply
324                     if(LOG.isDebugEnabled()) {
325                         LOG.debug("InstallSnapshotReply received, " +
326                                 "last chunk received, Chunk:{}. Follower:{} Setting nextIndex:{}",
327                             reply.getChunkIndex(), followerId,
328                             context.getReplicatedLog().getSnapshotIndex() + 1
329                         );
330                     }
331
332                     followerLogInformation.setMatchIndex(
333                         context.getReplicatedLog().getSnapshotIndex());
334                     followerLogInformation.setNextIndex(
335                         context.getReplicatedLog().getSnapshotIndex() + 1);
336                     mapFollowerToSnapshot.remove(followerId);
337
338                     if(LOG.isDebugEnabled()) {
339                         LOG.debug("followerToLog.get(followerId).getNextIndex()=" +
340                             followerToLog.get(followerId).getNextIndex());
341                     }
342
343                     if (mapFollowerToSnapshot.isEmpty()) {
344                         // once there are no pending followers receiving snapshots
345                         // we can remove snapshot from the memory
346                         setSnapshot(Optional.<ByteString>absent());
347                     }
348
349                 } else {
350                     followerToSnapshot.markSendStatus(true);
351                 }
352             } else {
353                 LOG.info("InstallSnapshotReply received, " +
354                         "sending snapshot chunk failed, Will retry, Chunk:{}",
355                     reply.getChunkIndex()
356                 );
357
358                 followerToSnapshot.markSendStatus(false);
359             }
360
361         } else {
362             LOG.error("ERROR!!" +
363                     "FollowerId in InstallSnapshotReply not known to Leader" +
364                     " or Chunk Index in InstallSnapshotReply not matching {} != {}",
365                 followerToSnapshot.getChunkIndex(), reply.getChunkIndex()
366             );
367
368             if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
369                 // Since the Follower did not find this index to be valid we should reset the follower snapshot
370                 // so that Installing the snapshot can resume from the beginning
371                 followerToSnapshot.reset();
372             }
373         }
374     }
375
376     private void replicate(Replicate replicate) {
377         long logIndex = replicate.getReplicatedLogEntry().getIndex();
378
379         if(LOG.isDebugEnabled()) {
380             LOG.debug("Replicate message {}", logIndex);
381         }
382
383         // Create a tracker entry we will use this later to notify the
384         // client actor
385         trackerList.add(
386             new ClientRequestTrackerImpl(replicate.getClientActor(),
387                 replicate.getIdentifier(),
388                 logIndex)
389         );
390
391         if (followerToLog.isEmpty()) {
392             context.setCommitIndex(logIndex);
393             applyLogToStateMachine(logIndex);
394         } else {
395             sendAppendEntries();
396         }
397     }
398
399     private void sendAppendEntries() {
400         // Send an AppendEntries to all followers
401         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
402             final String followerId = e.getKey();
403             ActorSelection followerActor = context.getPeerActorSelection(followerId);
404
405             if (followerActor != null) {
406                 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
407                 long followerNextIndex = followerLogInformation.getNextIndex();
408                 boolean isFollowerActive = followerLogInformation.isFollowerActive();
409
410                 if (mapFollowerToSnapshot.get(followerId) != null) {
411                     // if install snapshot is in process , then sent next chunk if possible
412                     if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
413                         sendSnapshotChunk(followerActor, followerId);
414                     } else {
415                         // we send a heartbeat even if we have not received a reply for the last chunk
416                         sendAppendEntriesToFollower(followerActor, followerNextIndex,
417                             Collections.<ReplicatedLogEntry>emptyList());
418                     }
419
420                 } else {
421                     long leaderLastIndex = context.getReplicatedLog().lastIndex();
422                     long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
423                     final List<ReplicatedLogEntry> entries;
424
425                     if (isFollowerActive &&
426                         context.getReplicatedLog().isPresent(followerNextIndex)) {
427                         // FIXME : Sending one entry at a time
428                         entries = context.getReplicatedLog().getFrom(followerNextIndex, 1);
429
430                     } else if (isFollowerActive && followerNextIndex >= 0 &&
431                         leaderLastIndex >= followerNextIndex ) {
432                         // if the followers next index is not present in the leaders log, and
433                         // if the follower is just not starting and if leader's index is more than followers index
434                         // then snapshot should be sent
435
436                         if(LOG.isDebugEnabled()) {
437                             LOG.debug("InitiateInstallSnapshot to follower:{}," +
438                                     "follower-nextIndex:{}, leader-snapshot-index:{},  " +
439                                     "leader-last-index:{}", followerId,
440                                 followerNextIndex, leaderSnapShotIndex, leaderLastIndex
441                             );
442                         }
443                         actor().tell(new InitiateInstallSnapshot(), actor());
444
445                         // we would want to sent AE as the capture snapshot might take time
446                         entries =  Collections.<ReplicatedLogEntry>emptyList();
447
448                     } else {
449                         //we send an AppendEntries, even if the follower is inactive
450                         // in-order to update the followers timestamp, in case it becomes active again
451                         entries =  Collections.<ReplicatedLogEntry>emptyList();
452                     }
453
454                     sendAppendEntriesToFollower(followerActor, followerNextIndex, entries);
455
456                 }
457             }
458         }
459     }
460
461     private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
462         List<ReplicatedLogEntry> entries) {
463         followerActor.tell(
464             new AppendEntries(currentTerm(), context.getId(),
465                 prevLogIndex(followerNextIndex),
466                 prevLogTerm(followerNextIndex), entries,
467                 context.getCommitIndex()).toSerializable(),
468             actor()
469         );
470     }
471
472     /**
473      * An installSnapshot is scheduled at a interval that is a multiple of
474      * a HEARTBEAT_INTERVAL. This is to avoid the need to check for installing
475      * snapshots at every heartbeat.
476      *
477      * Install Snapshot works as follows
478      * 1. Leader sends a InitiateInstallSnapshot message to self
479      * 2. Leader then initiates the capture snapshot by sending a CaptureSnapshot message to actor
480      * 3. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
481      * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
482      * 4. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
483      * 5. On complete, Follower sends back a InstallSnapshotReply.
484      * 6. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
485      * and replenishes the memory by deleting the snapshot in Replicated log.
486      *
487      */
488     private void installSnapshotIfNeeded() {
489         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
490             final ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
491
492             if (followerActor != null) {
493                 long nextIndex = e.getValue().getNextIndex();
494
495                 if (!context.getReplicatedLog().isPresent(nextIndex) &&
496                     context.getReplicatedLog().isInSnapshot(nextIndex)) {
497                     LOG.info("{} follower needs a snapshot install", e.getKey());
498                     if (snapshot.isPresent()) {
499                         // if a snapshot is present in the memory, most likely another install is in progress
500                         // no need to capture snapshot
501                         sendSnapshotChunk(followerActor, e.getKey());
502
503                     } else {
504                         initiateCaptureSnapshot();
505                         //we just need 1 follower who would need snapshot to be installed.
506                         // when we have the snapshot captured, we would again check (in SendInstallSnapshot)
507                         // who needs an install and send to all who need
508                         break;
509                     }
510
511                 }
512             }
513         }
514     }
515
516     // on every install snapshot, we try to capture the snapshot.
517     // Once a capture is going on, another one issued will get ignored by RaftActor.
518     private void initiateCaptureSnapshot() {
519         LOG.info("Initiating Snapshot Capture to Install Snapshot, Leader:{}", getLeaderId());
520         ReplicatedLogEntry lastAppliedEntry = context.getReplicatedLog().get(context.getLastApplied());
521         long lastAppliedIndex = -1;
522         long lastAppliedTerm = -1;
523
524         if (lastAppliedEntry != null) {
525             lastAppliedIndex = lastAppliedEntry.getIndex();
526             lastAppliedTerm = lastAppliedEntry.getTerm();
527         } else if (context.getReplicatedLog().getSnapshotIndex() > -1)  {
528             lastAppliedIndex = context.getReplicatedLog().getSnapshotIndex();
529             lastAppliedTerm = context.getReplicatedLog().getSnapshotTerm();
530         }
531
532         boolean isInstallSnapshotInitiated = true;
533         actor().tell(new CaptureSnapshot(lastIndex(), lastTerm(),
534                 lastAppliedIndex, lastAppliedTerm, isInstallSnapshotInitiated),
535             actor());
536     }
537
538
539     private void sendInstallSnapshot() {
540         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
541             ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
542
543             if (followerActor != null) {
544                 long nextIndex = e.getValue().getNextIndex();
545
546                 if (!context.getReplicatedLog().isPresent(nextIndex) &&
547                     context.getReplicatedLog().isInSnapshot(nextIndex)) {
548                     sendSnapshotChunk(followerActor, e.getKey());
549                 }
550             }
551         }
552     }
553
554     /**
555      *  Sends a snapshot chunk to a given follower
556      *  InstallSnapshot should qualify as a heartbeat too.
557      */
558     private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
559         try {
560             if (snapshot.isPresent()) {
561                 followerActor.tell(
562                     new InstallSnapshot(currentTerm(), context.getId(),
563                         context.getReplicatedLog().getSnapshotIndex(),
564                         context.getReplicatedLog().getSnapshotTerm(),
565                         getNextSnapshotChunk(followerId,snapshot.get()),
566                         mapFollowerToSnapshot.get(followerId).incrementChunkIndex(),
567                         mapFollowerToSnapshot.get(followerId).getTotalChunks(),
568                         Optional.of(mapFollowerToSnapshot.get(followerId).getLastChunkHashCode())
569                     ).toSerializable(),
570                     actor()
571                 );
572                 LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}",
573                     followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(),
574                     mapFollowerToSnapshot.get(followerId).getTotalChunks());
575             }
576         } catch (IOException e) {
577             LOG.error(e, "InstallSnapshot failed for Leader.");
578         }
579     }
580
581     /**
582      * Acccepts snaphot as ByteString, enters into map for future chunks
583      * creates and return a ByteString chunk
584      */
585     private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
586         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
587         if (followerToSnapshot == null) {
588             followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
589             mapFollowerToSnapshot.put(followerId, followerToSnapshot);
590         }
591         ByteString nextChunk = followerToSnapshot.getNextChunk();
592         if (LOG.isDebugEnabled()) {
593             LOG.debug("Leader's snapshot nextChunk size:{}", nextChunk.size());
594         }
595         return nextChunk;
596     }
597
598     private void sendHeartBeat() {
599         if (!followerToLog.isEmpty()) {
600             sendAppendEntries();
601         }
602     }
603
604     private void stopHeartBeat() {
605         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
606             heartbeatSchedule.cancel();
607         }
608     }
609
610     private void scheduleHeartBeat(FiniteDuration interval) {
611         if (followerToLog.isEmpty()) {
612             // Optimization - do not bother scheduling a heartbeat as there are
613             // no followers
614             return;
615         }
616
617         stopHeartBeat();
618
619         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
620         // message is sent to itself.
621         // Scheduling the heartbeat only once here because heartbeats do not
622         // need to be sent if there are other messages being sent to the remote
623         // actor.
624         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
625             interval, context.getActor(), new SendHeartBeat(),
626             context.getActorSystem().dispatcher(), context.getActor());
627     }
628
629     @Override
630     public void close() throws Exception {
631         stopHeartBeat();
632     }
633
634     @Override
635     public String getLeaderId() {
636         return context.getId();
637     }
638
639     protected boolean isLeaderIsolated() {
640         int minPresent = minIsolatedLeaderPeerCount;
641         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
642             if (followerLogInformation.isFollowerActive()) {
643                 --minPresent;
644                 if (minPresent == 0) {
645                     break;
646                 }
647             }
648         }
649         return (minPresent != 0);
650     }
651
652     /**
653      * Encapsulates the snapshot bytestring and handles the logic of sending
654      * snapshot chunks
655      */
656     protected class FollowerToSnapshot {
657         private ByteString snapshotBytes;
658         private int offset = 0;
659         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
660         private int replyReceivedForOffset;
661         // if replyStatus is false, the previous chunk is attempted
662         private boolean replyStatus = false;
663         private int chunkIndex;
664         private int totalChunks;
665         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
666         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
667
668         public FollowerToSnapshot(ByteString snapshotBytes) {
669             this.snapshotBytes = snapshotBytes;
670             int size = snapshotBytes.size();
671             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
672                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
673             if(LOG.isDebugEnabled()) {
674                 LOG.debug("Snapshot {} bytes, total chunks to send:{}",
675                     size, totalChunks);
676             }
677             replyReceivedForOffset = -1;
678             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
679         }
680
681         public ByteString getSnapshotBytes() {
682             return snapshotBytes;
683         }
684
685         public int incrementOffset() {
686             if(replyStatus) {
687                 // if prev chunk failed, we would want to sent the same chunk again
688                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
689             }
690             return offset;
691         }
692
693         public int incrementChunkIndex() {
694             if (replyStatus) {
695                 // if prev chunk failed, we would want to sent the same chunk again
696                 chunkIndex =  chunkIndex + 1;
697             }
698             return chunkIndex;
699         }
700
701         public int getChunkIndex() {
702             return chunkIndex;
703         }
704
705         public int getTotalChunks() {
706             return totalChunks;
707         }
708
709         public boolean canSendNextChunk() {
710             // we only send a false if a chunk is sent but we have not received a reply yet
711             return replyReceivedForOffset == offset;
712         }
713
714         public boolean isLastChunk(int chunkIndex) {
715             return totalChunks == chunkIndex;
716         }
717
718         public void markSendStatus(boolean success) {
719             if (success) {
720                 // if the chunk sent was successful
721                 replyReceivedForOffset = offset;
722                 replyStatus = true;
723                 lastChunkHashCode = nextChunkHashCode;
724             } else {
725                 // if the chunk sent was failure
726                 replyReceivedForOffset = offset;
727                 replyStatus = false;
728             }
729         }
730
731         public ByteString getNextChunk() {
732             int snapshotLength = getSnapshotBytes().size();
733             int start = incrementOffset();
734             int size = context.getConfigParams().getSnapshotChunkSize();
735             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
736                 size = snapshotLength;
737             } else {
738                 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
739                     size = snapshotLength - start;
740                 }
741             }
742
743             if(LOG.isDebugEnabled()) {
744                 LOG.debug("length={}, offset={},size={}",
745                     snapshotLength, start, size);
746             }
747             ByteString substring = getSnapshotBytes().substring(start, start + size);
748             nextChunkHashCode = substring.hashCode();
749             return substring;
750         }
751
752         /**
753          * reset should be called when the Follower needs to be sent the snapshot from the beginning
754          */
755         public void reset(){
756             offset = 0;
757             replyStatus = false;
758             replyReceivedForOffset = offset;
759             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
760             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
761         }
762
763         public int getLastChunkHashCode() {
764             return lastChunkHashCode;
765         }
766     }
767
768     // called from example-actor for printing the follower-states
769     public String printFollowerStates() {
770         final StringBuilder sb = new StringBuilder();
771
772         sb.append('[');
773         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
774             sb.append('{');
775             sb.append(followerLogInformation.getId());
776             sb.append(" state:");
777             sb.append(followerLogInformation.isFollowerActive());
778             sb.append("},");
779         }
780         sb.append(']');
781
782         return sb.toString();
783     }
784
785     @VisibleForTesting
786     public FollowerLogInformation getFollower(String followerId) {
787         return followerToLog.get(followerId);
788     }
789
790     @VisibleForTesting
791     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
792         mapFollowerToSnapshot.put(followerId, snapshot);
793     }
794
795     @VisibleForTesting
796     public int followerSnapshotSize() {
797         return mapFollowerToSnapshot.size();
798     }
799
800     @VisibleForTesting
801     public int followerLogSize() {
802         return followerToLog.size();
803     }
804 }