Debian Codegraph @

src/main/org/h2/mvstore/MVStore.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 java.lang.Thread.UncaughtExceptionHandler;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.Deque;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.Locale;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.concurrent.Callable;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.atomic.AtomicInteger;
24 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
25 import java.util.concurrent.atomic.AtomicLong;
26 import java.util.concurrent.locks.ReentrantLock;
27 import java.util.function.BiConsumer;
28 import java.util.function.LongConsumer;
29 import java.util.function.Predicate;
30 import org.h2.compress.CompressDeflate;
31 import org.h2.compress.CompressLZF;
32 import org.h2.compress.Compressor;
33 import org.h2.mvstore.type.StringDataType;
34 import org.h2.store.fs.FileUtils;
35 import org.h2.util.Utils;
36
37 /*
38
39 TODO:
40
41 Documentation
42 - rolling docs review: at "Metadata Map"
43 - better document that writes are in background thread
44 - better document how to do non-unique indexes
45 - document pluggable store and OffHeapStore
46
47 TransactionStore:
48 - ability to disable the transaction log,
49 if there is only one connection
50
51 MVStore:
52 - better and clearer memory usage accounting rules
53 (heap memory versus disk memory), so that even there is
54 never an out of memory
55 even for a small heap, and so that chunks
56 are still relatively big on average
57 - make sure serialization / deserialization errors don't corrupt the file
58 - test and possibly improve compact operation (for large dbs)
59 - automated 'kill process' and 'power failure' test
60 - defragment (re-creating maps, specially those with small pages)
61 - store number of write operations per page (maybe defragment
62 if much different than count)
63 - r-tree: nearest neighbor search
64 - use a small object value cache (StringCache), test on Android
65 for default serialization
66 - MVStoreTool.dump should dump the data if possible;
67 possibly using a callback for serialization
68 - implement a sharded map (in one store, multiple stores)
69 to support concurrent updates and writes, and very large maps
70 - to save space when persisting very small transactions,
71 use a transaction log where only the deltas are stored
72 - serialization for lists, sets, sets, sorted sets, maps, sorted maps
73 - maybe rename 'rollback' to 'revert' to distinguish from transactions
74 - support other compression algorithms (deflate, LZ4,...)
75 - remove features that are not really needed; simplify the code
76 possibly using a separate layer or tools
77 (retainVersion?)
78 - optional pluggable checksum mechanism (per page), which
79 requires that everything is a page (including headers)
80 - rename "store" to "save", as "store" is used in "storeVersion"
81 - rename setStoreVersion to setDataVersion, setSchemaVersion or similar
82 - temporary file storage
83 - simple rollback method (rollback to last committed version)
84 - MVMap to implement SortedMap, then NavigableMap
85 - storage that splits database into multiple files,
86 to speed up compact and allow using trim
87 (by truncating / deleting empty files)
88 - add new feature to the file system API to avoid copying data
89 (reads that returns a ByteBuffer instead of writing into one)
90 for memory mapped files and off-heap storage
91 - support log structured merge style operations (blind writes)
92 using one map per level plus bloom filter
93 - have a strict call order MVStore -> MVMap -> Page -> FileStore
94 - autocommit commits, stores, and compacts from time to time;
95 the background thread should wait at least 90% of the
96 configured write delay to store changes
97 - compact* should also store uncommitted changes (if there are any)
98 - write a LSM-tree (log structured merge tree) utility on top of the MVStore
99 with blind writes and/or a bloom filter that
100 internally uses regular maps and merge sort
101 - chunk metadata: maybe split into static and variable,
102 or use a small page size for metadata
103 - data type "string": maybe use prefix compression for keys
104 - test chunk id rollover
105 - feature to auto-compact from time to time and on close
106 - compact very small chunks
107 - Page: to save memory, combine keys & values into one array
108 (also children & counts). Maybe remove some other
109 fields (childrenCount for example)
110 - Support SortedMap for MVMap
111 - compact: copy whole pages (without having to open all maps)
112 - maybe change the length code to have lower gaps
113 - test with very low limits (such as: short chunks, small pages)
114 - maybe allow to read beyond the retention time:
115 when compacting, move live pages in old chunks
116 to a map (possibly the metadata map) -
117 this requires a change in the compaction code, plus
118 a map lookup when reading old data; also, this
119 old data map needs to be cleaned up somehow;
120 maybe using an additional timeout
121 */
122
123 /**
124 * A persistent storage for maps.
125 */
126 public class MVStore implements AutoCloseable {
127
128 /**
129 * Store is open.
130 */
131 private static final int STATE_OPEN = 0;
132
133 /**
134 * Store is about to close now, but is still operational.
135 * Outstanding store operation by background writer or other thread may be in progress.
136 * New updates must not be initiated, unless they are part of a closing procedure itself.
137 */
138 private static final int STATE_STOPPING = 1;
139
140 /**
141 * Store is closed.
142 */
143 private static final int STATE_CLOSED = 2;
144
145 /**
146 * This designates the "last stored" version for a store which was
147 * just open for the first time.
148 */
149 static final long INITIAL_VERSION = -1;
150
151
152 /**
153 * Lock which governs access to major store operations: store(), close(), ...
154 * It serves as a replacement for synchronized(this), except it allows for
155 * non-blocking lock attempts.
156 */
157 private final ReentrantLock storeLock = new ReentrantLock(true);
158
159 /**
160 * Flag to refine the state under storeLock.
161 * It indicates that store() operation is running, and we have to prevent possible re-entrance.
162 */
163 private final AtomicBoolean storeOperationInProgress = new AtomicBoolean();
164
165 private volatile int state;
166
167 private final FileStore<?> fileStore;
168
169 private final boolean fileStoreShallBeClosed;
170
171 private final int keysPerPage;
172
173 private long updateCounter = 0;
174 private long updateAttemptCounter = 0;
175
176 /**
177 * The metadata map. Holds name -> id and id -> name and id -> metadata
178 * mapping for all maps. This is relatively slow changing part of metadata
179 */
180 private final MVMap<String, String> meta;
181
182 private final ConcurrentHashMap<Integer, MVMap<?, ?>> maps = new ConcurrentHashMap<>();
183
184 private final AtomicInteger lastMapId = new AtomicInteger();
185
186 private int versionsToKeep = 5;
187
188 /**
189 * The compression level for new pages (0 for disabled, 1 for fast, 2 for
190 * high). Even if disabled, the store may contain (old) compressed pages.
191 */
192 private final int compressionLevel;
193
194 private Compressor compressorFast;
195
196 private Compressor compressorHigh;
197
198 public final UncaughtExceptionHandler backgroundExceptionHandler;
199
200 private volatile long currentVersion;
201
202 /**
203 * Oldest store version in use. All version beyond this can be safely dropped
204 */
205 private final AtomicLong oldestVersionToKeep = new AtomicLong();
206
207 /**
208 * Ordered collection of all version usage counters for all versions starting
209 * from oldestVersionToKeep and up to current.
210 */
211 private final Deque<TxCounter> versions = new LinkedList<>();
212
213 /**
214 * Counter of open transactions for the latest (current) store version
215 */
216 private volatile TxCounter currentTxCounter = new TxCounter(currentVersion);
217
218 /**
219 * The estimated memory used by unsaved pages. This number is not accurate,
220 * also because it may be changed concurrently, and because temporary pages
221 * are counted.
222 */
223 private int unsavedMemory;
224 private final int autoCommitMemory;
225 private volatile boolean saveNeeded;
226
227 private volatile boolean metaChanged;
228
229
230 private volatile MVStoreException panicException;
231
232 private long lastTimeAbsolute;
233
234 private long leafCount;
235 private long nonLeafCount;
236
237 /**
238 * Callback for maintenance after some unused store versions were dropped
239 */
240 private volatile LongConsumer oldestVersionTracker;
241
242
243 /**
244 * Create and open the store.
245 *
246 * @param config the configuration to use
247 * @throws MVStoreException if the file is corrupt, or an exception
248 * occurred while opening
249 * @throws IllegalArgumentException if the directory does not exist
250 */
251 MVStore(Map<String, Object> config) {
252 compressionLevel = DataUtils.getConfigParam(config, "compress", 0);
253 String fileName = (String) config.get("fileName");
254 FileStore<?> fileStore = (FileStore<?>) config.get("fileStore");
255 boolean fileStoreShallBeOpen = false;
256 if (fileStore == null) {
257 if (fileName != null) {
258 fileStore = new SingleFileStore(config);
259 fileStoreShallBeOpen = true;
260 }
261 fileStoreShallBeClosed = true;
262 } else {
263 if (fileName != null) {
264 throw new IllegalArgumentException("fileName && fileStore");
265 }
266 Boolean fileStoreIsAdopted = (Boolean) config.get("fileStoreIsAdopted");
267 fileStoreShallBeClosed = fileStoreIsAdopted != null && fileStoreIsAdopted;
268 }
269 this.fileStore = fileStore;
270 keysPerPage = DataUtils.getConfigParam(config, "keysPerPage", 48);
271 backgroundExceptionHandler =
272 (UncaughtExceptionHandler)config.get("backgroundExceptionHandler");
273 if (fileStore != null) {
274 // 19 KB memory is about 1 KB storage
275 int kb = Math.max(1, Math.min(19, Utils.scaleForAvailableMemory(64))) * 1024;
276 kb = DataUtils.getConfigParam(config, "autoCommitBufferSize", kb);
277 autoCommitMemory = kb * 1024;
278 char[] encryptionKey = (char[]) config.remove("encryptionKey");
279 MVMap<String, String> metaMap = null;
280 // there is no need to lock store here, since it is not opened (or even created) yet,
281 // just to make some assertions happy, when they ensure single-threaded access
282 storeLock.lock();
283 try {
284 if (fileStoreShallBeOpen) {
285 boolean readOnly = config.containsKey("readOnly");
286 fileStore.open(fileName, readOnly, encryptionKey);
287 }
288 fileStore.bind(this);
289 metaMap = fileStore.start();
290 } catch (MVStoreException e) {
291 panic(e);
292 } finally {
293 if (encryptionKey != null) {
294 Arrays.fill(encryptionKey, (char) 0);
295 }
296 unlockAndCheckPanicCondition();
297 }
298
299 meta = metaMap;
300 scrubMetaMap();
301
302 // setAutoCommitDelay starts the thread, but only if
303 // the parameter is different from the old value
304 int delay = DataUtils.getConfigParam(config, "autoCommitDelay", 1000);
305 setAutoCommitDelay(delay);
306 } else {
307 autoCommitMemory = 0;
308 meta = openMetaMap();
309 }
310 onVersionChange(currentVersion);
311 }
312
313 public MVMap<String,String> openMetaMap() {
314 int metaId = fileStore != null ? fileStore.getMetaMapId(this::getNextMapId) : 1;
315 MVMap<String,String> map = new MVMap<>(this, metaId, StringDataType.INSTANCE, StringDataType.INSTANCE);
316 map.setRootPos(getRootPos(map.getId()), currentVersion);
317 return map;
318 }
319
320 private void scrubMetaMap() {
321 Set<String> keysToRemove = new HashSet<>();
322
323 // ensure that there is only one name mapped to each id
324 // this could be a leftover of an unfinished map rename
325 for (Iterator<String> it = meta.keyIterator(DataUtils.META_NAME); it.hasNext();) {
326 String key = it.next();
327 if (!key.startsWith(DataUtils.META_NAME)) {
328 break;
329 }
330 String mapName = key.substring(DataUtils.META_NAME.length());
331 int mapId = DataUtils.parseHexInt(meta.get(key));
332 String realMapName = getMapName(mapId);
333 if(!mapName.equals(realMapName)) {
334 keysToRemove.add(key);
335 }
336 }
337
338 for (String key : keysToRemove) {
339 meta.remove(key);
340 markMetaChanged();
341 }
342
343 for (Iterator<String> it = meta.keyIterator(DataUtils.META_MAP); it.hasNext();) {
344 String key = it.next();
345 if (!key.startsWith(DataUtils.META_MAP)) {
346 break;
347 }
348 String mapName = DataUtils.getMapName(meta.get(key));
349 String mapIdStr = key.substring(DataUtils.META_MAP.length());
350 // ensure that last map id is not smaller than max of any existing map ids
351 adjustLastMapId(DataUtils.parseHexInt(mapIdStr));
352 // each map should have a proper name
353 if(!mapIdStr.equals(meta.get(DataUtils.META_NAME + mapName))) {
354 meta.put(DataUtils.META_NAME + mapName, mapIdStr);
355 markMetaChanged();
356 }
357 }
358 }
359
360 private void unlockAndCheckPanicCondition() {
361 storeLock.unlock();
362 MVStoreException exception = getPanicException();
363 if (exception != null) {
364 closeImmediately();
365 throw exception;
366 }
367 }
368
369 public void panic(MVStoreException e) {
370 if (isOpen()) {
371 handleException(e);
372 panicException = e;
373 }
374 throw e;
375 }
376
377 public MVStoreException getPanicException() {
378 return panicException;
379 }
380
381 /**
382 * Open a store in exclusive mode. For a file-based store, the parent
383 * directory must already exist.
384 *
385 * @param fileName the file name (null for in-memory)
386 * @return the store
387 */
388 public static MVStore open(String fileName) {
389 HashMap<String, Object> config = new HashMap<>();
390 config.put("fileName", fileName);
391 return new MVStore(config);
392 }
393
394 /**
395 * Open a map with the default settings. The map is automatically create if
396 * it does not yet exist. If a map with this name is already open, this map
397 * is returned.
398 *
399 * @param <K> the key type
400 * @param <V> the value type
401 * @param name the name of the map
402 * @return the map
403 */
404 public <K, V> MVMap<K, V> openMap(String name) {
405 return openMap(name, new MVMap.Builder<>());
406 }
407
408 /**
409 * Open a map with the given builder. The map is automatically create if it
410 * does not yet exist. If a map with this name is already open, this map is
411 * returned.
412 *
413 * @param <M> the map type
414 * @param <K> the key type
415 * @param <V> the value type
416 * @param name the name of the map
417 * @param builder the map builder
418 * @return the map
419 */
420 public <M extends MVMap<K, V>, K, V> M openMap(String name, MVMap.MapBuilder<M, K, V> builder) {
421 int id = getMapId(name);
422 if (id >= 0) {
423 @SuppressWarnings("unchecked")
424 M map = (M) getMap(id);
425 if(map == null) {
426 map = openMap(id, builder);
427 }
428 assert builder.getKeyType() == null || map.getKeyType().getClass().equals(builder.getKeyType().getClass());
429 assert builder.getValueType() == null
430 || map.getValueType().getClass().equals(builder.getValueType().getClass());
431 return map;
432 } else {
433 HashMap<String, Object> c = new HashMap<>();
434 id = getNextMapId();
435 assert getMap(id) == null;
436 c.put("id", id);
437 long curVersion = currentVersion;
438 c.put("createVersion", curVersion);
439 M map = builder.create(this, c);
440 String x = Integer.toHexString(id);
441 meta.put(MVMap.getMapKey(id), map.asString(name));
442 String existing = meta.putIfAbsent(DataUtils.META_NAME + name, x);
443 if (existing != null) {
444 // looks like map was created concurrently, cleanup and re-start
445 meta.remove(MVMap.getMapKey(id));
446 return openMap(name, builder);
447 }
448 map.setRootPos(0, curVersion);
449 markMetaChanged();
450 @SuppressWarnings("unchecked")
451 M existingMap = (M) maps.putIfAbsent(id, map);
452 if (existingMap != null) {
453 map = existingMap;
454 }
455 return map;
456 }
457 }
458
459 /**
460 * Open an existing map with the given builder.
461 *
462 * @param <M> the map type
463 * @param <K> the key type
464 * @param <V> the value type
465 * @param id the map id
466 * @param builder the map builder
467 * @return the map
468 */
469 @SuppressWarnings("unchecked")
470 public <M extends MVMap<K, V>, K, V> M openMap(int id, MVMap.MapBuilder<M, K, V> builder) {
471 M map;
472 while ((map = (M)getMap(id)) == null) {
473 String configAsString = meta.get(MVMap.getMapKey(id));
474 DataUtils.checkArgument(configAsString != null, "Missing map with id {0}", id);
475 HashMap<String, Object> config = new HashMap<>(DataUtils.parseMap(configAsString));
476 config.put("id", id);
477 map = builder.create(this, config);
478 long root = getRootPos(id);
479 map.setRootPos(root, currentVersion);
480 if (maps.putIfAbsent(id, map) == null) {
481 break;
482 }
483 // looks like map has been concurrently created already, re-start
484 }
485 return map;
486 }
487
488 /**
489 * Get map by id.
490 *
491 * @param <K> the key type
492 * @param <V> the value type
493 * @param id map id
494 * @return Map
495 */
496 public <K, V> MVMap<K,V> getMap(int id) {
497 checkNotClosed();
498 @SuppressWarnings("unchecked")
499 MVMap<K, V> map = (MVMap<K, V>) maps.get(id);
500 return map;
501 }
502
503 /**
504 * Get the set of all map names.
505 *
506 * @return the set of names
507 */
508 public Set<String> getMapNames() {
509 HashSet<String> set = new HashSet<>();
510 checkNotClosed();
511 for (Iterator<String> it = meta.keyIterator(DataUtils.META_NAME); it.hasNext();) {
512 String x = it.next();
513 if (!x.startsWith(DataUtils.META_NAME)) {
514 break;
515 }
516 String mapName = x.substring(DataUtils.META_NAME.length());
517 set.add(mapName);
518 }
519 return set;
520 }
521
522 /**
523 * Get this store's layout map. This data is for informational purposes only. The
524 * data is subject to change in future versions.
525 * <p>
526 * The data in this map should not be modified (changing system data may corrupt the store).
527 * <p>
528 * The layout map contains the following entries:
529 * <pre>
530 * chunk.{chunkId} = {chunk metadata}
531 * root.{mapId} = {root position}
532 * </pre>
533 *
534 * @return the metadata map
535 */
536 public Map<String, String> getLayoutMap() {
537 return fileStore == null ? null : fileStore.getLayoutMap();
538 }
539
540 @SuppressWarnings("ReferenceEquality")
541 private boolean isRegularMap(MVMap<?,?> map) {
542 return map != meta && (fileStore == null || fileStore.isRegularMap(map));
543 }
544
545 /**
546 * Get the metadata map. This data is for informational purposes only. The
547 * data is subject to change in future versions.
548 * <p>
549 * The data in this map should not be modified (changing system data may corrupt the store).
550 * <p>
551 * The metadata map contains the following entries:
552 * <pre>
553 * name.{name} = {mapId}
554 * map.{mapId} = {map metadata}
555 * setting.storeVersion = {version}
556 * </pre>
557 *
558 * @return the metadata map
559 */
560 public MVMap<String, String> getMetaMap() {
561 checkNotClosed();
562 return meta;
563 }
564
565 /**
566 * Check whether a given map exists.
567 *
568 * @param name the map name
569 * @return true if it exists
570 */
571 public boolean hasMap(String name) {
572 return meta.containsKey(DataUtils.META_NAME + name);
573 }
574
575 /**
576 * Check whether a given map exists and has data.
577 *
578 * @param name the map name
579 * @return true if it exists and has data.
580 */
581 public boolean hasData(String name) {
582 return hasMap(name) && getRootPos(getMapId(name)) != 0;
583 }
584
585 void markMetaChanged() {
586 // changes in the metadata alone are usually not detected, as the meta
587 // map is changed after storing
588 metaChanged = true;
589 }
590
591 int getLastMapId() {
592 return lastMapId.get();
593 }
594
595 private int getNextMapId() {
596 return lastMapId.incrementAndGet();
597 }
598
599 void adjustLastMapId(int mapId) {
600 if (mapId > lastMapId.get()) {
601 lastMapId.set(mapId);
602 }
603 }
604
605 void resetLastMapId(int mapId) {
606 lastMapId.set(mapId);
607 }
608
609 /**
610 * Close the file and the store. Unsaved changes are written to disk first.
611 */
612 @Override
613 public void close() {
614 closeStore(true, 0);
615 }
616
617
618 /**
619 * Close the store. Pending changes are persisted.
620 * If time is allocated for housekeeping, chunks with a low
621 * fill rate are compacted, and some chunks are put next to each other.
622 * If time is unlimited then full compaction is performed, which uses
623 * different algorithm - opens alternative temp store and writes all live
624 * data there, then replaces this store with a new one.
625 *
626 * @param allowedCompactionTime time (in milliseconds) allotted for file
627 * compaction activity, 0 means no compaction,
628 * -1 means unlimited time (full compaction)
629 */
630 public void close(int allowedCompactionTime) {
631 if (!isClosed()) {
632 if (fileStore != null) {
633 boolean compactFully = allowedCompactionTime == -1;
634 if (fileStore.isReadOnly()) {
635 compactFully = false;
636 } else {
637 commit();
638 }
639 if (compactFully) {
640 allowedCompactionTime = 0;
641 }
642
643 closeStore(true, allowedCompactionTime);
644
645 String fileName = fileStore.getFileName();
646 if (compactFully && FileUtils.exists(fileName)) {
647 // the file could have been deleted concurrently,
648 // so only compact if the file still exists
649 MVStoreTool.compact(fileName, true);
650 }
651 } else {
652 close();
653 }
654 }
655 }
656
657 /**
658 * Close the file and the store, without writing anything.
659 * This will try to stop the background thread (without waiting for it).
660 * This method ignores all errors.
661 */
662 public void closeImmediately() {
663 try {
664 closeStore(false, 0);
665 } catch (Throwable e) {
666 handleException(e);
667 }
668 }
669
670 private void closeStore(boolean normalShutdown, int allowedCompactionTime) {
671 // If any other thead have already initiated closure procedure,
672 // isClosed() would wait until closure is done and then we jump out of the loop.
673 // This is a subtle difference between !isClosed() and isOpen().
674 while (!isClosed()) {
675 setAutoCommitDelay(-1);
676 setOldestVersionTracker(null);
677 storeLock.lock();
678 try {
679 if (state == STATE_OPEN) {
680 state = STATE_STOPPING;
681 try {
682 try {
683 if (normalShutdown && fileStore != null && !fileStore.isReadOnly()) {
684 for (MVMap<?, ?> map : maps.values()) {
685 if (map.isClosed()) {
686 fileStore.deregisterMapRoot(map.getId());
687 }
688 }
689 setRetentionTime(0);
690 commit();
691 assert oldestVersionToKeep.get() == currentVersion : oldestVersionToKeep.get() + " != "
692 + currentVersion;
693 fileStore.stop(allowedCompactionTime);
694 }
695
696 if (meta != null) {
697 meta.close();
698 }
699 for (MVMap<?, ?> m : new ArrayList<>(maps.values())) {
700 m.close();
701 }
702 maps.clear();
703 } finally {
704 if (fileStore != null && fileStoreShallBeClosed) {
705 fileStore.close();
706 }
707 }
708 } finally {
709 state = STATE_CLOSED;
710 }
711 }
712 } finally {
713 storeLock.unlock();
714 }
715 }
716 }
717
718 /**
719 * Indicates whether this MVStore is backed by FileStore,
720 * and therefore it's data will survive this store closure
721 * (but not necessary process termination in case of in-memory store).
722 * @return true if persistent
723 */
724 public boolean isPersistent() {
725 return fileStore != null;
726 }
727
728 /**
729 * Unlike regular commit this method returns immediately if there is commit
730 * in progress on another thread, otherwise it acts as regular commit.
731 *
732 * This method may return BEFORE this thread changes are actually persisted!
733 *
734 * @return the new version (incremented if there were changes) or -1 if there were no commit
735 */
736 public long tryCommit() {
737 return tryCommit(x -> true);
738 }
739
740 private long tryCommit(Predicate<MVStore> check) {
741 if (canStartStoreOperation() && storeLock.tryLock()) {
742 try {
743 if (check.test(this)) {
744 return store(false);
745 }
746 } finally {
747 unlockAndCheckPanicCondition();
748 }
749 }
750 return INITIAL_VERSION;
751 }
752
753 /**
754 * Commit the changes.
755 * <p>
756 * This method does nothing if there are no unsaved changes,
757 * otherwise it increments the current version
758 * and stores the data (for file based stores).
759 * <p>
760 * It is not necessary to call this method when auto-commit is enabled (the default
761 * setting), as in this case it is automatically called from time to time or
762 * when enough changes have accumulated. However, it may still be called to
763 * flush all changes to disk.
764 * <p>
765 * At most one store operation may run at any time.
766 *
767 * @return the new version (incremented if there were changes) or -1 if there were no commit
768 */
769 public long commit() {
770 return commit(x -> true);
771 }
772
773 private long commit(Predicate<MVStore> check) {
774 if(canStartStoreOperation()) {
775 storeLock.lock();
776 try {
777 if (check.test(this)) {
778 return store(true);
779 }
780 } finally {
781 unlockAndCheckPanicCondition();
782 }
783 }
784 return INITIAL_VERSION;
785 }
786
787 private boolean canStartStoreOperation() {
788 // we need to prevent re-entrance, which may be possible,
789 // because meta map is modified within storeNow() and that
790 // causes beforeWrite() call with possibility of going back here
791 return !storeLock.isHeldByCurrentThread() || !storeOperationInProgress.get();
792 }
793
794 private long store(boolean syncWrite) {
795 assert storeLock.isHeldByCurrentThread();
796 if (isOpenOrStopping() && hasUnsavedChanges() && storeOperationInProgress.compareAndSet(false, true)) {
797 try {
798 storeOperationInProgress.compareAndSet(false, true);
799 @SuppressWarnings({"NonAtomicVolatileUpdate", "NonAtomicOperationOnVolatileField"})
800 long result = ++currentVersion;
801 if (fileStore == null) {
802 setWriteVersion(currentVersion);
803 } else {
804 if (fileStore.isReadOnly()) {
805 throw DataUtils.newMVStoreException(
806 DataUtils.ERROR_WRITING_FAILED, "This store is read-only");
807 }
808 fileStore.dropUnusedChunks();
809 storeNow(syncWrite);
810 }
811 return result;
812 } finally {
813 storeOperationInProgress.set(false);
814 }
815 }
816 return INITIAL_VERSION;
817 }
818
819 private void setWriteVersion(long version) {
820 for (Iterator<MVMap<?, ?>> iter = maps.values().iterator(); iter.hasNext(); ) {
821 MVMap<?, ?> map = iter.next();
822 assert isRegularMap(map);
823 if (map.setWriteVersion(version) == null) {
824 iter.remove();
825 }
826 }
827 meta.setWriteVersion(version);
828 onVersionChange(version);
829 }
830
831 @SuppressWarnings({"NonAtomicVolatileUpdate", "NonAtomicOperationOnVolatileField"})
832 void storeNow() {
833 // it is ok, since that path suppose to be single-threaded under storeLock
834 ++currentVersion;
835 storeNow(true);
836 }
837
838 private void storeNow(boolean syncWrite) {
839 try {
840 int currentUnsavedMemory = unsavedMemory;
841 long version = currentVersion;
842
843 assert storeLock.isHeldByCurrentThread();
844 fileStore.storeIt(collectChangedMapRoots(version), version, syncWrite);
845
846 // some pages might have been changed in the meantime (in the newest
847 // version)
848 saveNeeded = false;
849 unsavedMemory = Math.max(0, unsavedMemory - currentUnsavedMemory);
850 } catch (MVStoreException e) {
851 panic(e);
852 } catch (Throwable e) {
853 panic(DataUtils.newMVStoreException(DataUtils.ERROR_INTERNAL, "{0}", e.toString(),
854 e));
855 }
856 }
857
858 private ArrayList<Page<?,?>> collectChangedMapRoots(long version) {
859 long lastStoredVersion = version - 2;
860 ArrayList<Page<?,?>> changed = new ArrayList<>();
861 for (Iterator<MVMap<?, ?>> iter = maps.values().iterator(); iter.hasNext(); ) {
862 MVMap<?, ?> map = iter.next();
863 RootReference<?,?> rootReference = map.setWriteVersion(version);
864 if (rootReference == null) {
865 iter.remove();
866 } else if (map.getCreateVersion() < version && // if map was created after storing started, skip it
867 !map.isVolatile() &&
868 map.hasChangesSince(lastStoredVersion)) {
869 assert rootReference.version <= version : rootReference.version + " > " + version;
870 // simply checking rootPage.isSaved() won't work here because
871 // after deletion previously saved page
872 // may pop up as a root, but we still need
873 // to save new root pos in meta
874 changed.add(rootReference.root);
875 }
876 }
877 RootReference<?,?> rootReference = meta.setWriteVersion(version);
878 if (meta.hasChangesSince(lastStoredVersion) || metaChanged) {
879 assert rootReference != null && rootReference.version <= version
880 : rootReference == null ? "null" : rootReference.version + " > " + version;
881 changed.add(rootReference.root);
882 }
883 return changed;
884 }
885
886 public long getTimeAbsolute() {
887 long now = System.currentTimeMillis();
888 if (lastTimeAbsolute != 0 && now < lastTimeAbsolute) {
889 // time seems to have run backwards - this can happen
890 // when the system time is adjusted, for example
891 // on a leap second
892 now = lastTimeAbsolute;
893 } else {
894 lastTimeAbsolute = now;
895 }
896 return now;
897 }
898
899 /**
900 * Check whether there are any unsaved changes.
901 *
902 * @return if there are any changes
903 */
904 public boolean hasUnsavedChanges() {
905 if (metaChanged) {
906 return true;
907 }
908 long lastStoredVersion = currentVersion - 1;
909 for (MVMap<?, ?> m : maps.values()) {
910 if (!m.isClosed()) {
911 if(m.hasChangesSince(lastStoredVersion)) {
912 return true;
913 }
914 }
915 }
916 return fileStore != null && fileStore.hasChangesSince(lastStoredVersion);
917 }
918
919 public void executeFilestoreOperation(Runnable operation) {
920 storeLock.lock();
921 try {
922 checkNotClosed();
923 fileStore.executeFilestoreOperation(operation);
924 } catch (MVStoreException e) {
925 panic(e);
926 } catch (Throwable e) {
927 panic(DataUtils.newMVStoreException(
928 DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
929 } finally {
930 unlockAndCheckPanicCondition();
931 }
932 }
933
934 <R> R tryExecuteUnderStoreLock(Callable<R> operation) throws InterruptedException {
935 R result = null;
936 if (storeLock.tryLock(10, TimeUnit.MILLISECONDS)) {
937 try {
938 result = operation.call();
939 } catch (MVStoreException e) {
940 panic(e);
941 } catch (Throwable e) {
942 panic(DataUtils.newMVStoreException(
943 DataUtils.ERROR_INTERNAL, "{0}", e.toString(), e));
944 } finally {
945 unlockAndCheckPanicCondition();
946 }
947 }
948 return result;
949 }
950
951 /**
952 * Force all stored changes to be written to the storage. The default
953 * implementation calls FileChannel.force(true).
954 */
955 public void sync() {
956 checkOpen();
957 FileStore<?> f = fileStore;
958 if (f != null) {
959 f.sync();
960 }
961 }
962
963 /**
964 * Compact store file, that is, compact blocks that have a low
965 * fill rate, and move chunks next to each other. This will typically
966 * shrink the file. Changes are flushed to the file, and old
967 * chunks are overwritten.
968 *
969 * @param maxCompactTime the maximum time in milliseconds to compact
970 */
971 public void compactFile(int maxCompactTime) {
972 if (fileStore != null) {
973 setRetentionTime(0);
974 storeLock.lock();
975 try {
976 fileStore.compactStore(maxCompactTime);
977 } finally {
978 unlockAndCheckPanicCondition();
979 }
980 }
981 }
982
983 /**
984 * Try to increase the fill rate by re-writing partially full chunks. Chunks
985 * with a low number of live items are re-written.
986 * <p>
987 * If the current fill rate is higher than the target fill rate, nothing is
988 * done.
989 * <p>
990 * Please note this method will not necessarily reduce the file size, as
991 * empty chunks are not overwritten.
992 * <p>
993 * Only data of open maps can be moved. For maps that are not open, the old
994 * chunk is still referenced. Therefore, it is recommended to open all maps
995 * before calling this method.
996 *
997 * @param targetFillRate the minimum percentage of live entries
998 * @param write the minimum number of bytes to write
999 * @return if any chunk was re-written
1000 */
1001 public boolean compact(int targetFillRate, int write) {
1002 checkOpen();
1003 return fileStore != null && fileStore.compact(targetFillRate, write);
1004 }
1005
1006 public int getFillRate() {
1007 return fileStore.getFillRate();
1008 }
1009
1010 /**
1011 * Read a page.
1012 *
1013 * @param <K> key type
1014 * @param <V> value type
1015 *
1016 * @param map the map
1017 * @param pos the page position
1018 * @return the page
1019 */
1020 <K,V> Page<K,V> readPage(MVMap<K,V> map, long pos) {
1021 checkNotClosed();
1022 return fileStore.readPage(map, pos);
1023 }
1024
1025 /**
1026 * Remove a page.
1027 * @param pos the position of the page
1028 * @param version at which page was removed
1029 * @param pinned whether page is considered pinned
1030 * @param pageNo sequential page number within chunk
1031 */
1032 void accountForRemovedPage(long pos, long version, boolean pinned, int pageNo) {
1033 fileStore.accountForRemovedPage(pos, version, pinned, pageNo);
1034 }
1035
1036 Compressor getCompressorFast() {
1037 if (compressorFast == null) {
1038 compressorFast = new CompressLZF();
1039 }
1040 return compressorFast;
1041 }
1042
1043 Compressor getCompressorHigh() {
1044 if (compressorHigh == null) {
1045 compressorHigh = new CompressDeflate();
1046 }
1047 return compressorHigh;
1048 }
1049
1050 int getCompressionLevel() {
1051 return compressionLevel;
1052 }
1053
1054 public int getKeysPerPage() {
1055 return keysPerPage;
1056 }
1057
1058 public long getMaxPageSize() {
1059 return fileStore == null ? Long.MAX_VALUE : fileStore.getMaxPageSize();
1060 }
1061
1062 /**
1063 * Get the maximum cache size, in MB.
1064 * Note that this does not include the page chunk references cache, which is
1065 * 25% of the size of the page cache.
1066 *
1067 * @return the cache size
1068 */
1069 public int getCacheSize() {
1070 return fileStore == null ? 0 : fileStore.getCacheSize();
1071 }
1072
1073 /**
1074 * Get the amount of memory used for caching, in MB.
1075 * Note that this does not include the page chunk references cache, which is
1076 * 25% of the size of the page cache.
1077 *
1078 * @return the amount of memory used for caching
1079 */
1080 public int getCacheSizeUsed() {
1081 return fileStore == null ? 0 : fileStore.getCacheSizeUsed();
1082 }
1083
1084 /**
1085 * Set the maximum memory to be used by the cache.
1086 *
1087 * @param kb the maximum size in KB
1088 */
1089 public void setCacheSize(int kb) {
1090 if (fileStore != null) {
1091 fileStore.setCacheSize(Math.max(1, kb / 1024));
1092 }
1093 }
1094
1095 public boolean isSpaceReused() {
1096 return fileStore.isSpaceReused();
1097 }
1098
1099 /**
1100 * Whether empty space in the file should be re-used. If enabled, old data
1101 * is overwritten (default). If disabled, writes are appended at the end of
1102 * the file.
1103 * <p>
1104 * This setting is specially useful for online backup. To create an online
1105 * backup, disable this setting, then copy the file (starting at the
1106 * beginning of the file). In this case, concurrent backup and write
1107 * operations are possible (obviously the backup process needs to be faster
1108 * than the write operations).
1109 *
1110 * @param reuseSpace the new value
1111 */
1112 public void setReuseSpace(boolean reuseSpace) {
1113 fileStore.setReuseSpace(reuseSpace);
1114 }
1115
1116 public int getRetentionTime() {
1117 return fileStore == null ? 0 : fileStore.getRetentionTime();
1118 }
1119
1120 /**
1121 * How long to retain old, persisted chunks, in milliseconds. Chunks that
1122 * are older may be overwritten once they contain no live data.
1123 * <p>
1124 * The default value is 45000 (45 seconds) when using the default file
1125 * store. It is assumed that a file system and hard disk will flush all
1126 * write buffers within this time. Using a lower value might be dangerous,
1127 * unless the file system and hard disk flush the buffers earlier. To
1128 * manually flush the buffers, use
1129 * <code>MVStore.getFile().force(true)</code>, however please note that
1130 * according to various tests this does not always work as expected
1131 * depending on the operating system and hardware.
1132 * <p>
1133 * The retention time needs to be long enough to allow reading old chunks
1134 * while traversing over the entries of a map.
1135 * <p>
1136 * This setting is not persisted.
1137 *
1138 * @param ms how many milliseconds to retain old chunks (0 to overwrite them
1139 * as early as possible)
1140 */
1141 public void setRetentionTime(int ms) {
1142 if (fileStore != null) {
1143 fileStore.setRetentionTime(ms);
1144 }
1145 }
1146
1147 /**
1148 * Indicates whether store versions are rolling.
1149 * @return true if versions are rolling, false otherwise
1150 */
1151 public boolean isVersioningRequired() {
1152 return fileStore != null && !fileStore.isReadOnly() || versionsToKeep > 0;
1153 }
1154
1155 /**
1156 * How many versions to retain for in-memory stores. If not set, 5 old
1157 * versions are retained.
1158 *
1159 * @param count the number of versions to keep
1160 */
1161 public void setVersionsToKeep(int count) {
1162 this.versionsToKeep = count;
1163 }
1164
1165 /**
1166 * Get the oldest version to retain in memory (for in-memory stores).
1167 *
1168 * @return the version
1169 */
1170 public long getVersionsToKeep() {
1171 return versionsToKeep;
1172 }
1173
1174 /**
1175 * Get the oldest version to retain.
1176 * We keep at least number of previous versions specified by "versionsToKeep"
1177 * configuration parameter (default 5).
1178 * Previously it was used only in case of non-persistent MVStore.
1179 * Now it's honored in all cases (although H2 always sets it to zero).
1180 * Oldest version determination also takes into account calls (de)registerVersionUsage(),
1181 * and will not release the version, while version is still in use.
1182 *
1183 * @return the version
1184 */
1185 long getOldestVersionToKeep() {
1186 return Math.min(oldestVersionToKeep.get(),
1187 Math.max(currentVersion - versionsToKeep, INITIAL_VERSION));
1188 }
1189
1190 private void setOldestVersionToKeep(long version) {
1191 boolean success;
1192 do {
1193 long current = oldestVersionToKeep.get();
1194 // Oldest version may only advance, never goes back
1195 success = version <= current ||
1196 oldestVersionToKeep.compareAndSet(current, version);
1197 } while (!success);
1198 assert version <= currentVersion : version + " <= " + currentVersion;
1199
1200 if (oldestVersionTracker != null) {
1201 oldestVersionTracker.accept(version);
1202 }
1203 }
1204
1205 public void setOldestVersionTracker(LongConsumer callback) {
1206 oldestVersionTracker = callback;
1207 }
1208
1209 /**
1210 * Check whether all data can be read from this version. This requires that
1211 * all chunks referenced by this version are still available (not
1212 * overwritten).
1213 *
1214 * @param version the version
1215 * @return true if all data can be read
1216 */
1217 private boolean isKnownVersion(long version) {
1218 long curVersion = getCurrentVersion();
1219 if (version > curVersion || version < 0) {
1220 return false;
1221 }
1222 if (version == curVersion) {
1223 // no stored data
1224 return true;
1225 }
1226 return fileStore == null || fileStore.isKnownVersion(version);
1227 }
1228
1229 /**
1230 * Adjust amount of "unsaved memory" meaning amount of RAM occupied by pages
1231 * not saved yet to the file. This is the amount which triggers auto-commit.
1232 *
1233 * @param memory adjustment
1234 */
1235 public void registerUnsavedMemory(int memory) {
1236 assert fileStore != null;
1237 // this counter was intentionally left unprotected against race
1238 // condition for performance reasons
1239 // TODO: evaluate performance impact of atomic implementation,
1240 // since updates to unsavedMemory are largely aggregated now
1241 unsavedMemory += memory;
1242 if (needStore()) {
1243 saveNeeded = true;
1244 }
1245 }
1246
1247 void registerUnsavedMemoryAndCommitIfNeeded(int memory) {
1248 registerUnsavedMemory(memory);
1249 if (saveNeeded) {
1250 commit();
1251 }
1252 }
1253
1254 /**
1255 * This method is called before writing to a map.
1256 *
1257 * @param map the map
1258 */
1259 void beforeWrite(MVMap<?, ?> map) {
1260 if (saveNeeded && isOpenOrStopping() &&
1261 // condition below is to prevent potential deadlock,
1262 // because we should never seek storeLock while holding
1263 // map root lock
1264 (storeLock.isHeldByCurrentThread() || !map.getRoot().isLockedByCurrentThread()) &&
1265 // to avoid infinite recursion via store() -> dropUnusedChunks() -> layout.remove()
1266 fileStore.isRegularMap(map)) {
1267 saveNeeded = false;
1268 // check again, because it could have been written by now
1269 if (autoCommitMemory > 0 && needStore()) {
1270 // if unsaved memory creation rate is to high,
1271 // some back pressure need to be applied
1272 // to slow things down and avoid OOME
1273 if (requireStore() && !map.isSingleWriter()) {
1274 commit(MVStore::requireStore);
1275 } else {
1276 tryCommit(MVStore::needStore);
1277 }
1278 }
1279 }
1280 }
1281
1282 private boolean requireStore() {
1283 return 3 * unsavedMemory > 4 * autoCommitMemory;
1284 }
1285
1286 private boolean needStore() {
1287 return autoCommitMemory > 0 && fileStore.shouldSaveNow(unsavedMemory, autoCommitMemory);
1288 }
1289
1290 /**
1291 * Get the store version. The store version is usually used to upgrade the
1292 * structure of the store after upgrading the application. Initially the
1293 * store version is 0, until it is changed.
1294 *
1295 * @return the store version
1296 */
1297 public int getStoreVersion() {
1298 checkOpen();
1299 String x = meta.get("setting.storeVersion");
1300 return x == null ? 0 : DataUtils.parseHexInt(x);
1301 }
1302
1303 /**
1304 * Update the store version.
1305 *
1306 * @param version the new store version
1307 */
1308 public void setStoreVersion(int version) {
1309 storeLock.lock();
1310 try {
1311 checkOpen();
1312 markMetaChanged();
1313 meta.put("setting.storeVersion", Integer.toHexString(version));
1314 } finally {
1315 storeLock.unlock();
1316 }
1317 }
1318
1319 /**
1320 * Revert to the beginning of the current version, reverting all uncommitted
1321 * changes.
1322 */
1323 public void rollback() {
1324 rollbackTo(currentVersion);
1325 }
1326
1327 /**
1328 * Revert to the beginning of the given version. All later changes (stored
1329 * or not) are forgotten. All maps that were created later are closed. A
1330 * rollback to a version before the last stored version is immediately
1331 * persisted. Rollback to version 0 means all data is removed.
1332 *
1333 * @param version the version to revert to
1334 */
1335 public void rollbackTo(long version) {
1336 storeLock.lock();
1337 try {
1338 currentVersion = version;
1339 checkOpen();
1340 DataUtils.checkArgument(isKnownVersion(version), "Unknown version {0}", version);
1341
1342 TxCounter txCounter;
1343 while ((txCounter = versions.peekLast()) != null && txCounter.version >= version) {
1344 versions.removeLast();
1345 }
1346 currentTxCounter = new TxCounter(version);
1347 if (oldestVersionToKeep.get() > version) {
1348 oldestVersionToKeep.set(version);
1349 }
1350
1351 if (fileStore != null) {
1352 fileStore.rollbackTo(version);
1353 }
1354 if (!meta.rollbackRoot(version)) {
1355 meta.setRootPos(getRootPos(meta.getId()), version - 1);
1356 }
1357 metaChanged = false;
1358
1359 for (MVMap<?, ?> m : new ArrayList<>(maps.values())) {
1360 int id = m.getId();
1361 if (m.getCreateVersion() >= version) {
1362 m.close();
1363 maps.remove(id);
1364 } else {
1365 if (!m.rollbackRoot(version)) {
1366 m.setRootPos(getRootPos(id), version);
1367 }
1368 }
1369 }
1370 onVersionChange(currentVersion);
1371 assert !hasUnsavedChanges();
1372 } finally {
1373 unlockAndCheckPanicCondition();
1374 }
1375 }
1376
1377 private long getRootPos(int mapId) {
1378 return fileStore == null ? 0 : fileStore.getRootPos(mapId);
1379 }
1380
1381 /**
1382 * Get the current version of the data. When a new store is created, the
1383 * version is 0.
1384 *
1385 * @return the version
1386 */
1387 public long getCurrentVersion() {
1388 return currentVersion;
1389 }
1390
1391 void setCurrentVersion(long curVersion) {
1392 currentVersion = curVersion;
1393 }
1394
1395 /**
1396 * Get the file store.
1397 *
1398 * @return the file store
1399 */
1400 public FileStore<?> getFileStore() {
1401 return fileStore;
1402 }
1403
1404 /**
1405 * Get the store header. This data is for informational purposes only. The
1406 * data is subject to change in future versions. The data should not be
1407 * modified (doing so may corrupt the store).
1408 *
1409 * @return the store header
1410 */
1411 public Map<String, Object> getStoreHeader() {
1412 return fileStore.getStoreHeader();
1413 }
1414
1415 private void checkOpen() {
1416 if (!isOpen()) {
1417 throw DataUtils.newMVStoreException(DataUtils.ERROR_CLOSED,
1418 "This store is closed", panicException);
1419 }
1420 }
1421
1422 private void checkNotClosed() {
1423 if (!isOpenOrStopping()) {
1424 throw DataUtils.newMVStoreException(DataUtils.ERROR_CLOSED,
1425 "This store is closed", panicException);
1426 }
1427 }
1428
1429 /**
1430 * Rename a map.
1431 *
1432 * @param map the map
1433 * @param newName the new name
1434 */
1435 public void renameMap(MVMap<?, ?> map, String newName) {
1436 checkOpen();
1437 DataUtils.checkArgument(isRegularMap(map), "Renaming the meta map is not allowed");
1438 int id = map.getId();
1439 String oldName = getMapName(id);
1440 if (oldName != null && !oldName.equals(newName)) {
1441 String idHexStr = Integer.toHexString(id);
1442 // at first create a new name as an "alias"
1443 String existingIdHexStr = meta.putIfAbsent(DataUtils.META_NAME + newName, idHexStr);
1444 // we need to cope with the case of previously unfinished rename
1445 DataUtils.checkArgument(
1446 existingIdHexStr == null || existingIdHexStr.equals(idHexStr),
1447 "A map named {0} already exists", newName);
1448 // switch roles of a new and old names - old one is an alias now
1449 meta.put(MVMap.getMapKey(id), map.asString(newName));
1450 // get rid of the old name completely
1451 meta.remove(DataUtils.META_NAME + oldName);
1452 markMetaChanged();
1453 }
1454 }
1455
1456 /**
1457 * Remove a map from the current version of the store.
1458 *
1459 * @param map the map to remove
1460 */
1461 public void removeMap(MVMap<?,?> map) {
1462 storeLock.lock();
1463 try {
1464 checkOpen();
1465 DataUtils.checkArgument(isRegularMap(map), "Removing the meta map is not allowed");
1466 RootReference<?,?> rootReference = map.clearIt();
1467 map.close();
1468
1469 updateCounter += rootReference.updateCounter;
1470 updateAttemptCounter += rootReference.updateAttemptCounter;
1471
1472 int id = map.getId();
1473 String name = getMapName(id);
1474 if (meta.remove(MVMap.getMapKey(id)) != null) {
1475 markMetaChanged();
1476 }
1477 if (meta.remove(DataUtils.META_NAME + name) != null) {
1478 markMetaChanged();
1479 }
1480 // normally actual map removal is delayed, up until this current version go out os scope,
1481 // but for in-memory case, when versions rolling is turned off, do it now
1482 if (!isVersioningRequired()) {
1483 maps.remove(id);
1484 }
1485 } finally {
1486 storeLock.unlock();
1487 }
1488 }
1489
1490 /**
1491 * Performs final stage of map removal - delete root location info from the layout table.
1492 * Map is supposedly closed and anonymous and has no outstanding usage by now.
1493 *
1494 * @param mapId to deregister
1495 */
1496 void deregisterMapRoot(int mapId) {
1497 if (fileStore != null && fileStore.deregisterMapRoot(mapId)) {
1498 markMetaChanged();
1499 }
1500 }
1501
1502 /**
1503 * Remove map by name.
1504 *
1505 * @param name the map name
1506 */
1507 public void removeMap(String name) {
1508 int id = getMapId(name);
1509 if(id > 0) {
1510 MVMap<?, ?> map = getMap(id);
1511 if (map == null) {
1512 map = openMap(name, MVStoreTool.getGenericMapBuilder());
1513 }
1514 removeMap(map);
1515 }
1516 }
1517
1518 /**
1519 * Get the name of the given map.
1520 *
1521 * @param id the map id
1522 * @return the name, or null if not found
1523 */
1524 public String getMapName(int id) {
1525 String m = meta.get(MVMap.getMapKey(id));
1526 return m == null ? null : DataUtils.getMapName(m);
1527 }
1528
1529 private int getMapId(String name) {
1530 String m = meta.get(DataUtils.META_NAME + name);
1531 return m == null ? -1 : DataUtils.parseHexInt(m);
1532 }
1533
1534 public void populateInfo(BiConsumer<String, String> consumer) {
1535 consumer.accept("info.UPDATE_FAILURE_PERCENT",
1536 String.format(Locale.ENGLISH, "%.2f%%", 100 * getUpdateFailureRatio()));
1537 consumer.accept("info.LEAF_RATIO", Integer.toString(getLeafRatio()));
1538
1539 if (fileStore != null) {
1540 fileStore.populateInfo(consumer);
1541 }
1542 }
1543
1544 boolean handleException(Throwable ex) {
1545 if (backgroundExceptionHandler != null) {
1546 try {
1547 backgroundExceptionHandler.uncaughtException(Thread.currentThread(), ex);
1548 } catch(Throwable e) {
1549 if (ex != e) { // OOME may be the same
1550 ex.addSuppressed(e);
1551 }
1552 }
1553 return true;
1554 }
1555 return false;
1556 }
1557
1558 boolean isOpen() {
1559 return state == STATE_OPEN;
1560 }
1561
1562 /**
1563 * Determine that store is open, or wait for it to be closed (by other thread)
1564 * @return true if store is open, false otherwise
1565 */
1566 public boolean isClosed() {
1567 if (isOpen()) {
1568 return false;
1569 }
1570 storeLock.lock();
1571 try {
1572 return state == STATE_CLOSED;
1573 } finally {
1574 storeLock.unlock();
1575 }
1576 }
1577
1578 private boolean isOpenOrStopping() {
1579 return state <= STATE_STOPPING;
1580 }
1581
1582 /**
1583 * Set the maximum delay in milliseconds to auto-commit changes.
1584 * <p>
1585 * To disable auto-commit, set the value to 0. In this case, changes are
1586 * only committed when explicitly calling commit.
1587 * <p>
1588 * The default is 1000, meaning all changes are committed after at most one
1589 * second.
1590 *
1591 * @param millis the maximum delay
1592 */
1593 public void setAutoCommitDelay(int millis) {
1594 if (fileStore != null) {
1595 fileStore.setAutoCommitDelay(millis);
1596 }
1597 }
1598
1599 /**
1600 * Get the auto-commit delay.
1601 *
1602 * @return the delay in milliseconds, or 0 if auto-commit is disabled.
1603 */
1604 public int getAutoCommitDelay() {
1605 return fileStore == null ? 0 : fileStore.getAutoCommitDelay();
1606 }
1607
1608 /**
1609 * Get the maximum memory (in bytes) used for unsaved pages. If this number
1610 * is exceeded, unsaved changes are stored to disk.
1611 *
1612 * @return the memory in bytes
1613 */
1614 public int getAutoCommitMemory() {
1615 return autoCommitMemory;
1616 }
1617
1618 /**
1619 * Get the estimated memory (in bytes) of unsaved data. If the value exceeds
1620 * the auto-commit memory, the changes are committed.
1621 * <p>
1622 * The returned value is an estimation only.
1623 *
1624 * @return the memory in bytes
1625 */
1626 public int getUnsavedMemory() {
1627 return unsavedMemory;
1628 }
1629
1630 /**
1631 * Whether the store is read-only.
1632 *
1633 * @return true if it is
1634 */
1635 public boolean isReadOnly() {
1636 return fileStore != null && fileStore.isReadOnly();
1637 }
1638
1639 private int getLeafRatio() {
1640 return (int)(leafCount * 100 / Math.max(1, leafCount + nonLeafCount));
1641 }
1642
1643 private double getUpdateFailureRatio() {
1644 long updateCounter = this.updateCounter;
1645 long updateAttemptCounter = this.updateAttemptCounter;
1646 RootReference<?,?> rootReference = meta.getRoot();
1647 updateCounter += rootReference.updateCounter;
1648 updateAttemptCounter += rootReference.updateAttemptCounter;
1649 for (MVMap<?, ?> map : maps.values()) {
1650 RootReference<?,?> root = map.getRoot();
1651 updateCounter += root.updateCounter;
1652 updateAttemptCounter += root.updateAttemptCounter;
1653 }
1654 return updateAttemptCounter == 0 ? 0 : 1 - ((double)updateCounter / updateAttemptCounter);
1655 }
1656
1657 /**
1658 * Register opened operation (transaction).
1659 * This would increment usage counter for the current version.
1660 * This version (and all after it) should not be dropped until all
1661 * transactions involved are closed and usage counter goes to zero.
1662 * @return TxCounter to be decremented when operation finishes (transaction closed).
1663 */
1664 public TxCounter registerVersionUsage() {
1665 TxCounter txCounter;
1666 while(true) {
1667 txCounter = currentTxCounter;
1668 if(txCounter.incrementAndGet() > 0) {
1669 return txCounter;
1670 }
1671 // The only way for counter to be negative
1672 // if it was retrieved right before onVersionChange()
1673 // and now onVersionChange() is done.
1674 // This version is eligible for reclamation now
1675 // and should not be used here, so restore count
1676 // not to upset accounting and try again with a new
1677 // version (currentTxCounter should have changed).
1678 assert txCounter != currentTxCounter : txCounter;
1679 txCounter.decrementAndGet();
1680 }
1681 }
1682
1683 /**
1684 * De-register (close) completed operation (transaction).
1685 * This will decrement usage counter for the corresponding version.
1686 * If counter reaches zero, that version (and all unused after it)
1687 * can be dropped immediately.
1688 *
1689 * @param txCounter to be decremented, obtained from registerVersionUsage()
1690 */
1691 public void deregisterVersionUsage(TxCounter txCounter) {
1692 if(decrementVersionUsageCounter(txCounter)) {
1693 if (storeLock.isHeldByCurrentThread()) {
1694 dropUnusedVersions();
1695 } else if (storeLock.tryLock()) {
1696 try {
1697 dropUnusedVersions();
1698 } finally {
1699 storeLock.unlock();
1700 }
1701 }
1702 }
1703 }
1704
1705 /**
1706 * De-register (close) completed operation (transaction).
1707 * This will decrement usage counter for the corresponding version.
1708 *
1709 * @param txCounter to be decremented, obtained from registerVersionUsage()
1710 * @return true if counter reaches zero, which indicates that version is no longer in use, false otherwise.
1711 */
1712 public boolean decrementVersionUsageCounter(TxCounter txCounter) {
1713 return txCounter != null && txCounter.decrementAndGet() <= 0;
1714 }
1715
1716 void onVersionChange(long version) {
1717 metaChanged = false;
1718 TxCounter txCounter = currentTxCounter;
1719 assert txCounter.get() >= 0;
1720 versions.add(txCounter);
1721 currentTxCounter = new TxCounter(version);
1722 txCounter.decrementAndGet();
1723 dropUnusedVersions();
1724 }
1725
1726 private void dropUnusedVersions() {
1727 TxCounter txCounter;
1728 while ((txCounter = versions.peek()) != null
1729 && txCounter.get() < 0) {
1730 versions.poll();
1731 }
1732 long oldestVersionToKeep = (txCounter != null ? txCounter : currentTxCounter).version;
1733 setOldestVersionToKeep(oldestVersionToKeep);
1734 }
1735
1736 public void countNewPage(boolean leaf) {
1737 if (leaf) {
1738 ++leafCount;
1739 } else {
1740 ++nonLeafCount;
1741 }
1742 }
1743
1744 /**
1745 * Class TxCounter is a simple data structure to hold version of the store
1746 * along with the counter of open transactions,
1747 * which are still operating on this version.
1748 */
1749 public static final class TxCounter {
1750
1751 /**
1752 * Version of a store, this TxCounter is related to
1753 */
1754 public final long version;
1755
1756 /**
1757 * Counter of outstanding operation on this version of a store
1758 */
1759 private volatile int counter;
1760
1761 private static final AtomicIntegerFieldUpdater<TxCounter> counterUpdater =
1762 AtomicIntegerFieldUpdater.newUpdater(TxCounter.class, "counter");
1763
1764
1765 TxCounter(long version) {
1766 this.version = version;
1767 }
1768
1769 int get() {
1770 return counter;
1771 }
1772
1773 /**
1774 * Increment and get the counter value.
1775 *
1776 * @return the new value
1777 */
1778 int incrementAndGet() {
1779 return counterUpdater.incrementAndGet(this);
1780 }
1781
1782 /**
1783 * Decrement and get the counter values.
1784 *
1785 * @return the new value
1786 */
1787 int decrementAndGet() {
1788 return counterUpdater.decrementAndGet(this);
1789 }
1790
1791 @Override
1792 public String toString() {
1793 return "v=" + version + " / cnt=" + counter;
1794 }
1795 }
1796
1797 /**
1798 * A builder for an MVStore.
1799 */
1800 public static final class Builder {
1801
1802 private final HashMap<String, Object> config;
1803
1804 private Builder(HashMap<String, Object> config) {
1805 this.config = config;
1806 }
1807
1808 /**
1809 * Creates new instance of MVStore.Builder.
1810 */
1811 public Builder() {
1812 config = new HashMap<>();
1813 }
1814
1815 private Builder set(String key, Object value) {
1816 config.put(key, value);
1817 return this;
1818 }
1819
1820 /**
1821 * Disable auto-commit, by setting the auto-commit delay and auto-commit
1822 * buffer size to 0.
1823 *
1824 * @return this
1825 */
1826 public Builder autoCommitDisabled() {
1827 // we have a separate config option so that
1828 // no thread is started if the write delay is 0
1829 // (if we only had a setter in the MVStore,
1830 // the thread would need to be started in any case)
1831 //set("autoCommitBufferSize", 0);
1832 return set("autoCommitDelay", 0);
1833 }
1834
1835 /**
1836 * Set the size of the write buffer, in KB disk space (for file-based
1837 * stores). Unless auto-commit is disabled, changes are automatically
1838 * saved if there are more than this amount of changes.
1839 * <p>
1840 * The default is 1024 KB.
1841 * <p>
1842 * When the value is set to 0 or lower, data is not automatically
1843 * stored.
1844 *
1845 * @param kb the write buffer size, in kilobytes
1846 * @return this
1847 */
1848 public Builder autoCommitBufferSize(int kb) {
1849 return set("autoCommitBufferSize", kb);
1850 }
1851
1852 /**
1853 * Set the auto-compact target fill rate. If the average fill rate (the
1854 * percentage of the storage space that contains active data) of the
1855 * chunks is lower, then the chunks with a low fill rate are re-written.
1856 * Also, if the percentage of empty space between chunks is higher than
1857 * this value, then chunks at the end of the file are moved. Compaction
1858 * stops if the target fill rate is reached.
1859 * <p>
1860 * The default value is 90 (90%). The value 0 disables auto-compacting.
1861 * </p>
1862 *
1863 * @param percent the target fill rate
1864 * @return this
1865 */
1866 public Builder autoCompactFillRate(int percent) {
1867 return set("autoCompactFillRate", percent);
1868 }
1869
1870 /**
1871 * Use the following file name. If the file does not exist, it is
1872 * automatically created. The parent directory already must exist.
1873 *
1874 * @param fileName the file name
1875 * @return this
1876 */
1877 public Builder fileName(String fileName) {
1878 return set("fileName", fileName);
1879 }
1880
1881 /**
1882 * Encrypt / decrypt the file using the given password. This method has
1883 * no effect for in-memory stores. The password is passed as a
1884 * char array so that it can be cleared as soon as possible. Please note
1885 * there is still a small risk that password stays in memory (due to
1886 * Java garbage collection). Also, the hashed encryption key is kept in
1887 * memory as long as the file is open.
1888 *
1889 * @param password the password
1890 * @return this
1891 */
1892 public Builder encryptionKey(char[] password) {
1893 return set("encryptionKey", password);
1894 }
1895
1896 /**
1897 * Open the file in read-only mode. In this case, a shared lock will be
1898 * acquired to ensure the file is not concurrently opened in write mode.
1899 * <p>
1900 * If this option is not used, the file is locked exclusively.
1901 * <p>
1902 * Please note a store may only be opened once in every JVM (no matter
1903 * whether it is opened in read-only or read-write mode), because each
1904 * file may be locked only once in a process.
1905 *
1906 * @return this
1907 */
1908 public Builder readOnly() {
1909 return set("readOnly", 1);
1910 }
1911
1912 /**
1913 * Set the number of keys per page.
1914 *
1915 * @param keyCount the number of keys
1916 * @return this
1917 */
1918 public Builder keysPerPage(int keyCount) {
1919 return set("keysPerPage", keyCount);
1920 }
1921
1922 /**
1923 * Open the file in recovery mode, where some errors may be ignored.
1924 *
1925 * @return this
1926 */
1927 public Builder recoveryMode() {
1928 return set("recoveryMode", 1);
1929 }
1930
1931 /**
1932 * Set the read cache size in MB. The default is 16 MB.
1933 *
1934 * @param mb the cache size in megabytes
1935 * @return this
1936 */
1937 public Builder cacheSize(int mb) {
1938 return set("cacheSize", mb);
1939 }
1940
1941 /**
1942 * Set the read cache concurrency. The default is 16, meaning 16
1943 * segments are used.
1944 *
1945 * @param concurrency the cache concurrency
1946 * @return this
1947 */
1948 public Builder cacheConcurrency(int concurrency) {
1949 return set("cacheConcurrency", concurrency);
1950 }
1951
1952 /**
1953 * Compress data before writing using the LZF algorithm. This will save
1954 * about 50% of the disk space, but will slow down read and write
1955 * operations slightly.
1956 * <p>
1957 * This setting only affects writes; it is not necessary to enable
1958 * compression when reading, even if compression was enabled when
1959 * writing.
1960 *
1961 * @return this
1962 */
1963 public Builder compress() {
1964 return set("compress", 1);
1965 }
1966
1967 /**
1968 * Compress data before writing using the Deflate algorithm. This will
1969 * save more disk space, but will slow down read and write operations
1970 * quite a bit.
1971 * <p>
1972 * This setting only affects writes; it is not necessary to enable
1973 * compression when reading, even if compression was enabled when
1974 * writing.
1975 *
1976 * @return this
1977 */
1978 public Builder compressHigh() {
1979 return set("compress", 2);
1980 }
1981
1982 /**
1983 * Set the amount of memory a page should contain at most, in bytes,
1984 * before it is split. The default is 16 KB for persistent stores and 4
1985 * KB for in-memory stores. This is not a limit in the page size, as
1986 * pages with one entry can get larger. It is just the point where pages
1987 * that contain more than one entry are split.
1988 *
1989 * @param pageSplitSize the page size
1990 * @return this
1991 */
1992 public Builder pageSplitSize(int pageSplitSize) {
1993 return set("pageSplitSize", pageSplitSize);
1994 }
1995
1996 /**
1997 * Set the listener to be used for exceptions that occur when writing in
1998 * the background thread.
1999 *
2000 * @param exceptionHandler the handler
2001 * @return this
2002 */
2003 public Builder backgroundExceptionHandler(
2004 Thread.UncaughtExceptionHandler exceptionHandler) {
2005 return set("backgroundExceptionHandler", exceptionHandler);
2006 }
2007
2008 /**
2009 * Use the provided file store instead of the default one.
2010 * <p>
2011 * File stores passed in this way need to be open. They are not closed
2012 * when closing the store.
2013 * <p>
2014 * Please note that any kind of store (including an off-heap store) is
2015 * considered a "persistence", while an "in-memory store" means objects
2016 * are not persisted and fully kept in the JVM heap.
2017 *
2018 * @param store the file store
2019 * @return this
2020 */
2021 public Builder fileStore(FileStore<?> store) {
2022 return set("fileStore", store);
2023 }
2024
2025 public Builder adoptFileStore(FileStore store) {
2026 set("fileStoreIsAdopted", true);
2027 return set("fileStore", store);
2028 }
2029
2030 /**
2031 * Open the store.
2032 *
2033 * @return the opened store
2034 */
2035 public MVStore open() {
2036 return new MVStore(config);
2037 }
2038
2039 @Override
2040 public String toString() {
2041 return DataUtils.appendMap(new StringBuilder(), config).toString();
2042 }
2043
2044 /**
2045 * Read the configuration from a string.
2046 *
2047 * @param s the string representation
2048 * @return the builder
2049 */
2050 @SuppressWarnings({"unchecked", "rawtypes", "unused"})
2051 public static Builder fromString(String s) {
2052 // Cast from HashMap<String, String> to HashMap<String, Object> is safe
2053 return new Builder((HashMap) DataUtils.parseMap(s));
2054 }
2055 }
2056 }