Debian Codegraph @

src/main/org/h2/mvstore/FileStore.java

raw
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.engine.Constants;
9 import static org.h2.mvstore.MVStore.INITIAL_VERSION;
10 import org.h2.mvstore.cache.CacheLongKeyLIRS;
11 import org.h2.mvstore.type.StringDataType;
12 import org.h2.util.MathUtils;
13 import org.h2.util.Utils;
14 import java.io.IOException;
15 import java.nio.ByteBuffer;
16 import java.nio.channels.FileChannel;
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.BitSet;
21 import java.util.Collection;
22 import java.util.Comparator;
23 import java.util.Deque;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.NoSuchElementException;
30 import java.util.PriorityQueue;
31 import java.util.Queue;
32 import java.util.Set;
33 import java.util.TreeMap;
34 import java.util.concurrent.ArrayBlockingQueue;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.ConcurrentMap;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.Future;
39 import java.util.concurrent.PriorityBlockingQueue;
40 import java.util.concurrent.RejectedExecutionException;
41 import java.util.concurrent.ThreadPoolExecutor;
42 import java.util.concurrent.atomic.AtomicLong;
43 import java.util.concurrent.atomic.AtomicReference;
44 import java.util.concurrent.locks.ReentrantLock;
45 import java.util.function.BiConsumer;
46 import java.util.function.IntSupplier;
47 import java.util.zip.ZipOutputStream;
48
49 /**
50 * Class FileStore is a base class to allow for different store implementations.
51 * FileStore concept revolves around notion of a "chunk", which is a piece of data
52 * written into the store at once.
53 *
54 * @author <a href="mailto:[email protected]">Andrei Tokar</a>
55 */
56 public abstract class FileStore<C extends Chunk<C>>
57 {
58 // The following are attribute names (keys) in store header map
59 static final String HDR_H = "H";
60 static final String HDR_BLOCK_SIZE = "blockSize";
61 static final String HDR_FORMAT = "format";
62 static final String HDR_CREATED = "created";
63 static final String HDR_FORMAT_READ = "formatRead";
64 static final String HDR_CHUNK = "chunk";
65 static final String HDR_BLOCK = "block";
66 static final String HDR_VERSION = "version";
67 static final String HDR_CLEAN = "clean";
68 static final String HDR_FLETCHER = "fletcher";
69
70 /**
71 * The key for the entry within "layout" map, which contains id of "meta" map.
72 * Entry value (hex encoded) is usually equal to 1, unless it's a legacy
73 * (upgraded) database and id 1 has been taken already by another map.
74 */
75 public static final String META_ID_KEY = "meta.id";
76
77 /**
78 * The block size (physical sector size) of the disk. The store header is
79 * written twice, one copy in each block, to ensure it survives a crash.
80 */
81 static final int BLOCK_SIZE = 4 * 1024;
82
83 private static final int FORMAT_WRITE_MIN = 3;
84 private static final int FORMAT_WRITE_MAX = 3;
85 private static final int FORMAT_READ_MIN = 3;
86 private static final int FORMAT_READ_MAX = 3;
87
88 MVStore mvStore;
89 private boolean closed;
90
91 /**
92 * The number of read operations.
93 */
94 protected final AtomicLong readCount = new AtomicLong();
95
96 /**
97 * The number of read bytes.
98 */
99 protected final AtomicLong readBytes = new AtomicLong();
100
101 /**
102 * The number of write operations.
103 */
104 protected final AtomicLong writeCount = new AtomicLong();
105
106 /**
107 * The number of written bytes.
108 */
109 protected final AtomicLong writeBytes = new AtomicLong();
110
111 /**
112 * The file name.
113 */
114 private String fileName;
115
116 /**
117 * For how long (in milliseconds) to retain a persisted chunk after it becomes irrelevant
118 * (not in use, because it only contains data from some old versions).
119 * Non-positive value allows chunk to be discarded immediately, once it goes out of use.
120 */
121 private int retentionTime = getDefaultRetentionTime();
122
123 private final int maxPageSize;
124
125 /**
126 * The file size (cached).
127 */
128 private long size;
129
130 /**
131 * Whether this store is read-only.
132 */
133 private boolean readOnly;
134
135 /**
136 * Lock guarding submission to serializationExecutor
137 */
138 private final ReentrantLock serializationLock = new ReentrantLock(true);
139
140 /**
141 * Single-threaded executor for serialization of the store snapshot into ByteBuffer
142 */
143 private ThreadPoolExecutor serializationExecutor;
144
145 /**
146 * Single-threaded executor for saving ByteBuffer as a new Chunk
147 */
148 private ThreadPoolExecutor bufferSaveExecutor;
149
150
151 /**
152 * The page cache. The default size is 16 MB, and the average size is 2 KB.
153 * It is split in 16 segments. The stack move distance is 2% of the expected
154 * number of entries.
155 */
156 private final CacheLongKeyLIRS<Page<?,?>> cache;
157
158 /**
159 * Cache for chunks "Table of Content" used to translate page's
160 * sequential number within containing chunk into byte position
161 * within chunk's image. Cache keyed by chunk id.
162 */
163 private final CacheLongKeyLIRS<long[]> chunksToC;
164
165 private final Queue<RemovedPageInfo> removedPages = new PriorityBlockingQueue<>();
166
167 /**
168 * The newest chunk. If nothing was stored yet, this field is not set.
169 */
170 protected volatile C lastChunk;
171
172 private int lastChunkId; // protected by serializationLock
173
174 protected final ReentrantLock saveChunkLock = new ReentrantLock(true);
175
176 /**
177 * The map of chunks.
178 */
179 final ConcurrentHashMap<Integer, C> chunks = new ConcurrentHashMap<>();
180
181 protected final HashMap<String, Object> storeHeader = new HashMap<>();
182
183 /**
184 * The time the store was created, in milliseconds since 1970.
185 */
186 private long creationTime;
187
188
189 private final Queue<WriteBuffer> writeBufferPool = new ArrayBlockingQueue<>(PIPE_LENGTH + 1);
190
191 /**
192 * The layout map. Contains chunk's metadata and root locations for all maps.
193 * This is relatively fast changing part of metadata
194 */
195 private MVMap<String, String> layout;
196
197 private final Deque<C> deadChunks = new ArrayDeque<>();
198
199 /**
200 * Reference to a background thread, which is expected to be running, if any.
201 */
202 private final AtomicReference<BackgroundWriterThread> backgroundWriterThread = new AtomicReference<>();
203
204 private final int autoCompactFillRate;
205
206 /**
207 * The delay in milliseconds to automatically commit and write changes.
208 */
209 private int autoCommitDelay;
210
211 private long autoCompactLastFileOpCount;
212
213 private long lastCommitTime;
214
215 protected final boolean recoveryMode;
216
217 public static final int PIPE_LENGTH = 3;
218
219
220
221
222 protected FileStore(Map<String, Object> config) {
223 recoveryMode = config.containsKey("recoveryMode");
224 autoCompactFillRate = DataUtils.getConfigParam(config, "autoCompactFillRate", 90);
225 CacheLongKeyLIRS.Config cc = null;
226 int mb = DataUtils.getConfigParam(config, "cacheSize", 16);
227 if (mb > 0) {
228 cc = new CacheLongKeyLIRS.Config();
229 cc.maxMemory = mb * 1024L * 1024L;
230 Object o = config.get("cacheConcurrency");
231 if (o != null) {
232 cc.segmentCount = (Integer)o;
233 }
234 }
235 cache = cc == null ? null : new CacheLongKeyLIRS<>(cc);
236
237 CacheLongKeyLIRS.Config cc2 = new CacheLongKeyLIRS.Config();
238 cc2.maxMemory = 1024L * 1024L;
239 chunksToC = new CacheLongKeyLIRS<>(cc2);
240
241 int maxPageSize = Integer.MAX_VALUE;
242 // Make sure pages will fit into cache
243 if (cache != null) {
244 maxPageSize = 16 * 1024;
245 int maxCachableSize = (int) (cache.getMaxItemSize() >> 4);
246 if (maxPageSize > maxCachableSize) {
247 maxPageSize = maxCachableSize;
248 }
249 }
250 this.maxPageSize = maxPageSize;
251 }
252
253 public abstract void open(String fileName, boolean readOnly, char[] encryptionKey);
254
255 public abstract FileStore<C> open(String fileName, boolean readOnly);
256
257 protected final void init(String fileName, boolean readOnly) {
258 this.fileName = fileName;
259 this.readOnly = readOnly;
260 }
261
262 public final void bind(MVStore mvStore) {
263 if(this.mvStore != mvStore) {
264 long pos = layout == null ? 0L : layout.getRootPage().getPos();
265 layout = new MVMap<>(mvStore, 0, StringDataType.INSTANCE, StringDataType.INSTANCE);
266 layout.setRootPos(pos, mvStore.getCurrentVersion());
267 this.mvStore = mvStore;
268 mvStore.resetLastMapId(lastChunk == null ? 0 : lastChunk.mapId);
269 mvStore.setCurrentVersion(lastChunkVersion());
270 }
271 }
272
273 public final void stop(long allowedCompactionTime) {
274 if (allowedCompactionTime > 0) {
275 compactStore(allowedCompactionTime);
276 }
277 writeCleanShutdown();
278 clearCaches();
279 }
280
281 public void close() {
282 layout.close();
283 closed = true;
284 chunks.clear();
285 }
286
287 public final int getMetaMapId(IntSupplier nextIdSupplier) {
288 String metaIdStr = layout.get(META_ID_KEY);
289 int metaId;
290 if (metaIdStr == null) {
291 metaId = nextIdSupplier.getAsInt();
292 layout.put(META_ID_KEY, Integer.toHexString(metaId));
293 } else {
294 metaId = DataUtils.parseHexInt(metaIdStr);
295 }
296 return metaId;
297 }
298
299 /**
300 * Get this store's layout map. This data is for informational purposes only. The
301 * data is subject to change in future versions.
302 * <p>
303 * The data in this map should not be modified (changing system data may corrupt the store).
304 * <p>
305 * The layout map contains the following entries:
306 * <pre>
307 * chunk.{chunkId} = {chunk metadata}
308 * root.{mapId} = {root position}
309 * </pre>
310 *
311 * @return the metadata map
312 */
313 public final Map<String, String> getLayoutMap() {
314 return new TreeMap<>(layout);
315 }
316
317 @SuppressWarnings("ReferenceEquality")
318 public final boolean isRegularMap(MVMap<?,?> map) {
319 return map != layout;
320 }
321
322 /**
323 * Get "position" of the root page for the specified map
324 * @param mapId to get root position for
325 * @return opaque "position" value, that should be used to read the page
326 */
327 public final long getRootPos(int mapId) {
328 String root = layout.get(MVMap.getMapRootKey(mapId));
329 return root == null ? 0 : DataUtils.parseHexLong(root);
330 }
331
332 /**
333 * Performs final stage of map removal - delete root location info from the layout map.
334 * Specified map is supposedly closed, is anonymous and has no outstanding usage by now.
335 *
336 * @param mapId to deregister
337 * @return true if root was removed, false if it is not there
338 */
339 public final boolean deregisterMapRoot(int mapId) {
340 return layout.remove(MVMap.getMapRootKey(mapId)) != null;
341 }
342
343 /**
344 * Check whether there are any unsaved changes since specified version.
345 *
346 * @param lastStoredVersion version to take as a base for changes
347 * @return if there are any changes
348 */
349 public final boolean hasChangesSince(long lastStoredVersion) {
350 return layout.hasChangesSince(lastStoredVersion) && lastStoredVersion > INITIAL_VERSION;
351 }
352
353 public final long lastChunkVersion() {
354 C chunk = lastChunk;
355 return chunk == null ? INITIAL_VERSION + 1 : chunk.version;
356 }
357
358 public final long getMaxPageSize() {
359 return maxPageSize;
360 }
361
362 public final int getRetentionTime() {
363 return retentionTime;
364 }
365
366 /**
367 * How long to retain old, persisted chunks, in milliseconds. Chunks that
368 * are older may be overwritten once they contain no live data.
369 * <p>
370 * The default value is 45000 (45 seconds) when using the default file
371 * store. It is assumed that a file system and hard disk will flush all
372 * write buffers within this time. Using a lower value might be dangerous,
373 * unless the file system and hard disk flush the buffers earlier. To
374 * manually flush the buffers, use
375 * <code>MVStore.getFile().force(true)</code>, however please note that
376 * according to various tests this does not always work as expected
377 * depending on the operating system and hardware.
378 * <p>
379 * The retention time needs to be long enough to allow reading old chunks
380 * while traversing over the entries of a map.
381 * <p>
382 * This setting is not persisted.
383 *
384 * @param ms how many milliseconds to retain old chunks (0 to overwrite them
385 * as early as possible)
386 */
387 public final void setRetentionTime(int ms) {
388 retentionTime = ms;
389 }
390
391 /**
392 * Decision about autocommit is delegated to store
393 * @param unsavedMemory amount of unsaved memory, so far
394 * @param autoCommitMemory configured limit on amount of unsaved memory
395 * @return true if commit should happen now
396 */
397 public abstract boolean shouldSaveNow(int unsavedMemory, int autoCommitMemory);
398
399 /**
400 * Get the auto-commit delay.
401 *
402 * @return the delay in milliseconds, or 0 if auto-commit is disabled.
403 */
404 public final int getAutoCommitDelay() {
405 return autoCommitDelay;
406 }
407
408 /**
409 * Set the maximum delay in milliseconds to auto-commit changes.
410 * <p>
411 * To disable auto-commit, set the value to 0. In this case, changes are
412 * only committed when explicitly calling commit.
413 * <p>
414 * The default is 1000, meaning all changes are committed after at most one
415 * second.
416 *
417 * @param millis the maximum delay
418 */
419 public final void setAutoCommitDelay(int millis) {
420 if (autoCommitDelay != millis) {
421 autoCommitDelay = millis;
422 if (!isReadOnly()) {
423 stopBackgroundThread(millis >= 0);
424 // start the background thread if needed
425 if (millis > 0 && mvStore.isOpen()) {
426 int sleep = Math.max(1, millis / 10);
427 BackgroundWriterThread t = new BackgroundWriterThread(this, sleep, toString());
428 if (backgroundWriterThread.compareAndSet(null, t)) {
429 t.start();
430 serializationExecutor = Utils.createSingleThreadExecutor("H2-serialization");
431 bufferSaveExecutor = Utils.createSingleThreadExecutor("H2-save");
432 }
433 }
434 }
435 }
436 }
437
438 /**
439 * Check whether all data can be read from this version. This requires that
440 * all chunks referenced by this version are still available (not
441 * overwritten).
442 *
443 * @param version the version
444 * @return true if all data can be read
445 */
446 public final boolean isKnownVersion(long version) {
447 if (chunks.isEmpty()) {
448 // no stored data
449 return true;
450 }
451 // need to check if a chunk for this version exists
452 C c = getChunkForVersion(version);
453 if (c == null) {
454 return false;
455 }
456 try {
457 // also, all chunks referenced by this version
458 // need to be available in the file
459 MVMap<String, String> oldLayoutMap = getLayoutMap(version);
460 for (C chunk : getChunksFromLayoutMap(oldLayoutMap)) {
461 String chunkKey = Chunk.getMetaKey(chunk.id);
462 // if current layout map does not have it - verify it's existence
463 if (!layout.containsKey(chunkKey) && !isValidChunk(chunk)) {
464 return false;
465 }
466 }
467 } catch (MVStoreException e) {
468 // the chunk missing where the metadata is stored
469 return false;
470 }
471 return true;
472 }
473
474 public final void rollbackTo(long version) {
475 if (version == 0) {
476 // special case: remove all data
477 String metaId = layout.get(META_ID_KEY);
478 layout.setInitialRoot(layout.createEmptyLeaf(), INITIAL_VERSION);
479 layout.put(META_ID_KEY, metaId);
480 } else {
481 if (!layout.rollbackRoot(version)) {
482 MVMap<String, String> layoutMap = getLayoutMap(version);
483 layout.setInitialRoot(layoutMap.getRootPage(), version);
484 }
485 }
486 serializationLock.lock();
487 try {
488 C keep = getChunkForVersion(version);
489 if (keep != null) {
490 saveChunkLock.lock();
491 try {
492 deadChunks.clear();
493 setLastChunk(keep);
494 adjustStoreToLastChunk();
495 } finally {
496 saveChunkLock.unlock();
497 }
498 }
499 } finally {
500 serializationLock.unlock();
501 }
502 removedPages.clear();
503 clearCaches();
504 }
505
506 protected final void initializeCommonHeaderAttributes(long time) {
507 setLastChunk(null);
508 creationTime = time;
509 storeHeader.put(FileStore.HDR_H, 2);
510 storeHeader.put(FileStore.HDR_BLOCK_SIZE, FileStore.BLOCK_SIZE);
511 storeHeader.put(FileStore.HDR_FORMAT, FORMAT_WRITE_MAX);
512 storeHeader.put(FileStore.HDR_CREATED, creationTime);
513 }
514
515 protected final void processCommonHeaderAttributes() {
516 creationTime = DataUtils.readHexLong(storeHeader, FileStore.HDR_CREATED, 0);
517 long now = System.currentTimeMillis();
518 // calculate the year (doesn't have to be exact;
519 // we assume 365.25 days per year, * 4 = 1461)
520 int year = 1970 + (int) (now / (1000L * 60 * 60 * 6 * 1461));
521 if (year < 2014) {
522 // if the year is before 2014,
523 // we assume the system doesn't have a real-time clock,
524 // and we set the creationTime to the past, so that
525 // existing chunks are overwritten
526 creationTime = now - getRetentionTime();
527 } else if (now < creationTime) {
528 // the system time was set to the past:
529 // we change the creation time
530 creationTime = now;
531 storeHeader.put(FileStore.HDR_CREATED, creationTime);
532 }
533
534 int blockSize = DataUtils.readHexInt(storeHeader, FileStore.HDR_BLOCK_SIZE, FileStore.BLOCK_SIZE);
535 if (blockSize != FileStore.BLOCK_SIZE) {
536 throw DataUtils.newMVStoreException(
537 DataUtils.ERROR_UNSUPPORTED_FORMAT,
538 "Block size {0} is currently not supported",
539 blockSize);
540 }
541 long format = DataUtils.readHexLong(storeHeader, HDR_FORMAT, 1);
542 if (!isReadOnly()) {
543 if (format > FORMAT_WRITE_MAX) {
544 throw getUnsupportedWriteFormatException(format, FORMAT_WRITE_MAX,
545 "The write format {0} is larger than the supported format {1}");
546 } else if (format < FORMAT_WRITE_MIN) {
547 throw getUnsupportedWriteFormatException(format, FORMAT_WRITE_MIN,
548 "The write format {0} is smaller than the supported format {1}");
549 }
550 }
551 format = DataUtils.readHexLong(storeHeader, HDR_FORMAT_READ, format);
552 if (format > FORMAT_READ_MAX) {
553 throw DataUtils.newMVStoreException(
554 DataUtils.ERROR_UNSUPPORTED_FORMAT,
555 "The read format {0} is larger than the supported format {1}",
556 format, FORMAT_READ_MAX);
557 } else if (format < FORMAT_READ_MIN) {
558 throw DataUtils.newMVStoreException(
559 DataUtils.ERROR_UNSUPPORTED_FORMAT,
560 "The read format {0} is smaller than the supported format {1}",
561 format, FORMAT_READ_MIN);
562 }
563 }
564
565 private long getTimeSinceCreation() {
566 return Math.max(0, mvStore.getTimeAbsolute() - getCreationTime());
567 }
568
569 private MVMap<String, String> getLayoutMap(long version) {
570 C chunk = getChunkForVersion(version);
571 DataUtils.checkArgument(chunk != null, "Unknown version {0}", version);
572 return layout.openReadOnly(chunk.layoutRootPos, version);
573 }
574
575 private C getChunkForVersion(long version) {
576 C newest = null;
577 for (C c : chunks.values()) {
578 if (c.version <= version) {
579 if (newest == null || c.id > newest.id) {
580 newest = c;
581 }
582 }
583 }
584 return newest;
585 }
586
587 private void scrubLayoutMap(MVMap<String, String> meta) {
588 Set<String> keysToRemove = new HashSet<>();
589
590 // split meta map off layout map
591 for (String prefix : new String[]{ DataUtils.META_NAME, DataUtils.META_MAP }) {
592 for (Iterator<String> it = layout.keyIterator(prefix); it.hasNext(); ) {
593 String key = it.next();
594 if (!key.startsWith(prefix)) {
595 break;
596 }
597 meta.putIfAbsent(key, layout.get(key));
598 mvStore.markMetaChanged();
599 keysToRemove.add(key);
600 }
601 }
602
603 // remove roots of non-existent maps (leftover after unfinished map removal)
604 for (Iterator<String> it = layout.keyIterator(DataUtils.META_ROOT); it.hasNext();) {
605 String key = it.next();
606 if (!key.startsWith(DataUtils.META_ROOT)) {
607 break;
608 }
609 String mapIdStr = key.substring(key.lastIndexOf('.') + 1);
610 if(!meta.containsKey(DataUtils.META_MAP + mapIdStr) && DataUtils.parseHexInt(mapIdStr) != meta.getId()) {
611 keysToRemove.add(key);
612 }
613 }
614
615 for (String key : keysToRemove) {
616 layout.remove(key);
617 }
618 }
619
620 protected final boolean hasPersistentData() {
621 return lastChunk != null;
622 }
623
624 protected final boolean isIdle() {
625 return autoCompactLastFileOpCount == getWriteCount() + getReadCount();
626 }
627
628 protected final void setLastChunk(C last) {
629 lastChunk = last;
630 chunks.clear();
631 lastChunkId = 0;
632 long layoutRootPos = 0;
633 if (last != null) { // there is a valid chunk
634 lastChunkId = last.id;
635 layoutRootPos = last.layoutRootPos;
636 chunks.put(last.id, last);
637 }
638 layout.setRootPos(layoutRootPos, lastChunkVersion());
639 }
640
641 protected final void registerDeadChunk(C chunk) {
642 deadChunks.offer(chunk);
643 }
644
645 public final void dropUnusedChunks() {
646 if (!deadChunks.isEmpty()) {
647 long oldestVersionToKeep = mvStore.getOldestVersionToKeep();
648 long time = getTimeSinceCreation();
649 List<C> toBeFreed = new ArrayList<>();
650 C chunk;
651 while ((chunk = deadChunks.poll()) != null &&
652 (isSeasonedChunk(chunk, time) && canOverwriteChunk(chunk, oldestVersionToKeep) ||
653 // if chunk is not ready yet, put it back and exit
654 // since this deque is unbounded, offerFirst() always return true
655 !deadChunks.offerFirst(chunk))) {
656
657 if (chunks.remove(chunk.id) != null) {
658 // purge dead pages from cache
659 long[] toc = cleanToCCache(chunk);
660 if (toc != null && cache != null) {
661 for (long tocElement : toc) {
662 long pagePos = DataUtils.composePagePos(chunk.id, tocElement);
663 cache.remove(pagePos);
664 }
665 }
666
667 if (layout.remove(Chunk.getMetaKey(chunk.id)) != null) {
668 mvStore.markMetaChanged();
669 }
670 if (chunk.isAllocated()) {
671 toBeFreed.add(chunk);
672 }
673 }
674 }
675 if (!toBeFreed.isEmpty()) {
676 saveChunkLock.lock();
677 try {
678 freeChunkSpace(toBeFreed);
679 } finally {
680 saveChunkLock.unlock();
681 }
682 }
683 }
684 }
685
686 private static <C extends Chunk<C>> boolean canOverwriteChunk(C c, long oldestVersionToKeep) {
687 return !c.isLive() && c.unusedAtVersion < oldestVersionToKeep;
688 }
689
690 private boolean isSeasonedChunk(C chunk, long time) {
691 int retentionTime = getRetentionTime();
692 return retentionTime < 0 || chunk.time + retentionTime <= time;
693 }
694
695 private boolean isRewritable(C chunk, long time) {
696 return chunk.isRewritable() && isSeasonedChunk(chunk, time);
697 }
698
699 /**
700 * Write to the file.
701 * @param chunk to write
702 * @param pos the write position
703 * @param src the source buffer
704 */
705 protected abstract void writeFully(C chunk, long pos, ByteBuffer src);
706
707 /**
708 * Read data from the store.
709 *
710 * @param chunk that owns data to be read
711 * @param pos the read "position"
712 * @param len the number of bytes to read
713 * @return the byte buffer with data requested
714 */
715 public abstract ByteBuffer readFully(C chunk, long pos, int len);
716
717 protected final ByteBuffer readFully(FileChannel file, long pos, int len) {
718 ByteBuffer dst = ByteBuffer.allocate(len);
719 DataUtils.readFully(file, pos, dst);
720 readCount.incrementAndGet();
721 readBytes.addAndGet(len);
722 return dst;
723 }
724
725
726 /**
727 * Allocate logical space and assign position of the buffer within the store.
728 *
729 * @param chunk to allocate space for
730 * @param buff to allocate space for
731 */
732 protected abstract void allocateChunkSpace(C chunk, WriteBuffer buff);
733
734 /**
735 * Write buffer associated with chunk into store at chunk's allocated position
736 * @param chunk chunk to write
737 * @param buffer to write
738 */
739 protected abstract void writeChunk(C chunk, WriteBuffer buffer);
740
741 /**
742 * Performs final preparation before store is closed normally
743 */
744 protected abstract void writeCleanShutdownMark();
745
746 /**
747 * Make persistent changes after lastChunk was reset
748 */
749 protected abstract void adjustStoreToLastChunk();
750
751 /**
752 * Get the store header. This data is for informational purposes only. The
753 * data is subject to change in future versions. The data should not be
754 * modified (doing so may corrupt the store).
755 *
756 * @return the store header
757 */
758 public Map<String, Object> getStoreHeader() {
759 return storeHeader;
760 }
761
762 private C createChunk(long time, long version) {
763 int newChunkId = findNewChunkId();
764 C c = createChunk(newChunkId);
765 c.time = time;
766 c.version = version;
767 c.occupancy = new BitSet();
768 return c;
769 }
770
771 protected abstract C createChunk(int id);
772
773 /**
774 * Build a Chunk from the given string.
775 *
776 * @param s the string
777 * @return the Chunk created
778 */
779 public abstract C createChunk(String s);
780
781 protected abstract C createChunk(Map<String, String> map);
782
783
784 private int findNewChunkId() {
785 int newChunkId;
786 while (true) {
787 newChunkId = ++lastChunkId & Chunk.MAX_ID;
788 if (newChunkId == lastChunkId) {
789 break;
790 }
791 C old = chunks.get(newChunkId);
792 if (old == null) {
793 break;
794 }
795 if (!old.isSaved()) {
796 throw DataUtils.newMVStoreException(
797 DataUtils.ERROR_INTERNAL,
798 "Last block {0} not stored, possibly due to out-of-memory", old);
799 }
800 }
801 return newChunkId;
802 }
803
804 protected void writeCleanShutdown() {
805 if (!isReadOnly()) {
806 saveChunkLock.lock();
807 try {
808 writeCleanShutdownMark();
809 sync();
810 assert validateFileLength("on close");
811 } finally {
812 saveChunkLock.unlock();
813 }
814 }
815 }
816
817 /**
818 * Store chunk's serialized metadata as an entry in a layout map.
819 * Key for this entry would be "chunk.&lt;id&gt;"
820 *
821 * @param chunk to save
822 */
823 @SuppressWarnings("ThreadPriorityCheck")
824 public void saveChunkMetadataChanges(C chunk) {
825 assert serializationLock.isHeldByCurrentThread();
826 // chunk's location has to be determined before
827 // it's metadata can be is serialized
828 while (!chunk.isAllocated()) {
829 saveChunkLock.lock();
830 try {
831 if (chunk.isAllocated()) {
832 break;
833 }
834 } finally {
835 saveChunkLock.unlock();
836 }
837 // just let chunks saving thread to deal with it
838 Thread.yield();
839 }
840 layout.put(Chunk.getMetaKey(chunk.id), chunk.asString());
841 }
842
843 /**
844 * Mark the space occupied by specified chunks as free.
845 *
846 * @param chunks chunks to be processed
847 */
848 protected abstract void freeChunkSpace(Iterable<C> chunks);
849
850 protected abstract boolean validateFileLength(String msg);
851
852 /**
853 * Try to increase the fill rate by re-writing partially full chunks. Chunks
854 * with a low number of live items are re-written.
855 * <p>
856 * If the current fill rate is higher than the target fill rate, nothing is
857 * done.
858 * <p>
859 * Please note this method will not necessarily reduce the file size, as
860 * empty chunks are not overwritten.
861 * <p>
862 * Only data of open maps can be moved. For maps that are not open, the old
863 * chunk is still referenced. Therefore, it is recommended to open all maps
864 * before calling this method.
865 *
866 * @param targetFillRate the minimum percentage of live entries
867 * @param write the minimum number of bytes to write
868 * @return if any chunk was re-written
869 */
870 public boolean compact(int targetFillRate, int write) {
871 if (hasPersistentData()) {
872 if (targetFillRate > 0 && getChunksFillRate() < targetFillRate) {
873 // We can't wait forever for the lock here,
874 // because if called from the background thread,
875 // it might go into deadlock with concurrent database closure
876 // and attempt to stop this thread.
877 try {
878 Boolean result = mvStore.tryExecuteUnderStoreLock(() -> rewriteChunks(write, 100));
879 return result != null && result;
880 } catch (InterruptedException e) {
881 throw new RuntimeException(e);
882 }
883 }
884 }
885 return false;
886 }
887
888 public void compactStore(long maxCompactTime) {
889 compactStore(autoCompactFillRate, maxCompactTime, 16 * 1024 * 1024, mvStore);
890 }
891
892 /**
893 * Compact store file, that is, compact blocks that have a low
894 * fill rate, and move chunks next to each other. This will typically
895 * shrink the file. Changes are flushed to the file, and old
896 * chunks are overwritten.
897 *
898 * @param thresholdFillRate do not compact if store fill rate above this value (0-100)
899 * @param maxCompactTime the maximum time in milliseconds to compact
900 * @param maxWriteSize the maximum amount of data to be written as part of this call
901 * @param mvStore that owns this FileStore
902 */
903 protected abstract void compactStore(int thresholdFillRate, long maxCompactTime, int maxWriteSize, //
904 MVStore mvStore);
905
906 protected abstract void doHousekeeping(MVStore mvStore) throws InterruptedException;
907
908
909
910 public MVMap<String, String> start() {
911 if (size() == 0) {
912 initializeCommonHeaderAttributes(mvStore.getTimeAbsolute());
913 initializeStoreHeader(mvStore.getTimeAbsolute());
914 } else {
915 saveChunkLock.lock();
916 try {
917 readStoreHeader(recoveryMode);
918 } finally {
919 saveChunkLock.unlock();
920 }
921 }
922 lastCommitTime = getTimeSinceCreation();
923 mvStore.resetLastMapId(lastMapId());
924 mvStore.setCurrentVersion(lastChunkVersion());
925 MVMap<String, String> metaMap = mvStore.openMetaMap();
926 scrubLayoutMap(metaMap);
927 return metaMap;
928 }
929
930 protected abstract void initializeStoreHeader(long time);
931
932 protected abstract void readStoreHeader(boolean recoveryMode);
933
934 private int lastMapId() {
935 C chunk = lastChunk;
936 return chunk == null ? 0 : chunk.mapId;
937 }
938
939 private MVStoreException getUnsupportedWriteFormatException(long format, int expectedFormat, String s) {
940 format = DataUtils.readHexLong(storeHeader, HDR_FORMAT_READ, format);
941 if (format >= FORMAT_READ_MIN && format <= FORMAT_READ_MAX) {
942 s += ", and the file was not opened in read-only mode";
943 }
944 return DataUtils.newMVStoreException(DataUtils.ERROR_UNSUPPORTED_FORMAT, s, format, expectedFormat);
945 }
946
947 /**
948 * Discover a valid chunk, searching file backwards from the given block
949 *
950 * @param block to start search from (found chunk footer should be no
951 * further than block-1)
952 * @return valid chunk or null if none found
953 */
954 protected final C discoverChunk(long block) {
955 long candidateLocation = Long.MAX_VALUE;
956 C candidate = null;
957 while (true) {
958 if (block == candidateLocation) {
959 return candidate;
960 }
961 if (block == 2) { // number of blocks occupied by headers
962 return null;
963 }
964 C test = readChunkFooter(block);
965 if (test != null) {
966 // if we encounter chunk footer (with or without corresponding header)
967 // in the middle of prospective chunk, stop considering it
968 candidateLocation = Long.MAX_VALUE;
969 test = readChunkHeaderOptionally(test.block, test.id);
970 if (test != null) {
971 // if that footer has a corresponding header,
972 // consider them as a new candidate for a valid chunk
973 candidate = test;
974 candidateLocation = test.block;
975 }
976 }
977
978 // if we encounter chunk header without corresponding footer
979 // (due to incomplete write?) in the middle of prospective
980 // chunk, stop considering it
981 if (--block > candidateLocation && readChunkHeaderOptionally(block) != null) {
982 candidateLocation = Long.MAX_VALUE;
983 }
984 }
985 }
986
987 protected final boolean findLastChunkWithCompleteValidChunkSet(Comparator<C> chunkComparator,
988 Map<Long, C> validChunksByLocation, boolean afterFullScan) {
989 // this collection will hold potential candidates for lastChunk to fall back to,
990 // in order from the most to least likely
991 C[] array = createChunksArray(validChunksByLocation.size());
992 C[] lastChunkCandidates = validChunksByLocation.values().toArray(array);
993 Arrays.sort(lastChunkCandidates, chunkComparator);
994 Map<Integer, C> validChunksById = new HashMap<>();
995 for (C chunk : lastChunkCandidates) {
996 validChunksById.put(chunk.id, chunk);
997 }
998 // Try candidates for "last chunk" in order from newest to oldest
999 // until suitable is found. Suitable one should have meta map
1000 // where all chunk references point to valid locations.
1001 for (C chunk : lastChunkCandidates) {
1002 boolean verified = true;
1003 try {
1004 setLastChunk(chunk);
1005 // load the chunk metadata: although meta's root page resides in the lastChunk,
1006 // traversing meta map might recursively load another chunk(s)
1007 for (C c : getChunksFromLayoutMap()) {
1008 C test;
1009 if ((test = validChunksByLocation.get(c.block)) == null || test.id != c.id) {
1010 if ((test = validChunksById.get(c.id)) != null) {
1011 // We do not have a valid chunk at that location,
1012 // but there is a copy of same chunk from original
1013 // location.
1014 // Chunk header at original location does not have
1015 // any dynamic (occupancy) metadata, so it can't be
1016 // used here as is, re-point our chunk to original
1017 // location instead.
1018 c.block = test.block;
1019 } else if (c.isLive() && (afterFullScan || readChunkHeaderAndFooter(c.block, c.id) == null)) {
1020 // chunk reference is invalid
1021 // this "last chunk" candidate is not suitable
1022 verified = false;
1023 break;
1024 }
1025 }
1026 if (!c.isLive()) {
1027 // we can just remove entry from meta, referencing to this chunk,
1028 // but store maybe R/O, and it's not properly started yet,
1029 // so lets make this chunk "dead" and taking no space,
1030 // and it will be automatically removed later.
1031 c.block = 0;
1032 c.len = 0;
1033 if (c.unused == 0) {
1034 c.unused = getCreationTime();
1035 }
1036 if (c.unusedAtVersion == 0) {
1037 c.unusedAtVersion = INITIAL_VERSION;
1038 }
1039 }
1040 }
1041 } catch(Exception ignored) {
1042 verified = false;
1043 }
1044 if (verified) {
1045 return true;
1046 }
1047 }
1048 return false;
1049 }
1050
1051 @SuppressWarnings("unchecked")
1052 private C[] createChunksArray(int sz) {
1053 return (C[]) new Chunk[sz];
1054 }
1055
1056 private C readChunkHeader(long block) {
1057 long p = block * FileStore.BLOCK_SIZE;
1058 ByteBuffer buff = readFully((C)null, p, Chunk.MAX_HEADER_LENGTH);
1059 Throwable exception = null;
1060 try {
1061 C chunk = createChunk(Chunk.readChunkHeader(buff));
1062 if (chunk.block == 0) {
1063 chunk.block = block;
1064 }
1065 if (chunk.block == block) {
1066 return chunk;
1067 }
1068 } catch (MVStoreException e) {
1069 exception = e.getCause();
1070 } catch (Throwable e) {
1071 // there could be various reasons
1072 exception = e;
1073 }
1074 throw DataUtils.newMVStoreException(
1075 DataUtils.ERROR_FILE_CORRUPT,
1076 "File corrupt reading chunk at position {0}", p, exception);
1077 }
1078
1079 protected Iterable<C> getChunksFromLayoutMap() {
1080 return getChunksFromLayoutMap(layout);
1081 }
1082
1083 private Iterable<C> getChunksFromLayoutMap(MVMap<String, String> layoutMap) {
1084 return () -> new Iterator<C>() {
1085 private final Cursor<String, String> cursor = layoutMap.cursor(DataUtils.META_CHUNK);
1086 private C nextChunk;
1087
1088 @Override
1089 public boolean hasNext() {
1090 if(nextChunk == null && cursor.hasNext()) {
1091 if (cursor.next().startsWith(DataUtils.META_CHUNK)) {
1092 nextChunk = createChunk(cursor.getValue());
1093 // might be there already, due to layout traversal
1094 // see readPage() ... getChunkIfFound(),
1095 // then take existing one instead
1096 C existingChunk = chunks.putIfAbsent(nextChunk.id, nextChunk);
1097 if (existingChunk != null) {
1098 nextChunk = existingChunk;
1099 }
1100 }
1101 }
1102 return nextChunk != null;
1103 }
1104
1105 @Override
1106 public C next() {
1107 if (!hasNext()) {
1108 throw new NoSuchElementException();
1109 }
1110 C chunk = nextChunk;
1111 nextChunk = null;
1112 return chunk;
1113 }
1114 };
1115 }
1116
1117
1118 /**
1119 * Read a chunk header and footer, and verify the stored data is consistent.
1120 *
1121 * @param chunk to verify existence
1122 * @return true if Chunk exists in the file and is valid, false otherwise
1123 */
1124 private boolean isValidChunk(C chunk) {
1125 return readChunkHeaderAndFooter(chunk.block, chunk.id) != null;
1126 }
1127
1128 /**
1129 * Read a chunk header and footer, and verify the stored data is consistent.
1130 *
1131 * @param block the block
1132 * @param expectedId of the chunk
1133 * @return the chunk, or null if the header or footer don't match or are not
1134 * consistent
1135 */
1136 protected final C readChunkHeaderAndFooter(long block, int expectedId) {
1137 C header = readChunkHeaderOptionally(block, expectedId);
1138 if (header != null) {
1139 C footer = readChunkFooter(block + header.len);
1140 if (footer == null || footer.id != expectedId || footer.block != header.block) {
1141 return null;
1142 }
1143 }
1144 return header;
1145 }
1146
1147 protected final C readChunkHeaderOptionally(long block, int expectedId) {
1148 C chunk = readChunkHeaderOptionally(block);
1149 return chunk == null || chunk.id != expectedId ? null : chunk;
1150 }
1151
1152 protected final C readChunkHeaderOptionally(long block) {
1153 try {
1154 C chunk = readChunkHeader(block);
1155 return chunk.block != block ? null : chunk;
1156 } catch (Exception ignore) {
1157 return null;
1158 }
1159 }
1160
1161 /**
1162 * Try to read a chunk footer.
1163 *
1164 * @param block the index of the next block after the chunk
1165 * @return the chunk, or null if not successful
1166 */
1167 protected final C readChunkFooter(long block) {
1168 // the following can fail for various reasons
1169 try {
1170 // read the chunk footer of the last block of the file
1171 long pos = block * FileStore.BLOCK_SIZE - Chunk.FOOTER_LENGTH;
1172 if(pos < 0) {
1173 return null;
1174 }
1175 ByteBuffer lastBlock = readFully((C)null, pos, Chunk.FOOTER_LENGTH);
1176 byte[] buff = new byte[Chunk.FOOTER_LENGTH];
1177 lastBlock.get(buff);
1178 HashMap<String, String> m = DataUtils.parseChecksummedMap(buff);
1179 if (m != null) {
1180 C chunk = createChunk(m);
1181 if (chunk.block == 0) {
1182 chunk.block = block - chunk.len;
1183 }
1184 return chunk;
1185 }
1186 } catch (Exception e) {
1187 // ignore
1188 }
1189 return null;
1190 }
1191
1192 /**
1193 * Get a buffer for writing. This caller must synchronize on the store
1194 * before calling the method and until after using the buffer.
1195 *
1196 * @return the buffer
1197 */
1198 public WriteBuffer getWriteBuffer() {
1199 WriteBuffer buff = writeBufferPool.poll();
1200 if (buff != null) {
1201 buff.clear();
1202 } else {
1203 buff = new WriteBuffer();
1204 }
1205 return buff;
1206 }
1207
1208 /**
1209 * Release a buffer for writing. This caller must synchronize on the store
1210 * before calling the method and until after using the buffer.
1211 *
1212 * @param buff the buffer than can be re-used
1213 */
1214 public void releaseWriteBuffer(WriteBuffer buff) {
1215 if (buff.capacity() <= 4 * 1024 * 1024) {
1216 writeBufferPool.offer(buff);
1217 }
1218 }
1219
1220 /**
1221 * The time the store was created, in milliseconds since 1970.
1222 * @return creation time
1223 */
1224 public long getCreationTime() {
1225 return creationTime;
1226 }
1227
1228 protected final int getAutoCompactFillRate() {
1229 return autoCompactFillRate;
1230 }
1231
1232
1233 public void sync() {}
1234
1235 public abstract int getFillRate();
1236
1237 /**
1238 * Shrink store if possible, and if at least a given percentage can be
1239 * saved.
1240 *
1241 * @param minPercent the minimum percentage to save
1242 */
1243 protected abstract void shrinkStoreIfPossible(int minPercent);
1244
1245
1246 /**
1247 * Get the file size.
1248 *
1249 * @return the file size
1250 */
1251 public long size() {
1252 return size;
1253 }
1254
1255 protected final void setSize(long size) {
1256 this.size = size;
1257 }
1258
1259 /**
1260 * Get the number of write operations since this store was opened.
1261 * For file based stores, this is the number of file write operations.
1262 *
1263 * @return the number of write operations
1264 */
1265 public long getWriteCount() {
1266 return writeCount.get();
1267 }
1268
1269 /**
1270 * Get the number of written bytes since this store was opened.
1271 *
1272 * @return the number of write operations
1273 */
1274 private long getWriteBytes() {
1275 return writeBytes.get();
1276 }
1277
1278 /**
1279 * Get the number of read operations since this store was opened.
1280 * For file based stores, this is the number of file read operations.
1281 *
1282 * @return the number of read operations
1283 */
1284 public long getReadCount() {
1285 return readCount.get();
1286 }
1287
1288 /**
1289 * Get the number of read bytes since this store was opened.
1290 *
1291 * @return the number of write operations
1292 */
1293 public long getReadBytes() {
1294 return readBytes.get();
1295 }
1296
1297 public boolean isReadOnly() {
1298 return readOnly;
1299 }
1300
1301 /**
1302 * Get the default retention time for this store in milliseconds.
1303 *
1304 * @return the retention time
1305 */
1306 public int getDefaultRetentionTime() {
1307 return 45_000;
1308 }
1309
1310 public void clear() {
1311 saveChunkLock.lock();
1312 try {
1313 deadChunks.clear();
1314 lastChunk = null;
1315 readCount.set(0);
1316 readBytes.set(0);
1317 writeCount.set(0);
1318 writeBytes.set(0);
1319 } finally {
1320 saveChunkLock.unlock();
1321 }
1322 }
1323
1324 /**
1325 * Get the file name.
1326 *
1327 * @return the file name
1328 */
1329 public String getFileName() {
1330 return fileName;
1331 }
1332
1333 protected final MVStore getMvStore() {
1334 return mvStore;
1335 }
1336
1337 /**
1338 * Mark the space as in use.
1339 *
1340 * @param pos the position in bytes
1341 * @param length the number of bytes
1342 */
1343 protected abstract void markUsed(long pos, int length);
1344
1345 public abstract void backup(ZipOutputStream out) throws IOException;
1346
1347 protected final ConcurrentMap<Integer, C> getChunks() {
1348 return chunks;
1349 }
1350
1351 protected Collection<C> getRewriteCandidates() {
1352 return null;
1353 }
1354
1355 public boolean isSpaceReused() {
1356 return true;
1357 }
1358
1359 public void setReuseSpace(boolean reuseSpace) {
1360 }
1361
1362 protected final void store() {
1363 serializationLock.unlock();
1364 try {
1365 mvStore.storeNow();
1366 } finally {
1367 serializationLock.lock();
1368 }
1369 }
1370
1371 private int serializationExecutorHWM;
1372
1373
1374 final void storeIt(ArrayList<Page<?,?>> changed, long version, boolean syncWrite) throws ExecutionException {
1375 lastCommitTime = getTimeSinceCreation();
1376 serializationExecutorHWM = submitOrRun(serializationExecutor,
1377 () -> serializeAndStore(syncWrite, changed, lastCommitTime, version),
1378 syncWrite, PIPE_LENGTH, serializationExecutorHWM);
1379 }
1380
1381 private static int submitOrRun(ThreadPoolExecutor executor, Runnable action,
1382 boolean syncRun, int threshold, int hwm) throws ExecutionException {
1383 if (executor != null) {
1384 try {
1385 Future<?> future = executor.submit(action);
1386 int size = executor.getQueue().size();
1387 if (size > hwm) {
1388 hwm = size;
1389 // System.err.println(executor + " HWM: " + hwm);
1390 }
1391 if (syncRun || size > threshold) {
1392 try {
1393 future.get();
1394 } catch (InterruptedException ignore) {/**/}
1395 }
1396 return hwm;
1397 } catch (RejectedExecutionException ex) {
1398 assert executor.isShutdown();
1399 Utils.shutdownExecutor(executor);
1400 }
1401 }
1402 action.run();
1403 return hwm;
1404 }
1405
1406
1407 private int bufferSaveExecutorHWM;
1408
1409 private void serializeAndStore(boolean syncRun, ArrayList<Page<?,?>> changed, long time, long version) {
1410 serializationLock.lock();
1411 try {
1412 C lastChunk = null;
1413 int chunkId = lastChunkId;
1414 if (chunkId != 0) {
1415 chunkId &= Chunk.MAX_ID;
1416 lastChunk = chunks.get(chunkId);
1417 assert lastChunk != null : lastChunkId + " ("+chunkId+") " + chunks;
1418 // never go backward in time
1419 time = Math.max(lastChunk.time, time);
1420 }
1421 C c;
1422 WriteBuffer buff;
1423 try {
1424 c = createChunk(time, version);
1425 buff = getWriteBuffer();
1426 serializeToBuffer(buff, changed, c, lastChunk);
1427 chunks.put(c.id, c);
1428 } catch (Throwable t) {
1429 lastChunkId = chunkId;
1430 throw t;
1431 }
1432
1433 bufferSaveExecutorHWM = submitOrRun(bufferSaveExecutor, () -> storeBuffer(c, buff),
1434 syncRun, 5, bufferSaveExecutorHWM);
1435
1436 for (Page<?, ?> p : changed) {
1437 p.releaseSavedPages();
1438 }
1439 } catch (MVStoreException e) {
1440 mvStore.panic(e);
1441 } catch (Throwable e) {
1442 mvStore.panic(DataUtils.newMVStoreException(DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
1443 } finally {
1444 serializationLock.unlock();
1445 }
1446 }
1447
1448 private void serializeToBuffer(WriteBuffer buff, ArrayList<Page<?, ?>> changed, C c, C previousChunk) {
1449 // need to patch the header later
1450 int headerLength = c.estimateHeaderSize();
1451 buff.position(headerLength);
1452 c.next = headerLength;
1453
1454 long version = c.version;
1455 PageSerializationManager pageSerializationManager = new PageSerializationManager(c, buff);
1456 for (Page<?,?> p : changed) {
1457 String key = MVMap.getMapRootKey(p.getMapId());
1458 if (p.getTotalCount() == 0) {
1459 layout.remove(key);
1460 } else {
1461 p.writeUnsavedRecursive(pageSerializationManager);
1462 long root = p.getPos();
1463 layout.put(key, Long.toHexString(root));
1464 }
1465 }
1466
1467 acceptChunkOccupancyChanges(c.time, version);
1468
1469 if (previousChunk != null) {
1470 // the metadata of the last chunk was not stored in the layout map yet,
1471 // just was embedded into the chunk itself, and this need to be done now
1472 // (it's better not to update right after storing, because that
1473 // would modify the meta map again)
1474 if (!layout.containsKey(Chunk.getMetaKey(previousChunk.id))) {
1475 saveChunkMetadataChanges(previousChunk);
1476 }
1477 }
1478
1479 RootReference<String,String> layoutRootReference = layout.setWriteVersion(version);
1480 assert layoutRootReference != null;
1481 assert layoutRootReference.version == version : layoutRootReference.version + " != " + version;
1482
1483 acceptChunkOccupancyChanges(c.time, version);
1484
1485 mvStore.onVersionChange(version);
1486
1487 Page<String,String> layoutRoot = layoutRootReference.root;
1488 layoutRoot.writeUnsavedRecursive(pageSerializationManager);
1489 c.layoutRootPos = layoutRoot.getPos();
1490 changed.add(layoutRoot);
1491
1492 // last allocated map id should be captured after the meta map was saved, because
1493 // this will ensure that concurrently created map, which made it into meta before save,
1494 // will have it's id reflected in mapid header field of the currently written chunk
1495 c.mapId = mvStore.getLastMapId();
1496
1497 c.tocPos = buff.position();
1498 pageSerializationManager.serializeToC();
1499 int chunkLength = buff.position();
1500
1501 // add the store header and round to the next block
1502 int length = MathUtils.roundUpInt(chunkLength + Chunk.FOOTER_LENGTH, FileStore.BLOCK_SIZE);
1503 buff.limit(length);
1504 c.len = buff.limit() / FileStore.BLOCK_SIZE;
1505 c.buffer = buff.getBuffer();
1506 }
1507
1508 private void storeBuffer(C c, WriteBuffer buff) {
1509 saveChunkLock.lock();
1510 try {
1511 if (closed) {
1512 throw DataUtils.newMVStoreException(DataUtils.ERROR_WRITING_FAILED, "This fileStore is closed");
1513 }
1514
1515 int headerLength = (int)c.next;
1516
1517 allocateChunkSpace(c, buff);
1518
1519 buff.position(0);
1520 c.writeChunkHeader(buff, headerLength);
1521 buff.position(buff.limit() - Chunk.FOOTER_LENGTH);
1522 buff.put(c.getFooterBytes());
1523 buff.position(0);
1524
1525 writeChunk(c, buff);
1526 lastChunk = c;
1527 } catch (MVStoreException e) {
1528 mvStore.panic(e);
1529 } catch (Throwable e) {
1530 mvStore.panic(DataUtils.newMVStoreException(DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
1531 } finally {
1532 saveChunkLock.unlock();
1533 c.buffer = null;
1534 releaseWriteBuffer(buff);
1535 }
1536 }
1537
1538 /**
1539 * Apply the freed space to the chunk metadata. The metadata is updated, but
1540 * completely free chunks are not removed from the set of chunks, and the
1541 * disk space is not yet marked as free. They are queued instead and wait until
1542 * their usage is over.
1543 */
1544 private void acceptChunkOccupancyChanges(long time, long version) {
1545 assert serializationLock.isHeldByCurrentThread();
1546 if (hasPersistentData()) {
1547 Set<C> modifiedChunks = new HashSet<>();
1548 while (true) {
1549 RemovedPageInfo rpi;
1550 while ((rpi = removedPages.peek()) != null && rpi.version < version) {
1551 rpi = removedPages.poll(); // could be different from the peeked one
1552 assert rpi != null; // since nobody else retrieves from queue
1553 assert rpi.version < version : rpi + " < " + version;
1554 int chunkId = rpi.getPageChunkId();
1555 C chunk = chunks.get(chunkId);
1556 assert !mvStore.isOpen() || chunk != null : chunkId;
1557 if (chunk != null) {
1558 modifiedChunks.add(chunk);
1559 if (chunk.accountForRemovedPage(rpi.getPageNo(), rpi.getPageLength(),
1560 rpi.isPinned(), time, rpi.version)) {
1561 registerDeadChunk(chunk);
1562 }
1563 }
1564 }
1565 if (modifiedChunks.isEmpty()) {
1566 return;
1567 }
1568 for (C chunk : modifiedChunks) {
1569 saveChunkMetadataChanges(chunk);
1570 }
1571 modifiedChunks.clear();
1572 }
1573 }
1574 }
1575
1576 /**
1577 * Get the current fill rate (percentage of used space in the file). Unlike
1578 * the fill rate of the store, here we only account for chunk data; the fill
1579 * rate here is how much of the chunk data is live (still referenced). Young
1580 * chunks are considered live.
1581 *
1582 * @return the fill rate, in percent (100 is completely full)
1583 */
1584 public int getChunksFillRate() {
1585 return getChunksFillRate(true);
1586 }
1587
1588 int getRewritableChunksFillRate() {
1589 return getChunksFillRate(false);
1590 }
1591
1592 private int getChunksFillRate(boolean all) {
1593 long maxLengthSum = 1;
1594 long maxLengthLiveSum = 1;
1595 long time = getTimeSinceCreation();
1596 for (C c : chunks.values()) {
1597 if (all || isRewritable(c, time)) {
1598 assert c.maxLen >= 0;
1599 maxLengthSum += c.maxLen;
1600 maxLengthLiveSum += c.maxLenLive;
1601 }
1602 }
1603 // the fill rate of all chunks combined
1604 int fillRate = (int) (100 * maxLengthLiveSum / maxLengthSum);
1605 return fillRate;
1606 }
1607
1608 /**
1609 * Get data chunks count.
1610 *
1611 * @return number of existing chunks in store.
1612 */
1613 private int getChunkCount() {
1614 return chunks.size();
1615 }
1616
1617 /**
1618 * Get data pages count.
1619 *
1620 * @return number of existing pages in store.
1621 */
1622 private int getPageCount() {
1623 int count = 0;
1624 for (C chunk : chunks.values()) {
1625 count += chunk.pageCount;
1626 }
1627 return count;
1628 }
1629
1630 /**
1631 * Get live data pages count.
1632 *
1633 * @return number of existing live pages in store.
1634 */
1635 private int getLivePageCount() {
1636 int count = 0;
1637 for (C chunk : chunks.values()) {
1638 count += chunk.pageCountLive;
1639 }
1640 return count;
1641 }
1642
1643 /**
1644 * Put the page in the cache.
1645 * @param page the page
1646 */
1647 void cachePage(Page<?,?> page) {
1648 if (cache != null) {
1649 cache.put(page.getPos(), page, page.getMemory());
1650 }
1651 }
1652
1653 /**
1654 * Get the maximum cache size, in MB.
1655 * Note that this does not include the page chunk references cache, which is
1656 * 25% of the size of the page cache.
1657 *
1658 * @return the cache size
1659 */
1660 public int getCacheSize() {
1661 if (cache == null) {
1662 return 0;
1663 }
1664 return (int) (cache.getMaxMemory() >> 20);
1665 }
1666
1667 /**
1668 * Get the amount of memory used for caching, in MB.
1669 * Note that this does not include the page chunk references cache, which is
1670 * 25% of the size of the page cache.
1671 *
1672 * @return the amount of memory used for caching
1673 */
1674 public int getCacheSizeUsed() {
1675 if (cache == null) {
1676 return 0;
1677 }
1678 return (int) (cache.getUsedMemory() >> 20);
1679 }
1680
1681 /**
1682 * Set the read cache size in MB.
1683 *
1684 * @param mb the cache size in MB.
1685 */
1686 public void setCacheSize(int mb) {
1687 final long bytes = (long) mb * 1024 * 1024;
1688 if (cache != null) {
1689 cache.setMaxMemory(bytes);
1690 cache.clear();
1691 }
1692 }
1693
1694 void cacheToC(C chunk, long[] toc) {
1695 chunksToC.put(chunk.version, toc, toc.length * 8L + Constants.MEMORY_ARRAY);
1696 }
1697
1698 private long[] cleanToCCache(C chunk) {
1699 return chunksToC.remove(chunk.version);
1700 }
1701
1702 public void populateInfo(BiConsumer<String, String> consumer) {
1703 consumer.accept("info.FILE_WRITE", Long.toString(getWriteCount()));
1704 consumer.accept("info.FILE_WRITE_BYTES", Long.toString(getWriteBytes()));
1705 consumer.accept("info.FILE_READ", Long.toString(getReadCount()));
1706 consumer.accept("info.FILE_READ_BYTES", Long.toString(getReadBytes()));
1707 consumer.accept("info.FILL_RATE", Integer.toString(getFillRate()));
1708 consumer.accept("info.CHUNKS_FILL_RATE", Integer.toString(getChunksFillRate()));
1709 consumer.accept("info.CHUNKS_FILL_RATE_RW", Integer.toString(getRewritableChunksFillRate()));
1710 consumer.accept("info.FILE_SIZE", Long.toString(size()));
1711 consumer.accept("info.CHUNK_COUNT", Long.toString(getChunkCount()));
1712 consumer.accept("info.PAGE_COUNT", Long.toString(getPageCount()));
1713 consumer.accept("info.PAGE_COUNT_LIVE", Long.toString(getLivePageCount()));
1714 consumer.accept("info.PAGE_SIZE", Long.toString(getMaxPageSize()));
1715 consumer.accept("info.CACHE_MAX_SIZE", Integer.toString(getCacheSize()));
1716 consumer.accept("info.CACHE_SIZE", Integer.toString(getCacheSizeUsed()));
1717 consumer.accept("info.CACHE_HIT_RATIO", Integer.toString(getCacheHitRatio()));
1718 consumer.accept("info.TOC_CACHE_HIT_RATIO", Integer.toString(getTocCacheHitRatio()));
1719 }
1720
1721
1722 public int getCacheHitRatio() {
1723 return getCacheHitRatio(cache);
1724 }
1725
1726 public int getTocCacheHitRatio() {
1727 return getCacheHitRatio(chunksToC);
1728 }
1729
1730 private static int getCacheHitRatio(CacheLongKeyLIRS<?> cache) {
1731 if (cache == null) {
1732 return 0;
1733 }
1734 long hits = cache.getHits();
1735 return (int) (100 * hits / (hits + cache.getMisses() + 1));
1736 }
1737
1738 boolean isBackgroundThread() {
1739 return Thread.currentThread() == backgroundWriterThread.get();
1740 }
1741
1742 @SuppressWarnings("ThreadJoinLoop")
1743 private void stopBackgroundThread(boolean waitForIt) {
1744 // Loop here is not strictly necessary, except for case of a spurious failure,
1745 // which should not happen with non-weak flavour of CAS operation,
1746 // but I've seen it, so just to be safe...
1747 BackgroundWriterThread t;
1748 while ((t = backgroundWriterThread.get()) != null) {
1749 if (backgroundWriterThread.compareAndSet(t, null)) {
1750 // if called from within the thread itself - can not join
1751 if (t != Thread.currentThread()) {
1752 synchronized (t.sync) {
1753 t.sync.notifyAll();
1754 }
1755
1756 if (waitForIt) {
1757 try {
1758 t.join();
1759 } catch (Exception e) {
1760 // ignore
1761 }
1762 }
1763 }
1764 shutdownExecutors();
1765 break;
1766 }
1767 }
1768 }
1769
1770 private void shutdownExecutors() {
1771 Utils.shutdownExecutor(serializationExecutor);
1772 serializationExecutor = null;
1773 Utils.shutdownExecutor(bufferSaveExecutor);
1774 bufferSaveExecutor = null;
1775 }
1776
1777 private Iterable<C> findOldChunks(int writeLimit, int targetFillRate) {
1778 assert hasPersistentData();
1779 long time = getTimeSinceCreation();
1780
1781 // the queue will contain chunks we want to free up
1782 // the smaller the collectionPriority, the more desirable this chunk's re-write is
1783 // queue will be ordered in descending order of collectionPriority values,
1784 // so most desirable chunks will stay at the tail
1785 PriorityQueue<C> queue = new PriorityQueue<>(this.chunks.size() / 4 + 1,
1786 (o1, o2) -> {
1787 int comp = Integer.compare(o2.collectPriority, o1.collectPriority);
1788 if (comp == 0) {
1789 comp = Long.compare(o2.maxLenLive, o1.maxLenLive);
1790 }
1791 return comp;
1792 });
1793
1794 long totalSize = 0;
1795 long latestVersion = lastChunkVersion() + 1;
1796
1797 Collection<C> candidates = getRewriteCandidates();
1798 if (candidates == null) {
1799 candidates = chunks.values();
1800 }
1801 for (C chunk : candidates) {
1802 // only look at chunk older than the retention time
1803 // (it's possible to compact chunks earlier, but right
1804 // now we don't do that)
1805 int fillRate = chunk.getFillRate();
1806 if (isRewritable(chunk, time) && fillRate <= targetFillRate) {
1807 long age = Math.max(1, latestVersion - chunk.version);
1808 chunk.collectPriority = (int) (fillRate * 1000 / age);
1809 totalSize += chunk.maxLenLive;
1810 queue.offer(chunk);
1811 while (totalSize > writeLimit) {
1812 C removed = queue.poll();
1813 if (removed == null) {
1814 break;
1815 }
1816 totalSize -= removed.maxLenLive;
1817 }
1818 }
1819 }
1820
1821 return queue.isEmpty() ? null : queue;
1822 }
1823
1824
1825 /**
1826 * Commit and save all changes, if there are any, and compact the store if
1827 * needed.
1828 */
1829 void writeInBackground() {
1830 try {
1831 if (mvStore.isOpen() && !isReadOnly()) {
1832 // could also commit when there are many unsaved pages,
1833 // but according to a test it doesn't really help
1834 long time = getTimeSinceCreation();
1835 if (time > lastCommitTime + autoCommitDelay) {
1836 mvStore.tryCommit();
1837 }
1838 doHousekeeping(mvStore);
1839 autoCompactLastFileOpCount = getWriteCount() + getReadCount();
1840 }
1841 } catch (InterruptedException ignore) {
1842 } catch (Throwable e) {
1843 if (!mvStore.handleException(e)) {
1844 throw e;
1845 }
1846 }
1847 }
1848
1849 protected boolean rewriteChunks(int writeLimit, int targetFillRate) {
1850 serializationLock.lock();
1851 try {
1852 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
1853 try {
1854 acceptChunkOccupancyChanges(getTimeSinceCreation(), mvStore.getCurrentVersion());
1855 Iterable<C> old = findOldChunks(writeLimit, targetFillRate);
1856 if (old != null) {
1857 HashSet<Integer> idSet = createIdSet(old);
1858 return !idSet.isEmpty() && compactRewrite(idSet) > 0;
1859 }
1860 } finally {
1861 mvStore.deregisterVersionUsage(txCounter);
1862 }
1863 return false;
1864 } finally {
1865 serializationLock.unlock();
1866 }
1867 }
1868
1869 private static <C extends Chunk<C>> HashSet<Integer> createIdSet(Iterable<C> toCompact) {
1870 HashSet<Integer> set = new HashSet<>();
1871 for (C c : toCompact) {
1872 set.add(c.id);
1873 }
1874 return set;
1875 }
1876
1877 public void executeFilestoreOperation(Runnable operation) {
1878 // because serializationExecutor is a single-threaded one and
1879 // all task submissions to it are done under storeLock,
1880 // it is guaranteed, that upon this dummy task completion
1881 // there are no pending / in-progress task here
1882 Utils.flushExecutor(serializationExecutor);
1883 serializationLock.lock();
1884 try {
1885 // similarly, all task submissions to bufferSaveExecutor
1886 // are done under serializationLock, and upon this dummy task completion
1887 // it will be no pending / in-progress task here
1888 Utils.flushExecutor(bufferSaveExecutor);
1889 operation.run();
1890 } finally {
1891 serializationLock.unlock();
1892 }
1893 }
1894
1895 private int compactRewrite(Set<Integer> set) {
1896 acceptChunkOccupancyChanges(getTimeSinceCreation(), mvStore.getCurrentVersion());
1897 int rewrittenPageCount = rewriteChunks(set, false);
1898 acceptChunkOccupancyChanges(getTimeSinceCreation(), mvStore.getCurrentVersion());
1899 rewrittenPageCount += rewriteChunks(set, true);
1900 return rewrittenPageCount;
1901 }
1902
1903 private int rewriteChunks(Set<Integer> set, boolean secondPass) {
1904 int rewrittenPageCount = 0;
1905 for (int chunkId : set) {
1906 C chunk = chunks.get(chunkId);
1907 long[] toc = getToC(chunk);
1908 if (toc != null) {
1909 for (int pageNo = 0; (pageNo = chunk.occupancy.nextClearBit(pageNo)) < chunk.pageCount; ++pageNo) {
1910 long tocElement = toc[pageNo];
1911 int mapId = DataUtils.getPageMapId(tocElement);
1912 MVMap<String, String> metaMap = mvStore.getMetaMap();
1913 MVMap<?, ?> map = mapId == layout.getId() ? layout
1914 : mapId == metaMap.getId() ? metaMap : mvStore.getMap(mapId);
1915 if (map != null && !map.isClosed()) {
1916 assert !map.isSingleWriter();
1917 if (secondPass || DataUtils.isLeafPosition(tocElement)) {
1918 long pagePos = DataUtils.composePagePos(chunkId, tocElement);
1919 serializationLock.unlock();
1920 try {
1921 if (map.rewritePage(pagePos)) {
1922 ++rewrittenPageCount;
1923 if (mapId == metaMap.getId()) {
1924 mvStore.markMetaChanged();
1925 }
1926 }
1927 } finally {
1928 serializationLock.lock();
1929 }
1930 }
1931 }
1932 }
1933 }
1934 }
1935 return rewrittenPageCount;
1936 }
1937
1938
1939 /**
1940 * Read a page.
1941 *
1942 * @param map the map
1943 * @param pos the page position
1944 * @return the page
1945 */
1946 <K,V> Page<K,V> readPage(MVMap<K,V> map, long pos) {
1947 try {
1948 if (!DataUtils.isPageSaved(pos)) {
1949 throw DataUtils.newMVStoreException(
1950 DataUtils.ERROR_FILE_CORRUPT, "Position 0");
1951 }
1952 Page<K,V> page = readPageFromCache(pos);
1953 if (page == null) {
1954 C chunk = getChunk(pos);
1955 int pageOffset = DataUtils.getPageOffset(pos);
1956 while(true) {
1957 MVStoreException exception = null;
1958 ByteBuffer buff = chunk.buffer;
1959 boolean alreadySaved = buff == null;
1960 if (alreadySaved) {
1961 buff = chunk.readBufferForPage(this, pageOffset, pos);
1962 } else {
1963 // System.err.println("Using unsaved buffer " + chunk.id + "/" + pageOffset);
1964 buff = buff.duplicate();
1965 buff.position(pageOffset);
1966 buff = buff.slice();
1967 }
1968 try {
1969 page = Page.read(buff, pos, map);
1970 } catch (MVStoreException e) {
1971 exception = e;
1972 } catch (Exception e) {
1973 exception = DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
1974 "Unable to read the page at position 0x{0}, chunk {1}, offset 0x{3}",
1975 Long.toHexString(pos), chunk, Long.toHexString(pageOffset), e);
1976 }
1977 if (alreadySaved) {
1978 if (exception == null) {
1979 break;
1980 }
1981 throw exception;
1982 }
1983 }
1984 cachePage(page);
1985 }
1986 return page;
1987 } catch (MVStoreException e) {
1988 if (recoveryMode) {
1989 return map.createEmptyLeaf();
1990 }
1991 throw e;
1992 }
1993 }
1994
1995 /**
1996 * Get the chunk for the given position.
1997 *
1998 * @param pos the position
1999 * @return the chunk
2000 */
2001 private C getChunk(long pos) {
2002 int chunkId = DataUtils.getPageChunkId(pos);
2003 C c = chunks.get(chunkId);
2004 if (c == null) {
2005 String s = layout.get(Chunk.getMetaKey(chunkId));
2006 if (s == null) {
2007 throw DataUtils.newMVStoreException(
2008 DataUtils.ERROR_CHUNK_NOT_FOUND,
2009 "Chunk {0} not found", chunkId);
2010 }
2011 c = createChunk(s);
2012 if (!c.isSaved()) {
2013 throw DataUtils.newMVStoreException(
2014 DataUtils.ERROR_FILE_CORRUPT,
2015 "Chunk {0} is invalid", chunkId);
2016 }
2017 chunks.put(c.id, c);
2018 }
2019 return c;
2020 }
2021
2022 private int calculatePageNo(long pos) {
2023 int pageNo = -1;
2024 C chunk = getChunk(pos);
2025 long[] toC = getToC(chunk);
2026 if (toC != null) {
2027 int offset = DataUtils.getPageOffset(pos);
2028 int low = 0;
2029 int high = toC.length - 1;
2030 while (low <= high) {
2031 int mid = (low + high) >>> 1;
2032 long midVal = DataUtils.getPageOffset(toC[mid]);
2033 if (midVal < offset) {
2034 low = mid + 1;
2035 } else if (midVal > offset) {
2036 high = mid - 1;
2037 } else {
2038 pageNo = mid;
2039 break;
2040 }
2041 }
2042 }
2043 return pageNo;
2044 }
2045
2046 private void clearCaches() {
2047 if (cache != null) {
2048 cache.clear();
2049 }
2050 if (chunksToC != null) {
2051 chunksToC.clear();
2052 }
2053 removedPages.clear();
2054 }
2055
2056 private long[] getToC(C chunk) {
2057 if (chunk.tocPos == 0) {
2058 // legacy chunk without table of content
2059 return null;
2060 }
2061 long[] toc = chunksToC.get(chunk.id);
2062 if (toc == null) {
2063 toc = chunk.readToC(this);
2064 cacheToC(chunk, toc);
2065 }
2066 assert toc.length == chunk.pageCount : toc.length + " != " + chunk.pageCount;
2067 return toc;
2068 }
2069
2070 @SuppressWarnings("unchecked")
2071 private <K, V> Page<K, V> readPageFromCache(long pos) {
2072 return cache == null ? null : (Page<K,V>)cache.get(pos);
2073 }
2074
2075 /**
2076 * Remove a page.
2077 * @param pos the position of the page
2078 * @param version at which page was removed
2079 * @param pinned whether page is considered pinned
2080 * @param pageNo sequential page number within chunk
2081 */
2082 public void accountForRemovedPage(long pos, long version, boolean pinned, int pageNo) {
2083 assert DataUtils.isPageSaved(pos);
2084 if (pageNo < 0) {
2085 pageNo = calculatePageNo(pos);
2086 }
2087 RemovedPageInfo rpi = new RemovedPageInfo(pos, pinned, version, pageNo);
2088 removedPages.add(rpi);
2089 }
2090
2091
2092
2093 public final class PageSerializationManager
2094 {
2095 private final C chunk;
2096 private final WriteBuffer buff;
2097 private final List<Long> toc = new ArrayList<>();
2098
2099 PageSerializationManager(C chunk, WriteBuffer buff) {
2100 this.chunk = chunk;
2101 this.buff = buff;
2102 }
2103
2104 public WriteBuffer getBuffer() {
2105 return buff;
2106 }
2107
2108 private int getChunkId() {
2109 return chunk.id;
2110 }
2111
2112 public int getPageNo() {
2113 return toc.size();
2114 }
2115
2116 public long getPagePosition(int mapId, int offset, int pageLength, int type) {
2117 long tocElement = DataUtils.composeTocElement(mapId, offset, pageLength, type);
2118 toc.add(tocElement);
2119 long pagePos = DataUtils.composePagePos(chunk.id, tocElement);
2120 int chunkId = getChunkId();
2121 int check = DataUtils.getCheckValue(chunkId)
2122 ^ DataUtils.getCheckValue(offset)
2123 ^ DataUtils.getCheckValue(pageLength);
2124 buff.putInt(offset, pageLength).
2125 putShort(offset + 4, (short) check);
2126 return pagePos;
2127 }
2128
2129 public void onPageSerialized(Page<?,?> page, boolean isDeleted, int diskSpaceUsed, boolean isPinned) {
2130 cachePage(page);
2131 if (!page.isLeaf()) {
2132 // cache again - this will make sure nodes stays in the cache
2133 // for a longer time
2134 cachePage(page);
2135 }
2136 chunk.accountForWrittenPage(diskSpaceUsed, isPinned);
2137 if (isDeleted) {
2138 accountForRemovedPage(page.getPos(), chunk.version + 1, isPinned, page.pageNo);
2139 }
2140 }
2141
2142 public void serializeToC() {
2143 long[] tocArray = new long[toc.size()];
2144 int index = 0;
2145 for (long tocElement : toc) {
2146 tocArray[index++] = tocElement;
2147 buff.putLong(tocElement);
2148 mvStore.countNewPage(DataUtils.isLeafPosition(tocElement));
2149 }
2150 cacheToC(chunk, tocArray);
2151 }
2152 }
2153
2154
2155 private static final class RemovedPageInfo implements Comparable<RemovedPageInfo> {
2156 final long version;
2157 final long removedPageInfo;
2158
2159 RemovedPageInfo(long pagePos, boolean pinned, long version, int pageNo) {
2160 this.removedPageInfo = createRemovedPageInfo(pagePos, pinned, pageNo);
2161 this.version = version;
2162 }
2163
2164 @Override
2165 public int compareTo(RemovedPageInfo other) {
2166 return Long.compare(version, other.version);
2167 }
2168
2169 int getPageChunkId() {
2170 return DataUtils.getPageChunkId(removedPageInfo);
2171 }
2172
2173 int getPageNo() {
2174 return DataUtils.getPageOffset(removedPageInfo);
2175 }
2176
2177 int getPageLength() {
2178 return DataUtils.getPageMaxLength(removedPageInfo);
2179 }
2180
2181 /**
2182 * Find out if removed page was pinned (can not be evacuated to a new chunk).
2183 * @return true if page has been pinned
2184 */
2185 boolean isPinned() {
2186 return (removedPageInfo & 1) == 1;
2187 }
2188
2189 /**
2190 * Transforms saved page position into removed page info by
2191 * replacing "page offset" with "page sequential number" and
2192 * "page type" bit with "pinned page" flag.
2193 * @param pagePos of the saved page
2194 * @param isPinned whether page belong to a "single writer" map
2195 * @param pageNo 0-based sequential page number within containing chunk
2196 * @return removed page info that contains chunk id, page number, page length and pinned flag
2197 */
2198 private static long createRemovedPageInfo(long pagePos, boolean isPinned, int pageNo) {
2199 assert pageNo >= 0;
2200 assert pageNo >> 26 == 0;
2201
2202 long result = (pagePos & ~((0xFFFFFFFFL << 6) | 1)) | ((long)pageNo << 6);
2203 if (isPinned) {
2204 result |= 1;
2205 }
2206 return result;
2207 }
2208
2209 @Override
2210 public String toString() {
2211 return "RemovedPageInfo{" +
2212 "version=" + version +
2213 ", chunk=" + getPageChunkId() +
2214 ", pageNo=" + getPageNo() +
2215 ", len=" + getPageLength() +
2216 (isPinned() ? ", pinned" : "") +
2217 '}';
2218 }
2219 }
2220
2221 /**
2222 * A background writer thread to automatically store changes from time to
2223 * time.
2224 */
2225 private static final class BackgroundWriterThread extends Thread {
2226
2227 public final Object sync = new Object();
2228 private final FileStore<?> store;
2229 private final int sleep;
2230
2231 BackgroundWriterThread(FileStore<?> store, int sleep, String fileStoreName) {
2232 super("MVStore background writer " + fileStoreName);
2233 this.store = store;
2234 this.sleep = sleep;
2235 setDaemon(true);
2236 }
2237
2238 @Override
2239 public void run() {
2240 while (store.isBackgroundThread()) {
2241 synchronized (sync) {
2242 try {
2243 sync.wait(sleep);
2244 } catch (InterruptedException ignore) {/**/}
2245 }
2246 if (!store.isBackgroundThread()) {
2247 break;
2248 }
2249 store.writeInBackground();
2250 }
2251 }
2252 }
2253 }