Add BackupHooks and ParallelZip for Build 42.21. Implement optimized backup file creation with parallel processing. Include hooks, utilities, and unit tests for validation.
ci / image (42, public) (push) Successful in 3m38s
ci / image (42, public) (push) Successful in 3m38s
This commit is contained in:
1 parent
7ffcbdbb06
commit
07dc3f0fad
9 files changed
+1153
-5
No files matched your search
+114
@@ -0,0 +1,114 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import dev.overlord.zomboidforge.compat.b42.util.ParallelZip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import zombie.ZomboidFileSystem;
|
||||
import zombie.core.backup.ZipBackup;
|
||||
import zombie.debug.DebugLog;
|
||||
import zombie.debug.DebugType;
|
||||
import zombie.debug.LogSeverity;
|
||||
import zombie.iso.IsoChunk;
|
||||
import zombie.network.CoopSlave;
|
||||
|
||||
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
|
||||
@SuppressWarnings("unused")
|
||||
public final class BackupHooks
|
||||
{
|
||||
/** {@code ZipBackup.rotateBackupFile(BackupTypes)}, private, taking the enum as {@code Object}. */
|
||||
private static final MethodHandle ROTATE;
|
||||
/** {@code ZipBackup.getBackupReadme(String)}, private. */
|
||||
private static final MethodHandle README;
|
||||
|
||||
/** The files of the cache folder that vanilla adds, each when it exists. */
|
||||
private static final String[] FILES = {
|
||||
"options.ini", "popman-options.ini", "latestSave.ini", "debug-options.ini", "sounds.ini", "gamepadBinding.config"
|
||||
};
|
||||
|
||||
/** The folders of the cache folder whose top-level files vanilla adds. */
|
||||
private static final String[] TOP_LEVEL_FOLDERS = { "mods", "Lua", "db", "Server" };
|
||||
|
||||
static
|
||||
{
|
||||
try
|
||||
{
|
||||
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(ZipBackup.class, MethodHandles.lookup());
|
||||
Class<?> types = Class.forName("zombie.core.backup.ZipBackup$BackupTypes");
|
||||
|
||||
ROTATE = lookup.findStatic(ZipBackup.class, "rotateBackupFile", MethodType.methodType(void.class, types))
|
||||
.asType(MethodType.methodType(void.class, Object.class));
|
||||
README = lookup.findStatic(ZipBackup.class, "getBackupReadme", MethodType.methodType(String.class, String.class));
|
||||
}
|
||||
catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
|
||||
}
|
||||
|
||||
private BackupHooks() {}
|
||||
|
||||
/**
|
||||
* Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)}; {@code type} is
|
||||
* the {@code BackupTypes} constant, a private enum. Writes the same entries into
|
||||
* {@code backups/<type>/backup_1.zip} as vanilla, after the same rotation: {@code readme.txt},
|
||||
* the files of {@link #FILES}, the top-level files of {@link #TOP_LEVEL_FOLDERS} (vanilla's
|
||||
* {@code zipDir(String, String)} skips every subfolder), and the save folder without the
|
||||
* folders named {@code blam}, read under {@code IsoChunk.WriteLock}. {@link ParallelZip}
|
||||
* writes them in one pass instead of vanilla's three. As vanilla, the backup logs its
|
||||
* failures and does not throw.
|
||||
*/
|
||||
public static void makeBackupFile(String serverName, Object type)
|
||||
{
|
||||
String backupDir = ZomboidFileSystem.instance.getCacheDir() + File.separator + "backups" + File.separator + ((Enum<?>) type).name();
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
DebugType.General.println("Start making backup");
|
||||
DebugType.DetailedInfo.println("backup dir: " + backupDir);
|
||||
CoopSlave.status("UI_ServerStatus_CreateBackup");
|
||||
|
||||
try
|
||||
{
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
new File(backupDir).mkdirs();
|
||||
BackupHooks.ROTATE.invokeExact(type);
|
||||
|
||||
Path zipFile = Paths.get(backupDir + File.separator + "backup_1.zip");
|
||||
try { Files.deleteIfExists(zipFile); }
|
||||
catch (IOException e) { DebugType.General.printException(e, LogSeverity.Error); }
|
||||
|
||||
String readme = (String) BackupHooks.README.invokeExact(serverName);
|
||||
String saveDir = "Saves" + File.separator + "Multiplayer" + File.separator + serverName;
|
||||
int threads = Runtime.getRuntime().availableProcessors();
|
||||
|
||||
try (ParallelZip zip = new ParallelZip(zipFile, readme, threads, e -> DebugType.General.printException(e, LogSeverity.Error)))
|
||||
{
|
||||
zip.addText("readme.txt", readme);
|
||||
|
||||
for (String name : BackupHooks.FILES)
|
||||
{
|
||||
Path file = Paths.get(ZomboidFileSystem.instance.getCacheDir() + File.separator + name);
|
||||
if (Files.exists(file)) zip.addFile(name, file);
|
||||
}
|
||||
|
||||
for (String folder : BackupHooks.TOP_LEVEL_FOLDERS) zip.addFolder(folder, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(folder)), subfolder -> false);
|
||||
|
||||
synchronized (IsoChunk.WriteLock)
|
||||
{
|
||||
zip.addFolder(saveDir, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(saveDir)), subfolder -> !subfolder.endsWith("blam"));
|
||||
}
|
||||
|
||||
zip.finish();
|
||||
}
|
||||
}
|
||||
// As vanilla's catch of Exception: errors pass; invokeExact declares Throwable.
|
||||
catch (Error e) { throw e; }
|
||||
catch (Throwable t) { DebugType.General.printException(t, LogSeverity.Error); }
|
||||
|
||||
DebugLog.log("Backup made in " + (System.currentTimeMillis() - startTime) + " ms");
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.Zip64Mode;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.NonReadableChannelException;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryIteratorException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
/**
|
||||
* A zip file of uncompressed (STORED) entries, Zip64 as needed, as {@code ZipBackup} writes,
|
||||
* written in one pass from files that a thread pool reads in parallel.
|
||||
*
|
||||
* <p>{@code ZipBackup.makeBackupFile} hands every file to {@code ParallelScatterZipCreator}, whose
|
||||
* threads copy the files into one temporary file per thread, which it then copies into the zip:
|
||||
* every byte is written three times. Here reader threads list the folders and read each file
|
||||
* with its CRC into memory, and the thread that adds a folder writes the files as entries with
|
||||
* size and CRC known: each byte is written once, each header once. Files of more than
|
||||
* {@value #LARGE} bytes are not held in memory: the writing thread copies them and patches size
|
||||
* and CRC into the entry's header afterwards. Read files waiting to be written hold at most
|
||||
* {@value #BUDGET} bytes.
|
||||
*
|
||||
* <p>Entries appear in the order their files were read, which varies between runs, as with
|
||||
* {@code ParallelScatterZipCreator}. The file is a valid zip only after {@link #finish()}.
|
||||
*/
|
||||
public final class ParallelZip implements Closeable
|
||||
{
|
||||
/** Files larger than this are copied by the writing thread instead of read into memory. */
|
||||
private static final int LARGE = 4 << 20;
|
||||
/** Bytes of read files that wait for the writing thread, at most. */
|
||||
private static final int BUDGET = 64 << 20;
|
||||
/** Write buffer of the zip file. */
|
||||
private static final int BUFFER = 1 << 20;
|
||||
|
||||
private static final AtomicInteger THREADS = new AtomicInteger();
|
||||
|
||||
/** A file read with its CRC; {@code permits} of the budget are released once it is written. */
|
||||
private record Loaded(String name, byte[] data, long crc, int permits) implements Item {}
|
||||
|
||||
/** A file the writing thread copies itself; {@code size} as listed. */
|
||||
private record Large(String name, Path file, long size) implements Item {}
|
||||
|
||||
/** An unexpected failure of a reader thread. */
|
||||
private record Failed(Throwable cause) implements Item {}
|
||||
|
||||
/** Every folder of the current {@link #addFolder} is read. */
|
||||
private record Done() implements Item {}
|
||||
|
||||
private sealed interface Item permits Loaded, Large, Failed, Done {}
|
||||
|
||||
private final BufferedChannel channel;
|
||||
private final ZipArchiveOutputStream zip;
|
||||
private final ExecutorService readers;
|
||||
private final Consumer<IOException> failures;
|
||||
private final Semaphore budget = new Semaphore(ParallelZip.BUDGET);
|
||||
private boolean finished;
|
||||
|
||||
/**
|
||||
* Creates or truncates {@code file}, with {@code threads} reader threads. Files and folders
|
||||
* that cannot be read are passed to {@code failures}, from any of these threads, and left out.
|
||||
*/
|
||||
public ParallelZip(Path file, String comment, int threads, Consumer<IOException> failures) throws IOException
|
||||
{
|
||||
this.channel = new BufferedChannel(FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
|
||||
this.zip = new ZipArchiveOutputStream(this.channel);
|
||||
this.failures = failures;
|
||||
this.readers = Executors.newFixedThreadPool(threads, task -> {
|
||||
Thread thread = new Thread(task, "zf-backup-reader-" + ParallelZip.THREADS.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
this.zip.setUseZip64(Zip64Mode.AsNeeded);
|
||||
this.zip.setMethod(ZipArchiveEntry.STORED);
|
||||
this.zip.setComment(comment);
|
||||
}
|
||||
|
||||
/** Adds the entry {@code name} with the UTF-8 bytes of {@code text}. */
|
||||
public void addText(String name, String text) throws IOException
|
||||
{
|
||||
byte[] data = text.getBytes(StandardCharsets.UTF_8);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(data);
|
||||
|
||||
this.write(new Loaded(name, data, crc.getValue(), 0));
|
||||
}
|
||||
|
||||
/** Adds the entry {@code name} with the content of {@code file}, on the calling thread. */
|
||||
public void addFile(String name, Path file) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
Item item = this.read(name, file, Files.readAttributes(file, BasicFileAttributes.class));
|
||||
if (item != null) this.write(item);
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
throw new InterruptedIOException("Interrupted while adding '" + file + "'.");
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds every file in {@code folder} as the entry {@code prefix/<path relative to folder>}, and
|
||||
* the files of each subfolder for which {@code descend} holds, recursively; as
|
||||
* {@code ZipBackup.zipDir}, links are not followed into folders, and a link to a file is
|
||||
* added with the file's content. Returns once every entry is written; nothing when
|
||||
* {@code folder} is no folder.
|
||||
*/
|
||||
@SuppressWarnings("DeconstructionCanBeUsed")
|
||||
public void addFolder(String prefix, Path folder, Predicate<Path> descend) throws IOException
|
||||
{
|
||||
if (!Files.isDirectory(folder)) return;
|
||||
|
||||
BlockingQueue<Item> ready = new LinkedBlockingQueue<>();
|
||||
AtomicInteger pending = new AtomicInteger(1);
|
||||
|
||||
this.readers.execute(() -> this.readFolder(prefix, folder, folder, descend, ready, pending));
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Item item = ready.take();
|
||||
|
||||
if (item instanceof Done) return;
|
||||
if (item instanceof Failed failed) throw new IOException("Reading '" + folder + "' failed.", failed.cause());
|
||||
|
||||
this.write(item);
|
||||
}
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
throw new InterruptedIOException("Interrupted while adding '" + folder + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the central directory: the file is a complete zip. */
|
||||
public void finish() throws IOException
|
||||
{
|
||||
this.zip.finish();
|
||||
this.finished = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the reader threads and closes the file; without {@link #finish()} the file has no
|
||||
* central directory, so no tool takes it for a complete backup.
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
this.readers.shutdownNow();
|
||||
|
||||
if (this.finished) this.zip.close();
|
||||
else this.channel.close();
|
||||
}
|
||||
|
||||
/** On a reader thread: lists {@code folder}, queues its files, and starts a task per subfolder to descend into. */
|
||||
private void readFolder(String prefix, Path root, Path folder, Predicate<Path> descend, BlockingQueue<Item> ready, AtomicInteger pending)
|
||||
{
|
||||
try (DirectoryStream<Path> entries = Files.newDirectoryStream(folder))
|
||||
{
|
||||
for (Path entry : entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
BasicFileAttributes attributes = Files.readAttributes(entry, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
|
||||
if (attributes.isDirectory())
|
||||
{
|
||||
if (!descend.test(entry)) continue;
|
||||
|
||||
pending.incrementAndGet();
|
||||
this.readers.execute(() -> this.readFolder(prefix, root, entry, descend, ready, pending));
|
||||
continue;
|
||||
}
|
||||
|
||||
String name = prefix + File.separator + root.relativize(entry).toString().replace("/", File.separator);
|
||||
Item item = this.read(name, entry, attributes);
|
||||
if (item != null) ready.add(item);
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
}
|
||||
}
|
||||
catch (IOException e) { this.failures.accept(e); }
|
||||
catch (DirectoryIteratorException e) { this.failures.accept(e.getCause()); }
|
||||
// Interrupted by close(), or an unexpected failure: addFolder throws.
|
||||
catch (Throwable t) { ready.add(new Failed(t)); }
|
||||
finally { if (pending.decrementAndGet() == 0) ready.add(new Done()); }
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code file} as an item to write: read with its CRC, or, when large, to be copied by the
|
||||
* writing thread. {@code null} for files that cannot be read (sockets and the like).
|
||||
*/
|
||||
private @Nullable Item read(String name, Path file, BasicFileAttributes attributes) throws IOException, InterruptedException
|
||||
{
|
||||
if (attributes.isOther()) return null;
|
||||
|
||||
// A link: the size of the file it points to.
|
||||
long size = attributes.isSymbolicLink() ? Files.size(file) : attributes.size();
|
||||
if (size > ParallelZip.LARGE) return new Large(name, file, size);
|
||||
|
||||
int permits = (int) size;
|
||||
this.budget.acquire(permits);
|
||||
|
||||
try
|
||||
{
|
||||
byte[] data = Files.readAllBytes(file);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(data);
|
||||
|
||||
return new Loaded(name, data, crc.getValue(), permits);
|
||||
}
|
||||
catch (IOException | RuntimeException | Error e)
|
||||
{
|
||||
this.budget.release(permits);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Item item) throws IOException
|
||||
{
|
||||
switch (item)
|
||||
{
|
||||
case Loaded loaded ->
|
||||
{
|
||||
ZipArchiveEntry entry = new ZipArchiveEntry(loaded.name());
|
||||
entry.setMethod(ZipArchiveEntry.STORED);
|
||||
entry.setSize(loaded.data().length);
|
||||
entry.setCompressedSize(loaded.data().length);
|
||||
entry.setCrc(loaded.crc());
|
||||
|
||||
// Size and CRC known: written once, no header rewrite.
|
||||
this.zip.addRawArchiveEntry(entry, new ByteArrayInputStream(loaded.data()));
|
||||
this.budget.release(loaded.permits());
|
||||
}
|
||||
case Large large ->
|
||||
{
|
||||
InputStream input;
|
||||
try { input = Files.newInputStream(large.file()); }
|
||||
catch (IOException e) { this.failures.accept(e); return; }
|
||||
|
||||
// The listed size keeps the header free of Zip64 fields below 4 GiB; the zip
|
||||
// stream then writes the copied size and CRC into the header.
|
||||
ZipArchiveEntry entry = new ZipArchiveEntry(large.name());
|
||||
entry.setMethod(ZipArchiveEntry.STORED);
|
||||
entry.setSize(large.size());
|
||||
|
||||
try (input)
|
||||
{
|
||||
this.zip.putArchiveEntry(entry);
|
||||
input.transferTo(this.zip);
|
||||
this.zip.closeArchiveEntry();
|
||||
}
|
||||
}
|
||||
case Failed failed -> throw new IOException(failed.cause());
|
||||
case Done done -> throw new IllegalStateException("'Done' is no entry.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link FileChannel} with a write buffer: the zip stream writes headers and data in small
|
||||
* pieces. Moving the position writes the buffer first, so patched headers land where the
|
||||
* zip stream puts them.
|
||||
*/
|
||||
private static final class BufferedChannel implements SeekableByteChannel
|
||||
{
|
||||
private final FileChannel channel;
|
||||
private final ByteBuffer buffer = ByteBuffer.allocate(ParallelZip.BUFFER);
|
||||
|
||||
BufferedChannel(FileChannel channel) { this.channel = channel; }
|
||||
|
||||
@Override
|
||||
public int write(ByteBuffer source) throws IOException
|
||||
{
|
||||
int length = source.remaining();
|
||||
|
||||
if (length > this.buffer.remaining()) this.flush();
|
||||
|
||||
if (length >= this.buffer.capacity())
|
||||
{
|
||||
while (source.hasRemaining()) this.channel.write(source);
|
||||
}
|
||||
else this.buffer.put(source);
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long position() throws IOException { return this.channel.position() + this.buffer.position(); }
|
||||
|
||||
@Override
|
||||
public SeekableByteChannel position(long position) throws IOException
|
||||
{
|
||||
this.flush();
|
||||
this.channel.position(position);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long size() throws IOException
|
||||
{
|
||||
this.flush();
|
||||
|
||||
return this.channel.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SeekableByteChannel truncate(long size) throws IOException
|
||||
{
|
||||
this.flush();
|
||||
this.channel.truncate(size);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(ByteBuffer target) { throw new NonReadableChannelException(); }
|
||||
|
||||
@Override
|
||||
public boolean isOpen() { return this.channel.isOpen(); }
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
try { this.flush(); }
|
||||
finally { this.channel.close(); }
|
||||
}
|
||||
|
||||
private void flush() throws IOException
|
||||
{
|
||||
this.buffer.flip();
|
||||
while (this.buffer.hasRemaining()) this.channel.write(this.buffer);
|
||||
this.buffer.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import zombie.ZomboidFileSystem;
|
||||
import zombie.core.backup.ZipBackup;
|
||||
import zombie.core.random.RandStandard;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The hook against vanilla's {@code ZipBackup.makeBackupFile} from the game jar, on the same cache folder. */
|
||||
class BackupHooksTest
|
||||
{
|
||||
private static final String SERVER = "servertest";
|
||||
|
||||
private @TempDir Path cache;
|
||||
|
||||
/** Unset, {@code getCacheDir()} picks the default folder again. */
|
||||
private static void unsetCacheDir() throws ReflectiveOperationException
|
||||
{
|
||||
Field field = ZomboidFileSystem.class.getDeclaredField("cacheDir");
|
||||
field.setAccessible(true);
|
||||
field.set(ZomboidFileSystem.instance, null);
|
||||
}
|
||||
|
||||
private static Object type(String name) throws ClassNotFoundException
|
||||
{
|
||||
for (Object constant : Class.forName("zombie.core.backup.ZipBackup$BackupTypes").getEnumConstants()) {
|
||||
if (((Enum<?>) constant).name().equals(name)) return constant;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(name);
|
||||
}
|
||||
|
||||
private static void vanilla(String serverName, Object type) throws ReflectiveOperationException
|
||||
{
|
||||
Method make = ZipBackup.class.getDeclaredMethod("makeBackupFile", String.class, type.getClass());
|
||||
make.setAccessible(true);
|
||||
make.invoke(null, serverName, type);
|
||||
}
|
||||
|
||||
private void write(String path, byte[] data) throws IOException
|
||||
{
|
||||
Path file = this.cache.resolve(path);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, data);
|
||||
}
|
||||
|
||||
private static byte[] random(int size, long seed)
|
||||
{
|
||||
byte[] data = new byte[size];
|
||||
new Random(seed).nextBytes(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** Entry name to content and method; {@code readme.txt} holds the backup time and is compared apart. */
|
||||
private static Map<String, String> entries(Path zip) throws IOException
|
||||
{
|
||||
Map<String, String> entries = new TreeMap<>();
|
||||
|
||||
try (ZipFile file = new ZipFile(zip.toFile()))
|
||||
{
|
||||
for (ZipEntry entry : Collections.list(file.entries()))
|
||||
{
|
||||
if (entry.getName().equals("readme.txt")) continue;
|
||||
|
||||
byte[] data = file.getInputStream(entry).readAllBytes();
|
||||
entries.put(entry.getName(), entry.getMethod() + " " + HexFormat.of().formatHex(data));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** {@code ZipBackup.rotateBackupFile} reads {@code ServerOptions}, whose constructor draws a random number. */
|
||||
@BeforeAll
|
||||
static void initRandom()
|
||||
{
|
||||
RandStandard.INSTANCE.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createCacheFolder() throws IOException
|
||||
{
|
||||
ZomboidFileSystem.instance.setCacheDir(this.cache.toString());
|
||||
|
||||
this.write("options.ini", "volume=1".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("sounds.ini", "sounds".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("mods/default.txt", "mods".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("mods/SomeMod/mod.info", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("Lua/settings.lua", "lua".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("db/" + BackupHooksTest.SERVER + ".db", BackupHooksTest.random(5000, 1));
|
||||
this.write("Server/" + BackupHooksTest.SERVER + ".ini", "PVP=true".getBytes(StandardCharsets.UTF_8));
|
||||
this.write("Server/backup/old.ini", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String save = "Saves/Multiplayer/" + BackupHooksTest.SERVER + "/";
|
||||
this.write(save + "map_t.bin", BackupHooksTest.random(100, 2));
|
||||
this.write(save + "players.db", BackupHooksTest.random(5 << 20, 3));
|
||||
this.write(save + "blam/skipped.bin", BackupHooksTest.random(10, 4));
|
||||
this.write(save + "map/blam/skipped.bin", BackupHooksTest.random(10, 5));
|
||||
for (int x = 0; x < 10; x++) {
|
||||
for (int y = 0; y < 10; y++) this.write(save + "map/" + x + "/" + y + ".bin", BackupHooksTest.random(x * 300 + y, x * 100L + y));
|
||||
}
|
||||
Files.createDirectories(this.cache.resolve(save + "isoregiondata"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void resetCacheFolder() throws ReflectiveOperationException
|
||||
{
|
||||
BackupHooksTest.unsetCacheDir();
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheEntriesOfVanilla() throws Exception
|
||||
{
|
||||
BackupHooksTest.vanilla(BackupHooksTest.SERVER, BackupHooksTest.type("version"));
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
|
||||
Path vanilla = this.cache.resolve("backups/version/backup_1.zip");
|
||||
Path hooked = this.cache.resolve("backups/period/backup_1.zip");
|
||||
|
||||
Map<String, String> expected = BackupHooksTest.entries(vanilla);
|
||||
assertTrue(expected.containsKey("Saves/Multiplayer/" + BackupHooksTest.SERVER + "/map/9/9.bin"), expected.keySet().toString());
|
||||
assertFalse(expected.containsKey("mods/SomeMod/mod.info"));
|
||||
assertEquals(expected, BackupHooksTest.entries(hooked));
|
||||
|
||||
try (ZipFile vanillaZip = new ZipFile(vanilla.toFile()); ZipFile hookedZip = new ZipFile(hooked.toFile()))
|
||||
{
|
||||
byte[] vanillaReadme = vanillaZip.getInputStream(vanillaZip.getEntry("readme.txt")).readAllBytes();
|
||||
byte[] hookedReadme = hookedZip.getInputStream(hookedZip.getEntry("readme.txt")).readAllBytes();
|
||||
|
||||
// Both start with the backup time, to the second.
|
||||
String readme = new String(hookedReadme, StandardCharsets.UTF_8);
|
||||
assertTrue(readme.startsWith("Backup time: "), readme);
|
||||
assertEquals(readme, hookedZip.getComment());
|
||||
assertArrayEquals(BackupHooksTest.tail(vanillaReadme), BackupHooksTest.tail(hookedReadme));
|
||||
}
|
||||
}
|
||||
|
||||
/** The readme after its first line, the backup time. */
|
||||
private static byte[] tail(byte[] readme)
|
||||
{
|
||||
String text = new String(readme, StandardCharsets.UTF_8);
|
||||
return text.substring(text.indexOf('\n')).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rotatesTheBackupsAsVanilla() throws Exception
|
||||
{
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
|
||||
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_1.zip")));
|
||||
assertTrue(Files.exists(this.cache.resolve("backups/period/backup_2.zip")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotThrowWhenTheBackupFails() throws Exception
|
||||
{
|
||||
// A folder where the zip file goes: opening it fails.
|
||||
Files.createDirectories(this.cache.resolve("backups/period/backup_1.zip/blocked"));
|
||||
|
||||
BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.util;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ParallelZipTest
|
||||
{
|
||||
private static byte[] random(int size, long seed)
|
||||
{
|
||||
byte[] data = new byte[size];
|
||||
new Random(seed).nextBytes(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void write(Path file, byte[] data) throws IOException
|
||||
{
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, data);
|
||||
}
|
||||
|
||||
/** Entry name to content, read with {@code ZipInputStream}, which checks each entry's CRC and size. */
|
||||
private static Map<String, byte[]> entries(Path zip) throws IOException
|
||||
{
|
||||
Map<String, byte[]> entries = new TreeMap<>();
|
||||
|
||||
try (ZipInputStream input = new ZipInputStream(Files.newInputStream(zip)))
|
||||
{
|
||||
for (ZipEntry entry = input.getNextEntry(); entry != null; entry = input.getNextEntry()) {
|
||||
entries.put(entry.getName(), input.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static Path zip(Path temp, Path folder, String prefix) throws IOException
|
||||
{
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "comment", 4, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addFolder(prefix, folder, subfolder -> !subfolder.endsWith("blam"));
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
return zip;
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsEveryFileOfTheTreeExceptSkippedFolders(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
List<String> expected = new ArrayList<>();
|
||||
|
||||
for (int x = 0; x < 20; x++)
|
||||
{
|
||||
for (int y = 0; y < 30; y++)
|
||||
{
|
||||
ParallelZipTest.write(root.resolve("map/" + x + "/" + y + ".bin"), ParallelZipTest.random(x * 100 + y, x * 1000L + y));
|
||||
expected.add("world/map/" + x + "/" + y + ".bin");
|
||||
}
|
||||
}
|
||||
ParallelZipTest.write(root.resolve("map_t.bin"), ParallelZipTest.random(10, 1));
|
||||
ParallelZipTest.write(root.resolve("blam/skipped.bin"), ParallelZipTest.random(10, 2));
|
||||
ParallelZipTest.write(root.resolve("map/blam/skipped.bin"), ParallelZipTest.random(10, 3));
|
||||
ParallelZipTest.write(root.resolve("notblam/kept.bin"), ParallelZipTest.random(10, 4));
|
||||
Files.createDirectories(root.resolve("empty"));
|
||||
expected.add("world/map_t.bin");
|
||||
expected.add("world/notblam/kept.bin");
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
Collections.sort(expected);
|
||||
assertEquals(expected, new ArrayList<>(entries.keySet()));
|
||||
for (String name : expected) assertArrayEquals(Files.readAllBytes(root.resolve(name.substring("world/".length()))), entries.get(name), name);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsOnlyTopLevelFilesWhenNotDescending(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("mods");
|
||||
ParallelZipTest.write(root.resolve("a.txt"), "a".getBytes(StandardCharsets.UTF_8));
|
||||
ParallelZipTest.write(root.resolve("sub/b.txt"), "b".getBytes(StandardCharsets.UTF_8));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 2, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addFolder("mods", root, subfolder -> false);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
assertEquals(List.of("mods/a.txt"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
|
||||
}
|
||||
|
||||
/** Large files are copied by the writing thread; more read data than the budget waits for it. */
|
||||
@Test
|
||||
void writesLargeFilesAndMoreThanTheBudget(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
for (int i = 0; i < 80; i++) ParallelZipTest.write(root.resolve("chunks/" + i + ".bin"), ParallelZipTest.random(1 << 20, i));
|
||||
ParallelZipTest.write(root.resolve("players.db"), ParallelZipTest.random(9 << 20, 100));
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
assertEquals(81, entries.size());
|
||||
assertArrayEquals(Files.readAllBytes(root.resolve("players.db")), entries.get("world/players.db"));
|
||||
assertArrayEquals(Files.readAllBytes(root.resolve("chunks/42.bin")), entries.get("world/chunks/42.bin"));
|
||||
}
|
||||
|
||||
/** As {@code ParallelScatterZipCreator}'s entries: STORED, without Zip64 fields; the comment is set. */
|
||||
@Test
|
||||
void writesStoredEntriesWithoutZip64Fields(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(root.resolve("small.bin"), ParallelZipTest.random(100, 1));
|
||||
ParallelZipTest.write(root.resolve("large.bin"), ParallelZipTest.random(5 << 20, 2));
|
||||
Path zip = ParallelZipTest.zip(temp, root, "world");
|
||||
|
||||
try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip.toFile())) { assertEquals("comment", file.getComment()); }
|
||||
|
||||
try (ZipFile file = ZipFile.builder().setPath(zip).get())
|
||||
{
|
||||
for (ZipArchiveEntry entry : Collections.list(file.getEntries()))
|
||||
{
|
||||
assertEquals(ZipEntry.STORED, entry.getMethod(), entry.getName());
|
||||
assertEquals(0, entry.getLocalFileDataExtra().length, entry.getName());
|
||||
assertEquals(0, entry.getCentralDirectoryExtra().length, entry.getName());
|
||||
assertTrue(file.canReadEntryData(entry));
|
||||
|
||||
try (InputStream input = file.getInputStream(entry)) { assertEquals(entry.getSize(), input.readAllBytes().length); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsAndSkipsFilesThatCannotBeRead(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(root.resolve("kept.bin"), ParallelZipTest.random(10, 1));
|
||||
Files.createSymbolicLink(root.resolve("dangling.bin"), root.resolve("missing.bin"));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
List<IOException> failures = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 2, failures::add))
|
||||
{
|
||||
writer.addFolder("world", root, subfolder -> true);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
assertEquals(List.of("world/kept.bin"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
|
||||
assertEquals(1, failures.size());
|
||||
assertTrue(failures.getFirst().getMessage().contains("dangling.bin"), failures.getFirst().getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsLinkedFilesWithTheirContent(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path root = temp.resolve("save");
|
||||
ParallelZipTest.write(temp.resolve("target.bin"), ParallelZipTest.random(10, 1));
|
||||
Files.createDirectories(root);
|
||||
Files.createSymbolicLink(root.resolve("link.bin"), temp.resolve("target.bin"));
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
|
||||
|
||||
assertArrayEquals(Files.readAllBytes(temp.resolve("target.bin")), entries.get("world/link.bin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsTextAndSingleFiles(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path file = temp.resolve("options.ini");
|
||||
ParallelZipTest.write(file, "volume=1".getBytes(StandardCharsets.UTF_8));
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); }))
|
||||
{
|
||||
writer.addText("readme.txt", "Backup time: now");
|
||||
writer.addFile("options.ini", file);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
Map<String, byte[]> entries = ParallelZipTest.entries(zip);
|
||||
assertEquals("Backup time: now", new String(entries.get("readme.txt"), StandardCharsets.UTF_8));
|
||||
assertEquals("volume=1", new String(entries.get("options.ini"), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Without finish(), as after a failure, the file has no central directory. */
|
||||
@Test
|
||||
void unfinishedFileIsNoZip(@TempDir Path temp) throws IOException
|
||||
{
|
||||
Path zip = temp.resolve("out.zip");
|
||||
|
||||
try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); })) { writer.addText("readme.txt", "text"); }
|
||||
|
||||
assertTrue(Files.size(zip) > 0);
|
||||
assertThrows(IOException.class, () -> ZipFile.builder().setPath(zip).get().close());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user