| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.mvstore; |
| 7 |
|
| 8 |
import org.h2.mvstore.cache.FilePathCache; |
| 9 |
import org.h2.store.fs.FilePath; |
| 10 |
import org.h2.store.fs.encrypt.FileEncrypt; |
| 11 |
import org.h2.store.fs.encrypt.FilePathEncrypt; |
| 12 |
import java.io.IOException; |
| 13 |
import java.nio.ByteBuffer; |
| 14 |
import java.nio.channels.FileChannel; |
| 15 |
import java.nio.channels.FileLock; |
| 16 |
import java.nio.channels.OverlappingFileLockException; |
| 17 |
import java.util.HashMap; |
| 18 |
import java.util.Map; |
| 19 |
import java.util.function.Function; |
| 20 |
import java.util.zip.ZipOutputStream; |
| 21 |
|
| 22 |
/** |
| 23 |
* Class AppendOnlyMultiFileStore. |
| 24 |
* |
| 25 |
* @author <a href="mailto:[email protected]">Andrei Tokar</a> |
| 26 |
*/ |
| 27 |
@SuppressWarnings("unused") |
| 28 |
public final class AppendOnlyMultiFileStore extends FileStore<MFChunk> |
| 29 |
{ |
| 30 |
/** |
| 31 |
* Limit for the number of files used by this store |
| 32 |
*/ |
| 33 |
@SuppressWarnings("FieldCanBeLocal") |
| 34 |
private final int maxFileCount; |
| 35 |
|
| 36 |
/** |
| 37 |
* The time the store was created, in milliseconds since 1970. |
| 38 |
*/ |
| 39 |
private long creationTime; |
| 40 |
|
| 41 |
private int volumeId; |
| 42 |
|
| 43 |
/** |
| 44 |
* Current number of files in use |
| 45 |
*/ |
| 46 |
private int fileCount; |
| 47 |
|
| 48 |
/** |
| 49 |
* The current file. This is writable channel in append mode |
| 50 |
*/ |
| 51 |
private FileChannel fileChannel; |
| 52 |
|
| 53 |
/** |
| 54 |
* The encrypted file (if encryption is used). |
| 55 |
*/ |
| 56 |
private FileChannel originalFileChannel; |
| 57 |
|
| 58 |
/** |
| 59 |
* All files currently used by this store. This includes current one at first position. |
| 60 |
* Previous files are opened in read-only mode. |
| 61 |
* Logical length of this array is defined by fileCount. |
| 62 |
*/ |
| 63 |
@SuppressWarnings("MismatchedReadAndWriteOfArray") |
| 64 |
private final FileChannel[] fileChannels; |
| 65 |
|
| 66 |
/** |
| 67 |
* The file lock. |
| 68 |
*/ |
| 69 |
private FileLock fileLock; |
| 70 |
|
| 71 |
private final Map<String, Object> config; |
| 72 |
|
| 73 |
|
| 74 |
public AppendOnlyMultiFileStore(Map<String, Object> config) { |
| 75 |
super(config); |
| 76 |
this.config = config; |
| 77 |
maxFileCount = DataUtils.getConfigParam(config, "maxFileCount", 16); |
| 78 |
fileChannels = new FileChannel[maxFileCount]; |
| 79 |
} |
| 80 |
|
| 81 |
@Override |
| 82 |
protected final MFChunk createChunk(int newChunkId) { |
| 83 |
return new MFChunk(newChunkId); |
| 84 |
} |
| 85 |
|
| 86 |
@Override |
| 87 |
public MFChunk createChunk(String s) { |
| 88 |
return new MFChunk(s); |
| 89 |
} |
| 90 |
|
| 91 |
@Override |
| 92 |
protected MFChunk createChunk(Map<String, String> map) { |
| 93 |
return new MFChunk(map); |
| 94 |
} |
| 95 |
|
| 96 |
@Override |
| 97 |
public boolean shouldSaveNow(int unsavedMemory, int autoCommitMemory) { |
| 98 |
return unsavedMemory > autoCommitMemory; |
| 99 |
} |
| 100 |
|
| 101 |
@Override |
| 102 |
public void open(String fileName, boolean readOnly, char[] encryptionKey) { |
| 103 |
open(fileName, readOnly, |
| 104 |
encryptionKey == null ? null |
| 105 |
: fileChannel -> new FileEncrypt(fileName, FilePathEncrypt.getPasswordBytes(encryptionKey), |
| 106 |
fileChannel)); |
| 107 |
} |
| 108 |
|
| 109 |
@Override |
| 110 |
public AppendOnlyMultiFileStore open(String fileName, boolean readOnly) { |
| 111 |
AppendOnlyMultiFileStore result = new AppendOnlyMultiFileStore(config); |
| 112 |
result.open(fileName, readOnly, originalFileChannel == null ? null : |
| 113 |
fileChannel -> new FileEncrypt(fileName, (FileEncrypt)this.fileChannel, fileChannel)); |
| 114 |
return result; |
| 115 |
} |
| 116 |
|
| 117 |
private void open(String fileName, boolean readOnly, Function<FileChannel,FileChannel> encryptionTransformer) { |
| 118 |
if (fileChannel != null && fileChannel.isOpen()) { |
| 119 |
return; |
| 120 |
} |
| 121 |
// ensure the Cache file system is registered |
| 122 |
FilePathCache.INSTANCE.getScheme(); |
| 123 |
FilePath f = FilePath.get(fileName); |
| 124 |
FilePath parent = f.getParent(); |
| 125 |
if (parent != null && !parent.exists()) { |
| 126 |
throw DataUtils.newIllegalArgumentException( |
| 127 |
"Directory does not exist: {0}", parent); |
| 128 |
} |
| 129 |
if (f.exists() && !f.canWrite()) { |
| 130 |
readOnly = true; |
| 131 |
} |
| 132 |
init(fileName, readOnly); |
| 133 |
try { |
| 134 |
fileChannel = f.open(readOnly ? "r" : "rw"); |
| 135 |
if (encryptionTransformer != null) { |
| 136 |
originalFileChannel = fileChannel; |
| 137 |
fileChannel = encryptionTransformer.apply(fileChannel); |
| 138 |
} |
| 139 |
try { |
| 140 |
fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, readOnly); |
| 141 |
} catch (OverlappingFileLockException e) { |
| 142 |
throw DataUtils.newMVStoreException( |
| 143 |
DataUtils.ERROR_FILE_LOCKED, |
| 144 |
"The file is locked: {0}", fileName, e); |
| 145 |
} |
| 146 |
if (fileLock == null) { |
| 147 |
try { close(); } catch (Exception ignore) {} |
| 148 |
throw DataUtils.newMVStoreException( |
| 149 |
DataUtils.ERROR_FILE_LOCKED, |
| 150 |
"The file is locked: {0}", fileName); |
| 151 |
} |
| 152 |
saveChunkLock.lock(); |
| 153 |
try { |
| 154 |
setSize(fileChannel.size()); |
| 155 |
} finally { |
| 156 |
saveChunkLock.unlock(); |
| 157 |
} |
| 158 |
} catch (IOException e) { |
| 159 |
try { close(); } catch (Exception ignore) {} |
| 160 |
throw DataUtils.newMVStoreException( |
| 161 |
DataUtils.ERROR_READING_FAILED, |
| 162 |
"Could not open file {0}", fileName, e); |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Close this store. |
| 168 |
*/ |
| 169 |
@Override |
| 170 |
public void close() { |
| 171 |
try { |
| 172 |
if(fileChannel.isOpen()) { |
| 173 |
if (fileLock != null) { |
| 174 |
fileLock.release(); |
| 175 |
} |
| 176 |
fileChannel.close(); |
| 177 |
} |
| 178 |
} catch (Exception e) { |
| 179 |
throw DataUtils.newMVStoreException( |
| 180 |
DataUtils.ERROR_WRITING_FAILED, |
| 181 |
"Closing failed for file {0}", getFileName(), e); |
| 182 |
} finally { |
| 183 |
fileLock = null; |
| 184 |
super.close(); |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
@Override |
| 189 |
protected void writeFully(MFChunk chunk, long pos, ByteBuffer src) { |
| 190 |
assert chunk.volumeId == volumeId; |
| 191 |
int len = src.remaining(); |
| 192 |
setSize(Math.max(super.size(), pos + len)); |
| 193 |
DataUtils.writeFully(fileChannels[volumeId], pos, src); |
| 194 |
writeCount.incrementAndGet(); |
| 195 |
writeBytes.addAndGet(len); |
| 196 |
} |
| 197 |
|
| 198 |
@Override |
| 199 |
public ByteBuffer readFully(MFChunk chunk, long pos, int len) { |
| 200 |
int volumeId = chunk.volumeId; |
| 201 |
return readFully(fileChannels[volumeId], pos, len); |
| 202 |
} |
| 203 |
|
| 204 |
@Override |
| 205 |
protected void initializeStoreHeader(long time) { |
| 206 |
} |
| 207 |
|
| 208 |
@Override |
| 209 |
protected void readStoreHeader(boolean recoveryMode) { |
| 210 |
ByteBuffer fileHeaderBlocks = readFully(new MFChunk(""), 0, FileStore.BLOCK_SIZE); |
| 211 |
byte[] buff = new byte[FileStore.BLOCK_SIZE]; |
| 212 |
fileHeaderBlocks.get(buff); |
| 213 |
// the following can fail for various reasons |
| 214 |
try { |
| 215 |
HashMap<String, String> m = DataUtils.parseChecksummedMap(buff); |
| 216 |
if (m == null) { |
| 217 |
throw DataUtils.newMVStoreException( |
| 218 |
DataUtils.ERROR_FILE_CORRUPT, |
| 219 |
"Store header is corrupt: {0}", this); |
| 220 |
} |
| 221 |
storeHeader.putAll(m); |
| 222 |
} catch (Exception ignore) { |
| 223 |
throw DataUtils.newMVStoreException( |
| 224 |
DataUtils.ERROR_FILE_CORRUPT, |
| 225 |
"Store header is corrupt: {0}", this); |
| 226 |
} |
| 227 |
|
| 228 |
processCommonHeaderAttributes(); |
| 229 |
|
| 230 |
long fileSize = size(); |
| 231 |
long blocksInVolume = fileSize / FileStore.BLOCK_SIZE; |
| 232 |
|
| 233 |
MFChunk chunk = discoverChunk(blocksInVolume); |
| 234 |
setLastChunk(chunk); |
| 235 |
// load the chunk metadata: although meta's root page resides in the lastChunk, |
| 236 |
// traversing meta map might recursively load another chunk(s) |
| 237 |
for (MFChunk c : getChunksFromLayoutMap()) { |
| 238 |
// might be there already, due to meta traversal |
| 239 |
// see readPage() ... getChunkIfFound() |
| 240 |
if (!c.isLive()) { |
| 241 |
registerDeadChunk(c); |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
@Override |
| 247 |
protected void allocateChunkSpace(MFChunk chunk, WriteBuffer buff) { |
| 248 |
chunk.block = size() / BLOCK_SIZE; |
| 249 |
setSize((chunk.block + chunk.len) * BLOCK_SIZE); |
| 250 |
} |
| 251 |
|
| 252 |
@Override |
| 253 |
protected void writeChunk(MFChunk chunk, WriteBuffer buff) { |
| 254 |
long filePos = chunk.block * BLOCK_SIZE; |
| 255 |
writeFully(chunk, filePos, buff.getBuffer()); |
| 256 |
} |
| 257 |
|
| 258 |
@Override |
| 259 |
protected void writeCleanShutdownMark() { |
| 260 |
|
| 261 |
} |
| 262 |
|
| 263 |
@Override |
| 264 |
protected void adjustStoreToLastChunk() { |
| 265 |
|
| 266 |
} |
| 267 |
|
| 268 |
@Override |
| 269 |
protected void compactStore(int thresholdFillRate, long maxCompactTime, int maxWriteSize, MVStore mvStore) { |
| 270 |
|
| 271 |
} |
| 272 |
|
| 273 |
@Override |
| 274 |
protected void doHousekeeping(MVStore mvStore) throws InterruptedException {} |
| 275 |
|
| 276 |
@Override |
| 277 |
public int getFillRate() { |
| 278 |
return 0; |
| 279 |
} |
| 280 |
|
| 281 |
@Override |
| 282 |
protected void shrinkStoreIfPossible(int minPercent) {} |
| 283 |
|
| 284 |
@Override |
| 285 |
public void markUsed(long pos, int length) {} |
| 286 |
|
| 287 |
@Override |
| 288 |
protected void freeChunkSpace(Iterable<MFChunk> chunks) {} |
| 289 |
|
| 290 |
@Override |
| 291 |
protected boolean validateFileLength(String msg) { |
| 292 |
return true; |
| 293 |
} |
| 294 |
|
| 295 |
@Override |
| 296 |
public void backup(ZipOutputStream out) throws IOException { |
| 297 |
|
| 298 |
} |
| 299 |
} |