From fa08d04c33d19e251e11b0044612ef2bcf92dc87 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 12 Nov 2026 17:49:15 -0600 Subject: [PATCH 1/2] Optimize hashing, compression, and memory. --- CHANGELOG | 9 + Dockerfile | 18 +- build.gradle.kts | 30 +- docs/database.md | 4 +- docs/settings.md | 11 + .../MediaGarrdProperties.java | 1 + .../mediagarrdServer/model/BackupArchive.java | 11 +- .../service/BackupArchiveService.java | 62 +-- .../service/BackupOrchestratorService.java | 102 ++++- .../service/DatabaseService.java | 2 +- .../service/DatabaseSnapshotService.java | 60 ++- .../service/PathCoverage.java | 60 +++ .../service/ServiceBackupRunner.java | 221 ++++++----- .../service/ZipCompression.java | 48 +++ .../mediagarrdServer/service/ZipFormat.java | 232 +++++++++++ .../service/ZipPartIndex.java | 27 ++ .../service/ZipPartMerger.java | 221 +++++++++++ .../service/ZipPartWriter.java | 364 ++++++++++++++++++ src/main/resources/application.yml | 1 + .../MediaGarrdPropertiesBindingTest.java | 1 + .../service/ArchiveInteropTest.java | 102 +++++ .../service/ArchiveScaleTest.java | 144 +++++++ .../service/ArchiveTestSupport.java | 92 +++++ .../service/BackupArchiveServiceTest.java | 123 +++++- .../service/BackupCopyRoundsTest.java | 318 +++++++++++++++ .../BackupOrchestratorServiceTest.java | 57 +-- .../service/CoveredSymlinkTest.java | 97 +++++ .../service/DatabaseSnapshotServiceTest.java | 4 +- .../service/GeneratedTar.java | 107 +++++ .../service/PathCoverageTest.java | 48 +++ .../service/ServiceBackupRunnerTest.java | 199 ++++++++-- .../mediagarrdServer/service/TallyTest.java | 47 +++ .../service/ZipCompressionBindingTest.java | 54 +++ .../service/ZipCompressionTest.java | 82 ++++ .../service/ZipFormatTest.java | 36 ++ .../service/ZipPartWriterTest.java | 267 +++++++++++++ 36 files changed, 2994 insertions(+), 268 deletions(-) create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java diff --git a/CHANGELOG b/CHANGELOG index a483054..5fb07d1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -5,6 +5,15 @@ - A scheduled check with nothing to back up now waits one full interval instead of retrying every 30 seconds, and adding or editing a service makes the schedule due again right away - `GET /api/v1/events` also sends `backups-changed` (backup deleted, backup location changed) and `config-changed` (schedule, settings, or services changed), each as `{"at":""}` - `GET /api/v1/health` and `GET /api/v1/backups` are logged at DEBUG, so polling no longer fills the log +- An archive's SHA-256 is now computed while it is written instead of by reading the finished file again, which saves a full pass over every backup +- Archives are compressed at a lighter level by default (`MEDIAGARRD_COMPRESSION_LEVEL`, `0` to `9`, default `1`), and already-compressed files (images, video, audio, zip, gz and similar) are stored as they are +- Backups use a fixed amount of memory regardless of how many files or how much data they hold: archives are written as a stream with an on-disk index, so any backup that fits on disk completes +- The archive writer is our own: zip64 is used automatically for entries over 4 GB, archives over 4 GB, and more than 65,535 entries, and entries now also carry an exact UTC modification time +- Entry owners are always written as a 4-byte uid/gid (`0x7875`), because bsdtar reads only 2- or 4-byte widths and ignored the shorter form, so `bsdtar -xp` now restores small uids such as 33 (www-data) correctly; the NTFS extra (`0x000A`) is no longer written +- A symlink inside a copied path that is also configured as its own path is not stored; the configured path is copied from its real content instead, so restoring that path no longer hits a link-versus-directory conflict and the merge never sees a duplicate name +- A path nested inside another configured path is no longer copied twice: it is skipped when the outer copy includes it, and copied on its own if the outer copy failed, and each service's result reflects its own outcome +- The database snapshot is taken first, and the live database and its `-journal`, `-wal`, and `-shm` files are left out of service copies only when the snapshot succeeded +- The container image is pinned to `eclipse-temurin:21.0.13_9-jre` and starts the JVM with G1, a small starting heap, periodic heap trimming, and `-XX:+ExitOnOutOfMemoryError`; the heap cap follows the container memory (`JAVA_TOOL_OPTIONS`, see `docs/settings.md`), and lazy initialization is no longer used ## 11-11-26 - `GET /api/v1/events` is a live Server-Sent Events stream that needs no setup session: `state` on connect, `run-started` and `run-finished` (`COMPLETED`, `PARTIAL`, or `FAILED`) the moment a run begins and ends, and a `ping` every 20 seconds diff --git a/Dockerfile b/Dockerfile index 45dd5a5..53332a9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,16 +3,20 @@ WORKDIR /workspace COPY . . RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all -FROM eclipse-temurin:21-jre +FROM eclipse-temurin:21.0.13_9-jre WORKDIR /app COPY --from=build /workspace/build/libs/*.jar app.jar EXPOSE 8080 +ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=50" + ENTRYPOINT ["java", \ - "-Xms32m", \ - "-XX:+UseZGC", \ - "-XX:+ZUncommit", \ - "-XX:ZUncommitDelay=30", \ - "-XX:+UseContainerSupport", \ - "-Dspring.main.lazy-initialization=true", \ + "-XX:+UseG1GC", \ + "-Xms16m", \ + "-XX:MinHeapFreeRatio=10", \ + "-XX:MaxHeapFreeRatio=30", \ + "-XX:G1PeriodicGCInterval=60000", \ + "-XX:-G1PeriodicGCInvokesConcurrent", \ + "-XX:TrimNativeHeapInterval=10000", \ + "-XX:+ExitOnOutOfMemoryError", \ "-jar", "/app/app.jar"] diff --git a/build.gradle.kts b/build.gradle.kts index b749201..c641e5f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -38,5 +38,33 @@ springBoot { } tasks.test { - useJUnitPlatform() + useJUnitPlatform { + excludeTags("scale") + } +} + +tasks.register("scaleTest") { + group = "verification" + description = "Builds very large archives under a small heap" + testClassesDirs = sourceSets.test.get().output.classesDirs + classpath = sourceSets.test.get().runtimeClasspath + useJUnitPlatform { + includeTags("scale") + } + val scratch = layout.buildDirectory.dir("scale-tmp").get().asFile + maxHeapSize = "64m" + jvmArgs("-XX:+UseG1GC", "-Xms16m", "-XX:MinHeapFreeRatio=10", "-XX:MaxHeapFreeRatio=30", "-XX:+ExitOnOutOfMemoryError") + systemProperty("java.io.tmpdir", scratch.absolutePath) + doFirst { + scratch.deleteRecursively() + scratch.mkdirs() + } + doLast { + scratch.deleteRecursively() + } + testLogging { + showStandardStreams = true + events("passed", "failed", "skipped") + } + shouldRunAfter(tasks.test) } diff --git a/docs/database.md b/docs/database.md index f2bf1ed..d92dab6 100644 --- a/docs/database.md +++ b/docs/database.md @@ -25,7 +25,7 @@ Never restore over the database of a running server. 2. Extract the copy into an empty directory: ```bash mkdir restore - bsdtar -xpf .zip -C restore '' + bsdtar -xpPf .zip -C restore '' ``` 3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): ```bash @@ -37,7 +37,7 @@ Never restore over the database of a running server. docker compose start ``` -`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. +`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. `-P` lets it extract through symbolic links stored in the archive. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. ## If the database is damaged The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. diff --git a/docs/settings.md b/docs/settings.md index a1a3df3..30dfbad 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -9,6 +9,7 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | `MEDIAGARRD_RETENTION_COUNT` | `10` | How many backups to keep. Only the initial value, like the interval. | | `MEDIAGARRD_BACKUP_ROOT` | `/var/lib/mediagarrd/backups` | Where archives are stored, inside the container. Only the initial value. It must be on a mounted volume. | | `MEDIAGARRD_DATABASE_PATH` | `/var/lib/mediagarrd/db/mediagarrd.db` | The database file, inside the container. It must be on a mounted volume. | +| `MEDIAGARRD_COMPRESSION_LEVEL` | `1` | How hard files are compressed in archives, from `0` (store, no compression) to `9` (smallest, slowest). Files that are already compressed (zip, gz, tgz, bz2, xz, zst, 7z, rar, jpg, jpeg, png, gif, webp, mp4, mkv, mp3, flac, ogg, mov, avi, webm, m4v, m4a, aac, opus, heic, avif, lz4, zstd, jar, docx, xlsx, pptx) are always stored. The server refuses to start with a value outside 0 to 9. | | `MEDIAGARRD_HELPER_IMAGE` | `busybox:stable` | The image used for the helper containers that read each service's files. | | `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Server` | The GitHub repository checked for new releases. | | `MEDIAGARRD_GITHUB_API_URL` | `https://api.github.com` | The GitHub API used for the release check. | @@ -19,3 +20,13 @@ To change where data is kept on the host, change the left side of the volumes in - `./data/server/db`: the database, which holds every setting and service. Keep it on persistent storage. The server also needs `/var/run/docker.sock` mounted to run its helper containers. + +## Memory + +The server idles at roughly 100 to 150 MB and uses a fixed amount of memory while backing up, however many files or however much data a backup holds. Archives are written to disk as a stream, so the only requirement is free disk space: about twice the size of the archive while a run is in progress (the per-path parts plus the merged archive). + +The JVM is tuned in the `Dockerfile`: G1 with a small starting heap that shrinks back after a backup, native memory trimming, and `-XX:+ExitOnOutOfMemoryError` so the container restarts instead of hanging. + +The heap cap defaults to half of the container's memory limit (`JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=50`). Without a memory limit on the container this is half of the host's RAM. To change it, set `JAVA_TOOL_OPTIONS` in `environment`, for example `JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=70` or `JAVA_TOOL_OPTIONS=-Xmx256m`. Setting it replaces the whole default value, and the JVM prints `Picked up JAVA_TOOL_OPTIONS` at startup when it is in effect. + +The image is pinned to `eclipse-temurin:21.0.13_9-jre` because `-XX:TrimNativeHeapInterval` needs Java 21.0.3 or newer. To check the flags against another image, run `docker run --rm java -XX:TrimNativeHeapInterval=10000 -XX:+UseG1GC -version`. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index b50e931..41ea9c5 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -16,6 +16,7 @@ public class MediaGarrdProperties { private String backupRoot = "/var/lib/mediagarrd/backups"; private int retentionCount = 10; private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; + private int compressionLevel = 1; private String helperImage = "busybox:stable"; private String updateRepository = "MediaGarrd/Server"; private String githubApiBaseUrl = "https://api.github.com"; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index 4f1bb69..3322f4e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -15,8 +15,17 @@ public record BackupArchive( String fileName, Path path, long sizeBytes, - Instant createdAt + Instant createdAt, + String checksum ) { + public BackupArchive(String id, String fileName, Path path, long sizeBytes, Instant createdAt) { + this(id, fileName, path, sizeBytes, createdAt, null); + } + + public String resolvedChecksum() { + return checksum != null ? checksum : generateChecksum(); + } + public String generateChecksum() { try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), MessageDigest.getInstance("SHA-256"))) { in.transferTo(OutputStream.nullOutputStream()); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index 43354ad..49d1ebf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -10,22 +10,13 @@ import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -43,7 +34,6 @@ public class BackupArchiveService { .withZone(ZoneOffset.UTC); private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds static final String ARCHIVE_SUFFIX = "-media-backup.zip"; - private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private final DatabaseService db; private final AtomicReference> cachedArchives = new AtomicReference<>(null); @@ -166,14 +156,14 @@ public BackupArchive createArchive(Path runDirectory) { LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); try { Files.createDirectories(root); - mergeParts(runDirectory, archivePath); + String checksum = mergeParts(runDirectory, archivePath); enforceRetention(); long size = Files.size(archivePath); LOGGER.info("Archive created: {} ({} bytes)", fileName, size); invalidateCache(); - return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); + return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt, checksum); } catch (IOException e) { LOGGER.error("Failed to create backup archive: {}", fileName, e); throw new IllegalStateException("Failed to create backup archive", e); @@ -289,63 +279,33 @@ private void invalidateCache() { cachedArchives.set(null); } - private void mergeParts(Path runDirectory, Path zipPath) throws IOException { + private String mergeParts(Path runDirectory, Path zipPath) throws IOException { List parts; try (var walk = Files.walk(runDirectory)) { parts = walk .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip")) + .filter(path -> path.getFileName().toString().endsWith(ZipPartWriter.PART_SUFFIX)) .sorted() .toList(); } Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); Path snapshotDirectory = runDirectory.resolve(DatabaseSnapshotService.PART_DIRECTORY); - List openParts = new ArrayList<>(); - SortedMap entries = new TreeMap<>(); - Set reserved = new HashSet<>(); + ZipPartMerger.Result result; try { - for (Path part : parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList()) { - ZipFile zip = ZipFile.builder().setPath(part).get(); - openParts.add(zip); - for (ZipArchiveEntry entry : Collections.list(zip.getEntriesInPhysicalOrder())) { - entries.put(entry.getName(), new ZipEntrySource(zip, entry)); - if (!entry.isDirectory()) { - DATABASE_SIDECAR_SUFFIXES.forEach(suffix -> reserved.add(entry.getName() + suffix)); - } - } - } - for (Path part : parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList()) { - ZipFile zip = ZipFile.builder().setPath(part).get(); - openParts.add(zip); - for (ZipArchiveEntry entry : Collections.list(zip.getEntriesInPhysicalOrder())) { - if (reserved.contains(entry.getName())) { - LOGGER.warn("Dropping {} from {}, the database snapshot owns that path", entry.getName(), part); - continue; - } - entries.putIfAbsent(entry.getName(), new ZipEntrySource(zip, entry)); - } - } - // Sorted names put every directory before its contents, so unzip applies directory modes and times - try (var out = new ZipArchiveOutputStream(tempZip)) { - for (ZipEntrySource source : entries.values()) { - out.addRawArchiveEntry(source.entry(), source.zip().getRawInputStream(source.entry())); - } - } + result = ZipPartMerger.merge( + parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList(), + parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList(), + tempZip, runDirectory); } catch (IOException | RuntimeException e) { Files.deleteIfExists(tempZip); throw e; - } finally { - for (ZipFile zip : openParts) { - zip.close(); - } } Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - LOGGER.info("Merged {} part(s) into {} entries", parts.size(), entries.size()); + LOGGER.info("Merged {} part(s) into {} entries", parts.size(), result.entries()); + return result.checksum(); } - private record ZipEntrySource(ZipFile zip, ZipArchiveEntry entry) {} - private BackupArchive toArchive(Path path) { String fileName = path.getFileName().toString(); return new BackupArchive( diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 4130464..f9501b9 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -10,8 +10,12 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -146,19 +150,13 @@ BackupRunResult runBackup(boolean scheduled) { LOGGER.info("Backup run started: runDir={}, services={}", runDir, services.stream().map(ServiceDefinition::name).toList()); - List> futures = services.stream() - .map(service -> CompletableFuture - .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) - .exceptionally(t -> { - Throwable cause = unwrap(t); - LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); - return failedResult(service.name(), cause); - })) - .toList(); + DatabaseSnapshotService.Outcome snapshot = snapshotDatabase(runDir); + BackupServiceResult snapshotResult = snapshot.result(); + Set excluded = COMPLETED.equals(snapshotResult.status()) && snapshot.hostPath() != null + ? DatabaseSnapshotService.reservedNames(snapshot.hostPath()) + : Set.of(); - List serviceRunResults = futures.stream() - .map(CompletableFuture::join) - .toList(); + List serviceRunResults = copyServices(services, runDir, excluded); List incomplete = serviceRunResults.stream() .filter(r -> !COMPLETED.equals(r.status())) @@ -180,7 +178,6 @@ BackupRunResult runBackup(boolean scheduled) { throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); } - BackupServiceResult snapshotResult = snapshotDatabase(runDir); List recordedResults = new ArrayList<>(serviceRunResults); recordedResults.add(snapshotResult); boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status()); @@ -247,12 +244,85 @@ private void publishFinished(String status, Instant startedAt) { } } - private BackupServiceResult snapshotDatabase(Path runDir) { + private List copyServices(List services, Path runDir, Set excluded) { + Map tallies = new LinkedHashMap<>(); + List unresolved = new ArrayList<>(); + for (ServiceDefinition service : services) { + tallies.put(service.name(), new ServiceBackupRunner.Tally(service.name())); + for (int i = 0; i < service.paths().size(); i++) { + unresolved.add(new PathCoverage.Item(service, i)); + } + } + + int round = 0; + while (!unresolved.isEmpty()) { + round++; + List owners = PathCoverage.plan(unresolved); + Map> byService = new LinkedHashMap<>(); + owners.forEach(owner -> byService.computeIfAbsent(owner.item().service().name(), name -> new ArrayList<>()).add(owner)); + LOGGER.debug("Copy round {}: {} path(s), {} left", round, owners.size(), unresolved.size()); + + Map> futures = new LinkedHashMap<>(); + byService.forEach((name, serviceOwners) -> { + ServiceDefinition service = serviceOwners.get(0).item().service(); + List indexes = serviceOwners.stream().map(owner -> owner.item().index()).toList(); + List> covered = serviceOwners.stream() + .map(owner -> owner.covered().stream().map(PathCoverage.Item::key).collect(Collectors.toUnmodifiableSet())) + .toList(); + futures.put(name, CompletableFuture + .supplyAsync(() -> runner.copyPaths(service, indexes, runDir, excluded, covered), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", name, cause); + return failedRound(service, indexes, cause); + })); + }); + + Map copies = new HashMap<>(); + futures.forEach((name, future) -> { + ServiceBackupRunner.ServiceRound finished = future.join(); + tallies.get(name).add(finished); + ServiceDefinition service = byService.get(name).get(0).item().service(); + finished.paths().forEach(copy -> copies.put(new PathCoverage.Item(service, copy.index()), copy)); + }); + + List resolved = new ArrayList<>(); + for (PathCoverage.Owner owner : owners) { + resolved.add(owner.item()); + ServiceBackupRunner.PathCopy copy = copies.get(owner.item()); + if (copy == null || !copy.copied()) { + owner.covered().forEach(item -> LOGGER.info("[{}] {} was covered by {} which failed, copying it on its own", + item.service().name(), item.path(), owner.item().path())); + continue; + } + for (PathCoverage.Item item : owner.covered()) { + if (copy.confirmed().contains(item.key())) { + tallies.get(item.service().name()).addCovered(1); + resolved.add(item); + LOGGER.info("[{}] {} is included in {} ({})", item.service().name(), item.path(), owner.item().path(), owner.item().service().name()); + } else { + LOGGER.info("[{}] {} was not found inside {}, copying it on its own", item.service().name(), item.path(), owner.item().path()); + } + } + } + unresolved.removeAll(resolved); + } + return tallies.values().stream().map(ServiceBackupRunner.Tally::result).toList(); + } + + private static ServiceBackupRunner.ServiceRound failedRound(ServiceDefinition service, List indexes, Throwable cause) { + List copies = indexes.stream() + .map(index -> new ServiceBackupRunner.PathCopy(index, service.paths().get(index), false, null, Set.of())) + .toList(); + return new ServiceBackupRunner.ServiceRound(Objects.requireNonNullElse(cause.getMessage(), cause.toString()), copies); + } + + private DatabaseSnapshotService.Outcome snapshotDatabase(Path runDir) { try { - return snapshotService.snapshot(runDir); + return snapshotService.snapshotWithHostPath(runDir); } catch (RuntimeException e) { LOGGER.warn("[{}] Failed to snapshot database", SNAPSHOT_NAME, e); - return failedResult(SNAPSHOT_NAME, e); + return new DatabaseSnapshotService.Outcome(failedResult(SNAPSHOT_NAME, e), null); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index ac34cfc..d76ca4a 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -313,7 +313,7 @@ private Integer addMasterBackup(Connection connection, BackupRunResult backupRec statement.setString(3, backupRecord.endTime()); statement.setString(4, backupRecord.status()); BackupArchive archive = backupRecord.archive(); - statement.setString(5, archive == null ? null : archive.generateChecksum()); + statement.setString(5, archive == null ? null : archive.resolvedChecksum()); statement.setString(6, archive == null ? null : archive.path().toString()); statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java index 03a9ecf..506cbbe 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -5,16 +5,18 @@ import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.sql.SQLException; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -28,52 +30,76 @@ public class DatabaseSnapshotService { static final String SERVICE_NAME = "_mediagarrd-server"; static final String PART_DIRECTORY = ".mediagarrd-server"; - static final String PART_NAME = "database.zip"; + static final String PART_NAME = "database" + ZipPartWriter.PART_SUFFIX; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private static final String SNAPSHOT_FILE = "snapshot.db"; private final DatabaseService db; private final DatabaseHostPathResolver hostPaths; + private final ZipCompression compression; - public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths) { + public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { this.db = db; this.hostPaths = hostPaths; + this.compression = compression; } + public record Outcome(BackupServiceResult result, Path hostPath) {} + public BackupServiceResult snapshot(Path runDirectory) { + return snapshotWithHostPath(runDirectory).result(); + } + + public Outcome snapshotWithHostPath(Path runDirectory) { String startTime = recordCurrentTime(); Path directory = runDirectory.resolve(PART_DIRECTORY); Path snapshot = directory.resolve(SNAPSHOT_FILE); Path part = directory.resolve(PART_NAME); + Path hostPath = null; try { if (!Files.isRegularFile(db.databaseFile())) { throw new IOException("Database file " + db.databaseFile() + " does not exist"); } - Path hostPath = hostPaths.resolve(db.databaseFile()); + hostPath = hostPaths.resolve(db.databaseFile()); Files.createDirectories(directory); db.snapshotTo(snapshot); writePart(snapshot, hostPath, part); LOGGER.info("[{}] Snapshotted database {} as {}", SERVICE_NAME, db.databaseFile(), hostPath); - return new BackupServiceResult(null, COMPLETED, startTime, recordCurrentTime(), SERVICE_NAME, null); + return new Outcome(new BackupServiceResult(null, COMPLETED, startTime, recordCurrentTime(), SERVICE_NAME, null), hostPath); } catch (IOException | SQLException | RuntimeException e) { LOGGER.warn("[{}] Failed to snapshot database", SERVICE_NAME, e); - deleteQuietly(part); - return new BackupServiceResult(null, FAILED, startTime, recordCurrentTime(), SERVICE_NAME, - Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName())); + discardQuietly(part); + return new Outcome(new BackupServiceResult(null, FAILED, startTime, recordCurrentTime(), SERVICE_NAME, + Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName())), hostPath); } finally { deleteQuietly(snapshot); } } + static String entryName(Path hostPath) { + return hostPath.getRoot().relativize(hostPath).toString(); + } + + static Set reservedNames(Path hostPath) { + String name = entryName(hostPath); + return DATABASE_SIDECAR_SUFFIXES.stream().map(suffix -> name + suffix).collect(Collectors.toUnmodifiableSet()); + } + private void writePart(Path snapshot, Path hostPath, Path part) throws IOException { Map attributes = Files.readAttributes(db.databaseFile(), "unix:mode,uid,gid,lastModifiedTime"); - ZipArchiveEntry entry = new ZipArchiveEntry(hostPath.getRoot().relativize(hostPath).toString()); - entry.setUnixMode(UnixStat.FILE_FLAG | ((Integer) attributes.get("mode") & 07777)); - entry.setTime(((FileTime) attributes.get("lastModifiedTime")).toMillis()); - entry.addExtraField(ServiceBackupRunner.owner(((Integer) attributes.get("uid")).longValue(), ((Integer) attributes.get("gid")).longValue())); - try (var zip = new ZipArchiveOutputStream(part)) { - zip.putArchiveEntry(entry); - Files.copy(snapshot, zip); - zip.closeArchiveEntry(); + try (var writer = new ZipPartWriter(part, compression); InputStream content = Files.newInputStream(snapshot)) { + writer.addEntry(entryName(hostPath), UnixStat.FILE_FLAG | ((Integer) attributes.get("mode") & 07777), + ((Integer) attributes.get("uid")).longValue(), ((Integer) attributes.get("gid")).longValue(), + ((FileTime) attributes.get("lastModifiedTime")).toMillis(), Files.size(snapshot), content); + writer.complete(); + } + } + + private static void discardQuietly(Path part) { + try { + ZipPartWriter.discard(part); + } catch (IOException e) { + LOGGER.warn("Unable to remove {}", part, e); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java new file mode 100644 index 0000000..71a7d2d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java @@ -0,0 +1,60 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +final class PathCoverage { + + private static final Comparator TIE_BREAK = Comparator.comparing((Item item) -> item.service().name()).thenComparingInt(Item::index); + + record Item(ServiceDefinition service, int index) { + + String path() { + return service.paths().get(index); + } + + Path location() { + return Path.of(path()); + } + + String key() { + Path location = location(); + return location.getRoot() == null ? path() : location.getRoot().relativize(location).toString(); + } + } + + record Owner(Item item, List covered) {} + + private PathCoverage() {} + + static List plan(List unresolved) { + List owners = new ArrayList<>(); + for (Item candidate : unresolved) { + if (unresolved.stream().noneMatch(other -> other != candidate && covers(other, candidate))) { + owners.add(new Owner(candidate, new ArrayList<>())); + } + } + for (Item candidate : unresolved) { + if (owners.stream().noneMatch(owner -> owner.item() == candidate)) { + owners.stream() + .filter(owner -> candidate.location().startsWith(owner.item().location())) + .findFirst() + .ifPresent(owner -> owner.covered().add(candidate)); + } + } + return owners; + } + + private static boolean covers(Item other, Item candidate) { + Path otherLocation = other.location(); + Path candidateLocation = candidate.location(); + if (candidateLocation.equals(otherLocation)) { + return TIE_BREAK.compare(other, candidate) < 0; + } + return candidateLocation.startsWith(otherLocation); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java index cff0ff2..71e4394 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java @@ -13,19 +13,14 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.stream.IntStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.compress.archivers.zip.X7875_NewUnix; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -38,83 +33,164 @@ public class ServiceBackupRunner { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBackupRunner.class); - static final String PART_SUFFIX = ".zip"; - static final String LINKS_PART_SUFFIX = "-links.zip"; + static final String PART_SUFFIX = ZipPartWriter.PART_SUFFIX; + + public record PathCopy(int index, String path, boolean copied, String error, Set confirmed) {} + + public record ServiceRound(String error, List paths) {} + + record ArchiveResult(int entries, Set confirmed) {} + + public static final class Tally { + + private final String serviceName; + private final String startTime = recordCurrentTime(); + private final List errors = new ArrayList<>(); + private String endTime = startTime; + private int copied; + + public Tally(String serviceName) { + this.serviceName = serviceName; + } + + public void add(ServiceRound round) { + if (round.error() != null && !errors.contains(round.error())) { + errors.add(round.error()); + } + for (PathCopy path : round.paths()) { + if (path.copied()) { + copied++; + } else if (path.error() != null) { + errors.add(path.error()); + } + } + endTime = recordCurrentTime(); + } + + public void addCovered(int paths) { + copied += paths; + endTime = recordCurrentTime(); + } + + public BackupServiceResult result() { + String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; + return new BackupServiceResult(null, status, startTime, endTime, serviceName, + errors.isEmpty() ? null : String.join("; ", errors)); + } + } private final DockerService docker; + private final ZipCompression compression; - public ServiceBackupRunner(DockerService docker) { + public ServiceBackupRunner(DockerService docker, ZipCompression compression) { this.docker = docker; + this.compression = compression; } public BackupServiceResult run(ServiceDefinition service, Path runDirectory) { - String startTime = recordCurrentTime(); - Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); - List errors = new ArrayList<>(); - int copied = 0; + Tally tally = new Tally(service.name()); + tally.add(copyPaths(service, IntStream.range(0, service.paths().size()).boxed().toList(), runDirectory, Set.of(), List.of())); + return tally.result(); + } + public ServiceRound copyPaths(ServiceDefinition service, List indexes, Path runDirectory, Set excluded, List> covered) { + Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); + List copies = new ArrayList<>(); try { Files.createDirectories(serviceDirectory); String containerId = docker.containerFor(service); - for (int i = 0; i < service.paths().size(); i++) { - String hostPath = service.paths().get(i); - Path part = serviceDirectory.resolve(i + PART_SUFFIX); - try (InputStream tar = docker.copyFrom(containerId, hostPath)) { - int entries = archive(tar, hostPath, part); - copied++; - LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, entries); - } catch (IOException | RuntimeException e) { - discard(part); - LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); - errors.add(hostPath + ": " + describe(e)); - } + for (int i = 0; i < indexes.size(); i++) { + copies.add(copyPath(containerId, service, indexes.get(i), serviceDirectory, excluded, covered.isEmpty() ? Set.of() : covered.get(i))); } + return new ServiceRound(null, copies); } catch (IOException | RuntimeException e) { LOGGER.warn("[{}] Unable to prepare helper container", service.name(), e); - errors.add(describe(e)); + for (int i = copies.size(); i < indexes.size(); i++) { + int index = indexes.get(i); + copies.add(new PathCopy(index, service.paths().get(index), false, null, Set.of())); + } + return new ServiceRound(describe(e), copies); } + } - String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; - return new BackupServiceResult(null, status, startTime, recordCurrentTime(), service.name(), - errors.isEmpty() ? null : String.join("; ", errors)); + private PathCopy copyPath(String containerId, ServiceDefinition service, int index, Path serviceDirectory, Set excluded, Set covered) { + String hostPath = service.paths().get(index); + Path part = serviceDirectory.resolve(index + PART_SUFFIX); + try (InputStream tar = docker.copyFrom(containerId, hostPath)) { + ArchiveResult result = archive(tar, hostPath, part, compression, excluded, covered); + LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, result.entries()); + return new PathCopy(index, hostPath, true, null, result.confirmed()); + } catch (IOException | RuntimeException e) { + discard(part); + LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); + return new PathCopy(index, hostPath, false, hostPath + ": " + describe(e), Set.of()); + } + } + + static int archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression) throws IOException { + return archive(tarStream, hostPath, part, compression, Set.of(), Set.of()).entries(); } - static int archive(InputStream tarStream, String hostPath, Path part) throws IOException { + static ArchiveResult archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression, Set excluded, Set covered) + throws IOException { Path source = Path.of(hostPath); Path base = Objects.requireNonNullElse(source.getParent(), source.getRoot()); - Set names = new HashSet<>(); - Map hardLinks = new LinkedHashMap<>(); + Set confirmed = new HashSet<>(); - try (var tar = new TarArchiveInputStream(tarStream); var zip = new ZipArchiveOutputStream(part)) { + try (var tar = new TarArchiveInputStream(tarStream); var writer = new ZipPartWriter(part, compression)) { TarArchiveEntry entry; while ((entry = tar.getNextEntry()) != null) { String name = entryName(base, source, entry.getName(), entry.isDirectory()); - if (!names.add(name)) { + if (excluded.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Skipping {} in {}, the database snapshot owns that path", name, hostPath); continue; } + if (writer.contains(name)) { + continue; + } + long modified = entry.getModTime().getTime(); + boolean content = false; if (entry.isFIFO() || entry.isCharacterDevice() || entry.isBlockDevice()) { - names.remove(name); + writer.markSkipped(name); LOGGER.warn("Skipping special file {} in {}", entry.getName(), hostPath); } else if (entry.isDirectory()) { - write(zip, entry, name, UnixStat.DIR_FLAG, null); + writer.addEntry(name, UnixStat.DIR_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, 0, + InputStream.nullInputStream()); + content = true; + } else if (entry.isSymbolicLink() && covered.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Not storing symlink {} in {}, it is configured as its own path and is copied from its target", name, hostPath); } else if (entry.isSymbolicLink()) { byte[] target = entry.getLinkName().getBytes(StandardCharsets.UTF_8); - write(zip, entry, name, UnixStat.LINK_FLAG, new ByteArrayInputStream(target)); + writer.addEntry(name, UnixStat.LINK_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + target.length, new ByteArrayInputStream(target)); } else if (entry.isLink()) { - hardLinks.put(name, entryName(base, source, entry.getLinkName(), false)); + if (writer.addCopy(name, entryName(base, source, entry.getLinkName(), false))) { + content = true; + } else { + writer.markSkipped(name); + LOGGER.warn("Skipping hard link {} in {}, its target was skipped", entry.getName(), hostPath); + } } else if (entry.isFile()) { - write(zip, entry, name, UnixStat.FILE_FLAG, tar); + writer.addEntry(name, UnixStat.FILE_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + entry.getRealSize(), tar); + content = true; } else { - names.remove(name); + writer.markSkipped(name); LOGGER.warn("Skipping unsupported entry {} in {}", entry.getName(), hostPath); } + if (content) { + String key = name.endsWith("/") ? name.substring(0, name.length() - 1) : name; + if (covered.contains(key)) { + confirmed.add(key); + } + } } + int entries = writer.entryCount(); + writer.complete(); + return new ArchiveResult(entries, confirmed); } - - if (!hardLinks.isEmpty()) { - writeHardLinks(part, hardLinks); - } - return names.size(); } static String entryName(Path base, Path source, String tarName, boolean directory) throws IOException { @@ -126,67 +202,14 @@ static String entryName(Path base, Path source, String tarName, boolean director return directory ? name + "/" : name; } - private static void write(ZipArchiveOutputStream zip, TarArchiveEntry source, String name, int type, InputStream content) - throws IOException { - ZipArchiveEntry entry = new ZipArchiveEntry(name); - entry.setUnixMode(type | (source.getMode() & 07777)); - entry.setTime(source.getModTime().getTime()); - entry.addExtraField(owner(source.getLongUserId(), source.getLongGroupId())); - zip.putArchiveEntry(entry); - if (content != null) { - content.transferTo(zip); - } - zip.closeArchiveEntry(); - } - - private static void writeHardLinks(Path part, Map hardLinks) throws IOException { - Path linksPart = linksPart(part); - try (ZipFile written = ZipFile.builder().setPath(part).get(); var zip = new ZipArchiveOutputStream(linksPart)) { - for (var link : hardLinks.entrySet()) { - ZipArchiveEntry target = written.getEntry(link.getValue()); - if (target == null) { - throw new IOException("Hard link " + link.getKey() + " points to a missing entry " + link.getValue()); - } - zip.addRawArchiveEntry(renamed(target, link.getKey()), written.getRawInputStream(target)); - } - } catch (IOException e) { - Files.deleteIfExists(linksPart); - throw e; - } - } - - private static ZipArchiveEntry renamed(ZipArchiveEntry target, String name) { - ZipArchiveEntry entry = new ZipArchiveEntry(name); - entry.setMethod(target.getMethod()); - entry.setCrc(target.getCrc()); - entry.setSize(target.getSize()); - entry.setCompressedSize(target.getCompressedSize()); - entry.setUnixMode(target.getUnixMode()); - entry.setTime(target.getTime()); - entry.setExtraFields(target.getExtraFields()); - return entry; - } - - static X7875_NewUnix owner(long uid, long gid) { - X7875_NewUnix owner = new X7875_NewUnix(); - owner.setUID(uid); - owner.setGID(gid); - return owner; - } - private static void discard(Path part) { try { - Files.deleteIfExists(part); - Files.deleteIfExists(linksPart(part)); + ZipPartWriter.discard(part); } catch (IOException e) { LOGGER.warn("Unable to remove incomplete archive part {}", part, e); } } - private static Path linksPart(Path part) { - return part.resolveSibling(part.getFileName().toString().replace(PART_SUFFIX, LINKS_PART_SUFFIX)); - } - private static String describe(Throwable e) { return Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java new file mode 100644 index 0000000..f8b7d9f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java @@ -0,0 +1,48 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.Locale; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Component +public class ZipCompression { + + static final int MIN_LEVEL = 0; + static final int MAX_LEVEL = 9; + private static final Set ALREADY_COMPRESSED = Set.of( + "zip", "gz", "tgz", "bz2", "xz", "zst", "7z", "rar", + "jpg", "jpeg", "png", "gif", "webp", + "mp4", "mkv", "mp3", "flac", "ogg", + "mov", "avi", "webm", "m4v", "m4a", "aac", "opus", "heic", "avif", + "lz4", "zstd", "jar", "docx", "xlsx", "pptx"); + + private final int level; + + @Autowired + public ZipCompression(MediaGarrdProperties properties) { + this(properties.getCompressionLevel()); + } + + public ZipCompression(int level) { + if (level < MIN_LEVEL || level > MAX_LEVEL) { + throw new IllegalStateException("mediagarrd.compression-level must be between " + MIN_LEVEL + " and " + MAX_LEVEL + ", was " + level); + } + this.level = level; + } + + public int level() { + return level; + } + + boolean stores(String name) { + if (level == 0) { + return true; + } + int dot = name.lastIndexOf('.'); + return dot >= 0 && dot > name.lastIndexOf('/') && ALREADY_COMPRESSED.contains(name.substring(dot + 1).toLowerCase(Locale.ROOT)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java new file mode 100644 index 0000000..30cfc6b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java @@ -0,0 +1,232 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; + +final class ZipFormat { + + static final int STORED = 0; + static final int DEFLATED = 8; + static final long ZIP64_LIMIT = 0xFFFFFFFFL; + static final long UINT32_MAX = 0xFFFFFFFFL; + static final long ZIP64_LOCAL_THRESHOLD = 0xF0000000L; + static final int LOCAL_HEADER_SIZE = 30; + static final int CRC_OFFSET = 14; + static final int ZIP64_FIELD_BYTES = 16; + static final int MAX_NAME_BYTES = 0xFFFF; + + private static final int LOCAL_SIGNATURE = 0x04034b50; + private static final int CENTRAL_SIGNATURE = 0x02014b50; + private static final int END_SIGNATURE = 0x06054b50; + private static final int ZIP64_END_SIGNATURE = 0x06064b50; + private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50; + private static final int UTF8_FLAG = 0x0800; + private static final int VERSION_DEFAULT = 20; + private static final int VERSION_ZIP64 = 45; + private static final int MADE_BY_UNIX = 0x0314; + private static final int MADE_BY_UNIX_ZIP64 = 0x032D; + private static final int ZIP64_ID = 0x0001; + private static final int TIMESTAMP_ID = 0x5455; + private static final int OWNER_ID = 0x7875; + private static final int DOS_BEFORE_1980 = 1 << 21 | 1 << 16; + private static final int DOS_MAX_YEAR = 2107; + + private ZipFormat() {} + + record Entry(String name, long localOffset, long dataOffset, int method, long crc, long compressedSize, long size, + int mode, long uid, long gid, long modified, boolean localZip64) {} + + static byte[] nameBytes(String name) throws IOException { + byte[] bytes = name.getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_NAME_BYTES) { + throw new IOException("Entry name is too long for a zip archive: " + name.substring(0, 64) + "..."); + } + return bytes; + } + + static byte[] localHeader(byte[] name, int method, long modified, long uid, long gid, boolean zip64, long crc, long compressedSize, long size) { + byte[] extra = localExtra(modified, uid, gid, zip64, compressedSize, size); + byte[] header = new byte[LOCAL_HEADER_SIZE + name.length + extra.length]; + put32(header, 0, LOCAL_SIGNATURE); + put16(header, 4, zip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 6, UTF8_FLAG); + put16(header, 8, method); + put32(header, 10, dosTime(modified)); + System.arraycopy(localSizes(zip64, crc, compressedSize, size), 0, header, CRC_OFFSET, 12); + put16(header, 26, name.length); + put16(header, 28, extra.length); + System.arraycopy(name, 0, header, LOCAL_HEADER_SIZE, name.length); + System.arraycopy(extra, 0, header, LOCAL_HEADER_SIZE + name.length, extra.length); + return header; + } + + static byte[] localSizes(boolean zip64, long crc, long compressedSize, long size) { + byte[] sizes = new byte[12]; + put32(sizes, 0, crc); + put32(sizes, 4, zip64 ? ZIP64_LIMIT : compressedSize); + put32(sizes, 8, zip64 ? ZIP64_LIMIT : size); + return sizes; + } + + static byte[] zip64LocalExtra(long compressedSize, long size) { + byte[] extra = new byte[4 + ZIP64_FIELD_BYTES]; + put16(extra, 0, ZIP64_ID); + put16(extra, 2, ZIP64_FIELD_BYTES); + put64(extra, 4, size); + put64(extra, 12, compressedSize); + return extra; + } + + private static byte[] localExtra(long modified, long uid, long gid, boolean zip64, long compressedSize, long size) { + byte[] ownerData = ownerData(uid, gid); + boolean timestamp = fitsUnixTime(modified); + byte[] extra = new byte[(zip64 ? 4 + ZIP64_FIELD_BYTES : 0) + (timestamp ? 9 : 0) + 4 + ownerData.length]; + int pos = 0; + if (zip64) { + byte[] field = zip64LocalExtra(compressedSize, size); + System.arraycopy(field, 0, extra, pos, field.length); + pos += field.length; + } + if (timestamp) { + pos = putTimestamp(extra, pos, modified); + } + put16(extra, pos, OWNER_ID); + put16(extra, pos + 2, ownerData.length); + System.arraycopy(ownerData, 0, extra, pos + 4, ownerData.length); + return extra; + } + + static byte[] ownerData(long uid, long gid) { + byte[] data = new byte[11]; + data[0] = 1; + data[1] = 4; + put32(data, 2, Math.max(0, Math.min(uid, UINT32_MAX))); + data[6] = 4; + put32(data, 7, Math.max(0, Math.min(gid, UINT32_MAX))); + return data; + } + + static byte[] centralHeader(Entry entry, long offset) throws IOException { + byte[] name = nameBytes(entry.name()); + boolean overflowSize = entry.size() >= ZIP64_LIMIT; + boolean overflowCompressed = entry.compressedSize() >= ZIP64_LIMIT; + boolean overflowOffset = offset >= ZIP64_LIMIT; + int zip64Fields = (overflowSize ? 1 : 0) + (overflowCompressed ? 1 : 0) + (overflowOffset ? 1 : 0); + boolean zip64 = zip64Fields > 0; + boolean timestamp = fitsUnixTime(entry.modified()); + int extraLength = (zip64 ? 4 + 8 * zip64Fields : 0) + (timestamp ? 9 : 0) + 4; + byte[] header = new byte[46 + name.length + extraLength]; + boolean needsZip64 = zip64 || entry.localZip64(); + put32(header, 0, CENTRAL_SIGNATURE); + put16(header, 4, needsZip64 ? MADE_BY_UNIX_ZIP64 : MADE_BY_UNIX); + put16(header, 6, needsZip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 8, UTF8_FLAG); + put16(header, 10, entry.method()); + put32(header, 12, dosTime(entry.modified())); + put32(header, 16, entry.crc()); + put32(header, 20, overflowCompressed ? ZIP64_LIMIT : entry.compressedSize()); + put32(header, 24, overflowSize ? ZIP64_LIMIT : entry.size()); + put16(header, 28, name.length); + put16(header, 30, extraLength); + put32(header, 38, externalAttributes(entry.mode(), entry.name().endsWith("/"))); + put32(header, 42, overflowOffset ? ZIP64_LIMIT : offset); + System.arraycopy(name, 0, header, 46, name.length); + int pos = 46 + name.length; + if (zip64) { + put16(header, pos, ZIP64_ID); + put16(header, pos + 2, 8 * zip64Fields); + pos += 4; + if (overflowSize) { + put64(header, pos, entry.size()); + pos += 8; + } + if (overflowCompressed) { + put64(header, pos, entry.compressedSize()); + pos += 8; + } + if (overflowOffset) { + put64(header, pos, offset); + pos += 8; + } + } + if (timestamp) { + pos = putTimestamp(header, pos, entry.modified()); + } + put16(header, pos, OWNER_ID); + put16(header, pos + 2, 0); + return header; + } + + static byte[] endOfArchive(long entries, long centralSize, long centralOffset) { + boolean zip64 = entries >= 0xFFFF || centralSize >= ZIP64_LIMIT || centralOffset >= ZIP64_LIMIT; + byte[] tail = new byte[(zip64 ? 56 + 20 : 0) + 22]; + int pos = 0; + if (zip64) { + put32(tail, 0, ZIP64_END_SIGNATURE); + put64(tail, 4, 44); + put16(tail, 12, MADE_BY_UNIX_ZIP64); + put16(tail, 14, VERSION_ZIP64); + put64(tail, 24, entries); + put64(tail, 32, entries); + put64(tail, 40, centralSize); + put64(tail, 48, centralOffset); + put32(tail, 56, ZIP64_LOCATOR_SIGNATURE); + put64(tail, 64, centralOffset + centralSize); + put32(tail, 72, 1); + pos = 76; + } + put32(tail, pos, END_SIGNATURE); + put16(tail, pos + 8, Math.min(entries, 0xFFFF)); + put16(tail, pos + 10, Math.min(entries, 0xFFFF)); + put32(tail, pos + 12, Math.min(centralSize, ZIP64_LIMIT)); + put32(tail, pos + 16, Math.min(centralOffset, ZIP64_LIMIT)); + return tail; + } + + static long externalAttributes(int mode, boolean directory) { + return ((long) mode << 16) | ((mode & 0200) == 0 ? 1 : 0) | (directory ? 0x10 : 0); + } + + static boolean fitsUnixTime(long millis) { + long seconds = Math.floorDiv(millis, 1000L); + return seconds >= 0 && seconds <= Integer.MAX_VALUE; + } + + static long dosTime(long millis) { + LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); + if (time.getYear() < 1980) { + return DOS_BEFORE_1980; + } + if (time.getYear() > DOS_MAX_YEAR) { + time = LocalDateTime.of(DOS_MAX_YEAR, 12, 31, 23, 59, 58); + } + return ((long) (time.getYear() - 1980) << 25 | (long) time.getMonthValue() << 21 | (long) time.getDayOfMonth() << 16 + | (long) time.getHour() << 11 | (long) time.getMinute() << 5 | time.getSecond() >> 1) & 0xFFFFFFFFL; + } + + private static int putTimestamp(byte[] target, int pos, long modified) { + put16(target, pos, TIMESTAMP_ID); + put16(target, pos + 2, 5); + target[pos + 4] = 1; + put32(target, pos + 5, Math.floorDiv(modified, 1000L)); + return pos + 9; + } + + static void put16(byte[] target, int pos, long value) { + target[pos] = (byte) value; + target[pos + 1] = (byte) (value >> 8); + } + + static void put32(byte[] target, int pos, long value) { + put16(target, pos, value); + put16(target, pos + 2, value >> 16); + } + + static void put64(byte[] target, int pos, long value) { + put32(target, pos, value); + put32(target, pos + 4, value >> 32); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java new file mode 100644 index 0000000..6503070 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java @@ -0,0 +1,27 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +final class ZipPartIndex { + + private static final int CACHE_KIB = 2048; + + private ZipPartIndex() {} + + static Connection open(Path file) throws SQLException { + Connection connection = DriverManager.getConnection("jdbc:sqlite:" + file.toAbsolutePath()); + try (Statement statement = connection.createStatement()) { + statement.execute("PRAGMA journal_mode=OFF"); + statement.execute("PRAGMA synchronous=OFF"); + statement.execute("PRAGMA cache_size=-" + CACHE_KIB); + } catch (SQLException e) { + connection.close(); + throw e; + } + return connection; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java new file mode 100644 index 0000000..76ee8f0 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java @@ -0,0 +1,221 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; + +final class ZipPartMerger { + + private static final Logger LOGGER = LoggerFactory.getLogger(ZipPartMerger.class); + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + record Result(String checksum, long entries, long bytes) {} + + private ZipPartMerger() {} + + static Result merge(List snapshotParts, List parts, Path output, Path scratchDirectory) throws IOException { + Path names = scratchDirectory.resolve("merge-names" + ZipPartWriter.INDEX_SUFFIX); + MessageDigest digest = sha256(); + try (OutputStream file = Files.newOutputStream(output); Sink sink = new Sink(file, digest); NameIndex seen = new NameIndex(names)) { + List ordered = new ArrayList<>(snapshotParts); + ordered.addAll(parts); + long[] bases = new long[ordered.size()]; + for (int i = 0; i < ordered.size(); i++) { + bases[i] = sink.written(); + copyData(ordered.get(i), sink); + } + + Set reserved = new HashSet<>(); + long centralStart = sink.written(); + long entries = 0; + for (int i = 0; i < ordered.size(); i++) { + boolean snapshot = i < snapshotParts.size(); + entries += writeCentral(ordered.get(i), bases[i], snapshot, reserved, seen, sink); + } + long centralSize = sink.written() - centralStart; + sink.write(ZipFormat.endOfArchive(entries, centralSize, centralStart)); + sink.flush(); + LOGGER.debug("Merged {} part(s) into {} entries", ordered.size(), entries); + return new Result(HexFormat.of().formatHex(digest.digest()), entries, sink.written()); + } finally { + Files.deleteIfExists(names); + } + } + + private static void copyData(Path part, Sink sink) throws IOException { + byte[] chunk = new byte[BUFFER_SIZE]; + try (InputStream in = Files.newInputStream(part)) { + int read; + while ((read = in.read(chunk)) != -1) { + sink.write(chunk, 0, read); + } + } + } + + private static long writeCentral(Path part, long base, boolean snapshot, Set reserved, NameIndex seen, Sink sink) throws IOException { + Path index = ZipPartWriter.indexOf(part); + if (!Files.isRegularFile(index)) { + throw new IOException("Archive part " + part + " has no index"); + } + long count = 0; + try (Connection connection = ZipPartIndex.open(index); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT name,lfh_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64 FROM entries ORDER BY id")) { + while (rows.next()) { + String name = rows.getString(1); + if (snapshot) { + if (!name.endsWith("/")) { + DATABASE_SIDECAR_SUFFIXES.forEach(suffix -> reserved.add(name + suffix)); + } + } else if (reserved.contains(name)) { + throw new IOException("Archive part " + part + " contains " + name + ", which the database snapshot owns"); + } + seen.add(name, part); + Entry entry = new Entry(name, rows.getLong(2), 0, rows.getInt(3), rows.getLong(4), rows.getLong(5), rows.getLong(6), + rows.getInt(7), rows.getLong(8), rows.getLong(9), rows.getLong(10), rows.getInt(11) != 0); + sink.write(ZipFormat.centralHeader(entry, base + entry.localOffset())); + count++; + } + } catch (SQLException e) { + throw new IOException("Unable to read the index of archive part " + part, e); + } + return count; + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + private static final class NameIndex implements AutoCloseable { + + private final Connection connection; + private final PreparedStatement insert; + private int pending; + + NameIndex(Path file) throws IOException { + Connection opened = null; + try { + Files.deleteIfExists(file); + opened = ZipPartIndex.open(file); + try (Statement statement = opened.createStatement()) { + statement.execute("CREATE TABLE names(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + opened.setAutoCommit(false); + insert = opened.prepareStatement("INSERT INTO names(name) VALUES(?)"); + connection = opened; + } catch (SQLException | IOException e) { + if (opened != null) { + try { + opened.close(); + } catch (SQLException ignored) { + LOGGER.debug("Unable to close the name index", ignored); + } + } + throw e instanceof IOException io ? io : new IOException("Unable to create the merge name index", e); + } + } + + void add(String name, Path part) throws IOException { + try { + insert.setString(1, name); + insert.executeUpdate(); + if (++pending >= COMMIT_INTERVAL) { + connection.commit(); + pending = 0; + } + } catch (SQLException e) { + throw new IOException("Duplicate or unrecordable entry " + name + " in archive part " + part, e); + } + } + + @Override + public void close() throws IOException { + try { + insert.close(); + connection.close(); + } catch (SQLException e) { + throw new IOException("Unable to close the merge name index", e); + } + } + } + + private static final class Sink extends OutputStream { + + private final OutputStream out; + private final MessageDigest digest; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private int buffered; + private long written; + + Sink(OutputStream out, MessageDigest digest) { + this.out = out; + this.digest = digest; + } + + long written() { + return written; + } + + @Override + public void write(int b) throws IOException { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + digest.update(data, offset, length); + out.write(data, offset, length); + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + written += length; + } + + @Override + public void flush() throws IOException { + if (buffered > 0) { + digest.update(buffer, 0, buffered); + out.write(buffer, 0, buffered); + buffered = 0; + } + } + + @Override + public void close() throws IOException { + flush(); + out.flush(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java new file mode 100644 index 0000000..317aa19 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java @@ -0,0 +1,364 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.zip.CRC32; +import java.util.zip.Deflater; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; + +final class ZipPartWriter implements Closeable { + + static final String PART_SUFFIX = ".part"; + static final String INDEX_SUFFIX = ".idx"; + static final String PARTIAL_SUFFIX = ".partial"; + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final String COLUMNS = "name,lfh_offset,data_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64"; + + private final Path part; + private final Path partial; + private final Path index; + private final ZipCompression compression; + private final FileChannel channel; + private final Connection connection; + private final PreparedStatement insert; + private final PreparedStatement exists; + private final PreparedStatement lookup; + private final PreparedStatement skip; + private final PreparedStatement skipped; + private final Deflater deflater; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private final byte[] chunk = new byte[BUFFER_SIZE]; + private final byte[] compressed = new byte[BUFFER_SIZE]; + private int buffered; + private long position; + private int entries; + private int pendingRows; + private boolean completed; + private boolean closed; + + ZipPartWriter(Path part, ZipCompression compression) throws IOException { + this.part = part; + this.partial = partialOf(part); + this.index = indexOf(part); + this.compression = compression; + this.deflater = new Deflater(Math.max(compression.level(), 1), true); + FileChannel opened = null; + Connection connected = null; + try { + Files.deleteIfExists(index); + opened = FileChannel.open(partial, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.READ, StandardOpenOption.WRITE); + connected = ZipPartIndex.open(index); + try (Statement statement = connected.createStatement()) { + statement.execute("CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, lfh_offset INTEGER NOT NULL, data_offset INTEGER NOT NULL, " + + "method INTEGER NOT NULL, crc INTEGER NOT NULL, csize INTEGER NOT NULL, usize INTEGER NOT NULL, mode INTEGER NOT NULL, " + + "uid INTEGER NOT NULL, gid INTEGER NOT NULL, mtime INTEGER NOT NULL, zip64 INTEGER NOT NULL)"); + statement.execute("CREATE TABLE skipped(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + connected.setAutoCommit(false); + this.insert = connected.prepareStatement("INSERT INTO entries(" + COLUMNS + ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); + this.exists = connected.prepareStatement("SELECT 1 FROM entries WHERE name=?"); + this.lookup = connected.prepareStatement("SELECT " + COLUMNS + " FROM entries WHERE name=?"); + this.skip = connected.prepareStatement("INSERT OR IGNORE INTO skipped(name) VALUES(?)"); + this.skipped = connected.prepareStatement("SELECT 1 FROM skipped WHERE name=?"); + this.channel = opened; + this.connection = connected; + } catch (SQLException | IOException | RuntimeException e) { + deflater.end(); + closeQuietly(connected); + closeQuietly(opened); + deleteQuietly(partial); + deleteQuietly(index); + throw e instanceof IOException io ? io : new IOException("Unable to create archive part " + part, e); + } + } + + static Path partialOf(Path part) { + return part.resolveSibling(part.getFileName() + PARTIAL_SUFFIX); + } + + static Path indexOf(Path part) { + return part.resolveSibling(part.getFileName() + INDEX_SUFFIX); + } + + static void discard(Path part) throws IOException { + Files.deleteIfExists(part); + Files.deleteIfExists(partialOf(part)); + Files.deleteIfExists(indexOf(part)); + } + + int entryCount() { + return entries; + } + + boolean contains(String name) throws IOException { + try { + exists.setString(1, name); + try (ResultSet rows = exists.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void markSkipped(String name) throws IOException { + try { + skip.setString(1, name); + skip.executeUpdate(); + } catch (SQLException e) { + throw new IOException("Unable to update the archive part index", e); + } + } + + boolean wasSkipped(String name) throws IOException { + try { + skipped.setString(1, name); + try (ResultSet rows = skipped.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void addEntry(String name, int mode, long uid, long gid, long modified, long size, InputStream content) throws IOException { + int method = compression.stores(name) ? ZipFormat.STORED : ZipFormat.DEFLATED; + boolean zip64 = size >= ZipFormat.ZIP64_LOCAL_THRESHOLD; + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, method, modified, uid, gid, zip64, 0, 0, 0); + write(header, 0, header.length); + long dataOffset = localOffset + header.length; + + CRC32 crc = new CRC32(); + long total = 0; + long compressedSize = 0; + if (method == ZipFormat.STORED) { + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + write(chunk, 0, read); + total += read; + } + compressedSize = total; + } else { + deflater.reset(); + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + total += read; + deflater.setInput(chunk, 0, read); + compressedSize += drain(false); + } + deflater.finish(); + compressedSize += drain(true); + } + if (total != size) { + throw new EOFException("Entry " + name + " has " + total + " bytes but its header says " + size); + } + if (!zip64 && (compressedSize >= ZipFormat.ZIP64_LIMIT || total >= ZipFormat.ZIP64_LIMIT)) { + throw new IOException("Entry " + name + " outgrew its header, size " + total + ", compressed " + compressedSize); + } + patchSizes(localOffset, nameBytes.length, zip64, crc.getValue(), compressedSize, total); + record(new Entry(name, localOffset, dataOffset, method, crc.getValue(), compressedSize, total, mode, uid, gid, modified, zip64)); + } + + boolean addCopy(String name, String targetName) throws IOException { + Entry target = find(targetName); + if (target == null) { + if (wasSkipped(targetName)) { + return false; + } + throw new IOException("Hard link " + name + " points to a missing entry " + targetName); + } + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, target.method(), target.modified(), target.uid(), target.gid(), target.localZip64(), + target.crc(), target.compressedSize(), target.size()); + flush(); + write(header, 0, header.length); + long remaining = target.compressedSize(); + long from = target.dataOffset(); + while (remaining > 0) { + int length = (int) Math.min(chunk.length, remaining); + ByteBuffer slice = ByteBuffer.wrap(chunk, 0, length); + while (slice.hasRemaining()) { + int read = channel.read(slice, from + slice.position()); + if (read < 0) { + throw new EOFException("Archive part ended while copying " + targetName); + } + } + write(chunk, 0, length); + from += length; + remaining -= length; + } + record(new Entry(name, localOffset, localOffset + header.length, target.method(), target.crc(), target.compressedSize(), target.size(), + target.mode(), target.uid(), target.gid(), target.modified(), target.localZip64())); + return true; + } + + void complete() throws IOException { + flush(); + try { + connection.commit(); + } catch (SQLException e) { + throw new IOException("Unable to save the archive part index", e); + } + release(); + Files.move(partial, part, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + completed = true; + } + + @Override + public void close() { + release(); + if (!completed) { + deleteQuietly(partial); + deleteQuietly(index); + } + } + + private Entry find(String name) throws IOException { + try { + lookup.setString(1, name); + try (ResultSet rows = lookup.executeQuery()) { + if (!rows.next()) { + return null; + } + return new Entry(rows.getString(1), rows.getLong(2), rows.getLong(3), rows.getInt(4), rows.getLong(5), rows.getLong(6), rows.getLong(7), + rows.getInt(8), rows.getLong(9), rows.getLong(10), rows.getLong(11), rows.getInt(12) != 0); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + private void record(Entry entry) throws IOException { + try { + insert.setString(1, entry.name()); + insert.setLong(2, entry.localOffset()); + insert.setLong(3, entry.dataOffset()); + insert.setInt(4, entry.method()); + insert.setLong(5, entry.crc()); + insert.setLong(6, entry.compressedSize()); + insert.setLong(7, entry.size()); + insert.setInt(8, entry.mode()); + insert.setLong(9, entry.uid()); + insert.setLong(10, entry.gid()); + insert.setLong(11, entry.modified()); + insert.setInt(12, entry.localZip64() ? 1 : 0); + insert.executeUpdate(); + entries++; + if (++pendingRows >= COMMIT_INTERVAL) { + connection.commit(); + pendingRows = 0; + } + } catch (SQLException e) { + throw new IOException("Unable to record " + entry.name() + " in the archive part index", e); + } + } + + private long drain(boolean finish) throws IOException { + long produced = 0; + while (finish ? !deflater.finished() : !deflater.needsInput()) { + int length = deflater.deflate(compressed); + if (length > 0) { + write(compressed, 0, length); + produced += length; + } + } + return produced; + } + + private void patchSizes(long localOffset, int nameLength, boolean zip64, long crc, long compressedSize, long size) throws IOException { + flush(); + writeAt(localOffset + ZipFormat.CRC_OFFSET, ZipFormat.localSizes(zip64, crc, compressedSize, size)); + if (zip64) { + writeAt(localOffset + ZipFormat.LOCAL_HEADER_SIZE + nameLength, ZipFormat.zip64LocalExtra(compressedSize, size)); + } + } + + private void writeAt(long at, byte[] data) throws IOException { + ByteBuffer source = ByteBuffer.wrap(data); + long written = at; + while (source.hasRemaining()) { + written += channel.write(source, written); + } + } + + private void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + ByteBuffer source = ByteBuffer.wrap(data, offset, length); + while (source.hasRemaining()) { + channel.write(source); + } + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + position += length; + } + + private void flush() throws IOException { + if (buffered > 0) { + ByteBuffer source = ByteBuffer.wrap(buffer, 0, buffered); + while (source.hasRemaining()) { + channel.write(source); + } + buffered = 0; + } + } + + private void release() { + if (closed) { + return; + } + closed = true; + deflater.end(); + closeQuietly(skipped); + closeQuietly(skip); + closeQuietly(lookup); + closeQuietly(exists); + closeQuietly(insert); + closeQuietly(connection); + closeQuietly(channel); + } + + private static void closeQuietly(AutoCloseable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (Exception e) { + return; + } + } + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + return; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 2ce92ec..00b03a2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -12,6 +12,7 @@ mediagarrd: backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} + compression-level: ${MEDIAGARRD_COMPRESSION_LEVEL:1} helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 8f0185b..40a1715 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -27,6 +27,7 @@ void bindsApplicationProperties() { assertEquals(10, properties.getRetentionCount()); assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); + assertEquals(1, properties.getCompressionLevel()); assertEquals("alpine:3", properties.getHelperImage()); assertEquals("MediaGarrd/Server", properties.getUpdateRepository()); assertEquals("http://127.0.0.1:1", properties.getGithubApiBaseUrl()); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java new file mode 100644 index 0000000..c4fac32 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java @@ -0,0 +1,102 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Date; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(120) +class ArchiveInteropTest { + + private static final long MTIME = 1_700_000_001_000L; + + @TempDir + Path dir; + + private Path archive() throws Exception { + Item folder = dir("data/"); + folder.entry().setMode(040750); + folder.entry().setModTime(new Date(MTIME)); + folder.entry().setUserId(1000); + folder.entry().setGroupId(1001); + Item secret = file("data/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setModTime(new Date(MTIME)); + secret.entry().setUserId(1000); + secret.entry().setGroupId(1001); + Item text = file("data/café ünï.txt", "compressible ".repeat(1000)); + text.entry().setModTime(new Date(MTIME + 2000)); + text.entry().setUserId(5); + text.entry().setGroupId(6); + Item empty = dir("data/empty/"); + empty.entry().setModTime(new Date(MTIME)); + Item symlink = link("data/latest", TarConstants.LF_SYMLINK, "id_rsa"); + symlink.entry().setModTime(new Date(MTIME)); + Item hardLink = link("data/id_rsa.bak", TarConstants.LF_LINK, "data/id_rsa"); + Path part = dir.resolve("0.part"); + ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink), "/srv/data", part, new ZipCompression(1)); + return ArchiveTestSupport.merge(dir, part); + } + + @Test + void bsdtarRestoresContentsModesTimesAndSymlinksFromSeekableAndStreamedArchives() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + for (boolean streamed : new boolean[] {false, true}) { + Path target = Files.createDirectories(dir.resolve(streamed ? "streamed" : "seekable")); + if (streamed) { + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", target.toString()); + } else { + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + } + + Path data = target.resolve("srv/data"); + assertEquals("key", Files.readString(data.resolve("id_rsa"))); + assertEquals("key", Files.readString(data.resolve("id_rsa.bak"))); + assertEquals("compressible ".repeat(1000), Files.readString(data.resolve("café ünï.txt"), StandardCharsets.UTF_8)); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(data.resolve("id_rsa")))); + assertEquals("rwxr-x---", PosixFilePermissions.toString(Files.getPosixFilePermissions(data))); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data.resolve("id_rsa")).toMillis() / 1000); + assertEquals((MTIME + 2000) / 1000, Files.getLastModifiedTime(data.resolve("café ünï.txt")).toMillis() / 1000); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data).toMillis() / 1000); + assertTrue(Files.isSymbolicLink(data.resolve("latest"))); + assertEquals("id_rsa", Files.readSymbolicLink(data.resolve("latest")).toString()); + assertTrue(Files.isDirectory(data.resolve("empty"))); + } + } + + @Test + void listingsShowNumericOwnersFromTheLocalHeaders() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + + for (String listing : new String[] { + ArchiveTestSupport.run(null, "bsdtar", "-tvf", archive.toString(), "--numeric-owner"), + ArchiveTestSupport.run(archive, "bsdtar", "-tvf", "-", "--numeric-owner")}) { + assertTrue(listing.matches("(?s).*-rw-------\\s+\\d+\\s+1000\\s+1001\\s+3\\s.*id_rsa\\n.*"), listing); + assertTrue(listing.matches("(?s).*\\s5\\s+6\\s.*caf.*"), listing); + assertTrue(listing.matches("(?s).*drwxr-x---\\s+\\d+\\s+1000\\s+1001.*srv/data/\\n.*"), listing); + } + } + + @Test + void everyReaderAcceptsTheArchive() throws Exception { + ZipPartWriterTest.verifyWithTools(archive(), 6); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java new file mode 100644 index 0000000..09b32d9 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java @@ -0,0 +1,144 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.GeneratedTar.Spec; + +@Tag("scale") +@Timeout(value = 60, unit = java.util.concurrent.TimeUnit.MINUTES) +class ArchiveScaleTest { + + private static final long FOUR_GIB = 0x100000000L; + private static final byte[] SMALL = "small file content\n".getBytes(java.nio.charset.StandardCharsets.UTF_8); + + @TempDir + Path dir; + + private Thread sampler; + private volatile boolean sampling; + private volatile long peakHeap; + private long started; + + @BeforeEach + void startSampling() { + assumeTrue(Runtime.getRuntime().maxMemory() <= 128L * 1024 * 1024, "run through scaleTest, which caps the heap"); + started = System.nanoTime(); + sampling = true; + sampler = new Thread(() -> { + while (sampling) { + Runtime runtime = Runtime.getRuntime(); + peakHeap = Math.max(peakHeap, runtime.totalMemory() - runtime.freeMemory()); + try { + Thread.sleep(20); + } catch (InterruptedException e) { + return; + } + } + }, "heap-sampler"); + sampler.setDaemon(true); + sampler.start(); + } + + @AfterEach + void report(org.junit.jupiter.api.TestInfo info) throws Exception { + sampling = false; + sampler.join(); + System.out.printf("SCALE %s: %d s, max heap %d MiB, peak sampled used heap %d MiB, tmpdir %s%n", info.getDisplayName(), + (System.nanoTime() - started) / 1_000_000_000L, Runtime.getRuntime().maxMemory() >> 20, peakHeap >> 20, System.getProperty("java.io.tmpdir")); + } + + private static byte[] randomBlock() { + byte[] block = new byte[64 * 1024]; + new Random(42).nextBytes(block); + return block; + } + + private Path archive(Iterator specs, String hostPath, int level) throws Exception { + Path part = dir.resolve("0.part"); + try (var tar = new GeneratedTar(specs)) { + ServiceBackupRunner.archive(tar, hostPath, part, new ZipCompression(level)); + } + System.out.printf("SCALE part %d MiB%n", Files.size(part) >> 20); + Path merged = dir.resolve("merged.zip"); + ZipPartMerger.Result result = ZipPartMerger.merge(List.of(), List.of(part), merged, dir); + Files.delete(part); + Files.delete(ZipPartWriter.indexOf(part)); + System.out.printf("SCALE archive %d MiB, %d entries, sha256 %s%n", Files.size(merged) >> 20, result.entries(), result.checksum()); + return merged; + } + + @Test + void threeHundredThousandSmallFilesBuildAnArchiveReadableByEveryTool() throws Exception { + int count = 300_000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.directory("many/")), + IntStream.range(0, count).mapToObj(i -> Spec.file("many/dir" + (i % 100) + "/file-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/many", 1); + + ZipPartWriterTest.verifyWithTools(merged, count + 1); + } + + @Test + void aStoredEntryJustUnderFourGiBUsesALocalZip64ExtraWithClassicCentralSizes() throws Exception { + long size = 0xF0000000L + 0x100000L; + + Path merged = archive(List.of(Spec.file("movies/film.mkv", size, randomBlock())).iterator(), "/srv/movies", 1); + + assertTrue(size < 0xFFFFFFFFL); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + @Test + void aStoredEntryOverFourGiBFollowedBySmallEntriesPushesOffsetsPastFourGiB() throws Exception { + long size = FOUR_GIB + 300_000_000L; + int small = 1000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.file("movies/big.mkv", size, randomBlock())), + IntStream.range(0, small).mapToObj(i -> Spec.file("movies/small-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/movies", 1); + + assertTrue(Files.size(merged) > FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, small + 1); + extractOne(merged, "srv/movies/small-999.txt", new String(SMALL, java.nio.charset.StandardCharsets.UTF_8)); + } + + @Test + void aDeflatedEntryOverFourGiBOfRepeatedBytesOverflowsOnlyTheUncompressedSize() throws Exception { + long size = FOUR_GIB + 200_000_000L; + + Path merged = archive(List.of(Spec.file("logs/huge.log", size, new byte[64 * 1024])).iterator(), "/srv/logs", 1); + + assertTrue(Files.size(merged) < FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + private void extractOne(Path archive, String name, String expected) throws IOException, InterruptedException { + if (ArchiveTestSupport.available("bsdtar")) { + assertEquals(expected, ArchiveTestSupport.run(null, "bsdtar", "-xOf", archive.toString(), name)); + assertEquals(expected, ArchiveTestSupport.run(archive, "bsdtar", "-xOf", "-", name)); + } + if (ArchiveTestSupport.available("unzip")) { + assertEquals(expected, ArchiveTestSupport.run(null, "unzip", "-p", archive.toString(), name)); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java new file mode 100644 index 0000000..066fd67 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java @@ -0,0 +1,92 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +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.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; + +final class ArchiveTestSupport { + + private ArchiveTestSupport() {} + + static Path merge(Path scratch, Path... parts) throws IOException { + return merge(scratch, List.of(), List.of(parts)); + } + + static Path merge(Path scratch, List snapshotParts, List parts) throws IOException { + Path archive = scratch.resolve("merged-" + System.nanoTime() + ".zip"); + ZipPartMerger.merge(snapshotParts, parts, archive, scratch); + return archive; + } + + static Map contents(Path zipPath) throws IOException { + Map entries = new TreeMap<>(); + try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { + for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { + try (InputStream in = zip.getInputStream(entry)) { + entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } + return entries; + } + + static Map partContents(Path scratch, Path... parts) throws IOException { + return contents(merge(scratch, parts)); + } + + static boolean available(String tool) { + try { + Process process = new ProcessBuilder(tool, "--help").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); + process.waitFor(20, TimeUnit.SECONDS); + return true; + } catch (IOException | InterruptedException e) { + return false; + } + } + + record Output(String text, long lines) {} + + static String run(Path stdin, String... command) throws IOException, InterruptedException { + return runCounting(stdin, command).text(); + } + + static Output runCounting(Path stdin, String... command) throws IOException, InterruptedException { + Path output = Files.createTempFile("tool-output", ".txt"); + try { + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()); + if (stdin != null) { + builder.redirectInput(stdin.toFile()); + } + Process process = builder.start(); + if (!process.waitFor(30, TimeUnit.MINUTES)) { + process.destroyForcibly(); + throw new IOException("Timed out: " + String.join(" ", command)); + } + String text = head(output); + assertEquals(0, process.exitValue(), String.join(" ", command) + "\n" + text); + try (var lines = Files.lines(output, StandardCharsets.ISO_8859_1)) { + return new Output(text, lines.count()); + } + } finally { + Files.deleteIfExists(output); + } + } + + private static String head(Path file) throws IOException { + try (InputStream in = Files.newInputStream(file)) { + return new String(in.readNBytes(1_000_000), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 9a1cfa6..1fc30cc 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -7,7 +7,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; -import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.contents; +import static wellatleastitried.mediagarrdServer.service.ArchiveTestSupport.contents; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; @@ -102,29 +103,37 @@ void mergeKeepsMetadataAndIncludesHardLinkParts() throws Exception { } @Test - void overlappingPathsAcrossServicesAppearOnce() throws Exception { + void aDuplicateNameAcrossPartsFailsTheMergeAndLeavesNoArchive() throws Exception { Path run = service.createRunDirectory(); part(run, "a", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); part(run, "b", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); - BackupArchive archive = service.createArchive(run); + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); - assertEquals(Map.of("srv/shared/", "", "srv/shared/x", "1"), contents(archive.path())); + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + } + assertFalse(Files.exists(run.resolve("merge-names.idx"))); } @Test - void directoriesPrecedeTheirContentsAcrossParts() throws Exception { + void partsAreWrittenInSortedPathOrderWithTheSnapshotFirst() throws Exception { + db.saveSetting("backup_root", "/marker"); + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); Path run = service.createRunDirectory(); Item restricted = dir("a/"); restricted.entry().setMode(040700); - part(run, "child", 0, "/srv/a/b", tar(dir("b/"), file("b/x", "1"))); - part(run, "parent", 0, "/srv/a", tar(restricted, dir("a/b/"), file("a/b/x", "1"), file("a/y", "2"))); + part(run, "second", 0, "/srv/b", tar(dir("b/"), file("b/x", "1"))); + part(run, "first", 1, "/srv/a", tar(restricted, dir("a/c/"), file("a/c/x", "1"), file("a/y", "2"))); + part(run, "first", 0, "/srv/a0", tar(file("a0", "0"))); + assertEquals(COMPLETED, new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run).status()); BackupArchive archive = service.createArchive(run); try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { List order = java.util.Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList(); - assertEquals(List.of("srv/a/", "srv/a/b/", "srv/a/b/x", "srv/a/y"), order); + assertEquals(List.of("srv/zzz/mediagarrd.db", "srv/a0", "srv/a/", "srv/a/c/", "srv/a/c/x", "srv/a/y", "srv/b/", "srv/b/x"), order); assertEquals(UnixStat.DIR_FLAG | 0700, zip.getEntry("srv/a/").getUnixMode()); } } @@ -141,7 +150,7 @@ void ignoresStrayFilesInRunDirectory() throws Exception { @Test void failedMergeLeavesNoArchiveBehind() throws Exception { Path run = service.createRunDirectory(); - Files.writeString(run.resolve("corrupt.zip"), "not a zip"); + Files.writeString(run.resolve("corrupt.part"), "not a part"); assertThrows(IllegalStateException.class, () -> service.createArchive(run)); @@ -289,22 +298,23 @@ void startupCleanupRemovesStaleArtifacts() throws Exception { } @Test - void theDatabaseSnapshotAlwaysWinsOverServiceCopiesOfTheSamePath() throws Exception { + void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throws Exception { db.saveSetting("backup_root", "/marker"); DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); String entry = "srv/mediagarrd/db/mediagarrd.db"; when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/" + entry)); Path run = service.createRunDirectory(); - part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar( + var excluded = DatabaseSnapshotService.reservedNames(Path.of("/" + entry)); + Path directory = Files.createDirectories(run.resolve("Mediagarrd")); + ServiceBackupRunner.archive(tar( dir("db/"), file("db/mediagarrd.db", "LIVE COPY"), file("db/mediagarrd.db-journal", "stale journal"), file("db/mediagarrd.db-wal", "wal"), file("db/mediagarrd.db-shm", "shm"), - file("db/notes.txt", "keep"))); - part(run, "0radarr", 0, "/srv/mediagarrd/db/mediagarrd.db", tar(file("mediagarrd.db", "LIVE COPY 2"))); + file("db/notes.txt", "keep")), "/srv/mediagarrd/db", directory.resolve("0.part"), new ZipCompression(1), excluded, java.util.Set.of()); - var snapshot = new DatabaseSnapshotService(db, hostPaths).snapshot(run); + var snapshot = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); BackupArchive archive = service.createArchive(run); assertEquals(COMPLETED, snapshot.status()); @@ -323,6 +333,84 @@ void theDatabaseSnapshotAlwaysWinsOverServiceCopiesOfTheSamePath() throws Except } } + @Test + void aLiveDatabaseCopyThatSlippedPastTheExclusionFailsTheMerge() throws Exception { + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); + Path run = service.createRunDirectory(); + part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar(dir("db/"), file("db/mediagarrd.db-wal", "wal"))); + new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + } + } + + @Test + @Timeout(30) + void carriesAChecksumOfTheFinalFileComputedWhileWriting() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x".repeat(100_000)))); + part(run, "plex", 0, "/srv/plex/movie.mkv", tar(file("movie.mkv", "y".repeat(50_000)))); + + BackupArchive archive = service.createArchive(run); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + assertEquals(java.util.HexFormat.of().formatHex(expected), archive.checksum()); + assertEquals(archive.checksum(), archive.resolvedChecksum()); + assertEquals(Files.size(archive.path()), archive.sizeBytes()); + assertFalse(Files.exists(archive.path().resolveSibling(archive.fileName() + ".tmp"))); + } + + @Test + @Timeout(30) + void storesTheChecksumFromWritingInTheBackupRecord() throws Exception { + BackupArchive archive = createArchive(); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + tempDir.resolve("mediagarrd.db")); + var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT checksum FROM backups")) { + assertEquals(java.util.HexFormat.of().formatHex(expected), result.getString(1)); + } + } + + @Test + @Timeout(30) + void mergesPartsWithMixedStoredAndDeflatedEntries() throws Exception { + String text = "compressible text ".repeat(2000); + Path run = service.createRunDirectory(); + partWith(run, "stored", 0, "/srv/stored", tar(dir("stored/"), file("stored/a.txt", text)), 0); + partWith(run, "mixed", 0, "/srv/mixed", tar(file("mixed/b.txt", text), file("mixed/c.mkv", text)), 9); + partWith(run, "fast", 0, "/srv/fast", tar(file("fast/d.txt", text)), 1); + + BackupArchive archive = service.createArchive(run); + + assertEquals(text, contents(archive.path()).get("srv/stored/a.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/b.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/c.mkv")); + assertEquals(text, contents(archive.path()).get("srv/fast/d.txt")); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/stored/a.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/mixed/b.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/mixed/c.mkv").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/fast/d.txt").getMethod()); + for (ZipArchiveEntry entry : java.util.Collections.list(zip.getEntries())) { + assertFalse(entry.getGeneralPurposeBit().usesDataDescriptor(), entry.getName()); + } + } + java.util.Map streamed = new java.util.TreeMap<>(); + try (var in = new org.apache.commons.compress.archivers.zip.ZipArchiveInputStream(Files.newInputStream(archive.path()))) { + ZipArchiveEntry entry; + while ((entry = in.getNextEntry()) != null) { + streamed.put(entry.getName(), new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + } + } + assertEquals(contents(archive.path()), streamed); + } + @Test void archivesWithoutASnapshotPartStillMerge() throws Exception { Path run = service.createRunDirectory(); @@ -333,9 +421,14 @@ void archivesWithoutASnapshotPartStillMerge() throws Exception { assertEquals(List.of("srv/radarr"), List.copyOf(contents(archive.path()).keySet())); } + private static void partWith(Path run, String service, int index, String hostPath, java.io.InputStream tar, int level) throws Exception { + Path directory = Files.createDirectories(run.resolve(service)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(level)); + } + private static void part(Path run, String service, int index, String hostPath, java.io.InputStream tar) throws Exception { Path directory = Files.createDirectories(run.resolve(service)); - ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(1)); } private BackupArchive createArchive() throws Exception { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java new file mode 100644 index 0000000..41fa227 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java @@ -0,0 +1,318 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(60) +class BackupCopyRoundsTest { + + private static final BackupArchive ARCHIVE = new BackupArchive("archive-1", "archive-1.zip", Path.of("archive-1.zip"), 1, Instant.EPOCH); + private static final Path DATABASE = Path.of("/srv/app/db/mediagarrd.db"); + + @TempDir + Path run; + + private final DockerService docker = mock(DockerService.class); + private final BackupArchiveService archives = mock(BackupArchiveService.class); + private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); + private final DatabaseService db = mock(DatabaseService.class); + private final Map> sources = new HashMap<>(); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService( + new ServiceBackupRunner(docker, new ZipCompression(1)), archives, mock(BackupScheduleService.class), snapshots, db, mock(RunStatusBroadcaster.class)); + + @BeforeEach + void setUp() throws Exception { + when(archives.createRunDirectory()).thenReturn(run); + when(archives.createArchive(run)).thenReturn(ARCHIVE); + when(docker.containerFor(any())).thenReturn("cid"); + when(docker.copyFrom(eq("cid"), anyString())).thenAnswer(invocation -> { + Supplier source = sources.get(invocation.getArgument(1)); + if (source == null) { + throw new IllegalStateException("no such path"); + } + return source.get(); + }); + snapshotSucceeds(); + } + + @AfterEach + void tearDown() { + orchestrator.shutdownRunnerExecutor(); + } + + private void snapshotSucceeds() { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", COMPLETED), DATABASE)); + } + + private static BackupServiceResult result(String name, String status) { + return new BackupServiceResult(null, status, "start", "end", name, null); + } + + private void serve(String path, Item... items) { + sources.put(path, () -> { + try { + return tar(items); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + } + + private BackupRunResult runBackup(ServiceDefinition... services) { + when(db.fetchServices()).thenReturn(List.of(services)); + return orchestrator.runBackup(); + } + + private Map part(String service, int index) throws IOException { + return ArchiveTestSupport.partContents(run, run.resolve(service).resolve(index + ServiceBackupRunner.PART_SUFFIX)); + } + + private static BackupServiceResult resultOf(BackupRunResult run, String service) { + return run.serviceResults().stream().filter(r -> r.serviceName().equals(service)).findFirst().orElseThrow(); + } + + @Test + void aNestedPathIsSkippedWhenItsOwnerCopiedItAndCountsAsCompleted() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media", "/srv/media/config")); + serve("/srv/media", dir("media/"), file("media/a", "1"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "media").status()); + verify(docker, times(1)).copyFrom(eq("cid"), eq("/srv/media")); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + assertEquals(Map.of("srv/media/", "", "srv/media/a", "1", "srv/media/config/", "", "srv/media/config/c", "2"), part("media", 0)); + assertFalse(Files.exists(run.resolve("media/1.part"))); + } + + @Test + void aNestedPathInAnotherServiceIsSkippedAndReportedByItsOwnOutcome() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + serve("/srv/media", dir("media/"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertNull(resultOf(result, "config").errorMessage()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + } + + @Test + void whenTheOwnerFailsTheCoveredPathIsCopiedOnItsOwn() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/media/config", dir("config/"), file("config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "media").status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertEquals(Map.of("srv/media/config/", "", "srv/media/config/c", "2"), part("config", 0)); + } + + @Test + void aCoveredPathThatFailsOnItsOwnAfterAFailedOwnerFailsOnlyItsService() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + ServiceDefinition other = new ServiceDefinition("other", List.of("/srv/other")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/other", dir("other/")); + + BackupRunResult result = runBackup(media, config, other); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "config").status()); + assertEquals("/srv/media/config: no such path", resultOf(result, "config").errorMessage()); + } + + @Test + void aSymbolicLinkAtTheCoveredPathIsNotStoredSoTheCoveredPathIsCopiedItself() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/a")); + ServiceDefinition linked = new ServiceDefinition("linked", List.of("/srv/a/link")); + serve("/srv/a", dir("a/"), link("a/link", TarConstants.LF_SYMLINK, "/mnt/x")); + serve("/srv/a/link", dir("link/"), file("link/data", "real")); + + BackupRunResult result = runBackup(media, linked); + + assertEquals(COMPLETED, result.status()); + verify(docker).copyFrom("cid", "/srv/a/link"); + assertEquals(Map.of("srv/a/link/", "", "srv/a/link/data", "real"), part("linked", 0)); + assertFalse(part("media", 0).containsKey("srv/a/link")); + } + + @Test + void aChainOfNestedPathsFallsBackOneRoundAtATimeWithoutDuplicates() throws Exception { + ServiceDefinition outer = new ServiceDefinition("outer", List.of("/srv/a")); + ServiceDefinition middle = new ServiceDefinition("middle", List.of("/srv/a/b")); + ServiceDefinition inner = new ServiceDefinition("inner", List.of("/srv/a/b/c")); + sources.put("/srv/a", () -> { + throw new IllegalStateException("outer broke"); + }); + serve("/srv/a/b", dir("b/"), dir("b/c/"), file("b/c/x", "1")); + + BackupRunResult result = runBackup(outer, middle, inner); + + assertEquals(FAILED, resultOf(result, "outer").status()); + assertEquals(COMPLETED, resultOf(result, "middle").status()); + assertEquals(COMPLETED, resultOf(result, "inner").status()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/a/b/c")); + assertEquals(3, part("middle", 0).size()); + } + + @Test + void ofSeveralServicesWithTheSamePathOnlyTheFirstByNameCopiesIt() throws Exception { + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + serve("/srv/shared", dir("shared/"), file("shared/x", "1")); + + BackupRunResult result = runBackup(b, a, c); + + assertEquals(COMPLETED, result.status()); + verify(docker, times(1)).copyFrom("cid", "/srv/shared"); + assertTrue(Files.exists(run.resolve("a/0.part"))); + assertFalse(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void whenTheOwnerOfSeveralEqualPathsFailsExactlyOneOtherCopiesIt() throws Exception { + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + int[] calls = {0}; + sources.put("/srv/shared", () -> { + if (calls[0]++ == 0) { + throw new IllegalStateException("first broke"); + } + try { + return tar(dir("shared/"), file("shared/x", "1")); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + BackupRunResult result = runBackup(a, b, c); + + assertEquals(2, calls[0]); + assertEquals(FAILED, resultOf(result, "a").status()); + assertEquals(COMPLETED, resultOf(result, "b").status()); + assertEquals(COMPLETED, resultOf(result, "c").status()); + assertTrue(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void aServiceKeepsItsOwnPathsWhileOneOfThemIsCoveredElsewhere() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition mixed = new ServiceDefinition("mixed", List.of("/srv/media/config", "/etc/mixed")); + serve("/srv/media", dir("media/"), dir("media/config/")); + serve("/etc/mixed", dir("mixed/"), file("mixed/m", "m")); + + BackupRunResult result = runBackup(media, mixed); + + assertEquals(COMPLETED, resultOf(result, "mixed").status()); + assertFalse(Files.exists(run.resolve("mixed/0.part"))); + assertEquals(Map.of("etc/mixed/", "", "etc/mixed/m", "m"), part("mixed", 1)); + } + + @Test + void theDatabaseAndItsSidecarsAreLeftOutOfServiceCopiesWhenTheSnapshotSucceeded() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal"), + file("app/db/mediagarrd.db-shm", "shm"), file("app/db/mediagarrd.db-journal", "j"), link("app/db/hard", TarConstants.LF_LINK, "app/db/mediagarrd.db"), + file("app/db/notes", "keep")); + + runBackup(app); + + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/notes", "keep"), part("app", 0)); + } + + @Test + void theLiveDatabaseIsKeptWhenTheSnapshotFails() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", FAILED), DATABASE)); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/mediagarrd.db", "live", "srv/app/db/mediagarrd.db-wal", "wal"), part("app", 0)); + } + + @Test + void nothingIsExcludedWhenTheSnapshotThrows() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenThrow(new IllegalStateException("docker down")); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), file("app/mediagarrd.db", "live")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/mediagarrd.db", "live"), part("app", 0)); + verify(archives, atLeastOnce()).createArchive(run); + } + + @Test + void theSnapshotIsTakenOnceBeforeAnyCopyStarts() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/")); + + runBackup(app); + + var order = org.mockito.Mockito.inOrder(snapshots, docker); + order.verify(snapshots).snapshotWithHostPath(run); + order.verify(docker).copyFrom("cid", "/srv/app"); + verify(snapshots, times(1)).snapshotWithHostPath(run); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index a999d67..145ad75 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -21,6 +21,7 @@ import java.nio.file.Path; import java.time.Instant; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -59,7 +60,7 @@ class BackupOrchestratorServiceTest { void setUp() { when(archives.createRunDirectory()).thenReturn(RUN_DIR); when(archives.createArchive(RUN_DIR)).thenReturn(ARCHIVE); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(COMPLETED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(COMPLETED)); } @AfterEach @@ -110,10 +111,10 @@ void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); when(schedule.dueNow()).thenReturn(true); @@ -161,7 +162,7 @@ void partialWhenSomeServicesFail() { @Test void partialWhenOnlyTheDatabaseSnapshotFails() { givenResults(COMPLETED, COMPLETED); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); BackupRunResult result = orchestrator.runBackup(); @@ -175,7 +176,7 @@ void partialWhenOnlyTheDatabaseSnapshotFails() { @Test void snapshotFailureIsAddedToTheServiceErrors() { givenResults(COMPLETED, FAILED); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); BackupRunResult result = orchestrator.runBackup(); @@ -186,7 +187,7 @@ void snapshotFailureIsAddedToTheServiceErrors() { @Test void aThrowingSnapshotStillProducesAPartialArchive() { givenResults(COMPLETED, COMPLETED); - when(snapshots.snapshot(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); BackupRunResult result = orchestrator.runBackup(); @@ -197,13 +198,14 @@ void aThrowingSnapshotStillProducesAPartialArchive() { } @Test - void snapshotRunsBeforeTheArchiveIsCreated() { + void snapshotRunsBeforeTheCopiesAndTheArchiveIsCreatedLast() { givenResults(COMPLETED, COMPLETED); orchestrator.runBackup(); - var order = inOrder(snapshots, archives); - order.verify(snapshots).snapshot(RUN_DIR); + var order = inOrder(snapshots, runner, archives); + order.verify(snapshots).snapshotWithHostPath(RUN_DIR); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), eq(RUN_DIR), any(), any()); order.verify(archives).createArchive(RUN_DIR); } @@ -222,7 +224,6 @@ void skipsArchiveWhenEveryServiceFails() { assertTrue(e.getMessage().contains("radarr: boom\nsonarr: boom")); verify(archives, never()).createArchive(any()); - verify(snapshots, never()).snapshot(any()); verify(archives).removeRunDirectory(RUN_DIR); assertFalse(orchestrator.isRunning()); @@ -238,8 +239,8 @@ void skipsArchiveWhenEveryServiceFails() { @Test void runnerExceptionsBecomeFailedResults() { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); - when(runner.run(RADARR, RUN_DIR)).thenThrow(new IllegalStateException("crashed")); - when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", COMPLETED)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, COMPLETED)); BackupRunResult result = orchestrator.runBackup(); @@ -264,10 +265,10 @@ void rejectsConcurrentRuns() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -291,10 +292,10 @@ void configChangesAreRejectedDuringABackupRun() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -343,7 +344,7 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { var order = inOrder(broadcaster, runner, db); order.verify(db).fetchServices(); order.verify(broadcaster).publishStarted(any()); - order.verify(runner, org.mockito.Mockito.atLeastOnce()).run(any(), any()); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), any(), any(), any()); order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); @@ -455,10 +456,10 @@ void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -503,12 +504,22 @@ void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { private void givenResults(String radarrStatus, String sonarrStatus) { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); - when(runner.run(RADARR, RUN_DIR)).thenReturn(result("radarr", radarrStatus)); - when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", sonarrStatus)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, radarrStatus)); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, sonarrStatus)); } - private static BackupServiceResult snapshotResult(String status) { - return result(SNAPSHOT, status); + private static DatabaseSnapshotService.Outcome snapshotOutcome(String status) { + return new DatabaseSnapshotService.Outcome(result(SNAPSHOT, status), Path.of("/srv/mediagarrd/db/mediagarrd.db")); + } + + private static ServiceBackupRunner.ServiceRound round(ServiceDefinition service, String status) { + String path = service.paths().get(0); + return switch (status) { + case COMPLETED -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()))); + case PARTIAL -> new ServiceBackupRunner.ServiceRound(null, List.of( + new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()), new ServiceBackupRunner.PathCopy(1, path, false, "boom", Set.of()))); + default -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, false, "boom", Set.of()))); + }; } private static BackupServiceResult result(String name, String status) { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java new file mode 100644 index 0000000..facaf5b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java @@ -0,0 +1,97 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +@Timeout(120) +class CoveredSymlinkTest { + + private static final ZipCompression COMPRESSION = new ZipCompression(1); + + @TempDir + Path dir; + + private Path owner(String name, ServiceBackupRunner.ArchiveResult[] result, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve(name + ".part"); + result[0] = ServiceBackupRunner.archive(tar(items), "/srv/a", part, COMPRESSION, Set.of(), Set.of("srv/a/covered")); + return part; + } + + private Path fallback(String hostPath, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve("fallback.part"); + ServiceBackupRunner.archive(tar(items), hostPath, part, COMPRESSION, Set.of(), Set.of()); + return part; + } + + private void extract(Path archive, Path target) throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Files.createDirectories(target); + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + Path streamed = dir.resolve("streamed"); + Files.createDirectories(streamed); + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", streamed.toString()); + assertEquals(Files.isSymbolicLink(target.resolve("srv/a/other")), Files.isSymbolicLink(streamed.resolve("srv/a/other"))); + } + + @Test + void aSymlinkToAFileAtACoveredPathIsLeftOutAndTheRealFileTakesItsName() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/x"), + link("a/other", TarConstants.LF_SYMLINK, "keep")); + Path fallbackPart = fallback("/srv/a/covered", file("covered", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertEquals("real", contents.get("srv/a/covered")); + assertEquals("keep", contents.get("srv/a/other")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertEquals("real", Files.readString(target.resolve("srv/a/covered"))); + assertFalse(Files.isSymbolicLink(target.resolve("srv/a/covered"))); + assertTrue(Files.isSymbolicLink(target.resolve("srv/a/other"))); + assertEquals("keep", Files.readSymbolicLink(target.resolve("srv/a/other")).toString()); + } + + @Test + void aSymlinkToADirectoryAtACoveredPathIsLeftOutAndTheRealDirectoryIsRestored() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/dir")); + Path fallbackPart = fallback("/srv/a/covered", dir("covered/"), file("covered/data", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertFalse(contents.containsKey("srv/a/covered")); + assertTrue(contents.containsKey("srv/a/covered/")); + assertEquals("real", contents.get("srv/a/covered/data")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertTrue(Files.isDirectory(target.resolve("srv/a/covered"), java.nio.file.LinkOption.NOFOLLOW_LINKS)); + assertEquals("real", Files.readString(target.resolve("srv/a/covered/data"))); + } + + @Test + void aSymlinkAtANameThatIsNotCoveredIsStillStoredAsASymlink() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), link("a/other", TarConstants.LF_SYMLINK, "/mnt/x")); + + assertEquals("/mnt/x", ArchiveTestSupport.partContents(dir, ownerPart).get("srv/a/other")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java index 5ee1cb7..fba6743 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -46,7 +46,7 @@ void setUp() throws Exception { db = new DatabaseService(properties); hostPaths = mock(DatabaseHostPathResolver.class); when(hostPaths.resolve(db.databaseFile())).thenReturn(HOST_DATABASE); - snapshots = new DatabaseSnapshotService(db, hostPaths); + snapshots = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)); run = Files.createDirectories(tempDir.resolve("run")); } @@ -62,7 +62,7 @@ void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { assertEquals(COMPLETED, result.status()); assertEquals(DatabaseSnapshotService.SERVICE_NAME, result.serviceName()); Path part = run.resolve(DatabaseSnapshotService.PART_DIRECTORY).resolve(DatabaseSnapshotService.PART_NAME); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(tempDir, part)).get()) { assertEquals(List.of("srv/mediagarrd/db/mediagarrd.db"), Collections.list(zip.getEntries()).stream().map(ZipArchiveEntry::getName).toList()); ZipArchiveEntry entry = zip.getEntry("srv/mediagarrd/db/mediagarrd.db"); assertEquals(0640, entry.getUnixMode() & 07777); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java new file mode 100644 index 0000000..a1330cd --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java @@ -0,0 +1,107 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.Iterator; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; + +final class GeneratedTar extends InputStream { + + record Spec(String name, long size, byte[] pattern) { + + static Spec directory(String name) { + return new Spec(name, -1, null); + } + + static Spec file(String name, long size, byte[] pattern) { + return new Spec(name, size, pattern); + } + } + + private static final int BLOCK = 512; + + private final Iterator specs; + private final byte[] header = new byte[BLOCK]; + private int headerPosition = BLOCK; + private long contentRemaining; + private long contentOffset; + private byte[] pattern; + private int padding; + private int trailer = 2 * BLOCK; + + GeneratedTar(Iterator specs) { + this.specs = specs; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int read = read(one, 0, 1); + return read < 0 ? -1 : one[0] & 0xFF; + } + + @Override + public int read(byte[] target, int offset, int length) throws IOException { + if (length == 0) { + return 0; + } + while (true) { + if (headerPosition < BLOCK) { + int count = Math.min(length, BLOCK - headerPosition); + System.arraycopy(header, headerPosition, target, offset, count); + headerPosition += count; + return count; + } + if (contentRemaining > 0) { + int count = (int) Math.min(length, contentRemaining); + for (int i = 0; i < count; i++) { + target[offset + i] = pattern[(int) ((contentOffset + i) % pattern.length)]; + } + contentOffset += count; + contentRemaining -= count; + if (contentRemaining == 0) { + padding = (int) ((BLOCK - contentOffset % BLOCK) % BLOCK); + } + return count; + } + if (padding > 0) { + int count = Math.min(length, padding); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + padding -= count; + return count; + } + if (specs.hasNext()) { + begin(specs.next()); + continue; + } + if (trailer > 0) { + int count = Math.min(length, trailer); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + trailer -= count; + return count; + } + return -1; + } + } + + private void begin(Spec spec) { + TarArchiveEntry entry = new TarArchiveEntry(spec.name()); + entry.setModTime(new Date(1_700_000_000_000L)); + entry.setUserId(1000); + entry.setGroupId(1000); + if (spec.size() < 0) { + entry.setMode(040755); + } else { + entry.setMode(0100644); + entry.setSize(spec.size()); + } + java.util.Arrays.fill(header, (byte) 0); + entry.writeEntryHeader(header); + headerPosition = 0; + contentRemaining = Math.max(spec.size(), 0); + contentOffset = 0; + pattern = spec.pattern(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java new file mode 100644 index 0000000..582634e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java @@ -0,0 +1,48 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.PathCoverage.Item; +import wellatleastitried.mediagarrdServer.service.PathCoverage.Owner; + +class PathCoverageTest { + + private static Item item(String service, String path) { + return new Item(new ServiceDefinition(service, List.of(path)), 0); + } + + @Test + void anAncestorOwnsEveryDescendantAndSiblingsStaySeparate() { + Item a = item("a", "/srv/a"); + Item inner = item("b", "/srv/a/b/c"); + Item middle = item("c", "/srv/a/b"); + Item sibling = item("d", "/srv/ab"); + + List owners = PathCoverage.plan(List.of(inner, a, sibling, middle)); + + assertEquals(List.of(a, sibling), owners.stream().map(Owner::item).toList()); + assertEquals(List.of(inner, middle), owners.get(0).covered()); + assertEquals(List.of(), owners.get(1).covered()); + } + + @Test + void equalPathsAreOwnedByTheServiceThatSortsFirst() { + Item b = item("b", "/srv/x"); + Item a = item("a", "/srv/x"); + + List owners = PathCoverage.plan(List.of(b, a)); + + assertEquals(List.of(a), owners.stream().map(Owner::item).toList()); + assertEquals(List.of(b), owners.get(0).covered()); + } + + @Test + void keysAreEntryNamesWithoutTheLeadingSlash() { + assertEquals("srv/a/b", item("a", "/srv/a/b").key()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java index 62fee1b..63e3696 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java @@ -19,12 +19,12 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; -import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; -import java.util.TreeMap; import java.util.stream.Stream; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; @@ -34,10 +34,12 @@ 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.Timeout; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; @@ -50,7 +52,7 @@ class ServiceBackupRunnerTest { Path runDir; private final DockerService docker = mock(DockerService.class); - private final ServiceBackupRunner runner = new ServiceBackupRunner(docker); + private final ServiceBackupRunner runner = new ServiceBackupRunner(docker, new ZipCompression(1)); @Test void storesDirectoryContentsUnderTheirAbsolutePaths() throws Exception { @@ -63,11 +65,11 @@ void storesDirectoryContentsUnderTheirAbsolutePaths() throws Exception { assertEquals(COMPLETED, result.status()); assertNull(result.errorMessage()); - Map config = contents(runDir.resolve("radarr/0.zip")); + Map config = contents(runDir.resolve("radarr/0.part")); assertEquals(List.of("srv/radarr/config/", "srv/radarr/config/config.xml", "srv/radarr/config/empty/", "srv/radarr/config/logs/app.log"), List.copyOf(config.keySet())); assertEquals("", config.get("srv/radarr/config/config.xml")); - assertEquals("db", contents(runDir.resolve("radarr/1.zip")).get("srv/radarr/data/radarr.db")); + assertEquals("db", contents(runDir.resolve("radarr/1.part")).get("srv/radarr/data/radarr.db")); } @Test @@ -78,7 +80,7 @@ void storesOnlyTheFileWhenPathIsAFile() throws Exception { assertEquals(COMPLETED, runner.run(nginx, runDir).status()); - assertEquals(Map.of("etc/nginx/sites-available/config", "server {}"), contents(runDir.resolve("nginx/0.zip"))); + assertEquals(Map.of("etc/nginx/sites-available/config", "server {}"), contents(runDir.resolve("nginx/0.part"))); } static Stream archivedEntries() { @@ -99,7 +101,7 @@ static Stream archivedEntries() { void archivesExpectedEntries(String description, String hostPath, Item[] items, Map expected) throws Exception { Path part = runDir.resolve("part.zip"); - assertEquals(expected.size(), ServiceBackupRunner.archive(tar(items), hostPath, part)); + assertEquals(expected.size(), ServiceBackupRunner.archive(tar(items), hostPath, part, new ZipCompression(1))); assertEquals(expected, contents(part)); } @@ -111,16 +113,16 @@ void preservesModeOwnerAndModificationTime() throws Exception { secret.entry().setMode(0100600); secret.entry().setUserId(1000); secret.entry().setGroupId(1001); - secret.entry().setModTime(new Date(1_700_000_000_000L)); + secret.entry().setModTime(new Date(1_700_000_001_000L)); Item folder = dir("config/"); folder.entry().setMode(040750); - ServiceBackupRunner.archive(tar(folder, secret), "/home/user/config", part); + ServiceBackupRunner.archive(tar(folder, secret), "/home/user/config", part, new ZipCompression(1)); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { ZipArchiveEntry key = zip.getEntry("home/user/config/id_rsa"); assertEquals(UnixStat.FILE_FLAG | 0600, key.getUnixMode()); - assertEquals(1_700_000_000_000L, key.getTime()); + assertEquals(1_700_000_001_000L, key.getTime()); X7875_NewUnix owner = (X7875_NewUnix) key.getExtraField(new X7875_NewUnix().getHeaderId()); assertEquals(1000, owner.getUID()); assertEquals(1001, owner.getGID()); @@ -128,14 +130,96 @@ void preservesModeOwnerAndModificationTime() throws Exception { } } + @ParameterizedTest(name = "level {0}") + @ValueSource(ints = {0, 1, 9}) + @Timeout(30) + void picksEntryMethodsByLevelAndExtensionAndRoundTripsContents(int level) throws Exception { + Path part = runDir.resolve("part.zip"); + String text = "compressible text ".repeat(2000); + Item notes = file("data/notes.txt", text); + notes.entry().setMode(0100640); + notes.entry().setUserId(1000); + notes.entry().setGroupId(1001); + notes.entry().setModTime(new Date(1_700_000_000_000L)); + Item movie = file("data/movie.MKV", text); + movie.entry().setMode(0100600); + movie.entry().setUserId(7); + movie.entry().setGroupId(8); + + ServiceBackupRunner.archive(tar(dir("data/"), notes, movie, file("data/empty.txt", "")), "/srv/data", part, new ZipCompression(level)); + + assertEquals(text, contents(part).get("srv/data/notes.txt")); + assertEquals(text, contents(part).get("srv/data/movie.MKV")); + assertEquals("", contents(part).get("srv/data/empty.txt")); + CRC32 crc = new CRC32(); + crc.update(text.getBytes(StandardCharsets.UTF_8)); + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { + ZipArchiveEntry stored = zip.getEntry("srv/data/movie.MKV"); + assertEquals(ZipEntry.STORED, stored.getMethod()); + assertEquals(text.length(), stored.getSize()); + assertEquals(text.length(), stored.getCompressedSize()); + assertEquals(crc.getValue(), stored.getCrc()); + assertEquals(UnixStat.FILE_FLAG | 0600, stored.getUnixMode()); + X7875_NewUnix owner = (X7875_NewUnix) stored.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(7, owner.getUID()); + assertEquals(8, owner.getGID()); + + ZipArchiveEntry notesEntry = zip.getEntry("srv/data/notes.txt"); + assertEquals(level == 0 ? ZipEntry.STORED : ZipEntry.DEFLATED, notesEntry.getMethod()); + assertEquals(level == 0, notesEntry.getCompressedSize() == notesEntry.getSize()); + assertEquals(UnixStat.FILE_FLAG | 0640, notesEntry.getUnixMode()); + assertEquals(1_700_000_000_000L, notesEntry.getTime()); + X7875_NewUnix notesOwner = (X7875_NewUnix) notesEntry.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(1000, notesOwner.getUID()); + assertEquals(1001, notesOwner.getGID()); + assertEquals(UnixStat.DIR_FLAG | 0755, zip.getEntry("srv/data/").getUnixMode()); + } + } + + @Test + @Timeout(30) + void higherLevelsProduceSmallerPartsForCompressibleData() throws Exception { + String text = "compressible text ".repeat(20000); + Path none = runDir.resolve("none.zip"); + Path fast = runDir.resolve("fast.zip"); + Path best = runDir.resolve("best.zip"); + + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", none, new ZipCompression(0)); + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", fast, new ZipCompression(1)); + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", best, new ZipCompression(9)); + + assertTrue(Files.size(none) > text.length()); + assertTrue(Files.size(fast) < text.length() / 10); + assertTrue(Files.size(best) <= Files.size(fast)); + } + + @Test + @Timeout(30) + void hardLinksToStoredAndDeflatedEntriesKeepTheirMethods() throws Exception { + Path part = runDir.resolve("part.zip"); + Item stored = file("data/clip.mp4", "video".repeat(500)); + Item deflated = file("data/log.txt", "text".repeat(500)); + Item linkStored = link("data/clip-link.mp4", TarConstants.LF_LINK, "data/clip.mp4"); + Item linkDeflated = link("data/log-link.txt", TarConstants.LF_LINK, "data/log.txt"); + + ServiceBackupRunner.archive(tar(dir("data/"), stored, deflated, linkStored, linkDeflated), "/srv/data", part, new ZipCompression(1)); + + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { + assertEquals(ZipEntry.STORED, zip.getEntry("srv/data/clip-link.mp4").getMethod()); + assertEquals(ZipEntry.DEFLATED, zip.getEntry("srv/data/log-link.txt").getMethod()); + } + assertEquals("video".repeat(500), contents(part).get("srv/data/clip-link.mp4")); + assertEquals("text".repeat(500), contents(part).get("srv/data/log-link.txt")); + } + @Test void storesSymbolicLinksAsLinks() throws Exception { Path part = runDir.resolve("part.zip"); Item symlink = link("sites-enabled/default", TarConstants.LF_SYMLINK, "/etc/nginx/sites-available/default"); - ServiceBackupRunner.archive(tar(dir("sites-enabled/"), symlink), "/etc/nginx/sites-enabled", part); + ServiceBackupRunner.archive(tar(dir("sites-enabled/"), symlink), "/etc/nginx/sites-enabled", part, new ZipCompression(1)); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { ZipArchiveEntry entry = zip.getEntry("etc/nginx/sites-enabled/default"); assertTrue(entry.isUnixSymlink()); assertEquals("/etc/nginx/sites-available/default", zip.getUnixSymlink(entry)); @@ -143,14 +227,65 @@ void storesSymbolicLinksAsLinks() throws Exception { } @Test - void copiesHardLinksIntoALinksPart() throws Exception { - Path part = runDir.resolve("0.zip"); + void storesHardLinksAsRegularCopiesOfTheirTarget() throws Exception { + Path part = runDir.resolve("0.part"); Item hardLink = link("data/link", TarConstants.LF_LINK, "data/original"); - assertEquals(3, ServiceBackupRunner.archive(tar(dir("data/"), file("data/original", "same"), hardLink), "/srv/data", part)); + assertEquals(3, ServiceBackupRunner.archive(tar(dir("data/"), file("data/original", "same"), hardLink), "/srv/data", part, new ZipCompression(1))); + + assertEquals(Map.of("srv/data/", "", "srv/data/original", "same", "srv/data/link", "same"), contents(part)); + } + + @Test + void excludedNamesAndHardLinksToThemAreSkipped() throws Exception { + Path part = runDir.resolve("0.part"); + Item hardLink = link("data/db-link", TarConstants.LF_LINK, "data/live.db"); + + ServiceBackupRunner.ArchiveResult result = ServiceBackupRunner.archive( + tar(dir("data/"), file("data/live.db", "live"), hardLink, file("data/keep", "k")), "/srv/data", part, new ZipCompression(1), + java.util.Set.of("srv/data/live.db"), java.util.Set.of()); + + assertEquals(2, result.entries()); + assertEquals(Map.of("srv/data/", "", "srv/data/keep", "k"), contents(part)); + } + + @Test + void aHardLinkToASkippedSpecialFileIsSkippedInsteadOfFailingThePath() throws Exception { + Path part = runDir.resolve("0.part"); + + int entries = ServiceBackupRunner.archive( + tar(dir("data/"), special("data/pipe", TarConstants.LF_FIFO), link("data/pipe2", TarConstants.LF_LINK, "data/pipe"), file("data/f", "x")), + "/srv/data", part, new ZipCompression(1)); + + assertEquals(2, entries); + assertEquals(Map.of("srv/data/", "", "srv/data/f", "x"), contents(part)); + } + + @Test + void hardLinksToHardLinksResolveAndUnknownTargetsFailThePath() throws Exception { + Path part = runDir.resolve("0.part"); + + ServiceBackupRunner.archive(tar(file("data/a", "same"), link("data/b", TarConstants.LF_LINK, "data/a"), link("data/c", TarConstants.LF_LINK, "data/b")), + "/srv/data", part, new ZipCompression(1)); + + assertEquals(Map.of("srv/data/a", "same", "srv/data/b", "same", "srv/data/c", "same"), contents(part)); + Path broken = runDir.resolve("broken.part"); + assertThrows(IOException.class, + () -> ServiceBackupRunner.archive(tar(link("data/b", TarConstants.LF_LINK, "data/nothing")), "/srv/data", broken, new ZipCompression(1))); + assertFalse(Files.exists(broken)); + assertFalse(Files.exists(ZipPartWriter.indexOf(broken))); + } + + @Test + void confirmsCoveredPathsOnlyWhenTheirDirectoryOrFileWasStored() throws Exception { + Path part = runDir.resolve("0.part"); + + ServiceBackupRunner.ArchiveResult result = ServiceBackupRunner.archive( + tar(dir("a/"), dir("a/dir/"), file("a/file", "f"), link("a/link", TarConstants.LF_SYMLINK, "/mnt/x"), dir("a/other/")), + "/srv/a", part, new ZipCompression(1), + java.util.Set.of(), java.util.Set.of("srv/a/dir", "srv/a/file", "srv/a/link", "srv/a/missing", "srv/a")); - assertFalse(contents(part).containsKey("srv/data/link")); - assertEquals(Map.of("srv/data/link", "same"), contents(runDir.resolve("0-links.zip"))); + assertEquals(java.util.Set.of("srv/a/dir", "srv/a/file", "srv/a"), result.confirmed()); } @Test @@ -163,8 +298,10 @@ void reportsPartialAndDiscardsOnlyTheFailedPath() throws Exception { assertEquals(PARTIAL, result.status()); assertTrue(result.errorMessage().startsWith("/srv/radarr/data: ")); - assertTrue(Files.exists(runDir.resolve("radarr/0.zip"))); - assertFalse(Files.exists(runDir.resolve("radarr/1.zip"))); + assertTrue(Files.exists(runDir.resolve("radarr/0.part"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part.partial"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part.idx"))); } @Test @@ -193,8 +330,8 @@ void reportsFailedWhenContainerCannotBePrepared() { void rejectsEntriesOutsideTheBackedUpPath() { Path part = runDir.resolve("part.zip"); - assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("../escaped.txt", "x")), "/srv/data", part)); - assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("other/file", "x")), "/srv/data", part)); + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("../escaped.txt", "x")), "/srv/data", part, new ZipCompression(1))); + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("other/file", "x")), "/srv/data", part, new ZipCompression(1))); } @Test @@ -202,7 +339,7 @@ void rejectsHardLinksOutsideTheBackedUpPath() { Item hardLink = link("data/link", TarConstants.LF_LINK, "../etc/shadow"); assertThrows(IOException.class, - () -> ServiceBackupRunner.archive(tar(dir("data/"), hardLink), "/srv/data", runDir.resolve("part.zip"))); + () -> ServiceBackupRunner.archive(tar(dir("data/"), hardLink), "/srv/data", runDir.resolve("part.zip"), new ZipCompression(1))); } @Test @@ -212,16 +349,12 @@ void buildsEntryNamesFromAbsolutePaths() throws IOException { assertEquals("srv/", ServiceBackupRunner.entryName(Path.of("/"), Path.of("/srv"), "srv/", true)); } - static Map contents(Path zipPath) throws IOException { - Map entries = new TreeMap<>(); - try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { - for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { - try (InputStream in = zip.getInputStream(entry)) { - entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); - } - } - } - return entries; + static Path merged(Path part) throws IOException { + return ArchiveTestSupport.merge(part.getParent(), part); + } + + static Map contents(Path part) throws IOException { + return ArchiveTestSupport.contents(merged(part)); } record Item(TarArchiveEntry entry, byte[] content) {} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java new file mode 100644 index 0000000..c6738b6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java @@ -0,0 +1,47 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.PathCopy; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.ServiceRound; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.Tally; + +class TallyTest { + + private static ServiceRound failed(String error, String... paths) { + return new ServiceRound(error, java.util.Arrays.stream(paths).map(p -> new PathCopy(0, p, false, null, Set.of())).toList()); + } + + @Test + void theSameServiceLevelErrorInSeveralRoundsIsReportedOnce() { + Tally tally = new Tally("media"); + tally.add(failed("no helper", "/a")); + tally.add(failed("no helper", "/b")); + + BackupServiceResult result = tally.result(); + + assertEquals(FAILED, result.status()); + assertEquals("no helper", result.errorMessage()); + } + + @Test + void differentErrorsAreAllKeptInOrder() { + Tally tally = new Tally("media"); + tally.add(failed("no helper", "/a")); + tally.add(new ServiceRound(null, List.of(new PathCopy(1, "/b", false, "/b: boom", Set.of()), new PathCopy(2, "/c", true, null, Set.of())))); + tally.add(failed("other", "/d")); + + BackupServiceResult result = tally.result(); + + assertEquals(PARTIAL, result.status()); + assertEquals("no helper; /b: boom; other", result.errorMessage()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java new file mode 100644 index 0000000..1fc4dac --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java @@ -0,0 +1,54 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Timeout(30) +class ZipCompressionBindingTest { + + private final ApplicationContextRunner runner = new ApplicationContextRunner().withUserConfiguration(Config.class); + + @Test + void bindsALevelInRange() { + runner.withPropertyValues("mediagarrd.compression-level=5").run(context -> { + assertTrue(context.getStartupFailure() == null); + assertEquals(5, context.getBean(ZipCompression.class).level()); + }); + } + + @Test + void defaultsToOne() { + runner.run(context -> assertEquals(1, context.getBean(ZipCompression.class).level())); + } + + @Test + void failsStartupForALevelOutOfRange() { + runner.withPropertyValues("mediagarrd.compression-level=12").run(context -> { + assertTrue(context.getStartupFailure() != null); + assertTrue(rootMessages(context.getStartupFailure()).contains("mediagarrd.compression-level must be between 0 and 9, was 12")); + }); + } + + private static String rootMessages(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable t = failure; t != null; t = t.getCause()) { + messages.append(t.getMessage()).append('\n'); + } + return messages.toString(); + } + + @Configuration + @EnableConfigurationProperties(MediaGarrdProperties.class) + @Import(ZipCompression.class) + static class Config { + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java new file mode 100644 index 0000000..afef227 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java @@ -0,0 +1,82 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Timeout(30) +class ZipCompressionTest { + + @ParameterizedTest + @ValueSource(ints = {-1, 10, 100}) + void rejectsLevelsOutsideZeroToNine(int level) { + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZipCompression(level)); + + assertTrue(e.getMessage().contains("mediagarrd.compression-level must be between 0 and 9"), e.getMessage()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 5, 9}) + void acceptsLevelsZeroToNine(int level) { + assertEquals(level, new ZipCompression(level).level()); + } + + @Test + void defaultsToLevelOneFromProperties() { + assertEquals(1, new ZipCompression(new MediaGarrdProperties()).level()); + } + + @Test + void rejectsAnInvalidLevelFromProperties() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setCompressionLevel(12); + + assertThrows(IllegalStateException.class, () -> new ZipCompression(properties)); + } + + @ParameterizedTest + @ValueSource(strings = {"a.zip", "a.gz", "a.tgz", "a.bz2", "a.xz", "a.zst", "a.7z", "a.rar", "a.jpg", "a.jpeg", "a.png", + "a.gif", "a.webp", "a.mp4", "a.mkv", "a.mp3", "a.flac", "a.ogg", "a.mov", "a.avi", "a.webm", "a.m4v", "a.m4a", "a.aac", + "a.opus", "a.heic", "a.avif", "a.lz4", "a.zstd", "a.jar", "a.docx", "a.xlsx", "a.pptx", "dir/Photo.JPG", "x/y.tar.gz"}) + void storesAlreadyCompressedFilesAtAnyNonZeroLevel(String name) { + for (int level : new int[] {1, 9}) { + assertTrue(new ZipCompression(level).stores(name), name); + } + } + + @ParameterizedTest + @ValueSource(strings = {"a.txt", "a.db", "a.xml", "noextension", "dir.zip/file", "dir.png/readme", "a.", "gz", ".hidden"}) + void deflatesEverythingElseAtNonZeroLevels(String name) { + for (int level : new int[] {1, 9}) { + assertFalse(new ZipCompression(level).stores(name), name); + } + } + + @Test + void levelZeroStoresEverything() { + ZipCompression none = new ZipCompression(0); + + assertTrue(none.stores("a.txt")); + assertTrue(none.stores("a.jpg")); + assertTrue(none.stores("noextension")); + } + + @Test + void storesAlreadyCompressedFilesAtLevelOneAndReportsItsLevel() { + ZipCompression one = new ZipCompression(1); + + assertEquals(1, one.level()); + assertTrue(one.stores("a.mkv")); + assertFalse(one.stores("a.txt")); + assertEquals(0, new ZipCompression(0).level()); + assertTrue(new ZipCompression(0).stores("a.txt")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java new file mode 100644 index 0000000..83f9649 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java @@ -0,0 +1,36 @@ +package wellatleastitried.mediagarrdServer.service; + +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; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +@Timeout(30) +class ZipFormatTest { + + @Test + void theExtendedTimestampCoversOnlyTimesFromTheEpochToTheSignedLimit() { + assertFalse(ZipFormat.fitsUnixTime(-1L)); + assertFalse(ZipFormat.fitsUnixTime(-631_152_000_000L)); + assertTrue(ZipFormat.fitsUnixTime(0L)); + assertTrue(ZipFormat.fitsUnixTime(Integer.MAX_VALUE * 1000L)); + assertFalse(ZipFormat.fitsUnixTime((Integer.MAX_VALUE + 1L) * 1000L)); + } + + @Test + void ownerDataIsAlwaysFourByteIdsInLittleEndian() { + assertArrayEquals(new byte[] {1, 4, 33, 0, 0, 0, 4, (byte) 0xE8, 3, 0, 0}, ZipFormat.ownerData(33, 1000)); + assertArrayEquals(new byte[] {1, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0}, ZipFormat.ownerData(0, 0)); + } + + @Test + void ownerIdsOutsideThirtyTwoBitsAreClamped() { + byte[] data = ZipFormat.ownerData(0x100000005L, -7); + + assertEquals(11, data.length); + assertArrayEquals(new byte[] {1, 4, -1, -1, -1, -1, 4, 0, 0, 0, 0}, data); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java new file mode 100644 index 0000000..deaba30 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java @@ -0,0 +1,267 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.ByteArrayInputStream; +import java.io.EOFException; +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.Collections; +import java.util.List; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; + +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +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.Timeout; +import org.junit.jupiter.api.io.TempDir; + +class ZipPartWriterTest { + + private static final int FILE = UnixStat.FILE_FLAG | 0644; + private static final int DIRECTORY = UnixStat.DIR_FLAG | 0755; + + @TempDir + Path dir; + + private static InputStream bytes(String text) { + return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); + } + + private void add(ZipPartWriter writer, String name, String text) throws IOException { + writer.addEntry(name, FILE, 1000, 1001, 1_700_000_001_000L, text.getBytes(StandardCharsets.UTF_8).length, bytes(text)); + } + + @Test + void writesEntriesWithMetadataThatReadersAndExactTimesRoundTrip() throws Exception { + Path part = dir.resolve("0.part"); + String text = "compressible text ".repeat(500); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("srv/data/", DIRECTORY, 0, 0, 1_700_000_001_000L, 0, bytes("")); + writer.addEntry("srv/data/notes.txt", UnixStat.FILE_FLAG | 0640, 1000, 1001, 1_700_000_001_000L, text.length(), bytes(text)); + writer.addEntry("srv/data/movie.mkv", UnixStat.FILE_FLAG | 0400, 7, 8, 1_700_000_003_000L, text.length(), bytes(text)); + writer.addEntry("srv/data/empty.txt", FILE, 1, 2, 1_700_000_005_000L, 0, bytes("")); + writer.complete(); + assertEquals(4, writer.entryCount()); + } + assertTrue(Files.exists(part)); + assertFalse(Files.exists(ZipPartWriter.partialOf(part))); + + CRC32 crc = new CRC32(); + crc.update(text.getBytes(StandardCharsets.UTF_8)); + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(dir, part)).get()) { + assertEquals(List.of("srv/data/", "srv/data/notes.txt", "srv/data/movie.mkv", "srv/data/empty.txt"), + Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList()); + ZipArchiveEntry notes = zip.getEntry("srv/data/notes.txt"); + assertEquals(ZipEntry.DEFLATED, notes.getMethod()); + assertEquals(text.length(), notes.getSize()); + assertTrue(notes.getCompressedSize() < text.length() / 4); + assertEquals(crc.getValue(), notes.getCrc()); + assertEquals(UnixStat.FILE_FLAG | 0640, notes.getUnixMode()); + assertEquals(1_700_000_001_000L, notes.getTime()); + assertEquals(1_700_000_001L, ((X5455_ExtendedTimestamp) notes.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)).getModifyJavaTime().getTime() / 1000); + assertEquals(text, new String(zip.getInputStream(notes).readAllBytes(), StandardCharsets.UTF_8)); + + ZipArchiveEntry movie = zip.getEntry("srv/data/movie.mkv"); + assertEquals(ZipEntry.STORED, movie.getMethod()); + assertEquals(text.length(), movie.getCompressedSize()); + assertEquals(UnixStat.FILE_FLAG | 0400, movie.getUnixMode()); + assertEquals(1_700_000_003_000L, movie.getTime()); + assertEquals(text, new String(zip.getInputStream(movie).readAllBytes(), StandardCharsets.UTF_8)); + + assertEquals(UnixStat.DIR_FLAG | 0755, zip.getEntry("srv/data/").getUnixMode()); + assertTrue(zip.getEntry("srv/data/").isDirectory()); + assertEquals("", new String(zip.getInputStream(zip.getEntry("srv/data/empty.txt")).readAllBytes(), StandardCharsets.UTF_8)); + } + } + + @Test + void writesOwnerOnlyInTheLocalHeaderAndTimesOutsideTheExtendedRangeAsDosOnly() throws Exception { + Path part = dir.resolve("0.part"); + long before1980 = 100_000_000L; + long after2038 = 4_300_000_000_000L; + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("old", FILE, 1000, 1001, before1980, 1, bytes("x")); + writer.addEntry("pre1970", FILE, 1000, 1001, -1_000_000_000_000L, 1, bytes("z")); + writer.addEntry("future", FILE, 3000000000L, 1001, after2038, 1, bytes("y")); + writer.complete(); + } + + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(dir, part)).get()) { + ZipArchiveEntry old = zip.getEntry("old"); + assertNotNull(old.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + assertNull(zip.getEntry("pre1970").getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + ZipArchiveEntry future = zip.getEntry("future"); + assertNull(future.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + assertTrue(future.getTime() > 0); + X7875_NewUnix owner = (X7875_NewUnix) future.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(3000000000L, owner.getUID()); + } + assumeTrue(ArchiveTestSupport.available("bsdtar")); + String listing = ArchiveTestSupport.run(null, "bsdtar", "-tvf", ArchiveTestSupport.merge(dir, part).toString(), "--numeric-owner"); + assertTrue(listing.matches("(?s).*\\b3000000000\\s+1001\\b.*"), listing); + assertTrue(listing.matches("(?s).*\\b1000\\s+1001\\b.*"), listing); + } + + @Test + void copiesHardLinkTargetsUnderTheLinkNameAndKeepsTheirMethod() throws Exception { + Path part = dir.resolve("0.part"); + String text = "video".repeat(500); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("a/clip.mp4", FILE, 1, 2, 1_700_000_000_000L, text.length(), bytes(text)); + writer.addEntry("a/log.txt", FILE, 1, 2, 1_700_000_000_000L, text.length(), bytes(text)); + assertTrue(writer.addCopy("a/clip-link.mp4", "a/clip.mp4")); + assertTrue(writer.addCopy("a/log-link.txt", "a/log.txt")); + assertTrue(writer.addCopy("a/log-link-link.txt", "a/log-link.txt")); + writer.complete(); + assertEquals(5, writer.entryCount()); + } + + Path archive = ArchiveTestSupport.merge(dir, part); + assertEquals(text, ArchiveTestSupport.contents(archive).get("a/clip-link.mp4")); + assertEquals(text, ArchiveTestSupport.contents(archive).get("a/log-link-link.txt")); + try (ZipFile zip = ZipFile.builder().setPath(archive).get()) { + assertEquals(ZipEntry.STORED, zip.getEntry("a/clip-link.mp4").getMethod()); + assertEquals(ZipEntry.DEFLATED, zip.getEntry("a/log-link.txt").getMethod()); + assertEquals(zip.getEntry("a/log.txt").getCrc(), zip.getEntry("a/log-link.txt").getCrc()); + } + } + + @Test + void hardLinksToMissingTargetsFailButSkippedTargetsAreIgnored() throws Exception { + try (var writer = new ZipPartWriter(dir.resolve("0.part"), new ZipCompression(1))) { + add(writer, "a/one", "1"); + writer.markSkipped("a/pipe"); + + assertFalse(writer.addCopy("a/pipe-link", "a/pipe")); + assertThrows(IOException.class, () -> writer.addCopy("a/link", "a/missing")); + assertTrue(writer.contains("a/one")); + assertFalse(writer.contains("a/pipe-link")); + } + } + + @Test + void anEntryShorterThanItsDeclaredSizeFailsAndClosingDiscardsTheIncompletePart() throws Exception { + Path part = dir.resolve("0.part"); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + assertThrows(EOFException.class, () -> writer.addEntry("a", FILE, 1, 1, 0, 10, bytes("short"))); + } + + assertFalse(Files.exists(part)); + assertFalse(Files.exists(ZipPartWriter.partialOf(part))); + assertFalse(Files.exists(ZipPartWriter.indexOf(part))); + } + + @Test + void mergeFailsOnADuplicateNameAcrossPartsAndOnAReservedNameInAServicePart() throws Exception { + Path first = dir.resolve("0.part"); + Path second = dir.resolve("1.part"); + Path snapshot = dir.resolve("snap.part"); + Path live = dir.resolve("live.part"); + for (Path part : List.of(first, second)) { + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + add(writer, "a/same", "x"); + writer.complete(); + } + } + try (var writer = new ZipPartWriter(snapshot, new ZipCompression(1))) { + add(writer, "db/mediagarrd.db", "snapshot"); + writer.complete(); + } + try (var writer = new ZipPartWriter(live, new ZipCompression(1))) { + add(writer, "db/mediagarrd.db-wal", "live"); + writer.complete(); + } + + Path out = dir.resolve("out.zip"); + assertThrows(IOException.class, () -> ZipPartMerger.merge(List.of(), List.of(first, second), out, dir)); + assertThrows(IOException.class, () -> ZipPartMerger.merge(List.of(snapshot), List.of(live), out, dir)); + assertFalse(Files.exists(dir.resolve("merge-names.idx"))); + } + + @Test + void mergeChecksumMatchesTheWrittenFileAndOffsetsSurviveSeveralParts() throws Exception { + Path first = dir.resolve("0.part"); + Path second = dir.resolve("1.part"); + for (Path part : List.of(first, second)) { + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + add(writer, part.getFileName() + "/x", "data " + part.getFileName()); + add(writer, part.getFileName() + "/y.mp4", "stored " + part.getFileName()); + writer.complete(); + } + } + Path out = dir.resolve("out.zip"); + + ZipPartMerger.Result result = ZipPartMerger.merge(List.of(), List.of(first, second), out, dir); + + assertEquals(4, result.entries()); + assertEquals(Files.size(out), result.bytes()); + assertEquals(java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(out))), result.checksum()); + assertEquals("stored 1.part", ArchiveTestSupport.contents(out).get("1.part/y.mp4")); + } + + @Test + @Timeout(120) + void manyEntriesBeyondTheClassicLimitUseZip64AndReadBack() throws Exception { + Path part = dir.resolve("0.part"); + int count = 70_000; + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + for (int i = 0; i < count; i++) { + add(writer, "many/f" + i, Integer.toString(i)); + } + writer.complete(); + } + Path archive = ArchiveTestSupport.merge(dir, part); + + try (ZipFile zip = ZipFile.builder().setPath(archive).get()) { + assertEquals(count, Collections.list(zip.getEntries()).size()); + assertEquals("69999", new String(zip.getInputStream(zip.getEntry("many/f69999")).readAllBytes(), StandardCharsets.UTF_8)); + } + verifyWithTools(archive, count); + } + + @Test + void smallArchiveIsAcceptedByExternalTools() throws Exception { + Path part = dir.resolve("0.part"); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("srv/", DIRECTORY, 0, 0, 1_700_000_001_000L, 0, bytes("")); + add(writer, "srv/a.txt", "hello".repeat(100)); + add(writer, "srv/b.mp4", "world".repeat(100)); + assertTrue(writer.addCopy("srv/c.txt", "srv/a.txt")); + writer.complete(); + } + + verifyWithTools(ArchiveTestSupport.merge(dir, part), 4); + } + + static void verifyWithTools(Path archive, int entries) throws Exception { + if (ArchiveTestSupport.available("unzip")) { + String output = ArchiveTestSupport.run(null, "unzip", "-tq", archive.toString()); + assertTrue(output.contains("No errors"), output); + } + if (ArchiveTestSupport.available("bsdtar")) { + assertEquals(entries, ArchiveTestSupport.runCounting(null, "bsdtar", "-tf", archive.toString()).lines()); + assertEquals(entries, ArchiveTestSupport.runCounting(archive, "bsdtar", "-tf", "-").lines()); + } + if (ArchiveTestSupport.available("python3")) { + ArchiveTestSupport.run(null, "python3", "-I", "-m", "zipfile", "-t", archive.toString()); + } + if (ArchiveTestSupport.available("7z")) { + String output = ArchiveTestSupport.run(null, "7z", "t", archive.toString()); + assertTrue(output.contains("Everything is Ok"), output); + } + } +} From 57a3a2450a89f4b7b4f5d9b1dbdd5e1f002c27ee Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 14 Nov 2026 15:25:03 -0600 Subject: [PATCH 2/2] Update docs to reflect new recovery tool --- docs/database.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/database.md b/docs/database.md index d92dab6..4e8cabc 100644 --- a/docs/database.md +++ b/docs/database.md @@ -22,22 +22,30 @@ Never restore over the database of a running server. ```bash docker compose stop ``` -2. Extract the copy into an empty directory: +2. Restore the archive into a new directory with [mgrecover](https://github.com/MediaGarrd/Recovery): + ```bash + curl -fLO https://github.com/MediaGarrd/Recovery/releases/latest/download/mgrecover.sh + chmod +x mgrecover.sh + ./mgrecover.sh -C restore .zip + ``` + `-C` restores the whole archive under `restore` (created if missing), so it can be large. It prints a plan and asks for confirmation (`-y` skips it and is required without a terminal). It creates no symbolic links and writes nothing outside that directory. With `-C`, files are restored without their original owners (they belong to you); step 3 copies the database back as root into the server's existing directory, which keeps its owner and mode. + + To extract only the database instead (this needs the directory to exist): ```bash mkdir restore - bsdtar -xpPf .zip -C restore '' + bsdtar -xpf .zip -C restore '' ``` 3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): ```bash - cp restore/ ./data/server/db/mediagarrd.db - rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm + sudo cp restore/ ./data/server/db/mediagarrd.db + sudo rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm ``` 4. Start the server again: ```bash docker compose start ``` -`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. `-P` lets it extract through symbolic links stored in the archive. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. +mgrecover needs `bsdtar` (the `libarchive-tools` package on Debian and Ubuntu). A full restore with `sudo ./mgrecover.sh .zip` puts back every file in the archive, not only the database, and writes the database to its host path. That is only safe while the server is stopped; remove the `-journal`, `-wal` and `-shm` files as in step 3 before starting the server. ## If the database is damaged The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again.