diff --git a/CHANGELOG b/CHANGELOG index 23fc174..f3c0b04 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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 -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 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md index 8b9ae6a..f963bc2 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ 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 @@ -75,9 +77,11 @@ sudo bsdtar -xpf .zip -C / ``` Extract into an empty directory with `-C ` 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 .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) diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index ca4f5f8..43354ad 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -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; @@ -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 DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private final DatabaseService db; private final AtomicReference> cachedArchives = new AtomicReference<>(null); @@ -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 openParts = new ArrayList<>(); SortedMap entries = new TreeMap<>(); + Set 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)); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 07d88b1..2729377 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -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; @@ -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; @@ -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(); @@ -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; } @@ -156,19 +161,32 @@ public BackupRunResult runBackup() { 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()); + 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 { @@ -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; } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java new file mode 100644 index 0000000..ded1f51 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java @@ -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 CONTAINER_OWNED_FILES = Set.of("/etc/hostname", "/etc/resolv.conf", "/etc/hosts"); + + private final Path mountInfo; + private final List markers; + private final Supplier 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 markers, Supplier hostname) { + this.mountInfo = mountInfo; + this.markers = markers; + this.hostname = hostname; + } + + public boolean insideContainer() { + return markers.stream().anyMatch(Files::exists) || mountedContainerId().isPresent(); + } + + public List containerIdCandidates() { + List candidates = new ArrayList<>(); + Optional 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 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(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java new file mode 100644 index 0000000..90f8b54 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java @@ -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 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 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 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; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 0918d5b..ac34cfc 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -32,12 +32,15 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.sqlite.SQLiteErrorCode; +import org.sqlite.SQLiteConfig; import org.sqlite.SQLiteException; +import org.sqlite.SQLiteOpenMode; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -65,6 +68,9 @@ public class DatabaseService { private static final List DATABASE_FILE_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + private static final List REQUIRED_TABLES = List.of("backups", "backup_services", "services", "settings"); + + private final ReentrantReadWriteLock databaseLock = new ReentrantReadWriteLock(); private final Path databaseFile; private final String databaseUrl; private volatile SchemaFingerprint verifiedSchema; @@ -284,6 +290,7 @@ protected void setDatabaseVersion(Connection connection, int version) { } public void addNewBackupRecord(BackupRunResult backupRecord) { + databaseLock.readLock().lock(); try (var connection = openVerifiedConnection()) { connection.setAutoCommit(false); Integer backupId = addMasterBackup(connection, backupRecord); @@ -294,6 +301,8 @@ public void addNewBackupRecord(BackupRunResult backupRecord) { LOGGER.warn("Could not log record of backup: " + backupRecord.runId(), sE); } catch (Exception e) { LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } finally { + databaseLock.readLock().unlock(); } } @@ -364,6 +373,7 @@ private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs public Optional fetchBackupById(String archiveId) { FetchedBackupRecord backupRecord = null; + databaseLock.readLock().lock(); try (var connection = openVerifiedConnection()) { backupRecord = fetchMasterRecordById(connection, archiveId); if (backupRecord != null) { @@ -373,6 +383,8 @@ public Optional fetchBackupById(String archiveId) { LOGGER.warn("An error occurred while fetching a backup record by archive_id (" + archiveId + ")", sE); } catch (Exception e) { LOGGER.warn("An unknown error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); + } finally { + databaseLock.readLock().unlock(); } return Optional.ofNullable(backupRecord); @@ -392,6 +404,7 @@ private FetchedBackupRecord fetchMasterRecordById(Connection connection, String public Optional fetchLatestBackupRecord() { FetchedBackupRecord backupRecord = null; + databaseLock.readLock().lock(); try (var connection = openVerifiedConnection()) { backupRecord = fetchLatestMasterRecord(connection); if (backupRecord != null) { @@ -401,6 +414,8 @@ public Optional fetchLatestBackupRecord() { LOGGER.warn("An error occurred while fetching the latest backup record", sE); } catch (Exception e) { LOGGER.warn("An unknown error occurred while fetching the latest backup record", e); + } finally { + databaseLock.readLock().unlock(); } return Optional.ofNullable(backupRecord); @@ -454,6 +469,7 @@ private void handleSqlException(Connection connection) { } public void deleteBackupRecordById(String archiveId) { + databaseLock.readLock().lock(); try (var connection = openVerifiedConnection(); var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { statement.setString(1, archiveId); @@ -461,6 +477,8 @@ public void deleteBackupRecordById(String archiveId) { } catch (SQLException sE) { invalidateIfDamaged(sE); LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); + } finally { + databaseLock.readLock().unlock(); } } @@ -520,15 +538,78 @@ private int update(String action, String sql, String... params) { } private T execute(String action, String sql, String[] params, StatementWork work) { - for (int attempt = 1; ; attempt++) { - try (var connection = openVerifiedConnection(); var statement = connection.prepareStatement(sql)) { - bind(statement, params); - return work.run(statement); - } catch (SQLException sE) { - if (attempt > 1 || !invalidateIfDamaged(sE)) { - throw new IllegalStateException("Failed to " + action, sE); + databaseLock.readLock().lock(); + try { + for (int attempt = 1; ; attempt++) { + try (var connection = openVerifiedConnection(); var statement = connection.prepareStatement(sql)) { + bind(statement, params); + return work.run(statement); + } catch (SQLException sE) { + if (attempt > 1 || !invalidateIfDamaged(sE)) { + throw new IllegalStateException("Failed to " + action, sE); + } + LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", sE.getMessage()); + } + } + } finally { + databaseLock.readLock().unlock(); + } + } + + public Path databaseFile() { + return databaseFile; + } + + public void snapshotTo(Path target) throws SQLException, IOException { + databaseLock.writeLock().lock(); + try { + if (Files.exists(target)) { + throw new IOException("Snapshot target " + target + " already exists"); + } + try { + if (!Files.isRegularFile(databaseFile)) { + throw new IOException("Database file " + databaseFile + " does not exist"); } - LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", sE.getMessage()); + try (var connection = openSnapshotConnection(databaseFile)) { + checkNotCorrupt(connection); + try (var statement = connection.createStatement()) { + statement.execute("VACUUM INTO '" + target.toString().replace("'", "''") + "'"); + } + } + verifySnapshot(target); + } catch (SQLException | IOException | RuntimeException e) { + Files.deleteIfExists(target); + throw e; + } + } finally { + databaseLock.writeLock().unlock(); + } + } + + protected Connection openSnapshotConnection(Path file) throws SQLException { + SQLiteConfig config = new SQLiteConfig(); + config.resetOpenMode(SQLiteOpenMode.CREATE); + return config.createConnection(SQLITE + file); + } + + private void verifySnapshot(Path snapshot) throws SQLException, IOException { + if (!Files.isRegularFile(snapshot)) { + throw new IOException("Snapshot was not written to " + snapshot); + } + try (var connection = openSnapshotConnection(snapshot)) { + checkNotCorrupt(connection); + if (getDatabaseVersion(connection) < 1) { + throw new SQLException("Snapshot is missing its schema version"); + } + List tables = new ArrayList<>(); + try (var statement = connection.createStatement(); + var rs = statement.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table'")) { + while (rs.next()) { + tables.add(rs.getString(1)); + } + } + if (!tables.containsAll(REQUIRED_TABLES)) { + throw new SQLException("Snapshot is missing tables, found " + tables); } } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java new file mode 100644 index 0000000..03a9ecf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -0,0 +1,87 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.sql.SQLException; +import java.util.Map; +import java.util.Objects; + +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; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; + +@Service +public class DatabaseSnapshotService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSnapshotService.class); + + static final String SERVICE_NAME = "_mediagarrd-server"; + static final String PART_DIRECTORY = ".mediagarrd-server"; + static final String PART_NAME = "database.zip"; + private static final String SNAPSHOT_FILE = "snapshot.db"; + + private final DatabaseService db; + private final DatabaseHostPathResolver hostPaths; + + public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths) { + this.db = db; + this.hostPaths = hostPaths; + } + + public BackupServiceResult snapshot(Path runDirectory) { + String startTime = recordCurrentTime(); + Path directory = runDirectory.resolve(PART_DIRECTORY); + Path snapshot = directory.resolve(SNAPSHOT_FILE); + Path part = directory.resolve(PART_NAME); + try { + if (!Files.isRegularFile(db.databaseFile())) { + throw new IOException("Database file " + db.databaseFile() + " does not exist"); + } + Path 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); + } 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())); + } finally { + deleteQuietly(snapshot); + } + } + + 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(); + } + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + LOGGER.warn("Unable to remove {}", file, e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java index 0349418..eb36c32 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.HostConfig; @@ -58,6 +59,11 @@ public InputStream copyFrom(String containerId, String hostPath) { return client.copyArchiveFromContainerCmd(containerId, containerPath(hostPath)).exec(); } + public List mountsOf(String containerId) { + List mounts = client.inspectContainerCmd(containerId).exec().getMounts(); + return mounts == null ? List.of() : mounts; + } + public void removeContainers(String serviceName) { try { managedContainers(serviceName).forEach(container -> removeContainer(container.getId())); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java index 2040666..cff0ff2 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java @@ -167,7 +167,7 @@ private static ZipArchiveEntry renamed(ZipArchiveEntry target, String name) { return entry; } - private static X7875_NewUnix owner(long uid, long gid) { + static X7875_NewUnix owner(long uid, long gid) { X7875_NewUnix owner = new X7875_NewUnix(); owner.setUID(uid); owner.setGID(gid); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 947f80e..9a1cfa6 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -4,6 +4,8 @@ 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 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.ServiceBackupRunnerTest.dir; @@ -14,6 +16,7 @@ import java.nio.file.Files; import java.nio.file.Path; +import java.sql.DriverManager; import java.util.List; import java.util.Map; @@ -285,6 +288,51 @@ void startupCleanupRemovesStaleArtifacts() throws Exception { assertFalse(Files.exists(tempZip)); } + @Test + void theDatabaseSnapshotAlwaysWinsOverServiceCopiesOfTheSamePath() 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( + 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"))); + + var snapshot = new DatabaseSnapshotService(db, hostPaths).snapshot(run); + BackupArchive archive = service.createArchive(run); + + assertEquals(COMPLETED, snapshot.status()); + assertEquals( + List.of("srv/mediagarrd/db/", entry, "srv/mediagarrd/db/notes.txt"), + List.copyOf(contents(archive.path()).keySet())); + assertEquals("keep", contents(archive.path()).get("srv/mediagarrd/db/notes.txt")); + Path extracted = tempDir.resolve("extracted.db"); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + Files.copy(zip.getInputStream(zip.getEntry(entry)), extracted); + } + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + extracted); + var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals("/marker", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + } + } + + @Test + void archivesWithoutASnapshotPartStillMerge() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x"))); + + BackupArchive archive = service.createArchive(run); + + assertEquals(List.of("srv/radarr"), List.copyOf(contents(archive.path()).keySet())); + } + 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)); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index 5c6f7fe..33d03c2 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -36,6 +37,7 @@ class BackupOrchestratorServiceTest { private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); private static final ServiceDefinition SONARR = new ServiceDefinition("sonarr", List.of("/srv/sonarr")); + private static final String SNAPSHOT = DatabaseSnapshotService.SERVICE_NAME; private static final Path RUN_DIR = Path.of("/tmp/run"); private static final BackupArchive ARCHIVE = new BackupArchive("archive-1", "archive-1.zip", Path.of("archive-1.zip"), 1, Instant.EPOCH); @@ -43,12 +45,14 @@ class BackupOrchestratorServiceTest { private final BackupArchiveService archives = mock(BackupArchiveService.class); private final BackupScheduleService schedule = mock(BackupScheduleService.class); private final DatabaseService db = mock(DatabaseService.class); - private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, db); + private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db); @BeforeEach void setUp() { when(archives.createRunDirectory()).thenReturn(RUN_DIR); when(archives.createArchive(RUN_DIR)).thenReturn(ARCHIVE); + when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(COMPLETED)); } @AfterEach @@ -74,7 +78,7 @@ void completedWhenEveryServiceSucceeds() { assertEquals(COMPLETED, result.status()); assertEquals("", result.errorMessage()); - assertEquals(List.of("radarr", "sonarr"), result.serviceNames()); + assertEquals(List.of("radarr", "sonarr", SNAPSHOT), result.serviceNames()); result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); verify(schedule).markRunStarted(); verify(db).addNewBackupRecord(result); @@ -91,6 +95,55 @@ void partialWhenSomeServicesFail() { assertEquals("sonarr: boom", result.errorMessage()); } + @Test + void partialWhenOnlyTheDatabaseSnapshotFails() { + givenResults(COMPLETED, COMPLETED); + when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals(SNAPSHOT + ": boom", result.errorMessage()); + assertEquals(ARCHIVE, result.archive()); + result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); + verify(db).addNewBackupRecord(result); + } + + @Test + void snapshotFailureIsAddedToTheServiceErrors() { + givenResults(COMPLETED, FAILED); + when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("sonarr: boom\n" + SNAPSHOT + ": boom", result.errorMessage()); + } + + @Test + void aThrowingSnapshotStillProducesAPartialArchive() { + givenResults(COMPLETED, COMPLETED); + when(snapshots.snapshot(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals(SNAPSHOT + ": docker down", result.errorMessage()); + assertEquals(ARCHIVE, result.archive()); + verify(db).addNewBackupRecord(result); + } + + @Test + void snapshotRunsBeforeTheArchiveIsCreated() { + givenResults(COMPLETED, COMPLETED); + + orchestrator.runBackup(); + + var order = inOrder(snapshots, archives); + order.verify(snapshots).snapshot(RUN_DIR); + order.verify(archives).createArchive(RUN_DIR); + } + @Test void failedWhenNoServiceCompletes() { givenResults(PARTIAL, FAILED); @@ -106,6 +159,7 @@ 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()); @@ -223,6 +277,10 @@ private void givenResults(String radarrStatus, String sonarrStatus) { when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", sonarrStatus)); } + private static BackupServiceResult snapshotResult(String status) { + return result(SNAPSHOT, status); + } + private static BackupServiceResult result(String name, String status) { return new BackupServiceResult(null, status, "start", "end", name, COMPLETED.equals(status) ? null : "boom"); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java new file mode 100644 index 0000000..71c77c3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java @@ -0,0 +1,84 @@ +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 java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ContainerEnvironmentTest { + + private static final String ID = "0123456789abcdef".repeat(4); + + @TempDir + Path tempDir; + + @Test + void findsTheContainerIdFromTheHostnameMountEvenWhenHostnameIsWrong() throws Exception { + ContainerEnvironment environment = environment(mountInfo( + "1 2 0:1 / / rw - overlay overlay rw", + "3 1 8:1 /var/lib/docker/containers/" + ID + "/resolv.conf /etc/resolv.conf rw - ext4 /dev/sda1 rw", + "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"), "my-host"); + + assertTrue(environment.insideContainer()); + assertEquals(List.of(ID), environment.containerIdCandidates()); + } + + @Test + void neverFallsBackToTheHostnameWhenMountinfoGivesAnId() throws Exception { + ContainerEnvironment environment = environment(mountInfo( + "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"), "other-container"); + + assertEquals(List.of(ID), environment.containerIdCandidates()); + } + + @Test + void findsRootlessDockerContainers() throws Exception { + String line = "4 1 8:1 /home/u/.local/share/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"; + + assertEquals(List.of(ID), environment(mountInfo(line), null).containerIdCandidates()); + } + + @Test + void ignoresContainerPathsMountedSomewhereElse() throws Exception { + ContainerEnvironment environment = environment(mountInfo( + "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /srv/other rw - ext4 /dev/sda1 rw"), null); + + assertFalse(environment.insideContainer()); + assertEquals(List.of(), environment.containerIdCandidates()); + } + + @Test + void fallsBackToTheHostnameOnly() throws Exception { + ContainerEnvironment environment = environment(mountInfo("1 2 0:1 / / rw - ext4 /dev/sda1 rw"), " abc123 "); + + assertEquals(List.of("abc123"), environment.containerIdCandidates()); + } + + @Test + void aMarkerFileMeansInsideAContainer() throws Exception { + Path marker = Files.createFile(tempDir.resolve(".dockerenv")); + ContainerEnvironment environment = new ContainerEnvironment(tempDir.resolve("missing"), List.of(marker), () -> null); + + assertTrue(environment.insideContainer()); + assertEquals(List.of(), environment.containerIdCandidates()); + } + + @Test + void notInsideAContainerWithoutMarkersOrMountedHostFiles() throws Exception { + assertFalse(environment(mountInfo("1 2 0:1 / / rw - ext4 /dev/sda1 rw"), "host").insideContainer()); + } + + private Path mountInfo(String... lines) throws Exception { + return Files.write(tempDir.resolve("mountinfo"), List.of(lines)); + } + + private ContainerEnvironment environment(Path mountInfo, String hostname) { + return new ContainerEnvironment(mountInfo, List.of(tempDir.resolve("no-marker")), () -> hostname); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java new file mode 100644 index 0000000..559a0c5 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java @@ -0,0 +1,153 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Volume; + +class DatabaseHostPathResolverTest { + + @TempDir + Path tempDir; + + private final DockerService docker = mock(DockerService.class); + private final ContainerEnvironment environment = mock(ContainerEnvironment.class); + private final DatabaseHostPathResolver resolver = new DatabaseHostPathResolver(docker, environment); + + private Path database; + private Path databaseDirectory; + + @BeforeEach + void setUp() throws Exception { + databaseDirectory = Files.createDirectories(tempDir.toRealPath().resolve("db")); + database = Files.createFile(databaseDirectory.resolve("mediagarrd.db")); + when(environment.insideContainer()).thenReturn(true); + when(environment.containerIdCandidates()).thenReturn(List.of("abc")); + } + + @Test + void usesThePathAsIsOutsideAContainer() throws Exception { + when(environment.insideContainer()).thenReturn(false); + + assertEquals(database, resolver.resolve(database)); + + verify(docker, never()).mountsOf(anyString()); + } + + @Test + void mapsThroughABindMount() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/home/u/data/server/db"))); + + assertEquals(Path.of("/home/u/data/server/db/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void mapsThroughANamedVolume() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/var/lib/docker/volumes/db/_data"))); + + assertEquals(Path.of("/var/lib/docker/volumes/db/_data/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void picksTheLongestMatchingMount() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of( + mount(tempDir.toRealPath().toString(), "/outer"), + mount(databaseDirectory.toString(), "/inner"), + mount("/", "/rootfs"))); + + assertEquals(Path.of("/inner/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void doesNotMatchASiblingWithTheSamePrefix() throws Exception { + Path sibling = Files.createDirectories(tempDir.toRealPath().resolve("dbx")); + when(docker.mountsOf("abc")).thenReturn(List.of(mount(sibling.toString(), "/elsewhere"))); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("no mount covers")); + } + + @Test + void mapsAMountOfTheDatabaseFileItself() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(database.toString(), "/home/u/mediagarrd.db"))); + + assertEquals(Path.of("/home/u/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void failsForAMountWithoutAHostSource() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), ""))); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("no host source")); + } + + @Test + void failsWhenTheDatabaseIsInTheWritableLayer() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount("/tmp/else", "/home/u/else"))); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void failsWhenInspectThrows() { + when(docker.mountsOf("abc")).thenThrow(new NotFoundException("gone")); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("gone")); + } + + @Test + void failsWhenTheContainerIdIsUnknown() { + when(environment.containerIdCandidates()).thenReturn(List.of()); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void failsWhenTheSourceIsNotAbsolute() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "relative/db"))); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void fallsBackToTheNextCandidateWhenTheFirstDoesNotCoverTheDatabase() throws Exception { + when(environment.containerIdCandidates()).thenReturn(List.of("host-name", "abc")); + when(docker.mountsOf("host-name")).thenThrow(new NotFoundException("no such container")); + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/home/u/db"))); + + assertEquals(Path.of("/home/u/db/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void failsWhenTheDatabaseFileDoesNotExist() throws Exception { + Files.delete(database); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + private static InspectContainerResponse.Mount mount(String destination, String source) { + return new InspectContainerResponse.Mount().withDestination(new Volume(destination)).withSource(source); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java index 6c74602..1f3ee24 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; @@ -16,10 +17,16 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; @@ -302,6 +309,145 @@ void movesACorruptDatabaseAsideWhileRunning() throws Exception { assertEquals(1, quarantinedContents().size()); } + @Test + void snapshotIsAValidCopyWithTheSameRowsAndVersion() throws Exception { + db.addService(RADARR); + db.saveSetting("backup_root", "/backups"); + db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + Path snapshot = tempDir.resolve("snapshot.db"); + + db.snapshotTo(snapshot); + + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + snapshot); var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals(2, statement.executeQuery("PRAGMA user_version").getInt(1)); + assertEquals("/backups", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + assertEquals("radarr", statement.executeQuery("SELECT name FROM services").getString(1)); + assertEquals("run-1", statement.executeQuery("SELECT archive_id FROM backups").getString(1)); + assertEquals("radarr", statement.executeQuery("SELECT service_name FROM backup_services").getString(1)); + } + assertEquals(List.of(RADARR), db.fetchServices()); + } + + @Test + void snapshotHandlesQuotesInTheTargetPath() throws Exception { + Path snapshot = Files.createDirectories(tempDir.resolve("it's here")).resolve("snapshot.db"); + + db.snapshotTo(snapshot); + + assertTrue(Files.isRegularFile(snapshot)); + } + + @Test + void snapshotRefusesToOverwriteAnExistingFile() throws Exception { + Path existing = tempDir.resolve("existing.db"); + Files.writeString(existing, "keep me"); + + assertThrows(IOException.class, () -> db.snapshotTo(existing)); + + assertEquals("keep me", Files.readString(existing)); + } + + @Test + void snapshotFailsForAMissingDatabaseWithoutCreatingOne() throws Exception { + Files.delete(databaseFile()); + Path snapshot = tempDir.resolve("snapshot.db"); + + assertThrows(IOException.class, () -> db.snapshotTo(snapshot)); + + assertFalse(Files.exists(databaseFile())); + assertFalse(Files.exists(snapshot)); + } + + @Test + void snapshotFailsForACorruptDatabaseWithoutMovingItAside() throws Exception { + Files.writeString(databaseFile(), "x".repeat(4096)); + Path snapshot = tempDir.resolve("snapshot.db"); + + assertThrows(SQLException.class, () -> db.snapshotTo(snapshot)); + + assertFalse(Files.exists(snapshot)); + assertEquals("x".repeat(4096), Files.readString(databaseFile())); + assertEquals(List.of(), quarantinedContents()); + } + + @Test + void writesWaitWhileTheSnapshotIsBeingTaken() throws Exception { + CountDownLatch snapshotting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + DatabaseService paused = new DatabaseService(properties) { + @Override + protected Connection openSnapshotConnection(Path file) throws SQLException { + snapshotting.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return super.openSnapshotConnection(file); + } + }; + paused.saveSetting("backup_root", "/before"); + + CompletableFuture snapshot = CompletableFuture.runAsync(() -> { + try { + paused.snapshotTo(tempDir.resolve("snapshot.db")); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + assertTrue(snapshotting.await(5, TimeUnit.SECONDS)); + + CompletableFuture write = CompletableFuture.runAsync(() -> paused.saveSetting("backup_root", "/during")); + CompletableFuture delete = CompletableFuture.runAsync(() -> paused.deleteBackupRecordById("none")); + CompletableFuture insert = CompletableFuture.runAsync(() -> + paused.addNewBackupRecord(backupRun("run-2", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null)))); + assertThrows(TimeoutException.class, () -> write.get(300, TimeUnit.MILLISECONDS)); + assertFalse(delete.isDone()); + assertFalse(insert.isDone()); + + release.countDown(); + snapshot.get(5, TimeUnit.SECONDS); + write.get(5, TimeUnit.SECONDS); + delete.get(5, TimeUnit.SECONDS); + insert.get(5, TimeUnit.SECONDS); + + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + tempDir.resolve("snapshot.db")); + var statement = connection.createStatement()) { + assertEquals("/before", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + assertFalse(statement.executeQuery("SELECT 1 FROM backups").next()); + } + assertEquals(Optional.of("/during"), paused.fetchSetting("backup_root")); + assertTrue(paused.fetchBackupById("run-2").isPresent()); + } + + @Test + void snapshotsDoNotDeadlockWithIntegrityChecksAndWrites() { + assertTimeoutPreemptively(Duration.ofSeconds(60), () -> { + List> work = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + int worker = i; + work.add(CompletableFuture.runAsync(() -> { + for (int n = 0; n < 15; n++) { + try { + db.snapshotTo(tempDir.resolve("snapshot-" + worker + "-" + n + ".db")); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + })); + work.add(CompletableFuture.runAsync(() -> { + for (int n = 0; n < 30; n++) { + db.saveSetting("backup_root", "/" + n); + db.fetchServices(); + db.verifyDatabaseIntegrity(); + } + })); + } + CompletableFuture.allOf(work.toArray(CompletableFuture[]::new)).get(); + }); + } + private Path databaseFile() { return Path.of(properties.getDatabasePath()); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java new file mode 100644 index 0000000..5ee1cb7 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -0,0 +1,133 @@ +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.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.sql.DriverManager; +import java.util.Collections; +import java.util.List; + +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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class DatabaseSnapshotServiceTest { + + private static final Path HOST_DATABASE = Path.of("/srv/mediagarrd/db/mediagarrd.db"); + + @TempDir + Path tempDir; + + private DatabaseService db; + private DatabaseHostPathResolver hostPaths; + private DatabaseSnapshotService snapshots; + private Path run; + + @BeforeEach + void setUp() throws Exception { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("db/mediagarrd.db").toString()); + db = new DatabaseService(properties); + hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.databaseFile())).thenReturn(HOST_DATABASE); + snapshots = new DatabaseSnapshotService(db, hostPaths); + run = Files.createDirectories(tempDir.resolve("run")); + } + + @Test + void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { + db.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); + Files.setPosixFilePermissions(db.databaseFile(), PosixFilePermissions.fromString("rw-r-----")); + Integer uid = (Integer) Files.getAttribute(db.databaseFile(), "unix:uid"); + Integer gid = (Integer) Files.getAttribute(db.databaseFile(), "unix:gid"); + + BackupServiceResult result = snapshots.snapshot(run); + + 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()) { + 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); + X7875_NewUnix owner = (X7875_NewUnix) entry.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(uid.longValue(), owner.getUID()); + assertEquals(gid.longValue(), owner.getGID()); + + Path extracted = tempDir.resolve("extracted.db"); + Files.copy(zip.getInputStream(entry), extracted); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + extracted); var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals(2, statement.executeQuery("PRAGMA user_version").getInt(1)); + assertEquals("radarr", statement.executeQuery("SELECT name FROM services").getString(1)); + } + } + assertFalse(Files.exists(run.resolve(DatabaseSnapshotService.PART_DIRECTORY).resolve("snapshot.db"))); + } + + @Test + void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { + when(hostPaths.resolve(db.databaseFile())).thenThrow(new IOException("no mount covers the database")); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("no mount covers the database", result.errorMessage()); + assertNoPart(); + } + + @Test + void failsWithoutAPartWhenTheDatabaseIsMissing() throws Exception { + Files.delete(db.databaseFile()); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("Database file " + db.databaseFile() + " does not exist", result.errorMessage()); + assertFalse(Files.exists(db.databaseFile())); + assertNoPart(); + } + + @Test + void failsWithoutAPartWhenTheDatabaseIsCorrupt() throws Exception { + Files.writeString(db.databaseFile(), "x".repeat(4096)); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("x".repeat(4096), Files.readString(db.databaseFile())); + assertNoPart(); + } + + @Test + void resolverFailuresOfAnyKindBecomeAFailedResult() throws Exception { + when(hostPaths.resolve(db.databaseFile())).thenThrow(new IllegalStateException("docker down")); + + assertEquals("docker down", snapshots.snapshot(run).errorMessage()); + } + + private void assertNoPart() throws IOException { + Path directory = run.resolve(DatabaseSnapshotService.PART_DIRECTORY); + if (Files.exists(directory)) { + try (var files = Files.list(directory)) { + assertTrue(files.toList().isEmpty()); + } + } + } +}