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.protobuf.ByteString;
13 import java.util.Arrays;
14 import org.slf4j.Logger;
17 * SnapshotTracker does house keeping for a snapshot that is being installed in chunks on the Follower
19 public class SnapshotTracker {
20 private final Logger LOG;
21 private final int totalChunks;
22 private ByteString collectedChunks = ByteString.EMPTY;
23 private int lastChunkIndex = AbstractLeader.FIRST_CHUNK_INDEX - 1;
24 private boolean sealed = false;
25 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
27 SnapshotTracker(Logger LOG, int totalChunks){
29 this.totalChunks = totalChunks;
33 * Adds a chunk to the tracker
37 * @return true when the lastChunk is received
38 * @throws InvalidChunkException
40 boolean addChunk(int chunkIndex, byte[] chunk, Optional<Integer> lastChunkHashCode) throws InvalidChunkException{
41 LOG.debug("addChunk: chunkIndex={}, lastChunkIndex={}, collectedChunks.size={}, lastChunkHashCode={}",
42 chunkIndex, lastChunkIndex, collectedChunks.size(), this.lastChunkHashCode);
45 throw new InvalidChunkException("Invalid chunk received with chunkIndex " + chunkIndex + " all chunks already received");
48 if(lastChunkIndex + 1 != chunkIndex){
49 throw new InvalidChunkException("Expected chunkIndex " + (lastChunkIndex + 1) + " got " + chunkIndex);
52 if(lastChunkHashCode.isPresent()){
53 if(lastChunkHashCode.get() != this.lastChunkHashCode){
54 throw new InvalidChunkException("The hash code of the recorded last chunk does not match " +
55 "the senders hash code, expected " + this.lastChunkHashCode + " was " + lastChunkHashCode.get());
59 sealed = (chunkIndex == totalChunks);
60 lastChunkIndex = chunkIndex;
61 collectedChunks = collectedChunks.concat(ByteString.copyFrom(chunk));
62 this.lastChunkHashCode = Arrays.hashCode(chunk);
68 throw new IllegalStateException("lastChunk not received yet");
71 return collectedChunks.toByteArray();
74 ByteString getCollectedChunks(){
75 return collectedChunks;
78 public static class InvalidChunkException extends Exception {
79 private static final long serialVersionUID = 1L;
81 InvalidChunkException(String message){