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
8 changes: 8 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# CHANGELOG

## 11-05-26
- Every backup archive now includes a consistent snapshot of the server's own database (settings, services, and backup records), stored at its absolute host path so the future recovery tool and `bsdtar -xpf <archive> -C /` restore it in place
- The host path is found by inspecting the server's own container, a run is reported as partial with the error logged if it cannot be found or the snapshot fails, and a corrupt or missing database is never replaced by an empty one
- All database operations now wait while the snapshot is taken, so nothing is written to the database mid-copy
- The database snapshot appears as `_mediagarrd-server` in each run's service results and in the API's service names
- A service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to the snapshot in the archive
- Documented how to restore the database from an archive

## 10-26-26
- Fixed logic issue with migration versioning
- Added Structurizr diagrams to visualize workflow
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,20 @@ srv/radarr/config/config.xml
```
Each entry keeps its permissions, owner (uid/gid), and modification time. Symbolic links are stored as links, empty directories are kept, and hard links are stored as regular copies. Named pipes, sockets, and device files are skipped. If two services back up the same path it appears once. If a path fails to copy, none of it is included and the run is reported as partial.

Every archive also contains a consistent snapshot of the server's own database (settings, services, and backup records) at the database file's absolute host path, for example `home/you/MediaGarrd/data/server/db/mediagarrd.db` when `./data/server/db` is mounted at `/var/lib/mediagarrd/db`. The server finds that host path by inspecting its own container, and no other database operation runs while the snapshot is taken. If the path cannot be resolved or the snapshot fails, the archive is still created, the run is reported as partial, and the error is listed under `_mediagarrd-server` (which also shows up in each run's service list). The snapshot never contains the record of its own run. On Docker Desktop (macOS and Windows) the host path reported by Docker is a path inside its VM, so the snapshot's location in the archive will not match your real host path. If a service also backs up the database directory, the snapshot replaces that service's copy of the database file, and its `-journal`, `-wal`, and `-shm` files are left out of the archive.

### Restoring
Because the layout mirrors the filesystem, restoring is a single extraction onto `/`. Use `bsdtar` (libarchive, the `libarchive-tools` package on Debian/Ubuntu), which restores contents, permissions, owners, modification times, and symbolic links:
```bash
sudo bsdtar -xpf <archive>.zip -C /
```
Extract into an empty directory with `-C <dir>` to inspect a backup first.

To restore the server's database, stop the server first (`docker compose stop`), extract the snapshot into an empty directory, copy it over `mediagarrd.db` in the mounted database directory (`./data/server/db`), then start the server again. Do not extract it over a running server's database. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped.

Info-ZIP `unzip -o <archive>.zip -d /` restores contents, permissions, and symbolic links, but UnZip 6.00 (the version most distributions ship) does not restore owners, so files end up owned by whoever ran it. Tools that ignore Unix metadata, such as Python's `zipfile` or most GUI archive managers, restore only the file contents.

> **Security:** the server needs `/var/run/docker.sock`, which gives it root-equivalent access to the host. During setup the configuration API requires the PIN session, but once setup is finished the API is unauthenticated, so do not expose the server port to untrusted networks.

## License
[GPLv3](./LICENSE)
[MIT](./LICENSE)
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
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;
Expand All @@ -41,6 +43,7 @@ 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 @@ -297,13 +300,29 @@ private void mergeParts(Path runDirectory, Path zipPath) throws IOException {
}

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<>();
try {
for (Path part : parts) {
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));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
Expand Down Expand Up @@ -40,6 +41,7 @@ public class BackupOrchestratorService {

private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class);

private static final String SNAPSHOT_NAME = DatabaseSnapshotService.SERVICE_NAME;
private static final int RUNNER_POOL_SIZE = 6;
private static final long RUNNER_IDLE_TTL_SECONDS = 30;
private static final long SCHEDULED_CHECK_INTERVAL_MS = 30000;
Expand All @@ -48,6 +50,7 @@ public class BackupOrchestratorService {
private final ServiceBackupRunner runner;
private final BackupArchiveService archiveService;
private final BackupScheduleService scheduleService;
private final DatabaseSnapshotService snapshotService;
private final DatabaseService db;
private final AtomicBoolean running = new AtomicBoolean(false);
private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock();
Expand All @@ -57,11 +60,13 @@ public BackupOrchestratorService(
ServiceBackupRunner runner,
BackupArchiveService archiveService,
BackupScheduleService scheduleService,
DatabaseSnapshotService snapshotService,
DatabaseService db
) {
this.runner = runner;
this.archiveService = archiveService;
this.scheduleService = scheduleService;
this.snapshotService = snapshotService;
this.db = db;
}

Expand Down Expand Up @@ -156,19 +161,32 @@ public BackupRunResult runBackup() {
throw new IllegalStateException("Every service failed, no archive created: " + errorMessage);
}

BackupServiceResult snapshotResult = snapshotDatabase(runDir);
List<BackupServiceResult> recordedResults = new ArrayList<>(serviceRunResults);
recordedResults.add(snapshotResult);
boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status());
if (snapshotFailed) {
LOGGER.warn("Database snapshot did not complete (non-fatal): {}", snapshotResult.errorMessage());
String snapshotError = SNAPSHOT_NAME + ": " + Objects.requireNonNullElse(snapshotResult.errorMessage(), "no details");
errorMessage = errorMessage.isEmpty() ? snapshotError : errorMessage + "\n" + snapshotError;
}

BackupArchive archive = archiveService.createArchive(runDirectory);
serviceRunResults.forEach(r -> r.setId(archive.id()));
recordedResults.forEach(r -> r.setId(archive.id()));

long durationMs = Duration.between(startedAt, Instant.now()).toMillis();
LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}",
archive.fileName(), archive.sizeBytes(), durationMs,
serviceRunResults.stream().map(BackupServiceResult::serviceName).toList());
recordedResults.stream().map(BackupServiceResult::serviceName).toList());

String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED;
if (snapshotFailed && COMPLETED.equals(status)) {
status = PARTIAL;
}

BackupRunResult backupRecord = new BackupRunResult(
archive.id(), formatTime(startedAt), recordCurrentTime(), status,
serviceRunResults, archive, errorMessage);
recordedResults, archive, errorMessage);
db.addNewBackupRecord(backupRecord);
return backupRecord;
} finally {
Expand All @@ -181,6 +199,15 @@ public BackupRunResult runBackup() {
}
}

private BackupServiceResult snapshotDatabase(Path runDir) {
try {
return snapshotService.snapshot(runDir);
} catch (RuntimeException e) {
LOGGER.warn("[{}] Failed to snapshot database", SNAPSHOT_NAME, e);
return failedResult(SNAPSHOT_NAME, e);
}
}

private static Throwable unwrap(Throwable t) {
return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package wellatleastitried.mediagarrdServer.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ContainerEnvironment {

private static final Logger LOGGER = LoggerFactory.getLogger(ContainerEnvironment.class);

private static final Pattern CONTAINER_ID = Pattern.compile("containers/([0-9a-f]{64})/");
private static final Set<String> CONTAINER_OWNED_FILES = Set.of("/etc/hostname", "/etc/resolv.conf", "/etc/hosts");

private final Path mountInfo;
private final List<Path> markers;
private final Supplier<String> hostname;

@Autowired
public ContainerEnvironment() {
this(Path.of("/proc/self/mountinfo"), List.of(Path.of("/.dockerenv"), Path.of("/run/.containerenv")), () -> System.getenv("HOSTNAME"));
}

ContainerEnvironment(Path mountInfo, List<Path> markers, Supplier<String> hostname) {
this.mountInfo = mountInfo;
this.markers = markers;
this.hostname = hostname;
}

public boolean insideContainer() {
return markers.stream().anyMatch(Files::exists) || mountedContainerId().isPresent();
}

public List<String> containerIdCandidates() {
List<String> candidates = new ArrayList<>();
Optional<String> mounted = mountedContainerId();
if (mounted.isPresent()) {
return List.of(mounted.get());
}
String name = hostname.get();
if (name != null && !name.isBlank() && !candidates.contains(name.strip())) {
candidates.add(name.strip());
}
return candidates;
}

private Optional<String> mountedContainerId() {
try {
for (String line : Files.readAllLines(mountInfo)) {
String[] fields = line.split(" ");
if (fields.length > 4 && CONTAINER_OWNED_FILES.contains(fields[4])) {
Matcher matcher = CONTAINER_ID.matcher(line);
if (matcher.find()) {
return Optional.of(matcher.group(1));
}
}
}
} catch (IOException | RuntimeException e) {
LOGGER.debug("Unable to read {}", mountInfo, e);
}
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package wellatleastitried.mediagarrdServer.service;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.github.dockerjava.api.command.InspectContainerResponse;

@Component
public class DatabaseHostPathResolver {

private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHostPathResolver.class);

private final DockerService docker;
private final ContainerEnvironment environment;

public DatabaseHostPathResolver(DockerService docker, ContainerEnvironment environment) {
this.docker = docker;
this.environment = environment;
}

public Path resolve(Path databaseFile) throws IOException {
Path real = databaseFile.toRealPath();
if (!environment.insideContainer()) {
return real;
}

List<String> candidates = environment.containerIdCandidates();
if (candidates.isEmpty()) {
throw new IOException("The server is running in a container but its container ID could not be determined");
}

List<String> failures = new ArrayList<>();
for (String containerId : candidates) {
try {
Path hostPath = mapThroughMounts(real, docker.mountsOf(containerId));
if (hostPath != null) {
return hostPath;
}
failures.add(containerId + ": no mount covers " + real);
} catch (IOException e) {
failures.add(containerId + ": " + e.getMessage());
} catch (RuntimeException e) {
LOGGER.debug("Unable to inspect container {}", containerId, e);
failures.add(containerId + ": " + e.getMessage());
}
}
throw new IOException("Unable to resolve the host path of " + real + " (" + String.join("; ", failures) + ")");
}

private static Path mapThroughMounts(Path real, List<InspectContainerResponse.Mount> mounts) throws IOException {
InspectContainerResponse.Mount best = null;
Path bestDestination = null;
for (InspectContainerResponse.Mount mount : mounts) {
if (mount.getDestination() == null || mount.getDestination().getPath() == null) {
continue;
}
Path destination = Path.of(mount.getDestination().getPath()).normalize();
if (real.startsWith(destination)
&& (bestDestination == null || destination.getNameCount() > bestDestination.getNameCount())) {
best = mount;
bestDestination = destination;
}
}
if (best == null) {
return null;
}
String source = best.getSource();
if (source == null || source.isBlank()) {
throw new IOException("the mount at " + bestDestination + " has no host source");
}
Path sourcePath = Path.of(source);
Path hostPath = sourcePath.resolve(bestDestination.relativize(real).toString()).normalize();
if (!sourcePath.isAbsolute() || hostPath.equals(hostPath.getRoot()) || !hostPath.startsWith(sourcePath.normalize())) {
throw new IOException("the mount source " + source + " does not give a usable host path");
}
return hostPath;
}
}
Loading
Loading