Debian Codegraph @

src/main/org/h2/mvstore/db/LobStorageMap.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.db;
7
8 import java.io.FilterInputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.Reader;
12 import java.nio.ByteBuffer;
13 import java.nio.charset.StandardCharsets;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.Iterator;
17 import java.util.Map.Entry;
18 import java.util.Queue;
19 import java.util.concurrent.ConcurrentLinkedQueue;
20 import java.util.concurrent.RejectedExecutionException;
21 import java.util.concurrent.SynchronousQueue;
22 import java.util.concurrent.ThreadPoolExecutor;
23 import java.util.concurrent.atomic.AtomicLong;
24 import org.h2.api.ErrorCode;
25 import org.h2.engine.Database;
26 import org.h2.message.DbException;
27 import org.h2.mvstore.DataUtils;
28 import org.h2.mvstore.MVMap;
29 import org.h2.mvstore.MVStore;
30 import org.h2.mvstore.MVStoreException;
31 import org.h2.mvstore.StreamStore;
32 import org.h2.mvstore.WriteBuffer;
33 import org.h2.mvstore.tx.TransactionStore;
34 import org.h2.mvstore.type.BasicDataType;
35 import org.h2.mvstore.type.ByteArrayDataType;
36 import org.h2.mvstore.type.LongDataType;
37 import org.h2.store.CountingReaderInputStream;
38 import org.h2.store.LobStorageFrontend;
39 import org.h2.store.LobStorageInterface;
40 import org.h2.store.RangeInputStream;
41 import org.h2.util.IOUtils;
42 import org.h2.util.StringUtils;
43 import org.h2.util.Utils;
44 import org.h2.value.Value;
45 import org.h2.value.ValueBlob;
46 import org.h2.value.ValueClob;
47 import org.h2.value.ValueLob;
48 import org.h2.value.ValueNull;
49 import org.h2.value.lob.LobData;
50 import org.h2.value.lob.LobDataDatabase;
51
52 /**
53 * This class stores LOB objects in the database, in maps. This is the back-end
54 * i.e. the server side of the LOB storage.
55 */
56 public final class LobStorageMap implements LobStorageInterface
57 {
58 private static final boolean TRACE = false;
59
60 private final Database database;
61 final MVStore mvStore;
62 private final AtomicLong nextLobId = new AtomicLong(0);
63 private final ThreadPoolExecutor cleanupExecutor;
64
65
66 /**
67 * The lob metadata map. It contains the mapping from the lob id
68 * (which is a long) to the blob metadata, including stream store id (which is a byte array).
69 */
70 private final MVMap<Long, BlobMeta> lobMap;
71
72 /**
73 * The lob metadata map for temporary lobs. It contains the mapping from the lob id
74 * (which is a long) to the stream store id (which is a byte array).
75 *
76 * Key: lobId (long)
77 * Value: streamStoreId (byte[])
78 */
79 private final MVMap<Long, byte[]> tempLobMap;
80
81 /**
82 * The reference map. It is used to remove data from the stream store: if no
83 * more entries for the given streamStoreId exist, the data is removed from
84 * the stream store.
85 */
86 private final MVMap<BlobReference,Value> refMap;
87
88 private final StreamStore streamStore;
89
90 private final Queue<LobRemovalInfo> pendingLobRemovals = new ConcurrentLinkedQueue<>();
91
92 /**
93 * Open map used to store LOB metadata
94 * @param txStore containing map
95 * @return MVMap instance
96 */
97 public static MVMap<Long, LobStorageMap.BlobMeta> openLobMap(TransactionStore txStore) {
98 return txStore.openMap("lobMap", LongDataType.INSTANCE, LobStorageMap.BlobMeta.Type.INSTANCE);
99 }
100
101 /**
102 * Open map used to store LOB data
103 * @param txStore containing map
104 * @return MVMap instance
105 */
106 public static MVMap<Long, byte[]> openLobDataMap(TransactionStore txStore) {
107 return txStore.openMap("lobData", LongDataType.INSTANCE, ByteArrayDataType.INSTANCE);
108 }
109
110 public LobStorageMap(Database database) {
111 this.database = database;
112 Store s = database.getStore();
113 TransactionStore txStore = s.getTransactionStore();
114 mvStore = s.getMvStore();
115 if (mvStore.isVersioningRequired()) {
116 cleanupExecutor = Utils.createSingleThreadExecutor("H2-lob-cleaner", new SynchronousQueue<>());
117 mvStore.setOldestVersionTracker(oldestVersionToKeep -> {
118 if (needCleanup()) {
119 try {
120 cleanupExecutor.execute(() -> {
121 try {
122 cleanup(oldestVersionToKeep);
123 } catch (MVStoreException e) {
124 mvStore.panic(e);
125 }
126 });
127 } catch (RejectedExecutionException ignore) {/**/}
128 }
129 });
130 } else {
131 cleanupExecutor = null;
132 }
133 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
134 try {
135 lobMap = openLobMap(txStore);
136 tempLobMap = txStore.openMap("tempLobMap", LongDataType.INSTANCE, ByteArrayDataType.INSTANCE);
137 refMap = txStore.openMap("lobRef", BlobReference.Type.INSTANCE, NullValueDataType.INSTANCE);
138 /* The stream store data map.
139 *
140 * Key: stream store block id (long).
141 * Value: data (byte[]).
142 */
143 MVMap<Long, byte[]> dataMap = openLobDataMap(txStore);
144 streamStore = new StreamStore(dataMap);
145 // garbage collection of the last blocks
146 if (!database.isReadOnly()) {
147 // don't re-use block ids, except at the very end
148 Long last = dataMap.lastKey();
149 if (last != null) {
150 streamStore.setNextKey(last + 1);
151 }
152 // find the latest lob ID
153 Long id1 = lobMap.lastKey();
154 Long id2 = tempLobMap.lastKey(); // just in case we had unclean shutdown
155 long next = 1;
156 if (id1 != null) {
157 next = id1 + 1;
158 }
159 if (id2 != null) {
160 next = Math.max(next, id2 + 1);
161 }
162 nextLobId.set( next );
163 }
164 } finally {
165 mvStore.deregisterVersionUsage(txCounter);
166 }
167 }
168
169 @Override
170 public ValueBlob createBlob(InputStream in, long maxLength) {
171 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
172 try {
173 if (maxLength != -1
174 && maxLength <= database.getMaxLengthInplaceLob()) {
175 byte[] small = new byte[(int) maxLength];
176 int len = IOUtils.readFully(in, small, (int) maxLength);
177 if (len > maxLength) {
178 throw new IllegalStateException(
179 "len > blobLength, " + len + " > " + maxLength);
180 }
181 if (len < small.length) {
182 small = Arrays.copyOf(small, len);
183 }
184 return ValueBlob.createSmall(small);
185 }
186 if (maxLength != -1) {
187 in = new RangeInputStream(in, 0L, maxLength);
188 }
189 return createBlob(in);
190 } catch (IllegalStateException e) {
191 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
192 } catch (IOException e) {
193 throw DbException.convertIOException(e, null);
194 } finally {
195 mvStore.deregisterVersionUsage(txCounter);
196 }
197 }
198
199 @Override
200 public ValueClob createClob(Reader reader, long maxLength) {
201 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
202 try {
203 // we multiple by 3 here to get the worst-case size in bytes
204 if (maxLength != -1
205 && maxLength * 3 <= database.getMaxLengthInplaceLob()) {
206 char[] small = new char[(int) maxLength];
207 int len = IOUtils.readFully(reader, small, (int) maxLength);
208 if (len > maxLength) {
209 throw new IllegalStateException(
210 "len > blobLength, " + len + " > " + maxLength);
211 }
212 byte[] utf8 = new String(small, 0, len)
213 .getBytes(StandardCharsets.UTF_8);
214 if (utf8.length > database.getMaxLengthInplaceLob()) {
215 throw new IllegalStateException(
216 "len > maxinplace, " + utf8.length + " > "
217 + database.getMaxLengthInplaceLob());
218 }
219 return ValueClob.createSmall(utf8, len);
220 }
221 if (maxLength < 0) {
222 maxLength = Long.MAX_VALUE;
223 }
224 CountingReaderInputStream in = new CountingReaderInputStream(reader, maxLength);
225 ValueBlob blob = createBlob(in);
226 LobData lobData = blob.getLobData();
227 return new ValueClob(lobData, blob.octetLength(), in.getLength());
228 } catch (IllegalStateException e) {
229 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
230 } catch (IOException e) {
231 throw DbException.convertIOException(e, null);
232 } finally {
233 mvStore.deregisterVersionUsage(txCounter);
234 }
235 }
236
237 private ValueBlob createBlob(InputStream in) throws IOException {
238 byte[] streamStoreId;
239 try {
240 streamStoreId = streamStore.put(in);
241 } catch (Exception e) {
242 throw DataUtils.convertToIOException(e);
243 }
244 long lobId = generateLobId();
245 long length = streamStore.length(streamStoreId);
246 final int tableId = LobStorageFrontend.TABLE_TEMP;
247 tempLobMap.put(lobId, streamStoreId);
248 BlobReference key = new BlobReference(streamStoreId, lobId);
249 refMap.put(key, ValueNull.INSTANCE);
250 ValueBlob lob = new ValueBlob(new LobDataDatabase(database, tableId, lobId), length);
251 if (TRACE) {
252 trace("create " + tableId + "/" + lobId);
253 }
254 return lob;
255 }
256
257 private long generateLobId() {
258 return nextLobId.getAndIncrement();
259 }
260
261 @Override
262 public boolean isReadOnly() {
263 return database.isReadOnly();
264 }
265
266 @Override
267 public ValueLob copyLob(ValueLob old, int tableId) {
268 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
269 try {
270 final LobDataDatabase lobData = (LobDataDatabase) old.getLobData();
271 final int type = old.getValueType();
272 final long oldLobId = lobData.getLobId();
273 long octetLength = old.octetLength();
274 // get source lob
275 final byte[] streamStoreId;
276 if (isTemporaryLob(lobData.getTableId())) {
277 streamStoreId = tempLobMap.get(oldLobId);
278 } else {
279 BlobMeta value = lobMap.get(oldLobId);
280 streamStoreId = value.streamStoreId;
281 }
282 // create destination lob
283 final long newLobId = generateLobId();
284 if (isTemporaryLob(tableId)) {
285 tempLobMap.put(newLobId, streamStoreId);
286 } else {
287 BlobMeta value = new BlobMeta(streamStoreId, tableId,
288 type == Value.CLOB ? old.charLength() : octetLength, 0);
289 lobMap.put(newLobId, value);
290 }
291 BlobReference refMapKey = new BlobReference(streamStoreId, newLobId);
292 refMap.put(refMapKey, ValueNull.INSTANCE);
293 LobDataDatabase newLobData = new LobDataDatabase(database, tableId, newLobId);
294 ValueLob lob = type == Value.BLOB ? new ValueBlob(newLobData, octetLength)
295 : new ValueClob(newLobData, octetLength, old.charLength());
296 if (TRACE) {
297 trace("copy " + lobData.getTableId() + "/" + lobData.getLobId() +
298 " > " + tableId + "/" + newLobId);
299 }
300 return lob;
301 } finally {
302 mvStore.deregisterVersionUsage(txCounter);
303 }
304 }
305
306 @Override
307 public InputStream getInputStream(long lobId, long byteCount)
308 throws IOException {
309 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
310 try {
311 byte[] streamStoreId = tempLobMap.get(lobId);
312 if (streamStoreId == null) {
313 BlobMeta value = lobMap.get(lobId);
314 streamStoreId = value.streamStoreId;
315 }
316 if (streamStoreId == null) {
317 throw DbException.get(ErrorCode.LOB_CLOSED_ON_TIMEOUT_1, "" + lobId);
318 }
319 InputStream inputStream = streamStore.get(streamStoreId);
320 return new LobInputStream(inputStream);
321 } finally {
322 mvStore.deregisterVersionUsage(txCounter);
323 }
324 }
325
326 @Override
327 public InputStream getInputStream(long lobId, int tableId, long byteCount)
328 throws IOException {
329 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
330 try {
331 byte[] streamStoreId;
332 if (isTemporaryLob(tableId)) {
333 streamStoreId = tempLobMap.get(lobId);
334 } else {
335 BlobMeta value = lobMap.get(lobId);
336 streamStoreId = value.streamStoreId;
337 }
338 if (streamStoreId == null) {
339 throw DbException.get(ErrorCode.LOB_CLOSED_ON_TIMEOUT_1, "" + lobId);
340 }
341 InputStream inputStream = streamStore.get(streamStoreId);
342 return new LobInputStream(inputStream);
343 } finally {
344 mvStore.deregisterVersionUsage(txCounter);
345 }
346 }
347
348 private final class LobInputStream extends FilterInputStream {
349
350 public LobInputStream(InputStream in) {
351 super(in);
352 }
353
354 @Override
355 public int read(byte[] b, int off, int len) throws IOException {
356 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
357 try {
358 return super.read(b, off, len);
359 } finally {
360 mvStore.deregisterVersionUsage(txCounter);
361 }
362 }
363
364 @Override
365 public int read() throws IOException {
366 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
367 try {
368 return super.read();
369 } finally {
370 mvStore.deregisterVersionUsage(txCounter);
371 }
372 }
373 }
374
375 @Override
376 public void removeAllForTable(int tableId) {
377 if (mvStore.isClosed()) {
378 return;
379 }
380 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
381 try {
382 if (isTemporaryLob(tableId)) {
383 final Iterator<Long> iter = tempLobMap.keyIterator(0L);
384 while (iter.hasNext()) {
385 long lobId = iter.next();
386 doRemoveLob(tableId, lobId);
387 }
388 tempLobMap.clear();
389 } else {
390 final ArrayList<Long> list = new ArrayList<>();
391 // This might not be very efficient, but should only happen
392 // on DROP TABLE.
393 // To speed it up, we would need yet another map.
394 for (Entry<Long, BlobMeta> e : lobMap.entrySet()) {
395 BlobMeta value = e.getValue();
396 if (value.tableId == tableId) {
397 list.add(e.getKey());
398 }
399 }
400 for (long lobId : list) {
401 doRemoveLob(tableId, lobId);
402 }
403 }
404 } finally {
405 mvStore.deregisterVersionUsage(txCounter);
406 }
407 }
408
409 @Override
410 public void removeLob(ValueLob lob) {
411 LobDataDatabase lobData = (LobDataDatabase) lob.getLobData();
412 int tableId = lobData.getTableId();
413 long lobId = lobData.getLobId();
414 requestLobRemoval(tableId, lobId);
415 }
416
417 private void requestLobRemoval(int tableId, long lobId) {
418 pendingLobRemovals.offer(new LobRemovalInfo(mvStore.getCurrentVersion(), lobId, tableId));
419 }
420
421 private boolean needCleanup() {
422 return !pendingLobRemovals.isEmpty();
423 }
424
425 @Override
426 public void close() {
427 mvStore.setOldestVersionTracker(null);
428 Utils.shutdownExecutor(cleanupExecutor);
429 if (!mvStore.isClosed() && mvStore.isVersioningRequired()) {
430 // remove all session variables and temporary lobs
431 removeAllForTable(LobStorageFrontend.TABLE_ID_SESSION_VARIABLE);
432 // remove all dead LOBs, even deleted in current version, before the store closed
433 cleanup(mvStore.getCurrentVersion() + 1);
434 }
435 }
436
437 private void cleanup(long oldestVersionToKeep) {
438 MVStore.TxCounter txCounter = mvStore.registerVersionUsage();
439 try {
440 LobRemovalInfo lobRemovalInfo;
441 while ((lobRemovalInfo = pendingLobRemovals.poll()) != null
442 && lobRemovalInfo.version < oldestVersionToKeep) {
443 doRemoveLob(lobRemovalInfo.mapId, lobRemovalInfo.lobId);
444 }
445 if (lobRemovalInfo != null) {
446 pendingLobRemovals.offer(lobRemovalInfo);
447 }
448 } finally {
449 // we can not call deregisterVersionUsage() due to a possible infinite recursion
450 mvStore.decrementVersionUsageCounter(txCounter);
451 }
452 }
453
454 private void doRemoveLob(int tableId, long lobId) {
455 if (TRACE) {
456 trace("remove " + tableId + "/" + lobId);
457 }
458 byte[] streamStoreId;
459 if (isTemporaryLob(tableId)) {
460 streamStoreId = tempLobMap.remove(lobId);
461 if (streamStoreId == null) {
462 // already removed
463 return;
464 }
465 } else {
466 BlobMeta value = lobMap.remove(lobId);
467 if (value == null) {
468 // already removed
469 return;
470 }
471 streamStoreId = value.streamStoreId;
472 }
473 BlobReference key = new BlobReference(streamStoreId, lobId);
474 Value existing = refMap.remove(key);
475 assert existing != null;
476 // check if there are more entries for this streamStoreId
477 key = new BlobReference(streamStoreId, 0L);
478 BlobReference value = refMap.ceilingKey(key);
479 boolean hasMoreEntries = false;
480 if (value != null) {
481 byte[] s2 = value.streamStoreId;
482 if (Arrays.equals(streamStoreId, s2)) {
483 if (TRACE) {
484 trace(" stream still needed in lob " + value.lobId);
485 }
486 hasMoreEntries = true;
487 }
488 }
489 if (!hasMoreEntries) {
490 if (TRACE) {
491 trace(" remove stream " + StringUtils.convertBytesToHex(streamStoreId));
492 }
493 streamStore.remove(streamStoreId);
494 }
495 }
496
497 private static boolean isTemporaryLob(int tableId) {
498 return tableId == LobStorageFrontend.TABLE_ID_SESSION_VARIABLE || tableId == LobStorageFrontend.TABLE_TEMP
499 || tableId == LobStorageFrontend.TABLE_RESULT;
500 }
501
502 private static void trace(String op) {
503 System.out.println("[" + Thread.currentThread().getName() + "] LOB " + op);
504 }
505
506
507 public static final class BlobReference implements Comparable<BlobReference>
508 {
509 public final byte[] streamStoreId;
510 public final long lobId;
511
512 public BlobReference(byte[] streamStoreId, long lobId) {
513 this.streamStoreId = streamStoreId;
514 this.lobId = lobId;
515 }
516
517 @Override
518 public int compareTo(BlobReference other) {
519 int res = Integer.compare(streamStoreId.length, other.streamStoreId.length);
520 if (res == 0) {
521 for (int i = 0; res == 0 && i < streamStoreId.length; i++) {
522 res = Byte.compare(streamStoreId[i], other.streamStoreId[i]);
523 }
524 if (res == 0) {
525 res = Long.compare(lobId, other.lobId);
526 }
527 }
528 return res;
529 }
530
531 public static final class Type extends BasicDataType<BlobReference> {
532 public static final Type INSTANCE = new Type();
533
534 private Type() {}
535
536 @Override
537 public int getMemory(BlobReference blobReference) {
538 return blobReference.streamStoreId.length + 8;
539 }
540
541 @Override
542 public int compare(BlobReference one, BlobReference two) {
543 return one == two ? 0 : one == null ? 1 : two == null ? -1 : one.compareTo(two);
544 }
545
546 @Override
547 public void write(WriteBuffer buff, BlobReference blobReference) {
548 buff.putVarInt(blobReference.streamStoreId.length);
549 buff.put(blobReference.streamStoreId);
550 buff.putVarLong(blobReference.lobId);
551 }
552
553 @Override
554 public BlobReference read(ByteBuffer buff) {
555 int len = DataUtils.readVarInt(buff);
556 byte[] streamStoreId = new byte[len];
557 buff.get(streamStoreId);
558 long blobId = DataUtils.readVarLong(buff);
559 return new BlobReference(streamStoreId, blobId);
560 }
561
562 @Override
563 public BlobReference[] createStorage(int size) {
564 return new BlobReference[size];
565 }
566 }
567 }
568
569 public static final class BlobMeta
570 {
571 /**
572 * Stream identifier. It is used as a key in LOB data map.
573 */
574 public final byte[] streamStoreId;
575 final int tableId;
576 final long byteCount;
577 final long hash;
578
579 public BlobMeta(byte[] streamStoreId, int tableId, long byteCount, long hash) {
580 this.streamStoreId = streamStoreId;
581 this.tableId = tableId;
582 this.byteCount = byteCount;
583 this.hash = hash;
584 }
585
586 public static final class Type extends BasicDataType<BlobMeta> {
587 public static final Type INSTANCE = new Type();
588
589 private Type() {
590 }
591
592 @Override
593 public int getMemory(BlobMeta blobMeta) {
594 return blobMeta.streamStoreId.length + 20;
595 }
596
597 @Override
598 public void write(WriteBuffer buff, BlobMeta blobMeta) {
599 buff.putVarInt(blobMeta.streamStoreId.length);
600 buff.put(blobMeta.streamStoreId);
601 buff.putVarInt(blobMeta.tableId);
602 buff.putVarLong(blobMeta.byteCount);
603 buff.putLong(blobMeta.hash);
604 }
605
606 @Override
607 public BlobMeta read(ByteBuffer buff) {
608 int len = DataUtils.readVarInt(buff);
609 byte[] streamStoreId = new byte[len];
610 buff.get(streamStoreId);
611 int tableId = DataUtils.readVarInt(buff);
612 long byteCount = DataUtils.readVarLong(buff);
613 long hash = buff.getLong();
614 return new BlobMeta(streamStoreId, tableId, byteCount, hash);
615 }
616
617 @Override
618 public BlobMeta[] createStorage(int size) {
619 return new BlobMeta[size];
620 }
621 }
622 }
623
624 private static final class LobRemovalInfo
625 {
626 final long version;
627 final long lobId;
628 final int mapId;
629
630 LobRemovalInfo(long version, long lobId, int mapId) {
631 this.version = version;
632 this.lobId = lobId;
633 this.mapId = mapId;
634 }
635 }
636 }