| 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.io.IOException; |
| 9 |
import java.io.OutputStream; |
| 10 |
import java.io.PrintWriter; |
| 11 |
import java.io.Writer; |
| 12 |
import java.nio.ByteBuffer; |
| 13 |
import java.nio.channels.FileChannel; |
| 14 |
import java.nio.charset.StandardCharsets; |
| 15 |
import java.sql.Timestamp; |
| 16 |
import java.util.Map; |
| 17 |
import java.util.Map.Entry; |
| 18 |
import java.util.TreeMap; |
| 19 |
|
| 20 |
import org.h2.compress.CompressDeflate; |
| 21 |
import org.h2.compress.CompressLZF; |
| 22 |
import org.h2.compress.Compressor; |
| 23 |
import org.h2.engine.Constants; |
| 24 |
import org.h2.mvstore.tx.TransactionStore; |
| 25 |
import org.h2.mvstore.type.BasicDataType; |
| 26 |
import org.h2.mvstore.type.StringDataType; |
| 27 |
import org.h2.store.fs.FilePath; |
| 28 |
import org.h2.store.fs.FileUtils; |
| 29 |
import org.h2.util.Utils; |
| 30 |
|
| 31 |
/** |
| 32 |
* Utility methods used in combination with the MVStore. |
| 33 |
*/ |
| 34 |
public class MVStoreTool { |
| 35 |
|
| 36 |
/** |
| 37 |
* Runs this tool. |
| 38 |
* Options are case sensitive. Supported options are: |
| 39 |
* <table> |
| 40 |
* <caption>Command line options</caption> |
| 41 |
* <tr><td>[-dump <fileName>]</td> |
| 42 |
* <td>Dump the contends of the file</td></tr> |
| 43 |
* <tr><td>[-info <fileName>]</td> |
| 44 |
* <td>Get summary information about a file</td></tr> |
| 45 |
* <tr><td>[-compact <fileName>]</td> |
| 46 |
* <td>Compact a store</td></tr> |
| 47 |
* <tr><td>[-compress <fileName>]</td> |
| 48 |
* <td>Compact a store with compression enabled</td></tr> |
| 49 |
* </table> |
| 50 |
* |
| 51 |
* @param args the command line arguments |
| 52 |
*/ |
| 53 |
public static void main(String... args) { |
| 54 |
for (int i = 0; i < args.length; i++) { |
| 55 |
if ("-dump".equals(args[i])) { |
| 56 |
String fileName = args[++i]; |
| 57 |
dump(fileName, new PrintWriter(System.out), true); |
| 58 |
} else if ("-info".equals(args[i])) { |
| 59 |
String fileName = args[++i]; |
| 60 |
info(fileName, new PrintWriter(System.out)); |
| 61 |
} else if ("-compact".equals(args[i])) { |
| 62 |
String fileName = args[++i]; |
| 63 |
compact(fileName, false); |
| 64 |
} else if ("-compress".equals(args[i])) { |
| 65 |
String fileName = args[++i]; |
| 66 |
compact(fileName, true); |
| 67 |
} else if ("-rollback".equals(args[i])) { |
| 68 |
String fileName = args[++i]; |
| 69 |
long targetVersion = Long.decode(args[++i]); |
| 70 |
rollback(fileName, targetVersion, new PrintWriter(System.out)); |
| 71 |
} else if ("-repair".equals(args[i])) { |
| 72 |
String fileName = args[++i]; |
| 73 |
repair(fileName); |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Read the contents of the file and write them to system out. |
| 80 |
* |
| 81 |
* @param fileName the name of the file |
| 82 |
* @param details whether to print details |
| 83 |
*/ |
| 84 |
public static void dump(String fileName, boolean details) { |
| 85 |
dump(fileName, new PrintWriter(System.out), details); |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Read the summary information of the file and write them to system out. |
| 90 |
* |
| 91 |
* @param fileName the name of the file |
| 92 |
*/ |
| 93 |
public static void info(String fileName) { |
| 94 |
info(fileName, new PrintWriter(System.out)); |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Read the contents of the file and display them in a human-readable |
| 99 |
* format. |
| 100 |
* |
| 101 |
* @param fileName the name of the file |
| 102 |
* @param writer the print writer |
| 103 |
* @param details print the page details |
| 104 |
*/ |
| 105 |
public static void dump(String fileName, Writer writer, boolean details) { |
| 106 |
PrintWriter pw = new PrintWriter(writer, true); |
| 107 |
if (!FilePath.get(fileName).exists()) { |
| 108 |
pw.println("File not found: " + fileName); |
| 109 |
return; |
| 110 |
} |
| 111 |
long size = FileUtils.size(fileName); |
| 112 |
pw.printf("File %s, %d bytes, %d MB\n", fileName, size, size / 1024 / 1024); |
| 113 |
int blockSize = FileStore.BLOCK_SIZE; |
| 114 |
TreeMap<Integer, Long> mapSizesTotal = |
| 115 |
new TreeMap<>(); |
| 116 |
long pageSizeTotal = 0; |
| 117 |
try (FileChannel file = FilePath.get(fileName).open("r")) { |
| 118 |
long fileSize = file.size(); |
| 119 |
int len = Long.toHexString(fileSize).length(); |
| 120 |
ByteBuffer buffer = ByteBuffer.allocate(4096); |
| 121 |
long pageCount = 0; |
| 122 |
for (long pos = 0; pos < fileSize; ) { |
| 123 |
buffer.rewind(); |
| 124 |
// Bugfix - An MVStoreException that wraps EOFException is |
| 125 |
// thrown when partial writes happens in the case of power off |
| 126 |
// or file system issues. |
| 127 |
// So we should skip the broken block at end of the DB file. |
| 128 |
try { |
| 129 |
DataUtils.readFully(file, pos, buffer); |
| 130 |
} catch (MVStoreException e) { |
| 131 |
pos += blockSize; |
| 132 |
pw.printf("ERROR illegal position %d%n", pos); |
| 133 |
continue; |
| 134 |
} |
| 135 |
buffer.rewind(); |
| 136 |
int headerType = buffer.get(); |
| 137 |
if (headerType == 'H') { |
| 138 |
String header = new String(buffer.array(), StandardCharsets.ISO_8859_1).trim(); |
| 139 |
pw.printf("%0" + len + "x fileHeader %s%n", |
| 140 |
pos, header); |
| 141 |
pos += blockSize; |
| 142 |
continue; |
| 143 |
} |
| 144 |
if (headerType != 'c') { |
| 145 |
pos += blockSize; |
| 146 |
continue; |
| 147 |
} |
| 148 |
buffer.position(0); |
| 149 |
Chunk c; |
| 150 |
try { |
| 151 |
c = new SFChunk(Chunk.readChunkHeader(buffer)); |
| 152 |
} catch (MVStoreException e) { |
| 153 |
pos += blockSize; |
| 154 |
continue; |
| 155 |
} |
| 156 |
if (c.len <= 0) { |
| 157 |
// not a chunk |
| 158 |
pos += blockSize; |
| 159 |
continue; |
| 160 |
} |
| 161 |
int length = c.len * FileStore.BLOCK_SIZE; |
| 162 |
pw.printf("%n%0" + len + "x chunkHeader %s%n", pos, c); |
| 163 |
ByteBuffer chunk = ByteBuffer.allocate(length); |
| 164 |
DataUtils.readFully(file, pos, chunk); |
| 165 |
int p = buffer.position(); |
| 166 |
pos += length; |
| 167 |
int remaining = c.pageCount; |
| 168 |
pageCount += c.pageCount; |
| 169 |
TreeMap<Integer, Integer> mapSizes = |
| 170 |
new TreeMap<>(); |
| 171 |
int pageSizeSum = 0; |
| 172 |
while (remaining > 0) { |
| 173 |
int start = p; |
| 174 |
try { |
| 175 |
chunk.position(p); |
| 176 |
} catch (IllegalArgumentException e) { |
| 177 |
// too far |
| 178 |
pw.printf("ERROR illegal position %d%n", p); |
| 179 |
break; |
| 180 |
} |
| 181 |
int pageSize = chunk.getInt(); |
| 182 |
// check value (ignored) |
| 183 |
chunk.getShort(); |
| 184 |
/*int pageNo =*/ DataUtils.readVarInt(chunk); |
| 185 |
int mapId = DataUtils.readVarInt(chunk); |
| 186 |
int entries = DataUtils.readVarInt(chunk); |
| 187 |
int type = chunk.get(); |
| 188 |
boolean compressed = (type & DataUtils.PAGE_COMPRESSED) != 0; |
| 189 |
boolean node = (type & DataUtils.PAGE_TYPE_NODE) != 0; |
| 190 |
if (details) { |
| 191 |
pw.printf( |
| 192 |
"+%0" + len + |
| 193 |
"x %s, map %x, %d entries, %d bytes, maxLen %x%n", |
| 194 |
p, |
| 195 |
(node ? "node" : "leaf") + |
| 196 |
(compressed ? " compressed" : ""), |
| 197 |
mapId, |
| 198 |
node ? entries + 1 : entries, |
| 199 |
pageSize, |
| 200 |
DataUtils.getPageMaxLength(DataUtils.composePagePos(0, 0, pageSize, 0)) |
| 201 |
); |
| 202 |
} |
| 203 |
p += pageSize; |
| 204 |
Integer mapSize = mapSizes.get(mapId); |
| 205 |
if (mapSize == null) { |
| 206 |
mapSize = 0; |
| 207 |
} |
| 208 |
mapSizes.put(mapId, mapSize + pageSize); |
| 209 |
Long total = mapSizesTotal.get(mapId); |
| 210 |
if (total == null) { |
| 211 |
total = 0L; |
| 212 |
} |
| 213 |
mapSizesTotal.put(mapId, total + pageSize); |
| 214 |
pageSizeSum += pageSize; |
| 215 |
pageSizeTotal += pageSize; |
| 216 |
remaining--; |
| 217 |
long[] children = null; |
| 218 |
long[] counts = null; |
| 219 |
if (node) { |
| 220 |
children = new long[entries + 1]; |
| 221 |
for (int i = 0; i <= entries; i++) { |
| 222 |
children[i] = chunk.getLong(); |
| 223 |
} |
| 224 |
counts = new long[entries + 1]; |
| 225 |
for (int i = 0; i <= entries; i++) { |
| 226 |
long s = DataUtils.readVarLong(chunk); |
| 227 |
counts[i] = s; |
| 228 |
} |
| 229 |
} |
| 230 |
String[] keys = new String[entries]; |
| 231 |
if (mapId == 0 && details) { |
| 232 |
ByteBuffer data; |
| 233 |
if (compressed) { |
| 234 |
boolean fast = (type & DataUtils.PAGE_COMPRESSED_HIGH) != DataUtils.PAGE_COMPRESSED_HIGH; |
| 235 |
Compressor compressor = getCompressor(fast); |
| 236 |
int lenAdd = DataUtils.readVarInt(chunk); |
| 237 |
int compLen = pageSize + start - chunk.position(); |
| 238 |
byte[] comp = Utils.newBytes(compLen); |
| 239 |
chunk.get(comp); |
| 240 |
int l = compLen + lenAdd; |
| 241 |
data = ByteBuffer.allocate(l); |
| 242 |
compressor.expand(comp, 0, compLen, data.array(), 0, l); |
| 243 |
} else { |
| 244 |
data = chunk; |
| 245 |
} |
| 246 |
for (int i = 0; i < entries; i++) { |
| 247 |
String k = StringDataType.INSTANCE.read(data); |
| 248 |
keys[i] = k; |
| 249 |
} |
| 250 |
if (node) { |
| 251 |
// meta map node |
| 252 |
for (int i = 0; i < entries; i++) { |
| 253 |
long cp = children[i]; |
| 254 |
pw.printf(" %d children < %s @ " + |
| 255 |
"chunk %x +%0" + |
| 256 |
len + "x%n", |
| 257 |
counts[i], |
| 258 |
keys[i], |
| 259 |
DataUtils.getPageChunkId(cp), |
| 260 |
DataUtils.getPageOffset(cp)); |
| 261 |
} |
| 262 |
long cp = children[entries]; |
| 263 |
pw.printf(" %d children >= %s @ chunk %x +%0" + |
| 264 |
len + "x%n", |
| 265 |
counts[entries], |
| 266 |
entries <= keys.length ? null : keys[entries], |
| 267 |
DataUtils.getPageChunkId(cp), |
| 268 |
DataUtils.getPageOffset(cp)); |
| 269 |
} else { |
| 270 |
// meta map leaf |
| 271 |
String[] values = new String[entries]; |
| 272 |
for (int i = 0; i < entries; i++) { |
| 273 |
String v = StringDataType.INSTANCE.read(data); |
| 274 |
values[i] = v; |
| 275 |
} |
| 276 |
for (int i = 0; i < entries; i++) { |
| 277 |
pw.println(" " + keys[i] + |
| 278 |
" = " + values[i]); |
| 279 |
} |
| 280 |
} |
| 281 |
} else { |
| 282 |
if (node && details) { |
| 283 |
for (int i = 0; i <= entries; i++) { |
| 284 |
long cp = children[i]; |
| 285 |
pw.printf(" %d children @ chunk %x +%0" + |
| 286 |
len + "x%n", |
| 287 |
counts[i], |
| 288 |
DataUtils.getPageChunkId(cp), |
| 289 |
DataUtils.getPageOffset(cp)); |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
} |
| 294 |
pageSizeSum = Math.max(1, pageSizeSum); |
| 295 |
for (Integer mapId : mapSizes.keySet()) { |
| 296 |
int percent = 100 * mapSizes.get(mapId) / pageSizeSum; |
| 297 |
pw.printf("map %x: %d bytes, %d%%%n", mapId, mapSizes.get(mapId), percent); |
| 298 |
} |
| 299 |
int footerPos = chunk.limit() - Chunk.FOOTER_LENGTH; |
| 300 |
try { |
| 301 |
chunk.position(footerPos); |
| 302 |
pw.printf( |
| 303 |
"+%0" + len + "x chunkFooter %s%n", |
| 304 |
footerPos, |
| 305 |
new String(chunk.array(), chunk.position(), |
| 306 |
Chunk.FOOTER_LENGTH, StandardCharsets.ISO_8859_1).trim()); |
| 307 |
} catch (IllegalArgumentException e) { |
| 308 |
// too far |
| 309 |
pw.printf("ERROR illegal footer position %d%n", footerPos); |
| 310 |
} |
| 311 |
} |
| 312 |
pw.printf("%n%0" + len + "x eof%n", fileSize); |
| 313 |
pw.printf("\n"); |
| 314 |
pageCount = Math.max(1, pageCount); |
| 315 |
pw.printf("page size total: %d bytes, page count: %d, average page size: %d bytes\n", |
| 316 |
pageSizeTotal, pageCount, pageSizeTotal / pageCount); |
| 317 |
pageSizeTotal = Math.max(1, pageSizeTotal); |
| 318 |
for (Integer mapId : mapSizesTotal.keySet()) { |
| 319 |
int percent = (int) (100 * mapSizesTotal.get(mapId) / pageSizeTotal); |
| 320 |
pw.printf("map %x: %d bytes, %d%%%n", mapId, mapSizesTotal.get(mapId), percent); |
| 321 |
} |
| 322 |
} catch (IOException e) { |
| 323 |
pw.println("ERROR: " + e); |
| 324 |
e.printStackTrace(pw); |
| 325 |
} |
| 326 |
// ignore |
| 327 |
pw.flush(); |
| 328 |
} |
| 329 |
|
| 330 |
private static Compressor getCompressor(boolean fast) { |
| 331 |
return fast ? new CompressLZF() : new CompressDeflate(); |
| 332 |
} |
| 333 |
|
| 334 |
/** |
| 335 |
* Read the summary information of the file and write them to system out. |
| 336 |
* |
| 337 |
* @param fileName the name of the file |
| 338 |
* @param writer the print writer |
| 339 |
* @return null if successful (if there was no error), otherwise the error |
| 340 |
* message |
| 341 |
*/ |
| 342 |
public static String info(String fileName, Writer writer) { |
| 343 |
PrintWriter pw = new PrintWriter(writer, true); |
| 344 |
if (!FilePath.get(fileName).exists()) { |
| 345 |
pw.println("File not found: " + fileName); |
| 346 |
return "File not found: " + fileName; |
| 347 |
} |
| 348 |
long fileLength = FileUtils.size(fileName); |
| 349 |
try (MVStore store = new MVStore.Builder(). |
| 350 |
fileName(fileName).recoveryMode(). |
| 351 |
readOnly().open()) { |
| 352 |
Map<String, String> layout = store.getLayoutMap(); |
| 353 |
Map<String, Object> header = store.getStoreHeader(); |
| 354 |
long fileCreated = DataUtils.readHexLong(header, "created", 0L); |
| 355 |
TreeMap<Integer, Chunk<?>> chunks = new TreeMap<>(); |
| 356 |
long chunkLength = 0; |
| 357 |
long maxLength = 0; |
| 358 |
long maxLengthLive = 0; |
| 359 |
long maxLengthNotEmpty = 0; |
| 360 |
for (Entry<String, String> e : layout.entrySet()) { |
| 361 |
String k = e.getKey(); |
| 362 |
if (k.startsWith(DataUtils.META_CHUNK)) { |
| 363 |
Chunk<?> c = store.getFileStore().createChunk(e.getValue()); |
| 364 |
chunks.put(c.id, c); |
| 365 |
chunkLength += (long)c.len * FileStore.BLOCK_SIZE; |
| 366 |
maxLength += c.maxLen; |
| 367 |
maxLengthLive += c.maxLenLive; |
| 368 |
if (c.maxLenLive > 0) { |
| 369 |
maxLengthNotEmpty += c.maxLen; |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
pw.printf("Created: %s\n", formatTimestamp(fileCreated, fileCreated)); |
| 374 |
pw.printf("Last modified: %s\n", |
| 375 |
formatTimestamp(FileUtils.lastModified(fileName), fileCreated)); |
| 376 |
pw.printf("File length: %d\n", fileLength); |
| 377 |
pw.printf("The last chunk is not listed\n"); |
| 378 |
pw.printf("Chunk length: %d\n", chunkLength); |
| 379 |
pw.printf("Chunk count: %d\n", chunks.size()); |
| 380 |
pw.printf("Used space: %d%%\n", getPercent(chunkLength, fileLength)); |
| 381 |
pw.printf("Chunk fill rate: %d%%\n", maxLength == 0 ? 100 : |
| 382 |
getPercent(maxLengthLive, maxLength)); |
| 383 |
pw.printf("Chunk fill rate excluding empty chunks: %d%%\n", |
| 384 |
maxLengthNotEmpty == 0 ? 100 : |
| 385 |
getPercent(maxLengthLive, maxLengthNotEmpty)); |
| 386 |
for (Entry<Integer, Chunk<?>> e : chunks.entrySet()) { |
| 387 |
Chunk<?> c = e.getValue(); |
| 388 |
long created = fileCreated + c.time; |
| 389 |
pw.printf(" Chunk %d: %s, %d%% used, %d blocks", |
| 390 |
c.id, formatTimestamp(created, fileCreated), |
| 391 |
getPercent(c.maxLenLive, c.maxLen), |
| 392 |
c.len |
| 393 |
); |
| 394 |
if (c.maxLenLive == 0) { |
| 395 |
pw.printf(", unused: %s", |
| 396 |
formatTimestamp(fileCreated + c.unused, fileCreated)); |
| 397 |
} |
| 398 |
pw.printf("\n"); |
| 399 |
} |
| 400 |
pw.printf("\n"); |
| 401 |
} catch (Exception e) { |
| 402 |
pw.println("ERROR: " + e); |
| 403 |
e.printStackTrace(pw); |
| 404 |
return e.getMessage(); |
| 405 |
} |
| 406 |
pw.flush(); |
| 407 |
return null; |
| 408 |
} |
| 409 |
|
| 410 |
private static String formatTimestamp(long t, long start) { |
| 411 |
String x = new Timestamp(t).toString(); |
| 412 |
String s = x.substring(0, 19); |
| 413 |
s += " (+" + ((t - start) / 1000) + " s)"; |
| 414 |
return s; |
| 415 |
} |
| 416 |
|
| 417 |
private static int getPercent(long value, long max) { |
| 418 |
if (value == 0) { |
| 419 |
return 0; |
| 420 |
} else if (value == max) { |
| 421 |
return 100; |
| 422 |
} |
| 423 |
return (int) (1 + 98 * value / Math.max(1, max)); |
| 424 |
} |
| 425 |
|
| 426 |
/** |
| 427 |
* Compress the store by creating a new file and copying the live pages |
| 428 |
* there. Temporarily, a file with the suffix ".tempFile" is created. This |
| 429 |
* file is then renamed, replacing the original file, if possible. If not, |
| 430 |
* the new file is renamed to ".newFile", then the old file is removed, and |
| 431 |
* the new file is renamed. This might be interrupted, so it's better to |
| 432 |
* compactCleanUp before opening a store, in case this method was used. |
| 433 |
* |
| 434 |
* @param fileName the file name |
| 435 |
* @param compress whether to compress the data |
| 436 |
*/ |
| 437 |
public static void compact(String fileName, boolean compress) { |
| 438 |
String tempName = fileName + Constants.SUFFIX_MV_STORE_TEMP_FILE; |
| 439 |
FileUtils.delete(tempName); |
| 440 |
compact(fileName, tempName, compress); |
| 441 |
moveAtomicReplace(tempName, fileName); |
| 442 |
} |
| 443 |
|
| 444 |
/** |
| 445 |
* Rename a file(s) of the named store, and try to atomically replace an |
| 446 |
* existing file(s) of another store. |
| 447 |
* |
| 448 |
* @param sourceName the old fully qualified file name of the store |
| 449 |
* @param destinationName the new fully qualified file name of the store |
| 450 |
*/ |
| 451 |
public static void moveAtomicReplace(String sourceName, String destinationName) { |
| 452 |
try { |
| 453 |
FileUtils.moveAtomicReplace(sourceName, destinationName); |
| 454 |
} catch (MVStoreException e) { |
| 455 |
String newName = destinationName + Constants.SUFFIX_MV_STORE_NEW_FILE; |
| 456 |
FileUtils.delete(newName); |
| 457 |
FileUtils.move(sourceName, newName); |
| 458 |
FileUtils.delete(destinationName); |
| 459 |
FileUtils.move(newName, destinationName); |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
/** |
| 464 |
* Clean up if needed, in a case a compact operation was interrupted due to |
| 465 |
* killing the process or a power failure. This will delete temporary files |
| 466 |
* (if any), and in case atomic file replacements were not used, rename the |
| 467 |
* new file. |
| 468 |
* |
| 469 |
* @param fileName the file name |
| 470 |
*/ |
| 471 |
public static void compactCleanUp(String fileName) { |
| 472 |
String tempName = fileName + Constants.SUFFIX_MV_STORE_TEMP_FILE; |
| 473 |
if (FileUtils.exists(tempName)) { |
| 474 |
FileUtils.delete(tempName); |
| 475 |
} |
| 476 |
String newName = fileName + Constants.SUFFIX_MV_STORE_NEW_FILE; |
| 477 |
if (FileUtils.exists(newName)) { |
| 478 |
if (FileUtils.exists(fileName)) { |
| 479 |
FileUtils.delete(newName); |
| 480 |
} else { |
| 481 |
FileUtils.move(newName, fileName); |
| 482 |
} |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
/** |
| 487 |
* Copy all live pages from the source store to the target store. |
| 488 |
* |
| 489 |
* @param sourceFileName the name of the source store |
| 490 |
* @param targetFileName the name of the target store |
| 491 |
* @param compress whether to compress the data |
| 492 |
*/ |
| 493 |
public static void compact(String sourceFileName, String targetFileName, boolean compress) { |
| 494 |
try (MVStore source = new MVStore.Builder(). |
| 495 |
fileName(sourceFileName).readOnly().open()) { |
| 496 |
// Bugfix - Add double "try-finally" statements to close source and target stores for |
| 497 |
//releasing lock and file resources in these stores even if OOM occurs. |
| 498 |
// Fix issues such as "Cannot delete file "/h2/data/test.mv.db.tempFile" [90025-197]" |
| 499 |
//when client connects to this server and reopens this store database in this process. |
| 500 |
// @since 2018-09-13 little-pan |
| 501 |
FileUtils.delete(targetFileName); |
| 502 |
MVStore.Builder b = new MVStore.Builder(). |
| 503 |
fileName(targetFileName); |
| 504 |
if (compress) { |
| 505 |
b.compress(); |
| 506 |
} |
| 507 |
try (MVStore target = b.open()) { |
| 508 |
compact(source, target); |
| 509 |
} |
| 510 |
} |
| 511 |
} |
| 512 |
|
| 513 |
/** |
| 514 |
* Copy all live pages from the source store to the target store. |
| 515 |
* |
| 516 |
* @param source the source store |
| 517 |
* @param target the target store |
| 518 |
*/ |
| 519 |
public static void compact(MVStore source, MVStore target) { |
| 520 |
target.setCurrentVersion(source.getCurrentVersion()); |
| 521 |
target.adjustLastMapId(source.getLastMapId()); |
| 522 |
int autoCommitDelay = target.getAutoCommitDelay(); |
| 523 |
boolean reuseSpace = target.isSpaceReused(); |
| 524 |
try { |
| 525 |
target.setReuseSpace(false); // disable unused chunks collection |
| 526 |
target.setAutoCommitDelay(0); // disable autocommit |
| 527 |
MVMap<String, String> sourceMeta = source.getMetaMap(); |
| 528 |
MVMap<String, String> targetMeta = target.getMetaMap(); |
| 529 |
for (Entry<String, String> m : sourceMeta.entrySet()) { |
| 530 |
String key = m.getKey(); |
| 531 |
if (key.startsWith(DataUtils.META_MAP)) { |
| 532 |
// ignore |
| 533 |
} else if (key.startsWith(DataUtils.META_NAME)) { |
| 534 |
// ignore |
| 535 |
} else { |
| 536 |
targetMeta.put(key, m.getValue()); |
| 537 |
} |
| 538 |
} |
| 539 |
// We are going to cheat a little bit in the copyFrom() by employing "incomplete" pages, |
| 540 |
// which would be spared of saving, but save completed pages underneath, |
| 541 |
// and those may appear as dead (non-reachable). |
| 542 |
// That's why it is important to preserve all chunks |
| 543 |
// created in the process, especially if retention time |
| 544 |
// is set to a lower value, or even 0. |
| 545 |
for (String mapName : source.getMapNames()) { |
| 546 |
MVMap.Builder<Object, Object> mp = getGenericMapBuilder(); |
| 547 |
// This is a hack to preserve chunks occupancy rate accounting. |
| 548 |
// It exposes design deficiency flaw in MVStore related to lack of |
| 549 |
// map's type metadata. |
| 550 |
// TODO: Introduce type metadata which will allow to open any store |
| 551 |
// TODO: without prior knowledge of keys / values types and map implementation |
| 552 |
// TODO: (MVMap vs MVRTreeMap, regular vs. singleWriter etc.) |
| 553 |
if (mapName.startsWith(TransactionStore.UNDO_LOG_NAME_PREFIX)) { |
| 554 |
mp.singleWriter(); |
| 555 |
} |
| 556 |
MVMap<Object, Object> sourceMap = source.openMap(mapName, mp); |
| 557 |
MVMap<Object, Object> targetMap = target.openMap(mapName, mp); |
| 558 |
targetMap.copyFrom(sourceMap); |
| 559 |
targetMeta.put(MVMap.getMapKey(targetMap.getId()), sourceMeta.get(MVMap.getMapKey(sourceMap.getId()))); |
| 560 |
} |
| 561 |
// this will end hacky mode of operation with incomplete pages |
| 562 |
// end ensure that all pages are saved |
| 563 |
target.commit(); |
| 564 |
} finally { |
| 565 |
target.setAutoCommitDelay(autoCommitDelay); |
| 566 |
target.setReuseSpace(reuseSpace); |
| 567 |
} |
| 568 |
} |
| 569 |
|
| 570 |
/** |
| 571 |
* Repair a store by rolling back to the newest good version. |
| 572 |
* |
| 573 |
* @param fileName the file name |
| 574 |
*/ |
| 575 |
public static void repair(String fileName) { |
| 576 |
PrintWriter pw = new PrintWriter(System.out); |
| 577 |
long version = Long.MAX_VALUE; |
| 578 |
OutputStream ignore = new OutputStream() { |
| 579 |
@Override |
| 580 |
public void write(int b) { |
| 581 |
// ignore |
| 582 |
} |
| 583 |
}; |
| 584 |
while (version >= 0) { |
| 585 |
pw.println(version == Long.MAX_VALUE ? "Trying latest version" |
| 586 |
: ("Trying version " + version)); |
| 587 |
pw.flush(); |
| 588 |
version = rollback(fileName, version, new PrintWriter(ignore)); |
| 589 |
try { |
| 590 |
String error = info(fileName + ".temp", new PrintWriter(ignore)); |
| 591 |
if (error == null) { |
| 592 |
FilePath.get(fileName).moveTo(FilePath.get(fileName + ".back"), true); |
| 593 |
FilePath.get(fileName + ".temp").moveTo(FilePath.get(fileName), true); |
| 594 |
pw.println("Success"); |
| 595 |
break; |
| 596 |
} |
| 597 |
pw.println(" ... failed: " + error); |
| 598 |
} catch (Exception e) { |
| 599 |
pw.println("Fail: " + e.getMessage()); |
| 600 |
pw.flush(); |
| 601 |
} |
| 602 |
version--; |
| 603 |
} |
| 604 |
pw.flush(); |
| 605 |
} |
| 606 |
|
| 607 |
/** |
| 608 |
* Roll back to a given revision into a file called *.temp. |
| 609 |
* |
| 610 |
* @param fileName the file name |
| 611 |
* @param targetVersion the version to roll back to (Long.MAX_VALUE for the |
| 612 |
* latest version) |
| 613 |
* @param writer the log writer |
| 614 |
* @return the version rolled back to (-1 if no version) |
| 615 |
*/ |
| 616 |
public static long rollback(String fileName, long targetVersion, Writer writer) { |
| 617 |
long newestVersion = -1; |
| 618 |
PrintWriter pw = new PrintWriter(writer, true); |
| 619 |
if (!FilePath.get(fileName).exists()) { |
| 620 |
pw.println("File not found: " + fileName); |
| 621 |
return newestVersion; |
| 622 |
} |
| 623 |
FileChannel file = null; |
| 624 |
FileChannel target = null; |
| 625 |
int blockSize = FileStore.BLOCK_SIZE; |
| 626 |
try { |
| 627 |
file = FilePath.get(fileName).open("r"); |
| 628 |
FilePath.get(fileName + ".temp").delete(); |
| 629 |
target = FilePath.get(fileName + ".temp").open("rw"); |
| 630 |
long fileSize = file.size(); |
| 631 |
ByteBuffer buffer = ByteBuffer.allocate(4096); |
| 632 |
Chunk newestChunk = null; |
| 633 |
for (long pos = 0; pos < fileSize;) { |
| 634 |
buffer.rewind(); |
| 635 |
DataUtils.readFully(file, pos, buffer); |
| 636 |
buffer.rewind(); |
| 637 |
int headerType = buffer.get(); |
| 638 |
if (headerType == 'H') { |
| 639 |
buffer.rewind(); |
| 640 |
target.write(buffer, pos); |
| 641 |
pos += blockSize; |
| 642 |
continue; |
| 643 |
} |
| 644 |
if (headerType != 'c') { |
| 645 |
pos += blockSize; |
| 646 |
continue; |
| 647 |
} |
| 648 |
Chunk c; |
| 649 |
try { |
| 650 |
c = new SFChunk(Chunk.readChunkHeader(buffer)); |
| 651 |
} catch (MVStoreException e) { |
| 652 |
pos += blockSize; |
| 653 |
continue; |
| 654 |
} |
| 655 |
if (c.len <= 0) { |
| 656 |
// not a chunk |
| 657 |
pos += blockSize; |
| 658 |
continue; |
| 659 |
} |
| 660 |
int length = c.len * FileStore.BLOCK_SIZE; |
| 661 |
ByteBuffer chunk = ByteBuffer.allocate(length); |
| 662 |
DataUtils.readFully(file, pos, chunk); |
| 663 |
if (c.version > targetVersion) { |
| 664 |
// newer than the requested version |
| 665 |
pos += length; |
| 666 |
continue; |
| 667 |
} |
| 668 |
chunk.rewind(); |
| 669 |
target.write(chunk, pos); |
| 670 |
if (newestChunk == null || c.version > newestChunk.version) { |
| 671 |
newestChunk = c; |
| 672 |
newestVersion = c.version; |
| 673 |
} |
| 674 |
pos += length; |
| 675 |
} |
| 676 |
int length = newestChunk.len * FileStore.BLOCK_SIZE; |
| 677 |
ByteBuffer chunk = ByteBuffer.allocate(length); |
| 678 |
DataUtils.readFully(file, newestChunk.block * FileStore.BLOCK_SIZE, chunk); |
| 679 |
chunk.rewind(); |
| 680 |
target.write(chunk, fileSize); |
| 681 |
} catch (IOException e) { |
| 682 |
pw.println("ERROR: " + e); |
| 683 |
e.printStackTrace(pw); |
| 684 |
} finally { |
| 685 |
if (file != null) { |
| 686 |
try { |
| 687 |
file.close(); |
| 688 |
} catch (IOException e) { |
| 689 |
// ignore |
| 690 |
} |
| 691 |
} |
| 692 |
if (target != null) { |
| 693 |
try { |
| 694 |
target.close(); |
| 695 |
} catch (IOException e) { |
| 696 |
// ignore |
| 697 |
} |
| 698 |
} |
| 699 |
} |
| 700 |
pw.flush(); |
| 701 |
return newestVersion; |
| 702 |
} |
| 703 |
|
| 704 |
@SuppressWarnings({"rawtypes","unchecked"}) |
| 705 |
static MVMap.Builder<Object,Object> getGenericMapBuilder() { |
| 706 |
return (MVMap.Builder)new MVMap.Builder<byte[],byte[]>(). |
| 707 |
keyType(GenericDataType.INSTANCE). |
| 708 |
valueType(GenericDataType.INSTANCE); |
| 709 |
} |
| 710 |
|
| 711 |
/** |
| 712 |
* A data type that can read any data that is persisted, and converts it to |
| 713 |
* a byte array. |
| 714 |
*/ |
| 715 |
private static class GenericDataType extends BasicDataType<byte[]> { |
| 716 |
static GenericDataType INSTANCE = new GenericDataType(); |
| 717 |
|
| 718 |
private GenericDataType() {} |
| 719 |
|
| 720 |
@Override |
| 721 |
public boolean isMemoryEstimationAllowed() { |
| 722 |
return false; |
| 723 |
} |
| 724 |
|
| 725 |
@Override |
| 726 |
public int getMemory(byte[] obj) { |
| 727 |
return obj == null ? 0 : obj.length * 8; |
| 728 |
} |
| 729 |
|
| 730 |
@Override |
| 731 |
public byte[][] createStorage(int size) { |
| 732 |
return new byte[size][]; |
| 733 |
} |
| 734 |
|
| 735 |
@Override |
| 736 |
public void write(WriteBuffer buff, byte[] obj) { |
| 737 |
if (obj != null) { |
| 738 |
buff.put(obj); |
| 739 |
} |
| 740 |
} |
| 741 |
|
| 742 |
@Override |
| 743 |
public byte[] read(ByteBuffer buff) { |
| 744 |
int len = buff.remaining(); |
| 745 |
if (len == 0) { |
| 746 |
return null; |
| 747 |
} |
| 748 |
byte[] data = new byte[len]; |
| 749 |
buff.get(data); |
| 750 |
return data; |
| 751 |
} |
| 752 |
} |
| 753 |
} |