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 org.opendaylight.controller.cluster.raft.ClientRequestTracker;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
31 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
33 import org.opendaylight.controller.cluster.raft.RaftActorContext;
34 import org.opendaylight.controller.cluster.raft.RaftState;
35 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
36 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
37 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
38 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
39 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
40 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
41 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
42 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
43 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
44 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
45 import scala.concurrent.duration.FiniteDuration;
48 * The behavior of a RaftActor when it is in the Leader state
52 * <li> Upon election: send initial empty AppendEntries RPCs
53 * (heartbeat) to each server; repeat during idle periods to
54 * prevent election timeouts (§5.2)
55 * <li> If command received from client: append entry to local log,
56 * respond after entry applied to state machine (§5.3)
57 * <li> If last log index ≥ nextIndex for a follower: send
58 * AppendEntries RPC with log entries starting at nextIndex
60 * <li> If successful: update nextIndex and matchIndex for
62 * <li> If AppendEntries fails because of log inconsistency:
63 * decrement nextIndex and retry (§5.3)
65 * <li> If there exists an N such that N > commitIndex, a majority
66 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
67 * set commitIndex = N (§5.3, §5.4).
69 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
71 // The index of the first chunk that is sent when installing a snapshot
72 public static final int FIRST_CHUNK_INDEX = 1;
74 // The index that the follower should respond with if it needs the install snapshot to be reset
75 public static final int INVALID_CHUNK_INDEX = -1;
77 // This would be passed as the hash code of the last chunk when sending the first chunk
78 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
80 private final Map<String, FollowerLogInformation> followerToLog;
81 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
83 private Cancellable heartbeatSchedule = null;
85 private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
87 protected final int minReplicationCount;
89 protected final int minIsolatedLeaderPeerCount;
91 private Optional<ByteString> snapshot;
93 public AbstractLeader(RaftActorContext context) {
94 super(context, RaftState.Leader);
96 final Builder<String, FollowerLogInformation> ftlBuilder = ImmutableMap.builder();
97 for (String followerId : context.getPeerAddresses().keySet()) {
98 FollowerLogInformation followerLogInformation =
99 new FollowerLogInformationImpl(followerId, -1, context);
101 ftlBuilder.put(followerId, followerLogInformation);
103 followerToLog = ftlBuilder.build();
105 leaderId = context.getId();
107 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
109 minReplicationCount = getMajorityVoteCount(getFollowerIds().size());
111 // the isolated Leader peer count will be 1 less than the majority vote count.
112 // this is because the vote count has the self vote counted in it
114 // 0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
115 // 2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
116 // 4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
117 minIsolatedLeaderPeerCount = minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
119 snapshot = Optional.absent();
121 // Immediately schedule a heartbeat
122 // Upon election: send initial empty AppendEntries RPCs
123 // (heartbeat) to each server; repeat during idle periods to
124 // prevent election timeouts (§5.2)
125 sendAppendEntries(0, false);
127 // It is important to schedule this heartbeat here
128 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
132 * Return an immutable collection of follower identifiers.
134 * @return Collection of follower IDs
136 public final Collection<String> getFollowerIds() {
137 return followerToLog.keySet();
141 void setSnapshot(Optional<ByteString> snapshot) {
142 this.snapshot = snapshot;
146 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
147 AppendEntries appendEntries) {
149 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
155 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
156 AppendEntriesReply appendEntriesReply) {
158 if(LOG.isTraceEnabled()) {
159 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
162 // Update the FollowerLogInformation
163 String followerId = appendEntriesReply.getFollowerId();
164 FollowerLogInformation followerLogInformation =
165 followerToLog.get(followerId);
167 if(followerLogInformation == null){
168 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
172 if(followerLogInformation.timeSinceLastActivity() >
173 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
174 LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
175 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
176 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
177 context.getLastApplied(), context.getCommitIndex());
180 followerLogInformation.markFollowerActive();
182 boolean updated = false;
183 if (appendEntriesReply.isSuccess()) {
184 updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
185 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
187 if(updated && LOG.isDebugEnabled()) {
188 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}", logName(),
189 followerId, followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
192 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
194 // TODO: When we find that the follower is out of sync with the
195 // Leader we simply decrement that followers next index by 1.
196 // Would it be possible to do better than this? The RAFT spec
197 // does not explicitly deal with it but may be something for us to
200 followerLogInformation.decrNextIndex();
203 // Now figure out if this reply warrants a change in the commitIndex
204 // If there exists an N such that N > commitIndex, a majority
205 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
206 // set commitIndex = N (§5.3, §5.4).
207 for (long N = context.getCommitIndex() + 1; ; N++) {
208 int replicatedCount = 1;
210 for (FollowerLogInformation info : followerToLog.values()) {
211 if (info.getMatchIndex() >= N) {
216 if (replicatedCount >= minReplicationCount) {
217 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
218 if (replicatedLogEntry != null &&
219 replicatedLogEntry.getTerm() == currentTerm()) {
220 context.setCommitIndex(N);
227 // Apply the change to the state machine
228 if (context.getCommitIndex() > context.getLastApplied()) {
229 if(LOG.isDebugEnabled()) {
230 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
231 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
234 applyLogToStateMachine(context.getCommitIndex());
237 if (!context.getSnapshotManager().isCapturing()) {
241 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
242 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
246 private void purgeInMemoryLog() {
247 //find the lowest index across followers which has been replicated to all.
248 // lastApplied if there are no followers, so that we keep clearing the log for single-node
249 // we would delete the in-mem log from that index on, in-order to minimize mem usage
250 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
251 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
252 for (FollowerLogInformation info : followerToLog.values()) {
253 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
256 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
260 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
261 final Iterator<ClientRequestTracker> it = trackerList.iterator();
262 while (it.hasNext()) {
263 final ClientRequestTracker t = it.next();
264 if (t.getIndex() == logIndex) {
274 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
275 for (ClientRequestTracker tracker : trackerList) {
276 if (tracker.getIndex() == logIndex) {
284 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
285 RequestVoteReply requestVoteReply) {
289 protected void beforeSendHeartbeat(){}
292 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
293 Preconditions.checkNotNull(sender, "sender should not be null");
295 Object message = fromSerializableMessage(originalMessage);
297 if (message instanceof RaftRPC) {
298 RaftRPC rpc = (RaftRPC) message;
299 // If RPC request or response contains term T > currentTerm:
300 // set currentTerm = T, convert to follower (§5.1)
301 // This applies to all RPC messages and responses
302 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
303 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
304 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
306 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
308 return switchBehavior(new Follower(context));
312 if (message instanceof SendHeartBeat) {
313 beforeSendHeartbeat();
315 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
318 } else if(message instanceof SendInstallSnapshot) {
319 // received from RaftActor
320 setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
321 sendInstallSnapshot();
323 } else if (message instanceof Replicate) {
324 replicate((Replicate) message);
326 } else if (message instanceof InstallSnapshotReply){
327 handleInstallSnapshotReply((InstallSnapshotReply) message);
332 return super.handleMessage(sender, message);
335 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
336 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
338 String followerId = reply.getFollowerId();
339 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
341 if (followerToSnapshot == null) {
342 LOG.error("{}: FollowerId {} in InstallSnapshotReply not known to Leader",
343 logName(), followerId);
347 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
348 followerLogInformation.markFollowerActive();
350 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
351 boolean wasLastChunk = false;
352 if (reply.isSuccess()) {
353 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
354 //this was the last chunk reply
355 if(LOG.isDebugEnabled()) {
356 LOG.debug("{}: InstallSnapshotReply received, " +
357 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
358 logName(), reply.getChunkIndex(), followerId,
359 context.getReplicatedLog().getSnapshotIndex() + 1
363 followerLogInformation.setMatchIndex(
364 context.getReplicatedLog().getSnapshotIndex());
365 followerLogInformation.setNextIndex(
366 context.getReplicatedLog().getSnapshotIndex() + 1);
367 mapFollowerToSnapshot.remove(followerId);
369 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
370 logName(), followerId, followerLogInformation.getMatchIndex(),
371 followerLogInformation.getNextIndex());
373 if (mapFollowerToSnapshot.isEmpty()) {
374 // once there are no pending followers receiving snapshots
375 // we can remove snapshot from the memory
376 setSnapshot(Optional.<ByteString>absent());
381 followerToSnapshot.markSendStatus(true);
384 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
385 logName(), reply.getChunkIndex());
387 followerToSnapshot.markSendStatus(false);
390 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
391 // Since the follower is now caught up try to purge the log.
393 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
394 ActorSelection followerActor = context.getPeerActorSelection(followerId);
395 if(followerActor != null) {
396 sendSnapshotChunk(followerActor, followerId);
401 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
402 logName(), reply.getChunkIndex(), followerId,
403 followerToSnapshot.getChunkIndex());
405 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
406 // Since the Follower did not find this index to be valid we should reset the follower snapshot
407 // so that Installing the snapshot can resume from the beginning
408 followerToSnapshot.reset();
413 private void replicate(Replicate replicate) {
414 long logIndex = replicate.getReplicatedLogEntry().getIndex();
416 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
417 replicate.getIdentifier(), logIndex);
419 // Create a tracker entry we will use this later to notify the
422 new ClientRequestTrackerImpl(replicate.getClientActor(),
423 replicate.getIdentifier(),
427 if (followerToLog.isEmpty()) {
428 context.setCommitIndex(logIndex);
429 applyLogToStateMachine(logIndex);
431 sendAppendEntries(0, false);
435 private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
436 // Send an AppendEntries to all followers
437 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
438 final String followerId = e.getKey();
439 final FollowerLogInformation followerLogInformation = e.getValue();
440 // This checks helps not to send a repeat message to the follower
441 if(!followerLogInformation.isFollowerActive() ||
442 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
443 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
450 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
451 * sending next snapshot chunk, and initiating a snapshot.
452 * @return true if any update is sent, false otherwise
455 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
456 boolean sendHeartbeat, boolean isHeartbeat) {
458 ActorSelection followerActor = context.getPeerActorSelection(followerId);
459 if (followerActor != null) {
460 long followerNextIndex = followerLogInformation.getNextIndex();
461 boolean isFollowerActive = followerLogInformation.isFollowerActive();
462 boolean sendAppendEntries = false;
463 List<ReplicatedLogEntry> entries = Collections.emptyList();
465 if (mapFollowerToSnapshot.get(followerId) != null) {
466 // if install snapshot is in process , then sent next chunk if possible
467 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
468 sendSnapshotChunk(followerActor, followerId);
469 } else if(sendHeartbeat) {
470 // we send a heartbeat even if we have not received a reply for the last chunk
471 sendAppendEntries = true;
474 long leaderLastIndex = context.getReplicatedLog().lastIndex();
475 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
477 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
478 LOG.debug("{}: Checking sendAppendEntries for follower {}, followerNextIndex {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
479 logName(), followerId, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
482 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
484 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
485 followerNextIndex, followerId);
487 // FIXME : Sending one entry at a time
488 if(followerLogInformation.okToReplicate()) {
489 entries = context.getReplicatedLog().getFrom(followerNextIndex, 1);
490 sendAppendEntries = true;
492 } else if (isFollowerActive && followerNextIndex >= 0 &&
493 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
494 // if the followers next index is not present in the leaders log, and
495 // if the follower is just not starting and if leader's index is more than followers index
496 // then snapshot should be sent
498 if (LOG.isDebugEnabled()) {
499 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
500 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
501 "leader-last-index: %d", logName(), followerId,
502 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
505 // Send heartbeat to follower whenever install snapshot is initiated.
506 sendAppendEntries = true;
507 initiateCaptureSnapshot(followerId, followerNextIndex);
509 } else if(sendHeartbeat) {
510 // we send an AppendEntries, even if the follower is inactive
511 // in-order to update the followers timestamp, in case it becomes active again
512 sendAppendEntries = true;
517 if(sendAppendEntries) {
518 sendAppendEntriesToFollower(followerActor, followerNextIndex,
519 entries, followerId);
524 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
525 List<ReplicatedLogEntry> entries, String followerId) {
526 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
527 prevLogIndex(followerNextIndex),
528 prevLogTerm(followerNextIndex), entries,
529 context.getCommitIndex(), super.getReplicatedToAllIndex());
531 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
532 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
536 followerActor.tell(appendEntries.toSerializable(), actor());
540 * Install Snapshot works as follows
541 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
542 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
543 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
544 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
545 * 4. On complete, Follower sends back a InstallSnapshotReply.
546 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
547 * and replenishes the memory by deleting the snapshot in Replicated log.
548 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
549 * then send the existing snapshot in chunks to the follower.
551 * @param followerNextIndex
553 private void initiateCaptureSnapshot(String followerId, long followerNextIndex) {
554 if (!context.getReplicatedLog().isPresent(followerNextIndex) &&
555 context.getReplicatedLog().isInSnapshot(followerNextIndex)) {
557 if (snapshot.isPresent()) {
558 // if a snapshot is present in the memory, most likely another install is in progress
559 // no need to capture snapshot.
560 // This could happen if another follower needs an install when one is going on.
561 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
562 sendSnapshotChunk(followerActor, followerId);
566 context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
567 this.getReplicatedToAllIndex(), followerId);
573 private void sendInstallSnapshot() {
574 LOG.debug("{}: sendInstallSnapshot", logName());
575 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
576 ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
578 if (followerActor != null) {
579 long nextIndex = e.getValue().getNextIndex();
581 if (!context.getReplicatedLog().isPresent(nextIndex) &&
582 context.getReplicatedLog().isInSnapshot(nextIndex)) {
583 sendSnapshotChunk(followerActor, e.getKey());
590 * Sends a snapshot chunk to a given follower
591 * InstallSnapshot should qualify as a heartbeat too.
593 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
595 if (snapshot.isPresent()) {
596 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId,snapshot.get());
598 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
599 // followerId to the followerToSnapshot map.
600 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
603 new InstallSnapshot(currentTerm(), context.getId(),
604 context.getReplicatedLog().getSnapshotIndex(),
605 context.getReplicatedLog().getSnapshotTerm(),
607 followerToSnapshot.incrementChunkIndex(),
608 followerToSnapshot.getTotalChunks(),
609 Optional.of(followerToSnapshot.getLastChunkHashCode())
614 if(LOG.isDebugEnabled()) {
615 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
616 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
617 followerToSnapshot.getTotalChunks());
620 } catch (IOException e) {
621 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
626 * Acccepts snaphot as ByteString, enters into map for future chunks
627 * creates and return a ByteString chunk
629 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
630 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
631 if (followerToSnapshot == null) {
632 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
633 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
635 ByteString nextChunk = followerToSnapshot.getNextChunk();
637 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
642 private void sendHeartBeat() {
643 if (!followerToLog.isEmpty()) {
644 LOG.trace("{}: Sending heartbeat", logName());
645 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
649 private void stopHeartBeat() {
650 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
651 heartbeatSchedule.cancel();
655 private void scheduleHeartBeat(FiniteDuration interval) {
656 if (followerToLog.isEmpty()) {
657 // Optimization - do not bother scheduling a heartbeat as there are
664 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
665 // message is sent to itself.
666 // Scheduling the heartbeat only once here because heartbeats do not
667 // need to be sent if there are other messages being sent to the remote
669 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
670 interval, context.getActor(), new SendHeartBeat(),
671 context.getActorSystem().dispatcher(), context.getActor());
675 public void close() throws Exception {
680 public String getLeaderId() {
681 return context.getId();
684 protected boolean isLeaderIsolated() {
685 int minPresent = minIsolatedLeaderPeerCount;
686 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
687 if (followerLogInformation.isFollowerActive()) {
689 if (minPresent == 0) {
694 return (minPresent != 0);
698 * Encapsulates the snapshot bytestring and handles the logic of sending
701 protected class FollowerToSnapshot {
702 private final ByteString snapshotBytes;
703 private int offset = 0;
704 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
705 private int replyReceivedForOffset;
706 // if replyStatus is false, the previous chunk is attempted
707 private boolean replyStatus = false;
708 private int chunkIndex;
709 private final int totalChunks;
710 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
711 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
713 public FollowerToSnapshot(ByteString snapshotBytes) {
714 this.snapshotBytes = snapshotBytes;
715 int size = snapshotBytes.size();
716 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
717 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
718 if(LOG.isDebugEnabled()) {
719 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
720 logName(), size, totalChunks);
722 replyReceivedForOffset = -1;
723 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
726 public ByteString getSnapshotBytes() {
727 return snapshotBytes;
730 public int incrementOffset() {
732 // if prev chunk failed, we would want to sent the same chunk again
733 offset = offset + context.getConfigParams().getSnapshotChunkSize();
738 public int incrementChunkIndex() {
740 // if prev chunk failed, we would want to sent the same chunk again
741 chunkIndex = chunkIndex + 1;
746 public int getChunkIndex() {
750 public int getTotalChunks() {
754 public boolean canSendNextChunk() {
755 // we only send a false if a chunk is sent but we have not received a reply yet
756 return replyReceivedForOffset == offset;
759 public boolean isLastChunk(int chunkIndex) {
760 return totalChunks == chunkIndex;
763 public void markSendStatus(boolean success) {
765 // if the chunk sent was successful
766 replyReceivedForOffset = offset;
768 lastChunkHashCode = nextChunkHashCode;
770 // if the chunk sent was failure
771 replyReceivedForOffset = offset;
776 public ByteString getNextChunk() {
777 int snapshotLength = getSnapshotBytes().size();
778 int start = incrementOffset();
779 int size = context.getConfigParams().getSnapshotChunkSize();
780 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
781 size = snapshotLength;
783 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
784 size = snapshotLength - start;
789 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
790 snapshotLength, start, size);
792 ByteString substring = getSnapshotBytes().substring(start, start + size);
793 nextChunkHashCode = substring.hashCode();
798 * reset should be called when the Follower needs to be sent the snapshot from the beginning
803 replyReceivedForOffset = offset;
804 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
805 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
808 public int getLastChunkHashCode() {
809 return lastChunkHashCode;
813 // called from example-actor for printing the follower-states
814 public String printFollowerStates() {
815 final StringBuilder sb = new StringBuilder();
818 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
820 sb.append(followerLogInformation.getId());
821 sb.append(" state:");
822 sb.append(followerLogInformation.isFollowerActive());
827 return sb.toString();
831 public FollowerLogInformation getFollower(String followerId) {
832 return followerToLog.get(followerId);
836 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
837 mapFollowerToSnapshot.put(followerId, snapshot);
841 public int followerSnapshotSize() {
842 return mapFollowerToSnapshot.size();
846 public int followerLogSize() {
847 return followerToLog.size();