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 com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.protobuf.ByteString;
14 import java.util.Arrays;
15 import org.slf4j.Logger;
18 * SnapshotTracker does house keeping for a snapshot that is being installed in chunks on the Follower
20 public class SnapshotTracker {
21 private final Logger LOG;
22 private final int totalChunks;
23 private final String leaderId;
24 private ByteString collectedChunks = ByteString.EMPTY;
25 private int lastChunkIndex = LeaderInstallSnapshotState.FIRST_CHUNK_INDEX - 1;
26 private boolean sealed = false;
27 private int lastChunkHashCode = LeaderInstallSnapshotState.INITIAL_LAST_CHUNK_HASH_CODE;
29 SnapshotTracker(Logger LOG, int totalChunks, String leaderId) {
31 this.totalChunks = totalChunks;
32 this.leaderId = Preconditions.checkNotNull(leaderId);
36 * Adds a chunk to the tracker
40 * @return true when the lastChunk is received
41 * @throws InvalidChunkException
43 boolean addChunk(int chunkIndex, byte[] chunk, Optional<Integer> lastChunkHashCode) throws InvalidChunkException{
44 LOG.debug("addChunk: chunkIndex={}, lastChunkIndex={}, collectedChunks.size={}, lastChunkHashCode={}",
45 chunkIndex, lastChunkIndex, collectedChunks.size(), this.lastChunkHashCode);
48 throw new InvalidChunkException("Invalid chunk received with chunkIndex " + chunkIndex + " all chunks already received");
51 if(lastChunkIndex + 1 != chunkIndex){
52 throw new InvalidChunkException("Expected chunkIndex " + (lastChunkIndex + 1) + " got " + chunkIndex);
55 if(lastChunkHashCode.isPresent()){
56 if(lastChunkHashCode.get() != this.lastChunkHashCode){
57 throw new InvalidChunkException("The hash code of the recorded last chunk does not match " +
58 "the senders hash code, expected " + this.lastChunkHashCode + " was " + lastChunkHashCode.get());
62 sealed = chunkIndex == totalChunks;
63 lastChunkIndex = chunkIndex;
64 collectedChunks = collectedChunks.concat(ByteString.copyFrom(chunk));
65 this.lastChunkHashCode = Arrays.hashCode(chunk);
71 throw new IllegalStateException("lastChunk not received yet");
74 return collectedChunks.toByteArray();
77 ByteString getCollectedChunks(){
78 return collectedChunks;
81 String getLeaderId() {
85 public static class InvalidChunkException extends Exception {
86 private static final long serialVersionUID = 1L;
88 InvalidChunkException(String message){