Debian Codegraph @

src/tools/org/h2/dev/fs/ArchiveToolStore.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.dev.fs;
7
8 import java.io.BufferedOutputStream;
9 import java.io.FileOutputStream;
10 import java.io.OutputStream;
11 import java.nio.ByteBuffer;
12 import java.nio.channels.FileChannel;
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.Map.Entry;
16 import java.util.Random;
17 import java.util.concurrent.TimeUnit;
18
19 import org.h2.mvstore.Cursor;
20 import org.h2.mvstore.DataUtils;
21 import org.h2.mvstore.MVMap;
22 import org.h2.mvstore.MVStore;
23 import org.h2.store.fs.FileUtils;
24
25 /**
26 * An archive tool to compress directories, using the MVStore backend.
27 */
28 public class ArchiveToolStore {
29
30 private static final int[] RANDOM = new int[256];
31 private static final int MB = 1000 * 1000;
32 private long lastTime;
33 private long start;
34 private int bucket;
35 private String fileName;
36
37 static {
38 Random r = new Random(1);
39 for (int i = 0; i < RANDOM.length; i++) {
40 RANDOM[i] = r.nextInt();
41 }
42 }
43
44 /**
45 * Run the tool.
46 *
47 * @param args the command line arguments
48 */
49 public static void main(String... args) throws Exception {
50 ArchiveToolStore app = new ArchiveToolStore();
51 String arg = args.length != 3 ? null : args[0];
52 if ("-compress".equals(arg)) {
53 app.fileName = args[1];
54 app.compress(args[2]);
55 } else if ("-extract".equals(arg)) {
56 app.fileName = args[1];
57 app.expand(args[2]);
58 } else {
59 System.out.println("Command line options:");
60 System.out.println("-compress <file> <sourceDir>");
61 System.out.println("-extract <file> <targetDir>");
62 }
63 }
64
65 private void compress(String sourceDir) throws Exception {
66 start();
67 long tempSize = 8 * 1024 * 1024;
68 String tempFileName = fileName + ".temp";
69 ArrayList<String> fileNames = new ArrayList<>();
70
71 System.out.println("Reading the file list");
72 long totalSize = addFiles(sourceDir, fileNames);
73 System.out.println("Compressing " + totalSize / MB + " MB");
74
75 FileUtils.delete(tempFileName);
76 FileUtils.delete(fileName);
77 MVStore storeTemp = new MVStore.Builder().
78 fileName(tempFileName).
79 autoCommitDisabled().
80 open();
81 final MVStore store = new MVStore.Builder().
82 fileName(fileName).
83 pageSplitSize(2 * 1024 * 1024).
84 compressHigh().
85 autoCommitDisabled().
86 open();
87 MVMap<String, int[]> filesTemp = storeTemp.openMap("files");
88 long currentSize = 0;
89 int segmentId = 1;
90 int segmentLength = 0;
91 ByteBuffer buff = ByteBuffer.allocate(1024 * 1024);
92 for (String s : fileNames) {
93 String name = s.substring(sourceDir.length() + 1);
94 if (FileUtils.isDirectory(s)) {
95 // directory
96 filesTemp.put(name, new int[1]);
97 continue;
98 }
99 buff.clear();
100 buff.flip();
101 ArrayList<Integer> posList = new ArrayList<>();
102 try (FileChannel fc = FileUtils.open(s, "r")) {
103 boolean eof = false;
104 while (true) {
105 while (!eof && buff.remaining() < 512 * 1024) {
106 int remaining = buff.remaining();
107 buff.compact();
108 buff.position(remaining);
109 int l = fc.read(buff);
110 if (l < 0) {
111 eof = true;
112 }
113 buff.flip();
114 }
115 if (buff.remaining() == 0) {
116 break;
117 }
118 int position = buff.position();
119 int c = getChunkLength(buff.array(), position,
120 buff.limit()) - position;
121 byte[] bytes = Arrays.copyOfRange(buff.array(), position, position + c);
122 buff.position(position + c);
123 int[] key = getKey(bucket, bytes);
124 key[3] = segmentId;
125 while (true) {
126 MVMap<int[], byte[]> data = storeTemp.
127 openMap("data" + segmentId);
128 byte[] old = data.get(key);
129 if (old == null) {
130 // new
131 data.put(key, bytes);
132 break;
133 }
134 if (Arrays.equals(old, bytes)) {
135 // duplicate
136 break;
137 }
138 // same checksum: change checksum
139 key[2]++;
140 }
141 for (int i = 0; i < key.length; i++) {
142 posList.add(key[i]);
143 }
144 segmentLength += c;
145 currentSize += c;
146 if (segmentLength > tempSize) {
147 storeTemp.commit();
148 segmentId++;
149 segmentLength = 0;
150 }
151 printProgress(0, 50, currentSize, totalSize);
152 }
153 }
154 int[] posArray = new int[posList.size()];
155 for (int i = 0; i < posList.size(); i++) {
156 posArray[i] = posList.get(i);
157 }
158 filesTemp.put(name, posArray);
159 }
160 storeTemp.commit();
161 ArrayList<Cursor<int[], byte[]>> list = new ArrayList<>(segmentId-1);
162 totalSize = 0;
163 for (int i = 1; i <= segmentId; i++) {
164 MVMap<int[], byte[]> data = storeTemp.openMap("data" + i);
165 totalSize += data.sizeAsLong();
166 Cursor<int[], byte[]> c = data.cursor(null);
167 if (c.hasNext()) {
168 c.next();
169 list.add(c);
170 }
171 }
172 segmentId = 1;
173 segmentLength = 0;
174 currentSize = 0;
175 MVMap<int[], byte[]> data = store.openMap("data" + segmentId);
176 MVMap<int[], Boolean> keepSegment = storeTemp.openMap("keep");
177 while (list.size() > 0) {
178 list.sort((o1, o2) -> {
179 int[] k1 = o1.getKey();
180 int[] k2 = o2.getKey();
181 int comp = 0;
182 for (int i = 0; i < k1.length - 1; i++) {
183 long x1 = k1[i];
184 long x2 = k2[i];
185 if (x1 > x2) {
186 comp = 1;
187 break;
188 } else if (x1 < x2) {
189 comp = -1;
190 break;
191 }
192 }
193 return comp;
194 });
195 Cursor<int[], byte[]> top = list.get(0);
196 int[] key = top.getKey();
197 byte[] bytes = top.getValue();
198 int[] k2 = Arrays.copyOf(key, key.length);
199 k2[key.length - 1] = 0;
200 // TODO this lookup can be avoided
201 // if we remember the last entry with k[..] = 0
202 byte[] old = data.get(k2);
203 if (old == null) {
204 if (segmentLength > tempSize) {
205 // switch only for new entries
206 // where segmentId is 0,
207 // so that entries with the same
208 // key but different segmentId
209 // are in the same segment
210 store.commit();
211 segmentLength = 0;
212 segmentId++;
213 data = store.openMap("data" + segmentId);
214 }
215 key = k2;
216 // new entry
217 data.put(key, bytes);
218 segmentLength += bytes.length;
219 } else if (Arrays.equals(old, bytes)) {
220 // duplicate
221 } else {
222 // almost a duplicate:
223 // keep segment id
224 keepSegment.put(key, Boolean.TRUE);
225 data.put(key, bytes);
226 segmentLength += bytes.length;
227 }
228 if (!top.hasNext()) {
229 list.remove(0);
230 } else {
231 top.next();
232 }
233 currentSize++;
234 printProgress(50, 100, currentSize, totalSize);
235 }
236 MVMap<String, int[]> files = store.openMap("files");
237 for (Entry<String, int[]> e : filesTemp.entrySet()) {
238 String k = e.getKey();
239 int[] ids = e.getValue();
240 if (ids.length == 1) {
241 // directory
242 files.put(k, ids);
243 continue;
244 }
245 int[] newIds = Arrays.copyOf(ids, ids.length);
246 for (int i = 0; i < ids.length; i += 4) {
247 int[] id = new int[4];
248 id[0] = ids[i];
249 id[1] = ids[i + 1];
250 id[2] = ids[i + 2];
251 id[3] = ids[i + 3];
252 if (!keepSegment.containsKey(id)) {
253 newIds[i + 3] = 0;
254 }
255 }
256 files.put(k, newIds);
257 }
258 store.commit();
259 storeTemp.close();
260 FileUtils.delete(tempFileName);
261 store.close();
262 System.out.println();
263 System.out.println("Compressed to " +
264 FileUtils.size(fileName) / MB + " MB");
265 printDone();
266 }
267
268 private void start() {
269 this.start = System.nanoTime();
270 this.lastTime = start;
271 }
272
273 private void printProgress(int low, int high, long current, long total) {
274 long now = System.nanoTime();
275 if (now - lastTime > TimeUnit.SECONDS.toNanos(5)) {
276 System.out.print((low + (high - low) * current / total) + "% ");
277 lastTime = now;
278 }
279 }
280
281 private void printDone() {
282 System.out.println("Done in " +
283 TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) +
284 " seconds");
285 }
286
287 private static long addFiles(String dir, ArrayList<String> list) {
288 long size = 0;
289 for (String s : FileUtils.newDirectoryStream(dir)) {
290 if (FileUtils.isDirectory(s)) {
291 size += addFiles(s, list);
292 } else {
293 size += FileUtils.size(s);
294 }
295 list.add(s);
296 }
297 return size;
298 }
299
300 private void expand(String targetDir) throws Exception {
301 start();
302 long tempSize = 8 * 1024 * 1024;
303 String tempFileName = fileName + ".temp";
304 FileUtils.createDirectories(targetDir);
305 MVStore store = new MVStore.Builder().
306 fileName(fileName).open();
307 MVMap<String, int[]> files = store.openMap("files");
308 System.out.println("Extracting " + files.size() + " files");
309 MVStore storeTemp = null;
310 FileUtils.delete(tempFileName);
311 long totalSize = 0;
312 int lastSegment = 0;
313 for (int i = 1;; i++) {
314 if (!store.hasMap("data" + i)) {
315 lastSegment = i - 1;
316 break;
317 }
318 }
319
320 storeTemp = new MVStore.Builder().
321 fileName(tempFileName).
322 autoCommitDisabled().
323 open();
324
325 MVMap<Integer, String> fileNames = storeTemp.openMap("fileNames");
326
327 MVMap<String, int[]> filesTemp = storeTemp.openMap("files");
328 int fileId = 0;
329 for (Entry<String, int[]> e : files.entrySet()) {
330 fileNames.put(fileId++, e.getKey());
331 filesTemp.put(e.getKey(), e.getValue());
332 totalSize += e.getValue().length / 4;
333 }
334 storeTemp.commit();
335
336 files = filesTemp;
337 long currentSize = 0;
338 int chunkSize = 0;
339 for (int s = 1; s <= lastSegment; s++) {
340 MVMap<int[], byte[]> segmentData = store.openMap("data" + s);
341 // key: fileId, blockId; value: data
342 MVMap<int[], byte[]> fileData = storeTemp.openMap("fileData" + s);
343 fileId = 0;
344 for (Entry<String, int[]> e : files.entrySet()) {
345 int[] keys = e.getValue();
346 if (keys.length == 1) {
347 fileId++;
348 continue;
349 }
350 for (int i = 0; i < keys.length; i += 4) {
351 int[] dk = new int[4];
352 dk[0] = keys[i];
353 dk[1] = keys[i + 1];
354 dk[2] = keys[i + 2];
355 dk[3] = keys[i + 3];
356 byte[] bytes = segmentData.get(dk);
357 if (bytes != null) {
358 int[] k = new int[] { fileId, i / 4 };
359 fileData.put(k, bytes);
360 chunkSize += bytes.length;
361 if (chunkSize > tempSize) {
362 storeTemp.commit();
363 chunkSize = 0;
364 }
365 currentSize++;
366 printProgress(0, 50, currentSize, totalSize);
367 }
368 }
369 fileId++;
370 }
371 storeTemp.commit();
372 }
373
374 ArrayList<Cursor<int[], byte[]>> list = new ArrayList<>(lastSegment-1);
375 totalSize = 0;
376 currentSize = 0;
377 for (int i = 1; i <= lastSegment; i++) {
378 MVMap<int[], byte[]> fileData = storeTemp.openMap("fileData" + i);
379 totalSize += fileData.sizeAsLong();
380 Cursor<int[], byte[]> c = fileData.cursor(null);
381 if (c.hasNext()) {
382 c.next();
383 list.add(c);
384 }
385 }
386 String lastFileName = null;
387 OutputStream file = null;
388 int[] lastKey = null;
389 while (list.size() > 0) {
390 list.sort((o1, o2) -> {
391 int[] k1 = o1.getKey();
392 int[] k2 = o2.getKey();
393 int comp = 0;
394 for (int i = 0; i < k1.length; i++) {
395 long x1 = k1[i];
396 long x2 = k2[i];
397 if (x1 > x2) {
398 comp = 1;
399 break;
400 } else if (x1 < x2) {
401 comp = -1;
402 break;
403 }
404 }
405 return comp;
406 });
407 Cursor<int[], byte[]> top = list.get(0);
408 int[] key = top.getKey();
409 byte[] bytes = top.getValue();
410 String f = targetDir + "/" + fileNames.get(key[0]);
411 if (!f.equals(lastFileName)) {
412 if (file != null) {
413 file.close();
414 }
415 String p = FileUtils.getParent(f);
416 if (p != null) {
417 FileUtils.createDirectories(p);
418 }
419 file = new BufferedOutputStream(new FileOutputStream(f));
420 lastFileName = f;
421 } else {
422 if (key[0] != lastKey[0] || key[1] != lastKey[1] + 1) {
423 System.out.println("missing entry after " + Arrays.toString(lastKey));
424 }
425 }
426 lastKey = key;
427 file.write(bytes);
428 if (!top.hasNext()) {
429 list.remove(0);
430 } else {
431 top.next();
432 }
433 currentSize++;
434 printProgress(50, 100, currentSize, totalSize);
435 }
436 for (Entry<String, int[]> e : files.entrySet()) {
437 String f = targetDir + "/" + e.getKey();
438 int[] keys = e.getValue();
439 if (keys.length == 1) {
440 FileUtils.createDirectories(f);
441 } else if (keys.length == 0) {
442 // empty file
443 String p = FileUtils.getParent(f);
444 if (p != null) {
445 FileUtils.createDirectories(p);
446 }
447 new FileOutputStream(f).close();
448 }
449 }
450 if (file != null) {
451 file.close();
452 }
453 store.close();
454
455 storeTemp.close();
456 FileUtils.delete(tempFileName);
457
458 System.out.println();
459 printDone();
460 }
461
462 private int getChunkLength(byte[] data, int start, int maxPos) {
463 int minLen = 4 * 1024;
464 int mask = 4 * 1024 - 1;
465 int factor = 31;
466 int hash = 0, mul = 1, offset = 8;
467 int min = Integer.MAX_VALUE;
468 int max = Integer.MIN_VALUE;
469 int i = start;
470 int[] rand = RANDOM;
471 for (int j = 0; i < maxPos; i++, j++) {
472 hash = hash * factor + rand[data[i] & 255];
473 if (j >= offset) {
474 hash -= mul * rand[data[i - offset] & 255];
475 } else {
476 mul *= factor;
477 }
478 if (hash < min) {
479 min = hash;
480 }
481 if (hash > max) {
482 max = hash;
483 }
484 if (j > minLen) {
485 if (j > minLen * 4) {
486 break;
487 }
488 if ((hash & mask) == 1) {
489 break;
490 }
491 }
492 }
493 bucket = min;
494 return i;
495 }
496
497 private static int[] getKey(int bucket, byte[] buff) {
498 int[] key = new int[4];
499 int[] counts = new int[8];
500 int len = buff.length;
501 for (int i = 0; i < len; i++) {
502 int x = buff[i] & 0xff;
503 counts[x >> 5]++;
504 }
505 int cs = 0;
506 for (int i = 0; i < 8; i++) {
507 cs *= 2;
508 if (counts[i] > (len / 32)) {
509 cs += 1;
510 }
511 }
512 key[0] = cs;
513 key[1] = bucket;
514 key[2] = DataUtils.getFletcher32(buff, 0, buff.length);
515 return key;
516 }
517
518 }