strangedb/src/main/java/org/warp/jcwdb/FileIndexManager.java

438 lines
13 KiB
Java
Raw Normal View History

2018-11-19 15:16:12 +01:00
package org.warp.jcwdb;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
2018-12-05 02:39:41 +01:00
import it.unimi.dsi.fastutil.longs.*;
2018-11-27 10:26:01 +01:00
2018-11-19 15:16:12 +01:00
import java.io.IOException;
2018-11-20 18:39:48 +01:00
import java.nio.ByteBuffer;
2018-11-19 15:16:12 +01:00
import java.nio.channels.Channels;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
2018-12-19 12:19:03 +01:00
import java.util.Iterator;
2018-12-11 23:00:51 +01:00
import java.util.function.Consumer;
2018-11-19 15:16:12 +01:00
public class FileIndexManager implements IndexManager {
private final SeekableByteChannel dataFileChannel, metadataFileChannel;
private final FileAllocator fileAllocator;
2018-11-26 14:50:44 +01:00
private final ByteBuffer metadataByteBuffer = ByteBuffer.allocateDirect(IndexDetails.TOTAL_BYTES);
private final ByteBuffer maskByteBuffer = ByteBuffer.allocateDirect(Integer.BYTES);
2018-11-20 18:39:48 +01:00
private volatile boolean closed;
private final Object closeLock = new Object();
2018-11-26 14:50:44 +01:00
private final Object metadataByteBufferLock = new Object();
2018-11-27 10:26:01 +01:00
private final Object maskByteBufferLock = new Object();
2018-11-27 17:47:19 +01:00
private final Object indicesMapsAccessLock = new Object();
2018-11-19 15:16:12 +01:00
2018-11-20 18:39:48 +01:00
/**
* Edit this using editIndex()
* Get using getIndexMetadata()
* This hashmap must contain all indices.
*/
2018-11-27 10:26:01 +01:00
private final Long2ObjectMap<IndexDetails> loadedIndices;
2018-11-20 18:39:48 +01:00
/**
* Edit this using editIndex()
*/
2018-11-27 10:26:01 +01:00
private final LongSet dirtyLoadedIndices, removedIndices;
2018-11-21 01:02:25 +01:00
private long firstAllocableIndex;
2018-11-20 18:39:48 +01:00
2018-11-27 10:26:01 +01:00
public FileIndexManager(Path dataFile, Path metadataFile) throws IOException {
2018-12-05 02:39:41 +01:00
loadedIndices = new Long2ObjectOpenHashMap<>();
dirtyLoadedIndices = new LongOpenHashSet();
removedIndices = new LongOpenHashSet();
2018-11-22 23:31:41 +01:00
if (Files.notExists(dataFile)) {
Files.createFile(dataFile);
}
if (Files.notExists(metadataFile)) {
Files.createFile(metadataFile);
}
dataFileChannel = Files.newByteChannel(dataFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
metadataFileChannel = Files.newByteChannel(metadataFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
2018-11-19 15:16:12 +01:00
fileAllocator = new FileAllocator(dataFileChannel);
2018-11-21 01:02:25 +01:00
firstAllocableIndex = metadataFileChannel.size() / (long) IndexDetails.TOTAL_BYTES;
2018-11-22 23:31:41 +01:00
if (firstAllocableIndex == 0) {
firstAllocableIndex = 1;
}
2018-11-19 15:16:12 +01:00
}
@Override
2018-11-20 18:39:48 +01:00
public <T> T get(long index, DBReader<T> reader) throws IOException {
checkClosed();
IndexDetails details = getIndexMetadata(index);
Input i = new Input(Channels.newInputStream(dataFileChannel.position(details.getOffset())));
2018-11-22 23:31:41 +01:00
T result = reader.read(i, details.getSize());
2018-11-19 15:16:12 +01:00
return result;
}
@Override
2018-11-20 18:39:48 +01:00
public int getType(long index) throws IOException {
return getIndexMetadata(index).getType();
}
@Override
2018-12-11 23:00:51 +01:00
public long getHash(long index) throws IOException {
return getIndexMetadata(index).getHash();
}
@Override
public <T> IndexDetails set(long index, DBDataOutput<T> data) throws IOException {
2018-11-20 18:39:48 +01:00
checkClosed();
2018-12-07 00:26:38 +01:00
final int dataSize = data.getSize();
2018-11-21 01:02:25 +01:00
final IndexDetails indexDetails = getIndexMetadataUnsafe(index);
2018-12-07 00:26:38 +01:00
if (indexDetails == null || indexDetails.getSize() < dataSize) {
// Allocate new space
2018-12-20 01:12:46 +01:00
IndexDetails newDetails = allocateAndWrite(index, data);
if (indexDetails != null) {
// Mark free the old bytes
fileAllocator.markFree(indexDetails.getOffset(), indexDetails.getSize());
}
return newDetails;
2018-11-20 18:39:48 +01:00
} else {
2018-12-07 00:26:38 +01:00
// Check if size changed
2018-12-11 23:00:51 +01:00
if (dataSize < indexDetails.getSize()) {
2018-12-07 00:26:38 +01:00
// Mark free the unused bytes
fileAllocator.markFree(indexDetails.getOffset() + dataSize, dataSize);
2018-11-20 18:39:48 +01:00
}
2018-12-07 00:26:38 +01:00
// Update index details
editIndex(index, indexDetails, indexDetails.getOffset(), dataSize, indexDetails.getType(), data.calculateHash());
// Write data
2018-11-21 01:02:25 +01:00
writeExact(indexDetails, data);
2018-12-11 23:00:51 +01:00
// Before returning, return IndexDetails
return indexDetails;
2018-11-20 18:39:48 +01:00
}
}
2018-11-21 01:02:25 +01:00
@Override
public <T> long add(DBDataOutput<T> data) throws IOException {
checkClosed();
final int size = data.getSize();
final long offset = fileAllocator.allocate(size);
final int type = data.getType();
2018-12-04 23:57:49 +01:00
final long hash = data.calculateHash();
final IndexDetails indexDetails = new IndexDetails(offset, size, type, hash);
2018-11-21 01:02:25 +01:00
final long index = createIndexMetadata(indexDetails);
writeExact(indexDetails, data);
return index;
}
/**
* Write the data at index.
* The input size must be equal to the index size!
2018-12-06 12:30:04 +01:00
*
2018-11-21 01:02:25 +01:00
* @param indexDetails
* @param data
* @throws IOException
*/
private void writeExact(final IndexDetails indexDetails, DBDataOutput<?> data) throws IOException {
2018-11-26 14:50:44 +01:00
final int dataSize = data.getSize();
if (indexDetails.getSize() != dataSize) {
throw new IOException("Unable to write " + dataSize + " in a space of " + indexDetails.getSize());
2018-11-21 01:02:25 +01:00
}
2018-11-20 18:39:48 +01:00
final long offset = indexDetails.getOffset();
2018-11-21 01:02:25 +01:00
2018-11-26 14:50:44 +01:00
final Output o = new Output(Channels.newOutputStream(dataFileChannel.position(offset)), dataSize);
2018-11-20 18:39:48 +01:00
data.getWriter().write(o);
2018-11-22 23:31:41 +01:00
o.flush();
2018-11-20 18:39:48 +01:00
}
2018-12-11 23:00:51 +01:00
private IndexDetails allocateAndWrite(final long index, DBDataOutput<?> w) throws IOException {
2018-11-20 18:39:48 +01:00
final int size = w.getSize();
final int type = w.getType();
2018-12-04 23:57:49 +01:00
final long hash = w.calculateHash();
2018-11-20 18:39:48 +01:00
final long offset = fileAllocator.allocate(size);
2018-12-04 23:57:49 +01:00
IndexDetails details = editIndex(index, offset, size, type, hash);
2018-11-21 01:02:25 +01:00
writeExact(details, w);
2018-12-11 23:00:51 +01:00
return details;
2018-11-19 15:16:12 +01:00
}
@Override
2018-11-21 01:02:25 +01:00
public void delete(long index) throws IOException {
2018-11-20 18:39:48 +01:00
checkClosed();
2018-11-21 01:02:25 +01:00
IndexDetails indexDetails = getIndexMetadataUnsafe(index);
if (indexDetails != null) {
fileAllocator.markFree(indexDetails.getOffset(), indexDetails.getSize());
}
2018-12-06 12:30:04 +01:00
synchronized (indicesMapsAccessLock) {
2018-11-27 17:47:19 +01:00
dirtyLoadedIndices.remove(index);
loadedIndices.remove(index);
removedIndices.add(index);
}
}
2018-12-06 12:30:04 +01:00
2018-11-27 17:47:19 +01:00
public void flushAndUnload(long index) throws IOException {
if (removedIndices.contains(index)) {
2018-12-06 12:30:04 +01:00
synchronized (indicesMapsAccessLock) {
2018-11-27 17:47:19 +01:00
removedIndices.remove(index);
dirtyLoadedIndices.remove(index);
loadedIndices.remove(index);
}
// Update indices metadata
SeekableByteChannel metadata = metadataFileChannel.position(index * IndexDetails.TOTAL_BYTES);
eraseIndexDetails(metadata);
}
2018-12-11 23:00:51 +01:00
boolean isDirty = false;
IndexDetails indexDetails = null;
synchronized (indicesMapsAccessLock) {
if (dirtyLoadedIndices.contains(index)) {
indexDetails = loadedIndices.get(index);
2018-11-27 17:47:19 +01:00
dirtyLoadedIndices.remove(index);
}
2018-12-11 23:00:51 +01:00
}
if (isDirty) {
2018-11-27 17:47:19 +01:00
// Update indices metadata
SeekableByteChannel metadata = metadataFileChannel.position(index * IndexDetails.TOTAL_BYTES);
writeIndexDetails(metadata, indexDetails);
}
2018-12-06 12:30:04 +01:00
synchronized (indicesMapsAccessLock) {
2018-11-27 17:47:19 +01:00
loadedIndices.remove(index);
}
2018-11-19 15:16:12 +01:00
}
@Override
public boolean has(long index) {
2018-11-20 18:39:48 +01:00
checkClosed();
2018-11-21 01:02:25 +01:00
try {
return getIndexMetadataUnsafe(index) != null;
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
2018-11-19 15:16:12 +01:00
}
2018-11-20 18:39:48 +01:00
2018-12-07 00:26:38 +01:00
/**
* Edit index data if a change is detected
* @param index
* @param oldData Old index data to check
* @param offset offset
* @param size size
* @param type type
* @param hash hash
* @return
*/
private IndexDetails editIndex(long index, IndexDetails oldData, long offset, int size, int type, long hash) {
if (oldData.getOffset() != offset || oldData.getSize() != size || oldData.getType() != type || oldData.getHash() != hash) {
2018-12-11 23:00:51 +01:00
return editIndex(index, offset, size, type, hash);
2018-12-07 00:26:38 +01:00
} else {
return oldData;
}
}
/**
* Edit index data
* @param index
* @param offset
* @param size
* @param type
* @param hash
* @return
*/
2018-12-04 23:57:49 +01:00
private IndexDetails editIndex(long index, long offset, int size, int type, long hash) {
IndexDetails indexDetails = new IndexDetails(offset, size, type, hash);
2018-11-20 18:39:48 +01:00
editIndex(index, indexDetails);
return indexDetails;
}
2018-12-07 00:26:38 +01:00
/**
* Edit index data
* @param index
* @param details
*/
2018-11-22 23:31:41 +01:00
private void editIndex(long index, IndexDetails details) {
2018-12-19 12:19:03 +01:00
synchronized (indicesMapsAccessLock) {// FIXXXX main3
2018-11-27 17:47:19 +01:00
loadedIndices.put(index, details);
dirtyLoadedIndices.add(index);
}
2018-11-22 23:31:41 +01:00
}
private long createIndexMetadata(IndexDetails indexDetails) {
2018-12-06 12:30:04 +01:00
synchronized (indicesMapsAccessLock) {
2018-11-27 17:47:19 +01:00
long newIndex = firstAllocableIndex++;
loadedIndices.put(newIndex, indexDetails);
dirtyLoadedIndices.add(newIndex);
removedIndices.remove(newIndex);
return newIndex;
}
2018-11-22 23:31:41 +01:00
}
2018-11-21 01:02:25 +01:00
private IndexDetails getIndexMetadataUnsafe(long index) throws IOException {
// Return index details if loaded
2018-11-27 17:47:19 +01:00
IndexDetails details;
2018-12-06 12:30:04 +01:00
synchronized (indicesMapsAccessLock) {
2018-11-27 17:47:19 +01:00
details = loadedIndices.getOrDefault(index, null);
}
2018-11-20 18:39:48 +01:00
if (details != null) return details;
2018-11-21 01:02:25 +01:00
// Try to load the details from file
2018-11-22 23:31:41 +01:00
final long metadataPosition = index * IndexDetails.TOTAL_BYTES;
if (metadataPosition + IndexDetails.TOTAL_BYTES > metadataFileChannel.size()) {
// Avoid underflow exception
return null;
}
SeekableByteChannel currentMetadataFileChannel = metadataFileChannel.position(metadataPosition);
2018-12-19 12:19:03 +01:00
IndexDetails indexDetails = null;
synchronized (metadataByteBufferLock) {// FIXXXX main2
2018-11-26 14:50:44 +01:00
metadataByteBuffer.rewind();
currentMetadataFileChannel.read(metadataByteBuffer);
metadataByteBuffer.rewind();
// If it's not deleted continue
if ((metadataByteBuffer.getInt() & IndexDetails.MASK_DELETED) == 0) {
final long offset = metadataByteBuffer.getLong();
2018-12-04 23:57:49 +01:00
// final long sizeAndType = metadataByteBuffer.getLong();
// final int size = (int)(sizeAndType >> 32);
// final int type = (int)sizeAndType;
2018-11-26 14:50:44 +01:00
final int size = metadataByteBuffer.getInt();
final int type = metadataByteBuffer.getInt();
2018-12-04 23:57:49 +01:00
final long hash = metadataByteBuffer.getLong();
2018-12-19 12:19:03 +01:00
indexDetails = new IndexDetails(offset, size, type, hash);
2018-11-26 14:50:44 +01:00
}
2018-11-21 01:02:25 +01:00
}
2018-12-19 12:19:03 +01:00
if (indexDetails != null) {
editIndex(index, indexDetails);
return indexDetails;
}
2018-11-21 01:02:25 +01:00
// No results found. Returning null
2018-11-20 18:39:48 +01:00
return null;
}
2018-11-21 01:02:25 +01:00
2018-11-20 18:39:48 +01:00
private IndexDetails getIndexMetadata(long index) throws IOException {
IndexDetails details = getIndexMetadataUnsafe(index);
if (details == null)
throw new IOException("Index " + index + " not found");
else
return details;
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
2018-11-21 01:02:25 +01:00
// Update indices metadata
2018-12-19 12:19:03 +01:00
flushAllIndices();
2018-11-21 01:02:25 +01:00
// Remove removed indices
2018-12-19 12:19:03 +01:00
removeRemovedIndices();
2018-11-20 18:39:48 +01:00
fileAllocator.close();
}
2018-12-06 12:30:04 +01:00
2018-11-27 17:47:19 +01:00
private void writeIndexDetails(SeekableByteChannel position, IndexDetails indexDetails) throws IOException {
2018-12-19 12:19:03 +01:00
synchronized (metadataByteBufferLock) {// FIXXXX cleaner3
2018-12-04 23:57:49 +01:00
final int size = indexDetails.getSize();
final int type = indexDetails.getType();
final long offset = indexDetails.getOffset();
final long hash = indexDetails.getHash();
2018-11-27 17:47:19 +01:00
metadataByteBuffer.rewind();
metadataByteBuffer.putInt(0);
2018-12-04 23:57:49 +01:00
metadataByteBuffer.putLong(offset);
metadataByteBuffer.putInt(size);
metadataByteBuffer.putInt(type);
//metadataByteBuffer.putLong((long)size << 32 | type & 0xFFFFFFFFL);
metadataByteBuffer.putLong(hash);
2018-11-27 17:47:19 +01:00
metadataByteBuffer.rewind();
position.write(metadataByteBuffer);
}
}
2018-12-06 12:30:04 +01:00
2018-11-27 17:47:19 +01:00
private void eraseIndexDetails(SeekableByteChannel position) throws IOException {
synchronized (maskByteBufferLock) {
maskByteBuffer.rewind();
maskByteBuffer.putInt(IndexDetails.MASK_DELETED);
maskByteBuffer.rewind();
position.write(maskByteBuffer);
}
}
2018-11-20 18:39:48 +01:00
private void checkClosed() {
if (closed) {
throw new RuntimeException("Index Manager is closed.");
}
}
2018-11-27 17:47:19 +01:00
@Override
public long clean() {
2018-12-19 12:19:03 +01:00
long cleaned = 0;
try {
cleaned += flushAllIndices();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
cleaned += removeRemovedIndices();
} catch (IOException ex) {
ex.printStackTrace();
}
cleaned += cleanExtraIndices();
return cleaned;
}
private long flushAllIndices() throws IOException {
long flushedIndices = 0;
SeekableByteChannel metadata = metadataFileChannel;
long lastIndex = -2;
synchronized (indicesMapsAccessLock) {
for (long index : dirtyLoadedIndices) {
IndexDetails indexDetails = loadedIndices.get(index);
if (index - lastIndex != 1) {
metadata = metadata.position(index * IndexDetails.TOTAL_BYTES);
}
writeIndexDetails(metadata, indexDetails);
lastIndex = index;
flushedIndices++;
}
dirtyLoadedIndices.clear();
}
return flushedIndices;
}
private long removeRemovedIndices() throws IOException {
SeekableByteChannel metadata = metadataFileChannel;
synchronized (indicesMapsAccessLock) {
long removed = this.removedIndices.size();
for (long index : this.removedIndices) {
metadata = metadata.position(index * IndexDetails.TOTAL_BYTES);
eraseIndexDetails(metadata);
}
this.removedIndices.clear();
return removed;
}
2018-11-27 17:47:19 +01:00
}
2018-12-06 12:30:04 +01:00
2018-11-27 17:47:19 +01:00
private long cleanExtraIndices() {
long removedIndices = 0;
2018-12-06 12:30:04 +01:00
LongArrayList toUnload = new LongArrayList();
synchronized (indicesMapsAccessLock) {
2018-12-15 01:01:23 +01:00
if (loadedIndices.size() > JCWDatabase.MAX_LOADED_INDICES) {
2018-11-27 17:47:19 +01:00
long count = loadedIndices.size();
2018-12-05 02:39:41 +01:00
LongIterator it = loadedIndices.keySet().iterator();
2018-12-06 12:30:04 +01:00
while (it.hasNext()) {
2018-12-05 02:39:41 +01:00
long loadedIndex = it.nextLong();
2018-12-15 01:01:23 +01:00
if (count < JCWDatabase.MAX_LOADED_INDICES * 3l / 2l) {
2018-11-27 17:47:19 +01:00
break;
}
2018-12-06 12:30:04 +01:00
toUnload.add(loadedIndex);
2018-11-27 17:47:19 +01:00
removedIndices++;
count--;
}
}
}
2018-12-06 12:30:04 +01:00
for (long index : toUnload.elements()) {
try {
flushAndUnload(index);
} catch (IOException e) {
e.printStackTrace();
}
}
2018-11-27 17:47:19 +01:00
return removedIndices;
}
2018-11-19 15:16:12 +01:00
}