Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -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":"<ISO-8601>"}`
- `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
Expand Down
18 changes: 11 additions & 7 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
30 changes: 29 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,33 @@ springBoot {
}

tasks.test {
useJUnitPlatform()
useJUnitPlatform {
excludeTags("scale")
}
}

tasks.register<Test>("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)
}
16 changes: 12 additions & 4 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <archive>.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 -xpf <archive>.zip -C restore '<path from the listing above>'
```
3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file):
```bash
cp restore/<path from the listing above> ./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/<path from the listing above> ./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. 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 <archive>.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-<timestamp>` 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.
11 changes: 11 additions & 0 deletions docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -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 <image> java -XX:TrimNativeHeapInterval=10000 -XX:+UseG1GC -version`.
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<String> DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm");

private final DatabaseService db;
private final AtomicReference<List<BackupArchive>> cachedArchives = new AtomicReference<>(null);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<Path> 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<ZipFile> openParts = new ArrayList<>();
SortedMap<String, ZipEntrySource> entries = new TreeMap<>();
Set<String> 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(
Expand Down
Loading
Loading