2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft.behaviors;
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;
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;
51 * The behavior of a RaftActor when it is in the Leader state
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
63 * <li> If successful: update nextIndex and matchIndex for
65 * <li> If AppendEntries fails because of log inconsistency:
66 * decrement nextIndex and retry (§5.3)
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).
72 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
74 // The index of the first chunk that is sent when installing a snapshot
75 public static final int FIRST_CHUNK_INDEX = 1;
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;
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;
83 private final Map<String, FollowerLogInformation> followerToLog;
84 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
86 private Cancellable heartbeatSchedule = null;
88 private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
90 protected final int minReplicationCount;
92 protected final int minIsolatedLeaderPeerCount;
94 private Optional<ByteString> snapshot;
96 public AbstractLeader(RaftActorContext context) {
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());
106 ftlBuilder.put(followerId, followerLogInformation);
108 followerToLog = ftlBuilder.build();
110 leaderId = context.getId();
112 LOG.debug("Election:Leader has following peers: {}", getFollowerIds());
114 minReplicationCount = getMajorityVoteCount(getFollowerIds().size());
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
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;
124 snapshot = Optional.absent();
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));
134 * Return an immutable collection of follower identifiers.
136 * @return Collection of follower IDs
138 protected final Collection<String> getFollowerIds() {
139 return followerToLog.keySet();
142 private Optional<ByteString> getSnapshot() {
147 void setSnapshot(Optional<ByteString> snapshot) {
148 this.snapshot = snapshot;
152 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
153 AppendEntries appendEntries) {
155 if(LOG.isDebugEnabled()) {
156 LOG.debug(appendEntries.toString());
163 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
164 AppendEntriesReply appendEntriesReply) {
166 if(! appendEntriesReply.isSuccess()) {
167 if(LOG.isDebugEnabled()) {
168 LOG.debug(appendEntriesReply.toString());
172 // Update the FollowerLogInformation
173 String followerId = appendEntriesReply.getFollowerId();
174 FollowerLogInformation followerLogInformation =
175 followerToLog.get(followerId);
177 if(followerLogInformation == null){
178 LOG.error("Unknown follower {}", followerId);
182 followerLogInformation.markFollowerActive();
184 if (appendEntriesReply.isSuccess()) {
185 followerLogInformation
186 .setMatchIndex(appendEntriesReply.getLogLastIndex());
187 followerLogInformation
188 .setNextIndex(appendEntriesReply.getLogLastIndex() + 1);
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
197 followerLogInformation.decrNextIndex();
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;
207 for (FollowerLogInformation info : followerToLog.values()) {
208 if (info.getMatchIndex() >= N) {
213 if (replicatedCount >= minReplicationCount) {
214 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
215 if (replicatedLogEntry != null &&
216 replicatedLogEntry.getTerm() == currentTerm()) {
217 context.setCommitIndex(N);
224 // Apply the change to the state machine
225 if (context.getCommitIndex() > context.getLastApplied()) {
226 applyLogToStateMachine(context.getCommitIndex());
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) {
247 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
248 for (ClientRequestTracker tracker : trackerList) {
249 if (tracker.getIndex() == logIndex) {
257 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
258 RequestVoteReply requestVoteReply) {
263 public RaftState state() {
264 return RaftState.Leader;
268 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
269 Preconditions.checkNotNull(sender, "sender should not be null");
271 Object message = fromSerializableMessage(originalMessage);
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);
281 return switchBehavior(new Follower(context));
286 if (message instanceof SendHeartBeat) {
290 } else if(message instanceof InitiateInstallSnapshot) {
291 installSnapshotIfNeeded();
293 } else if(message instanceof SendInstallSnapshot) {
294 // received from RaftActor
295 setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
296 sendInstallSnapshot();
298 } else if (message instanceof Replicate) {
299 replicate((Replicate) message);
301 } else if (message instanceof InstallSnapshotReply){
302 handleInstallSnapshotReply((InstallSnapshotReply) message);
306 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
309 return super.handleMessage(sender, message);
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();
318 if (followerToSnapshot != null &&
319 followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
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
332 followerLogInformation.setMatchIndex(
333 context.getReplicatedLog().getSnapshotIndex());
334 followerLogInformation.setNextIndex(
335 context.getReplicatedLog().getSnapshotIndex() + 1);
336 mapFollowerToSnapshot.remove(followerId);
338 if(LOG.isDebugEnabled()) {
339 LOG.debug("followerToLog.get(followerId).getNextIndex()=" +
340 followerToLog.get(followerId).getNextIndex());
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());
350 followerToSnapshot.markSendStatus(true);
353 LOG.info("InstallSnapshotReply received, " +
354 "sending snapshot chunk failed, Will retry, Chunk:{}",
355 reply.getChunkIndex()
358 followerToSnapshot.markSendStatus(false);
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()
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();
376 private void replicate(Replicate replicate) {
377 long logIndex = replicate.getReplicatedLogEntry().getIndex();
379 if(LOG.isDebugEnabled()) {
380 LOG.debug("Replicate message {}", logIndex);
383 // Create a tracker entry we will use this later to notify the
386 new ClientRequestTrackerImpl(replicate.getClientActor(),
387 replicate.getIdentifier(),
391 if (followerToLog.isEmpty()) {
392 context.setCommitIndex(logIndex);
393 applyLogToStateMachine(logIndex);
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);
405 if (followerActor != null) {
406 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
407 long followerNextIndex = followerLogInformation.getNextIndex();
408 boolean isFollowerActive = followerLogInformation.isFollowerActive();
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);
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());
421 long leaderLastIndex = context.getReplicatedLog().lastIndex();
422 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
423 final List<ReplicatedLogEntry> entries;
425 if (isFollowerActive &&
426 context.getReplicatedLog().isPresent(followerNextIndex)) {
427 // FIXME : Sending one entry at a time
428 entries = context.getReplicatedLog().getFrom(followerNextIndex, 1);
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
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
443 actor().tell(new InitiateInstallSnapshot(), actor());
445 // we would want to sent AE as the capture snapshot might take time
446 entries = Collections.<ReplicatedLogEntry>emptyList();
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();
454 sendAppendEntriesToFollower(followerActor, followerNextIndex, entries);
461 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
462 List<ReplicatedLogEntry> entries) {
464 new AppendEntries(currentTerm(), context.getId(),
465 prevLogIndex(followerNextIndex),
466 prevLogTerm(followerNextIndex), entries,
467 context.getCommitIndex()).toSerializable(),
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.
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.
488 private void installSnapshotIfNeeded() {
489 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
490 final ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
492 if (followerActor != null) {
493 long nextIndex = e.getValue().getNextIndex();
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());
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
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;
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();
532 boolean isInstallSnapshotInitiated = true;
533 actor().tell(new CaptureSnapshot(lastIndex(), lastTerm(),
534 lastAppliedIndex, lastAppliedTerm, isInstallSnapshotInitiated),
539 private void sendInstallSnapshot() {
540 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
541 ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
543 if (followerActor != null) {
544 long nextIndex = e.getValue().getNextIndex();
546 if (!context.getReplicatedLog().isPresent(nextIndex) &&
547 context.getReplicatedLog().isInSnapshot(nextIndex)) {
548 sendSnapshotChunk(followerActor, e.getKey());
555 * Sends a snapshot chunk to a given follower
556 * InstallSnapshot should qualify as a heartbeat too.
558 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
560 if (snapshot.isPresent()) {
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())
572 LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}",
573 followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(),
574 mapFollowerToSnapshot.get(followerId).getTotalChunks());
576 } catch (IOException e) {
577 LOG.error(e, "InstallSnapshot failed for Leader.");
582 * Acccepts snaphot as ByteString, enters into map for future chunks
583 * creates and return a ByteString chunk
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);
591 ByteString nextChunk = followerToSnapshot.getNextChunk();
592 if (LOG.isDebugEnabled()) {
593 LOG.debug("Leader's snapshot nextChunk size:{}", nextChunk.size());
598 private void sendHeartBeat() {
599 if (!followerToLog.isEmpty()) {
604 private void stopHeartBeat() {
605 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
606 heartbeatSchedule.cancel();
610 private void scheduleHeartBeat(FiniteDuration interval) {
611 if (followerToLog.isEmpty()) {
612 // Optimization - do not bother scheduling a heartbeat as there are
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
624 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
625 interval, context.getActor(), new SendHeartBeat(),
626 context.getActorSystem().dispatcher(), context.getActor());
630 public void close() throws Exception {
635 public String getLeaderId() {
636 return context.getId();
639 protected boolean isLeaderIsolated() {
640 int minPresent = minIsolatedLeaderPeerCount;
641 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
642 if (followerLogInformation.isFollowerActive()) {
644 if (minPresent == 0) {
649 return (minPresent != 0);
653 * Encapsulates the snapshot bytestring and handles the logic of sending
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;
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:{}",
677 replyReceivedForOffset = -1;
678 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
681 public ByteString getSnapshotBytes() {
682 return snapshotBytes;
685 public int incrementOffset() {
687 // if prev chunk failed, we would want to sent the same chunk again
688 offset = offset + context.getConfigParams().getSnapshotChunkSize();
693 public int incrementChunkIndex() {
695 // if prev chunk failed, we would want to sent the same chunk again
696 chunkIndex = chunkIndex + 1;
701 public int getChunkIndex() {
705 public int getTotalChunks() {
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;
714 public boolean isLastChunk(int chunkIndex) {
715 return totalChunks == chunkIndex;
718 public void markSendStatus(boolean success) {
720 // if the chunk sent was successful
721 replyReceivedForOffset = offset;
723 lastChunkHashCode = nextChunkHashCode;
725 // if the chunk sent was failure
726 replyReceivedForOffset = offset;
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;
738 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
739 size = snapshotLength - start;
743 if(LOG.isDebugEnabled()) {
744 LOG.debug("length={}, offset={},size={}",
745 snapshotLength, start, size);
747 ByteString substring = getSnapshotBytes().substring(start, start + size);
748 nextChunkHashCode = substring.hashCode();
753 * reset should be called when the Follower needs to be sent the snapshot from the beginning
758 replyReceivedForOffset = offset;
759 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
760 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
763 public int getLastChunkHashCode() {
764 return lastChunkHashCode;
768 // called from example-actor for printing the follower-states
769 public String printFollowerStates() {
770 final StringBuilder sb = new StringBuilder();
773 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
775 sb.append(followerLogInformation.getId());
776 sb.append(" state:");
777 sb.append(followerLogInformation.isFollowerActive());
782 return sb.toString();
786 public FollowerLogInformation getFollower(String followerId) {
787 return followerToLog.get(followerId);
791 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
792 mapFollowerToSnapshot.put(followerId, snapshot);
796 public int followerSnapshotSize() {
797 return mapFollowerToSnapshot.size();
801 public int followerLogSize() {
802 return followerToLog.size();