HCOLL-378 #36 Add ChronicleHashBuilder.recoverPersistedTo() and ChronicleHashInstanceBuilder.recover() functionality

This commit is contained in:
leventov
2016-01-04 23:24:39 +03:00
parent b4c97ced36
commit 97e4c12de1
31 changed files with 1026 additions and 121 deletions
@@ -24,6 +24,7 @@ import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.hash.ChronicleHashBuilder;
import net.openhft.chronicle.hash.ChronicleHashBuilderPrivateAPI;
import net.openhft.chronicle.hash.ChronicleHashInstanceBuilder;
import net.openhft.chronicle.hash.ChronicleHashRecoveryFailedException;
import net.openhft.chronicle.hash.impl.CompactOffHeapLinearHashTable;
import net.openhft.chronicle.hash.impl.stage.entry.ChecksumStrategy;
import net.openhft.chronicle.hash.impl.util.math.PoissonDistribution;
@@ -47,7 +48,6 @@ import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.lang.Double.isNaN;
import static java.lang.Math.round;
@@ -267,6 +267,7 @@ public final class ChronicleMapBuilder<K, V> implements
* @deprecated don't use private API in the client code
*/
@Override
@Deprecated
public ChronicleHashBuilderPrivateAPI<K> privateAPI() {
return privateAPI;
}
@@ -1358,8 +1359,7 @@ public final class ChronicleMapBuilder<K, V> implements
@Override
public ChronicleHashInstanceBuilder<ChronicleMap<K, V>> instance() {
return new MapInstanceBuilder<>(this.clone(), singleHashReplication, null, null, null,
new AtomicBoolean(false));
return new MapInstanceBuilder<>(this.clone(), singleHashReplication);
}
@Override
@@ -1367,7 +1367,13 @@ public final class ChronicleMapBuilder<K, V> implements
// clone() to make this builder instance thread-safe, because createWithFile() method
// computes some state based on configurations, but doesn't synchronize on configuration
// changes.
return clone().createWithFile(file, singleHashReplication, null);
return clone().createWithFile(file, singleHashReplication, null, false, false);
}
@Override
public ChronicleMap<K, V> recoverPersistedTo(File file, boolean sameBuilderConfig)
throws IOException {
return clone().createWithFile(file, singleHashReplication, null, true, sameBuilderConfig);
}
@Override
@@ -1378,9 +1384,12 @@ public final class ChronicleMapBuilder<K, V> implements
return clone().createWithoutFile(singleHashReplication, null);
}
ChronicleMap<K, V> create(MapInstanceBuilder<K, V> ib) throws IOException {
ChronicleMap<K, V> create(
MapInstanceBuilder<K, V> ib, boolean recover, boolean sameBuilderConfig)
throws IOException {
if (ib.file != null) {
return createWithFile(ib.file, ib.singleHashReplication, ib.channel);
return createWithFile(
ib.file, ib.singleHashReplication, ib.channel, recover, sameBuilderConfig);
} else {
return createWithoutFile(ib.singleHashReplication, ib.channel);
}
@@ -1388,7 +1397,10 @@ public final class ChronicleMapBuilder<K, V> implements
ChronicleMap<K, V> createWithFile(
File file, SingleChronicleHashReplication singleHashReplication,
ReplicationChannel channel) throws IOException {
ReplicationChannel channel,
boolean recover, boolean overrideBuilderConfig) throws IOException {
if (overrideBuilderConfig && !recover)
throw new AssertionError("recover -> overrideBuilderConfig");
replicated = singleHashReplication != null || channel != null;
persisted = true;
@@ -1397,6 +1409,12 @@ public final class ChronicleMapBuilder<K, V> implements
if (fileLength > 0) {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
FileChannel fileChannel = raf.getChannel();
int headerSize = 0;
if (overrideBuilderConfig) {
VanillaChronicleMap<K, V, ?> mapObjectForHeaderOverwrite =
newMap(singleHashReplication, channel);
headerSize = writeHeader(fileChannel, mapObjectForHeaderOverwrite);
}
ByteBuffer headerBuffer = ByteBuffer.allocate(MAX_BOOTSTRAPPING_HEADER_SIZE);
while (headerBuffer.remaining() > 0 &&
headerBuffer.position() < fileChannel.size()) {
@@ -1408,24 +1426,42 @@ public final class ChronicleMapBuilder<K, V> implements
headerBytes.readLimit(headerBuffer.limit());
Wire wire = new BinaryWire(headerBytes);
VanillaChronicleMap<K, V, ?> map = wire.getValueIn().typedMarshallable();
map.initTransientsFromBuilder(this);
initTransientsFromReplication(map, singleHashReplication, channel);
map.initBeforeMapping(fileChannel, headerBytes.readPosition());
long readHeaderSize = headerBytes.readPosition();
if (overrideBuilderConfig && headerSize != readHeaderSize) {
throw new ChronicleHashRecoveryFailedException("read header size " +
readHeaderSize + " != overwritten header size " + headerSize);
}
map.initBeforeMapping(file, fileChannel, readHeaderSize);
long expectedFileLength = map.expectedFileSize();
if (expectedFileLength != fileLength) {
if (!recover && expectedFileLength != fileLength) {
throw new IOException("The file " + file + " the map is serialized from " +
"has unexpected length " + fileLength + ", probably corrupted. " +
"Expected length is " + expectedFileLength);
}
map.createMappedStoreAndSegments(file, raf);
map.initTransientsFromBuilder(this);
initTransientsFromReplication(map, singleHashReplication, channel);
if (!recover) {
map.createMappedStoreAndSegments(file, raf);
} else {
map.recover(file, raf);
}
establishReplication(map, singleHashReplication, channel);
fileChannel.force(true);
// TODO according to Self Boostrapping Data spec, should write "init complete"
// byte *after* the above force instruction, see HCOLL-396
return map;
} catch (Exception e) {
if (recover && !(e instanceof IOException))
throw new ChronicleHashRecoveryFailedException(e);
throw e;
}
}
if (recover)
throw new FileNotFoundException("file " + file + " should exist for recovery");
if (file.createNewFile() || fileLength == 0) {
break;
}
@@ -1443,21 +1479,28 @@ public final class ChronicleMapBuilder<K, V> implements
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
FileChannel fileChannel = raf.getChannel();
ByteBuffer headerBuffer = ByteBuffer.allocate(MAX_BOOTSTRAPPING_HEADER_SIZE);
Bytes<ByteBuffer> headerBytes = Bytes.wrapForWrite(headerBuffer);
Wire wire = new BinaryWire(headerBytes);
wire.getValueOut().typedMarshallable(map);
int headerSize = writeHeader(fileChannel, map);
map.initBeforeMapping(file, fileChannel, headerSize);
int headerSize = (int) headerBytes.writePosition();
headerBuffer.limit(headerSize);
while (headerBuffer.remaining() > 0) {
fileChannel.write(headerBuffer, headerBuffer.position());
}
map.initBeforeMapping(fileChannel, headerSize);
map.createMappedStoreAndSegments(file, raf);
establishReplication(map, singleHashReplication, channel);
return map;
}
}
return establishReplication(map, singleHashReplication, channel);
private static <K, V> int writeHeader(FileChannel fileChannel, VanillaChronicleMap<K, V, ?> map)
throws IOException {
ByteBuffer headerBuffer = ByteBuffer.allocate(MAX_BOOTSTRAPPING_HEADER_SIZE);
Bytes<ByteBuffer> headerBytes = Bytes.wrapForWrite(headerBuffer);
Wire wire = new BinaryWire(headerBytes);
wire.getValueOut().typedMarshallable(map);
int headerSize = (int) headerBytes.writePosition();
headerBuffer.limit(headerSize);
while (headerBuffer.remaining() > 0) {
fileChannel.write(headerBuffer, headerBuffer.position());
}
return headerSize;
}
private static void initTransientsFromReplication(
@@ -1492,7 +1535,8 @@ public final class ChronicleMapBuilder<K, V> implements
BytesStore bytesStore =
lazyNativeBytesStoreWithFixedCapacity(map.sizeInBytesWithoutTiers());
map.createMappedStoreAndSegments(bytesStore);
return establishReplication(map, singleHashReplication, channel);
establishReplication(map, singleHashReplication, channel);
return map;
} catch (IOException e) {
// file-less version should never trigger an IOException.
throw new AssertionError(e);
@@ -1552,7 +1596,7 @@ public final class ChronicleMapBuilder<K, V> implements
&& actualChunkSize > 0;
}
private ChronicleMap<K, V> establishReplication(
private void establishReplication(
VanillaChronicleMap<K, V, ?> map,
SingleChronicleHashReplication singleHashReplication,
ReplicationChannel channel) throws IOException {
@@ -1591,7 +1635,6 @@ public final class ChronicleMapBuilder<K, V> implements
result.addCloseable(token);
}
}
return map;
}
private void establishCleanupThread(ReplicatedChronicleMap map) {
@@ -24,7 +24,6 @@ import net.openhft.chronicle.hash.replication.TcpTransportAndNetworkConfig;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicBoolean;
final class MapInstanceBuilder<K, V>
implements ChronicleHashInstanceBuilder<ChronicleMap<K, V>>, Serializable {
@@ -35,18 +34,12 @@ final class MapInstanceBuilder<K, V>
transient File file;
String name;
final AtomicBoolean used;
volatile boolean used = false;
MapInstanceBuilder(ChronicleMapBuilder<K, V> mapBuilder,
SingleChronicleHashReplication singleHashReplication,
ReplicationChannel channel,
File file, String name, AtomicBoolean used) {
SingleChronicleHashReplication singleHashReplication) {
this.mapBuilder = mapBuilder;
this.singleHashReplication = singleHashReplication;
this.channel = channel;
this.file = file;
this.name = name;
this.used = used;
}
@Override
@@ -84,14 +77,35 @@ final class MapInstanceBuilder<K, V>
@Override
public synchronized ChronicleMap<K, V> create() throws IOException {
if (!used.getAndSet(true)) {
return mapBuilder.create(this);
if (!used) {
ChronicleMap<K, V> map = mapBuilder.create(this, false, false);
// Set used = true, if map created successfully.
// If exception is thrown in mapBuilder.create(), the next line is not executed.
used = true;
return map;
} else {
throw new IllegalStateException(
"A ChronicleMap has already been created using this instance config chain. " +
"Create a new instance config (builder.instance()) to create a new " +
"ChronicleMap instance");
throw alreadyCreated();
}
}
@Override
public synchronized ChronicleMap<K, V> recover(boolean sameBuilderConfig) throws IOException {
if (file == null)
throw new IllegalStateException("persistedTo(file) must be configured for " +
"ChronicleHashInstanceBuilder, for recover()");
if (!used) {
ChronicleMap<K, V> map = mapBuilder.create(this, true, sameBuilderConfig);
used = true;
return map;
} else {
throw alreadyCreated();
}
}
private static IllegalStateException alreadyCreated() {
return new IllegalStateException(
"A ChronicleHash has already been created using this " +
"ChronicleHashInstanceBuilder. Create a new instance builder " +
"(chronicleHashBuilder.instance()) to create another Chronicle Hash");
}
}
@@ -172,7 +172,7 @@ public class ReplicatedChronicleMap<K, V, R> extends VanillaChronicleMap<K, V, R
}
@Override
protected ReplicatedGlobalMutableState globalMutableState() {
public ReplicatedGlobalMutableState globalMutableState() {
return (ReplicatedGlobalMutableState) super.globalMutableState();
}
@@ -340,6 +340,15 @@ public class ReplicatedChronicleMap<K, V, R> extends VanillaChronicleMap<K, V, R
}
}
public ModificationIterator[] acquireAllModificationIterators() {
for (int remoteIdentifier = 0; remoteIdentifier < 128; remoteIdentifier++) {
if (globalMutableState().getModificationIteratorInitAt(remoteIdentifier)) {
acquireModificationIterator((byte) remoteIdentifier);
}
}
return assignedModificationIterators;
}
public void raiseChange(long tierIndex, long pos) {
// -1 is invalid remoteIdentifier => raise change for all
raiseChangeForAllExcept(tierIndex, pos, (byte) -1);
@@ -601,7 +610,7 @@ public class ReplicatedChronicleMap<K, V, R> extends VanillaChronicleMap<K, V, R
*
* @author Rob Austin.
*/
class ModificationIterator implements Replica.ModificationIterator {
public class ModificationIterator implements Replica.ModificationIterator {
private final byte remoteIdentifier;
private final long segmentBitSetsAddr;
private final long offsetToBitSetsWithinATierBulk;
@@ -926,5 +935,22 @@ public class ReplicatedChronicleMap<K, V, R> extends VanillaChronicleMap<K, V, R
dropChangeInTierBulk(bulkIndex, offsetToTierBitSet, pos);
}
}
public void clearRange0(long tierIndex, long pos, long endPosExclusive) {
if (tierIndex <= actualSegments) {
long segmentIndex = tierIndex - 1;
long offsetToTierBitSet = segmentIndex * tierModIterBitSetOuterSize;
tierModIterFrame.clearRange(nativeAccess(), null,
segmentBitSetsAddr + offsetToTierBitSet, pos, endPosExclusive);
} else {
long extraTierIndex = tierIndex - 1 - actualSegments;
int bulkIndex = (int) (extraTierIndex >> log2TiersInBulk);
long offsetToTierBitSet =
(extraTierIndex & (tiersInBulk - 1)) * tierModIterBitSetOuterSize;
TierBulkData tierBulkData = tierBulkOffsets.get(bulkIndex);
long bitSetAddr = bitSetsAddr(tierBulkData) + offsetToTierBitSet;
tierModIterFrame.clearRange(nativeAccess(), null, bitSetAddr, pos, endPosExclusive);
}
}
}
}
@@ -36,8 +36,10 @@ import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
@@ -148,6 +150,11 @@ public class VanillaChronicleMap<K, V, R>
initOwnTransients();
}
public void recover(File file, RandomAccessFile raf) throws IOException {
basicRecover(file, raf);
iterationContext().recoverSegments();
}
private void initOwnTransients() {
couldNotDetermineAlignmentBeforeAllocation =
greatestCommonDivisor((int) chunkSize, alignment) != alignment;
@@ -19,8 +19,13 @@ package net.openhft.chronicle.map.impl;
import net.openhft.chronicle.map.MapEntry;
import net.openhft.chronicle.map.MapSegmentContext;
import java.util.List;
import java.util.Set;
public interface IterationContext<K, V, R> extends MapEntry<K, V>, MapSegmentContext<K, V, R> {
long pos();
void initSegmentIndex(int segmentIndex);
void recoverSegments();
}
@@ -21,9 +21,7 @@ import net.openhft.chronicle.hash.impl.stage.entry.*;
import net.openhft.chronicle.hash.impl.stage.hash.KeyBytesInterop;
import net.openhft.chronicle.hash.impl.stage.hash.LogHolder;
import net.openhft.chronicle.hash.impl.stage.hash.OwnerThreadHolder;
import net.openhft.chronicle.hash.impl.stage.iter.IterationAlloc;
import net.openhft.chronicle.hash.impl.stage.iter.IterationKeyHashCode;
import net.openhft.chronicle.hash.impl.stage.iter.IterationSegmentStages;
import net.openhft.chronicle.hash.impl.stage.iter.*;
import net.openhft.chronicle.hash.impl.stage.query.KeySearch;
import net.openhft.chronicle.map.impl.stage.data.bytes.EntryValueBytesData;
import net.openhft.chronicle.map.impl.stage.data.bytes.WrappedValueBytesData;
@@ -61,6 +59,9 @@ import net.openhft.sg.Staged;
MapEntryOperationsDelegation.class,
IterationAlloc.class,
TierRecovery.class,
SegmentsRecovery.class,
}, nested = {
ReadLock.class,
UpdateLock.class,
@@ -24,16 +24,14 @@ import net.openhft.chronicle.hash.impl.stage.hash.OwnerThreadHolder;
import net.openhft.chronicle.hash.impl.stage.iter.IterationAlloc;
import net.openhft.chronicle.hash.impl.stage.iter.IterationKeyHashCode;
import net.openhft.chronicle.hash.impl.stage.iter.IterationSegmentStages;
import net.openhft.chronicle.hash.impl.stage.iter.SegmentsRecovery;
import net.openhft.chronicle.hash.impl.stage.query.KeySearch;
import net.openhft.chronicle.map.impl.stage.data.DummyValueZeroData;
import net.openhft.chronicle.map.impl.stage.data.bytes.EntryValueBytesData;
import net.openhft.chronicle.map.impl.stage.data.bytes.WrappedValueBytesData;
import net.openhft.chronicle.map.impl.stage.data.instance.WrappedValueInstanceDataHolder;
import net.openhft.chronicle.map.impl.stage.entry.ReplicatedMapEntryStages;
import net.openhft.chronicle.map.impl.stage.iter.IterationCheckOnEachPublicOperation;
import net.openhft.chronicle.map.impl.stage.iter.ReplicatedMapAbsentDelegatingForIteration;
import net.openhft.chronicle.map.impl.stage.iter.ReplicatedMapEntryDelegating;
import net.openhft.chronicle.map.impl.stage.iter.ReplicatedMapSegmentIteration;
import net.openhft.chronicle.map.impl.stage.iter.*;
import net.openhft.chronicle.map.impl.stage.map.*;
import net.openhft.chronicle.map.impl.stage.replication.ReplicationUpdate;
import net.openhft.sg.Context;
@@ -68,6 +66,9 @@ import net.openhft.sg.Staged;
DefaultValue.class,
IterationAlloc.class,
ReplicatedTierRecovery.class,
SegmentsRecovery.class,
}, nested = {
ReadLock.class,
UpdateLock.class,
@@ -112,7 +112,7 @@ public abstract class MapEntryStages<K, V> extends HashEntryStages<K>
}
@Override
protected long entryEnd() {
public long entryEnd() {
return valueOffset + valueSize;
}
@@ -26,6 +26,11 @@ import net.openhft.sg.StageRef;
import net.openhft.sg.Staged;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Staged
public abstract class MapSegmentIteration<K, V, R> extends HashSegmentIteration<K, MapEntry<K, V>>
implements MapEntry<K, V>, IterationContext<K, V, R> {
@@ -48,4 +53,15 @@ public abstract class MapSegmentIteration<K, V, R> extends HashSegmentIteration<
public WrappedValueInstanceDataHolderAccess<K, V, ?> context() {
return wrappedValueInstanceDataHolderAccess;
}
//
// @Override
// public void recover(List<Set<Long>> usedTierIndexesBySegment) {
// for (int visitedSegmentIndex = 0; visitedSegmentIndex < usedTierIndexesBySegment.size();
// visitedSegmentIndex++) {
// Set<Long> intersection = new HashSet<>(
// usedTierIndexesBySegment.get(visitedSegmentIndex));
// intersection.retainAll(usedTierIndexes);
// if (Collections.dis)
// }
// }
}
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.map.impl.stage.iter;
import net.openhft.chronicle.algo.bitset.ReusableBitSet;
import net.openhft.chronicle.hash.impl.CompactOffHeapLinearHashTable;
import net.openhft.chronicle.hash.impl.VanillaChronicleHash;
import net.openhft.chronicle.hash.impl.stage.entry.SegmentStages;
import net.openhft.chronicle.hash.impl.stage.hash.LogHolder;
import net.openhft.chronicle.hash.impl.stage.iter.TierRecovery;
import net.openhft.chronicle.map.ReplicatedChronicleMap;
import net.openhft.chronicle.map.impl.ReplicatedChronicleMapHolder;
import net.openhft.chronicle.map.impl.stage.entry.ReplicatedMapEntryStages;
import net.openhft.sg.StageRef;
import net.openhft.sg.Staged;
@Staged
public class ReplicatedTierRecovery extends TierRecovery {
@StageRef ReplicatedChronicleMapHolder<?, ?, ?> rh;
@StageRef SegmentStages s;
@StageRef ReplicatedMapEntryStages<?, ?> e;
@StageRef LogHolder lh;
@Override
public void removeDuplicatesInSegment() {
super.removeDuplicatesInSegment();
recoverTierDeleted();
cleanupModificationIterationBits();
}
private void recoverTierDeleted() {
VanillaChronicleHash<?, ?, ?, ?> h = rh.h();
CompactOffHeapLinearHashTable hl = h.hashLookup;
long hlAddr = s.tierBaseAddr;
long deleted = 0;
long hlPos = 0;
do {
long hlEntry = hl.readEntry(hlAddr, hlPos);
if (!hl.empty(hlEntry)) {
e.readExistingEntry(hl.value(hlEntry));
if (e.entryDeleted()) {
deleted++;
}
}
hlPos = hl.step(hlPos);
} while (hlPos != 0);
if (s.tierDeleted() != deleted) {
lh.LOG.error("wrong deleted counter for tier with index {}, stored: {}, should be: {}",
s.tierIndex, s.tierDeleted(), deleted);
s.tierDeleted(deleted);
}
}
private void cleanupModificationIterationBits() {
ReplicatedChronicleMap<?, ?, ?> m = rh.m();
ReplicatedChronicleMap<?, ?, ?>.ModificationIterator[] its =
m.acquireAllModificationIterators();
ReusableBitSet freeList = s.freeList;
for (long pos = 0;;) {
long nextPos = freeList.nextSetBit(pos);
if (nextPos > pos) {
for (ReplicatedChronicleMap<?, ?, ?>.ModificationIterator it : its) {
it.clearRange0(s.tierIndex, pos, nextPos);
}
}
if (nextPos > 0) {
e.readExistingEntry(nextPos);
if (e.entrySizeInChunks > 1) {
for (ReplicatedChronicleMap<?, ?, ?>.ModificationIterator it : its) {
it.clearRange0(s.tierIndex, nextPos + 1, nextPos + e.entrySizeInChunks);
}
}
pos = nextPos + e.entrySizeInChunks;
} else {
if (pos < m.actualChunksPerSegmentTier) {
for (ReplicatedChronicleMap<?, ?, ?>.ModificationIterator it : its) {
it.clearRange0(s.tierIndex, pos, m.actualChunksPerSegmentTier);
}
}
}
}
}
}