Debian Codegraph @

src/main/org/h2/mvstore/Chunk.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.nio.ByteBuffer;
9 import java.nio.charset.StandardCharsets;
10 import java.util.BitSet;
11 import java.util.Comparator;
12 import java.util.Map;
13
14 import org.h2.util.StringUtils;
15
16 /**
17 * A chunk of data, containing one or multiple pages.
18 * <p>
19 * Minimum chunk size is usually 4096 bytes, and it grows in those fixed increments (blocks).
20 * Chunk's length and it's position in the underlying filestore
21 * are multiples of that increment (block size),
22 * therefore they both are measured in blocks, instead of bytes.
23 * There are at most 67 million (2^26) chunks,
24 * and each chunk is at most 2 GB large.
25 */
26 public abstract class Chunk<C extends Chunk<C>> {
27
28 /**
29 * The maximum chunk id.
30 */
31 public static final int MAX_ID = (1 << 26) - 1;
32
33 /**
34 * The maximum length of a chunk header, in bytes.
35 * chunk:ffffffff,len:ffffffff,pages:ffffffff,pinCount:ffffffff,max:ffffffffffffffff,map:ffffffff,
36 * root:ffffffffffffffff,time:ffffffffffffffff,version:ffffffffffffffff,next:ffffffffffffffff,toc:ffffffff
37 */
38 static final int MAX_HEADER_LENGTH = 1024; // 199 really
39
40 /**
41 * The length of the chunk footer. The longest footer is:
42 * chunk:ffffffff,len:ffffffff,version:ffffffffffffffff,fletcher:ffffffff
43 */
44 static final int FOOTER_LENGTH = 128; // it's really 70 now
45
46 private static final String ATTR_CHUNK = "chunk";
47 private static final String ATTR_BLOCK = "block";
48 private static final String ATTR_LEN = "len";
49 private static final String ATTR_MAP = "map";
50 private static final String ATTR_MAX = "max";
51 private static final String ATTR_NEXT = "next";
52 private static final String ATTR_PAGES = "pages";
53 private static final String ATTR_ROOT = "root";
54 private static final String ATTR_TIME = "time";
55 private static final String ATTR_VERSION = "version";
56 private static final String ATTR_LIVE_MAX = "liveMax";
57 private static final String ATTR_LIVE_PAGES = "livePages";
58 private static final String ATTR_UNUSED = "unused";
59 private static final String ATTR_UNUSED_AT_VERSION = "unusedAtVersion";
60 private static final String ATTR_PIN_COUNT = "pinCount";
61 private static final String ATTR_TOC = "toc";
62 private static final String ATTR_OCCUPANCY = "occupancy";
63 private static final String ATTR_FLETCHER = "fletcher";
64
65 /**
66 * The chunk id.
67 */
68 public final int id;
69
70 /**
71 * The start block number within the file.
72 */
73 public volatile long block;
74
75 /**
76 * The length in number of blocks.
77 */
78 public int len;
79
80 /**
81 * The total number of pages in this chunk.
82 */
83 int pageCount;
84
85 /**
86 * The number of pages that are still alive in the latest version of the store.
87 */
88 int pageCountLive;
89
90 /**
91 * Byte offset (from the beginning of the chunk) for the table of content (ToC).
92 * Table of content is holding a value of type "long" for each page in the chunk.
93 * This value consists of map id, page offset, page length and page type.
94 * Format is the same as page's position id, but with map id replacing chunk id.
95 *
96 * @see DataUtils#composeTocElement(int, int, int, int) for field format details
97 */
98 int tocPos;
99
100 /**
101 * Collection of "deleted" flags for all pages in the chunk.
102 */
103 BitSet occupancy;
104
105 /**
106 * The sum of the max length of all pages.
107 */
108 public long maxLen;
109
110 /**
111 * The sum of the length of all pages that are still alive.
112 */
113 public long maxLenLive;
114
115 /**
116 * The garbage collection priority. Priority 0 means it needs to be
117 * collected, a high value means low priority.
118 */
119 int collectPriority;
120
121 /**
122 * The position of the root of layout map.
123 */
124 long layoutRootPos;
125
126 /**
127 * The version stored in this chunk.
128 */
129 public long version;
130
131 /**
132 * When this chunk was created, in milliseconds since the store was created.
133 */
134 public long time;
135
136 /**
137 * When this chunk was no longer needed, in milliseconds after the store was
138 * created. After this, the chunk is kept alive a bit longer (in case it is
139 * referenced in older versions).
140 */
141 public long unused;
142
143 /**
144 * Version of the store at which chunk become unused and therefore can be
145 * considered "dead" and collected after this version is no longer in use.
146 */
147 long unusedAtVersion;
148
149 /**
150 * The last used map id.
151 */
152 public int mapId;
153
154 /**
155 * The predicted position of the next chunk.
156 */
157 public long next;
158
159 /**
160 * Number of live pinned pages.
161 */
162 private int pinCount;
163
164 /**
165 * ByteBuffer holding this Chunk's serialized content before it gets saved to file store.
166 * This allows to release pages of this Chunk earlier, allowing them to be garbage collected.
167 */
168 public volatile ByteBuffer buffer;
169
170 Chunk(String s) {
171 this(DataUtils.parseMap(s), true);
172 }
173
174 Chunk(Map<String, String> map, boolean full) {
175 this(DataUtils.readHexInt(map, ATTR_CHUNK, 0));
176 block = DataUtils.readHexLong(map, ATTR_BLOCK, 0);
177 len = DataUtils.readHexInt(map, ATTR_LEN, 0);
178 version = DataUtils.readHexLong(map, ATTR_VERSION, id);
179 if (full) {
180 pageCount = DataUtils.readHexInt(map, ATTR_PAGES, 0);
181 pageCountLive = DataUtils.readHexInt(map, ATTR_LIVE_PAGES, pageCount);
182 mapId = DataUtils.readHexInt(map, ATTR_MAP, 0);
183 maxLen = DataUtils.readHexLong(map, ATTR_MAX, 0);
184 maxLenLive = DataUtils.readHexLong(map, ATTR_LIVE_MAX, maxLen);
185 layoutRootPos = DataUtils.readHexLong(map, ATTR_ROOT, 0);
186 time = DataUtils.readHexLong(map, ATTR_TIME, 0);
187 unused = DataUtils.readHexLong(map, ATTR_UNUSED, 0);
188 unusedAtVersion = DataUtils.readHexLong(map, ATTR_UNUSED_AT_VERSION, 0);
189 next = DataUtils.readHexLong(map, ATTR_NEXT, 0);
190 pinCount = DataUtils.readHexInt(map, ATTR_PIN_COUNT, 0);
191 tocPos = DataUtils.readHexInt(map, ATTR_TOC, 0);
192 byte[] bytes = DataUtils.parseHexBytes(map, ATTR_OCCUPANCY);
193 if (bytes == null) {
194 occupancy = new BitSet();
195 assert pageCountLive == pageCount;
196 } else {
197 occupancy = BitSet.valueOf(bytes);
198 if (pageCount - pageCountLive != occupancy.cardinality()) {
199 throw DataUtils.newMVStoreException(
200 DataUtils.ERROR_FILE_CORRUPT, "Inconsistent occupancy info {0} - {1} != {2} {3}",
201 pageCount, pageCountLive, occupancy.cardinality(), this);
202 }
203 }
204 }
205 }
206
207 Chunk(int id) {
208 this.id = id;
209 if (id <= 0) {
210 throw DataUtils.newMVStoreException(
211 DataUtils.ERROR_FILE_CORRUPT, "Invalid chunk id {0}", id);
212 }
213 }
214
215 protected abstract ByteBuffer readFully(FileStore<C> fileStore, long filePos, int length);
216
217 /**
218 * Read the header from the byte buffer.
219 *
220 * @param buff the source buffer
221 * @return the chunk
222 */
223 static String readChunkHeader(ByteBuffer buff) {
224 int pos = buff.position();
225 byte[] data = new byte[Math.min(buff.remaining(), MAX_HEADER_LENGTH)];
226 buff.get(data);
227 for (int i = 0; i < data.length; i++) {
228 if (data[i] == '\n') {
229 // set the position to the start of the first page
230 buff.position(pos + i + 1);
231 String s = new String(data, 0, i, StandardCharsets.ISO_8859_1).trim();
232 return s;
233 }
234 }
235 return null;
236 }
237
238 /**
239 * Write the chunk header.
240 *
241 * @return estimated size of the header
242 */
243 int estimateHeaderSize() {
244 byte[] headerBytes = getHeaderBytes();
245 int headerLength = headerBytes.length;
246 // Initial chunk will look like (length-wise) something in between those two lines:
247 // chunk:0,len:0,pages:0,max:0,map:0,root:0,time:0,version:0 // 57
248 // chunk:ffffffff,len:0,pages:0,max:0,map:0,root:0,time:ffffffffffffffff,version:ffffffffffffffff // 94
249 assert 57 <= headerLength && headerLength <= 94 : headerLength + " " + getHeader();
250 // When header is fully formed, it will grow and here are fields,
251 // which do not exist in initial header or may grow from their initial values:
252 // len:0[fffffff],pages:0[fffffff][,pinCount:ffffffff],max:0[fffffffffffffff],map:0[fffffff],
253 // root:0[fffffffffffffff,next:ffffffffffffffff,toc:fffffffff] // 104 extra chars
254 return headerLength + 104 + 1; // extra one for the terminator
255 }
256
257 /**
258 * Write the chunk header.
259 *
260 * @param buff the target buffer
261 * @param maxLength length of the area reserved for the header
262 */
263 void writeChunkHeader(WriteBuffer buff, int maxLength) {
264 int terminatorPosition = buff.position() + maxLength - 1;
265 byte[] headerBytes = getHeaderBytes();
266 buff.put(headerBytes);
267 while (buff.position() < terminatorPosition) {
268 buff.put((byte) ' ');
269 }
270 if (maxLength != 0 && buff.position() > terminatorPosition) {
271 throw DataUtils.newMVStoreException(
272 DataUtils.ERROR_INTERNAL,
273 "Chunk metadata too long {0} {1} {2}", terminatorPosition, buff.position(),
274 getHeader());
275 }
276 buff.put((byte) '\n');
277 }
278
279 /**
280 * Get the metadata key for the given chunk id.
281 *
282 * @param chunkId the chunk id
283 * @return the metadata key
284 */
285 static String getMetaKey(int chunkId) {
286 return ATTR_CHUNK + "." + Integer.toHexString(chunkId);
287 }
288
289 /**
290 * Calculate the fill rate in %. 0 means empty, 100 means full.
291 *
292 * @return the fill rate
293 */
294 int getFillRate() {
295 assert maxLenLive <= maxLen : maxLenLive + " > " + maxLen;
296 if (maxLenLive <= 0) {
297 return 0;
298 } else if (maxLenLive == maxLen) {
299 return 100;
300 }
301 return 1 + (int) (98 * maxLenLive / maxLen);
302 }
303
304 @Override
305 public int hashCode() {
306 return id;
307 }
308
309 @SuppressWarnings("unchecked")
310 @Override
311 public boolean equals(Object o) {
312 return o instanceof Chunk && ((Chunk<C>) o).id == id;
313 }
314
315 /**
316 * Get the chunk metadata as a string to be stored in a layout map.
317 *
318 * @return the string
319 */
320 public final String asString() {
321 StringBuilder buff = new StringBuilder(240);
322 dump(buff);
323 return buff.toString();
324 }
325
326 protected void dump(StringBuilder buff) {
327 DataUtils.appendMap(buff, ATTR_CHUNK, id);
328 DataUtils.appendMap(buff, ATTR_BLOCK, block);
329 DataUtils.appendMap(buff, ATTR_LEN, len);
330 DataUtils.appendMap(buff, ATTR_PAGES, pageCount);
331 if (pageCount != pageCountLive) {
332 DataUtils.appendMap(buff, ATTR_LIVE_PAGES, pageCountLive);
333 }
334 DataUtils.appendMap(buff, ATTR_MAX, maxLen);
335 if (maxLen != maxLenLive) {
336 DataUtils.appendMap(buff, ATTR_LIVE_MAX, maxLenLive);
337 }
338 DataUtils.appendMap(buff, ATTR_MAP, mapId);
339 if (next != 0) {
340 DataUtils.appendMap(buff, ATTR_NEXT, next);
341 }
342 DataUtils.appendMap(buff, ATTR_ROOT, layoutRootPos);
343 DataUtils.appendMap(buff, ATTR_TIME, time);
344 if (unused != 0) {
345 DataUtils.appendMap(buff, ATTR_UNUSED, unused);
346 }
347 if (unusedAtVersion != 0) {
348 DataUtils.appendMap(buff, ATTR_UNUSED_AT_VERSION, unusedAtVersion);
349 }
350 DataUtils.appendMap(buff, ATTR_VERSION, version);
351 if (pinCount > 0) {
352 DataUtils.appendMap(buff, ATTR_PIN_COUNT, pinCount);
353 }
354 if (tocPos > 0) {
355 DataUtils.appendMap(buff, ATTR_TOC, tocPos);
356 }
357 if (occupancy != null && !occupancy.isEmpty()) {
358 DataUtils.appendMap(buff, ATTR_OCCUPANCY,
359 StringUtils.convertBytesToHex(occupancy.toByteArray()));
360 }
361 }
362
363 public String getHeader() {
364 return new String(getHeaderBytes(), StandardCharsets.ISO_8859_1);
365 }
366
367 private byte[] getHeaderBytes() {
368 StringBuilder buff = new StringBuilder(240);
369 DataUtils.appendMap(buff, ATTR_CHUNK, id);
370 DataUtils.appendMap(buff, ATTR_LEN, len);
371 DataUtils.appendMap(buff, ATTR_PAGES, pageCount);
372 if (pinCount > 0) {
373 DataUtils.appendMap(buff, ATTR_PIN_COUNT, pinCount);
374 }
375 DataUtils.appendMap(buff, ATTR_MAX, maxLen);
376 DataUtils.appendMap(buff, ATTR_MAP, mapId);
377 DataUtils.appendMap(buff, ATTR_ROOT, layoutRootPos);
378 DataUtils.appendMap(buff, ATTR_TIME, time);
379 DataUtils.appendMap(buff, ATTR_VERSION, version);
380 if (next != 0) {
381 DataUtils.appendMap(buff, ATTR_NEXT, next);
382 }
383 if (tocPos > 0) {
384 DataUtils.appendMap(buff, ATTR_TOC, tocPos);
385 }
386 return buff.toString().getBytes(StandardCharsets.ISO_8859_1);
387 }
388
389 byte[] getFooterBytes() {
390 StringBuilder buff = new StringBuilder(FOOTER_LENGTH);
391 DataUtils.appendMap(buff, ATTR_CHUNK, id);
392 DataUtils.appendMap(buff, ATTR_LEN, len);
393 DataUtils.appendMap(buff, ATTR_VERSION, version);
394 byte[] bytes = buff.toString().getBytes(StandardCharsets.ISO_8859_1);
395 int checksum = DataUtils.getFletcher32(bytes, 0, bytes.length);
396 DataUtils.appendMap(buff, ATTR_FLETCHER, checksum);
397 while (buff.length() < FOOTER_LENGTH - 1) {
398 buff.append(' ');
399 }
400 buff.append('\n');
401 return buff.toString().getBytes(StandardCharsets.ISO_8859_1);
402 }
403
404 boolean isAllocated() {
405 return block != 0;
406 }
407
408 boolean isSaved() {
409 return isAllocated() && buffer == null;
410 }
411
412 boolean isLive() {
413 return pageCountLive > 0;
414 }
415
416 boolean isRewritable() {
417 return isSaved()
418 && isLive()
419 && pageCountLive < pageCount // not fully occupied
420 && isEvacuatable();
421 }
422
423 private boolean isEvacuatable() {
424 return pinCount == 0;
425 }
426
427 /**
428 * Read a page of data into a ByteBuffer.
429 *
430 * @param fileStore to use
431 * @param offset of the page data
432 * @param pos page pos
433 * @return ByteBuffer containing page data.
434 */
435 ByteBuffer readBufferForPage(FileStore<C> fileStore, int offset, long pos) {
436 assert isSaved() : this;
437 while (true) {
438 long originalBlock = block;
439 try {
440 long filePos = originalBlock * FileStore.BLOCK_SIZE;
441 long maxPos = filePos + (long) len * FileStore.BLOCK_SIZE;
442 filePos += offset;
443 if (filePos < 0) {
444 throw DataUtils.newMVStoreException(
445 DataUtils.ERROR_FILE_CORRUPT,
446 "Negative position {0}; p={1}, c={2}", filePos, pos, toString());
447 }
448
449 int length = DataUtils.getPageMaxLength(pos);
450 if (length == DataUtils.PAGE_LARGE) {
451 // read the first bytes to figure out actual length
452 length = readFully(fileStore, filePos, 128).getInt();
453 // pageNo is deliberately not included into length to preserve compatibility
454 // TODO: remove this adjustment when page on disk format is re-organized
455 length += 4;
456 }
457 length = (int) Math.min(maxPos - filePos, length);
458 if (length < 0) {
459 throw DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
460 "Illegal page length {0} reading at {1}; max pos {2} ", length, filePos, maxPos);
461 }
462
463 ByteBuffer buff = buffer;
464 if (buff == null) {
465 buff = readFully(fileStore, filePos, length);
466 } else {
467 buff = buff.duplicate();
468 buff.position(offset);
469 buff = buff.slice();
470 buff.limit(length);
471 }
472
473 if (originalBlock == block) {
474 return buff;
475 }
476 } catch (MVStoreException ex) {
477 if (originalBlock == block) {
478 throw ex;
479 }
480 }
481 }
482 }
483
484 long[] readToC(FileStore<C> fileStore) {
485 assert buffer != null || isAllocated() : this;
486 assert tocPos > 0;
487 long[] toc = new long[pageCount];
488 while (true) {
489 long originalBlock = block;
490 try {
491 ByteBuffer buff = buffer;
492 if (buff == null) {
493 int length = pageCount * 8;
494 long filePos = originalBlock * FileStore.BLOCK_SIZE + tocPos;
495 buff = readFully(fileStore, filePos, length);
496 } else {
497 buff = buff.duplicate();
498 buff.position(tocPos);
499 buff = buff.slice();
500 }
501 buff.asLongBuffer().get(toc);
502 if (originalBlock == block) {
503 return toc;
504 }
505 } catch (MVStoreException ex) {
506 if (originalBlock == block) {
507 throw ex;
508 }
509 }
510 }
511 }
512
513 /**
514 * Modifies internal state to reflect the fact that one more page is stored
515 * within this chunk.
516 * @param pageLengthOnDisk
517 * size of the page
518 * @param singleWriter
519 * indicates whether page belongs to append mode capable map
520 * (single writer map). Such pages are "pinned" to the chunk,
521 * they can't be evacuated (moved to a different chunk) while
522 */
523 void accountForWrittenPage(int pageLengthOnDisk, boolean singleWriter) {
524 maxLen += pageLengthOnDisk;
525 pageCount++;
526 maxLenLive += pageLengthOnDisk;
527 pageCountLive++;
528 if (singleWriter) {
529 pinCount++;
530 }
531 assert pageCount - pageCountLive == occupancy.cardinality()
532 : pageCount + " - " + pageCountLive + " <> " + occupancy.cardinality() + " : " + occupancy;
533 }
534
535 /**
536 * Modifies internal state to reflect the fact that one the pages within
537 * this chunk was removed from the map.
538 *
539 * @param pageNo
540 * sequential page number within the chunk
541 * @param pageLength
542 * on disk of the removed page
543 * @param pinned
544 * whether removed page was pinned
545 * @param now
546 * is a moment in time (since creation of the store), when
547 * removal is recorded, and retention period starts
548 * @param version
549 * at which page was removed
550 * @return true if all of the pages, this chunk contains, were already
551 * removed, and false otherwise
552 */
553 boolean accountForRemovedPage(int pageNo, int pageLength, boolean pinned, long now, long version) {
554 assert buffer != null || isAllocated() : this;
555 // legacy chunks do not have a table of content,
556 // therefore pageNo is not valid, skip
557 if (tocPos > 0) {
558 assert pageNo >= 0 && pageNo < pageCount : pageNo + " // " + pageCount;
559 assert !occupancy.get(pageNo) : pageNo + " " + this + " " + occupancy;
560 assert pageCount - pageCountLive == occupancy.cardinality()
561 : pageCount + " - " + pageCountLive + " <> " + occupancy.cardinality() + " : " + occupancy;
562 occupancy.set(pageNo);
563 }
564
565 maxLenLive -= pageLength;
566 pageCountLive--;
567 if (pinned) {
568 pinCount--;
569 }
570
571 if (unusedAtVersion < version) {
572 unusedAtVersion = version;
573 }
574
575 assert pinCount >= 0 : this;
576 assert pageCountLive >= 0 : this;
577 assert pinCount <= pageCountLive : this;
578 assert maxLenLive >= 0 : this;
579 assert (pageCountLive == 0) == (maxLenLive == 0) : this;
580
581 if (!isLive()) {
582 unused = now;
583 return true;
584 }
585 return false;
586 }
587
588 @Override
589 public String toString() {
590 return asString() + (buffer == null ? "" : ", buf");
591 }
592
593
594 public static final class PositionComparator<C extends Chunk<C>> implements Comparator<C>
595 {
596 public static final Comparator<? extends Chunk<?>> INSTANCE = new PositionComparator<>();
597
598 @SuppressWarnings("unchecked")
599 public static <C extends Chunk<C>> Comparator<C> instance() {
600 return (Comparator<C>)INSTANCE;
601 }
602
603 private PositionComparator() {}
604
605 @Override
606 public int compare(C one, C two) {
607 return Long.compare(one.block, two.block);
608 }
609 }
610 }
611