From e11166db1d89a3e123c6aca9e2029fe020af30fc Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Fri, 18 Sep 2026 16:59:37 -0500 Subject: [PATCH 01/26] Implement database functionality to keep records of previous runs. --- .github/ISSUE_TEMPLATE/bug_report.md | 33 ++ .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/feature_request.md | 21 ++ .github/ISSUE_TEMPLATE/new_service_request.md | 19 ++ CHANGELOG | 4 + CONTRIBUTING.md | 12 + .../mediagarrd/Constants.java | 30 -- .../mediagarrd/MediaGarrd.java | 2 +- .../mediagarrd/MediaGarrdProperties.java | 7 +- .../mediagarrd/MediaGarrdUtilities.java | 173 +++++++++++ .../mediagarrd/ServicesProperties.java | 7 +- .../mediagarrd/api/BackupController.java | 34 ++- .../mediagarrd/dto/BackupDto.java | 2 +- .../mediagarrd/dto/BackupRunDto.java | 6 +- .../mediagarrd/dto/ScheduleUpdateRequest.java | 2 +- .../mediagarrd/dto/ServerStatusDto.java | 2 +- .../mediagarrd/model/BackupArchive.java | 32 +- .../mediagarrd/model/BackupRunResult.java | 68 ++++- .../mediagarrd/model/BackupServiceResult.java | 50 ++++ .../mediagarrd/model/FetchedBackupRecord.java | 11 + .../model/FetchedBackupServiceRecord.java | 18 ++ .../service/BackupArchiveService.java | 7 +- .../service/BackupOrchestratorService.java | 96 ++++-- .../service/BackupScheduleService.java | 4 +- .../mediagarrd/service/DatabaseService.java | 236 +++++++++++++++ .../mediagarrd/service/RunnerFactory.java | 10 +- .../config/AbstractServiceConfig.java | 2 +- .../services/config/CommonServiceConfig.java | 2 +- .../config/QBittorrentServiceConfig.java | 2 +- .../runner/AbstractLocalCopyRunner.java | 53 +++- .../services/runner/JellyfinRunner.java | 6 +- .../services/runner/ProwlarrRunner.java | 6 +- .../services/runner/QBittorrentRunner.java | 6 +- .../services/runner/RadarrRunner.java | 6 +- .../mediagarrd/services/runner/Runner.java | 10 +- .../services/runner/SonarrRunner.java | 6 +- .../services/runner/TdarrRunner.java | 6 +- .../mediagarrdServer/MediaGarrd.java | 16 + .../MediaGarrdProperties.java | 57 ++++ .../mediagarrdServer/MediaGarrdUtilities.java | 173 +++++++++++ .../mediagarrdServer/ServicesProperties.java | 84 ++++++ .../api/BackupController.java | 183 ++++++++++++ .../mediagarrdServer/dto/BackupDto.java | 11 + .../mediagarrdServer/dto/BackupRunDto.java | 13 + .../dto/ScheduleUpdateRequest.java | 5 + .../mediagarrdServer/dto/ServerStatusDto.java | 10 + .../mediagarrdServer/model/BackupArchive.java | 43 +++ .../model/BackupRunResult.java | 63 ++++ .../model/BackupServiceResult.java | 50 ++++ .../model/FetchedBackupRecord.java | 11 + .../model/FetchedBackupServiceRecord.java | 18 ++ .../model/FetchedServiceBackupRecord.java | 24 ++ .../service/BackupArchiveService.java | 281 ++++++++++++++++++ .../service/BackupOrchestratorService.java | 206 +++++++++++++ .../service/BackupScheduleService.java | 63 ++++ .../service/DatabaseService.java | 236 +++++++++++++++ .../service/RunnerFactory.java | 114 +++++++ .../config/AbstractServiceConfig.java | 37 +++ .../services/config/CommonServiceConfig.java | 5 + .../config/QBittorrentServiceConfig.java | 16 + .../runner/AbstractLocalCopyRunner.java | 188 ++++++++++++ .../services/runner/JellyfinRunner.java | 22 ++ .../services/runner/ProwlarrRunner.java | 22 ++ .../services/runner/QBittorrentRunner.java | 38 +++ .../services/runner/RadarrRunner.java | 22 ++ .../services/runner/Runner.java | 18 ++ .../services/runner/SonarrRunner.java | 22 ++ .../services/runner/TdarrRunner.java | 22 ++ .../MediaGarrdPropertiesBindingTest.java | 11 +- .../api/BackupControllerTest.java | 13 +- .../service/BackupArchiveServiceTest.java | 5 +- .../service/BackupScheduleServiceTest.java | 5 +- .../service/DatabaseServiceTest.java | 5 + .../service/RealRunnersInteractiveCheck.java | 13 +- .../service/RunnersIntegrationTest.java | 13 +- 75 files changed, 2970 insertions(+), 160 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/new_service_request.md create mode 100644 CONTRIBUTING.md delete mode 100644 src/main/java/wellatleastitried/mediagarrd/Constants.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/MediaGarrdPropertiesBindingTest.java (73%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/api/BackupControllerTest.java (84%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/BackupArchiveServiceTest.java (84%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/BackupScheduleServiceTest.java (81%) create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/RealRunnersInteractiveCheck.java (90%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/RunnersIntegrationTest.java (93%) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..9b52043 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]: " +labels: bug, needs-triage +assignees: '' +type: Bug + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Device(s) (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e17b1ba --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEAT]: " +labels: feature, needs-triage +assignees: '' +type: Feature + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/new_service_request.md b/.github/ISSUE_TEMPLATE/new_service_request.md new file mode 100644 index 0000000..836b1b7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new_service_request.md @@ -0,0 +1,19 @@ +--- +name: New service request +about: Request a new service to be support by MediaGarrd +title: "[ADD-SERVICE]: " +labels: add-service, needs-triage +assignees: '' +type: Feature + +--- + +**Name of the service:** + +**Provide a link to the service's repository:** + +**What files would need to be backed up?** +*Provide something like: `config/`, `service.db`, etc.* + +**Additional context** +*Add any other context about the new service here.* diff --git a/CHANGELOG b/CHANGELOG index 140a7e5..1324fb4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,10 @@ # CHANGELOG ## TBD +- Add database for keeping records of backups +- Add issue templates + +## 9-16-26 - Adding more detailed logging for service runners - Renaming QBittorrent's "graveyard" directory to "saved-torrents" to make it less ambiguous diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1092eb6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing to the MediaGarrd Server + +## Submitting Issues +Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the template that best fits the issue. + +The `needs-triage` label will automatically be applied. Once this issue has been reviewed/approved, the `approved` label will be added and Pull Requests can be opened referencing this issue. + +## Pull Requests +Pull requests should only be opened for issues that have the `approved` label. + +## AI Usage +See [AGENTS.md](https://github.com/MediaGarrd/Server/blob/main/AGENTS.md) for a more in-depth overview of the way AI is permitted in code submissions. If a signature is not present on a commit that even *appears* to be generated by an LLM, the PR will be closed. This is strictly for the continued maintainability of the project. diff --git a/src/main/java/wellatleastitried/mediagarrd/Constants.java b/src/main/java/wellatleastitried/mediagarrd/Constants.java deleted file mode 100644 index 94aeca9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/Constants.java +++ /dev/null @@ -1,30 +0,0 @@ -package wellatleastitried.mediagarrd; - -import java.util.EnumMap; - -//@ADD_NEW_SERVICE -public final class Constants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - - private Constants() {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java index fbe9798..9f32db2 100644 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java index 598fc10..6788f79 100644 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java @@ -1,12 +1,13 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import java.time.Duration; import java.util.EnumMap; import org.springframework.boot.context.properties.ConfigurationProperties; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java new file mode 100644 index 0000000..c95af0f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java @@ -0,0 +1,173 @@ +package wellatleastitried.mediagarrdServer; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumMap; +import java.util.List; + +//@ADD_NEW_SERVICE +public final class MediaGarrdUtilities { + private MediaGarrdUtilities() {} + + public class Utils { + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static int subtractTime(String startTime, String endTime) { + } + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) { + } + } + } + + public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } + } + + public class DatabaseConstants { + + // Migrations will be added inside of the static block + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + filename TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + services_completed, + filename, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; + + + /* + public record BackupRunResult( + String runId, + Instant startedAt, + Instant finishedAt, + List servicesRan, + BackupArchive archive + ) + public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt + ) + */ + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java index d7081dc..953e4d9 100644 --- a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java @@ -1,9 +1,10 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import java.util.EnumMap; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java index 92d11d0..0ea1ed6 100644 --- a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.api; +package wellatleastitried.mediagarrdServer.api; import java.io.IOException; import java.time.Duration; @@ -20,19 +20,20 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.dto.BackupDto; -import wellatleastitried.mediagarrd.dto.BackupRunDto; -import wellatleastitried.mediagarrd.dto.ScheduleUpdateRequest; -import wellatleastitried.mediagarrd.dto.ServerStatusDto; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; - @RestController @RequestMapping("/api/v1") public class BackupController { @@ -134,14 +135,15 @@ public ResponseEntity deleteBackup(@PathVariable String id) { public BackupRunDto runBackup() { LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); BackupRunResult result = orchestratorService.runBackup(); + var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", - result.runId(), result.servicesRan(), result.archive().fileName(), - result.finishedAt().toEpochMilli() - result.startedAt().toEpochMilli()); + result.runId(), result.serviceNames(), result.archive().fileName(), + backupDuration); return new BackupRunDto( result.runId(), - result.startedAt(), - result.finishedAt(), - result.servicesRan(), + result.startTime(), + result.endTime(), + result.serviceNames(), toDto(result.archive()) ); } diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java index e3932d2..6286b33 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Instant; diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java index e745805..00a31f9 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java @@ -1,12 +1,12 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Instant; import java.util.List; public record BackupRunDto( String runId, - Instant startedAt, - Instant finishedAt, + String startTime, + String endTime, List servicesRan, BackupDto archive ) { diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java index a0d0486..a3916da 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java index 8282d37..bd2613f 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java index 3f6300e..caeef08 100644 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java @@ -1,6 +1,11 @@ -package wellatleastitried.mediagarrd.model; +package wellatleastitried.mediagarrdServer.model; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; import java.time.Instant; public record BackupArchive( @@ -10,4 +15,29 @@ public record BackupArchive( long sizeBytes, Instant createdAt ) { + public String generateChecksum() { + Path file = Paths.get(fileName); + try { + byte[] data = Files.readAllBytes(file); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); + String checksum = new BigInteger(1, hash).toString(16); + return checksum; + } catch (Exception e) {} + return ""; + } + + public int fileSize() { + Path file = Paths.get(fileName); + + long size; + try { size = Files.size(file); } + catch (IOException iE) { size = 0; } + + if (size > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + + return (int) size; + + } } diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java index 18849bb..f46693e 100644 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java @@ -1,13 +1,63 @@ -package wellatleastitried.mediagarrd.model; +package wellatleastitried.mediagarrdServer.model; -import java.time.Instant; import java.util.List; -public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive -) { +public class BackupRunResult { + private final String runId; + private final String startTime; + private final String endTime; + private final String status; + private final List serviceResults; + private final BackupArchive archive; + private final String errorMessage; + + public BackupRunResult( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage + ) { + this.runId = runId; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.serviceResults = serviceResults; + this.archive = archive; + this.errorMessage = errorMessage; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + + public String startTime() { + return startTime; + } + + public String endTime() { + return endTime; + } + + public List serviceResults() { + return serviceResults; + } + + public List serviceNames() { + return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); + } + + public BackupArchive archive() { + return archive; + } + + public String errorMessage() { + return errorMessage; + } } diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java new file mode 100644 index 0000000..6877586 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdServer.model; + +public class BackupServiceResult { + private String runId; + private final String status; + private final String startTime; + private final String endTime; + private final String serviceName; + private final String errorMessage; + + public BackupServiceResult( + String runId, + String status, + String startTime, + String endTime, + String serviceName, + String errorMessage + ) { + this.runId = runId; + this.status = status; + this.startTime = startTime; + this.endTime = endTime; + this.serviceName = serviceName; + this.errorMessage = errorMessage; + } + + public void setId(String runId) { + this.runId = runId; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + public String startTime() { + return startTime; + } + public String endTime() { + return endTime; + } + public String serviceName() { + return serviceName; + } + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java new file mode 100644 index 0000000..65a4b40 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public record FetchedBackupRecord( + int id, + String startTime, + String status, + String filename, + List fetchedServices +) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java new file mode 100644 index 0000000..1236bf8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.model; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String serviceName, + String status, + String startTime +) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java index b90dc03..a08bcd6 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.io.IOException; import java.io.InputStream; @@ -20,14 +20,13 @@ import java.util.zip.ZipOutputStream; import jakarta.annotation.PostConstruct; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; - @Service public class BackupArchiveService { diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java index 17b49bc..8dba48a 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.nio.file.Path; import java.util.ArrayList; @@ -14,17 +14,19 @@ import java.util.concurrent.atomic.AtomicBoolean; import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.services.runner.Runner; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.services.runner.Runner; - @Service public class BackupOrchestratorService { @@ -34,11 +36,12 @@ public class BackupOrchestratorService { private final RunnerFactory runnerFactory; private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; + private final DatabaseService db; private final AtomicBoolean running = new AtomicBoolean(false); private final ExecutorService runnerExecutor = new ThreadPoolExecutor( 1, // core threads 6, // max threads - 30, // keep-alive time + 30, // ttl TimeUnit.SECONDS, new LinkedBlockingQueue<>() ); @@ -47,12 +50,14 @@ public BackupOrchestratorService( MediaGarrdProperties properties, RunnerFactory runnerFactory, BackupArchiveService archiveService, - BackupScheduleService scheduleService + BackupScheduleService scheduleService, + DatabaseService db ) { this.properties = properties; this.runnerFactory = runnerFactory; this.archiveService = archiveService; this.scheduleService = scheduleService; + this.db = db; } @Scheduled(fixedDelay = 10000) @@ -83,22 +88,26 @@ public BackupRunResult runBackup() { Path runDirectory = archiveService.createRunDirectory(); Instant startedAt = Instant.now(); List runners = runnerFactory.build(properties.getServiceConfigs()); - List servicesCompleted = new ArrayList<>(); + List serviceRunResults = new ArrayList<>(); - LOGGER.info("Backup run started: runDir={}, services={}", runDirectory, runners.stream().map(Runner::getServiceName).toList()); + LOGGER.info( + "Backup run started: runDir={}, services={}", + runDirectory, + runners.stream().map(Runner::getServiceName).toList()); try { - List> futures = new ArrayList<>(); + String errorMessage = ""; + List> futures = new ArrayList<>(); for (Runner runner : runners) { LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); } - for (Future future : futures) { + for (Future future : futures) { try { - RunnerOutcome outcome = future.get(); - if (outcome.success()) { - servicesCompleted.add(outcome.serviceName()); + BackupServiceResult outcome = future.get(); + serviceRunResults.add(outcome); + if (Status.COMPLETED.equals(outcome.status())) { LOGGER.info("Runner succeeded: {}", outcome.serviceName()); } else { LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); @@ -107,22 +116,49 @@ public BackupRunResult runBackup() { Thread.currentThread().interrupt(); throw new IllegalStateException("Backup run interrupted", ex); } catch (ExecutionException ex) { + errorMessage.concat(ex.getMessage() + "\n"); LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); } } - LOGGER.info("All runners finished: succeeded={}/{}", servicesCompleted.size(), runners.size()); + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + LOGGER.info( + "All runners finished: succeeded={}/{}", + successfulRunnerCount, + runners.size() + ); BackupArchive archive = archiveService.createArchive(runDirectory); + for (BackupServiceResult serviceResult : serviceRunResults) { + serviceResult.setId(archive.id()); + } long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), archive.sizeBytes(), durationMs, servicesCompleted); - return new BackupRunResult( + LOGGER.info( + "Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), + archive.sizeBytes(), + durationMs, + serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() + ); + + String status; + if (successfulRunnerCount == runners.size()) { + status = Status.COMPLETED; + } else if (successfulRunnerCount > 0) { + status = Status.PARTIAL; + } else { + status = Status.FAILED; + } + BackupRunResult backupRecord = new BackupRunResult( archive.id(), - startedAt, - Instant.now(), - servicesCompleted, - archive + status, + Utils.formatTime(startedAt), + Utils.recordCurrentTime(), + serviceRunResults, + archive, + errorMessage ); + db.addNewBackupRecord(backupRecord); + return backupRecord; } finally { archiveService.removeRunDirectory(runDirectory); running.set(false); @@ -147,20 +183,24 @@ public void shutdownRunnerExecutor() { runnerExecutor.shutdownNow(); } - private RunnerOutcome runSingleRunner(Runner runner, Path runDirectory) { + private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { LOGGER.info("[{}] Runner starting", runner.getServiceName()); long start = System.currentTimeMillis(); try { runner.run(runDirectory); LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); - return new RunnerOutcome(runner.getServiceName(), true); } catch (RuntimeException ex) { LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", runner.getServiceName(), System.currentTimeMillis() - start, ex); - return new RunnerOutcome(runner.getServiceName(), false); } - } - private record RunnerOutcome(String serviceName, boolean success) { + return new BackupServiceResult( + null, + runner.getRunnerStatus(), + runner.getRunnerStartTime(), + runner.getRunnerEndTime(), + runner.getServiceName(), + runner.getRunnerException() + ); } } diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java index 0d5f824..d3c8637 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.time.Duration; import java.time.Instant; @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; @Service public class BackupScheduleService { diff --git a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java new file mode 100644 index 0000000..0339e98 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; + +@Service +public class DatabaseService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); + + public DatabaseService() { + verifyDatabaseIntegrity(); + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + } catch (Exception e) { + LOGGER.warn("An error occurred while disabling auto-commit on the database", e); + } + } + + private boolean verifyDatabaseIntegrity() { + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + ensureTablesExist(connection); + runNeededMigrations(connection); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + return false; + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + return true; + } + + private void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + statement.execute(CREATE_TABLES); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("Failed to verify if tables exist in database.", sE); + handleSqlException(connection); + throw sE; + } + } + + private void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = getDatabaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion <= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException sE) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + sE + ); + handleSqlException(connection); + throw sE; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + private int getDatabaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + + return result.getInt(1); + } catch (SQLException sE) { + LOGGER.warn("Failed to fetch database version", sE); + return -1; + } + } + + private void setDatabaseVersion(Connection connection, int version) { + + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException sE) { + LOGGER.warn("Failed to set new database version", sE); + } + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); + return; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + addMasterBackup(connection, backupRecord); + addServiceBackups(connection, backupRecord.serviceResults()); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } + } + + private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + statement.setString(5, backupRecord.archive().generateChecksum()); + statement.setString(6, backupRecord.archive().fileName()); + statement.setInt(7, backupRecord.archive().fileSize()); + statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while logging a new backup record", sE); + handleSqlException(connection); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + } + + private void addServiceBackups(Connection connection, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setString(1, service.runId()); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); + handleSqlException(connection); + } + } + } + + public FetchedBackupRecord fetchLatestBackupRecord() { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch latest backup record"); + return null; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + int id = rs.getInt("id"); + String backupStartTime = rs.getString("start_time"); + String status = rs.getString("status"); + String filename = rs.getString("filename"); + return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private void handleSqlException(Connection connection) { + try { + connection.rollback(); + } catch (SQLException rollbackException) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java index 60646f3..28e2ecc 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java @@ -1,16 +1,18 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.util.ArrayList; import java.util.List; import java.util.EnumMap; import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.services.config.*; +import wellatleastitried.mediagarrdServer.services.runner.*; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; -import wellatleastitried.mediagarrd.services.runner.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java index e4954f8..974c31d 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; //import java.util.List; diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java index ba9eb66..20482e2 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; // For services that require only one path to backup, this can be used. // Otherwise, create a new config for a service-specific config. diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java index 10a9ff4..952667b 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; public class QBittorrentServiceConfig extends AbstractServiceConfig { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java index df60230..b5d0525 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.io.IOException; import java.nio.file.FileVisitResult; @@ -10,11 +10,12 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Locale; -import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; + //@ADD_NEW_SERVICE public abstract class AbstractLocalCopyRunner implements Runner { @@ -22,8 +23,15 @@ public abstract class AbstractLocalCopyRunner implements Runner { private final String serviceName; + private String startTime; + private String endTime; + private String status; + private String errorMessage; + protected AbstractLocalCopyRunner(String serviceName) { this.serviceName = serviceName; + status = "idle"; + startTime = endTime = errorMessage = ""; } @Override @@ -31,12 +39,36 @@ public String getServiceName() { return serviceName; } + @Override + public String getRunnerStartTime() { + return startTime; + } + + @Override + public String getRunnerEndTime() { + return endTime; + } + + @Override + public String getRunnerStatus() { + return status; + } + + @Override + public String getRunnerException() { + return errorMessage; + } + @Override public void run(Path outputDirectory) { + startTime = Utils.recordCurrentTime(); + status = "running"; Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); try { Files.createDirectories(serviceDirectory); } catch (IOException e) { + errorMessage = "Unable to create output directory for " + serviceName; + status = "failed"; throw new IllegalStateException("Unable to create output directory for " + serviceName, e); } @@ -52,6 +84,14 @@ public void run(Path outputDirectory) { } } LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); + if (succeeded == specs.size()) { + status = "completed"; + } else if (succeeded < specs.size() && succeeded > 0) { + status = "partial"; + } else { + status = "failed"; + } + endTime = Utils.recordCurrentTime(); } protected abstract List copySpecs(); @@ -66,12 +106,16 @@ protected CopySpec file(String sourcePath, String targetName) { private void copySpec(CopySpec spec, Path serviceDirectory) { if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - throw new IllegalArgumentException(serviceName + " runner missing source path for " + spec.targetName()); + errorMessage = serviceName + " runner missing source path for " + spec.targetName(); + status = "failed"; + throw new IllegalArgumentException(errorMessage); } Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); if (!Files.exists(source)) { - throw new IllegalStateException(serviceName + " source path not found: " + source); + errorMessage = serviceName + " source path not found: " + source; + status = "failed"; + throw new IllegalStateException(errorMessage); } Path target = serviceDirectory.resolve(spec.targetName()); @@ -94,6 +138,7 @@ private void copySpec(CopySpec spec, Path serviceDirectory) { LOGGER.debug("[{}] Copied file: {}", serviceName, target); } } catch (IOException e) { + status = "failed"; throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); } } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java index cea92d2..93dae71 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java index f98c771..e7ee6e0 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class ProwlarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java index 0679f0f..6d5eeb1 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java @@ -1,13 +1,13 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java index b55c477..259cac4 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class RadarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java index 44747c7..095420b 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.nio.file.Path; @@ -6,5 +6,13 @@ public interface Runner { String getServiceName(); + String getRunnerStartTime(); + + String getRunnerEndTime(); + + String getRunnerStatus(); + + String getRunnerException(); + void run(Path outputDirectory); } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java index beaa063..8e56234 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class SonarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java index b84cd99..7fa6bbb 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class TdarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java new file mode 100644 index 0000000..9f32db2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdServer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableConfigurationProperties(MediaGarrdProperties.class) +public class MediaGarrd { + + public static void main(String[] args) { + SpringApplication.run(MediaGarrd.class, args); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java new file mode 100644 index 0000000..6788f79 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -0,0 +1,57 @@ +package wellatleastitried.mediagarrdServer; + +import java.time.Duration; +import java.util.EnumMap; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +@ConfigurationProperties(prefix = "mediagarrd") +public class MediaGarrdProperties { + + private Duration backupInterval = Duration.ofHours(12); + private String backupRoot = "./data/server/backups"; + private int retentionCount = 10; + private ServicesProperties services = new ServicesProperties(); + + public Duration getBackupInterval() { + return backupInterval; + } + + public void setBackupInterval(Duration backupInterval) { + this.backupInterval = backupInterval; + } + + public String getBackupRoot() { + return backupRoot; + } + + public void setBackupRoot(String backupRoot) { + this.backupRoot = backupRoot; + } + + public int getRetentionCount() { + return retentionCount; + } + + public void setRetentionCount(int retentionCount) { + this.retentionCount = retentionCount; + } + + public ServicesProperties getServices() { + return services; + } + + public void setServices(ServicesProperties services) { + this.services = services; + } + + public EnumMap getServiceConfigs() { + return services.toRuntimeConfigs(); + } + + +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java new file mode 100644 index 0000000..c95af0f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java @@ -0,0 +1,173 @@ +package wellatleastitried.mediagarrdServer; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumMap; +import java.util.List; + +//@ADD_NEW_SERVICE +public final class MediaGarrdUtilities { + private MediaGarrdUtilities() {} + + public class Utils { + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static int subtractTime(String startTime, String endTime) { + } + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) { + } + } + } + + public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } + } + + public class DatabaseConstants { + + // Migrations will be added inside of the static block + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + filename TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + services_completed, + filename, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; + + + /* + public record BackupRunResult( + String runId, + Instant startedAt, + Instant finishedAt, + List servicesRan, + BackupArchive archive + ) + public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt + ) + */ + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java new file mode 100644 index 0000000..953e4d9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -0,0 +1,84 @@ +package wellatleastitried.mediagarrdServer; + +import java.util.EnumMap; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class ServicesProperties { + + //@ADD_NEW_SERVICE + private CommonServiceConfig jellyfin; + private CommonServiceConfig radarr; + private CommonServiceConfig sonarr; + private CommonServiceConfig prowlarr; + private CommonServiceConfig tdarr; + private QBittorrentServiceConfig qbittorrent; + + public EnumMap toRuntimeConfigs() { + EnumMap configs = new EnumMap<>(Services.class); + put(configs, Services.JELLYFIN, jellyfin); + put(configs, Services.RADARR, radarr); + put(configs, Services.SONARR, sonarr); + put(configs, Services.PROWLARR, prowlarr); + put(configs, Services.TDARR, tdarr); + put(configs, Services.QBITTORRENT, qbittorrent); + return configs; + } + + private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { + if (config != null) { + configs.put(service, config); + } + } + + public CommonServiceConfig getJellyfin() { + return jellyfin; + } + + public void setJellyfin(CommonServiceConfig jellyfin) { + this.jellyfin = jellyfin; + } + + public CommonServiceConfig getRadarr() { + return radarr; + } + + public void setRadarr(CommonServiceConfig radarr) { + this.radarr = radarr; + } + + public CommonServiceConfig getSonarr() { + return sonarr; + } + + public void setSonarr(CommonServiceConfig sonarr) { + this.sonarr = sonarr; + } + + public CommonServiceConfig getProwlarr() { + return prowlarr; + } + + public void setProwlarr(CommonServiceConfig prowlarr) { + this.prowlarr = prowlarr; + } + + public CommonServiceConfig getTdarr() { + return tdarr; + } + + public void setTdarr(CommonServiceConfig tdarr) { + this.tdarr = tdarr; + } + + public QBittorrentServiceConfig getQbittorrent() { + return qbittorrent; + } + + public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { + this.qbittorrent = qbittorrent; + } + +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java new file mode 100644 index 0000000..0ea1ed6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -0,0 +1,183 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.time.Duration; +import java.util.List; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RestController +@RequestMapping("/api/v1") +public class BackupController { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupController.class); + + private final BackupArchiveService archiveService; + private final BackupOrchestratorService orchestratorService; + private final MediaGarrdProperties properties; + + public BackupController( + BackupArchiveService archiveService, + BackupOrchestratorService orchestratorService, + MediaGarrdProperties properties + ) { + this.archiveService = archiveService; + this.orchestratorService = orchestratorService; + this.properties = properties; + } + + @GetMapping("/health") + public ServerStatusDto health() { + LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + return new ServerStatusDto( + true, + orchestratorService.isRunning(), + properties.getRetentionCount(), + orchestratorService.getInterval() + ); + } + + @PutMapping("/schedule") + public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { + LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); + Duration updated = orchestratorService.updateInterval(request.backupInterval()); + LOGGER.info("Schedule updated: newInterval={}", updated); + return new ServerStatusDto( + true, + orchestratorService.isRunning(), + properties.getRetentionCount(), + updated + ); + } + + @GetMapping("/backups") + public List listBackups() { + LOGGER.info("GET /api/v1/backups"); + List backups = archiveService.listArchives().stream().map(this::toDto).toList(); + LOGGER.info("Returning {} backup(s)", backups.size()); + return backups; + } + + @GetMapping("/backups/latest") + public BackupDto latestBackup() { + LOGGER.info("GET /api/v1/backups/latest"); + BackupArchive archive = archiveService.latest() + .orElseThrow(() -> notFound("No backup archives found")); + LOGGER.info("Latest backup: {}", archive.fileName()); + return toDto(archive); + } + + @GetMapping("/backups/{id}") + public BackupDto backupById(@PathVariable String id) { + LOGGER.info("GET /api/v1/backups/{}", id); + return archiveService.byId(id) + .map(this::toDto) + .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); + } + + @GetMapping("/backups/{id}/download") + public ResponseEntity downloadById(@PathVariable String id) { + LOGGER.info("GET /api/v1/backups/{}/download", id); + BackupArchive archive = archiveService.byId(id) + .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); + return downloadResponse(archive); + } + + @GetMapping("/backups/latest/download") + public ResponseEntity downloadLatest() { + LOGGER.info("GET /api/v1/backups/latest/download"); + BackupArchive archive = archiveService.latest() + .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); + return downloadResponse(archive); + } + + @DeleteMapping("/backups/{id}") + public ResponseEntity deleteBackup(@PathVariable String id) { + LOGGER.info("DELETE /api/v1/backups/{}", id); + boolean deleted = archiveService.deleteById(id); + if (!deleted) { + LOGGER.warn("Delete failed: backup not found: {}", id); + return ResponseEntity.notFound().build(); + } + LOGGER.info("Backup deleted: {}", id); + return ResponseEntity.noContent().build(); + } + + @PostMapping("/backups/run") + public BackupRunDto runBackup() { + LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); + BackupRunResult result = orchestratorService.runBackup(); + var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); + LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", + result.runId(), result.serviceNames(), result.archive().fileName(), + backupDuration); + return new BackupRunDto( + result.runId(), + result.startTime(), + result.endTime(), + result.serviceNames(), + toDto(result.archive()) + ); + } + + private ResponseEntity downloadResponse(BackupArchive archive) { + Resource file = new FileSystemResource(archive.path()); + if (!file.exists()) { + LOGGER.error("Archive file missing on disk: {}", archive.path()); + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); + } + + try { + LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(file.contentLength()) + .body(file); + } catch (IOException e) { + LOGGER.error("Failed to read backup file: {}", archive.path(), e); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); + } + } + + private BackupDto toDto(BackupArchive archive) { + return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); + } + + private ResponseStatusException notFound(String logMessage) { + return notFound(logMessage, logMessage); + } + + private ResponseStatusException notFound(String logMessage, String responseMessage) { + LOGGER.warn(logMessage); + return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java new file mode 100644 index 0000000..6286b33 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record BackupDto( + String id, + String fileName, + long sizeBytes, + Instant createdAt +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java new file mode 100644 index 0000000..00a31f9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; +import java.util.List; + +public record BackupRunDto( + String runId, + String startTime, + String endTime, + List servicesRan, + BackupDto archive +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java new file mode 100644 index 0000000..a3916da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record ScheduleUpdateRequest(Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java new file mode 100644 index 0000000..bd2613f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java @@ -0,0 +1,10 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record ServerStatusDto( + boolean healthy, + boolean running, + int backupRetentionCount, + Duration backupInterval +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java new file mode 100644 index 0000000..caeef08 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -0,0 +1,43 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.time.Instant; + +public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt +) { + public String generateChecksum() { + Path file = Paths.get(fileName); + try { + byte[] data = Files.readAllBytes(file); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); + String checksum = new BigInteger(1, hash).toString(16); + return checksum; + } catch (Exception e) {} + return ""; + } + + public int fileSize() { + Path file = Paths.get(fileName); + + long size; + try { size = Files.size(file); } + catch (IOException iE) { size = 0; } + + if (size > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + + return (int) size; + + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java new file mode 100644 index 0000000..f46693e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public class BackupRunResult { + private final String runId; + private final String startTime; + private final String endTime; + private final String status; + private final List serviceResults; + private final BackupArchive archive; + private final String errorMessage; + + public BackupRunResult( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage + ) { + this.runId = runId; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.serviceResults = serviceResults; + this.archive = archive; + this.errorMessage = errorMessage; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + + public String startTime() { + return startTime; + } + + public String endTime() { + return endTime; + } + + public List serviceResults() { + return serviceResults; + } + + public List serviceNames() { + return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); + } + + public BackupArchive archive() { + return archive; + } + + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java new file mode 100644 index 0000000..6877586 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdServer.model; + +public class BackupServiceResult { + private String runId; + private final String status; + private final String startTime; + private final String endTime; + private final String serviceName; + private final String errorMessage; + + public BackupServiceResult( + String runId, + String status, + String startTime, + String endTime, + String serviceName, + String errorMessage + ) { + this.runId = runId; + this.status = status; + this.startTime = startTime; + this.endTime = endTime; + this.serviceName = serviceName; + this.errorMessage = errorMessage; + } + + public void setId(String runId) { + this.runId = runId; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + public String startTime() { + return startTime; + } + public String endTime() { + return endTime; + } + public String serviceName() { + return serviceName; + } + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java new file mode 100644 index 0000000..65a4b40 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public record FetchedBackupRecord( + int id, + String startTime, + String status, + String filename, + List fetchedServices +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java new file mode 100644 index 0000000..1236bf8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.model; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String serviceName, + String status, + String startTime +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java new file mode 100644 index 0000000..ef75413 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java new file mode 100644 index 0000000..a08bcd6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -0,0 +1,281 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import jakarta.annotation.PostConstruct; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; + +import org.springframework.stereotype.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Service +public class BackupArchiveService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); + + private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") + .withZone(ZoneOffset.UTC); + private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds + + private final MediaGarrdProperties properties; + private final AtomicReference> cachedArchives = new AtomicReference<>(null); + private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); + + public BackupArchiveService(MediaGarrdProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void cleanupStaleArtifactsOnStartup() { + Path root = rootDirectory(); + Path runsRoot = root.resolve("runs"); + + try { + Files.createDirectories(root); + + try (var stream = Files.list(root)) { + stream + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) + .forEach(path -> { + try { + Files.deleteIfExists(path); + LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); + } + }); + } + + if (Files.exists(runsRoot)) { + try (var stream = Files.list(runsRoot)) { + stream + .filter(Files::isDirectory) + .forEach(runDir -> { + try { + removeRunDirectory(runDir); + LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); + } + }); + } + } + + enforceRetention(); + LOGGER.info("Startup cleanup: retention policy enforced"); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); + } + } + + public Path rootDirectory() { + return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); + } + + public BackupArchive createArchive(Path runDirectory) { + Instant createdAt = Instant.now(); + String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; + Path root = rootDirectory(); + Path archivePath = root.resolve(fileName); + + LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); + try { + Files.createDirectories(root); + zipDirectory(runDirectory, archivePath); + enforceRetention(); + long size = Files.size(archivePath); + LOGGER.info("Archive created: {} ({} bytes)", fileName, size); + + // Invalidate cache after new archive created + cacheLastUpdatedMs.set(0); + cachedArchives.set(null); + + return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); + } catch (IOException e) { + LOGGER.error("Failed to create backup archive: {}", fileName, e); + throw new IllegalStateException("Failed to create backup archive", e); + } + } + + public List listArchives() { + long now = System.currentTimeMillis(); + long lastUpdate = cacheLastUpdatedMs.get(); + + if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { + List cached = cachedArchives.get(); + if (cached != null) { + LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); + return cached; + } + } + + // Cache miss -> rebuild list + Path root = rootDirectory(); + List archives; + if (!Files.exists(root)) { + archives = List.of(); + } else { + try (var stream = Files.list(root)) { + archives = stream + .filter(path -> path.getFileName().toString().endsWith(".zip")) + .sorted(Comparator.comparing(this::lastModified).reversed()) + .map(this::toArchive) + .toList(); + } catch (IOException e) { + throw new IllegalStateException("Failed to list archives", e); + } + } + + cachedArchives.set(archives); + cacheLastUpdatedMs.set(now); + LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); + return archives; + } + + public Optional latest() { + return listArchives().stream().findFirst(); + } + + public Optional byId(String id) { + return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); + } + + public boolean deleteById(String id) { + Optional archive = byId(id); + if (archive.isEmpty()) { + return false; + } + + try { + Files.deleteIfExists(archive.get().path()); + LOGGER.info("Archive deleted: {}", id); + cacheLastUpdatedMs.set(0); + + cachedArchives.set(null); + return true; + + } catch (IOException e) { + LOGGER.error("Failed to delete archive: {}", id, e); + throw new IllegalStateException("Failed to delete archive " + id, e); + } + } + + public Path createRunDirectory() { + Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); + try { + Files.createDirectories(runDir); + return runDir; + } catch (IOException e) { + throw new IllegalStateException("Failed to create run directory", e); + } + } + + public void removeRunDirectory(Path runDirectory) { + if (runDirectory == null || !Files.exists(runDirectory)) { + return; + } + + try (var walk = Files.walk(runDirectory)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + throw new IllegalStateException("Failed to clean up run directory", e); + } + }); + } catch (IOException e) { + throw new IllegalStateException("Failed to walk run directory", e); + } + } + + private void enforceRetention() throws IOException { + int retain = Math.max(1, properties.getRetentionCount()); + List archives; + try (var stream = Files.list(rootDirectory())) { + archives = stream + .filter(path -> path.getFileName().toString().endsWith(".zip")) + .sorted(Comparator.comparing(this::lastModified).reversed()) + .toList(); + } + for (int i = retain; i < archives.size(); i++) { + Path toDelete = archives.get(i); + LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); + Files.deleteIfExists(toDelete); + } + } + + private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { + Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + ZipOutputStream zipOut = new ZipOutputStream(fileOut); + var paths = Files.walk(sourceDir)) { + + paths.filter(Files::isRegularFile).forEach(path -> { + Path relative = sourceDir.relativize(path); + try { + zipOut.putNextEntry(new ZipEntry(relative.toString())); + try (InputStream in = Files.newInputStream(path)) { + in.transferTo(zipOut); + } + zipOut.closeEntry(); + } catch (IOException e) { + throw new IllegalStateException("Failed to zip file " + path, e); + } + }); + } + Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } + + private BackupArchive toArchive(Path path) { + String fileName = path.getFileName().toString(); + return new BackupArchive( + toId(fileName), + fileName, + path, + fileSize(path), + lastModified(path) + ); + } + + private String toId(String fileName) { + return fileName.replace(".zip", ""); + } + + private long fileSize(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + return 0L; + } + } + + private Instant lastModified(Path path) { + try { + return Files.getLastModifiedTime(path).toInstant(); + } catch (IOException e) { + return Instant.EPOCH; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java new file mode 100644 index 0000000..8dba48a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -0,0 +1,206 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.services.runner.Runner; + +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Service +public class BackupOrchestratorService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); + + private final MediaGarrdProperties properties; + private final RunnerFactory runnerFactory; + private final BackupArchiveService archiveService; + private final BackupScheduleService scheduleService; + private final DatabaseService db; + private final AtomicBoolean running = new AtomicBoolean(false); + private final ExecutorService runnerExecutor = new ThreadPoolExecutor( + 1, // core threads + 6, // max threads + 30, // ttl + TimeUnit.SECONDS, + new LinkedBlockingQueue<>() + ); + + public BackupOrchestratorService( + MediaGarrdProperties properties, + RunnerFactory runnerFactory, + BackupArchiveService archiveService, + BackupScheduleService scheduleService, + DatabaseService db + ) { + this.properties = properties; + this.runnerFactory = runnerFactory; + this.archiveService = archiveService; + this.scheduleService = scheduleService; + this.db = db; + } + + @Scheduled(fixedDelay = 10000) + public void scheduledRun() { + if (running.get()) { + LOGGER.debug("Scheduled check skipped, backup already in progress"); + return; + } + if (!scheduleService.dueNow()) { + return; + } + LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); + try { + runBackup(); + } catch (RuntimeException ex) { + LOGGER.error("Scheduled backup run failed", ex); + } + } + + public BackupRunResult runBackup() { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new IllegalStateException("A backup run is already in progress"); + } + + scheduleService.markRunStarted(); + + Path runDirectory = archiveService.createRunDirectory(); + Instant startedAt = Instant.now(); + List runners = runnerFactory.build(properties.getServiceConfigs()); + List serviceRunResults = new ArrayList<>(); + + LOGGER.info( + "Backup run started: runDir={}, services={}", + runDirectory, + runners.stream().map(Runner::getServiceName).toList()); + + try { + String errorMessage = ""; + List> futures = new ArrayList<>(); + for (Runner runner : runners) { + LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); + futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); + } + + for (Future future : futures) { + try { + BackupServiceResult outcome = future.get(); + serviceRunResults.add(outcome); + if (Status.COMPLETED.equals(outcome.status())) { + LOGGER.info("Runner succeeded: {}", outcome.serviceName()); + } else { + LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Backup run interrupted", ex); + } catch (ExecutionException ex) { + errorMessage.concat(ex.getMessage() + "\n"); + LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); + } + } + + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + LOGGER.info( + "All runners finished: succeeded={}/{}", + successfulRunnerCount, + runners.size() + ); + BackupArchive archive = archiveService.createArchive(runDirectory); + for (BackupServiceResult serviceResult : serviceRunResults) { + serviceResult.setId(archive.id()); + } + long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); + LOGGER.info( + "Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), + archive.sizeBytes(), + durationMs, + serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() + ); + + String status; + if (successfulRunnerCount == runners.size()) { + status = Status.COMPLETED; + } else if (successfulRunnerCount > 0) { + status = Status.PARTIAL; + } else { + status = Status.FAILED; + } + BackupRunResult backupRecord = new BackupRunResult( + archive.id(), + status, + Utils.formatTime(startedAt), + Utils.recordCurrentTime(), + serviceRunResults, + archive, + errorMessage + ); + db.addNewBackupRecord(backupRecord); + return backupRecord; + } finally { + archiveService.removeRunDirectory(runDirectory); + running.set(false); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } + } + + public boolean isRunning() { + return running.get(); + } + + public Duration getInterval() { + return scheduleService.getInterval(); + } + + public Duration updateInterval(Duration duration) { + return scheduleService.updateInterval(duration); + } + + @PreDestroy + public void shutdownRunnerExecutor() { + runnerExecutor.shutdownNow(); + } + + private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { + LOGGER.info("[{}] Runner starting", runner.getServiceName()); + long start = System.currentTimeMillis(); + try { + runner.run(runDirectory); + LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); + } catch (RuntimeException ex) { + LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", + runner.getServiceName(), System.currentTimeMillis() - start, ex); + } + + return new BackupServiceResult( + null, + runner.getRunnerStatus(), + runner.getRunnerStartTime(), + runner.getRunnerEndTime(), + runner.getServiceName(), + runner.getRunnerException() + ); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java new file mode 100644 index 0000000..d3c8637 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Service +public class BackupScheduleService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); + + private final AtomicReference currentInterval; + private final AtomicReference nextRun; + + public BackupScheduleService(MediaGarrdProperties properties) { + Duration interval = safe(properties.getBackupInterval()); + this.currentInterval = new AtomicReference<>(interval); + this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); + LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); + } + + public Duration getInterval() { + return currentInterval.get(); + } + + public Instant getNextRun() { + return nextRun.get(); + } + + public Duration updateInterval(Duration interval) { + Duration safe = safe(interval); + currentInterval.set(safe); + Instant next = Instant.now().plus(safe); + nextRun.set(next); + LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); + return safe; + } + + public boolean dueNow() { + Instant now = Instant.now(); + Instant current = nextRun.get(); + return !now.isBefore(current); + } + + public void markRunStarted() { + Instant next = Instant.now().plus(currentInterval.get()); + nextRun.set(next); + LOGGER.info("Backup run started: nextScheduledRun={}", next); + } + + private Duration safe(Duration interval) { + if (interval == null || interval.isNegative() || interval.isZero()) { + return Duration.ofHours(12); + } + return interval; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java new file mode 100644 index 0000000..0339e98 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; + +@Service +public class DatabaseService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); + + public DatabaseService() { + verifyDatabaseIntegrity(); + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + } catch (Exception e) { + LOGGER.warn("An error occurred while disabling auto-commit on the database", e); + } + } + + private boolean verifyDatabaseIntegrity() { + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + ensureTablesExist(connection); + runNeededMigrations(connection); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + return false; + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + return true; + } + + private void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + statement.execute(CREATE_TABLES); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("Failed to verify if tables exist in database.", sE); + handleSqlException(connection); + throw sE; + } + } + + private void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = getDatabaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion <= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException sE) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + sE + ); + handleSqlException(connection); + throw sE; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + private int getDatabaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + + return result.getInt(1); + } catch (SQLException sE) { + LOGGER.warn("Failed to fetch database version", sE); + return -1; + } + } + + private void setDatabaseVersion(Connection connection, int version) { + + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException sE) { + LOGGER.warn("Failed to set new database version", sE); + } + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); + return; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + addMasterBackup(connection, backupRecord); + addServiceBackups(connection, backupRecord.serviceResults()); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } + } + + private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + statement.setString(5, backupRecord.archive().generateChecksum()); + statement.setString(6, backupRecord.archive().fileName()); + statement.setInt(7, backupRecord.archive().fileSize()); + statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while logging a new backup record", sE); + handleSqlException(connection); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + } + + private void addServiceBackups(Connection connection, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setString(1, service.runId()); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); + handleSqlException(connection); + } + } + } + + public FetchedBackupRecord fetchLatestBackupRecord() { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch latest backup record"); + return null; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + int id = rs.getInt("id"); + String backupStartTime = rs.getString("start_time"); + String status = rs.getString("status"); + String filename = rs.getString("filename"); + return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private void handleSqlException(Connection connection) { + try { + connection.rollback(); + } catch (SQLException rollbackException) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java new file mode 100644 index 0000000..28e2ecc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -0,0 +1,114 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.EnumMap; + +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.services.config.*; +import wellatleastitried.mediagarrdServer.services.runner.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +@Component +public class RunnerFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); + + public List build(EnumMap serviceConfigMap) { + List runners = new ArrayList<>(); + + for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { + AbstractServiceConfig config = entry.getValue(); + if (config == null || !config.isEnabled()) { + LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); + continue; + } + + validate(entry.getKey(), config); + + Services key = entry.getKey(); + + //@ADD_NEW_SERVICE + @SuppressWarnings("unused") + Object exhaustive = switch (key) { + case JELLYFIN -> { + runners.add(new JellyfinRunner(config)); + LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); + yield null; + } + case RADARR -> { + runners.add(new RadarrRunner(config)); + LOGGER.info("Registered runner: radarr"); + yield null; + } + case SONARR -> { + runners.add(new SonarrRunner(config)); + LOGGER.info("Registered runner: sonarr"); + yield null; + } + case PROWLARR -> { + runners.add(new ProwlarrRunner(config)); + LOGGER.info("Registered runner: prowlarr"); + yield null; + } + case TDARR -> { + runners.add(new TdarrRunner(config)); + LOGGER.info("Registered runner: tdarr"); + yield null; + } + case QBITTORRENT -> { + runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); + LOGGER.info("Registered runner: qbittorrent"); + yield null; + } + }; + } + + LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); + return runners; + } + + private void validate(Services key, AbstractServiceConfig config) { + boolean supported = SUPPORTED_SERVICES.entrySet() + .stream() + .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); + String serviceName = SUPPORTED_SERVICES.get(key); + if (!supported) { + throw new IllegalArgumentException("Unsupported service configured: " + serviceName); + } + + //@ADD_NEW_SERVICE + @SuppressWarnings("unused") + Object exhaustive = switch (key) { + case JELLYFIN -> { + requirePath(serviceName, "configPath", config.getConfigPath()); + yield null; + } + case RADARR, SONARR, PROWLARR, TDARR -> { + requirePath(serviceName, "path", config.getPath()); + yield null; + } + case QBITTORRENT -> { + if (!(config instanceof QBittorrentServiceConfig)) { + throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); + } + + QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; + requirePath(serviceName, "path", qbConfig.getPath()); + requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); + yield null; + } + }; + } + + private void requirePath(String serviceName, String fieldName, String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java new file mode 100644 index 0000000..974c31d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdServer.services.config; + +//import java.util.List; + +//@ADD_NEW_SERVICE +abstract public class AbstractServiceConfig { + + private boolean enabled; + private String path; + private String configPath; + + //private List configPaths; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getConfigPath() { + return configPath; + } + + public void setConfigPath(String configPath) { + this.configPath = configPath; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java new file mode 100644 index 0000000..20482e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.services.config; + +// For services that require only one path to backup, this can be used. +// Otherwise, create a new config for a service-specific config. +public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java new file mode 100644 index 0000000..952667b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdServer.services.config; + +public class QBittorrentServiceConfig extends AbstractServiceConfig { + + private String savedTorrentsPath; + + // public QBittorrentServiceConfig(ServiceConfig) {} + + public String getSavedTorrentsPath() { + return savedTorrentsPath; + } + + public void setSavedTorrentsPath(String savedTorrentsPath) { + this.savedTorrentsPath = savedTorrentsPath; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java new file mode 100644 index 0000000..b5d0525 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java @@ -0,0 +1,188 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.List; +import java.util.Locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; + +//@ADD_NEW_SERVICE +public abstract class AbstractLocalCopyRunner implements Runner { + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); + + private final String serviceName; + + private String startTime; + private String endTime; + private String status; + private String errorMessage; + + protected AbstractLocalCopyRunner(String serviceName) { + this.serviceName = serviceName; + status = "idle"; + startTime = endTime = errorMessage = ""; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getRunnerStartTime() { + return startTime; + } + + @Override + public String getRunnerEndTime() { + return endTime; + } + + @Override + public String getRunnerStatus() { + return status; + } + + @Override + public String getRunnerException() { + return errorMessage; + } + + @Override + public void run(Path outputDirectory) { + startTime = Utils.recordCurrentTime(); + status = "running"; + Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); + try { + Files.createDirectories(serviceDirectory); + } catch (IOException e) { + errorMessage = "Unable to create output directory for " + serviceName; + status = "failed"; + throw new IllegalStateException("Unable to create output directory for " + serviceName, e); + } + + List specs = copySpecs(); + LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); + int succeeded = 0; + for (CopySpec spec : specs) { + try { + copySpec(spec, serviceDirectory); + succeeded++; + } catch (RuntimeException ex) { + LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); + } + } + LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); + if (succeeded == specs.size()) { + status = "completed"; + } else if (succeeded < specs.size() && succeeded > 0) { + status = "partial"; + } else { + status = "failed"; + } + endTime = Utils.recordCurrentTime(); + } + + protected abstract List copySpecs(); + + protected CopySpec dir(String sourcePath, String targetName) { + return new CopySpec(sourcePath, targetName, true); + } + + protected CopySpec file(String sourcePath, String targetName) { + return new CopySpec(sourcePath, targetName, false); + } + + private void copySpec(CopySpec spec, Path serviceDirectory) { + if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { + errorMessage = serviceName + " runner missing source path for " + spec.targetName(); + status = "failed"; + throw new IllegalArgumentException(errorMessage); + } + + Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); + if (!Files.exists(source)) { + errorMessage = serviceName + " source path not found: " + source; + status = "failed"; + throw new IllegalStateException(errorMessage); + } + + Path target = serviceDirectory.resolve(spec.targetName()); + + try { + if (spec.directory()) { + if (!Files.isDirectory(source)) { + throw new IllegalStateException(serviceName + " expected directory path: " + source); + } + copyDirectory(source, target); + } else { + if (!Files.isRegularFile(source)) { + throw new IllegalStateException(serviceName + " expected file path: " + source); + } + Path parent = target.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); + LOGGER.debug("[{}] Copied file: {}", serviceName, target); + } + } catch (IOException e) { + status = "failed"; + throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); + } + } + + + private void copyDirectory(Path source, Path target) throws IOException { + Files.createDirectories(target); + FileVisitor visitor = new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Path relative = source.relativize(dir); + Path destination = target.resolve(relative); + Files.createDirectories(destination); + LOGGER.debug("[{}] Created dir: {}", serviceName, destination); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path relative = source.relativize(file); + Path destination = target.resolve(relative); + Path parent = destination.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + + // This will be used on all files including databases. There is a risk of corruption + // when copying a database as it could be in-use, but this is unlikely AND the fact + // that multiple backups will be retained mitigates this risk. This may be changed + // in the future with an OPTION to stop services during backup, but for now it will + // be a basic copy. + Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); + LOGGER.debug("[{}] Copied: {}", serviceName, destination); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); + return FileVisitResult.CONTINUE; + } + }; + Files.walkFileTree(source, visitor); + } + + protected record CopySpec(String sourcePath, String targetName, boolean directory) {} +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java new file mode 100644 index 0000000..93dae71 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class JellyfinRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public JellyfinRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getConfigPath(), "config")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java new file mode 100644 index 0000000..e7ee6e0 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class ProwlarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public ProwlarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.PROWLARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java new file mode 100644 index 0000000..6d5eeb1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -0,0 +1,38 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class QBittorrentRunner extends AbstractLocalCopyRunner { + + private final QBittorrentServiceConfig config; + + public QBittorrentRunner(QBittorrentServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); + this.config = config; + } + + @Override + protected List copySpecs() { + List specs = new ArrayList<>(); + specs.add(dir(config.getPath(), "appdata")); + + String savedTorrentPath = config.getSavedTorrentsPath(); + if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { + specs.add(dir(savedTorrentPath, "saved-torrents")); + } + + Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); + if (Files.isRegularFile(compose)) { + specs.add(file(compose.toString(), "docker-compose.yml")); + } + + return specs; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java new file mode 100644 index 0000000..259cac4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class RadarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public RadarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.RADARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java new file mode 100644 index 0000000..095420b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.nio.file.Path; + +public interface Runner { + + String getServiceName(); + + String getRunnerStartTime(); + + String getRunnerEndTime(); + + String getRunnerStatus(); + + String getRunnerException(); + + void run(Path outputDirectory); +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java new file mode 100644 index 0000000..8e56234 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class SonarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public SonarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.SONARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java new file mode 100644 index 0000000..7fa6bbb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class TdarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public TdarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.TDARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java similarity index 73% rename from src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index b037445..748ee76 100644 --- a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -9,10 +9,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; @SpringBootTest(properties = { "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-properties-test", diff --git a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java similarity index 84% rename from src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 0e10eca..2cd1c0e 100644 --- a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.api; +package wellatleastitried.mediagarrdServer.api; import static org.hamcrest.Matchers.hasSize; import static org.mockito.Mockito.when; @@ -18,11 +18,12 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.api.BackupController; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; @WebMvcTest(BackupController.class) class BackupControllerTest { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java similarity index 84% rename from src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index fdf7c1e..fe201fd 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,7 +9,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; class BackupArchiveServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java similarity index 81% rename from src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index b94912b..422f3ee 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -8,7 +8,8 @@ import org.junit.jupiter.api.Test; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.service.BackupScheduleService; class BackupScheduleServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java new file mode 100644 index 0000000..1c580e2 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.service; + +// TODO: Implement full unit testing for db +// ref: https://github.com/wellatleastitried/StreamLine/blob/menu-options/src/test/java/com/streamline/database/DatabaseRunnerTest.java +public class DatabaseServiceTest {} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java similarity index 90% rename from src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java index bec1370..385c71c 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -8,11 +8,12 @@ import java.util.List; import java.util.Locale; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.services.runner.Runner; public final class RealRunnersInteractiveCheck { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java similarity index 93% rename from src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java index b676ffc..3985680 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -17,11 +17,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.services.runner.Runner; @Tag("real-runners") class RunnersIntegrationTest { From 9d7767cc6acd911f1d53e5528b10c96d42af241e Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 19 Sep 2026 16:04:10 -0500 Subject: [PATCH 02/26] Fix renaming --- Dockerfile | 3 +- build.gradle.kts | 2 +- install.sh | 28 +- mise.toml | 2 + .../mediagarrd/MediaGarrd.java | 16 - .../mediagarrd/MediaGarrdProperties.java | 57 ---- .../mediagarrd/MediaGarrdUtilities.java | 173 ----------- .../mediagarrd/ServicesProperties.java | 84 ------ .../mediagarrd/api/BackupController.java | 183 ------------ .../mediagarrd/dto/BackupDto.java | 11 - .../mediagarrd/dto/BackupRunDto.java | 13 - .../mediagarrd/dto/ScheduleUpdateRequest.java | 5 - .../mediagarrd/dto/ServerStatusDto.java | 10 - .../mediagarrd/model/BackupArchive.java | 43 --- .../mediagarrd/model/BackupRunResult.java | 63 ---- .../mediagarrd/model/BackupServiceResult.java | 50 ---- .../mediagarrd/model/FetchedBackupRecord.java | 11 - .../model/FetchedBackupServiceRecord.java | 18 -- .../service/BackupArchiveService.java | 281 ------------------ .../service/BackupOrchestratorService.java | 206 ------------- .../service/BackupScheduleService.java | 63 ---- .../mediagarrd/service/DatabaseService.java | 236 --------------- .../mediagarrd/service/RunnerFactory.java | 114 ------- .../config/AbstractServiceConfig.java | 37 --- .../services/config/CommonServiceConfig.java | 5 - .../config/QBittorrentServiceConfig.java | 16 - .../runner/AbstractLocalCopyRunner.java | 188 ------------ .../services/runner/JellyfinRunner.java | 22 -- .../services/runner/ProwlarrRunner.java | 22 -- .../services/runner/RadarrRunner.java | 22 -- .../mediagarrd/services/runner/Runner.java | 18 -- .../services/runner/SonarrRunner.java | 22 -- .../services/runner/TdarrRunner.java | 22 -- .../MediaGarrdProperties.java | 2 +- .../mediagarrdServer/MediaGarrdUtilities.java | 15 +- .../mediagarrdServer/ServicesProperties.java | 2 +- .../model/FetchedBackupServiceRecord.java | 11 - .../model/FetchedServiceBackupRecord.java | 24 -- .../service/DatabaseService.java | 2 +- .../service/RunnerFactory.java | 2 +- .../config/AbstractServiceConfig.java | 4 - .../config/QBittorrentServiceConfig.java | 2 - .../services/runner/ArrRunner.java} | 18 +- .../services/runner/JellyfinRunner.java | 2 +- .../services/runner/ProwlarrRunner.java | 17 +- .../services/runner/QBittorrentRunner.java | 4 +- .../services/runner/RadarrRunner.java | 17 +- .../services/runner/SonarrRunner.java | 17 +- .../services/runner/TdarrRunner.java | 27 +- src/main/resources/application.yml | 30 +- 50 files changed, 99 insertions(+), 2143 deletions(-) create mode 100644 mise.toml delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/api/BackupController.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java rename src/main/java/wellatleastitried/{mediagarrd/services/runner/QBittorrentRunner.java => mediagarrdServer/services/runner/ArrRunner.java} (51%) diff --git a/Dockerfile b/Dockerfile index c57db07..45dd5a5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,7 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN --mount=type=cache,target=/home/gradle/.gradle \ - gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all FROM eclipse-temurin:21-jre WORKDIR /app diff --git a/build.gradle.kts b/build.gradle.kts index 7273d91..44dc0fd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -31,7 +31,7 @@ tasks.register("realRunnersPromptCheck") { description = "Runs interactive real-environment runner checks (prompts for credentials and endpoints)." group = "verification" classpath = sourceSets["test"].runtimeClasspath - mainClass.set("wellatleastitried.mediagarrd.service.RealRunnersInteractiveCheck") + mainClass.set("wellatleastitried.mediagarrdServer.service.RealRunnersInteractiveCheck") standardInput = System.`in` dependsOn(tasks.testClasses) } diff --git a/install.sh b/install.sh index 85d0458..105358c 100755 --- a/install.sh +++ b/install.sh @@ -72,18 +72,32 @@ EOF_ENV fi } > "$ENV_FILE" - cat > "$SERVER_ENV_FILE" < "$SERVER_ENV_FILE" rm -f "$CLIENT_ENV_FILE" diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..a0f2434 --- /dev/null +++ b/mise.toml @@ -0,0 +1,2 @@ +[tools] +java = "21.0.0" diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java deleted file mode 100644 index 9f32db2..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.scheduling.annotation.EnableScheduling; - -@SpringBootApplication -@EnableScheduling -@EnableConfigurationProperties(MediaGarrdProperties.class) -public class MediaGarrd { - - public static void main(String[] args) { - SpringApplication.run(MediaGarrd.class, args); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java deleted file mode 100644 index 6788f79..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java +++ /dev/null @@ -1,57 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.time.Duration; -import java.util.EnumMap; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -@ConfigurationProperties(prefix = "mediagarrd") -public class MediaGarrdProperties { - - private Duration backupInterval = Duration.ofHours(12); - private String backupRoot = "./data/server/backups"; - private int retentionCount = 10; - private ServicesProperties services = new ServicesProperties(); - - public Duration getBackupInterval() { - return backupInterval; - } - - public void setBackupInterval(Duration backupInterval) { - this.backupInterval = backupInterval; - } - - public String getBackupRoot() { - return backupRoot; - } - - public void setBackupRoot(String backupRoot) { - this.backupRoot = backupRoot; - } - - public int getRetentionCount() { - return retentionCount; - } - - public void setRetentionCount(int retentionCount) { - this.retentionCount = retentionCount; - } - - public ServicesProperties getServices() { - return services; - } - - public void setServices(ServicesProperties services) { - this.services = services; - } - - public EnumMap getServiceConfigs() { - return services.toRuntimeConfigs(); - } - - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java deleted file mode 100644 index c95af0f..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java +++ /dev/null @@ -1,173 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumMap; -import java.util.List; - -//@ADD_NEW_SERVICE -public final class MediaGarrdUtilities { - private MediaGarrdUtilities() {} - - public class Utils { - public static String recordCurrentTime() { - Instant instant = Instant.now(); - return formatTime(instant); - } - - public static String formatTime(Instant instant) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String formattedTime = sdf.format(Date.from(instant)); - return formattedTime; - } - - public static int subtractTime(String startTime, String endTime) { - } - public static long getDurationMs(String startTimeStr, String endTimeStr) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) { - } - } - } - - public class ServiceConstants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - } - - public class DatabaseConstants { - - // Migrations will be added inside of the static block - public record Migration(int version, String sql) {} - public static final List MIGRATIONS; - static { - MIGRATIONS = new ArrayList(); - // Migration versions will start at 2, as the initial tables will be schema v1 - } - - public static final String SQLITE = "jdbc:sqlite:"; - public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; - - // Status used for the overall backup AND the individual service runners - public class Status { - public static final String COMPLETED = "completed"; - public static final String PARTIAL = "partial"; - public static final String FAILED = "failed"; - } - - public static final String CREATE_TABLES = """ - CREATE TABLE IF NOT EXISTS backups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - archive_id TEXT NOT NULL UNIQUE, - start_time DATETIME NOT NULL, - end_time DATETIME, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - checksum TEXT, - filename TEXT, - file_size INTEGER NOT NULL, - file_created_time DATETIME, - error_message TEXT - ); - - CREATE TABLE IF NOT EXISTS backup_services ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - backup_id INTEGER NOT NULL, - service_name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), - start_time DATETIME, - end_time DATETIME, - error_message TEXT, - FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, - UNIQUE (backup_id, service_name) - ); - - CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); - CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); - """; - - public static final String ADD_BACKUP_RECORD = """ - INSERT INTO backups ( - archive_id, - start_time, - end_time, - status, - checksum, - services_completed, - filename, - file_size, - file_created_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); - """; - - public static final String ADD_BACKUP_SERVICE_RECORD = """ - INSERT INTO backup_services ( - backup_id, - service_name, - status, - start_time, - end_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?); - """; - - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - - public static final String DELETE_BACKUP_RECORD_BY_ID = """ - DELETE FROM backups - WHERE archive_id = ?; - """; - - - /* - public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive - ) - public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt - ) - */ - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java deleted file mode 100644 index 953e4d9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java +++ /dev/null @@ -1,84 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.util.EnumMap; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ServicesProperties { - - //@ADD_NEW_SERVICE - private CommonServiceConfig jellyfin; - private CommonServiceConfig radarr; - private CommonServiceConfig sonarr; - private CommonServiceConfig prowlarr; - private CommonServiceConfig tdarr; - private QBittorrentServiceConfig qbittorrent; - - public EnumMap toRuntimeConfigs() { - EnumMap configs = new EnumMap<>(Services.class); - put(configs, Services.JELLYFIN, jellyfin); - put(configs, Services.RADARR, radarr); - put(configs, Services.SONARR, sonarr); - put(configs, Services.PROWLARR, prowlarr); - put(configs, Services.TDARR, tdarr); - put(configs, Services.QBITTORRENT, qbittorrent); - return configs; - } - - private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { - if (config != null) { - configs.put(service, config); - } - } - - public CommonServiceConfig getJellyfin() { - return jellyfin; - } - - public void setJellyfin(CommonServiceConfig jellyfin) { - this.jellyfin = jellyfin; - } - - public CommonServiceConfig getRadarr() { - return radarr; - } - - public void setRadarr(CommonServiceConfig radarr) { - this.radarr = radarr; - } - - public CommonServiceConfig getSonarr() { - return sonarr; - } - - public void setSonarr(CommonServiceConfig sonarr) { - this.sonarr = sonarr; - } - - public CommonServiceConfig getProwlarr() { - return prowlarr; - } - - public void setProwlarr(CommonServiceConfig prowlarr) { - this.prowlarr = prowlarr; - } - - public CommonServiceConfig getTdarr() { - return tdarr; - } - - public void setTdarr(CommonServiceConfig tdarr) { - this.tdarr = tdarr; - } - - public QBittorrentServiceConfig getQbittorrent() { - return qbittorrent; - } - - public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { - this.qbittorrent = qbittorrent; - } - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java deleted file mode 100644 index 0ea1ed6..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java +++ /dev/null @@ -1,183 +0,0 @@ -package wellatleastitried.mediagarrdServer.api; - -import java.io.IOException; -import java.time.Duration; -import java.util.List; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.dto.BackupDto; -import wellatleastitried.mediagarrdServer.dto.BackupRunDto; -import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; -import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.service.BackupArchiveService; -import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RestController -@RequestMapping("/api/v1") -public class BackupController { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupController.class); - - private final BackupArchiveService archiveService; - private final BackupOrchestratorService orchestratorService; - private final MediaGarrdProperties properties; - - public BackupController( - BackupArchiveService archiveService, - BackupOrchestratorService orchestratorService, - MediaGarrdProperties properties - ) { - this.archiveService = archiveService; - this.orchestratorService = orchestratorService; - this.properties = properties; - } - - @GetMapping("/health") - public ServerStatusDto health() { - LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - orchestratorService.getInterval() - ); - } - - @PutMapping("/schedule") - public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { - LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); - Duration updated = orchestratorService.updateInterval(request.backupInterval()); - LOGGER.info("Schedule updated: newInterval={}", updated); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - updated - ); - } - - @GetMapping("/backups") - public List listBackups() { - LOGGER.info("GET /api/v1/backups"); - List backups = archiveService.listArchives().stream().map(this::toDto).toList(); - LOGGER.info("Returning {} backup(s)", backups.size()); - return backups; - } - - @GetMapping("/backups/latest") - public BackupDto latestBackup() { - LOGGER.info("GET /api/v1/backups/latest"); - BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("No backup archives found")); - LOGGER.info("Latest backup: {}", archive.fileName()); - return toDto(archive); - } - - @GetMapping("/backups/{id}") - public BackupDto backupById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}", id); - return archiveService.byId(id) - .map(this::toDto) - .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); - } - - @GetMapping("/backups/{id}/download") - public ResponseEntity downloadById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}/download", id); - BackupArchive archive = archiveService.byId(id) - .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); - return downloadResponse(archive); - } - - @GetMapping("/backups/latest/download") - public ResponseEntity downloadLatest() { - LOGGER.info("GET /api/v1/backups/latest/download"); - BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); - return downloadResponse(archive); - } - - @DeleteMapping("/backups/{id}") - public ResponseEntity deleteBackup(@PathVariable String id) { - LOGGER.info("DELETE /api/v1/backups/{}", id); - boolean deleted = archiveService.deleteById(id); - if (!deleted) { - LOGGER.warn("Delete failed: backup not found: {}", id); - return ResponseEntity.notFound().build(); - } - LOGGER.info("Backup deleted: {}", id); - return ResponseEntity.noContent().build(); - } - - @PostMapping("/backups/run") - public BackupRunDto runBackup() { - LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); - BackupRunResult result = orchestratorService.runBackup(); - var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); - LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", - result.runId(), result.serviceNames(), result.archive().fileName(), - backupDuration); - return new BackupRunDto( - result.runId(), - result.startTime(), - result.endTime(), - result.serviceNames(), - toDto(result.archive()) - ); - } - - private ResponseEntity downloadResponse(BackupArchive archive) { - Resource file = new FileSystemResource(archive.path()); - if (!file.exists()) { - LOGGER.error("Archive file missing on disk: {}", archive.path()); - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); - } - - try { - LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .contentLength(file.contentLength()) - .body(file); - } catch (IOException e) { - LOGGER.error("Failed to read backup file: {}", archive.path(), e); - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); - } - } - - private BackupDto toDto(BackupArchive archive) { - return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); - } - - private ResponseStatusException notFound(String logMessage) { - return notFound(logMessage, logMessage); - } - - private ResponseStatusException notFound(String logMessage, String responseMessage) { - LOGGER.warn(logMessage); - return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java deleted file mode 100644 index 6286b33..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Instant; - -public record BackupDto( - String id, - String fileName, - long sizeBytes, - Instant createdAt -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java deleted file mode 100644 index 00a31f9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Instant; -import java.util.List; - -public record BackupRunDto( - String runId, - String startTime, - String endTime, - List servicesRan, - BackupDto archive -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java deleted file mode 100644 index a3916da..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Duration; - -public record ScheduleUpdateRequest(Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java deleted file mode 100644 index bd2613f..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Duration; - -public record ServerStatusDto( - boolean healthy, - boolean running, - int backupRetentionCount, - Duration backupInterval -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java deleted file mode 100644 index caeef08..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java +++ /dev/null @@ -1,43 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.io.IOException; -import java.math.BigInteger; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.time.Instant; - -public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt -) { - public String generateChecksum() { - Path file = Paths.get(fileName); - try { - byte[] data = Files.readAllBytes(file); - byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); - String checksum = new BigInteger(1, hash).toString(16); - return checksum; - } catch (Exception e) {} - return ""; - } - - public int fileSize() { - Path file = Paths.get(fileName); - - long size; - try { size = Files.size(file); } - catch (IOException iE) { size = 0; } - - if (size > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } - - return (int) size; - - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java deleted file mode 100644 index f46693e..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java +++ /dev/null @@ -1,63 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - -public class BackupRunResult { - private final String runId; - private final String startTime; - private final String endTime; - private final String status; - private final List serviceResults; - private final BackupArchive archive; - private final String errorMessage; - - public BackupRunResult( - String runId, - String startTime, - String endTime, - String status, - List serviceResults, - BackupArchive archive, - String errorMessage - ) { - this.runId = runId; - this.startTime = startTime; - this.endTime = endTime; - this.status = status; - this.serviceResults = serviceResults; - this.archive = archive; - this.errorMessage = errorMessage; - } - - public String runId() { - return runId; - } - - public String status() { - return status; - } - - public String startTime() { - return startTime; - } - - public String endTime() { - return endTime; - } - - public List serviceResults() { - return serviceResults; - } - - public List serviceNames() { - return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); - } - - public BackupArchive archive() { - return archive; - } - - public String errorMessage() { - return errorMessage; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java deleted file mode 100644 index 6877586..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java +++ /dev/null @@ -1,50 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -public class BackupServiceResult { - private String runId; - private final String status; - private final String startTime; - private final String endTime; - private final String serviceName; - private final String errorMessage; - - public BackupServiceResult( - String runId, - String status, - String startTime, - String endTime, - String serviceName, - String errorMessage - ) { - this.runId = runId; - this.status = status; - this.startTime = startTime; - this.endTime = endTime; - this.serviceName = serviceName; - this.errorMessage = errorMessage; - } - - public void setId(String runId) { - this.runId = runId; - } - - public String runId() { - return runId; - } - - public String status() { - return status; - } - public String startTime() { - return startTime; - } - public String endTime() { - return endTime; - } - public String serviceName() { - return serviceName; - } - public String errorMessage() { - return errorMessage; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java deleted file mode 100644 index 65a4b40..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java +++ /dev/null @@ -1,11 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - -public record FetchedBackupRecord( - int id, - String startTime, - String status, - String filename, - List fetchedServices -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java deleted file mode 100644 index 1236bf8..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java +++ /dev/null @@ -1,18 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ -public record FetchedBackupServiceRecord( - String serviceName, - String status, - String startTime -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java deleted file mode 100644 index a08bcd6..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java +++ /dev/null @@ -1,281 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import jakarta.annotation.PostConstruct; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.model.BackupArchive; - -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Service -public class BackupArchiveService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); - - private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") - .withZone(ZoneOffset.UTC); - private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds - - private final MediaGarrdProperties properties; - private final AtomicReference> cachedArchives = new AtomicReference<>(null); - private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); - - public BackupArchiveService(MediaGarrdProperties properties) { - this.properties = properties; - } - - @PostConstruct - public void cleanupStaleArtifactsOnStartup() { - Path root = rootDirectory(); - Path runsRoot = root.resolve("runs"); - - try { - Files.createDirectories(root); - - try (var stream = Files.list(root)) { - stream - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) - .forEach(path -> { - try { - Files.deleteIfExists(path); - LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); - } - }); - } - - if (Files.exists(runsRoot)) { - try (var stream = Files.list(runsRoot)) { - stream - .filter(Files::isDirectory) - .forEach(runDir -> { - try { - removeRunDirectory(runDir); - LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); - } - }); - } - } - - enforceRetention(); - LOGGER.info("Startup cleanup: retention policy enforced"); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); - } - } - - public Path rootDirectory() { - return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); - } - - public BackupArchive createArchive(Path runDirectory) { - Instant createdAt = Instant.now(); - String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; - Path root = rootDirectory(); - Path archivePath = root.resolve(fileName); - - LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); - try { - Files.createDirectories(root); - zipDirectory(runDirectory, archivePath); - enforceRetention(); - long size = Files.size(archivePath); - LOGGER.info("Archive created: {} ({} bytes)", fileName, size); - - // Invalidate cache after new archive created - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); - - return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); - } catch (IOException e) { - LOGGER.error("Failed to create backup archive: {}", fileName, e); - throw new IllegalStateException("Failed to create backup archive", e); - } - } - - public List listArchives() { - long now = System.currentTimeMillis(); - long lastUpdate = cacheLastUpdatedMs.get(); - - if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { - List cached = cachedArchives.get(); - if (cached != null) { - LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); - return cached; - } - } - - // Cache miss -> rebuild list - Path root = rootDirectory(); - List archives; - if (!Files.exists(root)) { - archives = List.of(); - } else { - try (var stream = Files.list(root)) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .map(this::toArchive) - .toList(); - } catch (IOException e) { - throw new IllegalStateException("Failed to list archives", e); - } - } - - cachedArchives.set(archives); - cacheLastUpdatedMs.set(now); - LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); - return archives; - } - - public Optional latest() { - return listArchives().stream().findFirst(); - } - - public Optional byId(String id) { - return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); - } - - public boolean deleteById(String id) { - Optional archive = byId(id); - if (archive.isEmpty()) { - return false; - } - - try { - Files.deleteIfExists(archive.get().path()); - LOGGER.info("Archive deleted: {}", id); - cacheLastUpdatedMs.set(0); - - cachedArchives.set(null); - return true; - - } catch (IOException e) { - LOGGER.error("Failed to delete archive: {}", id, e); - throw new IllegalStateException("Failed to delete archive " + id, e); - } - } - - public Path createRunDirectory() { - Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); - try { - Files.createDirectories(runDir); - return runDir; - } catch (IOException e) { - throw new IllegalStateException("Failed to create run directory", e); - } - } - - public void removeRunDirectory(Path runDirectory) { - if (runDirectory == null || !Files.exists(runDirectory)) { - return; - } - - try (var walk = Files.walk(runDirectory)) { - walk.sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - throw new IllegalStateException("Failed to clean up run directory", e); - } - }); - } catch (IOException e) { - throw new IllegalStateException("Failed to walk run directory", e); - } - } - - private void enforceRetention() throws IOException { - int retain = Math.max(1, properties.getRetentionCount()); - List archives; - try (var stream = Files.list(rootDirectory())) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .toList(); - } - for (int i = retain; i < archives.size(); i++) { - Path toDelete = archives.get(i); - LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); - Files.deleteIfExists(toDelete); - } - } - - private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { - Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); - try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - ZipOutputStream zipOut = new ZipOutputStream(fileOut); - var paths = Files.walk(sourceDir)) { - - paths.filter(Files::isRegularFile).forEach(path -> { - Path relative = sourceDir.relativize(path); - try { - zipOut.putNextEntry(new ZipEntry(relative.toString())); - try (InputStream in = Files.newInputStream(path)) { - in.transferTo(zipOut); - } - zipOut.closeEntry(); - } catch (IOException e) { - throw new IllegalStateException("Failed to zip file " + path, e); - } - }); - } - Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - } - - private BackupArchive toArchive(Path path) { - String fileName = path.getFileName().toString(); - return new BackupArchive( - toId(fileName), - fileName, - path, - fileSize(path), - lastModified(path) - ); - } - - private String toId(String fileName) { - return fileName.replace(".zip", ""); - } - - private long fileSize(Path path) { - try { - return Files.size(path); - } catch (IOException e) { - return 0L; - } - } - - private Instant lastModified(Path path) { - try { - return Files.getLastModifiedTime(path).toInstant(); - } catch (IOException e) { - return Instant.EPOCH; - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java deleted file mode 100644 index 8dba48a..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java +++ /dev/null @@ -1,206 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - -import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.services.runner.Runner; - -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Service -public class BackupOrchestratorService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); - - private final MediaGarrdProperties properties; - private final RunnerFactory runnerFactory; - private final BackupArchiveService archiveService; - private final BackupScheduleService scheduleService; - private final DatabaseService db; - private final AtomicBoolean running = new AtomicBoolean(false); - private final ExecutorService runnerExecutor = new ThreadPoolExecutor( - 1, // core threads - 6, // max threads - 30, // ttl - TimeUnit.SECONDS, - new LinkedBlockingQueue<>() - ); - - public BackupOrchestratorService( - MediaGarrdProperties properties, - RunnerFactory runnerFactory, - BackupArchiveService archiveService, - BackupScheduleService scheduleService, - DatabaseService db - ) { - this.properties = properties; - this.runnerFactory = runnerFactory; - this.archiveService = archiveService; - this.scheduleService = scheduleService; - this.db = db; - } - - @Scheduled(fixedDelay = 10000) - public void scheduledRun() { - if (running.get()) { - LOGGER.debug("Scheduled check skipped, backup already in progress"); - return; - } - if (!scheduleService.dueNow()) { - return; - } - LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); - try { - runBackup(); - } catch (RuntimeException ex) { - LOGGER.error("Scheduled backup run failed", ex); - } - } - - public BackupRunResult runBackup() { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new IllegalStateException("A backup run is already in progress"); - } - - scheduleService.markRunStarted(); - - Path runDirectory = archiveService.createRunDirectory(); - Instant startedAt = Instant.now(); - List runners = runnerFactory.build(properties.getServiceConfigs()); - List serviceRunResults = new ArrayList<>(); - - LOGGER.info( - "Backup run started: runDir={}, services={}", - runDirectory, - runners.stream().map(Runner::getServiceName).toList()); - - try { - String errorMessage = ""; - List> futures = new ArrayList<>(); - for (Runner runner : runners) { - LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); - futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); - } - - for (Future future : futures) { - try { - BackupServiceResult outcome = future.get(); - serviceRunResults.add(outcome); - if (Status.COMPLETED.equals(outcome.status())) { - LOGGER.info("Runner succeeded: {}", outcome.serviceName()); - } else { - LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Backup run interrupted", ex); - } catch (ExecutionException ex) { - errorMessage.concat(ex.getMessage() + "\n"); - LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); - } - } - - int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); - LOGGER.info( - "All runners finished: succeeded={}/{}", - successfulRunnerCount, - runners.size() - ); - BackupArchive archive = archiveService.createArchive(runDirectory); - for (BackupServiceResult serviceResult : serviceRunResults) { - serviceResult.setId(archive.id()); - } - long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info( - "Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), - archive.sizeBytes(), - durationMs, - serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() - ); - - String status; - if (successfulRunnerCount == runners.size()) { - status = Status.COMPLETED; - } else if (successfulRunnerCount > 0) { - status = Status.PARTIAL; - } else { - status = Status.FAILED; - } - BackupRunResult backupRecord = new BackupRunResult( - archive.id(), - status, - Utils.formatTime(startedAt), - Utils.recordCurrentTime(), - serviceRunResults, - archive, - errorMessage - ); - db.addNewBackupRecord(backupRecord); - return backupRecord; - } finally { - archiveService.removeRunDirectory(runDirectory); - running.set(false); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } - } - - public boolean isRunning() { - return running.get(); - } - - public Duration getInterval() { - return scheduleService.getInterval(); - } - - public Duration updateInterval(Duration duration) { - return scheduleService.updateInterval(duration); - } - - @PreDestroy - public void shutdownRunnerExecutor() { - runnerExecutor.shutdownNow(); - } - - private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { - LOGGER.info("[{}] Runner starting", runner.getServiceName()); - long start = System.currentTimeMillis(); - try { - runner.run(runDirectory); - LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); - } catch (RuntimeException ex) { - LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", - runner.getServiceName(), System.currentTimeMillis() - start, ex); - } - - return new BackupServiceResult( - null, - runner.getRunnerStatus(), - runner.getRunnerStartTime(), - runner.getRunnerEndTime(), - runner.getServiceName(), - runner.getRunnerException() - ); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java deleted file mode 100644 index d3c8637..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java +++ /dev/null @@ -1,63 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; - -@Service -public class BackupScheduleService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); - - private final AtomicReference currentInterval; - private final AtomicReference nextRun; - - public BackupScheduleService(MediaGarrdProperties properties) { - Duration interval = safe(properties.getBackupInterval()); - this.currentInterval = new AtomicReference<>(interval); - this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); - LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); - } - - public Duration getInterval() { - return currentInterval.get(); - } - - public Instant getNextRun() { - return nextRun.get(); - } - - public Duration updateInterval(Duration interval) { - Duration safe = safe(interval); - currentInterval.set(safe); - Instant next = Instant.now().plus(safe); - nextRun.set(next); - LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); - return safe; - } - - public boolean dueNow() { - Instant now = Instant.now(); - Instant current = nextRun.get(); - return !now.isBefore(current); - } - - public void markRunStarted() { - Instant next = Instant.now().plus(currentInterval.get()); - nextRun.set(next); - LOGGER.info("Backup run started: nextScheduledRun={}", next); - } - - private Duration safe(Duration interval) { - if (interval == null || interval.isNegative() || interval.isZero()) { - return Duration.ofHours(12); - } - return interval; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java deleted file mode 100644 index 0339e98..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java +++ /dev/null @@ -1,236 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.stereotype.Service; - -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; -import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; - -@Service -public class DatabaseService { - - private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); - - public DatabaseService() { - verifyDatabaseIntegrity(); - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - } catch (Exception e) { - LOGGER.warn("An error occurred while disabling auto-commit on the database", e); - } - } - - private boolean verifyDatabaseIntegrity() { - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - ensureTablesExist(connection); - runNeededMigrations(connection); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while verifying the integrity of the database", sE); - return false; - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); - return false; - } - - return true; - } - - private void ensureTablesExist(Connection connection) throws SQLException { - try (var statement = connection.createStatement()) { - statement.execute(CREATE_TABLES); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("Failed to verify if tables exist in database.", sE); - handleSqlException(connection); - throw sE; - } - } - - private void runNeededMigrations(Connection connection) throws SQLException { - int currentVersion = getDatabaseVersion(connection); - if (currentVersion == -1) return; - - // 0 means it is a brand new database, or it was created before migrations existed - if (currentVersion == 0) { - // Initial tables will be "v1" - currentVersion = 1; - setDatabaseVersion(connection, currentVersion); - } - - for (Migration migration : MIGRATIONS) { - if (currentVersion <= migration.version()) { - continue; - } - - try (var statement = connection.createStatement()) { - statement.execute(migration.sql()); - } catch (SQLException sE) { - LOGGER.warn( - "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", - sE - ); - handleSqlException(connection); - throw sE; - } - - currentVersion = migration.version(); - setDatabaseVersion(connection, currentVersion); - } - - connection.commit(); - } - - private int getDatabaseVersion(Connection connection) { - try (var statement = connection.createStatement(); - var result = statement.executeQuery("PRAGMA user_version")) { - - return result.getInt(1); - } catch (SQLException sE) { - LOGGER.warn("Failed to fetch database version", sE); - return -1; - } - } - - private void setDatabaseVersion(Connection connection, int version) { - - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA user_version = " + version); - } catch (SQLException sE) { - LOGGER.warn("Failed to set new database version", sE); - } - } - - public void addNewBackupRecord(BackupRunResult backupRecord) { - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); - return; - } - - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - addMasterBackup(connection, backupRecord); - addServiceBackups(connection, backupRecord.serviceResults()); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); - } - } - - private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { - try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { - statement.setString(1, backupRecord.runId()); - statement.setString(2, backupRecord.startTime()); - statement.setString(3, backupRecord.endTime()); - statement.setString(4, backupRecord.status()); - statement.setString(5, backupRecord.archive().generateChecksum()); - statement.setString(6, backupRecord.archive().fileName()); - statement.setInt(7, backupRecord.archive().fileSize()); - statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); - statement.setString(9, backupRecord.errorMessage()); - statement.executeUpdate(); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while logging a new backup record", sE); - handleSqlException(connection); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while logging a new backup record", e); - } - } - - private void addServiceBackups(Connection connection, List serviceResults) { - for (BackupServiceResult service : serviceResults) { - try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { - statement.setString(1, service.runId()); - statement.setString(2, service.serviceName()); - statement.setString(3, service.status()); - statement.setString(4, service.startTime()); - statement.setString(5, service.endTime()); - statement.setString(6, service.errorMessage()); - statement.executeUpdate(); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); - handleSqlException(connection); - } - } - } - - public FetchedBackupRecord fetchLatestBackupRecord() { - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not fetch latest backup record"); - return null; - } - - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - return backupRecord; - } catch (SQLException sE) { - 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); - } - - return null; - } - - private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { - try (var statement = connection.createStatement()) { - var rs = statement.executeQuery(FETCH_LATEST_RECORD); - int id = rs.getInt("id"); - String backupStartTime = rs.getString("start_time"); - String status = rs.getString("status"); - String filename = rs.getString("filename"); - return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); - } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { - try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { - statement.setInt(1, backupRecord.id()); - var rs = statement.executeQuery(); - - while (rs.next()) { - String serviceName = rs.getString("service_name"); - String status = rs.getString("status"); - String startTime = rs.getString("start_time"); - var serviceRecord = new FetchedBackupServiceRecord( - serviceName, - status, - startTime - ); - backupRecord.fetchedServices().add(serviceRecord); - } - return backupRecord; - } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - private void handleSqlException(Connection connection) { - try { - connection.rollback(); - } catch (SQLException rollbackException) { - LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java deleted file mode 100644 index 28e2ecc..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.util.ArrayList; -import java.util.List; -import java.util.EnumMap; - -import org.springframework.stereotype.Component; - -import wellatleastitried.mediagarrdServer.services.config.*; -import wellatleastitried.mediagarrdServer.services.runner.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -@Component -public class RunnerFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); - - public List build(EnumMap serviceConfigMap) { - List runners = new ArrayList<>(); - - for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { - AbstractServiceConfig config = entry.getValue(); - if (config == null || !config.isEnabled()) { - LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); - continue; - } - - validate(entry.getKey(), config); - - Services key = entry.getKey(); - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - runners.add(new JellyfinRunner(config)); - LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); - yield null; - } - case RADARR -> { - runners.add(new RadarrRunner(config)); - LOGGER.info("Registered runner: radarr"); - yield null; - } - case SONARR -> { - runners.add(new SonarrRunner(config)); - LOGGER.info("Registered runner: sonarr"); - yield null; - } - case PROWLARR -> { - runners.add(new ProwlarrRunner(config)); - LOGGER.info("Registered runner: prowlarr"); - yield null; - } - case TDARR -> { - runners.add(new TdarrRunner(config)); - LOGGER.info("Registered runner: tdarr"); - yield null; - } - case QBITTORRENT -> { - runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); - LOGGER.info("Registered runner: qbittorrent"); - yield null; - } - }; - } - - LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); - return runners; - } - - private void validate(Services key, AbstractServiceConfig config) { - boolean supported = SUPPORTED_SERVICES.entrySet() - .stream() - .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); - String serviceName = SUPPORTED_SERVICES.get(key); - if (!supported) { - throw new IllegalArgumentException("Unsupported service configured: " + serviceName); - } - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - requirePath(serviceName, "configPath", config.getConfigPath()); - yield null; - } - case RADARR, SONARR, PROWLARR, TDARR -> { - requirePath(serviceName, "path", config.getPath()); - yield null; - } - case QBITTORRENT -> { - if (!(config instanceof QBittorrentServiceConfig)) { - throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); - } - - QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; - requirePath(serviceName, "path", qbConfig.getPath()); - requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); - yield null; - } - }; - } - - private void requirePath(String serviceName, String fieldName, String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java deleted file mode 100644 index 974c31d..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -//import java.util.List; - -//@ADD_NEW_SERVICE -abstract public class AbstractServiceConfig { - - private boolean enabled; - private String path; - private String configPath; - - //private List configPaths; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getConfigPath() { - return configPath; - } - - public void setConfigPath(String configPath) { - this.configPath = configPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java deleted file mode 100644 index 20482e2..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -// For services that require only one path to backup, this can be used. -// Otherwise, create a new config for a service-specific config. -public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java deleted file mode 100644 index 952667b..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -public class QBittorrentServiceConfig extends AbstractServiceConfig { - - private String savedTorrentsPath; - - // public QBittorrentServiceConfig(ServiceConfig) {} - - public String getSavedTorrentsPath() { - return savedTorrentsPath; - } - - public void setSavedTorrentsPath(String savedTorrentsPath) { - this.savedTorrentsPath = savedTorrentsPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java deleted file mode 100644 index b5d0525..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java +++ /dev/null @@ -1,188 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.List; -import java.util.Locale; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; - -//@ADD_NEW_SERVICE -public abstract class AbstractLocalCopyRunner implements Runner { - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); - - private final String serviceName; - - private String startTime; - private String endTime; - private String status; - private String errorMessage; - - protected AbstractLocalCopyRunner(String serviceName) { - this.serviceName = serviceName; - status = "idle"; - startTime = endTime = errorMessage = ""; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getRunnerStartTime() { - return startTime; - } - - @Override - public String getRunnerEndTime() { - return endTime; - } - - @Override - public String getRunnerStatus() { - return status; - } - - @Override - public String getRunnerException() { - return errorMessage; - } - - @Override - public void run(Path outputDirectory) { - startTime = Utils.recordCurrentTime(); - status = "running"; - Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); - try { - Files.createDirectories(serviceDirectory); - } catch (IOException e) { - errorMessage = "Unable to create output directory for " + serviceName; - status = "failed"; - throw new IllegalStateException("Unable to create output directory for " + serviceName, e); - } - - List specs = copySpecs(); - LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); - int succeeded = 0; - for (CopySpec spec : specs) { - try { - copySpec(spec, serviceDirectory); - succeeded++; - } catch (RuntimeException ex) { - LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); - } - } - LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); - if (succeeded == specs.size()) { - status = "completed"; - } else if (succeeded < specs.size() && succeeded > 0) { - status = "partial"; - } else { - status = "failed"; - } - endTime = Utils.recordCurrentTime(); - } - - protected abstract List copySpecs(); - - protected CopySpec dir(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, true); - } - - protected CopySpec file(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, false); - } - - private void copySpec(CopySpec spec, Path serviceDirectory) { - if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - errorMessage = serviceName + " runner missing source path for " + spec.targetName(); - status = "failed"; - throw new IllegalArgumentException(errorMessage); - } - - Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); - if (!Files.exists(source)) { - errorMessage = serviceName + " source path not found: " + source; - status = "failed"; - throw new IllegalStateException(errorMessage); - } - - Path target = serviceDirectory.resolve(spec.targetName()); - - try { - if (spec.directory()) { - if (!Files.isDirectory(source)) { - throw new IllegalStateException(serviceName + " expected directory path: " + source); - } - copyDirectory(source, target); - } else { - if (!Files.isRegularFile(source)) { - throw new IllegalStateException(serviceName + " expected file path: " + source); - } - Path parent = target.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied file: {}", serviceName, target); - } - } catch (IOException e) { - status = "failed"; - throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); - } - } - - - private void copyDirectory(Path source, Path target) throws IOException { - Files.createDirectories(target); - FileVisitor visitor = new SimpleFileVisitor<>() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(dir); - Path destination = target.resolve(relative); - Files.createDirectories(destination); - LOGGER.debug("[{}] Created dir: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(file); - Path destination = target.resolve(relative); - Path parent = destination.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - - // This will be used on all files including databases. There is a risk of corruption - // when copying a database as it could be in-use, but this is unlikely AND the fact - // that multiple backups will be retained mitigates this risk. This may be changed - // in the future with an OPTION to stop services during backup, but for now it will - // be a basic copy. - Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); - return FileVisitResult.CONTINUE; - } - }; - Files.walkFileTree(source, visitor); - } - - protected record CopySpec(String sourcePath, String targetName, boolean directory) {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java deleted file mode 100644 index 93dae71..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class JellyfinRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public JellyfinRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getConfigPath(), "config")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java deleted file mode 100644 index e7ee6e0..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ProwlarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java deleted file mode 100644 index 259cac4..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class RadarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java deleted file mode 100644 index 095420b..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java +++ /dev/null @@ -1,18 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.nio.file.Path; - -public interface Runner { - - String getServiceName(); - - String getRunnerStartTime(); - - String getRunnerEndTime(); - - String getRunnerStatus(); - - String getRunnerException(); - - void run(Path outputDirectory); -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java deleted file mode 100644 index 8e56234..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class SonarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java deleted file mode 100644 index 7fa6bbb..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class TdarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public TdarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.TDARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 6788f79..b0a3378 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java index c95af0f..c6a3477 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java @@ -1,5 +1,6 @@ package wellatleastitried.mediagarrdServer; +import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; @@ -23,16 +24,14 @@ public static String formatTime(Instant instant) { return formattedTime; } - public static int subtractTime(String startTime, String endTime) { - } public static long getDurationMs(String startTimeStr, String endTimeStr) { try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) { - } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) {} + return -1; } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java index 953e4d9..dc5e758 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java index 1236bf8..2ecc42e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -1,16 +1,5 @@ package wellatleastitried.mediagarrdServer.model; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ public record FetchedBackupServiceRecord( String serviceName, String status, diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java deleted file mode 100644 index ef75413..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java +++ /dev/null @@ -1,24 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ -public record FetchedBackupServiceRecord( - String runId, - String startTime, - String endTime, - String status, - List serviceResults, - BackupArchive archive, - String errorMessage -) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 0339e98..5493951 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -17,7 +17,7 @@ import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.*; @Service public class DatabaseService { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java index 28e2ecc..53c3d94 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -12,7 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java index 974c31d..6a72476 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java @@ -1,7 +1,5 @@ package wellatleastitried.mediagarrdServer.services.config; -//import java.util.List; - //@ADD_NEW_SERVICE abstract public class AbstractServiceConfig { @@ -9,8 +7,6 @@ abstract public class AbstractServiceConfig { private String path; private String configPath; - //private List configPaths; - public boolean isEnabled() { return enabled; } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java index 952667b..a6dbe04 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java @@ -4,8 +4,6 @@ public class QBittorrentServiceConfig extends AbstractServiceConfig { private String savedTorrentsPath; - // public QBittorrentServiceConfig(ServiceConfig) {} - public String getSavedTorrentsPath() { return savedTorrentsPath; } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java similarity index 51% rename from src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java rename to src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java index 6d5eeb1..966fcde 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java @@ -7,25 +7,23 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +public abstract class ArrRunner extends AbstractLocalCopyRunner { -public class QBittorrentRunner extends AbstractLocalCopyRunner { + private final AbstractServiceConfig config; - private final QBittorrentServiceConfig config; - - public QBittorrentRunner(QBittorrentServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); + public ArrRunner(String service, AbstractServiceConfig config) { + super(service); this.config = config; } @Override protected List copySpecs() { List specs = new ArrayList<>(); - specs.add(dir(config.getPath(), "appdata")); + specs.add(dir(config.getConfigPath(), "config")); - String savedTorrentPath = config.getSavedTorrentsPath(); - if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { - specs.add(dir(savedTorrentPath, "saved-torrents")); + Path data = Path.of(config.getPath()).resolve("data"); + if (Files.isDirectory(data)) { + specs.add(dir(data.toString(), "data")); } Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java index 93dae71..41d65bf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java index e7ee6e0..cff832e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ProwlarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class ProwlarrRunner extends ArrRunner { public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.PROWLARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java index 6d5eeb1..9b3a79f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { @@ -21,7 +21,7 @@ public QBittorrentRunner(QBittorrentServiceConfig config) { @Override protected List copySpecs() { List specs = new ArrayList<>(); - specs.add(dir(config.getPath(), "appdata")); + specs.add(dir(config.getConfigPath(), "config")); String savedTorrentPath = config.getSavedTorrentsPath(); if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java index 259cac4..ce52ac8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class RadarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class RadarrRunner extends ArrRunner { public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.RADARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java index 8e56234..9c8dc29 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class SonarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class SonarrRunner extends ArrRunner { public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.SONARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java index 7fa6bbb..c5a43cf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -1,11 +1,16 @@ package wellatleastitried.mediagarrdServer.services.runner; +import java.util.ArrayList; import java.util.List; +import java.nio.file.Files; +import java.nio.file.Path; import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +// Tdarr has a different structure than radarr/sonarr/prowlarr, so it will +// use the AbstractLocalCopyRunner instead of ArrRunner. public class TdarrRunner extends AbstractLocalCopyRunner { private final AbstractServiceConfig config; @@ -17,6 +22,24 @@ public TdarrRunner(AbstractServiceConfig config) { @Override protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + List specs = new ArrayList<>(); + specs.add(dir(config.getConfigPath(), "configs")); + + Path server = Path.of(config.getPath()).resolve("server"); + if (Files.isDirectory(server)) { + specs.add(dir(server.toString(), "server")); + } + + Path logs = Path.of(config.getPath()).resolve("logs"); + if (Files.isDirectory(logs)) { + specs.add(dir(logs.toString(), "logs")); + } + + Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); + if (Files.isRegularFile(compose)) { + specs.add(file(compose.toString(), "docker-compose.yml")); + } + + return specs; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7d47d49..f2a7d0e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -7,21 +7,27 @@ mediagarrd: retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} services: jellyfin: - enabled: ${JELLYFIN_ENABLED:true} - config-path: /srv/sources/jellyfin/config + enabled: ${JELLYFIN_ENABLED:false} + path: ${JELLYFIN_PATH:/srv/sources/jellyfin} + config-path: ${JELLYFIN_CONFIG_PATH:/srv/sources/jellyfin/config} radarr: - enabled: ${RADARR_ENABLED:true} - path: /srv/sources/radarr + enabled: ${RADARR_ENABLED:false} + path: ${RADARR_PATH:/srv/sources/radarr} + config-path: ${RADARR_CONFIG_PATH:/srv/sources/radarr/config} sonarr: - enabled: ${SONARR_ENABLED:true} - path: /srv/sources/sonarr + enabled: ${SONARR_ENABLED:false} + path: ${SONARR_PATH:/srv/sources/sonarr} + config-path: ${SONARR_CONFIG_PATH:/srv/sources/sonarr/config} prowlarr: - enabled: ${PROWLARR_ENABLED:true} - path: /srv/sources/prowlarr + enabled: ${PROWLARR_ENABLED:false} + path: ${PROWLARR_PATH:/srv/sources/prowlarr} + config-path: ${PROWLARR_CONFIG_PATH:/srv/sources/prowlarr/config} tdarr: - enabled: ${TDARR_ENABLED:true} - path: /srv/sources/tdarr + enabled: ${TDARR_ENABLED:false} + path: ${TDARR_PATH:/srv/sources/tdarr} + config-path: ${TDARR_CONFIG_PATH:/srv/sources/tdarr/configs} qbittorrent: - enabled: ${QBITTORRENT_ENABLED:true} - path: /srv/sources/qbittorrent + enabled: ${QBITTORRENT_ENABLED:false} + path: ${QBITTORRENT_PATH:/srv/sources/qbittorrent} + config-path: ${QBITTORRENT_CONFIG_PATH:/srv/sources/qbittorrent/config} saved-torrents-path: ${QBITTORRENT_SAVED_TORRENTS_PATH} From 5da89ce08f2a80f037ab1a8d256b9304fda8dd79 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Tue, 22 Sep 2026 13:24:02 -0500 Subject: [PATCH 03/26] Add testing for new database service. The basebones database and tests have been implemented, just need a little cleanup. --- .gitattributes | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 4 +- .github/ISSUE_TEMPLATE/feature_request.md | 56 ++++-- .github/ISSUE_TEMPLATE/new_service_request.md | 6 +- .gitignore | 1 + CHANGELOG | 1 + CONTRIBUTING.md | 2 +- Makefile | 4 + README.md | 2 +- build.gradle.kts | 1 + install.sh | 4 +- scripts/install-util.sh | 8 +- .../MediaGarrdProperties.java | 2 +- .../mediagarrdServer/MediaGarrdUtilities.java | 172 ------------------ .../mediagarrdServer/ServicesProperties.java | 2 +- .../api/BackupController.java | 5 +- .../mediagarrdServer/dto/BackupRunDto.java | 1 - .../mediagarrdServer/model/BackupArchive.java | 8 +- .../model/FetchedBackupRecord.java | 7 +- .../model/FetchedBackupServiceRecord.java | 4 +- .../service/BackupOrchestratorService.java | 21 ++- .../service/BackupScheduleService.java | 1 + .../service/DatabaseService.java | 117 +++++++++--- .../service/RunnerFactory.java | 2 +- .../runner/AbstractLocalCopyRunner.java | 6 +- .../services/runner/JellyfinRunner.java | 2 +- .../services/runner/ProwlarrRunner.java | 2 +- .../services/runner/QBittorrentRunner.java | 2 +- .../services/runner/RadarrRunner.java | 2 +- .../services/runner/SonarrRunner.java | 2 +- .../services/runner/TdarrRunner.java | 2 +- .../utilities/DatabaseUtils.java | 100 ++++++++++ .../utilities/MediaGarrdUtils.java | 33 ++++ .../utilities/ServiceConstants.java | 28 +++ .../MediaGarrdPropertiesBindingTest.java | 3 +- .../api/BackupControllerTest.java | 10 +- .../service/BackupArchiveServiceTest.java | 1 - .../service/BackupScheduleServiceTest.java | 1 - .../service/DatabaseServiceTest.java | 160 +++++++++++++++- .../service/RealRunnersInteractiveCheck.java | 3 +- .../service/RunnersIntegrationTest.java | 3 +- 41 files changed, 514 insertions(+), 278 deletions(-) create mode 100644 Makefile delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java diff --git a/.gitattributes b/.gitattributes index 93c61a2..e681a03 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ /gradlew text eol=lf *.bat text eol=crlf *.jar binary +src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java linguist-language=SQL diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 9b52043..3ed2bbd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -2,9 +2,7 @@ name: Bug report about: Create a report to help us improve title: "[BUG]: " -labels: bug, needs-triage -assignees: '' -type: Bug +labels: [ 'Type: Bug', 'Status: Needs Triage' ] --- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index e17b1ba..7e6c25b 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,21 +1,39 @@ ---- -name: Feature request -about: Suggest an idea for this project +name: Feature Request +description: Suggest an idea for this project title: "[FEAT]: " -labels: feature, needs-triage -assignees: '' -type: Feature +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/new_service_request.md b/.github/ISSUE_TEMPLATE/new_service_request.md index 836b1b7..aa56e07 100644 --- a/.github/ISSUE_TEMPLATE/new_service_request.md +++ b/.github/ISSUE_TEMPLATE/new_service_request.md @@ -1,10 +1,8 @@ --- name: New service request about: Request a new service to be support by MediaGarrd -title: "[ADD-SERVICE]: " -labels: add-service, needs-triage -assignees: '' -type: Feature +title: "[SERVICE]: " +labels: [ 'Type: Add Service', 'Status: Needs Triage' ] --- diff --git a/.gitignore b/.gitignore index 6703b86..39f57c5 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ gradle/ # Prod artifacts secrets/ +dockerenv/ .env data/ docker-compose.yml diff --git a/CHANGELOG b/CHANGELOG index 1324fb4..858cd74 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ ## TBD - Add database for keeping records of backups - Add issue templates +- Removed auto-routing to appdata/ within archive to retain actual paths of configs ## 9-16-26 - Adding more detailed logging for service runners diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1092eb6..c0b5e14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ ## Submitting Issues Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the template that best fits the issue. -The `needs-triage` label will automatically be applied. Once this issue has been reviewed/approved, the `approved` label will be added and Pull Requests can be opened referencing this issue. +The `Status: Needs Triage` label will automatically be applied. Once this issue has been reviewed/approved, the `Status: Approved` label will be added and Pull Requests can be opened referencing this issue. ## Pull Requests Pull requests should only be opened for issues that have the `approved` label. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..42be21a --- /dev/null +++ b/Makefile @@ -0,0 +1,4 @@ +.PHONY: test + +test: + ./gradlew test --warning-mode all diff --git a/README.md b/README.md index b8a331d..1e5daba 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This is the official server for [MediaGarrd](https://github.com/MediaGarrd/Media ```bash git clone --depth 1 https://github.com/MediaGarrd/Server.git cd Server -./install.sh # Drops .env, client.env, and docker-compose.yml +./install.sh # Drops .env, dockerenv/server.env, and docker-compose.yml docker compose up --build -d ``` diff --git a/build.gradle.kts b/build.gradle.kts index 44dc0fd..9bec437 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -10,6 +10,7 @@ repositories { dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.xerial:sqlite-jdbc:3.44.0.0") testRuntimeOnly("org.junit.platform:junit-platform-launcher") implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter") diff --git a/install.sh b/install.sh index 105358c..09027d2 100755 --- a/install.sh +++ b/install.sh @@ -110,7 +110,7 @@ services: dockerfile: Dockerfile container_name: mediagarrd-server env_file: - - ./secrets/server.env + - ./dockerenv/server.env ports: - "$server_port:$server_port" volumes: @@ -148,6 +148,6 @@ echo "Created: $SERVER_ENV_FILE" echo "" echo "Next steps:" echo "1. Review .env" -echo "2. Review secrets/server.env" +echo "2. Review dockerenv/server.env" echo "3. Review docker-compose.yml" echo "4. Start services with: docker compose up --build -d" diff --git a/scripts/install-util.sh b/scripts/install-util.sh index 75062bf..4e881f7 100644 --- a/scripts/install-util.sh +++ b/scripts/install-util.sh @@ -1,11 +1,11 @@ #!/usr/bin/env bash ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" +DOCKERENV_DIR="$ROOT_DIR/dockerenv" COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" +SERVER_ENV_FILE="$DOCKERENV_DIR/server.env" +CLIENT_ENV_FILE="$DOCKERENV_DIR/client.env" PORT_DEFAULT="38471" INTERVAL_DEFAULT="PT12H" @@ -15,7 +15,7 @@ BACKUP_RETENTION_DEFAULT="10" MNT_DIR="/mnt" DEFAULT_APPDATA_DIR="$MNT_DIR/appdata" -mkdir -p "$SECRETS_DIR" +mkdir -p "$DOCKERENV_DIR" prompt() { local var_name="$1" diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index b0a3378..258644e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java deleted file mode 100644 index c6a3477..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java +++ /dev/null @@ -1,172 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumMap; -import java.util.List; - -//@ADD_NEW_SERVICE -public final class MediaGarrdUtilities { - private MediaGarrdUtilities() {} - - public class Utils { - public static String recordCurrentTime() { - Instant instant = Instant.now(); - return formatTime(instant); - } - - public static String formatTime(Instant instant) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String formattedTime = sdf.format(Date.from(instant)); - return formattedTime; - } - - public static long getDurationMs(String startTimeStr, String endTimeStr) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) {} - return -1; - } - } - - public class ServiceConstants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - } - - public class DatabaseConstants { - - // Migrations will be added inside of the static block - public record Migration(int version, String sql) {} - public static final List MIGRATIONS; - static { - MIGRATIONS = new ArrayList(); - // Migration versions will start at 2, as the initial tables will be schema v1 - } - - public static final String SQLITE = "jdbc:sqlite:"; - public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; - - // Status used for the overall backup AND the individual service runners - public class Status { - public static final String COMPLETED = "completed"; - public static final String PARTIAL = "partial"; - public static final String FAILED = "failed"; - } - - public static final String CREATE_TABLES = """ - CREATE TABLE IF NOT EXISTS backups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - archive_id TEXT NOT NULL UNIQUE, - start_time DATETIME NOT NULL, - end_time DATETIME, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - checksum TEXT, - filename TEXT, - file_size INTEGER NOT NULL, - file_created_time DATETIME, - error_message TEXT - ); - - CREATE TABLE IF NOT EXISTS backup_services ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - backup_id INTEGER NOT NULL, - service_name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), - start_time DATETIME, - end_time DATETIME, - error_message TEXT, - FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, - UNIQUE (backup_id, service_name) - ); - - CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); - CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); - """; - - public static final String ADD_BACKUP_RECORD = """ - INSERT INTO backups ( - archive_id, - start_time, - end_time, - status, - checksum, - services_completed, - filename, - file_size, - file_created_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); - """; - - public static final String ADD_BACKUP_SERVICE_RECORD = """ - INSERT INTO backup_services ( - backup_id, - service_name, - status, - start_time, - end_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?); - """; - - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - - public static final String DELETE_BACKUP_RECORD_BY_ID = """ - DELETE FROM backups - WHERE archive_id = ?; - """; - - - /* - public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive - ) - public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt - ) - */ - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java index dc5e758..0336618 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 0ea1ed6..3ef0b03 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -21,7 +21,6 @@ import org.springframework.web.server.ResponseStatusException; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; import wellatleastitried.mediagarrdServer.dto.BackupDto; import wellatleastitried.mediagarrdServer.dto.BackupRunDto; import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; @@ -34,6 +33,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; + @RestController @RequestMapping("/api/v1") public class BackupController { @@ -135,7 +136,7 @@ public ResponseEntity deleteBackup(@PathVariable String id) { public BackupRunDto runBackup() { LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); BackupRunResult result = orchestratorService.runBackup(); - var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); + var backupDuration = getDurationMs(result.startTime(), result.endTime()); LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", result.runId(), result.serviceNames(), result.archive().fileName(), backupDuration); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java index 00a31f9..7992b8c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -1,6 +1,5 @@ package wellatleastitried.mediagarrdServer.dto; -import java.time.Instant; import java.util.List; public record BackupRunDto( diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index caeef08..3ff5942 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -4,7 +4,6 @@ import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.MessageDigest; import java.time.Instant; @@ -16,9 +15,8 @@ public record BackupArchive( Instant createdAt ) { public String generateChecksum() { - Path file = Paths.get(fileName); try { - byte[] data = Files.readAllBytes(file); + byte[] data = Files.readAllBytes(path); byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); String checksum = new BigInteger(1, hash).toString(16); return checksum; @@ -27,10 +25,8 @@ public String generateChecksum() { } public int fileSize() { - Path file = Paths.get(fileName); - long size; - try { size = Files.size(file); } + try { size = Files.size(path); } catch (IOException iE) { size = 0; } if (size > Integer.MAX_VALUE) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java index 65a4b40..cf67c10 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java @@ -4,8 +4,11 @@ public record FetchedBackupRecord( int id, + String archiveId, String startTime, + String endTime, String status, - String filename, - List fetchedServices + String filePath, + List fetchedServices, + String errorMessage ) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java index 2ecc42e..e823982 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -3,5 +3,7 @@ public record FetchedBackupServiceRecord( String serviceName, String status, - String startTime + String startTime, + String endTime, + String errorMessage ) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 8dba48a..f8580e8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -15,8 +15,6 @@ import jakarta.annotation.PreDestroy; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; @@ -27,6 +25,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status.*; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; + @Service public class BackupOrchestratorService { @@ -60,6 +61,8 @@ public BackupOrchestratorService( this.db = db; } + // TODO: Double check what this is + @Scheduled(fixedDelay = 10000) public void scheduledRun() { if (running.get()) { @@ -107,7 +110,7 @@ public BackupRunResult runBackup() { try { BackupServiceResult outcome = future.get(); serviceRunResults.add(outcome); - if (Status.COMPLETED.equals(outcome.status())) { + if (COMPLETED.equals(outcome.status())) { LOGGER.info("Runner succeeded: {}", outcome.serviceName()); } else { LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); @@ -121,7 +124,7 @@ public BackupRunResult runBackup() { } } - int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> COMPLETED.equals(r.status())).count(); LOGGER.info( "All runners finished: succeeded={}/{}", successfulRunnerCount, @@ -142,17 +145,17 @@ public BackupRunResult runBackup() { String status; if (successfulRunnerCount == runners.size()) { - status = Status.COMPLETED; + status = COMPLETED; } else if (successfulRunnerCount > 0) { - status = Status.PARTIAL; + status = PARTIAL; } else { - status = Status.FAILED; + status = FAILED; } BackupRunResult backupRecord = new BackupRunResult( archive.id(), status, - Utils.formatTime(startedAt), - Utils.recordCurrentTime(), + formatTime(startedAt), + recordCurrentTime(), serviceRunResults, archive, errorMessage diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index d3c8637..f9be79f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -56,6 +56,7 @@ public void markRunStarted() { private Duration safe(Duration interval) { if (interval == null || interval.isNegative() || interval.isZero()) { + // Default to 12 hours if the provided interval is invalid return Duration.ofHours(12); } return interval; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 5493951..7b16a29 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -2,6 +2,7 @@ import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -11,13 +12,15 @@ import org.springframework.stereotype.Service; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; +import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; + +// TODO: Add support for hosting the configuration in a table @Service public class DatabaseService { @@ -26,15 +29,14 @@ public class DatabaseService { public DatabaseService() { verifyDatabaseIntegrity(); - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - } catch (Exception e) { - LOGGER.warn("An error occurred while disabling auto-commit on the database", e); - } } - private boolean verifyDatabaseIntegrity() { - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + protected Connection getConnection() throws SQLException { + return DriverManager.getConnection(SQLITE + databasePath); + } + + protected boolean verifyDatabaseIntegrity() { + try (var connection = getConnection()) { connection.setAutoCommit(false); ensureTablesExist(connection); runNeededMigrations(connection); @@ -51,7 +53,13 @@ private boolean verifyDatabaseIntegrity() { private void ensureTablesExist(Connection connection) throws SQLException { try (var statement = connection.createStatement()) { - statement.execute(CREATE_TABLES); + for (String sql : CREATE_TABLES.split(";")) { + String CREATE_STATEMENT = sql.trim(); + if (!CREATE_STATEMENT.isEmpty()) { + statement.execute(CREATE_STATEMENT); + } + } + connection.commit(); } catch (SQLException sE) { LOGGER.warn("Failed to verify if tables exist in database.", sE); @@ -94,7 +102,7 @@ private void runNeededMigrations(Connection connection) throws SQLException { connection.commit(); } - private int getDatabaseVersion(Connection connection) { + protected int getDatabaseVersion(Connection connection) { try (var statement = connection.createStatement(); var result = statement.executeQuery("PRAGMA user_version")) { @@ -105,8 +113,7 @@ private int getDatabaseVersion(Connection connection) { } } - private void setDatabaseVersion(Connection connection, int version) { - + protected void setDatabaseVersion(Connection connection, int version) { try (var statement = connection.createStatement()) { statement.execute("PRAGMA user_version = " + version); } catch (SQLException sE) { @@ -120,7 +127,7 @@ public void addNewBackupRecord(BackupRunResult backupRecord) { return; } - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + try (var connection = getConnection()) { connection.setAutoCommit(false); addMasterBackup(connection, backupRecord); addServiceBackups(connection, backupRecord.serviceResults()); @@ -138,9 +145,9 @@ private void addMasterBackup(Connection connection, BackupRunResult backupRecord statement.setString(3, backupRecord.endTime()); statement.setString(4, backupRecord.status()); statement.setString(5, backupRecord.archive().generateChecksum()); - statement.setString(6, backupRecord.archive().fileName()); + statement.setString(6, backupRecord.archive().path().toString()); statement.setInt(7, backupRecord.archive().fileSize()); - statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(8, formatTime(backupRecord.archive().createdAt())); statement.setString(9, backupRecord.errorMessage()); statement.executeUpdate(); connection.commit(); @@ -170,14 +177,64 @@ private void addServiceBackups(Connection connection, List } } + private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + + int id = rs.getInt("id"); + String archiveId = rs.getString("archive_id"); + String backupStartTime = rs.getString("start_time"); + String backupEndTime = rs.getString("end_time"); + String status = rs.getString("status"); + String filePath = rs.getString("file_path"); + String errorMessage = rs.getString("error_message"); + + return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); + } + + public FetchedBackupRecord fetchBackupById(String archiveId) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch backup record by archive_id (" + archiveId + ")"); + return null; + } + + try (var connection = getConnection()) { + FetchedBackupRecord backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord == null) return null; + + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { + try (var statement = connection.prepareStatement(FETCH_RECORD_BY_ID)) { + statement.setString(1, archiveId); + var rs = statement.executeQuery(); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException sE) { + LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", sE); + return null; + } + } + public FetchedBackupRecord fetchLatestBackupRecord() { if (!verifyDatabaseIntegrity()) { LOGGER.warn("Could not fetch latest backup record"); return null; } - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + try (var connection = getConnection()) { FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord == null) return null; + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); return backupRecord; } catch (SQLException sE) { @@ -192,11 +249,7 @@ public FetchedBackupRecord fetchLatestBackupRecord() { private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { try (var statement = connection.createStatement()) { var rs = statement.executeQuery(FETCH_LATEST_RECORD); - int id = rs.getInt("id"); - String backupStartTime = rs.getString("start_time"); - String status = rs.getString("status"); - String filename = rs.getString("filename"); - return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + return buildFetchedBackupRecordFromQueryResult(rs); } catch (SQLException sE) { LOGGER.warn("Error fetching latest backup record", sE); return null; @@ -212,16 +265,20 @@ private FetchedBackupRecord populateFetchedRecordWithServices(Connection connect String serviceName = rs.getString("service_name"); String status = rs.getString("status"); String startTime = rs.getString("start_time"); + String endTime = rs.getString("end_time"); + String errorMessage = rs.getString("error_message"); var serviceRecord = new FetchedBackupServiceRecord( serviceName, status, - startTime + startTime, + endTime, + errorMessage ); backupRecord.fetchedServices().add(serviceRecord); } return backupRecord; } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); + LOGGER.warn("Error populating backup record with related services", sE); return null; } } @@ -233,4 +290,16 @@ private void handleSqlException(Connection connection) { LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); } } + + public void deleteBackupRecordById(String archiveId) { + try (var connection = getConnection(); + var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { + statement.setString(1, archiveId); + statement.executeUpdate(); + } catch (SQLException sE) { + LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); + } + } + + // TODO: Add support to fetch all records for a report on history } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java index 53c3d94..527ca62 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -12,7 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java index b5d0525..48a27a8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java @@ -14,7 +14,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; //@ADD_NEW_SERVICE public abstract class AbstractLocalCopyRunner implements Runner { @@ -61,7 +61,7 @@ public String getRunnerException() { @Override public void run(Path outputDirectory) { - startTime = Utils.recordCurrentTime(); + startTime = recordCurrentTime(); status = "running"; Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); try { @@ -91,7 +91,7 @@ public void run(Path outputDirectory) { } else { status = "failed"; } - endTime = Utils.recordCurrentTime(); + endTime = recordCurrentTime(); } protected abstract List copySpecs(); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java index 41d65bf..8dadf39 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java index cff832e..c9bb625 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class ProwlarrRunner extends ArrRunner { public ProwlarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java index 9b3a79f..a326e0a 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java index ce52ac8..0675a97 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class RadarrRunner extends ArrRunner { public RadarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java index 9c8dc29..1da70d3 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class SonarrRunner extends ArrRunner { public SonarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java index c5a43cf..b28be73 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; // Tdarr has a different structure than radarr/sonarr/prowlarr, so it will // use the AbstractLocalCopyRunner instead of ArrRunner. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java new file mode 100644 index 0000000..13e87e6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java @@ -0,0 +1,100 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.util.ArrayList; +import java.util.List; + +public class DatabaseUtils { + + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databasePath = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + file_path TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + file_path, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_RECORD_BY_ID = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + WHERE archive_id = ?; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time, end_time, error_message FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java new file mode 100644 index 0000000..19043a9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java @@ -0,0 +1,33 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; + +public class MediaGarrdUtils { + + private MediaGarrdUtils() {} + + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) {} + return -1; + } +} + diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java new file mode 100644 index 0000000..07fcf4f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java @@ -0,0 +1,28 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.util.EnumMap; + +//@ADD_NEW_SERVICE +public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 748ee76..29cbfd5 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -9,8 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 2cd1c0e..6e66556 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -19,7 +19,6 @@ import org.springframework.test.web.servlet.MockMvc; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.api.BackupController; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; @@ -52,6 +51,7 @@ void healthReturnsServerStatus() throws Exception { @Test void runAndListBackups() throws Exception { + String errorMessage = "testErrorMessage"; BackupArchive archive = new BackupArchive( "backup-1", "backup-1.zip", @@ -61,10 +61,12 @@ void runAndListBackups() throws Exception { ); BackupRunResult result = new BackupRunResult( "run-1", - Instant.parse("2026-01-01T00:00:00Z"), - Instant.parse("2026-01-01T00:01:00Z"), + "2026-01-01T00:00:00Z", + "2026-01-01T00:01:00Z", + "testStatus", List.of(), - archive + archive, + errorMessage ); when(orchestratorService.runBackup()).thenReturn(result); when(archiveService.listArchives()).thenReturn(List.of(archive)); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index fe201fd..1b4de04 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.service.BackupArchiveService; class BackupArchiveServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index 422f3ee..f54453e 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.Test; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.service.BackupScheduleService; class BackupScheduleServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java index 1c580e2..d5d7991 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -1,5 +1,159 @@ package wellatleastitried.mediagarrdServer.service; -// TODO: Implement full unit testing for db -// ref: https://github.com/wellatleastitried/StreamLine/blob/menu-options/src/test/java/com/streamline/database/DatabaseRunnerTest.java -public class DatabaseServiceTest {} +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static org.junit.jupiter.api.Assertions.*; + +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; + +public class DatabaseServiceTest { + + String testBackupId = "testId"; + String testStartTime = "testStartTime"; + String testEndTime = "testEndTime"; + String testFilename = "testFilename"; + Path testFilePath = Paths.get("testFilePath"); + long testFileSize = 1337; + Instant testInstant = Instant.now(); + BackupArchive testArchive = new BackupArchive(testBackupId, testFilename, testFilePath, testFileSize, testInstant); + String testErrorMessage = "testErrorMessage"; + + String serviceOneStartTime = "testStartTime1"; + String serviceOneEndTime = "testEndTime1"; + String serviceTwoStartTime = "testStartTime2"; + String serviceTwoEndTime = "testEndTime2"; + String serviceThreeStartTime = "testStartTime3"; + String serviceThreeEndTime = null; + + private DatabaseService databaseService; + private Connection testConnection; + + private Connection wrapUncloseable(Connection real) { + return (Connection) Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] { Connection.class }, + (proxy, method, args) -> { + // Need to "swallor" null so the in-memory database survives + if ("close".equals(method.getName())) { + return null; + } + try { + return method.invoke(real, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + ); + } + + @BeforeEach + public void setUp() throws SQLException { + testConnection = DriverManager.getConnection("jdbc:sqlite::memory:"); + Connection uncloseable = wrapUncloseable(testConnection); + databaseService = new DatabaseService() { + @Override + protected Connection getConnection() throws SQLException { + return uncloseable; + } + }; + } + + @AfterEach + public void tearDown() throws SQLException { + testConnection.close(); + } + + @Test + public void testDatabaseIntegrity() { + boolean hasIntegrity = databaseService.verifyDatabaseIntegrity(); + assertEquals(true, hasIntegrity); + } + + @Test + public void testConnection() throws SQLException { + try (var connection = databaseService.getConnection()) { + assertEquals(true, connection.isValid(10)); + } catch (SQLException sE) { fail(sE); } + } + + private BackupRunResult buildTestBackupRunResult() { + List testServiceResults = List.of( + new BackupServiceResult(testBackupId, Status.COMPLETED, serviceOneStartTime, serviceOneEndTime, SUPPORTED_SERVICES.get(Services.JELLYFIN), testErrorMessage), + new BackupServiceResult(testBackupId, Status.PARTIAL, serviceTwoStartTime, serviceTwoEndTime, SUPPORTED_SERVICES.get(Services.SONARR), testErrorMessage), + new BackupServiceResult(testBackupId, Status.FAILED, serviceThreeStartTime, serviceThreeEndTime, SUPPORTED_SERVICES.get(Services.QBITTORRENT), testErrorMessage) + ); + return new BackupRunResult( + testBackupId, + testStartTime, + testEndTime, + Status.COMPLETED, + testServiceResults, + testArchive, + testErrorMessage + ); + } + + @Test + public void testAddingBackupRecord() { + BackupRunResult testBackupRecord = buildTestBackupRunResult(); + + databaseService.addNewBackupRecord(testBackupRecord); + + FetchedBackupRecord testRecord = databaseService.fetchBackupById(testArchive.id()); + + assertEquals(testBackupId, testRecord.archiveId()); + assertEquals(testFilePath.toString(), testRecord.filePath()); + assertEquals(testStartTime, testRecord.startTime()); + assertEquals(testEndTime, testRecord.endTime()); + for (FetchedBackupServiceRecord testServiceResult : testRecord.fetchedServices()) { + if (SUPPORTED_SERVICES.get(Services.JELLYFIN).equals(testServiceResult.serviceName())) { + assertEquals(serviceOneStartTime, testServiceResult.startTime()); + assertEquals(serviceOneEndTime, testServiceResult.endTime()); + assertEquals(Status.COMPLETED, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + + } else if (SUPPORTED_SERVICES.get(Services.SONARR).equals(testServiceResult.serviceName())) { + assertEquals(serviceTwoStartTime, testServiceResult.startTime()); + assertEquals(serviceTwoEndTime, testServiceResult.endTime()); + assertEquals(Status.PARTIAL, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + } else if (SUPPORTED_SERVICES.get(Services.QBITTORRENT).equals(testServiceResult.serviceName())) { + assertEquals(serviceThreeStartTime, testServiceResult.startTime()); + assertEquals(serviceThreeEndTime, testServiceResult.endTime()); + assertEquals(Status.FAILED, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + } else { + fail("UNREACHABLE"); + } + } + } + + @Test + public void testDeletingBackupRecord() { + BackupRunResult testBackupRecord = buildTestBackupRunResult(); + databaseService.addNewBackupRecord(testBackupRecord); + databaseService.deleteBackupRecordById(testBackupRecord.runId()); + FetchedBackupRecord testFetchedBackupRecord = databaseService.fetchBackupById(testBackupRecord.runId()); + + assertEquals(null, testFetchedBackupRecord); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java index 385c71c..6eb37c3 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java @@ -8,8 +8,7 @@ import java.util.List; import java.util.Locale; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; -import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java index 3985680..a895099 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java @@ -17,8 +17,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; -import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; From 6757be74723375f8238ea13f8caf4cee8d5a1fb9 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 20:01:05 -0500 Subject: [PATCH 04/26] Finish logging fixes, finish database implementation cleanup. --- CHANGELOG | 1 + CONTRIBUTING.md | 2 +- docker-compose.example.yml | 3 +-- ref/SUPPORTED_SERVICES | 2 -- .../mediagarrdServer/service/BackupOrchestratorService.java | 4 +--- .../mediagarrdServer/service/DatabaseService.java | 4 ---- 6 files changed, 4 insertions(+), 12 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 858cd74..e224003 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ ## TBD - Add database for keeping records of backups +- Add thorough testing of database functionality - Add issue templates - Removed auto-routing to appdata/ within archive to retain actual paths of configs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0b5e14..1a83d1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the temp The `Status: Needs Triage` label will automatically be applied. Once this issue has been reviewed/approved, the `Status: Approved` label will be added and Pull Requests can be opened referencing this issue. ## Pull Requests -Pull requests should only be opened for issues that have the `approved` label. +Pull requests should only be opened for issues that have the `Status: Approved` label. ## AI Usage See [AGENTS.md](https://github.com/MediaGarrd/Server/blob/main/AGENTS.md) for a more in-depth overview of the way AI is permitted in code submissions. If a signature is not present on a commit that even *appears* to be generated by an LLM, the PR will be closed. This is strictly for the continued maintainability of the project. diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9f93f22..a1c4c39 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -1,4 +1,3 @@ -# Auto-generated docker-compose.yml by install.sh services: mediagarrd-server: build: @@ -6,7 +5,7 @@ services: dockerfile: Dockerfile container_name: mediagarrd-server env_file: - - ./secrets/server.env + - ./dockerenv/server.env ports: - "38471:38471" volumes: diff --git a/ref/SUPPORTED_SERVICES b/ref/SUPPORTED_SERVICES index c816d7f..659cab9 100644 --- a/ref/SUPPORTED_SERVICES +++ b/ref/SUPPORTED_SERVICES @@ -1,6 +1,4 @@ //@ADD_NEW_SERVICE -// All support services will be listed here - alphabetic order -// Coming soon - Gitea, Lidarr Jellyfin Prowlarr diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index f8580e8..ae7e21d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -61,9 +61,7 @@ public BackupOrchestratorService( this.db = db; } - // TODO: Double check what this is - - @Scheduled(fixedDelay = 10000) + @Scheduled(fixedDelay = 30000) public void scheduledRun() { if (running.get()) { LOGGER.debug("Scheduled check skipped, backup already in progress"); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 7b16a29..c7e9fe6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -20,8 +20,6 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; -// TODO: Add support for hosting the configuration in a table - @Service public class DatabaseService { @@ -300,6 +298,4 @@ public void deleteBackupRecordById(String archiveId) { LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); } } - - // TODO: Add support to fetch all records for a report on history } From d17ed67c04a6378de16f7990ac1778c48aba65c2 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 22:12:13 -0500 Subject: [PATCH 05/26] Finalize CHANGELOG --- CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index e224003..e90564b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ # CHANGELOG -## TBD +## 9-23-26 - Add database for keeping records of backups - Add thorough testing of database functionality - Add issue templates From 976b5e0c4f4e1dbe81b55d7a67c4402a8e19ee2f Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Fri, 18 Sep 2026 16:59:37 -0500 Subject: [PATCH 06/26] Implement database functionality to keep records of previous runs. --- .github/ISSUE_TEMPLATE/bug_report.md | 33 ++ .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/feature_request.md | 21 ++ .github/ISSUE_TEMPLATE/new_service_request.md | 19 ++ CHANGELOG | 4 + CONTRIBUTING.md | 12 + .../mediagarrd/Constants.java | 30 -- .../mediagarrd/MediaGarrd.java | 2 +- .../mediagarrd/MediaGarrdProperties.java | 7 +- .../mediagarrd/MediaGarrdUtilities.java | 173 +++++++++++ .../mediagarrd/ServicesProperties.java | 7 +- .../mediagarrd/api/BackupController.java | 34 ++- .../mediagarrd/dto/BackupDto.java | 2 +- .../mediagarrd/dto/BackupRunDto.java | 6 +- .../mediagarrd/dto/ScheduleUpdateRequest.java | 2 +- .../mediagarrd/dto/ServerStatusDto.java | 2 +- .../mediagarrd/model/BackupArchive.java | 32 +- .../mediagarrd/model/BackupRunResult.java | 68 ++++- .../mediagarrd/model/BackupServiceResult.java | 50 ++++ .../mediagarrd/model/FetchedBackupRecord.java | 11 + .../model/FetchedBackupServiceRecord.java | 18 ++ .../service/BackupArchiveService.java | 7 +- .../service/BackupOrchestratorService.java | 96 ++++-- .../service/BackupScheduleService.java | 4 +- .../mediagarrd/service/DatabaseService.java | 236 +++++++++++++++ .../mediagarrd/service/RunnerFactory.java | 10 +- .../config/AbstractServiceConfig.java | 2 +- .../services/config/CommonServiceConfig.java | 2 +- .../config/QBittorrentServiceConfig.java | 2 +- .../runner/AbstractLocalCopyRunner.java | 53 +++- .../services/runner/JellyfinRunner.java | 6 +- .../services/runner/ProwlarrRunner.java | 6 +- .../services/runner/QBittorrentRunner.java | 6 +- .../services/runner/RadarrRunner.java | 6 +- .../mediagarrd/services/runner/Runner.java | 10 +- .../services/runner/SonarrRunner.java | 6 +- .../services/runner/TdarrRunner.java | 6 +- .../mediagarrdServer/MediaGarrd.java | 16 + .../MediaGarrdProperties.java | 57 ++++ .../mediagarrdServer/MediaGarrdUtilities.java | 173 +++++++++++ .../mediagarrdServer/ServicesProperties.java | 84 ++++++ .../api/BackupController.java | 183 ++++++++++++ .../mediagarrdServer/dto/BackupDto.java | 11 + .../mediagarrdServer/dto/BackupRunDto.java | 13 + .../dto/ScheduleUpdateRequest.java | 5 + .../mediagarrdServer/dto/ServerStatusDto.java | 10 + .../mediagarrdServer/model/BackupArchive.java | 43 +++ .../model/BackupRunResult.java | 63 ++++ .../model/BackupServiceResult.java | 50 ++++ .../model/FetchedBackupRecord.java | 11 + .../model/FetchedBackupServiceRecord.java | 18 ++ .../model/FetchedServiceBackupRecord.java | 24 ++ .../service/BackupArchiveService.java | 281 ++++++++++++++++++ .../service/BackupOrchestratorService.java | 206 +++++++++++++ .../service/BackupScheduleService.java | 63 ++++ .../service/DatabaseService.java | 236 +++++++++++++++ .../service/RunnerFactory.java | 114 +++++++ .../config/AbstractServiceConfig.java | 37 +++ .../services/config/CommonServiceConfig.java | 5 + .../config/QBittorrentServiceConfig.java | 16 + .../runner/AbstractLocalCopyRunner.java | 188 ++++++++++++ .../services/runner/JellyfinRunner.java | 22 ++ .../services/runner/ProwlarrRunner.java | 22 ++ .../services/runner/QBittorrentRunner.java | 38 +++ .../services/runner/RadarrRunner.java | 22 ++ .../services/runner/Runner.java | 18 ++ .../services/runner/SonarrRunner.java | 22 ++ .../services/runner/TdarrRunner.java | 22 ++ .../MediaGarrdPropertiesBindingTest.java | 11 +- .../api/BackupControllerTest.java | 13 +- .../service/BackupArchiveServiceTest.java | 5 +- .../service/BackupScheduleServiceTest.java | 5 +- .../service/DatabaseServiceTest.java | 5 + .../service/RealRunnersInteractiveCheck.java | 13 +- .../service/RunnersIntegrationTest.java | 13 +- 75 files changed, 2970 insertions(+), 160 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/new_service_request.md create mode 100644 CONTRIBUTING.md delete mode 100644 src/main/java/wellatleastitried/mediagarrd/Constants.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/MediaGarrdPropertiesBindingTest.java (73%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/api/BackupControllerTest.java (84%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/BackupArchiveServiceTest.java (84%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/BackupScheduleServiceTest.java (81%) create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/RealRunnersInteractiveCheck.java (90%) rename src/test/java/wellatleastitried/{mediagarrd => mediagarrdServer}/service/RunnersIntegrationTest.java (93%) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..9b52043 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]: " +labels: bug, needs-triage +assignees: '' +type: Bug + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Device(s) (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e17b1ba --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEAT]: " +labels: feature, needs-triage +assignees: '' +type: Feature + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/new_service_request.md b/.github/ISSUE_TEMPLATE/new_service_request.md new file mode 100644 index 0000000..836b1b7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new_service_request.md @@ -0,0 +1,19 @@ +--- +name: New service request +about: Request a new service to be support by MediaGarrd +title: "[ADD-SERVICE]: " +labels: add-service, needs-triage +assignees: '' +type: Feature + +--- + +**Name of the service:** + +**Provide a link to the service's repository:** + +**What files would need to be backed up?** +*Provide something like: `config/`, `service.db`, etc.* + +**Additional context** +*Add any other context about the new service here.* diff --git a/CHANGELOG b/CHANGELOG index 140a7e5..1324fb4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,10 @@ # CHANGELOG ## TBD +- Add database for keeping records of backups +- Add issue templates + +## 9-16-26 - Adding more detailed logging for service runners - Renaming QBittorrent's "graveyard" directory to "saved-torrents" to make it less ambiguous diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1092eb6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing to the MediaGarrd Server + +## Submitting Issues +Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the template that best fits the issue. + +The `needs-triage` label will automatically be applied. Once this issue has been reviewed/approved, the `approved` label will be added and Pull Requests can be opened referencing this issue. + +## Pull Requests +Pull requests should only be opened for issues that have the `approved` label. + +## AI Usage +See [AGENTS.md](https://github.com/MediaGarrd/Server/blob/main/AGENTS.md) for a more in-depth overview of the way AI is permitted in code submissions. If a signature is not present on a commit that even *appears* to be generated by an LLM, the PR will be closed. This is strictly for the continued maintainability of the project. diff --git a/src/main/java/wellatleastitried/mediagarrd/Constants.java b/src/main/java/wellatleastitried/mediagarrd/Constants.java deleted file mode 100644 index 94aeca9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/Constants.java +++ /dev/null @@ -1,30 +0,0 @@ -package wellatleastitried.mediagarrd; - -import java.util.EnumMap; - -//@ADD_NEW_SERVICE -public final class Constants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - - private Constants() {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java index fbe9798..9f32db2 100644 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java index 598fc10..6788f79 100644 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java @@ -1,12 +1,13 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import java.time.Duration; import java.util.EnumMap; import org.springframework.boot.context.properties.ConfigurationProperties; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java new file mode 100644 index 0000000..c95af0f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java @@ -0,0 +1,173 @@ +package wellatleastitried.mediagarrdServer; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumMap; +import java.util.List; + +//@ADD_NEW_SERVICE +public final class MediaGarrdUtilities { + private MediaGarrdUtilities() {} + + public class Utils { + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static int subtractTime(String startTime, String endTime) { + } + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) { + } + } + } + + public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } + } + + public class DatabaseConstants { + + // Migrations will be added inside of the static block + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + filename TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + services_completed, + filename, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; + + + /* + public record BackupRunResult( + String runId, + Instant startedAt, + Instant finishedAt, + List servicesRan, + BackupArchive archive + ) + public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt + ) + */ + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java index d7081dc..953e4d9 100644 --- a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java @@ -1,9 +1,10 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import java.util.EnumMap; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java index 92d11d0..0ea1ed6 100644 --- a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.api; +package wellatleastitried.mediagarrdServer.api; import java.io.IOException; import java.time.Duration; @@ -20,19 +20,20 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.dto.BackupDto; -import wellatleastitried.mediagarrd.dto.BackupRunDto; -import wellatleastitried.mediagarrd.dto.ScheduleUpdateRequest; -import wellatleastitried.mediagarrd.dto.ServerStatusDto; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; - @RestController @RequestMapping("/api/v1") public class BackupController { @@ -134,14 +135,15 @@ public ResponseEntity deleteBackup(@PathVariable String id) { public BackupRunDto runBackup() { LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); BackupRunResult result = orchestratorService.runBackup(); + var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", - result.runId(), result.servicesRan(), result.archive().fileName(), - result.finishedAt().toEpochMilli() - result.startedAt().toEpochMilli()); + result.runId(), result.serviceNames(), result.archive().fileName(), + backupDuration); return new BackupRunDto( result.runId(), - result.startedAt(), - result.finishedAt(), - result.servicesRan(), + result.startTime(), + result.endTime(), + result.serviceNames(), toDto(result.archive()) ); } diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java index e3932d2..6286b33 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Instant; diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java index e745805..00a31f9 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java @@ -1,12 +1,12 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Instant; import java.util.List; public record BackupRunDto( String runId, - Instant startedAt, - Instant finishedAt, + String startTime, + String endTime, List servicesRan, BackupDto archive ) { diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java index a0d0486..a3916da 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java index 8282d37..bd2613f 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java +++ b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java index 3f6300e..caeef08 100644 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java @@ -1,6 +1,11 @@ -package wellatleastitried.mediagarrd.model; +package wellatleastitried.mediagarrdServer.model; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; import java.time.Instant; public record BackupArchive( @@ -10,4 +15,29 @@ public record BackupArchive( long sizeBytes, Instant createdAt ) { + public String generateChecksum() { + Path file = Paths.get(fileName); + try { + byte[] data = Files.readAllBytes(file); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); + String checksum = new BigInteger(1, hash).toString(16); + return checksum; + } catch (Exception e) {} + return ""; + } + + public int fileSize() { + Path file = Paths.get(fileName); + + long size; + try { size = Files.size(file); } + catch (IOException iE) { size = 0; } + + if (size > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + + return (int) size; + + } } diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java index 18849bb..f46693e 100644 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java @@ -1,13 +1,63 @@ -package wellatleastitried.mediagarrd.model; +package wellatleastitried.mediagarrdServer.model; -import java.time.Instant; import java.util.List; -public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive -) { +public class BackupRunResult { + private final String runId; + private final String startTime; + private final String endTime; + private final String status; + private final List serviceResults; + private final BackupArchive archive; + private final String errorMessage; + + public BackupRunResult( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage + ) { + this.runId = runId; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.serviceResults = serviceResults; + this.archive = archive; + this.errorMessage = errorMessage; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + + public String startTime() { + return startTime; + } + + public String endTime() { + return endTime; + } + + public List serviceResults() { + return serviceResults; + } + + public List serviceNames() { + return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); + } + + public BackupArchive archive() { + return archive; + } + + public String errorMessage() { + return errorMessage; + } } diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java new file mode 100644 index 0000000..6877586 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdServer.model; + +public class BackupServiceResult { + private String runId; + private final String status; + private final String startTime; + private final String endTime; + private final String serviceName; + private final String errorMessage; + + public BackupServiceResult( + String runId, + String status, + String startTime, + String endTime, + String serviceName, + String errorMessage + ) { + this.runId = runId; + this.status = status; + this.startTime = startTime; + this.endTime = endTime; + this.serviceName = serviceName; + this.errorMessage = errorMessage; + } + + public void setId(String runId) { + this.runId = runId; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + public String startTime() { + return startTime; + } + public String endTime() { + return endTime; + } + public String serviceName() { + return serviceName; + } + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java new file mode 100644 index 0000000..65a4b40 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public record FetchedBackupRecord( + int id, + String startTime, + String status, + String filename, + List fetchedServices +) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java new file mode 100644 index 0000000..1236bf8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.model; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String serviceName, + String status, + String startTime +) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java index b90dc03..a08bcd6 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.io.IOException; import java.io.InputStream; @@ -20,14 +20,13 @@ import java.util.zip.ZipOutputStream; import jakarta.annotation.PostConstruct; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; - @Service public class BackupArchiveService { diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java index 17b49bc..8dba48a 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.nio.file.Path; import java.util.ArrayList; @@ -14,17 +14,19 @@ import java.util.concurrent.atomic.AtomicBoolean; import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.services.runner.Runner; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.services.runner.Runner; - @Service public class BackupOrchestratorService { @@ -34,11 +36,12 @@ public class BackupOrchestratorService { private final RunnerFactory runnerFactory; private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; + private final DatabaseService db; private final AtomicBoolean running = new AtomicBoolean(false); private final ExecutorService runnerExecutor = new ThreadPoolExecutor( 1, // core threads 6, // max threads - 30, // keep-alive time + 30, // ttl TimeUnit.SECONDS, new LinkedBlockingQueue<>() ); @@ -47,12 +50,14 @@ public BackupOrchestratorService( MediaGarrdProperties properties, RunnerFactory runnerFactory, BackupArchiveService archiveService, - BackupScheduleService scheduleService + BackupScheduleService scheduleService, + DatabaseService db ) { this.properties = properties; this.runnerFactory = runnerFactory; this.archiveService = archiveService; this.scheduleService = scheduleService; + this.db = db; } @Scheduled(fixedDelay = 10000) @@ -83,22 +88,26 @@ public BackupRunResult runBackup() { Path runDirectory = archiveService.createRunDirectory(); Instant startedAt = Instant.now(); List runners = runnerFactory.build(properties.getServiceConfigs()); - List servicesCompleted = new ArrayList<>(); + List serviceRunResults = new ArrayList<>(); - LOGGER.info("Backup run started: runDir={}, services={}", runDirectory, runners.stream().map(Runner::getServiceName).toList()); + LOGGER.info( + "Backup run started: runDir={}, services={}", + runDirectory, + runners.stream().map(Runner::getServiceName).toList()); try { - List> futures = new ArrayList<>(); + String errorMessage = ""; + List> futures = new ArrayList<>(); for (Runner runner : runners) { LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); } - for (Future future : futures) { + for (Future future : futures) { try { - RunnerOutcome outcome = future.get(); - if (outcome.success()) { - servicesCompleted.add(outcome.serviceName()); + BackupServiceResult outcome = future.get(); + serviceRunResults.add(outcome); + if (Status.COMPLETED.equals(outcome.status())) { LOGGER.info("Runner succeeded: {}", outcome.serviceName()); } else { LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); @@ -107,22 +116,49 @@ public BackupRunResult runBackup() { Thread.currentThread().interrupt(); throw new IllegalStateException("Backup run interrupted", ex); } catch (ExecutionException ex) { + errorMessage.concat(ex.getMessage() + "\n"); LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); } } - LOGGER.info("All runners finished: succeeded={}/{}", servicesCompleted.size(), runners.size()); + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + LOGGER.info( + "All runners finished: succeeded={}/{}", + successfulRunnerCount, + runners.size() + ); BackupArchive archive = archiveService.createArchive(runDirectory); + for (BackupServiceResult serviceResult : serviceRunResults) { + serviceResult.setId(archive.id()); + } long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), archive.sizeBytes(), durationMs, servicesCompleted); - return new BackupRunResult( + LOGGER.info( + "Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), + archive.sizeBytes(), + durationMs, + serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() + ); + + String status; + if (successfulRunnerCount == runners.size()) { + status = Status.COMPLETED; + } else if (successfulRunnerCount > 0) { + status = Status.PARTIAL; + } else { + status = Status.FAILED; + } + BackupRunResult backupRecord = new BackupRunResult( archive.id(), - startedAt, - Instant.now(), - servicesCompleted, - archive + status, + Utils.formatTime(startedAt), + Utils.recordCurrentTime(), + serviceRunResults, + archive, + errorMessage ); + db.addNewBackupRecord(backupRecord); + return backupRecord; } finally { archiveService.removeRunDirectory(runDirectory); running.set(false); @@ -147,20 +183,24 @@ public void shutdownRunnerExecutor() { runnerExecutor.shutdownNow(); } - private RunnerOutcome runSingleRunner(Runner runner, Path runDirectory) { + private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { LOGGER.info("[{}] Runner starting", runner.getServiceName()); long start = System.currentTimeMillis(); try { runner.run(runDirectory); LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); - return new RunnerOutcome(runner.getServiceName(), true); } catch (RuntimeException ex) { LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", runner.getServiceName(), System.currentTimeMillis() - start, ex); - return new RunnerOutcome(runner.getServiceName(), false); } - } - private record RunnerOutcome(String serviceName, boolean success) { + return new BackupServiceResult( + null, + runner.getRunnerStatus(), + runner.getRunnerStartTime(), + runner.getRunnerEndTime(), + runner.getServiceName(), + runner.getRunnerException() + ); } } diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java index 0d5f824..d3c8637 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.time.Duration; import java.time.Instant; @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; @Service public class BackupScheduleService { diff --git a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java new file mode 100644 index 0000000..0339e98 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; + +@Service +public class DatabaseService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); + + public DatabaseService() { + verifyDatabaseIntegrity(); + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + } catch (Exception e) { + LOGGER.warn("An error occurred while disabling auto-commit on the database", e); + } + } + + private boolean verifyDatabaseIntegrity() { + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + ensureTablesExist(connection); + runNeededMigrations(connection); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + return false; + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + return true; + } + + private void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + statement.execute(CREATE_TABLES); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("Failed to verify if tables exist in database.", sE); + handleSqlException(connection); + throw sE; + } + } + + private void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = getDatabaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion <= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException sE) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + sE + ); + handleSqlException(connection); + throw sE; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + private int getDatabaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + + return result.getInt(1); + } catch (SQLException sE) { + LOGGER.warn("Failed to fetch database version", sE); + return -1; + } + } + + private void setDatabaseVersion(Connection connection, int version) { + + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException sE) { + LOGGER.warn("Failed to set new database version", sE); + } + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); + return; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + addMasterBackup(connection, backupRecord); + addServiceBackups(connection, backupRecord.serviceResults()); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } + } + + private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + statement.setString(5, backupRecord.archive().generateChecksum()); + statement.setString(6, backupRecord.archive().fileName()); + statement.setInt(7, backupRecord.archive().fileSize()); + statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while logging a new backup record", sE); + handleSqlException(connection); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + } + + private void addServiceBackups(Connection connection, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setString(1, service.runId()); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); + handleSqlException(connection); + } + } + } + + public FetchedBackupRecord fetchLatestBackupRecord() { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch latest backup record"); + return null; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + int id = rs.getInt("id"); + String backupStartTime = rs.getString("start_time"); + String status = rs.getString("status"); + String filename = rs.getString("filename"); + return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private void handleSqlException(Connection connection) { + try { + connection.rollback(); + } catch (SQLException rollbackException) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java index 60646f3..28e2ecc 100644 --- a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java @@ -1,16 +1,18 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.util.ArrayList; import java.util.List; import java.util.EnumMap; import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.services.config.*; +import wellatleastitried.mediagarrdServer.services.runner.*; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; -import wellatleastitried.mediagarrd.services.runner.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java index e4954f8..974c31d 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; //import java.util.List; diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java index ba9eb66..20482e2 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; // For services that require only one path to backup, this can be used. // Otherwise, create a new config for a service-specific config. diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java index 10a9ff4..952667b 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.config; +package wellatleastitried.mediagarrdServer.services.config; public class QBittorrentServiceConfig extends AbstractServiceConfig { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java index df60230..b5d0525 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.io.IOException; import java.nio.file.FileVisitResult; @@ -10,11 +10,12 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Locale; -import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; + //@ADD_NEW_SERVICE public abstract class AbstractLocalCopyRunner implements Runner { @@ -22,8 +23,15 @@ public abstract class AbstractLocalCopyRunner implements Runner { private final String serviceName; + private String startTime; + private String endTime; + private String status; + private String errorMessage; + protected AbstractLocalCopyRunner(String serviceName) { this.serviceName = serviceName; + status = "idle"; + startTime = endTime = errorMessage = ""; } @Override @@ -31,12 +39,36 @@ public String getServiceName() { return serviceName; } + @Override + public String getRunnerStartTime() { + return startTime; + } + + @Override + public String getRunnerEndTime() { + return endTime; + } + + @Override + public String getRunnerStatus() { + return status; + } + + @Override + public String getRunnerException() { + return errorMessage; + } + @Override public void run(Path outputDirectory) { + startTime = Utils.recordCurrentTime(); + status = "running"; Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); try { Files.createDirectories(serviceDirectory); } catch (IOException e) { + errorMessage = "Unable to create output directory for " + serviceName; + status = "failed"; throw new IllegalStateException("Unable to create output directory for " + serviceName, e); } @@ -52,6 +84,14 @@ public void run(Path outputDirectory) { } } LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); + if (succeeded == specs.size()) { + status = "completed"; + } else if (succeeded < specs.size() && succeeded > 0) { + status = "partial"; + } else { + status = "failed"; + } + endTime = Utils.recordCurrentTime(); } protected abstract List copySpecs(); @@ -66,12 +106,16 @@ protected CopySpec file(String sourcePath, String targetName) { private void copySpec(CopySpec spec, Path serviceDirectory) { if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - throw new IllegalArgumentException(serviceName + " runner missing source path for " + spec.targetName()); + errorMessage = serviceName + " runner missing source path for " + spec.targetName(); + status = "failed"; + throw new IllegalArgumentException(errorMessage); } Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); if (!Files.exists(source)) { - throw new IllegalStateException(serviceName + " source path not found: " + source); + errorMessage = serviceName + " source path not found: " + source; + status = "failed"; + throw new IllegalStateException(errorMessage); } Path target = serviceDirectory.resolve(spec.targetName()); @@ -94,6 +138,7 @@ private void copySpec(CopySpec spec, Path serviceDirectory) { LOGGER.debug("[{}] Copied file: {}", serviceName, target); } } catch (IOException e) { + status = "failed"; throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); } } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java index cea92d2..93dae71 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java index f98c771..e7ee6e0 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class ProwlarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java index 0679f0f..6d5eeb1 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java @@ -1,13 +1,13 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java index b55c477..259cac4 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class RadarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java index 44747c7..095420b 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.nio.file.Path; @@ -6,5 +6,13 @@ public interface Runner { String getServiceName(); + String getRunnerStartTime(); + + String getRunnerEndTime(); + + String getRunnerStatus(); + + String getRunnerException(); + void run(Path outputDirectory); } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java index beaa063..8e56234 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class SonarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java index b84cd99..7fa6bbb 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java @@ -1,10 +1,10 @@ -package wellatleastitried.mediagarrd.services.runner; +package wellatleastitried.mediagarrdServer.services.runner; import java.util.List; -import wellatleastitried.mediagarrd.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.Constants.*; +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; public class TdarrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java new file mode 100644 index 0000000..9f32db2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdServer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableConfigurationProperties(MediaGarrdProperties.class) +public class MediaGarrd { + + public static void main(String[] args) { + SpringApplication.run(MediaGarrd.class, args); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java new file mode 100644 index 0000000..6788f79 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -0,0 +1,57 @@ +package wellatleastitried.mediagarrdServer; + +import java.time.Duration; +import java.util.EnumMap; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +@ConfigurationProperties(prefix = "mediagarrd") +public class MediaGarrdProperties { + + private Duration backupInterval = Duration.ofHours(12); + private String backupRoot = "./data/server/backups"; + private int retentionCount = 10; + private ServicesProperties services = new ServicesProperties(); + + public Duration getBackupInterval() { + return backupInterval; + } + + public void setBackupInterval(Duration backupInterval) { + this.backupInterval = backupInterval; + } + + public String getBackupRoot() { + return backupRoot; + } + + public void setBackupRoot(String backupRoot) { + this.backupRoot = backupRoot; + } + + public int getRetentionCount() { + return retentionCount; + } + + public void setRetentionCount(int retentionCount) { + this.retentionCount = retentionCount; + } + + public ServicesProperties getServices() { + return services; + } + + public void setServices(ServicesProperties services) { + this.services = services; + } + + public EnumMap getServiceConfigs() { + return services.toRuntimeConfigs(); + } + + +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java new file mode 100644 index 0000000..c95af0f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java @@ -0,0 +1,173 @@ +package wellatleastitried.mediagarrdServer; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumMap; +import java.util.List; + +//@ADD_NEW_SERVICE +public final class MediaGarrdUtilities { + private MediaGarrdUtilities() {} + + public class Utils { + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static int subtractTime(String startTime, String endTime) { + } + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) { + } + } + } + + public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } + } + + public class DatabaseConstants { + + // Migrations will be added inside of the static block + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + filename TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + services_completed, + filename, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; + + + /* + public record BackupRunResult( + String runId, + Instant startedAt, + Instant finishedAt, + List servicesRan, + BackupArchive archive + ) + public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt + ) + */ + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java new file mode 100644 index 0000000..953e4d9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -0,0 +1,84 @@ +package wellatleastitried.mediagarrdServer; + +import java.util.EnumMap; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class ServicesProperties { + + //@ADD_NEW_SERVICE + private CommonServiceConfig jellyfin; + private CommonServiceConfig radarr; + private CommonServiceConfig sonarr; + private CommonServiceConfig prowlarr; + private CommonServiceConfig tdarr; + private QBittorrentServiceConfig qbittorrent; + + public EnumMap toRuntimeConfigs() { + EnumMap configs = new EnumMap<>(Services.class); + put(configs, Services.JELLYFIN, jellyfin); + put(configs, Services.RADARR, radarr); + put(configs, Services.SONARR, sonarr); + put(configs, Services.PROWLARR, prowlarr); + put(configs, Services.TDARR, tdarr); + put(configs, Services.QBITTORRENT, qbittorrent); + return configs; + } + + private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { + if (config != null) { + configs.put(service, config); + } + } + + public CommonServiceConfig getJellyfin() { + return jellyfin; + } + + public void setJellyfin(CommonServiceConfig jellyfin) { + this.jellyfin = jellyfin; + } + + public CommonServiceConfig getRadarr() { + return radarr; + } + + public void setRadarr(CommonServiceConfig radarr) { + this.radarr = radarr; + } + + public CommonServiceConfig getSonarr() { + return sonarr; + } + + public void setSonarr(CommonServiceConfig sonarr) { + this.sonarr = sonarr; + } + + public CommonServiceConfig getProwlarr() { + return prowlarr; + } + + public void setProwlarr(CommonServiceConfig prowlarr) { + this.prowlarr = prowlarr; + } + + public CommonServiceConfig getTdarr() { + return tdarr; + } + + public void setTdarr(CommonServiceConfig tdarr) { + this.tdarr = tdarr; + } + + public QBittorrentServiceConfig getQbittorrent() { + return qbittorrent; + } + + public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { + this.qbittorrent = qbittorrent; + } + +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java new file mode 100644 index 0000000..0ea1ed6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -0,0 +1,183 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.time.Duration; +import java.util.List; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RestController +@RequestMapping("/api/v1") +public class BackupController { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupController.class); + + private final BackupArchiveService archiveService; + private final BackupOrchestratorService orchestratorService; + private final MediaGarrdProperties properties; + + public BackupController( + BackupArchiveService archiveService, + BackupOrchestratorService orchestratorService, + MediaGarrdProperties properties + ) { + this.archiveService = archiveService; + this.orchestratorService = orchestratorService; + this.properties = properties; + } + + @GetMapping("/health") + public ServerStatusDto health() { + LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + return new ServerStatusDto( + true, + orchestratorService.isRunning(), + properties.getRetentionCount(), + orchestratorService.getInterval() + ); + } + + @PutMapping("/schedule") + public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { + LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); + Duration updated = orchestratorService.updateInterval(request.backupInterval()); + LOGGER.info("Schedule updated: newInterval={}", updated); + return new ServerStatusDto( + true, + orchestratorService.isRunning(), + properties.getRetentionCount(), + updated + ); + } + + @GetMapping("/backups") + public List listBackups() { + LOGGER.info("GET /api/v1/backups"); + List backups = archiveService.listArchives().stream().map(this::toDto).toList(); + LOGGER.info("Returning {} backup(s)", backups.size()); + return backups; + } + + @GetMapping("/backups/latest") + public BackupDto latestBackup() { + LOGGER.info("GET /api/v1/backups/latest"); + BackupArchive archive = archiveService.latest() + .orElseThrow(() -> notFound("No backup archives found")); + LOGGER.info("Latest backup: {}", archive.fileName()); + return toDto(archive); + } + + @GetMapping("/backups/{id}") + public BackupDto backupById(@PathVariable String id) { + LOGGER.info("GET /api/v1/backups/{}", id); + return archiveService.byId(id) + .map(this::toDto) + .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); + } + + @GetMapping("/backups/{id}/download") + public ResponseEntity downloadById(@PathVariable String id) { + LOGGER.info("GET /api/v1/backups/{}/download", id); + BackupArchive archive = archiveService.byId(id) + .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); + return downloadResponse(archive); + } + + @GetMapping("/backups/latest/download") + public ResponseEntity downloadLatest() { + LOGGER.info("GET /api/v1/backups/latest/download"); + BackupArchive archive = archiveService.latest() + .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); + return downloadResponse(archive); + } + + @DeleteMapping("/backups/{id}") + public ResponseEntity deleteBackup(@PathVariable String id) { + LOGGER.info("DELETE /api/v1/backups/{}", id); + boolean deleted = archiveService.deleteById(id); + if (!deleted) { + LOGGER.warn("Delete failed: backup not found: {}", id); + return ResponseEntity.notFound().build(); + } + LOGGER.info("Backup deleted: {}", id); + return ResponseEntity.noContent().build(); + } + + @PostMapping("/backups/run") + public BackupRunDto runBackup() { + LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); + BackupRunResult result = orchestratorService.runBackup(); + var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); + LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", + result.runId(), result.serviceNames(), result.archive().fileName(), + backupDuration); + return new BackupRunDto( + result.runId(), + result.startTime(), + result.endTime(), + result.serviceNames(), + toDto(result.archive()) + ); + } + + private ResponseEntity downloadResponse(BackupArchive archive) { + Resource file = new FileSystemResource(archive.path()); + if (!file.exists()) { + LOGGER.error("Archive file missing on disk: {}", archive.path()); + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); + } + + try { + LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(file.contentLength()) + .body(file); + } catch (IOException e) { + LOGGER.error("Failed to read backup file: {}", archive.path(), e); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); + } + } + + private BackupDto toDto(BackupArchive archive) { + return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); + } + + private ResponseStatusException notFound(String logMessage) { + return notFound(logMessage, logMessage); + } + + private ResponseStatusException notFound(String logMessage, String responseMessage) { + LOGGER.warn(logMessage); + return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java new file mode 100644 index 0000000..6286b33 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record BackupDto( + String id, + String fileName, + long sizeBytes, + Instant createdAt +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java new file mode 100644 index 0000000..00a31f9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; +import java.util.List; + +public record BackupRunDto( + String runId, + String startTime, + String endTime, + List servicesRan, + BackupDto archive +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java new file mode 100644 index 0000000..a3916da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record ScheduleUpdateRequest(Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java new file mode 100644 index 0000000..bd2613f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java @@ -0,0 +1,10 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record ServerStatusDto( + boolean healthy, + boolean running, + int backupRetentionCount, + Duration backupInterval +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java new file mode 100644 index 0000000..caeef08 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -0,0 +1,43 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.time.Instant; + +public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt +) { + public String generateChecksum() { + Path file = Paths.get(fileName); + try { + byte[] data = Files.readAllBytes(file); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); + String checksum = new BigInteger(1, hash).toString(16); + return checksum; + } catch (Exception e) {} + return ""; + } + + public int fileSize() { + Path file = Paths.get(fileName); + + long size; + try { size = Files.size(file); } + catch (IOException iE) { size = 0; } + + if (size > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + + return (int) size; + + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java new file mode 100644 index 0000000..f46693e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public class BackupRunResult { + private final String runId; + private final String startTime; + private final String endTime; + private final String status; + private final List serviceResults; + private final BackupArchive archive; + private final String errorMessage; + + public BackupRunResult( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage + ) { + this.runId = runId; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.serviceResults = serviceResults; + this.archive = archive; + this.errorMessage = errorMessage; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + + public String startTime() { + return startTime; + } + + public String endTime() { + return endTime; + } + + public List serviceResults() { + return serviceResults; + } + + public List serviceNames() { + return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); + } + + public BackupArchive archive() { + return archive; + } + + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java new file mode 100644 index 0000000..6877586 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdServer.model; + +public class BackupServiceResult { + private String runId; + private final String status; + private final String startTime; + private final String endTime; + private final String serviceName; + private final String errorMessage; + + public BackupServiceResult( + String runId, + String status, + String startTime, + String endTime, + String serviceName, + String errorMessage + ) { + this.runId = runId; + this.status = status; + this.startTime = startTime; + this.endTime = endTime; + this.serviceName = serviceName; + this.errorMessage = errorMessage; + } + + public void setId(String runId) { + this.runId = runId; + } + + public String runId() { + return runId; + } + + public String status() { + return status; + } + public String startTime() { + return startTime; + } + public String endTime() { + return endTime; + } + public String serviceName() { + return serviceName; + } + public String errorMessage() { + return errorMessage; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java new file mode 100644 index 0000000..65a4b40 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public record FetchedBackupRecord( + int id, + String startTime, + String status, + String filename, + List fetchedServices +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java new file mode 100644 index 0000000..1236bf8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.model; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String serviceName, + String status, + String startTime +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java new file mode 100644 index 0000000..ef75413 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + /* + public static final String FETCH_LATEST_RECORD = """ + SELECT id, start_time, status, filename FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time FROM backup_services + WHERE backup_id = ?; + """; + */ +public record FetchedBackupServiceRecord( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java new file mode 100644 index 0000000..a08bcd6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -0,0 +1,281 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import jakarta.annotation.PostConstruct; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; + +import org.springframework.stereotype.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Service +public class BackupArchiveService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); + + private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") + .withZone(ZoneOffset.UTC); + private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds + + private final MediaGarrdProperties properties; + private final AtomicReference> cachedArchives = new AtomicReference<>(null); + private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); + + public BackupArchiveService(MediaGarrdProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void cleanupStaleArtifactsOnStartup() { + Path root = rootDirectory(); + Path runsRoot = root.resolve("runs"); + + try { + Files.createDirectories(root); + + try (var stream = Files.list(root)) { + stream + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) + .forEach(path -> { + try { + Files.deleteIfExists(path); + LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); + } + }); + } + + if (Files.exists(runsRoot)) { + try (var stream = Files.list(runsRoot)) { + stream + .filter(Files::isDirectory) + .forEach(runDir -> { + try { + removeRunDirectory(runDir); + LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); + } + }); + } + } + + enforceRetention(); + LOGGER.info("Startup cleanup: retention policy enforced"); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); + } + } + + public Path rootDirectory() { + return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); + } + + public BackupArchive createArchive(Path runDirectory) { + Instant createdAt = Instant.now(); + String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; + Path root = rootDirectory(); + Path archivePath = root.resolve(fileName); + + LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); + try { + Files.createDirectories(root); + zipDirectory(runDirectory, archivePath); + enforceRetention(); + long size = Files.size(archivePath); + LOGGER.info("Archive created: {} ({} bytes)", fileName, size); + + // Invalidate cache after new archive created + cacheLastUpdatedMs.set(0); + cachedArchives.set(null); + + return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); + } catch (IOException e) { + LOGGER.error("Failed to create backup archive: {}", fileName, e); + throw new IllegalStateException("Failed to create backup archive", e); + } + } + + public List listArchives() { + long now = System.currentTimeMillis(); + long lastUpdate = cacheLastUpdatedMs.get(); + + if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { + List cached = cachedArchives.get(); + if (cached != null) { + LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); + return cached; + } + } + + // Cache miss -> rebuild list + Path root = rootDirectory(); + List archives; + if (!Files.exists(root)) { + archives = List.of(); + } else { + try (var stream = Files.list(root)) { + archives = stream + .filter(path -> path.getFileName().toString().endsWith(".zip")) + .sorted(Comparator.comparing(this::lastModified).reversed()) + .map(this::toArchive) + .toList(); + } catch (IOException e) { + throw new IllegalStateException("Failed to list archives", e); + } + } + + cachedArchives.set(archives); + cacheLastUpdatedMs.set(now); + LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); + return archives; + } + + public Optional latest() { + return listArchives().stream().findFirst(); + } + + public Optional byId(String id) { + return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); + } + + public boolean deleteById(String id) { + Optional archive = byId(id); + if (archive.isEmpty()) { + return false; + } + + try { + Files.deleteIfExists(archive.get().path()); + LOGGER.info("Archive deleted: {}", id); + cacheLastUpdatedMs.set(0); + + cachedArchives.set(null); + return true; + + } catch (IOException e) { + LOGGER.error("Failed to delete archive: {}", id, e); + throw new IllegalStateException("Failed to delete archive " + id, e); + } + } + + public Path createRunDirectory() { + Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); + try { + Files.createDirectories(runDir); + return runDir; + } catch (IOException e) { + throw new IllegalStateException("Failed to create run directory", e); + } + } + + public void removeRunDirectory(Path runDirectory) { + if (runDirectory == null || !Files.exists(runDirectory)) { + return; + } + + try (var walk = Files.walk(runDirectory)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + throw new IllegalStateException("Failed to clean up run directory", e); + } + }); + } catch (IOException e) { + throw new IllegalStateException("Failed to walk run directory", e); + } + } + + private void enforceRetention() throws IOException { + int retain = Math.max(1, properties.getRetentionCount()); + List archives; + try (var stream = Files.list(rootDirectory())) { + archives = stream + .filter(path -> path.getFileName().toString().endsWith(".zip")) + .sorted(Comparator.comparing(this::lastModified).reversed()) + .toList(); + } + for (int i = retain; i < archives.size(); i++) { + Path toDelete = archives.get(i); + LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); + Files.deleteIfExists(toDelete); + } + } + + private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { + Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + ZipOutputStream zipOut = new ZipOutputStream(fileOut); + var paths = Files.walk(sourceDir)) { + + paths.filter(Files::isRegularFile).forEach(path -> { + Path relative = sourceDir.relativize(path); + try { + zipOut.putNextEntry(new ZipEntry(relative.toString())); + try (InputStream in = Files.newInputStream(path)) { + in.transferTo(zipOut); + } + zipOut.closeEntry(); + } catch (IOException e) { + throw new IllegalStateException("Failed to zip file " + path, e); + } + }); + } + Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } + + private BackupArchive toArchive(Path path) { + String fileName = path.getFileName().toString(); + return new BackupArchive( + toId(fileName), + fileName, + path, + fileSize(path), + lastModified(path) + ); + } + + private String toId(String fileName) { + return fileName.replace(".zip", ""); + } + + private long fileSize(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + return 0L; + } + } + + private Instant lastModified(Path path) { + try { + return Files.getLastModifiedTime(path).toInstant(); + } catch (IOException e) { + return Instant.EPOCH; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java new file mode 100644 index 0000000..8dba48a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -0,0 +1,206 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.services.runner.Runner; + +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Service +public class BackupOrchestratorService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); + + private final MediaGarrdProperties properties; + private final RunnerFactory runnerFactory; + private final BackupArchiveService archiveService; + private final BackupScheduleService scheduleService; + private final DatabaseService db; + private final AtomicBoolean running = new AtomicBoolean(false); + private final ExecutorService runnerExecutor = new ThreadPoolExecutor( + 1, // core threads + 6, // max threads + 30, // ttl + TimeUnit.SECONDS, + new LinkedBlockingQueue<>() + ); + + public BackupOrchestratorService( + MediaGarrdProperties properties, + RunnerFactory runnerFactory, + BackupArchiveService archiveService, + BackupScheduleService scheduleService, + DatabaseService db + ) { + this.properties = properties; + this.runnerFactory = runnerFactory; + this.archiveService = archiveService; + this.scheduleService = scheduleService; + this.db = db; + } + + @Scheduled(fixedDelay = 10000) + public void scheduledRun() { + if (running.get()) { + LOGGER.debug("Scheduled check skipped, backup already in progress"); + return; + } + if (!scheduleService.dueNow()) { + return; + } + LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); + try { + runBackup(); + } catch (RuntimeException ex) { + LOGGER.error("Scheduled backup run failed", ex); + } + } + + public BackupRunResult runBackup() { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new IllegalStateException("A backup run is already in progress"); + } + + scheduleService.markRunStarted(); + + Path runDirectory = archiveService.createRunDirectory(); + Instant startedAt = Instant.now(); + List runners = runnerFactory.build(properties.getServiceConfigs()); + List serviceRunResults = new ArrayList<>(); + + LOGGER.info( + "Backup run started: runDir={}, services={}", + runDirectory, + runners.stream().map(Runner::getServiceName).toList()); + + try { + String errorMessage = ""; + List> futures = new ArrayList<>(); + for (Runner runner : runners) { + LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); + futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); + } + + for (Future future : futures) { + try { + BackupServiceResult outcome = future.get(); + serviceRunResults.add(outcome); + if (Status.COMPLETED.equals(outcome.status())) { + LOGGER.info("Runner succeeded: {}", outcome.serviceName()); + } else { + LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Backup run interrupted", ex); + } catch (ExecutionException ex) { + errorMessage.concat(ex.getMessage() + "\n"); + LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); + } + } + + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + LOGGER.info( + "All runners finished: succeeded={}/{}", + successfulRunnerCount, + runners.size() + ); + BackupArchive archive = archiveService.createArchive(runDirectory); + for (BackupServiceResult serviceResult : serviceRunResults) { + serviceResult.setId(archive.id()); + } + long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); + LOGGER.info( + "Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), + archive.sizeBytes(), + durationMs, + serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() + ); + + String status; + if (successfulRunnerCount == runners.size()) { + status = Status.COMPLETED; + } else if (successfulRunnerCount > 0) { + status = Status.PARTIAL; + } else { + status = Status.FAILED; + } + BackupRunResult backupRecord = new BackupRunResult( + archive.id(), + status, + Utils.formatTime(startedAt), + Utils.recordCurrentTime(), + serviceRunResults, + archive, + errorMessage + ); + db.addNewBackupRecord(backupRecord); + return backupRecord; + } finally { + archiveService.removeRunDirectory(runDirectory); + running.set(false); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } + } + + public boolean isRunning() { + return running.get(); + } + + public Duration getInterval() { + return scheduleService.getInterval(); + } + + public Duration updateInterval(Duration duration) { + return scheduleService.updateInterval(duration); + } + + @PreDestroy + public void shutdownRunnerExecutor() { + runnerExecutor.shutdownNow(); + } + + private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { + LOGGER.info("[{}] Runner starting", runner.getServiceName()); + long start = System.currentTimeMillis(); + try { + runner.run(runDirectory); + LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); + } catch (RuntimeException ex) { + LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", + runner.getServiceName(), System.currentTimeMillis() - start, ex); + } + + return new BackupServiceResult( + null, + runner.getRunnerStatus(), + runner.getRunnerStartTime(), + runner.getRunnerEndTime(), + runner.getServiceName(), + runner.getRunnerException() + ); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java new file mode 100644 index 0000000..d3c8637 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Service +public class BackupScheduleService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); + + private final AtomicReference currentInterval; + private final AtomicReference nextRun; + + public BackupScheduleService(MediaGarrdProperties properties) { + Duration interval = safe(properties.getBackupInterval()); + this.currentInterval = new AtomicReference<>(interval); + this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); + LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); + } + + public Duration getInterval() { + return currentInterval.get(); + } + + public Instant getNextRun() { + return nextRun.get(); + } + + public Duration updateInterval(Duration interval) { + Duration safe = safe(interval); + currentInterval.set(safe); + Instant next = Instant.now().plus(safe); + nextRun.set(next); + LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); + return safe; + } + + public boolean dueNow() { + Instant now = Instant.now(); + Instant current = nextRun.get(); + return !now.isBefore(current); + } + + public void markRunStarted() { + Instant next = Instant.now().plus(currentInterval.get()); + nextRun.set(next); + LOGGER.info("Backup run started: nextScheduledRun={}", next); + } + + private Duration safe(Duration interval) { + if (interval == null || interval.isNegative() || interval.isZero()) { + return Duration.ofHours(12); + } + return interval; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java new file mode 100644 index 0000000..0339e98 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; + +@Service +public class DatabaseService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); + + public DatabaseService() { + verifyDatabaseIntegrity(); + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + } catch (Exception e) { + LOGGER.warn("An error occurred while disabling auto-commit on the database", e); + } + } + + private boolean verifyDatabaseIntegrity() { + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + ensureTablesExist(connection); + runNeededMigrations(connection); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + return false; + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + return true; + } + + private void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + statement.execute(CREATE_TABLES); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("Failed to verify if tables exist in database.", sE); + handleSqlException(connection); + throw sE; + } + } + + private void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = getDatabaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion <= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException sE) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + sE + ); + handleSqlException(connection); + throw sE; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + private int getDatabaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + + return result.getInt(1); + } catch (SQLException sE) { + LOGGER.warn("Failed to fetch database version", sE); + return -1; + } + } + + private void setDatabaseVersion(Connection connection, int version) { + + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException sE) { + LOGGER.warn("Failed to set new database version", sE); + } + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); + return; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + connection.setAutoCommit(false); + addMasterBackup(connection, backupRecord); + addServiceBackups(connection, backupRecord.serviceResults()); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } + } + + private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + statement.setString(5, backupRecord.archive().generateChecksum()); + statement.setString(6, backupRecord.archive().fileName()); + statement.setInt(7, backupRecord.archive().fileSize()); + statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while logging a new backup record", sE); + handleSqlException(connection); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + } + + private void addServiceBackups(Connection connection, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setString(1, service.runId()); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + connection.commit(); + } catch (SQLException sE) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); + handleSqlException(connection); + } + } + } + + public FetchedBackupRecord fetchLatestBackupRecord() { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch latest backup record"); + return null; + } + + try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + int id = rs.getInt("id"); + String backupStartTime = rs.getString("start_time"); + String status = rs.getString("status"); + String filename = rs.getString("filename"); + return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException sE) { + LOGGER.warn("Error fetching latest backup record", sE); + return null; + } + } + + private void handleSqlException(Connection connection) { + try { + connection.rollback(); + } catch (SQLException rollbackException) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java new file mode 100644 index 0000000..28e2ecc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -0,0 +1,114 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.EnumMap; + +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.services.config.*; +import wellatleastitried.mediagarrdServer.services.runner.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +@Component +public class RunnerFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); + + public List build(EnumMap serviceConfigMap) { + List runners = new ArrayList<>(); + + for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { + AbstractServiceConfig config = entry.getValue(); + if (config == null || !config.isEnabled()) { + LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); + continue; + } + + validate(entry.getKey(), config); + + Services key = entry.getKey(); + + //@ADD_NEW_SERVICE + @SuppressWarnings("unused") + Object exhaustive = switch (key) { + case JELLYFIN -> { + runners.add(new JellyfinRunner(config)); + LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); + yield null; + } + case RADARR -> { + runners.add(new RadarrRunner(config)); + LOGGER.info("Registered runner: radarr"); + yield null; + } + case SONARR -> { + runners.add(new SonarrRunner(config)); + LOGGER.info("Registered runner: sonarr"); + yield null; + } + case PROWLARR -> { + runners.add(new ProwlarrRunner(config)); + LOGGER.info("Registered runner: prowlarr"); + yield null; + } + case TDARR -> { + runners.add(new TdarrRunner(config)); + LOGGER.info("Registered runner: tdarr"); + yield null; + } + case QBITTORRENT -> { + runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); + LOGGER.info("Registered runner: qbittorrent"); + yield null; + } + }; + } + + LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); + return runners; + } + + private void validate(Services key, AbstractServiceConfig config) { + boolean supported = SUPPORTED_SERVICES.entrySet() + .stream() + .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); + String serviceName = SUPPORTED_SERVICES.get(key); + if (!supported) { + throw new IllegalArgumentException("Unsupported service configured: " + serviceName); + } + + //@ADD_NEW_SERVICE + @SuppressWarnings("unused") + Object exhaustive = switch (key) { + case JELLYFIN -> { + requirePath(serviceName, "configPath", config.getConfigPath()); + yield null; + } + case RADARR, SONARR, PROWLARR, TDARR -> { + requirePath(serviceName, "path", config.getPath()); + yield null; + } + case QBITTORRENT -> { + if (!(config instanceof QBittorrentServiceConfig)) { + throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); + } + + QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; + requirePath(serviceName, "path", qbConfig.getPath()); + requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); + yield null; + } + }; + } + + private void requirePath(String serviceName, String fieldName, String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java new file mode 100644 index 0000000..974c31d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdServer.services.config; + +//import java.util.List; + +//@ADD_NEW_SERVICE +abstract public class AbstractServiceConfig { + + private boolean enabled; + private String path; + private String configPath; + + //private List configPaths; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getConfigPath() { + return configPath; + } + + public void setConfigPath(String configPath) { + this.configPath = configPath; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java new file mode 100644 index 0000000..20482e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.services.config; + +// For services that require only one path to backup, this can be used. +// Otherwise, create a new config for a service-specific config. +public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java new file mode 100644 index 0000000..952667b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdServer.services.config; + +public class QBittorrentServiceConfig extends AbstractServiceConfig { + + private String savedTorrentsPath; + + // public QBittorrentServiceConfig(ServiceConfig) {} + + public String getSavedTorrentsPath() { + return savedTorrentsPath; + } + + public void setSavedTorrentsPath(String savedTorrentsPath) { + this.savedTorrentsPath = savedTorrentsPath; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java new file mode 100644 index 0000000..b5d0525 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java @@ -0,0 +1,188 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.List; +import java.util.Locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; + +//@ADD_NEW_SERVICE +public abstract class AbstractLocalCopyRunner implements Runner { + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); + + private final String serviceName; + + private String startTime; + private String endTime; + private String status; + private String errorMessage; + + protected AbstractLocalCopyRunner(String serviceName) { + this.serviceName = serviceName; + status = "idle"; + startTime = endTime = errorMessage = ""; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getRunnerStartTime() { + return startTime; + } + + @Override + public String getRunnerEndTime() { + return endTime; + } + + @Override + public String getRunnerStatus() { + return status; + } + + @Override + public String getRunnerException() { + return errorMessage; + } + + @Override + public void run(Path outputDirectory) { + startTime = Utils.recordCurrentTime(); + status = "running"; + Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); + try { + Files.createDirectories(serviceDirectory); + } catch (IOException e) { + errorMessage = "Unable to create output directory for " + serviceName; + status = "failed"; + throw new IllegalStateException("Unable to create output directory for " + serviceName, e); + } + + List specs = copySpecs(); + LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); + int succeeded = 0; + for (CopySpec spec : specs) { + try { + copySpec(spec, serviceDirectory); + succeeded++; + } catch (RuntimeException ex) { + LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); + } + } + LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); + if (succeeded == specs.size()) { + status = "completed"; + } else if (succeeded < specs.size() && succeeded > 0) { + status = "partial"; + } else { + status = "failed"; + } + endTime = Utils.recordCurrentTime(); + } + + protected abstract List copySpecs(); + + protected CopySpec dir(String sourcePath, String targetName) { + return new CopySpec(sourcePath, targetName, true); + } + + protected CopySpec file(String sourcePath, String targetName) { + return new CopySpec(sourcePath, targetName, false); + } + + private void copySpec(CopySpec spec, Path serviceDirectory) { + if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { + errorMessage = serviceName + " runner missing source path for " + spec.targetName(); + status = "failed"; + throw new IllegalArgumentException(errorMessage); + } + + Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); + if (!Files.exists(source)) { + errorMessage = serviceName + " source path not found: " + source; + status = "failed"; + throw new IllegalStateException(errorMessage); + } + + Path target = serviceDirectory.resolve(spec.targetName()); + + try { + if (spec.directory()) { + if (!Files.isDirectory(source)) { + throw new IllegalStateException(serviceName + " expected directory path: " + source); + } + copyDirectory(source, target); + } else { + if (!Files.isRegularFile(source)) { + throw new IllegalStateException(serviceName + " expected file path: " + source); + } + Path parent = target.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); + LOGGER.debug("[{}] Copied file: {}", serviceName, target); + } + } catch (IOException e) { + status = "failed"; + throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); + } + } + + + private void copyDirectory(Path source, Path target) throws IOException { + Files.createDirectories(target); + FileVisitor visitor = new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Path relative = source.relativize(dir); + Path destination = target.resolve(relative); + Files.createDirectories(destination); + LOGGER.debug("[{}] Created dir: {}", serviceName, destination); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path relative = source.relativize(file); + Path destination = target.resolve(relative); + Path parent = destination.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + + // This will be used on all files including databases. There is a risk of corruption + // when copying a database as it could be in-use, but this is unlikely AND the fact + // that multiple backups will be retained mitigates this risk. This may be changed + // in the future with an OPTION to stop services during backup, but for now it will + // be a basic copy. + Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); + LOGGER.debug("[{}] Copied: {}", serviceName, destination); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); + return FileVisitResult.CONTINUE; + } + }; + Files.walkFileTree(source, visitor); + } + + protected record CopySpec(String sourcePath, String targetName, boolean directory) {} +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java new file mode 100644 index 0000000..93dae71 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class JellyfinRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public JellyfinRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getConfigPath(), "config")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java new file mode 100644 index 0000000..e7ee6e0 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class ProwlarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public ProwlarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.PROWLARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java new file mode 100644 index 0000000..6d5eeb1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -0,0 +1,38 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class QBittorrentRunner extends AbstractLocalCopyRunner { + + private final QBittorrentServiceConfig config; + + public QBittorrentRunner(QBittorrentServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); + this.config = config; + } + + @Override + protected List copySpecs() { + List specs = new ArrayList<>(); + specs.add(dir(config.getPath(), "appdata")); + + String savedTorrentPath = config.getSavedTorrentsPath(); + if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { + specs.add(dir(savedTorrentPath, "saved-torrents")); + } + + Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); + if (Files.isRegularFile(compose)) { + specs.add(file(compose.toString(), "docker-compose.yml")); + } + + return specs; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java new file mode 100644 index 0000000..259cac4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class RadarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public RadarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.RADARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java new file mode 100644 index 0000000..095420b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.nio.file.Path; + +public interface Runner { + + String getServiceName(); + + String getRunnerStartTime(); + + String getRunnerEndTime(); + + String getRunnerStatus(); + + String getRunnerException(); + + void run(Path outputDirectory); +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java new file mode 100644 index 0000000..8e56234 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class SonarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public SonarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.SONARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java new file mode 100644 index 0000000..7fa6bbb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +import java.util.List; + +import wellatleastitried.mediagarrdServer.services.config.*; + +import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; + +public class TdarrRunner extends AbstractLocalCopyRunner { + + private final AbstractServiceConfig config; + + public TdarrRunner(AbstractServiceConfig config) { + super(SUPPORTED_SERVICES.get(Services.TDARR)); + this.config = config; + } + + @Override + protected List copySpecs() { + return List.of(dir(config.getPath(), "appdata")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java similarity index 73% rename from src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index b037445..748ee76 100644 --- a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd; +package wellatleastitried.mediagarrdServer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -9,10 +9,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; @SpringBootTest(properties = { "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-properties-test", diff --git a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java similarity index 84% rename from src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 0e10eca..2cd1c0e 100644 --- a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.api; +package wellatleastitried.mediagarrdServer.api; import static org.hamcrest.Matchers.hasSize; import static org.mockito.Mockito.when; @@ -18,11 +18,12 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.api.BackupController; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; @WebMvcTest(BackupController.class) class BackupControllerTest { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java similarity index 84% rename from src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index fdf7c1e..fe201fd 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,7 +9,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; class BackupArchiveServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java similarity index 81% rename from src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index b94912b..422f3ee 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -8,7 +8,8 @@ import org.junit.jupiter.api.Test; -import wellatleastitried.mediagarrd.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.service.BackupScheduleService; class BackupScheduleServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java new file mode 100644 index 0000000..1c580e2 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.service; + +// TODO: Implement full unit testing for db +// ref: https://github.com/wellatleastitried/StreamLine/blob/menu-options/src/test/java/com/streamline/database/DatabaseRunnerTest.java +public class DatabaseServiceTest {} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java similarity index 90% rename from src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java index bec1370..385c71c 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -8,11 +8,12 @@ import java.util.List; import java.util.Locale; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.services.runner.Runner; public final class RealRunnersInteractiveCheck { diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java similarity index 93% rename from src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java rename to src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java index b676ffc..3985680 100644 --- a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.service; +package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -17,11 +17,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; +import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.services.runner.Runner; @Tag("real-runners") class RunnersIntegrationTest { From c90aafe224f828e7be7d876d3becd15210566068 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 19 Sep 2026 16:04:10 -0500 Subject: [PATCH 07/26] Fix renaming --- Dockerfile | 3 +- build.gradle.kts | 2 +- install.sh | 28 +- mise.toml | 2 + .../mediagarrd/MediaGarrd.java | 16 - .../mediagarrd/MediaGarrdProperties.java | 57 ---- .../mediagarrd/MediaGarrdUtilities.java | 173 ----------- .../mediagarrd/ServicesProperties.java | 84 ------ .../mediagarrd/api/BackupController.java | 183 ------------ .../mediagarrd/dto/BackupDto.java | 11 - .../mediagarrd/dto/BackupRunDto.java | 13 - .../mediagarrd/dto/ScheduleUpdateRequest.java | 5 - .../mediagarrd/dto/ServerStatusDto.java | 10 - .../mediagarrd/model/BackupArchive.java | 43 --- .../mediagarrd/model/BackupRunResult.java | 63 ---- .../mediagarrd/model/BackupServiceResult.java | 50 ---- .../mediagarrd/model/FetchedBackupRecord.java | 11 - .../model/FetchedBackupServiceRecord.java | 18 -- .../service/BackupArchiveService.java | 281 ------------------ .../service/BackupOrchestratorService.java | 206 ------------- .../service/BackupScheduleService.java | 63 ---- .../mediagarrd/service/DatabaseService.java | 236 --------------- .../mediagarrd/service/RunnerFactory.java | 114 ------- .../config/AbstractServiceConfig.java | 37 --- .../services/config/CommonServiceConfig.java | 5 - .../config/QBittorrentServiceConfig.java | 16 - .../runner/AbstractLocalCopyRunner.java | 188 ------------ .../services/runner/JellyfinRunner.java | 22 -- .../services/runner/ProwlarrRunner.java | 22 -- .../services/runner/RadarrRunner.java | 22 -- .../mediagarrd/services/runner/Runner.java | 18 -- .../services/runner/SonarrRunner.java | 22 -- .../services/runner/TdarrRunner.java | 22 -- .../MediaGarrdProperties.java | 2 +- .../mediagarrdServer/MediaGarrdUtilities.java | 15 +- .../mediagarrdServer/ServicesProperties.java | 2 +- .../model/FetchedBackupServiceRecord.java | 11 - .../model/FetchedServiceBackupRecord.java | 24 -- .../service/DatabaseService.java | 2 +- .../service/RunnerFactory.java | 2 +- .../config/AbstractServiceConfig.java | 4 - .../config/QBittorrentServiceConfig.java | 2 - .../services/runner/ArrRunner.java} | 18 +- .../services/runner/JellyfinRunner.java | 2 +- .../services/runner/ProwlarrRunner.java | 17 +- .../services/runner/QBittorrentRunner.java | 4 +- .../services/runner/RadarrRunner.java | 17 +- .../services/runner/SonarrRunner.java | 17 +- .../services/runner/TdarrRunner.java | 27 +- src/main/resources/application.yml | 30 +- 50 files changed, 99 insertions(+), 2143 deletions(-) create mode 100644 mise.toml delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/api/BackupController.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java rename src/main/java/wellatleastitried/{mediagarrd/services/runner/QBittorrentRunner.java => mediagarrdServer/services/runner/ArrRunner.java} (51%) diff --git a/Dockerfile b/Dockerfile index c57db07..45dd5a5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,7 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN --mount=type=cache,target=/home/gradle/.gradle \ - gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all FROM eclipse-temurin:21-jre WORKDIR /app diff --git a/build.gradle.kts b/build.gradle.kts index 7273d91..44dc0fd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -31,7 +31,7 @@ tasks.register("realRunnersPromptCheck") { description = "Runs interactive real-environment runner checks (prompts for credentials and endpoints)." group = "verification" classpath = sourceSets["test"].runtimeClasspath - mainClass.set("wellatleastitried.mediagarrd.service.RealRunnersInteractiveCheck") + mainClass.set("wellatleastitried.mediagarrdServer.service.RealRunnersInteractiveCheck") standardInput = System.`in` dependsOn(tasks.testClasses) } diff --git a/install.sh b/install.sh index 85d0458..105358c 100755 --- a/install.sh +++ b/install.sh @@ -72,18 +72,32 @@ EOF_ENV fi } > "$ENV_FILE" - cat > "$SERVER_ENV_FILE" < "$SERVER_ENV_FILE" rm -f "$CLIENT_ENV_FILE" diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..a0f2434 --- /dev/null +++ b/mise.toml @@ -0,0 +1,2 @@ +[tools] +java = "21.0.0" diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java deleted file mode 100644 index 9f32db2..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.scheduling.annotation.EnableScheduling; - -@SpringBootApplication -@EnableScheduling -@EnableConfigurationProperties(MediaGarrdProperties.class) -public class MediaGarrd { - - public static void main(String[] args) { - SpringApplication.run(MediaGarrd.class, args); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java deleted file mode 100644 index 6788f79..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java +++ /dev/null @@ -1,57 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.time.Duration; -import java.util.EnumMap; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -@ConfigurationProperties(prefix = "mediagarrd") -public class MediaGarrdProperties { - - private Duration backupInterval = Duration.ofHours(12); - private String backupRoot = "./data/server/backups"; - private int retentionCount = 10; - private ServicesProperties services = new ServicesProperties(); - - public Duration getBackupInterval() { - return backupInterval; - } - - public void setBackupInterval(Duration backupInterval) { - this.backupInterval = backupInterval; - } - - public String getBackupRoot() { - return backupRoot; - } - - public void setBackupRoot(String backupRoot) { - this.backupRoot = backupRoot; - } - - public int getRetentionCount() { - return retentionCount; - } - - public void setRetentionCount(int retentionCount) { - this.retentionCount = retentionCount; - } - - public ServicesProperties getServices() { - return services; - } - - public void setServices(ServicesProperties services) { - this.services = services; - } - - public EnumMap getServiceConfigs() { - return services.toRuntimeConfigs(); - } - - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java deleted file mode 100644 index c95af0f..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdUtilities.java +++ /dev/null @@ -1,173 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumMap; -import java.util.List; - -//@ADD_NEW_SERVICE -public final class MediaGarrdUtilities { - private MediaGarrdUtilities() {} - - public class Utils { - public static String recordCurrentTime() { - Instant instant = Instant.now(); - return formatTime(instant); - } - - public static String formatTime(Instant instant) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String formattedTime = sdf.format(Date.from(instant)); - return formattedTime; - } - - public static int subtractTime(String startTime, String endTime) { - } - public static long getDurationMs(String startTimeStr, String endTimeStr) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) { - } - } - } - - public class ServiceConstants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - } - - public class DatabaseConstants { - - // Migrations will be added inside of the static block - public record Migration(int version, String sql) {} - public static final List MIGRATIONS; - static { - MIGRATIONS = new ArrayList(); - // Migration versions will start at 2, as the initial tables will be schema v1 - } - - public static final String SQLITE = "jdbc:sqlite:"; - public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; - - // Status used for the overall backup AND the individual service runners - public class Status { - public static final String COMPLETED = "completed"; - public static final String PARTIAL = "partial"; - public static final String FAILED = "failed"; - } - - public static final String CREATE_TABLES = """ - CREATE TABLE IF NOT EXISTS backups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - archive_id TEXT NOT NULL UNIQUE, - start_time DATETIME NOT NULL, - end_time DATETIME, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - checksum TEXT, - filename TEXT, - file_size INTEGER NOT NULL, - file_created_time DATETIME, - error_message TEXT - ); - - CREATE TABLE IF NOT EXISTS backup_services ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - backup_id INTEGER NOT NULL, - service_name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), - start_time DATETIME, - end_time DATETIME, - error_message TEXT, - FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, - UNIQUE (backup_id, service_name) - ); - - CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); - CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); - """; - - public static final String ADD_BACKUP_RECORD = """ - INSERT INTO backups ( - archive_id, - start_time, - end_time, - status, - checksum, - services_completed, - filename, - file_size, - file_created_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); - """; - - public static final String ADD_BACKUP_SERVICE_RECORD = """ - INSERT INTO backup_services ( - backup_id, - service_name, - status, - start_time, - end_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?); - """; - - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - - public static final String DELETE_BACKUP_RECORD_BY_ID = """ - DELETE FROM backups - WHERE archive_id = ?; - """; - - - /* - public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive - ) - public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt - ) - */ - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java deleted file mode 100644 index 953e4d9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java +++ /dev/null @@ -1,84 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.util.EnumMap; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ServicesProperties { - - //@ADD_NEW_SERVICE - private CommonServiceConfig jellyfin; - private CommonServiceConfig radarr; - private CommonServiceConfig sonarr; - private CommonServiceConfig prowlarr; - private CommonServiceConfig tdarr; - private QBittorrentServiceConfig qbittorrent; - - public EnumMap toRuntimeConfigs() { - EnumMap configs = new EnumMap<>(Services.class); - put(configs, Services.JELLYFIN, jellyfin); - put(configs, Services.RADARR, radarr); - put(configs, Services.SONARR, sonarr); - put(configs, Services.PROWLARR, prowlarr); - put(configs, Services.TDARR, tdarr); - put(configs, Services.QBITTORRENT, qbittorrent); - return configs; - } - - private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { - if (config != null) { - configs.put(service, config); - } - } - - public CommonServiceConfig getJellyfin() { - return jellyfin; - } - - public void setJellyfin(CommonServiceConfig jellyfin) { - this.jellyfin = jellyfin; - } - - public CommonServiceConfig getRadarr() { - return radarr; - } - - public void setRadarr(CommonServiceConfig radarr) { - this.radarr = radarr; - } - - public CommonServiceConfig getSonarr() { - return sonarr; - } - - public void setSonarr(CommonServiceConfig sonarr) { - this.sonarr = sonarr; - } - - public CommonServiceConfig getProwlarr() { - return prowlarr; - } - - public void setProwlarr(CommonServiceConfig prowlarr) { - this.prowlarr = prowlarr; - } - - public CommonServiceConfig getTdarr() { - return tdarr; - } - - public void setTdarr(CommonServiceConfig tdarr) { - this.tdarr = tdarr; - } - - public QBittorrentServiceConfig getQbittorrent() { - return qbittorrent; - } - - public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { - this.qbittorrent = qbittorrent; - } - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java deleted file mode 100644 index 0ea1ed6..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java +++ /dev/null @@ -1,183 +0,0 @@ -package wellatleastitried.mediagarrdServer.api; - -import java.io.IOException; -import java.time.Duration; -import java.util.List; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.dto.BackupDto; -import wellatleastitried.mediagarrdServer.dto.BackupRunDto; -import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; -import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.service.BackupArchiveService; -import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RestController -@RequestMapping("/api/v1") -public class BackupController { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupController.class); - - private final BackupArchiveService archiveService; - private final BackupOrchestratorService orchestratorService; - private final MediaGarrdProperties properties; - - public BackupController( - BackupArchiveService archiveService, - BackupOrchestratorService orchestratorService, - MediaGarrdProperties properties - ) { - this.archiveService = archiveService; - this.orchestratorService = orchestratorService; - this.properties = properties; - } - - @GetMapping("/health") - public ServerStatusDto health() { - LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - orchestratorService.getInterval() - ); - } - - @PutMapping("/schedule") - public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { - LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); - Duration updated = orchestratorService.updateInterval(request.backupInterval()); - LOGGER.info("Schedule updated: newInterval={}", updated); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - updated - ); - } - - @GetMapping("/backups") - public List listBackups() { - LOGGER.info("GET /api/v1/backups"); - List backups = archiveService.listArchives().stream().map(this::toDto).toList(); - LOGGER.info("Returning {} backup(s)", backups.size()); - return backups; - } - - @GetMapping("/backups/latest") - public BackupDto latestBackup() { - LOGGER.info("GET /api/v1/backups/latest"); - BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("No backup archives found")); - LOGGER.info("Latest backup: {}", archive.fileName()); - return toDto(archive); - } - - @GetMapping("/backups/{id}") - public BackupDto backupById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}", id); - return archiveService.byId(id) - .map(this::toDto) - .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); - } - - @GetMapping("/backups/{id}/download") - public ResponseEntity downloadById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}/download", id); - BackupArchive archive = archiveService.byId(id) - .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); - return downloadResponse(archive); - } - - @GetMapping("/backups/latest/download") - public ResponseEntity downloadLatest() { - LOGGER.info("GET /api/v1/backups/latest/download"); - BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); - return downloadResponse(archive); - } - - @DeleteMapping("/backups/{id}") - public ResponseEntity deleteBackup(@PathVariable String id) { - LOGGER.info("DELETE /api/v1/backups/{}", id); - boolean deleted = archiveService.deleteById(id); - if (!deleted) { - LOGGER.warn("Delete failed: backup not found: {}", id); - return ResponseEntity.notFound().build(); - } - LOGGER.info("Backup deleted: {}", id); - return ResponseEntity.noContent().build(); - } - - @PostMapping("/backups/run") - public BackupRunDto runBackup() { - LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); - BackupRunResult result = orchestratorService.runBackup(); - var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); - LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", - result.runId(), result.serviceNames(), result.archive().fileName(), - backupDuration); - return new BackupRunDto( - result.runId(), - result.startTime(), - result.endTime(), - result.serviceNames(), - toDto(result.archive()) - ); - } - - private ResponseEntity downloadResponse(BackupArchive archive) { - Resource file = new FileSystemResource(archive.path()); - if (!file.exists()) { - LOGGER.error("Archive file missing on disk: {}", archive.path()); - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); - } - - try { - LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .contentLength(file.contentLength()) - .body(file); - } catch (IOException e) { - LOGGER.error("Failed to read backup file: {}", archive.path(), e); - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); - } - } - - private BackupDto toDto(BackupArchive archive) { - return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); - } - - private ResponseStatusException notFound(String logMessage) { - return notFound(logMessage, logMessage); - } - - private ResponseStatusException notFound(String logMessage, String responseMessage) { - LOGGER.warn(logMessage); - return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java deleted file mode 100644 index 6286b33..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Instant; - -public record BackupDto( - String id, - String fileName, - long sizeBytes, - Instant createdAt -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java deleted file mode 100644 index 00a31f9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Instant; -import java.util.List; - -public record BackupRunDto( - String runId, - String startTime, - String endTime, - List servicesRan, - BackupDto archive -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java deleted file mode 100644 index a3916da..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Duration; - -public record ScheduleUpdateRequest(Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java deleted file mode 100644 index bd2613f..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java +++ /dev/null @@ -1,10 +0,0 @@ -package wellatleastitried.mediagarrdServer.dto; - -import java.time.Duration; - -public record ServerStatusDto( - boolean healthy, - boolean running, - int backupRetentionCount, - Duration backupInterval -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java deleted file mode 100644 index caeef08..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java +++ /dev/null @@ -1,43 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.io.IOException; -import java.math.BigInteger; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.time.Instant; - -public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt -) { - public String generateChecksum() { - Path file = Paths.get(fileName); - try { - byte[] data = Files.readAllBytes(file); - byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); - String checksum = new BigInteger(1, hash).toString(16); - return checksum; - } catch (Exception e) {} - return ""; - } - - public int fileSize() { - Path file = Paths.get(fileName); - - long size; - try { size = Files.size(file); } - catch (IOException iE) { size = 0; } - - if (size > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } - - return (int) size; - - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java deleted file mode 100644 index f46693e..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java +++ /dev/null @@ -1,63 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - -public class BackupRunResult { - private final String runId; - private final String startTime; - private final String endTime; - private final String status; - private final List serviceResults; - private final BackupArchive archive; - private final String errorMessage; - - public BackupRunResult( - String runId, - String startTime, - String endTime, - String status, - List serviceResults, - BackupArchive archive, - String errorMessage - ) { - this.runId = runId; - this.startTime = startTime; - this.endTime = endTime; - this.status = status; - this.serviceResults = serviceResults; - this.archive = archive; - this.errorMessage = errorMessage; - } - - public String runId() { - return runId; - } - - public String status() { - return status; - } - - public String startTime() { - return startTime; - } - - public String endTime() { - return endTime; - } - - public List serviceResults() { - return serviceResults; - } - - public List serviceNames() { - return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); - } - - public BackupArchive archive() { - return archive; - } - - public String errorMessage() { - return errorMessage; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java deleted file mode 100644 index 6877586..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupServiceResult.java +++ /dev/null @@ -1,50 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -public class BackupServiceResult { - private String runId; - private final String status; - private final String startTime; - private final String endTime; - private final String serviceName; - private final String errorMessage; - - public BackupServiceResult( - String runId, - String status, - String startTime, - String endTime, - String serviceName, - String errorMessage - ) { - this.runId = runId; - this.status = status; - this.startTime = startTime; - this.endTime = endTime; - this.serviceName = serviceName; - this.errorMessage = errorMessage; - } - - public void setId(String runId) { - this.runId = runId; - } - - public String runId() { - return runId; - } - - public String status() { - return status; - } - public String startTime() { - return startTime; - } - public String endTime() { - return endTime; - } - public String serviceName() { - return serviceName; - } - public String errorMessage() { - return errorMessage; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java deleted file mode 100644 index 65a4b40..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupRecord.java +++ /dev/null @@ -1,11 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - -public record FetchedBackupRecord( - int id, - String startTime, - String status, - String filename, - List fetchedServices -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java deleted file mode 100644 index 1236bf8..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/FetchedBackupServiceRecord.java +++ /dev/null @@ -1,18 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ -public record FetchedBackupServiceRecord( - String serviceName, - String status, - String startTime -) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java deleted file mode 100644 index a08bcd6..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java +++ /dev/null @@ -1,281 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import jakarta.annotation.PostConstruct; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.model.BackupArchive; - -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Service -public class BackupArchiveService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); - - private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") - .withZone(ZoneOffset.UTC); - private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds - - private final MediaGarrdProperties properties; - private final AtomicReference> cachedArchives = new AtomicReference<>(null); - private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); - - public BackupArchiveService(MediaGarrdProperties properties) { - this.properties = properties; - } - - @PostConstruct - public void cleanupStaleArtifactsOnStartup() { - Path root = rootDirectory(); - Path runsRoot = root.resolve("runs"); - - try { - Files.createDirectories(root); - - try (var stream = Files.list(root)) { - stream - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) - .forEach(path -> { - try { - Files.deleteIfExists(path); - LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); - } - }); - } - - if (Files.exists(runsRoot)) { - try (var stream = Files.list(runsRoot)) { - stream - .filter(Files::isDirectory) - .forEach(runDir -> { - try { - removeRunDirectory(runDir); - LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); - } - }); - } - } - - enforceRetention(); - LOGGER.info("Startup cleanup: retention policy enforced"); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); - } - } - - public Path rootDirectory() { - return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); - } - - public BackupArchive createArchive(Path runDirectory) { - Instant createdAt = Instant.now(); - String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; - Path root = rootDirectory(); - Path archivePath = root.resolve(fileName); - - LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); - try { - Files.createDirectories(root); - zipDirectory(runDirectory, archivePath); - enforceRetention(); - long size = Files.size(archivePath); - LOGGER.info("Archive created: {} ({} bytes)", fileName, size); - - // Invalidate cache after new archive created - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); - - return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); - } catch (IOException e) { - LOGGER.error("Failed to create backup archive: {}", fileName, e); - throw new IllegalStateException("Failed to create backup archive", e); - } - } - - public List listArchives() { - long now = System.currentTimeMillis(); - long lastUpdate = cacheLastUpdatedMs.get(); - - if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { - List cached = cachedArchives.get(); - if (cached != null) { - LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); - return cached; - } - } - - // Cache miss -> rebuild list - Path root = rootDirectory(); - List archives; - if (!Files.exists(root)) { - archives = List.of(); - } else { - try (var stream = Files.list(root)) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .map(this::toArchive) - .toList(); - } catch (IOException e) { - throw new IllegalStateException("Failed to list archives", e); - } - } - - cachedArchives.set(archives); - cacheLastUpdatedMs.set(now); - LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); - return archives; - } - - public Optional latest() { - return listArchives().stream().findFirst(); - } - - public Optional byId(String id) { - return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); - } - - public boolean deleteById(String id) { - Optional archive = byId(id); - if (archive.isEmpty()) { - return false; - } - - try { - Files.deleteIfExists(archive.get().path()); - LOGGER.info("Archive deleted: {}", id); - cacheLastUpdatedMs.set(0); - - cachedArchives.set(null); - return true; - - } catch (IOException e) { - LOGGER.error("Failed to delete archive: {}", id, e); - throw new IllegalStateException("Failed to delete archive " + id, e); - } - } - - public Path createRunDirectory() { - Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); - try { - Files.createDirectories(runDir); - return runDir; - } catch (IOException e) { - throw new IllegalStateException("Failed to create run directory", e); - } - } - - public void removeRunDirectory(Path runDirectory) { - if (runDirectory == null || !Files.exists(runDirectory)) { - return; - } - - try (var walk = Files.walk(runDirectory)) { - walk.sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - throw new IllegalStateException("Failed to clean up run directory", e); - } - }); - } catch (IOException e) { - throw new IllegalStateException("Failed to walk run directory", e); - } - } - - private void enforceRetention() throws IOException { - int retain = Math.max(1, properties.getRetentionCount()); - List archives; - try (var stream = Files.list(rootDirectory())) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .toList(); - } - for (int i = retain; i < archives.size(); i++) { - Path toDelete = archives.get(i); - LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); - Files.deleteIfExists(toDelete); - } - } - - private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { - Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); - try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - ZipOutputStream zipOut = new ZipOutputStream(fileOut); - var paths = Files.walk(sourceDir)) { - - paths.filter(Files::isRegularFile).forEach(path -> { - Path relative = sourceDir.relativize(path); - try { - zipOut.putNextEntry(new ZipEntry(relative.toString())); - try (InputStream in = Files.newInputStream(path)) { - in.transferTo(zipOut); - } - zipOut.closeEntry(); - } catch (IOException e) { - throw new IllegalStateException("Failed to zip file " + path, e); - } - }); - } - Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - } - - private BackupArchive toArchive(Path path) { - String fileName = path.getFileName().toString(); - return new BackupArchive( - toId(fileName), - fileName, - path, - fileSize(path), - lastModified(path) - ); - } - - private String toId(String fileName) { - return fileName.replace(".zip", ""); - } - - private long fileSize(Path path) { - try { - return Files.size(path); - } catch (IOException e) { - return 0L; - } - } - - private Instant lastModified(Path path) { - try { - return Files.getLastModifiedTime(path).toInstant(); - } catch (IOException e) { - return Instant.EPOCH; - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java deleted file mode 100644 index 8dba48a..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java +++ /dev/null @@ -1,206 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - -import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.services.runner.Runner; - -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Service -public class BackupOrchestratorService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); - - private final MediaGarrdProperties properties; - private final RunnerFactory runnerFactory; - private final BackupArchiveService archiveService; - private final BackupScheduleService scheduleService; - private final DatabaseService db; - private final AtomicBoolean running = new AtomicBoolean(false); - private final ExecutorService runnerExecutor = new ThreadPoolExecutor( - 1, // core threads - 6, // max threads - 30, // ttl - TimeUnit.SECONDS, - new LinkedBlockingQueue<>() - ); - - public BackupOrchestratorService( - MediaGarrdProperties properties, - RunnerFactory runnerFactory, - BackupArchiveService archiveService, - BackupScheduleService scheduleService, - DatabaseService db - ) { - this.properties = properties; - this.runnerFactory = runnerFactory; - this.archiveService = archiveService; - this.scheduleService = scheduleService; - this.db = db; - } - - @Scheduled(fixedDelay = 10000) - public void scheduledRun() { - if (running.get()) { - LOGGER.debug("Scheduled check skipped, backup already in progress"); - return; - } - if (!scheduleService.dueNow()) { - return; - } - LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); - try { - runBackup(); - } catch (RuntimeException ex) { - LOGGER.error("Scheduled backup run failed", ex); - } - } - - public BackupRunResult runBackup() { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new IllegalStateException("A backup run is already in progress"); - } - - scheduleService.markRunStarted(); - - Path runDirectory = archiveService.createRunDirectory(); - Instant startedAt = Instant.now(); - List runners = runnerFactory.build(properties.getServiceConfigs()); - List serviceRunResults = new ArrayList<>(); - - LOGGER.info( - "Backup run started: runDir={}, services={}", - runDirectory, - runners.stream().map(Runner::getServiceName).toList()); - - try { - String errorMessage = ""; - List> futures = new ArrayList<>(); - for (Runner runner : runners) { - LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); - futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); - } - - for (Future future : futures) { - try { - BackupServiceResult outcome = future.get(); - serviceRunResults.add(outcome); - if (Status.COMPLETED.equals(outcome.status())) { - LOGGER.info("Runner succeeded: {}", outcome.serviceName()); - } else { - LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Backup run interrupted", ex); - } catch (ExecutionException ex) { - errorMessage.concat(ex.getMessage() + "\n"); - LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); - } - } - - int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); - LOGGER.info( - "All runners finished: succeeded={}/{}", - successfulRunnerCount, - runners.size() - ); - BackupArchive archive = archiveService.createArchive(runDirectory); - for (BackupServiceResult serviceResult : serviceRunResults) { - serviceResult.setId(archive.id()); - } - long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info( - "Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), - archive.sizeBytes(), - durationMs, - serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() - ); - - String status; - if (successfulRunnerCount == runners.size()) { - status = Status.COMPLETED; - } else if (successfulRunnerCount > 0) { - status = Status.PARTIAL; - } else { - status = Status.FAILED; - } - BackupRunResult backupRecord = new BackupRunResult( - archive.id(), - status, - Utils.formatTime(startedAt), - Utils.recordCurrentTime(), - serviceRunResults, - archive, - errorMessage - ); - db.addNewBackupRecord(backupRecord); - return backupRecord; - } finally { - archiveService.removeRunDirectory(runDirectory); - running.set(false); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } - } - - public boolean isRunning() { - return running.get(); - } - - public Duration getInterval() { - return scheduleService.getInterval(); - } - - public Duration updateInterval(Duration duration) { - return scheduleService.updateInterval(duration); - } - - @PreDestroy - public void shutdownRunnerExecutor() { - runnerExecutor.shutdownNow(); - } - - private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { - LOGGER.info("[{}] Runner starting", runner.getServiceName()); - long start = System.currentTimeMillis(); - try { - runner.run(runDirectory); - LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); - } catch (RuntimeException ex) { - LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", - runner.getServiceName(), System.currentTimeMillis() - start, ex); - } - - return new BackupServiceResult( - null, - runner.getRunnerStatus(), - runner.getRunnerStartTime(), - runner.getRunnerEndTime(), - runner.getServiceName(), - runner.getRunnerException() - ); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java deleted file mode 100644 index d3c8637..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java +++ /dev/null @@ -1,63 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; - -@Service -public class BackupScheduleService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); - - private final AtomicReference currentInterval; - private final AtomicReference nextRun; - - public BackupScheduleService(MediaGarrdProperties properties) { - Duration interval = safe(properties.getBackupInterval()); - this.currentInterval = new AtomicReference<>(interval); - this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); - LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); - } - - public Duration getInterval() { - return currentInterval.get(); - } - - public Instant getNextRun() { - return nextRun.get(); - } - - public Duration updateInterval(Duration interval) { - Duration safe = safe(interval); - currentInterval.set(safe); - Instant next = Instant.now().plus(safe); - nextRun.set(next); - LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); - return safe; - } - - public boolean dueNow() { - Instant now = Instant.now(); - Instant current = nextRun.get(); - return !now.isBefore(current); - } - - public void markRunStarted() { - Instant next = Instant.now().plus(currentInterval.get()); - nextRun.set(next); - LOGGER.info("Backup run started: nextScheduledRun={}", next); - } - - private Duration safe(Duration interval) { - if (interval == null || interval.isNegative() || interval.isZero()) { - return Duration.ofHours(12); - } - return interval; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java deleted file mode 100644 index 0339e98..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/DatabaseService.java +++ /dev/null @@ -1,236 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.stereotype.Service; - -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; -import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; - -@Service -public class DatabaseService { - - private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); - - public DatabaseService() { - verifyDatabaseIntegrity(); - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - } catch (Exception e) { - LOGGER.warn("An error occurred while disabling auto-commit on the database", e); - } - } - - private boolean verifyDatabaseIntegrity() { - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - ensureTablesExist(connection); - runNeededMigrations(connection); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while verifying the integrity of the database", sE); - return false; - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); - return false; - } - - return true; - } - - private void ensureTablesExist(Connection connection) throws SQLException { - try (var statement = connection.createStatement()) { - statement.execute(CREATE_TABLES); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("Failed to verify if tables exist in database.", sE); - handleSqlException(connection); - throw sE; - } - } - - private void runNeededMigrations(Connection connection) throws SQLException { - int currentVersion = getDatabaseVersion(connection); - if (currentVersion == -1) return; - - // 0 means it is a brand new database, or it was created before migrations existed - if (currentVersion == 0) { - // Initial tables will be "v1" - currentVersion = 1; - setDatabaseVersion(connection, currentVersion); - } - - for (Migration migration : MIGRATIONS) { - if (currentVersion <= migration.version()) { - continue; - } - - try (var statement = connection.createStatement()) { - statement.execute(migration.sql()); - } catch (SQLException sE) { - LOGGER.warn( - "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", - sE - ); - handleSqlException(connection); - throw sE; - } - - currentVersion = migration.version(); - setDatabaseVersion(connection, currentVersion); - } - - connection.commit(); - } - - private int getDatabaseVersion(Connection connection) { - try (var statement = connection.createStatement(); - var result = statement.executeQuery("PRAGMA user_version")) { - - return result.getInt(1); - } catch (SQLException sE) { - LOGGER.warn("Failed to fetch database version", sE); - return -1; - } - } - - private void setDatabaseVersion(Connection connection, int version) { - - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA user_version = " + version); - } catch (SQLException sE) { - LOGGER.warn("Failed to set new database version", sE); - } - } - - public void addNewBackupRecord(BackupRunResult backupRecord) { - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); - return; - } - - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - addMasterBackup(connection, backupRecord); - addServiceBackups(connection, backupRecord.serviceResults()); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); - } - } - - private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { - try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { - statement.setString(1, backupRecord.runId()); - statement.setString(2, backupRecord.startTime()); - statement.setString(3, backupRecord.endTime()); - statement.setString(4, backupRecord.status()); - statement.setString(5, backupRecord.archive().generateChecksum()); - statement.setString(6, backupRecord.archive().fileName()); - statement.setInt(7, backupRecord.archive().fileSize()); - statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); - statement.setString(9, backupRecord.errorMessage()); - statement.executeUpdate(); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while logging a new backup record", sE); - handleSqlException(connection); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while logging a new backup record", e); - } - } - - private void addServiceBackups(Connection connection, List serviceResults) { - for (BackupServiceResult service : serviceResults) { - try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { - statement.setString(1, service.runId()); - statement.setString(2, service.serviceName()); - statement.setString(3, service.status()); - statement.setString(4, service.startTime()); - statement.setString(5, service.endTime()); - statement.setString(6, service.errorMessage()); - statement.executeUpdate(); - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); - handleSqlException(connection); - } - } - } - - public FetchedBackupRecord fetchLatestBackupRecord() { - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not fetch latest backup record"); - return null; - } - - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - return backupRecord; - } catch (SQLException sE) { - 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); - } - - return null; - } - - private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { - try (var statement = connection.createStatement()) { - var rs = statement.executeQuery(FETCH_LATEST_RECORD); - int id = rs.getInt("id"); - String backupStartTime = rs.getString("start_time"); - String status = rs.getString("status"); - String filename = rs.getString("filename"); - return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); - } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { - try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { - statement.setInt(1, backupRecord.id()); - var rs = statement.executeQuery(); - - while (rs.next()) { - String serviceName = rs.getString("service_name"); - String status = rs.getString("status"); - String startTime = rs.getString("start_time"); - var serviceRecord = new FetchedBackupServiceRecord( - serviceName, - status, - startTime - ); - backupRecord.fetchedServices().add(serviceRecord); - } - return backupRecord; - } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - private void handleSqlException(Connection connection) { - try { - connection.rollback(); - } catch (SQLException rollbackException) { - LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java deleted file mode 100644 index 28e2ecc..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.util.ArrayList; -import java.util.List; -import java.util.EnumMap; - -import org.springframework.stereotype.Component; - -import wellatleastitried.mediagarrdServer.services.config.*; -import wellatleastitried.mediagarrdServer.services.runner.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -@Component -public class RunnerFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); - - public List build(EnumMap serviceConfigMap) { - List runners = new ArrayList<>(); - - for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { - AbstractServiceConfig config = entry.getValue(); - if (config == null || !config.isEnabled()) { - LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); - continue; - } - - validate(entry.getKey(), config); - - Services key = entry.getKey(); - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - runners.add(new JellyfinRunner(config)); - LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); - yield null; - } - case RADARR -> { - runners.add(new RadarrRunner(config)); - LOGGER.info("Registered runner: radarr"); - yield null; - } - case SONARR -> { - runners.add(new SonarrRunner(config)); - LOGGER.info("Registered runner: sonarr"); - yield null; - } - case PROWLARR -> { - runners.add(new ProwlarrRunner(config)); - LOGGER.info("Registered runner: prowlarr"); - yield null; - } - case TDARR -> { - runners.add(new TdarrRunner(config)); - LOGGER.info("Registered runner: tdarr"); - yield null; - } - case QBITTORRENT -> { - runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); - LOGGER.info("Registered runner: qbittorrent"); - yield null; - } - }; - } - - LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); - return runners; - } - - private void validate(Services key, AbstractServiceConfig config) { - boolean supported = SUPPORTED_SERVICES.entrySet() - .stream() - .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); - String serviceName = SUPPORTED_SERVICES.get(key); - if (!supported) { - throw new IllegalArgumentException("Unsupported service configured: " + serviceName); - } - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - requirePath(serviceName, "configPath", config.getConfigPath()); - yield null; - } - case RADARR, SONARR, PROWLARR, TDARR -> { - requirePath(serviceName, "path", config.getPath()); - yield null; - } - case QBITTORRENT -> { - if (!(config instanceof QBittorrentServiceConfig)) { - throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); - } - - QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; - requirePath(serviceName, "path", qbConfig.getPath()); - requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); - yield null; - } - }; - } - - private void requirePath(String serviceName, String fieldName, String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java deleted file mode 100644 index 974c31d..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -//import java.util.List; - -//@ADD_NEW_SERVICE -abstract public class AbstractServiceConfig { - - private boolean enabled; - private String path; - private String configPath; - - //private List configPaths; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getConfigPath() { - return configPath; - } - - public void setConfigPath(String configPath) { - this.configPath = configPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java deleted file mode 100644 index 20482e2..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -// For services that require only one path to backup, this can be used. -// Otherwise, create a new config for a service-specific config. -public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java deleted file mode 100644 index 952667b..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -public class QBittorrentServiceConfig extends AbstractServiceConfig { - - private String savedTorrentsPath; - - // public QBittorrentServiceConfig(ServiceConfig) {} - - public String getSavedTorrentsPath() { - return savedTorrentsPath; - } - - public void setSavedTorrentsPath(String savedTorrentsPath) { - this.savedTorrentsPath = savedTorrentsPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java deleted file mode 100644 index b5d0525..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java +++ /dev/null @@ -1,188 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.List; -import java.util.Locale; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; - -//@ADD_NEW_SERVICE -public abstract class AbstractLocalCopyRunner implements Runner { - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); - - private final String serviceName; - - private String startTime; - private String endTime; - private String status; - private String errorMessage; - - protected AbstractLocalCopyRunner(String serviceName) { - this.serviceName = serviceName; - status = "idle"; - startTime = endTime = errorMessage = ""; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getRunnerStartTime() { - return startTime; - } - - @Override - public String getRunnerEndTime() { - return endTime; - } - - @Override - public String getRunnerStatus() { - return status; - } - - @Override - public String getRunnerException() { - return errorMessage; - } - - @Override - public void run(Path outputDirectory) { - startTime = Utils.recordCurrentTime(); - status = "running"; - Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); - try { - Files.createDirectories(serviceDirectory); - } catch (IOException e) { - errorMessage = "Unable to create output directory for " + serviceName; - status = "failed"; - throw new IllegalStateException("Unable to create output directory for " + serviceName, e); - } - - List specs = copySpecs(); - LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); - int succeeded = 0; - for (CopySpec spec : specs) { - try { - copySpec(spec, serviceDirectory); - succeeded++; - } catch (RuntimeException ex) { - LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); - } - } - LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); - if (succeeded == specs.size()) { - status = "completed"; - } else if (succeeded < specs.size() && succeeded > 0) { - status = "partial"; - } else { - status = "failed"; - } - endTime = Utils.recordCurrentTime(); - } - - protected abstract List copySpecs(); - - protected CopySpec dir(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, true); - } - - protected CopySpec file(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, false); - } - - private void copySpec(CopySpec spec, Path serviceDirectory) { - if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - errorMessage = serviceName + " runner missing source path for " + spec.targetName(); - status = "failed"; - throw new IllegalArgumentException(errorMessage); - } - - Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); - if (!Files.exists(source)) { - errorMessage = serviceName + " source path not found: " + source; - status = "failed"; - throw new IllegalStateException(errorMessage); - } - - Path target = serviceDirectory.resolve(spec.targetName()); - - try { - if (spec.directory()) { - if (!Files.isDirectory(source)) { - throw new IllegalStateException(serviceName + " expected directory path: " + source); - } - copyDirectory(source, target); - } else { - if (!Files.isRegularFile(source)) { - throw new IllegalStateException(serviceName + " expected file path: " + source); - } - Path parent = target.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied file: {}", serviceName, target); - } - } catch (IOException e) { - status = "failed"; - throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); - } - } - - - private void copyDirectory(Path source, Path target) throws IOException { - Files.createDirectories(target); - FileVisitor visitor = new SimpleFileVisitor<>() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(dir); - Path destination = target.resolve(relative); - Files.createDirectories(destination); - LOGGER.debug("[{}] Created dir: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(file); - Path destination = target.resolve(relative); - Path parent = destination.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - - // This will be used on all files including databases. There is a risk of corruption - // when copying a database as it could be in-use, but this is unlikely AND the fact - // that multiple backups will be retained mitigates this risk. This may be changed - // in the future with an OPTION to stop services during backup, but for now it will - // be a basic copy. - Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); - return FileVisitResult.CONTINUE; - } - }; - Files.walkFileTree(source, visitor); - } - - protected record CopySpec(String sourcePath, String targetName, boolean directory) {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java deleted file mode 100644 index 93dae71..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class JellyfinRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public JellyfinRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getConfigPath(), "config")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java deleted file mode 100644 index e7ee6e0..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ProwlarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java deleted file mode 100644 index 259cac4..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class RadarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java deleted file mode 100644 index 095420b..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java +++ /dev/null @@ -1,18 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.nio.file.Path; - -public interface Runner { - - String getServiceName(); - - String getRunnerStartTime(); - - String getRunnerEndTime(); - - String getRunnerStatus(); - - String getRunnerException(); - - void run(Path outputDirectory); -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java deleted file mode 100644 index 8e56234..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class SonarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java deleted file mode 100644 index 7fa6bbb..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class TdarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public TdarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.TDARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 6788f79..b0a3378 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java index c95af0f..c6a3477 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java @@ -1,5 +1,6 @@ package wellatleastitried.mediagarrdServer; +import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; @@ -23,16 +24,14 @@ public static String formatTime(Instant instant) { return formattedTime; } - public static int subtractTime(String startTime, String endTime) { - } public static long getDurationMs(String startTimeStr, String endTimeStr) { try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) { - } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) {} + return -1; } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java index 953e4d9..dc5e758 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java index 1236bf8..2ecc42e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -1,16 +1,5 @@ package wellatleastitried.mediagarrdServer.model; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ public record FetchedBackupServiceRecord( String serviceName, String status, diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java deleted file mode 100644 index ef75413..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedServiceBackupRecord.java +++ /dev/null @@ -1,24 +0,0 @@ -package wellatleastitried.mediagarrdServer.model; - -import java.util.List; - /* - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - */ -public record FetchedBackupServiceRecord( - String runId, - String startTime, - String endTime, - String status, - List serviceResults, - BackupArchive archive, - String errorMessage -) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 0339e98..5493951 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -17,7 +17,7 @@ import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.DatabaseConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.*; @Service public class DatabaseService { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java index 28e2ecc..53c3d94 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -12,7 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java index 974c31d..6a72476 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java @@ -1,7 +1,5 @@ package wellatleastitried.mediagarrdServer.services.config; -//import java.util.List; - //@ADD_NEW_SERVICE abstract public class AbstractServiceConfig { @@ -9,8 +7,6 @@ abstract public class AbstractServiceConfig { private String path; private String configPath; - //private List configPaths; - public boolean isEnabled() { return enabled; } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java index 952667b..a6dbe04 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java @@ -4,8 +4,6 @@ public class QBittorrentServiceConfig extends AbstractServiceConfig { private String savedTorrentsPath; - // public QBittorrentServiceConfig(ServiceConfig) {} - public String getSavedTorrentsPath() { return savedTorrentsPath; } diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java similarity index 51% rename from src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java rename to src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java index 6d5eeb1..966fcde 100644 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java @@ -7,25 +7,23 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +public abstract class ArrRunner extends AbstractLocalCopyRunner { -public class QBittorrentRunner extends AbstractLocalCopyRunner { + private final AbstractServiceConfig config; - private final QBittorrentServiceConfig config; - - public QBittorrentRunner(QBittorrentServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); + public ArrRunner(String service, AbstractServiceConfig config) { + super(service); this.config = config; } @Override protected List copySpecs() { List specs = new ArrayList<>(); - specs.add(dir(config.getPath(), "appdata")); + specs.add(dir(config.getConfigPath(), "config")); - String savedTorrentPath = config.getSavedTorrentsPath(); - if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { - specs.add(dir(savedTorrentPath, "saved-torrents")); + Path data = Path.of(config.getPath()).resolve("data"); + if (Files.isDirectory(data)) { + specs.add(dir(data.toString(), "data")); } Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java index 93dae71..41d65bf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java index e7ee6e0..cff832e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class ProwlarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class ProwlarrRunner extends ArrRunner { public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.PROWLARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java index 6d5eeb1..9b3a79f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { @@ -21,7 +21,7 @@ public QBittorrentRunner(QBittorrentServiceConfig config) { @Override protected List copySpecs() { List specs = new ArrayList<>(); - specs.add(dir(config.getPath(), "appdata")); + specs.add(dir(config.getConfigPath(), "config")); String savedTorrentPath = config.getSavedTorrentsPath(); if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java index 259cac4..ce52ac8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class RadarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class RadarrRunner extends ArrRunner { public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.RADARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java index 8e56234..9c8dc29 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -1,22 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; - import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; - -public class SonarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +public class SonarrRunner extends ArrRunner { public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + super(SUPPORTED_SERVICES.get(Services.SONARR), config); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java index 7fa6bbb..c5a43cf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -1,11 +1,16 @@ package wellatleastitried.mediagarrdServer.services.runner; +import java.util.ArrayList; import java.util.List; +import java.nio.file.Files; +import java.nio.file.Path; import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrd.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +// Tdarr has a different structure than radarr/sonarr/prowlarr, so it will +// use the AbstractLocalCopyRunner instead of ArrRunner. public class TdarrRunner extends AbstractLocalCopyRunner { private final AbstractServiceConfig config; @@ -17,6 +22,24 @@ public TdarrRunner(AbstractServiceConfig config) { @Override protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); + List specs = new ArrayList<>(); + specs.add(dir(config.getConfigPath(), "configs")); + + Path server = Path.of(config.getPath()).resolve("server"); + if (Files.isDirectory(server)) { + specs.add(dir(server.toString(), "server")); + } + + Path logs = Path.of(config.getPath()).resolve("logs"); + if (Files.isDirectory(logs)) { + specs.add(dir(logs.toString(), "logs")); + } + + Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); + if (Files.isRegularFile(compose)) { + specs.add(file(compose.toString(), "docker-compose.yml")); + } + + return specs; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7d47d49..f2a7d0e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -7,21 +7,27 @@ mediagarrd: retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} services: jellyfin: - enabled: ${JELLYFIN_ENABLED:true} - config-path: /srv/sources/jellyfin/config + enabled: ${JELLYFIN_ENABLED:false} + path: ${JELLYFIN_PATH:/srv/sources/jellyfin} + config-path: ${JELLYFIN_CONFIG_PATH:/srv/sources/jellyfin/config} radarr: - enabled: ${RADARR_ENABLED:true} - path: /srv/sources/radarr + enabled: ${RADARR_ENABLED:false} + path: ${RADARR_PATH:/srv/sources/radarr} + config-path: ${RADARR_CONFIG_PATH:/srv/sources/radarr/config} sonarr: - enabled: ${SONARR_ENABLED:true} - path: /srv/sources/sonarr + enabled: ${SONARR_ENABLED:false} + path: ${SONARR_PATH:/srv/sources/sonarr} + config-path: ${SONARR_CONFIG_PATH:/srv/sources/sonarr/config} prowlarr: - enabled: ${PROWLARR_ENABLED:true} - path: /srv/sources/prowlarr + enabled: ${PROWLARR_ENABLED:false} + path: ${PROWLARR_PATH:/srv/sources/prowlarr} + config-path: ${PROWLARR_CONFIG_PATH:/srv/sources/prowlarr/config} tdarr: - enabled: ${TDARR_ENABLED:true} - path: /srv/sources/tdarr + enabled: ${TDARR_ENABLED:false} + path: ${TDARR_PATH:/srv/sources/tdarr} + config-path: ${TDARR_CONFIG_PATH:/srv/sources/tdarr/configs} qbittorrent: - enabled: ${QBITTORRENT_ENABLED:true} - path: /srv/sources/qbittorrent + enabled: ${QBITTORRENT_ENABLED:false} + path: ${QBITTORRENT_PATH:/srv/sources/qbittorrent} + config-path: ${QBITTORRENT_CONFIG_PATH:/srv/sources/qbittorrent/config} saved-torrents-path: ${QBITTORRENT_SAVED_TORRENTS_PATH} From dc255ea147aaaeec7500c170921186917f83cdca Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Tue, 22 Sep 2026 13:24:02 -0500 Subject: [PATCH 08/26] Add testing for new database service. The basebones database and tests have been implemented, just need a little cleanup. --- .gitattributes | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 4 +- .github/ISSUE_TEMPLATE/feature_request.md | 56 ++++-- .github/ISSUE_TEMPLATE/new_service_request.md | 6 +- .gitignore | 1 + CHANGELOG | 1 + CONTRIBUTING.md | 2 +- Makefile | 4 + README.md | 2 +- build.gradle.kts | 1 + install.sh | 4 +- scripts/install-util.sh | 8 +- .../MediaGarrdProperties.java | 2 +- .../mediagarrdServer/MediaGarrdUtilities.java | 172 ------------------ .../mediagarrdServer/ServicesProperties.java | 2 +- .../api/BackupController.java | 5 +- .../mediagarrdServer/dto/BackupRunDto.java | 1 - .../mediagarrdServer/model/BackupArchive.java | 8 +- .../model/FetchedBackupRecord.java | 7 +- .../model/FetchedBackupServiceRecord.java | 4 +- .../service/BackupOrchestratorService.java | 21 ++- .../service/BackupScheduleService.java | 1 + .../service/DatabaseService.java | 117 +++++++++--- .../service/RunnerFactory.java | 2 +- .../runner/AbstractLocalCopyRunner.java | 6 +- .../services/runner/JellyfinRunner.java | 2 +- .../services/runner/ProwlarrRunner.java | 2 +- .../services/runner/QBittorrentRunner.java | 2 +- .../services/runner/RadarrRunner.java | 2 +- .../services/runner/SonarrRunner.java | 2 +- .../services/runner/TdarrRunner.java | 2 +- .../utilities/DatabaseUtils.java | 100 ++++++++++ .../utilities/MediaGarrdUtils.java | 33 ++++ .../utilities/ServiceConstants.java | 28 +++ .../MediaGarrdPropertiesBindingTest.java | 3 +- .../api/BackupControllerTest.java | 10 +- .../service/BackupArchiveServiceTest.java | 1 - .../service/BackupScheduleServiceTest.java | 1 - .../service/DatabaseServiceTest.java | 160 +++++++++++++++- .../service/RealRunnersInteractiveCheck.java | 3 +- .../service/RunnersIntegrationTest.java | 3 +- 41 files changed, 514 insertions(+), 278 deletions(-) create mode 100644 Makefile delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java diff --git a/.gitattributes b/.gitattributes index 93c61a2..e681a03 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ /gradlew text eol=lf *.bat text eol=crlf *.jar binary +src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java linguist-language=SQL diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 9b52043..3ed2bbd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -2,9 +2,7 @@ name: Bug report about: Create a report to help us improve title: "[BUG]: " -labels: bug, needs-triage -assignees: '' -type: Bug +labels: [ 'Type: Bug', 'Status: Needs Triage' ] --- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index e17b1ba..7e6c25b 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,21 +1,39 @@ ---- -name: Feature request -about: Suggest an idea for this project +name: Feature Request +description: Suggest an idea for this project title: "[FEAT]: " -labels: feature, needs-triage -assignees: '' -type: Feature +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/new_service_request.md b/.github/ISSUE_TEMPLATE/new_service_request.md index 836b1b7..aa56e07 100644 --- a/.github/ISSUE_TEMPLATE/new_service_request.md +++ b/.github/ISSUE_TEMPLATE/new_service_request.md @@ -1,10 +1,8 @@ --- name: New service request about: Request a new service to be support by MediaGarrd -title: "[ADD-SERVICE]: " -labels: add-service, needs-triage -assignees: '' -type: Feature +title: "[SERVICE]: " +labels: [ 'Type: Add Service', 'Status: Needs Triage' ] --- diff --git a/.gitignore b/.gitignore index 6703b86..39f57c5 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ gradle/ # Prod artifacts secrets/ +dockerenv/ .env data/ docker-compose.yml diff --git a/CHANGELOG b/CHANGELOG index 1324fb4..858cd74 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ ## TBD - Add database for keeping records of backups - Add issue templates +- Removed auto-routing to appdata/ within archive to retain actual paths of configs ## 9-16-26 - Adding more detailed logging for service runners diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1092eb6..c0b5e14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ ## Submitting Issues Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the template that best fits the issue. -The `needs-triage` label will automatically be applied. Once this issue has been reviewed/approved, the `approved` label will be added and Pull Requests can be opened referencing this issue. +The `Status: Needs Triage` label will automatically be applied. Once this issue has been reviewed/approved, the `Status: Approved` label will be added and Pull Requests can be opened referencing this issue. ## Pull Requests Pull requests should only be opened for issues that have the `approved` label. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..42be21a --- /dev/null +++ b/Makefile @@ -0,0 +1,4 @@ +.PHONY: test + +test: + ./gradlew test --warning-mode all diff --git a/README.md b/README.md index b8a331d..1e5daba 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This is the official server for [MediaGarrd](https://github.com/MediaGarrd/Media ```bash git clone --depth 1 https://github.com/MediaGarrd/Server.git cd Server -./install.sh # Drops .env, client.env, and docker-compose.yml +./install.sh # Drops .env, dockerenv/server.env, and docker-compose.yml docker compose up --build -d ``` diff --git a/build.gradle.kts b/build.gradle.kts index 44dc0fd..9bec437 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -10,6 +10,7 @@ repositories { dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.xerial:sqlite-jdbc:3.44.0.0") testRuntimeOnly("org.junit.platform:junit-platform-launcher") implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter") diff --git a/install.sh b/install.sh index 105358c..09027d2 100755 --- a/install.sh +++ b/install.sh @@ -110,7 +110,7 @@ services: dockerfile: Dockerfile container_name: mediagarrd-server env_file: - - ./secrets/server.env + - ./dockerenv/server.env ports: - "$server_port:$server_port" volumes: @@ -148,6 +148,6 @@ echo "Created: $SERVER_ENV_FILE" echo "" echo "Next steps:" echo "1. Review .env" -echo "2. Review secrets/server.env" +echo "2. Review dockerenv/server.env" echo "3. Review docker-compose.yml" echo "4. Start services with: docker compose up --build -d" diff --git a/scripts/install-util.sh b/scripts/install-util.sh index 75062bf..4e881f7 100644 --- a/scripts/install-util.sh +++ b/scripts/install-util.sh @@ -1,11 +1,11 @@ #!/usr/bin/env bash ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" +DOCKERENV_DIR="$ROOT_DIR/dockerenv" COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" +SERVER_ENV_FILE="$DOCKERENV_DIR/server.env" +CLIENT_ENV_FILE="$DOCKERENV_DIR/client.env" PORT_DEFAULT="38471" INTERVAL_DEFAULT="PT12H" @@ -15,7 +15,7 @@ BACKUP_RETENTION_DEFAULT="10" MNT_DIR="/mnt" DEFAULT_APPDATA_DIR="$MNT_DIR/appdata" -mkdir -p "$SECRETS_DIR" +mkdir -p "$DOCKERENV_DIR" prompt() { local var_name="$1" diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index b0a3378..258644e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java deleted file mode 100644 index c6a3477..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdUtilities.java +++ /dev/null @@ -1,172 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumMap; -import java.util.List; - -//@ADD_NEW_SERVICE -public final class MediaGarrdUtilities { - private MediaGarrdUtilities() {} - - public class Utils { - public static String recordCurrentTime() { - Instant instant = Instant.now(); - return formatTime(instant); - } - - public static String formatTime(Instant instant) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String formattedTime = sdf.format(Date.from(instant)); - return formattedTime; - } - - public static long getDurationMs(String startTimeStr, String endTimeStr) { - try { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date startDate = sdf.parse(startTimeStr); - Date endDate = sdf.parse(endTimeStr); - return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) {} - return -1; - } - } - - public class ServiceConstants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - } - - public class DatabaseConstants { - - // Migrations will be added inside of the static block - public record Migration(int version, String sql) {} - public static final List MIGRATIONS; - static { - MIGRATIONS = new ArrayList(); - // Migration versions will start at 2, as the initial tables will be schema v1 - } - - public static final String SQLITE = "jdbc:sqlite:"; - public static final String databaseUrl = "/var/lib/mediagarrd/mediagarrd.db"; - - // Status used for the overall backup AND the individual service runners - public class Status { - public static final String COMPLETED = "completed"; - public static final String PARTIAL = "partial"; - public static final String FAILED = "failed"; - } - - public static final String CREATE_TABLES = """ - CREATE TABLE IF NOT EXISTS backups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - archive_id TEXT NOT NULL UNIQUE, - start_time DATETIME NOT NULL, - end_time DATETIME, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - checksum TEXT, - filename TEXT, - file_size INTEGER NOT NULL, - file_created_time DATETIME, - error_message TEXT - ); - - CREATE TABLE IF NOT EXISTS backup_services ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - backup_id INTEGER NOT NULL, - service_name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed')), - start_time DATETIME, - end_time DATETIME, - error_message TEXT, - FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, - UNIQUE (backup_id, service_name) - ); - - CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); - CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); - """; - - public static final String ADD_BACKUP_RECORD = """ - INSERT INTO backups ( - archive_id, - start_time, - end_time, - status, - checksum, - services_completed, - filename, - file_size, - file_created_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); - """; - - public static final String ADD_BACKUP_SERVICE_RECORD = """ - INSERT INTO backup_services ( - backup_id, - service_name, - status, - start_time, - end_time, - error_message - ) VALUES (?, ?, ?, ?, ?, ?); - """; - - public static final String FETCH_LATEST_RECORD = """ - SELECT id, start_time, status, filename FROM backups - ORDER BY start_time DESC - LIMIT 1; - """; - - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ - SELECT service_name, status, start_time FROM backup_services - WHERE backup_id = ?; - """; - - public static final String DELETE_BACKUP_RECORD_BY_ID = """ - DELETE FROM backups - WHERE archive_id = ?; - """; - - - /* - public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive - ) - public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt - ) - */ - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java index dc5e758..0336618 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 0ea1ed6..3ef0b03 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -21,7 +21,6 @@ import org.springframework.web.server.ResponseStatusException; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; import wellatleastitried.mediagarrdServer.dto.BackupDto; import wellatleastitried.mediagarrdServer.dto.BackupRunDto; import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; @@ -34,6 +33,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; + @RestController @RequestMapping("/api/v1") public class BackupController { @@ -135,7 +136,7 @@ public ResponseEntity deleteBackup(@PathVariable String id) { public BackupRunDto runBackup() { LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); BackupRunResult result = orchestratorService.runBackup(); - var backupDuration = Utils.getDurationMs(result.startTime(), result.endTime()); + var backupDuration = getDurationMs(result.startTime(), result.endTime()); LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", result.runId(), result.serviceNames(), result.archive().fileName(), backupDuration); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java index 00a31f9..7992b8c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -1,6 +1,5 @@ package wellatleastitried.mediagarrdServer.dto; -import java.time.Instant; import java.util.List; public record BackupRunDto( diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index caeef08..3ff5942 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -4,7 +4,6 @@ import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.MessageDigest; import java.time.Instant; @@ -16,9 +15,8 @@ public record BackupArchive( Instant createdAt ) { public String generateChecksum() { - Path file = Paths.get(fileName); try { - byte[] data = Files.readAllBytes(file); + byte[] data = Files.readAllBytes(path); byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); String checksum = new BigInteger(1, hash).toString(16); return checksum; @@ -27,10 +25,8 @@ public String generateChecksum() { } public int fileSize() { - Path file = Paths.get(fileName); - long size; - try { size = Files.size(file); } + try { size = Files.size(path); } catch (IOException iE) { size = 0; } if (size > Integer.MAX_VALUE) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java index 65a4b40..cf67c10 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java @@ -4,8 +4,11 @@ public record FetchedBackupRecord( int id, + String archiveId, String startTime, + String endTime, String status, - String filename, - List fetchedServices + String filePath, + List fetchedServices, + String errorMessage ) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java index 2ecc42e..e823982 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -3,5 +3,7 @@ public record FetchedBackupServiceRecord( String serviceName, String status, - String startTime + String startTime, + String endTime, + String errorMessage ) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 8dba48a..f8580e8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -15,8 +15,6 @@ import jakarta.annotation.PreDestroy; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.Status; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; @@ -27,6 +25,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status.*; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; + @Service public class BackupOrchestratorService { @@ -60,6 +61,8 @@ public BackupOrchestratorService( this.db = db; } + // TODO: Double check what this is + @Scheduled(fixedDelay = 10000) public void scheduledRun() { if (running.get()) { @@ -107,7 +110,7 @@ public BackupRunResult runBackup() { try { BackupServiceResult outcome = future.get(); serviceRunResults.add(outcome); - if (Status.COMPLETED.equals(outcome.status())) { + if (COMPLETED.equals(outcome.status())) { LOGGER.info("Runner succeeded: {}", outcome.serviceName()); } else { LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); @@ -121,7 +124,7 @@ public BackupRunResult runBackup() { } } - int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> Status.COMPLETED.equals(r.status())).count(); + int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> COMPLETED.equals(r.status())).count(); LOGGER.info( "All runners finished: succeeded={}/{}", successfulRunnerCount, @@ -142,17 +145,17 @@ public BackupRunResult runBackup() { String status; if (successfulRunnerCount == runners.size()) { - status = Status.COMPLETED; + status = COMPLETED; } else if (successfulRunnerCount > 0) { - status = Status.PARTIAL; + status = PARTIAL; } else { - status = Status.FAILED; + status = FAILED; } BackupRunResult backupRecord = new BackupRunResult( archive.id(), status, - Utils.formatTime(startedAt), - Utils.recordCurrentTime(), + formatTime(startedAt), + recordCurrentTime(), serviceRunResults, archive, errorMessage diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index d3c8637..f9be79f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -56,6 +56,7 @@ public void markRunStarted() { private Duration safe(Duration interval) { if (interval == null || interval.isNegative() || interval.isZero()) { + // Default to 12 hours if the provided interval is invalid return Duration.ofHours(12); } return interval; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 5493951..7b16a29 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -2,6 +2,7 @@ import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -11,13 +12,15 @@ import org.springframework.stereotype.Service; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.DatabaseConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; +import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; + +// TODO: Add support for hosting the configuration in a table @Service public class DatabaseService { @@ -26,15 +29,14 @@ public class DatabaseService { public DatabaseService() { verifyDatabaseIntegrity(); - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { - connection.setAutoCommit(false); - } catch (Exception e) { - LOGGER.warn("An error occurred while disabling auto-commit on the database", e); - } } - private boolean verifyDatabaseIntegrity() { - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + protected Connection getConnection() throws SQLException { + return DriverManager.getConnection(SQLITE + databasePath); + } + + protected boolean verifyDatabaseIntegrity() { + try (var connection = getConnection()) { connection.setAutoCommit(false); ensureTablesExist(connection); runNeededMigrations(connection); @@ -51,7 +53,13 @@ private boolean verifyDatabaseIntegrity() { private void ensureTablesExist(Connection connection) throws SQLException { try (var statement = connection.createStatement()) { - statement.execute(CREATE_TABLES); + for (String sql : CREATE_TABLES.split(";")) { + String CREATE_STATEMENT = sql.trim(); + if (!CREATE_STATEMENT.isEmpty()) { + statement.execute(CREATE_STATEMENT); + } + } + connection.commit(); } catch (SQLException sE) { LOGGER.warn("Failed to verify if tables exist in database.", sE); @@ -94,7 +102,7 @@ private void runNeededMigrations(Connection connection) throws SQLException { connection.commit(); } - private int getDatabaseVersion(Connection connection) { + protected int getDatabaseVersion(Connection connection) { try (var statement = connection.createStatement(); var result = statement.executeQuery("PRAGMA user_version")) { @@ -105,8 +113,7 @@ private int getDatabaseVersion(Connection connection) { } } - private void setDatabaseVersion(Connection connection, int version) { - + protected void setDatabaseVersion(Connection connection, int version) { try (var statement = connection.createStatement()) { statement.execute("PRAGMA user_version = " + version); } catch (SQLException sE) { @@ -120,7 +127,7 @@ public void addNewBackupRecord(BackupRunResult backupRecord) { return; } - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + try (var connection = getConnection()) { connection.setAutoCommit(false); addMasterBackup(connection, backupRecord); addServiceBackups(connection, backupRecord.serviceResults()); @@ -138,9 +145,9 @@ private void addMasterBackup(Connection connection, BackupRunResult backupRecord statement.setString(3, backupRecord.endTime()); statement.setString(4, backupRecord.status()); statement.setString(5, backupRecord.archive().generateChecksum()); - statement.setString(6, backupRecord.archive().fileName()); + statement.setString(6, backupRecord.archive().path().toString()); statement.setInt(7, backupRecord.archive().fileSize()); - statement.setString(8, Utils.formatTime(backupRecord.archive().createdAt())); + statement.setString(8, formatTime(backupRecord.archive().createdAt())); statement.setString(9, backupRecord.errorMessage()); statement.executeUpdate(); connection.commit(); @@ -170,14 +177,64 @@ private void addServiceBackups(Connection connection, List } } + private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + + int id = rs.getInt("id"); + String archiveId = rs.getString("archive_id"); + String backupStartTime = rs.getString("start_time"); + String backupEndTime = rs.getString("end_time"); + String status = rs.getString("status"); + String filePath = rs.getString("file_path"); + String errorMessage = rs.getString("error_message"); + + return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); + } + + public FetchedBackupRecord fetchBackupById(String archiveId) { + if (!verifyDatabaseIntegrity()) { + LOGGER.warn("Could not fetch backup record by archive_id (" + archiveId + ")"); + return null; + } + + try (var connection = getConnection()) { + FetchedBackupRecord backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord == null) return null; + + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + return backupRecord; + } catch (SQLException sE) { + 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); + } + + return null; + } + + private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { + try (var statement = connection.prepareStatement(FETCH_RECORD_BY_ID)) { + statement.setString(1, archiveId); + var rs = statement.executeQuery(); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException sE) { + LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", sE); + return null; + } + } + public FetchedBackupRecord fetchLatestBackupRecord() { if (!verifyDatabaseIntegrity()) { LOGGER.warn("Could not fetch latest backup record"); return null; } - try (var connection = DriverManager.getConnection(SQLITE + databaseUrl)) { + try (var connection = getConnection()) { FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord == null) return null; + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); return backupRecord; } catch (SQLException sE) { @@ -192,11 +249,7 @@ public FetchedBackupRecord fetchLatestBackupRecord() { private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { try (var statement = connection.createStatement()) { var rs = statement.executeQuery(FETCH_LATEST_RECORD); - int id = rs.getInt("id"); - String backupStartTime = rs.getString("start_time"); - String status = rs.getString("status"); - String filename = rs.getString("filename"); - return new FetchedBackupRecord(id, backupStartTime, status, filename, new ArrayList()); + return buildFetchedBackupRecordFromQueryResult(rs); } catch (SQLException sE) { LOGGER.warn("Error fetching latest backup record", sE); return null; @@ -212,16 +265,20 @@ private FetchedBackupRecord populateFetchedRecordWithServices(Connection connect String serviceName = rs.getString("service_name"); String status = rs.getString("status"); String startTime = rs.getString("start_time"); + String endTime = rs.getString("end_time"); + String errorMessage = rs.getString("error_message"); var serviceRecord = new FetchedBackupServiceRecord( serviceName, status, - startTime + startTime, + endTime, + errorMessage ); backupRecord.fetchedServices().add(serviceRecord); } return backupRecord; } catch (SQLException sE) { - LOGGER.warn("Error fetching latest backup record", sE); + LOGGER.warn("Error populating backup record with related services", sE); return null; } } @@ -233,4 +290,16 @@ private void handleSqlException(Connection connection) { LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); } } + + public void deleteBackupRecordById(String archiveId) { + try (var connection = getConnection(); + var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { + statement.setString(1, archiveId); + statement.executeUpdate(); + } catch (SQLException sE) { + LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); + } + } + + // TODO: Add support to fetch all records for a report on history } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java index 53c3d94..527ca62 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -12,7 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java index b5d0525..48a27a8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java @@ -14,7 +14,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.Utils; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; //@ADD_NEW_SERVICE public abstract class AbstractLocalCopyRunner implements Runner { @@ -61,7 +61,7 @@ public String getRunnerException() { @Override public void run(Path outputDirectory) { - startTime = Utils.recordCurrentTime(); + startTime = recordCurrentTime(); status = "running"; Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); try { @@ -91,7 +91,7 @@ public void run(Path outputDirectory) { } else { status = "failed"; } - endTime = Utils.recordCurrentTime(); + endTime = recordCurrentTime(); } protected abstract List copySpecs(); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java index 41d65bf..8dadf39 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -4,7 +4,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java index cff832e..c9bb625 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class ProwlarrRunner extends ArrRunner { public ProwlarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java index 9b3a79f..a326e0a 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class QBittorrentRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java index ce52ac8..0675a97 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class RadarrRunner extends ArrRunner { public RadarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java index 9c8dc29..1da70d3 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -2,7 +2,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; public class SonarrRunner extends ArrRunner { public SonarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java index c5a43cf..b28be73 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -7,7 +7,7 @@ import wellatleastitried.mediagarrdServer.services.config.*; -import static wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; // Tdarr has a different structure than radarr/sonarr/prowlarr, so it will // use the AbstractLocalCopyRunner instead of ArrRunner. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java new file mode 100644 index 0000000..13e87e6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java @@ -0,0 +1,100 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.util.ArrayList; +import java.util.List; + +public class DatabaseUtils { + + public record Migration(int version, String sql) {} + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databasePath = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + file_path TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + file_path, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_RECORD_BY_ID = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + WHERE archive_id = ?; + """; + + public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + SELECT service_name, status, start_time, end_time, error_message FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java new file mode 100644 index 0000000..19043a9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java @@ -0,0 +1,33 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; + +public class MediaGarrdUtils { + + private MediaGarrdUtils() {} + + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException pE) {} + return -1; + } +} + diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java new file mode 100644 index 0000000..07fcf4f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java @@ -0,0 +1,28 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.util.EnumMap; + +//@ADD_NEW_SERVICE +public class ServiceConstants { + + public enum Services { + JELLYFIN, + RADARR, + SONARR, + PROWLARR, + TDARR, + QBITTORRENT + } + + public static final EnumMap SUPPORTED_SERVICES; + + static { + SUPPORTED_SERVICES = new EnumMap<>(Services.class); + SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); + SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); + SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); + SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); + SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); + SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 748ee76..29cbfd5 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -9,8 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 2cd1c0e..6e66556 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -19,7 +19,6 @@ import org.springframework.test.web.servlet.MockMvc; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.api.BackupController; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; @@ -52,6 +51,7 @@ void healthReturnsServerStatus() throws Exception { @Test void runAndListBackups() throws Exception { + String errorMessage = "testErrorMessage"; BackupArchive archive = new BackupArchive( "backup-1", "backup-1.zip", @@ -61,10 +61,12 @@ void runAndListBackups() throws Exception { ); BackupRunResult result = new BackupRunResult( "run-1", - Instant.parse("2026-01-01T00:00:00Z"), - Instant.parse("2026-01-01T00:01:00Z"), + "2026-01-01T00:00:00Z", + "2026-01-01T00:01:00Z", + "testStatus", List.of(), - archive + archive, + errorMessage ); when(orchestratorService.runBackup()).thenReturn(result); when(archiveService.listArchives()).thenReturn(List.of(archive)); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index fe201fd..1b4de04 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.service.BackupArchiveService; class BackupArchiveServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index 422f3ee..f54453e 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.Test; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.service.BackupScheduleService; class BackupScheduleServiceTest { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java index 1c580e2..d5d7991 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -1,5 +1,159 @@ package wellatleastitried.mediagarrdServer.service; -// TODO: Implement full unit testing for db -// ref: https://github.com/wellatleastitried/StreamLine/blob/menu-options/src/test/java/com/streamline/database/DatabaseRunnerTest.java -public class DatabaseServiceTest {} +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +import static org.junit.jupiter.api.Assertions.*; + +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; + +public class DatabaseServiceTest { + + String testBackupId = "testId"; + String testStartTime = "testStartTime"; + String testEndTime = "testEndTime"; + String testFilename = "testFilename"; + Path testFilePath = Paths.get("testFilePath"); + long testFileSize = 1337; + Instant testInstant = Instant.now(); + BackupArchive testArchive = new BackupArchive(testBackupId, testFilename, testFilePath, testFileSize, testInstant); + String testErrorMessage = "testErrorMessage"; + + String serviceOneStartTime = "testStartTime1"; + String serviceOneEndTime = "testEndTime1"; + String serviceTwoStartTime = "testStartTime2"; + String serviceTwoEndTime = "testEndTime2"; + String serviceThreeStartTime = "testStartTime3"; + String serviceThreeEndTime = null; + + private DatabaseService databaseService; + private Connection testConnection; + + private Connection wrapUncloseable(Connection real) { + return (Connection) Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] { Connection.class }, + (proxy, method, args) -> { + // Need to "swallor" null so the in-memory database survives + if ("close".equals(method.getName())) { + return null; + } + try { + return method.invoke(real, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + ); + } + + @BeforeEach + public void setUp() throws SQLException { + testConnection = DriverManager.getConnection("jdbc:sqlite::memory:"); + Connection uncloseable = wrapUncloseable(testConnection); + databaseService = new DatabaseService() { + @Override + protected Connection getConnection() throws SQLException { + return uncloseable; + } + }; + } + + @AfterEach + public void tearDown() throws SQLException { + testConnection.close(); + } + + @Test + public void testDatabaseIntegrity() { + boolean hasIntegrity = databaseService.verifyDatabaseIntegrity(); + assertEquals(true, hasIntegrity); + } + + @Test + public void testConnection() throws SQLException { + try (var connection = databaseService.getConnection()) { + assertEquals(true, connection.isValid(10)); + } catch (SQLException sE) { fail(sE); } + } + + private BackupRunResult buildTestBackupRunResult() { + List testServiceResults = List.of( + new BackupServiceResult(testBackupId, Status.COMPLETED, serviceOneStartTime, serviceOneEndTime, SUPPORTED_SERVICES.get(Services.JELLYFIN), testErrorMessage), + new BackupServiceResult(testBackupId, Status.PARTIAL, serviceTwoStartTime, serviceTwoEndTime, SUPPORTED_SERVICES.get(Services.SONARR), testErrorMessage), + new BackupServiceResult(testBackupId, Status.FAILED, serviceThreeStartTime, serviceThreeEndTime, SUPPORTED_SERVICES.get(Services.QBITTORRENT), testErrorMessage) + ); + return new BackupRunResult( + testBackupId, + testStartTime, + testEndTime, + Status.COMPLETED, + testServiceResults, + testArchive, + testErrorMessage + ); + } + + @Test + public void testAddingBackupRecord() { + BackupRunResult testBackupRecord = buildTestBackupRunResult(); + + databaseService.addNewBackupRecord(testBackupRecord); + + FetchedBackupRecord testRecord = databaseService.fetchBackupById(testArchive.id()); + + assertEquals(testBackupId, testRecord.archiveId()); + assertEquals(testFilePath.toString(), testRecord.filePath()); + assertEquals(testStartTime, testRecord.startTime()); + assertEquals(testEndTime, testRecord.endTime()); + for (FetchedBackupServiceRecord testServiceResult : testRecord.fetchedServices()) { + if (SUPPORTED_SERVICES.get(Services.JELLYFIN).equals(testServiceResult.serviceName())) { + assertEquals(serviceOneStartTime, testServiceResult.startTime()); + assertEquals(serviceOneEndTime, testServiceResult.endTime()); + assertEquals(Status.COMPLETED, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + + } else if (SUPPORTED_SERVICES.get(Services.SONARR).equals(testServiceResult.serviceName())) { + assertEquals(serviceTwoStartTime, testServiceResult.startTime()); + assertEquals(serviceTwoEndTime, testServiceResult.endTime()); + assertEquals(Status.PARTIAL, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + } else if (SUPPORTED_SERVICES.get(Services.QBITTORRENT).equals(testServiceResult.serviceName())) { + assertEquals(serviceThreeStartTime, testServiceResult.startTime()); + assertEquals(serviceThreeEndTime, testServiceResult.endTime()); + assertEquals(Status.FAILED, testServiceResult.status()); + assertEquals(testErrorMessage, testServiceResult.errorMessage()); + } else { + fail("UNREACHABLE"); + } + } + } + + @Test + public void testDeletingBackupRecord() { + BackupRunResult testBackupRecord = buildTestBackupRunResult(); + databaseService.addNewBackupRecord(testBackupRecord); + databaseService.deleteBackupRecordById(testBackupRecord.runId()); + FetchedBackupRecord testFetchedBackupRecord = databaseService.fetchBackupById(testBackupRecord.runId()); + + assertEquals(null, testFetchedBackupRecord); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java index 385c71c..6eb37c3 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java @@ -8,8 +8,7 @@ import java.util.List; import java.util.Locale; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; -import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java index 3985680..a895099 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java @@ -17,8 +17,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrdServer.MediaGarrdUtilities.ServiceConstants.Services; -import wellatleastitried.mediagarrdServer.service.RunnerFactory; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; From 83f201b46063ebaaadb299af0a9ddfad3db9a865 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 20:01:05 -0500 Subject: [PATCH 09/26] Finish logging fixes, finish database implementation cleanup. --- CHANGELOG | 1 + CONTRIBUTING.md | 2 +- docker-compose.example.yml | 3 +-- ref/SUPPORTED_SERVICES | 2 -- .../mediagarrdServer/service/BackupOrchestratorService.java | 4 +--- .../mediagarrdServer/service/DatabaseService.java | 4 ---- 6 files changed, 4 insertions(+), 12 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 858cd74..e224003 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ ## TBD - Add database for keeping records of backups +- Add thorough testing of database functionality - Add issue templates - Removed auto-routing to appdata/ within archive to retain actual paths of configs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0b5e14..1a83d1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the temp The `Status: Needs Triage` label will automatically be applied. Once this issue has been reviewed/approved, the `Status: Approved` label will be added and Pull Requests can be opened referencing this issue. ## Pull Requests -Pull requests should only be opened for issues that have the `approved` label. +Pull requests should only be opened for issues that have the `Status: Approved` label. ## AI Usage See [AGENTS.md](https://github.com/MediaGarrd/Server/blob/main/AGENTS.md) for a more in-depth overview of the way AI is permitted in code submissions. If a signature is not present on a commit that even *appears* to be generated by an LLM, the PR will be closed. This is strictly for the continued maintainability of the project. diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9f93f22..a1c4c39 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -1,4 +1,3 @@ -# Auto-generated docker-compose.yml by install.sh services: mediagarrd-server: build: @@ -6,7 +5,7 @@ services: dockerfile: Dockerfile container_name: mediagarrd-server env_file: - - ./secrets/server.env + - ./dockerenv/server.env ports: - "38471:38471" volumes: diff --git a/ref/SUPPORTED_SERVICES b/ref/SUPPORTED_SERVICES index c816d7f..659cab9 100644 --- a/ref/SUPPORTED_SERVICES +++ b/ref/SUPPORTED_SERVICES @@ -1,6 +1,4 @@ //@ADD_NEW_SERVICE -// All support services will be listed here - alphabetic order -// Coming soon - Gitea, Lidarr Jellyfin Prowlarr diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index f8580e8..ae7e21d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -61,9 +61,7 @@ public BackupOrchestratorService( this.db = db; } - // TODO: Double check what this is - - @Scheduled(fixedDelay = 10000) + @Scheduled(fixedDelay = 30000) public void scheduledRun() { if (running.get()) { LOGGER.debug("Scheduled check skipped, backup already in progress"); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 7b16a29..c7e9fe6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -20,8 +20,6 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; -// TODO: Add support for hosting the configuration in a table - @Service public class DatabaseService { @@ -300,6 +298,4 @@ public void deleteBackupRecordById(String archiveId) { LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); } } - - // TODO: Add support to fetch all records for a report on history } From 2b3a5bd9b0258cac16b1bf3facca358db5391f25 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 22:12:13 -0500 Subject: [PATCH 10/26] Finalize CHANGELOG --- CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index e224003..e90564b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ # CHANGELOG -## TBD +## 9-23-26 - Add database for keeping records of backups - Add thorough testing of database functionality - Add issue templates From 5a74dc9a0f255851e40d92180b0745f11a0c5a75 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 22:46:20 -0500 Subject: [PATCH 11/26] Map out scope of API changes for plugin compatibility. --- .../mediagarrdServer/api/BackupController.java | 2 ++ .../mediagarrdServer/service/DatabaseService.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 3ef0b03..51e2b6e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -35,6 +35,8 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; +// TODO: Add more API endpoints for plugin compatibility + @RestController @RequestMapping("/api/v1") public class BackupController { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index c7e9fe6..5f7a551 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -20,6 +20,8 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; +// TODO: May need to add more tables/fields to support plugin endpoints + @Service public class DatabaseService { From edaef5ae822a743249bb627f4a17b3517f27c825 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 23 Sep 2026 22:53:42 -0500 Subject: [PATCH 12/26] Fixed some formatting. After some more planning, these API additions should be added after the database supports the configuration, as implementing a lot of the API support now will need to be changed when that happens anyways. --- Makefile | 1 + .../api/BackupController.java | 3 +- .../service/DatabaseService.java | 4 +- .../utilities/DatabaseUtils.java | 70 +++++++++---------- 4 files changed, 38 insertions(+), 40 deletions(-) diff --git a/Makefile b/Makefile index 42be21a..9fee8ce 100644 --- a/Makefile +++ b/Makefile @@ -2,3 +2,4 @@ test: ./gradlew test --warning-mode all + diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 51e2b6e..f15d8c4 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -35,8 +35,6 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; -// TODO: Add more API endpoints for plugin compatibility - @RestController @RequestMapping("/api/v1") public class BackupController { @@ -89,6 +87,7 @@ public List listBackups() { return backups; } + @GetMapping("/backups/latest") public BackupDto latestBackup() { LOGGER.info("GET /api/v1/backups/latest"); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 5f7a551..13551b6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -20,8 +20,6 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; -// TODO: May need to add more tables/fields to support plugin endpoints - @Service public class DatabaseService { @@ -257,7 +255,7 @@ private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { } private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { - try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_LATEST_RECORD)) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_RECORD)) { statement.setInt(1, backupRecord.id()); var rs = statement.executeQuery(); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java index 13e87e6..b912537 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java @@ -24,28 +24,28 @@ public class Status { public static final String CREATE_TABLES = """ CREATE TABLE IF NOT EXISTS backups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - archive_id TEXT NOT NULL UNIQUE, - start_time DATETIME NOT NULL, - end_time DATETIME, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - checksum TEXT, - file_path TEXT, - file_size INTEGER NOT NULL, - file_created_time DATETIME, - error_message TEXT + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + file_path TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT ); CREATE TABLE IF NOT EXISTS backup_services ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - backup_id INTEGER NOT NULL, - service_name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), - start_time DATETIME, - end_time DATETIME, - error_message TEXT, - FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, - UNIQUE (backup_id, service_name) + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) ); CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); @@ -54,26 +54,26 @@ FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, public static final String ADD_BACKUP_RECORD = """ INSERT INTO backups ( - archive_id, - start_time, - end_time, - status, - checksum, - file_path, - file_size, - file_created_time, - error_message + archive_id, + start_time, + end_time, + status, + checksum, + file_path, + file_size, + file_created_time, + error_message ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); """; public static final String ADD_BACKUP_SERVICE_RECORD = """ INSERT INTO backup_services ( - backup_id, - service_name, - status, - start_time, - end_time, - error_message + backup_id, + service_name, + status, + start_time, + end_time, + error_message ) VALUES (?, ?, ?, ?, ?, ?); """; @@ -88,7 +88,7 @@ INSERT INTO backup_services ( WHERE archive_id = ?; """; - public static final String FETCH_SERVICES_FROM_LATEST_RECORD = """ + public static final String FETCH_SERVICES_FROM_RECORD = """ SELECT service_name, status, start_time, end_time, error_message FROM backup_services WHERE backup_id = ?; """; From c8b54dbbb0294347a97c0b4e8dcaee1de2c3a566 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 26 Sep 2026 18:52:36 -0500 Subject: [PATCH 13/26] fix added space --- .../wellatleastitried/mediagarrdServer/api/BackupController.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index f15d8c4..3ef0b03 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -87,7 +87,6 @@ public List listBackups() { return backups; } - @GetMapping("/backups/latest") public BackupDto latestBackup() { LOGGER.info("GET /api/v1/backups/latest"); From 1b18224f9758eef5be27c2b4d4c9ed9d3c80de1e Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 26 Sep 2026 19:03:37 -0500 Subject: [PATCH 14/26] Plan out the configuration change to use the database instead of a bash script. --- .dockerignore | 1 + .factorypath | 3 + .gitignore | 2 + CHANGELOG | 5 + README.md | 3 + build.gradle.kts | 3 + ref/ADD_NEW_SERVICE.md | 7 - ref/services/ADD_NEW_SERVICE.md | 16 ++ ref/{ => services}/SUPPORTED_SERVICES | 0 ref/structurizr/workspace.dsl | 102 ++++++++ .../mediagarrdServer/MediaGarrdConfig.java | 11 + .../MediaGarrdProperties.java | 40 +-- .../mediagarrdServer/ServicesProperties.java | 7 +- .../api/BackupController.java | 9 +- .../api/ConfigController.java | 46 ++++ .../mediagarrdServer/dto/BackupDto.java | 3 +- .../mediagarrdServer/dto/BackupRunDto.java | 3 +- .../dto/ConfigUpdateRequest.java | 4 + .../mediagarrdServer/dto/ServerConfigDto.java | 5 + .../model/BackupRunResult.java | 33 +-- .../model/BackupServiceResult.java | 25 +- .../service/BackupArchiveService.java | 8 +- .../service/BackupOrchestratorService.java | 230 +++++++++++------- .../service/DatabaseService.java | 78 +++--- .../service/DockerService.java | 6 + .../service/RunnerFactory.java | 21 +- .../runner/AbstractContainerCopyRunner.java | 4 + .../runner/AbstractLocalCopyRunner.java | 4 +- .../services/runner/ArrRunner.java | 2 +- .../services/runner/JellyfinRunner.java | 7 +- .../services/runner/ProwlarrRunner.java | 5 +- .../services/runner/QBittorrentRunner.java | 7 +- .../services/runner/RadarrRunner.java | 5 +- .../services/runner/SonarrRunner.java | 5 +- .../services/runner/TdarrRunner.java | 11 +- .../DatabaseQueries.java} | 29 +-- .../utilities/database/DatabaseUtils.java | 15 ++ .../MediaGarrdPropertiesBindingTest.java | 2 +- .../api/ConfigControllerTest.java | 4 + .../service/DatabaseServiceTest.java | 21 +- .../service/RealRunnersInteractiveCheck.java | 2 +- .../service/RunnersIntegrationTest.java | 2 +- 42 files changed, 507 insertions(+), 289 deletions(-) create mode 100644 .factorypath delete mode 100644 ref/ADD_NEW_SERVICE.md create mode 100644 ref/services/ADD_NEW_SERVICE.md rename ref/{ => services}/SUPPORTED_SERVICES (100%) create mode 100644 ref/structurizr/workspace.dsl create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java rename src/main/java/wellatleastitried/mediagarrdServer/utilities/{DatabaseUtils.java => database/DatabaseQueries.java} (84%) create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java diff --git a/.dockerignore b/.dockerignore index 7838254..7b657fc 100644 --- a/.dockerignore +++ b/.dockerignore @@ -20,3 +20,4 @@ README.md docker-compose.yml.example .project .settings/ +.note.xnote diff --git a/.factorypath b/.factorypath new file mode 100644 index 0000000..b702554 --- /dev/null +++ b/.factorypath @@ -0,0 +1,3 @@ + + + diff --git a/.gitignore b/.gitignore index 39f57c5..c4d7272 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,5 @@ dockerenv/ .env data/ docker-compose.yml +ref/structurizr/*.json +ref/structurizr/.structurizr/ diff --git a/CHANGELOG b/CHANGELOG index e90564b..1d50e4d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,10 @@ # CHANGELOG +## TBD +- Fixed logic issue with migration versioning +- Added Structurizr diagrams to visualize workflow +- Added Lombok for simpler model classes + ## 9-23-26 - Add database for keeping records of backups - Add thorough testing of database functionality diff --git a/README.md b/README.md index 1e5daba..4d05496 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ This is the official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +## Supported Services +A list of all supported services can be found [here](./ref/services/SUPPORTED_SERVICES). If you would like a service added, open an issue and/or read through the contributor-guide. + ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Server.git diff --git a/build.gradle.kts b/build.gradle.kts index 9bec437..745262c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -14,6 +14,9 @@ dependencies { testRuntimeOnly("org.junit.platform:junit-platform-launcher") implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter") + implementation("org.xerial:sqlite-jdbc:3.44.0.0") + compileOnly("org.projectlombok:lombok:1.18.48") + annotationProcessor("org.projectlombok:lombok:1.18.48") } java { diff --git a/ref/ADD_NEW_SERVICE.md b/ref/ADD_NEW_SERVICE.md deleted file mode 100644 index 8a111bd..0000000 --- a/ref/ADD_NEW_SERVICE.md +++ /dev/null @@ -1,7 +0,0 @@ -# Adding a new service - -When adding a new service to the project, doing the following will make it easy: -```bash -rg //@ADD_NEW_SERVICE -``` -in the repository root to identify the files that require changes to support a new service. These files will always require modification when adding a new service, but there may be more to do depending on the implementation. diff --git a/ref/services/ADD_NEW_SERVICE.md b/ref/services/ADD_NEW_SERVICE.md new file mode 100644 index 0000000..0b2c454 --- /dev/null +++ b/ref/services/ADD_NEW_SERVICE.md @@ -0,0 +1,16 @@ +# Adding a new service + +The following is the process for adding support for a new service. + +## Open an issue +Go the [issues page](https://github.com/MediaGarrd/Server/issues) and use the template for `New Service Request`. + +## Contributing +If there is an existing issue for the service you want and it has a `Status: Approved` label on it, a PR can be opened. Be sure to read the [CONTRIBUTING.md](../../CONTRIBUTING.md) guide before starting any changes. + +### Implementation +When adding a new service to the project, doing the following will make it easy: +```bash +rg //@ADD_NEW_SERVICE +``` +in the repository root to identify the files that require changes to support a new service. These files will always require modification when adding a new service, but there may be more to do depending on the implementation. diff --git a/ref/SUPPORTED_SERVICES b/ref/services/SUPPORTED_SERVICES similarity index 100% rename from ref/SUPPORTED_SERVICES rename to ref/services/SUPPORTED_SERVICES diff --git a/ref/structurizr/workspace.dsl b/ref/structurizr/workspace.dsl new file mode 100644 index 0000000..72d89de --- /dev/null +++ b/ref/structurizr/workspace.dsl @@ -0,0 +1,102 @@ +workspace "MediaGarrd Server" "Automated backups for self-hosted services" { + + !identifiers hierarchical + + model { + u = softwareSystem "MediaGarrd-Client" "MediaGarrd-Client service running on a separate machine" { + tags "External" + } + + docker = softwareSystem "Docker Engine" "Runs short-lived backup containers" { + tags "External" + } + + targets = softwareSystem "Self-hosted Services" "Services being backed up" { + tags "External" + } + + ss = softwareSystem "MediaGarrd" "Automated backups for self-hosted services" { + server = container "Backup Server" "Serves API, schedules and orchestrates backups" "Java" { + api = component "API" "Handles HTTP requests" "REST" { + tags "Api" + } + schedule = component "Scheduler" "Triggers scheduled runs" { + tags "Schedule" + } + bo = component "Orchestrator" "Coordinates runs, prunes stale backups" { + tags "Management" + } + ir = component "Runners" "Launch one backup container per service" { + tags "Runner" + } + } + job = container "Backup Job" "Short-lived container that archives one service" "Docker image" { + tags "Job" + } + db = container "Database" "Config and backup history" { + tags "Database" + } + fs = container "Backup Storage" "Compressed backup archives" { + tags "Filesystem" + } + } + + u -> ss.server.api "Manages config/backups via" + ss.server.api -> ss.db "Reads config/history" + ss.server.api -> ss.fs "Reads backup data" + ss.server.api -> ss.server.bo "Triggers run" + + ss.server.schedule -> ss.server.bo "Triggers run" + ss.server.bo -> ss.server.ir "Delegates per-service backups" + ss.server.bo -> ss.fs "Deletes stale backups" + + ss.server.ir -> ss.db "Reads service config path, logs run results" + ss.server.ir -> docker "Starts and monitors containers" "Docker API" + docker -> ss.job "Runs" + ss.job -> targets "Reads data from" + ss.job -> ss.fs "Writes compressed archive" + } + + views { + systemContext ss "Context" { + include * + autolayout lr + } + + container ss "Containers" { + include * + autolayout lr + } + + component ss.server "Components" { + include * + autolayout lr + } + + styles { + element "Element" { + color #0773af + stroke #0773af + strokeWidth 7 + shape roundedbox + } + element "Database" { + shape cylinder + } + element "External" { + stroke #999999 + color #999999 + } + element "Boundary" { + strokeWidth 5 + } + relationship "Relationship" { + thickness 4 + } + } + } + + configuration { + scope softwaresystem + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java new file mode 100644 index 0000000..b3f0784 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java @@ -0,0 +1,11 @@ +package wellatleastitried.mediagarrdServer; + +import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; + +public class MediaGarrdConfig { + + public static MediaGarrdConfig buildConfigFromRequest(ConfigUpdateRequest request) { + // TODO: Not yet implemented + return new MediaGarrdConfig(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 258644e..15d62b2 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -5,10 +5,13 @@ import org.springframework.boot.context.properties.ConfigurationProperties; +import lombok.Getter; +import lombok.Setter; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; - +@Getter +@Setter @ConfigurationProperties(prefix = "mediagarrd") public class MediaGarrdProperties { @@ -16,38 +19,7 @@ public class MediaGarrdProperties { private String backupRoot = "./data/server/backups"; private int retentionCount = 10; private ServicesProperties services = new ServicesProperties(); - - public Duration getBackupInterval() { - return backupInterval; - } - - public void setBackupInterval(Duration backupInterval) { - this.backupInterval = backupInterval; - } - - public String getBackupRoot() { - return backupRoot; - } - - public void setBackupRoot(String backupRoot) { - this.backupRoot = backupRoot; - } - - public int getRetentionCount() { - return retentionCount; - } - - public void setRetentionCount(int retentionCount) { - this.retentionCount = retentionCount; - } - - public ServicesProperties getServices() { - return services; - } - - public void setServices(ServicesProperties services) { - this.services = services; - } + private MediaGarrdConfig config = new MediaGarrdConfig(); public EnumMap getServiceConfigs() { return services.toRuntimeConfigs(); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java index 0336618..d4eaaba 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java @@ -2,9 +2,10 @@ import java.util.EnumMap; -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class ServicesProperties { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 3ef0b03..ecaca2d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -1,9 +1,13 @@ package wellatleastitried.mediagarrdServer.api; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.getDurationMs; + import java.io.IOException; import java.time.Duration; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; @@ -30,11 +34,6 @@ import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; - @RestController @RequestMapping("/api/v1") public class BackupController { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java new file mode 100644 index 0000000..0497292 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -0,0 +1,46 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.MediaGarrdConfig; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerConfigDto; + +@RestController +@RequestMapping ("/api/v1") +public class ConfigController { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class); + + private final MediaGarrdProperties properties; + + public ConfigController( + MediaGarrdProperties properties + ) { + this.properties = properties; + } + + @GetMapping("/config") + public ServerConfigDto config() { + LOGGER.info("GET /api/v1/config"); + return new ServerConfigDto( + properties.getConfig() + ); + } + + @PostMapping("/config/update") + public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { + LOGGER.info("GET /api/v1/config"); + var config = MediaGarrdConfig.buildConfigFromRequest(request); + properties.setConfig(config); + return new ServerConfigDto( + properties.getConfig() + ); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java index 6286b33..7753414 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java @@ -7,5 +7,4 @@ public record BackupDto( String fileName, long sizeBytes, Instant createdAt -) { -} +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java index 7992b8c..471af38 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -8,5 +8,4 @@ public record BackupRunDto( String endTime, List servicesRan, BackupDto archive -) { -} +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java new file mode 100644 index 0000000..59ab359 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdServer.dto; + +// TODO: Determine what fields will be passed +public record ConfigUpdateRequest() {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java new file mode 100644 index 0000000..d6def7e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import wellatleastitried.mediagarrdServer.MediaGarrdConfig; + +public record ServerConfigDto(MediaGarrdConfig config) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java index f46693e..63cd4cc 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java @@ -2,6 +2,11 @@ import java.util.List; +import lombok.Getter; +import lombok.experimental.Accessors; + +@Accessors(fluent = true) +@Getter public class BackupRunResult { private final String runId; private final String startTime; @@ -29,35 +34,7 @@ public BackupRunResult( this.errorMessage = errorMessage; } - public String runId() { - return runId; - } - - public String status() { - return status; - } - - public String startTime() { - return startTime; - } - - public String endTime() { - return endTime; - } - - public List serviceResults() { - return serviceResults; - } - public List serviceNames() { return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); } - - public BackupArchive archive() { - return archive; - } - - public String errorMessage() { - return errorMessage; - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java index 6877586..f4be77f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java @@ -1,5 +1,10 @@ package wellatleastitried.mediagarrdServer.model; +import lombok.Getter; +import lombok.experimental.Accessors; + +@Accessors(fluent = true) +@Getter public class BackupServiceResult { private String runId; private final String status; @@ -27,24 +32,4 @@ public BackupServiceResult( public void setId(String runId) { this.runId = runId; } - - public String runId() { - return runId; - } - - public String status() { - return status; - } - public String startTime() { - return startTime; - } - public String endTime() { - return endTime; - } - public String serviceName() { - return serviceName; - } - public String errorMessage() { - return errorMessage; - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index a08bcd6..a8911a3 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -19,14 +19,14 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + import jakarta.annotation.PostConstruct; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @Service public class BackupArchiveService { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index ae7e21d..bdecb5c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -1,17 +1,31 @@ package wellatleastitried.mediagarrdServer.service; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; +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 static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + import java.nio.file.Path; -import java.util.ArrayList; import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; import jakarta.annotation.PreDestroy; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; @@ -20,48 +34,60 @@ import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.services.runner.Runner; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status.*; -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; - @Service public class BackupOrchestratorService { private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); + 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; + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); + private final MediaGarrdProperties properties; private final RunnerFactory runnerFactory; private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; private final DatabaseService db; + // private final DockerService dockerService; private final AtomicBoolean running = new AtomicBoolean(false); - private final ExecutorService runnerExecutor = new ThreadPoolExecutor( - 1, // core threads - 6, // max threads - 30, // ttl - TimeUnit.SECONDS, - new LinkedBlockingQueue<>() - ); + private final ExecutorService runnerExecutor = createRunnerExecutor(); + // TODO: public BackupOrchestratorService( MediaGarrdProperties properties, RunnerFactory runnerFactory, BackupArchiveService archiveService, BackupScheduleService scheduleService, - DatabaseService db + DatabaseService db/*, + DockerService dockerService*/ ) { this.properties = properties; this.runnerFactory = runnerFactory; this.archiveService = archiveService; this.scheduleService = scheduleService; this.db = db; + // this.dockerService = dockerService + } + + private static ExecutorService createRunnerExecutor() { + ThreadPoolExecutor executor = new ThreadPoolExecutor( + RUNNER_POOL_SIZE, + RUNNER_POOL_SIZE, + RUNNER_IDLE_TTL_SECONDS, + TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), + runnable -> { + Thread thread = new Thread(runnable, "backup-runner-" + THREAD_COUNTER.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + ); + executor.allowCoreThreadTimeOut(true); + return executor; } - @Scheduled(fixedDelay = 30000) + @Scheduled(fixedDelay = SCHEDULED_CHECK_INTERVAL_MS) public void scheduledRun() { if (running.get()) { LOGGER.debug("Scheduled check skipped, backup already in progress"); @@ -84,89 +110,106 @@ public BackupRunResult runBackup() { throw new IllegalStateException("A backup run is already in progress"); } - scheduleService.markRunStarted(); - - Path runDirectory = archiveService.createRunDirectory(); - Instant startedAt = Instant.now(); - List runners = runnerFactory.build(properties.getServiceConfigs()); - List serviceRunResults = new ArrayList<>(); - - LOGGER.info( - "Backup run started: runDir={}, services={}", - runDirectory, - runners.stream().map(Runner::getServiceName).toList()); - + Path runDirectory = null; try { - String errorMessage = ""; - List> futures = new ArrayList<>(); - for (Runner runner : runners) { - LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); - futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); + List runners = runnerFactory.build(properties.getServiceConfigs()); + if (runners.isEmpty()) { + LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); + throw new IllegalStateException("No services are configured for backup"); } - for (Future future : futures) { - try { - BackupServiceResult outcome = future.get(); - serviceRunResults.add(outcome); - if (COMPLETED.equals(outcome.status())) { - LOGGER.info("Runner succeeded: {}", outcome.serviceName()); - } else { - LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Backup run interrupted", ex); - } catch (ExecutionException ex) { - errorMessage.concat(ex.getMessage() + "\n"); - LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); + scheduleService.markRunStarted(); + runDirectory = archiveService.createRunDirectory(); + final Path runDir = runDirectory; + Instant startedAt = Instant.now(); + + LOGGER.info("Backup run started: runDir={}, services={}", + runDir, runners.stream().map(Runner::getServiceName).toList()); + + List> futures = runners.stream() + .map(r -> CompletableFuture + .supplyAsync(() -> runSingleRunner(r, runDir), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", r.getServiceName(), cause); + return failedResult(r.getServiceName(), cause); + })) + .toList(); + + try { + CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Backup run interrupted", ex); + } catch (ExecutionException ex) { + // Unreachable + throw new IllegalStateException("Unexpected failure collecting runner results", ex.getCause()); + } + + List serviceRunResults = futures.stream() + .map(CompletableFuture::join) + .toList(); + + for (BackupServiceResult result : serviceRunResults) { + if (COMPLETED.equals(result.status())) { + LOGGER.info("Runner succeeded: {}", result.serviceName()); + } else { + LOGGER.warn("Runner failed (non-fatal): {}", result.serviceName()); } } - int successfulRunnerCount = (int) serviceRunResults.stream().filter(r -> COMPLETED.equals(r.status())).count(); - LOGGER.info( - "All runners finished: succeeded={}/{}", - successfulRunnerCount, - runners.size() - ); + int successfulRunnerCount = (int) serviceRunResults.stream() + .filter(r -> COMPLETED.equals(r.status())) + .count(); + LOGGER.info("All runners finished: succeeded={}/{}", successfulRunnerCount, runners.size()); + + String errorMessage = serviceRunResults.stream() + .filter(r -> !COMPLETED.equals(r.status())) + .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) + .collect(Collectors.joining("\n")); + BackupArchive archive = archiveService.createArchive(runDirectory); - for (BackupServiceResult serviceResult : serviceRunResults) { - serviceResult.setId(archive.id()); - } - long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info( - "Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), - archive.sizeBytes(), - durationMs, - serviceRunResults.stream().map(BackupServiceResult::serviceName).toList() - ); - - String status; - if (successfulRunnerCount == runners.size()) { - status = COMPLETED; - } else if (successfulRunnerCount > 0) { - status = PARTIAL; - } else { - status = FAILED; - } + serviceRunResults.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()); + + String status = successfulRunnerCount == runners.size() ? COMPLETED + : successfulRunnerCount > 0 ? PARTIAL + : FAILED; + BackupRunResult backupRecord = new BackupRunResult( - archive.id(), - status, - formatTime(startedAt), - recordCurrentTime(), - serviceRunResults, - archive, - errorMessage - ); + archive.id(), formatTime(startedAt), recordCurrentTime(), status, + serviceRunResults, archive, errorMessage); db.addNewBackupRecord(backupRecord); return backupRecord; } finally { - archiveService.removeRunDirectory(runDirectory); + if (runDirectory != null) { + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } running.set(false); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); } } + private static Throwable unwrap(Throwable t) { + return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t; + } + + private static BackupServiceResult failedResult(String serviceName, Throwable cause) { + String timestamp = recordCurrentTime(); + return new BackupServiceResult( + null, + FAILED, + timestamp, + timestamp, + serviceName, + Objects.requireNonNullElse(cause.getMessage(), cause.toString()) + ); + } + public boolean isRunning() { return running.get(); } @@ -185,14 +228,15 @@ public void shutdownRunnerExecutor() { } private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { - LOGGER.info("[{}] Runner starting", runner.getServiceName()); - long start = System.currentTimeMillis(); + String serviceName = runner.getServiceName(); + LOGGER.info("[{}] Runner starting", serviceName); + long startNanos = System.nanoTime(); try { runner.run(runDirectory); - LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); + LOGGER.info("[{}] Runner finished in {}ms", serviceName, elapsedMs(startNanos)); } catch (RuntimeException ex) { LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", - runner.getServiceName(), System.currentTimeMillis() - start, ex); + serviceName, elapsedMs(startNanos), ex); } return new BackupServiceResult( @@ -204,4 +248,8 @@ private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { runner.getRunnerException() ); } + + private static long elapsedMs(long startNanos) { + return (System.nanoTime() - startNanos) / 1_000_000L; + } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 13551b6..01900b8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -1,24 +1,34 @@ package wellatleastitried.mediagarrdServer.service; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_SERVICE_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LATEST_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICES_FROM_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SQLITE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.databasePath; + import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.springframework.stereotype.Service; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; - -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; -import static wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.*; +import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; @Service public class DatabaseService { @@ -78,7 +88,7 @@ private void runNeededMigrations(Connection connection) throws SQLException { } for (Migration migration : MIGRATIONS) { - if (currentVersion <= migration.version()) { + if (currentVersion > migration.version()) { continue; } @@ -191,25 +201,24 @@ private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); } - public FetchedBackupRecord fetchBackupById(String archiveId) { + public Optional fetchBackupById(String archiveId) { + FetchedBackupRecord backupRecord = null; if (!verifyDatabaseIntegrity()) { LOGGER.warn("Could not fetch backup record by archive_id (" + archiveId + ")"); - return null; - } - - try (var connection = getConnection()) { - FetchedBackupRecord backupRecord = fetchMasterRecordById(connection, archiveId); - if (backupRecord == null) return null; - - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - return backupRecord; - } catch (SQLException sE) { - 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); + } else { + try (var connection = getConnection()) { + backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException sE) { + 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); + } } - return null; + return Optional.ofNullable(backupRecord); } private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { @@ -223,25 +232,24 @@ private FetchedBackupRecord fetchMasterRecordById(Connection connection, String } } - public FetchedBackupRecord fetchLatestBackupRecord() { + public Optional fetchLatestBackupRecord() { + FetchedBackupRecord backupRecord = null; if (!verifyDatabaseIntegrity()) { LOGGER.warn("Could not fetch latest backup record"); - return null; - } - - try (var connection = getConnection()) { - FetchedBackupRecord backupRecord = fetchLatestMasterRecord(connection); - if (backupRecord == null) return null; - - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - return backupRecord; - } catch (SQLException sE) { - 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); + } else { + try (var connection = getConnection()) { + backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException sE) { + 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); + } } - return null; + return Optional.ofNullable(backupRecord); } private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java new file mode 100644 index 0000000..6e73b65 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdServer.service; + +import org.springframework.stereotype.Service; + +@Service +public class DockerService {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java index 527ca62..ac21af2 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java @@ -1,18 +1,25 @@ package wellatleastitried.mediagarrdServer.service; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; + import java.util.ArrayList; -import java.util.List; import java.util.EnumMap; - -import org.springframework.stereotype.Component; - -import wellatleastitried.mediagarrdServer.services.config.*; -import wellatleastitried.mediagarrdServer.services.runner.*; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.services.runner.JellyfinRunner; +import wellatleastitried.mediagarrdServer.services.runner.ProwlarrRunner; +import wellatleastitried.mediagarrdServer.services.runner.QBittorrentRunner; +import wellatleastitried.mediagarrdServer.services.runner.RadarrRunner; +import wellatleastitried.mediagarrdServer.services.runner.Runner; +import wellatleastitried.mediagarrdServer.services.runner.SonarrRunner; +import wellatleastitried.mediagarrdServer.services.runner.TdarrRunner; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; @Component public class RunnerFactory { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java new file mode 100644 index 0000000..29d54a1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdServer.services.runner; + +// TODO: Not yet implemented +public abstract class AbstractContainerCopyRunner {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java index 48a27a8..626a3e6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java @@ -1,5 +1,7 @@ package wellatleastitried.mediagarrdServer.services.runner; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; + import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; @@ -14,8 +16,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.*; - //@ADD_NEW_SERVICE public abstract class AbstractLocalCopyRunner implements Runner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java index 966fcde..e3077da 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import java.util.List; -import wellatleastitried.mediagarrdServer.services.config.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; public abstract class ArrRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java index 8dadf39..dd4e29a 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java @@ -1,10 +1,11 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.List; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; -import wellatleastitried.mediagarrdServer.services.config.*; +import java.util.List; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class JellyfinRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java index c9bb625..05c41f8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java @@ -1,8 +1,9 @@ package wellatleastitried.mediagarrdServer.services.runner; -import wellatleastitried.mediagarrdServer.services.config.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class ProwlarrRunner extends ArrRunner { public ProwlarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java index a326e0a..ab4004c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java @@ -1,13 +1,14 @@ package wellatleastitried.mediagarrdServer.services.runner; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; + import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class QBittorrentRunner extends AbstractLocalCopyRunner { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java index 0675a97..4578685 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java @@ -1,8 +1,9 @@ package wellatleastitried.mediagarrdServer.services.runner; -import wellatleastitried.mediagarrdServer.services.config.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class RadarrRunner extends ArrRunner { public RadarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java index 1da70d3..a3a0dc5 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java @@ -1,8 +1,9 @@ package wellatleastitried.mediagarrdServer.services.runner; -import wellatleastitried.mediagarrdServer.services.config.*; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public class SonarrRunner extends ArrRunner { public SonarrRunner(AbstractServiceConfig config) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java index b28be73..459134b 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java @@ -1,13 +1,14 @@ package wellatleastitried.mediagarrdServer.services.runner; -import java.util.ArrayList; -import java.util.List; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; + import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; -import wellatleastitried.mediagarrdServer.services.config.*; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; // Tdarr has a different structure than radarr/sonarr/prowlarr, so it will // use the AbstractLocalCopyRunner instead of ArrRunner. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java similarity index 84% rename from src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java rename to src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java index b912537..a6ca71d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java @@ -1,26 +1,9 @@ -package wellatleastitried.mediagarrdServer.utilities; +package wellatleastitried.mediagarrdServer.utilities.database; import java.util.ArrayList; import java.util.List; -public class DatabaseUtils { - - public record Migration(int version, String sql) {} - public static final List MIGRATIONS; - static { - MIGRATIONS = new ArrayList(); - // Migration versions will start at 2, as the initial tables will be schema v1 - } - - public static final String SQLITE = "jdbc:sqlite:"; - public static final String databasePath = "/var/lib/mediagarrd/mediagarrd.db"; - - // Status used for the overall backup AND the individual service runners - public class Status { - public static final String COMPLETED = "completed"; - public static final String PARTIAL = "partial"; - public static final String FAILED = "failed"; - } +public class DatabaseQueries { public static final String CREATE_TABLES = """ CREATE TABLE IF NOT EXISTS backups ( @@ -97,4 +80,12 @@ INSERT INTO backup_services ( DELETE FROM backups WHERE archive_id = ?; """; + + public record Migration(int version, String sql) {} + + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java new file mode 100644 index 0000000..5372a7a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java @@ -0,0 +1,15 @@ +package wellatleastitried.mediagarrdServer.utilities.database; + +public class DatabaseUtils { + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String databasePath = "/var/lib/mediagarrd/mediagarrd.db"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 29cbfd5..31ad00b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -9,10 +9,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; @SpringBootTest(properties = { "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-properties-test", diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java new file mode 100644 index 0000000..245682d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdServer.api; + +// TODO: Not yet implemented +public class ConfigControllerTest {} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java index d5d7991..8ddd9b0 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -1,5 +1,9 @@ package wellatleastitried.mediagarrdServer.service; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; import java.nio.file.Path; @@ -9,21 +13,19 @@ import java.sql.SQLException; import java.time.Instant; import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import wellatleastitried.mediagarrdServer.utilities.DatabaseUtils.Status; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; - -import static org.junit.jupiter.api.Assertions.*; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.*; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; +import wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status; public class DatabaseServiceTest { @@ -118,7 +120,8 @@ public void testAddingBackupRecord() { databaseService.addNewBackupRecord(testBackupRecord); - FetchedBackupRecord testRecord = databaseService.fetchBackupById(testArchive.id()); + Optional optionalTestRecord = databaseService.fetchBackupById(testArchive.id()); + FetchedBackupRecord testRecord = optionalTestRecord.isPresent() ? optionalTestRecord.orElseThrow() : null; assertEquals(testBackupId, testRecord.archiveId()); assertEquals(testFilePath.toString(), testRecord.filePath()); @@ -152,8 +155,8 @@ public void testDeletingBackupRecord() { BackupRunResult testBackupRecord = buildTestBackupRunResult(); databaseService.addNewBackupRecord(testBackupRecord); databaseService.deleteBackupRecordById(testBackupRecord.runId()); - FetchedBackupRecord testFetchedBackupRecord = databaseService.fetchBackupById(testBackupRecord.runId()); - - assertEquals(null, testFetchedBackupRecord); + Optional optionalTestFetchedBackupRecord = databaseService.fetchBackupById(testBackupRecord.runId()); + assertEquals(true, optionalTestFetchedBackupRecord.isEmpty()); + System.out.println("TEST"); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java index 6eb37c3..4c1c9c0 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java @@ -8,11 +8,11 @@ import java.util.List; import java.util.Locale; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; import wellatleastitried.mediagarrdServer.services.runner.Runner; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; public final class RealRunnersInteractiveCheck { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java index a895099..8c625e7 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java @@ -17,11 +17,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; import wellatleastitried.mediagarrdServer.services.runner.Runner; +import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; @Tag("real-runners") class RunnersIntegrationTest { From 5df6c49057539364c012d907091f4d2d7675e125 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 30 Sep 2026 18:32:12 -0500 Subject: [PATCH 15/26] Add docker socket/add web-based setup --- .gitattributes | 2 +- .github/ISSUE_TEMPLATE/new_service_request.md | 17 - .github/workflows/integration-dev.yml | 17 + .github/workflows/integration-main.yml | 16 + .github/workflows/issue_handling.yml | 56 +++ .github/workflows/pr_handling.yml | 46 ++ .gitignore | 3 +- CHANGELOG | 15 + Makefile | 15 +- README.md | 72 ++- build.gradle.kts | 27 +- docker-compose.example.yml | 10 +- gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48966 bytes gradle/wrapper/gradle-wrapper.properties | 7 + install.sh | 153 ------- ref/services/ADD_NEW_SERVICE.md | 16 - ref/services/SUPPORTED_SERVICES | 8 - scripts/dry_test.sh | 21 + scripts/install-util.sh | 48 -- .../mediagarrdServer/MediaGarrd.java | 16 + .../mediagarrdServer/MediaGarrdConfig.java | 11 - .../MediaGarrdProperties.java | 15 +- .../mediagarrdServer/ServicesProperties.java | 85 ---- .../mediagarrdServer/WebMvcConfig.java | 28 ++ .../api/ApiExceptionHandler.java | 37 ++ .../api/BackupController.java | 27 +- .../api/ConfigController.java | 110 ++++- .../mediagarrdServer/api/SetupController.java | 79 ++++ .../api/SetupInterceptor.java | 63 +++ .../dto/ConfigUpdateRequest.java | 3 +- .../mediagarrdServer/dto/ServerConfigDto.java | 4 +- .../dto/SetupSessionRequest.java | 3 + .../mediagarrdServer/dto/SetupStatusDto.java | 3 + .../mediagarrdServer/model/BackupArchive.java | 29 +- .../model/ServiceDefinition.java | 44 ++ .../service/BackupArchiveService.java | 204 ++++++--- .../service/BackupOrchestratorService.java | 128 +++--- .../service/BackupScheduleService.java | 33 +- .../service/DatabaseService.java | 348 ++++++++++++--- .../service/DockerService.java | 128 +++++- .../service/RunnerFactory.java | 121 ------ .../service/ServiceBackupRunner.java | 193 +++++++++ .../service/SetupService.java | 94 ++++ .../config/AbstractServiceConfig.java | 33 -- .../services/config/CommonServiceConfig.java | 5 - .../config/QBittorrentServiceConfig.java | 14 - .../runner/AbstractContainerCopyRunner.java | 4 - .../runner/AbstractLocalCopyRunner.java | 188 -------- .../services/runner/ArrRunner.java | 36 -- .../services/runner/JellyfinRunner.java | 23 - .../services/runner/ProwlarrRunner.java | 12 - .../services/runner/QBittorrentRunner.java | 39 -- .../services/runner/RadarrRunner.java | 12 - .../services/runner/Runner.java | 18 - .../services/runner/SonarrRunner.java | 12 - .../services/runner/TdarrRunner.java | 46 -- .../utilities/ServiceConstants.java | 28 -- .../utilities/database/DatabaseQueries.java | 46 ++ .../utilities/database/DatabaseUtils.java | 5 +- src/main/resources/application.yml | 30 +- src/main/resources/static/config.html | 108 +++++ src/main/resources/static/css/mediagarrd.css | 148 +++++++ src/main/resources/static/index.html | 1 + src/main/resources/static/js/api.js | 27 ++ src/main/resources/static/js/config.js | 30 ++ src/main/resources/static/js/services.js | 91 ++++ src/main/resources/static/js/settings.js | 34 ++ src/main/resources/static/js/setup.js | 38 ++ .../MediaGarrdPropertiesBindingTest.java | 32 +- .../api/BackupControllerTest.java | 36 +- .../api/ConfigControllerTest.java | 260 ++++++++++- .../api/SetupControllerTest.java | 141 ++++++ .../model/BackupArchiveTest.java | 41 ++ .../model/ServiceDefinitionTest.java | 57 +++ .../service/BackupArchiveServiceTest.java | 281 +++++++++++- .../BackupOrchestratorServiceTest.java | 229 ++++++++++ .../service/BackupScheduleServiceTest.java | 73 +++- .../service/DatabaseServiceTest.java | 410 +++++++++++++----- .../service/DockerServiceTest.java | 179 ++++++++ .../service/RealRunnersInteractiveCheck.java | 120 ----- .../service/RunnersIntegrationTest.java | 201 --------- .../service/ServiceBackupRunnerTest.java | 277 ++++++++++++ .../service/SetupServiceTest.java | 105 +++++ vendor/dry4java/.gitignore | 1 + vendor/dry4java/README.md | 58 +++ vendor/dry4java/pom.xml | 62 +++ .../src/main/java/dry4java/Candidate.java | 4 + .../src/main/java/dry4java/Dry4Java.java | 91 ++++ .../java/dry4java/JavaDuplicateFinder.java | 164 +++++++ .../main/java/dry4java/JavaNormalizer.java | 84 ++++ .../src/main/java/dry4java/Location.java | 4 + .../main/java/dry4java/NormalizedNode.java | 63 +++ .../src/main/java/dry4java/Options.java | 85 ++++ .../dry4java/JavaDuplicateFinderTest.java | 181 ++++++++ 94 files changed, 4894 insertions(+), 1728 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/new_service_request.md create mode 100644 .github/workflows/integration-dev.yml create mode 100644 .github/workflows/integration-main.yml create mode 100644 .github/workflows/issue_handling.yml create mode 100644 .github/workflows/pr_handling.yml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties delete mode 100755 install.sh delete mode 100644 ref/services/ADD_NEW_SERVICE.md delete mode 100644 ref/services/SUPPORTED_SERVICES create mode 100755 scripts/dry_test.sh delete mode 100644 scripts/install-util.sh delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java create mode 100644 src/main/resources/static/config.html create mode 100644 src/main/resources/static/css/mediagarrd.css create mode 100644 src/main/resources/static/js/api.js create mode 100644 src/main/resources/static/js/config.js create mode 100644 src/main/resources/static/js/services.js create mode 100644 src/main/resources/static/js/settings.js create mode 100644 src/main/resources/static/js/setup.js create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java delete mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java delete mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/SetupServiceTest.java create mode 100644 vendor/dry4java/.gitignore create mode 100644 vendor/dry4java/README.md create mode 100644 vendor/dry4java/pom.xml create mode 100644 vendor/dry4java/src/main/java/dry4java/Candidate.java create mode 100644 vendor/dry4java/src/main/java/dry4java/Dry4Java.java create mode 100644 vendor/dry4java/src/main/java/dry4java/JavaDuplicateFinder.java create mode 100644 vendor/dry4java/src/main/java/dry4java/JavaNormalizer.java create mode 100644 vendor/dry4java/src/main/java/dry4java/Location.java create mode 100644 vendor/dry4java/src/main/java/dry4java/NormalizedNode.java create mode 100644 vendor/dry4java/src/main/java/dry4java/Options.java create mode 100644 vendor/dry4java/src/test/java/dry4java/JavaDuplicateFinderTest.java diff --git a/.gitattributes b/.gitattributes index e681a03..922296b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,5 @@ /gradlew text eol=lf *.bat text eol=crlf *.jar binary -src/main/java/wellatleastitried/mediagarrdServer/utilities/DatabaseUtils.java linguist-language=SQL +src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java linguist-language=SQL diff --git a/.github/ISSUE_TEMPLATE/new_service_request.md b/.github/ISSUE_TEMPLATE/new_service_request.md deleted file mode 100644 index aa56e07..0000000 --- a/.github/ISSUE_TEMPLATE/new_service_request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: New service request -about: Request a new service to be support by MediaGarrd -title: "[SERVICE]: " -labels: [ 'Type: Add Service', 'Status: Needs Triage' ] - ---- - -**Name of the service:** - -**Provide a link to the service's repository:** - -**What files would need to be backed up?** -*Provide something like: `config/`, `service.db`, etc.* - -**Additional context** -*Add any other context about the new service here.* diff --git a/.github/workflows/integration-dev.yml b/.github/workflows/integration-dev.yml new file mode 100644 index 0000000..f9e7557 --- /dev/null +++ b/.github/workflows/integration-dev.yml @@ -0,0 +1,17 @@ +name: Integration Test Dev Branch with Client + +on: + push: + branches: + - dev + pull_request: + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: ${{ github.head_ref || github.ref_name }} + client-branch: main diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml new file mode 100644 index 0000000..d2846e7 --- /dev/null +++ b/.github/workflows/integration-main.yml @@ -0,0 +1,16 @@ +name: Integration Test Main Branch with Client + +on: + push: + branches: + - main + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: main + client-branch: main diff --git a/.github/workflows/issue_handling.yml b/.github/workflows/issue_handling.yml new file mode 100644 index 0000000..8458fab --- /dev/null +++ b/.github/workflows/issue_handling.yml @@ -0,0 +1,56 @@ +name: Handle duplicate status label + +on: + issues: + types: [labeled, unlabeled] + +jobs: + correct-status-labels: + runs-on: ubuntu-latest + steps: + - name: Ensure one Status label per issue + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.MEDIAGARRD_SERVER_ACTIONS_TOKEN }} + script: | + const issueNumber = context.payload.issue.number; + const statusLabelsToCheck = [ + "Status: Needs Triage", + "Status: Approved", + "Status: Waiting on Child Issues", + "Status: Waiting on Client Update", + "Status: Waiting on Recovery Update" + ]; + + const existingLabels = context.payload.issue.labels.map(label => label.name); + const existingStatusLabels = existingLabels.filter(label => statusLabelsToCheck.includes(label)); + const addedLabel = context.payload.action === "labeled" ? context.payload.label.name : null; + + let keep = null; + if (statusLabelsToCheck.includes(addedLabel)) { + keep = addedLabel; + } else if (existingStatusLabels.length == 1) { + keep = existingStatusLabels[0]; + } + + for (const label of existingStatusLabels.filter(label => label !== keep)) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label + }); + console.log(`Removed label "${label}" from issue #${issueNumber}`); + } + + if (keep) { + console.log(`Status label: "${keep}" is set correctly`); + } else { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: ["Status: Needs Triage"] + }); + } + diff --git a/.github/workflows/pr_handling.yml b/.github/workflows/pr_handling.yml new file mode 100644 index 0000000..fe9016a --- /dev/null +++ b/.github/workflows/pr_handling.yml @@ -0,0 +1,46 @@ +name: Require approved issue + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + require-approved-issue: + if: github.head_ref != 'dev' + runs-on: ubuntu-latest + permissions: + issues: read + pull-requests: read + steps: + - name: Ensure every linked issue is approved + uses: actions/github-script@v7 + with: + script: | + const { repository } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 25) { + nodes { number labels(first: 25) { nodes { name } } } + } + } + } + }`, { + owner: context.repo.owner, + repo: context.repo.repo, + number: context.payload.pull_request.number + }); + + const issues = repository.pullRequest.closingIssuesReferences.nodes; + if (issues.length === 0) { + core.setFailed("Link the approved issue this pull request resolves, e.g. \"Closes #12\" in the description"); + return; + } + + const unapproved = issues.filter(issue => !issue.labels.nodes.some(label => label.name === "Status: Approved")); + if (unapproved.length > 0) { + core.setFailed(`Linked issues without "Status: Approved": ${unapproved.map(issue => `#${issue.number}`).join(", ")}`); + return; + } + + console.log(`All linked issues are approved: ${issues.map(issue => `#${issue.number}`).join(", ")}`); diff --git a/.gitignore b/.gitignore index c4d7272..be73259 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .gradle .settings/ build -gradle/ **/.settings/ **/.project **/.classpath @@ -13,6 +12,8 @@ gradle/ .env.* .env.example .env.test.example +vendor/**/*.jar +.factorypath # Prod artifacts secrets/ diff --git a/CHANGELOG b/CHANGELOG index 1d50e4d..0b71e66 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,21 @@ - Fixed logic issue with migration versioning - Added Structurizr diagrams to visualize workflow - Added Lombok for simpler model classes +- Services are now stored in the database and managed from the `/config` web page or `/api/v1/services`, any service can be backed up +- Backup location can be changed at runtime from `/config` or `PUT /api/v1/config` +- Replaced the per-service runners with a single runner that copies each service's paths through a cached, read-only helper container via the Docker socket +- Added integration test and issue label workflows +- Added first-time web setup reachable from the network, unlocked with a single-use PIN printed in the server logs and disabled once setup is finished +- `docker-compose.example.yml` now works without `install.sh` +- Backup interval and retention count are now stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting +- Configuration changes are rejected while a backup is running so a run never sees its services change underneath it +- Added a pull request check that requires every linked issue to be approved +- Backup archives are laid out by absolute host path with no per-service folder, so they can be restored with `bsdtar -xpf -C /` +- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy no longer leaves partial files in the archive +- Fixed special files (pipes, devices) being archived as empty regular files +- Fixed backup checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly +- Every API endpoint now returns errors as `{"error": "..."}` with a matching status code +- The database schema is verified once and then re-checked with a single query per call, rebuilding or upgrading the database whenever it is deleted, altered, or replaced, and moving a corrupt database aside ## 9-23-26 - Add database for keeping records of backups diff --git a/Makefile b/Makefile index 9fee8ce..7d6fe79 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,16 @@ -.PHONY: test +.PHONY: test lint-test full-test + +JF=./gradlew +JF_ARGS=test --warning-mode all + +SHELL=bash test: - ./gradlew test --warning-mode all + $(JF) $(JF_ARGS) + +lint-test: + cd vendor/dry4java && mvn -q -DskipTests package + ./scripts/dry_test.sh + @echo "Passable amount of duplicate code" +full-test: lint-test test diff --git a/README.md b/README.md index 4d05496..8b9ae6a 100644 --- a/README.md +++ b/README.md @@ -2,16 +2,82 @@ This is the official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). -## Supported Services -A list of all supported services can be found [here](./ref/services/SUPPORTED_SERVICES). If you would like a service added, open an issue and/or read through the contributor-guide. +## Requirements +- A Linux host running Docker with Compose v2 (`docker compose ...`) +- The host paths of the services you want to back up ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Server.git cd Server -./install.sh # Drops .env, dockerenv/server.env, and docker-compose.yml +cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` +The defaults in `docker-compose.yml` work as-is. To change them before the first start: +- **Port:** change both `SERVER_PORT` and the `ports` mapping (default `38471`). +- **Where archives are stored on the host:** change the left side of the `./data/server/backups` volume. +- **Where the database is stored on the host:** change the left side of the `./data/server/db` volume. This holds every setting and service, so keep it on persistent storage. + +## First-time setup +Until setup is finished, the server prints a single-use setup PIN to its logs: +```bash +docker logs mediagarrd-server 2>&1 | grep "Setup PIN" +``` +From any device on the network, open `http://:38471/config` and enter the PIN. A new PIN is logged each time one is used, after 5 wrong attempts, and on every restart. + +On the setup page: +1. **Backup Settings:** the backup location (a path *inside* the container that must be on a mounted volume, default `/var/lib/mediagarrd/backups`), the hours between backups, and how many backups to keep. +2. **Services:** add each service with a name and the absolute **host** paths to back up. Any service can be backed up. A path can be a directory (everything inside it is included) or a single file (only that file is included). +3. **Finish Setup:** available once at least one service exists. The setup page is then disabled for good. + +## Configuration after setup +Every setting is stored in the database and survives restarts and container rebuilds. After setup, change them through the API or the MediaGarrd Client: + +| Setting | Endpoint | +|---------|----------| +| Read all settings | `GET /api/v1/config` | +| Backup location and/or backups to keep | `PUT /api/v1/config` with `{"backupLocation": "/path", "retentionCount": 10}` | +| Time between backups (ISO-8601) | `PUT /api/v1/schedule` with `{"backupInterval": "PT12H"}` | +| List / add services | `GET` / `POST /api/v1/services` with `{"name": "radarr", "paths": ["/srv/radarr/config"]}` | +| Update / remove a service | `PUT` / `DELETE /api/v1/services/{name}` | + +Configuration changes are rejected with `409 Conflict` while a backup is running. A lower retention count takes effect on the next backup run. + +`MEDIAGARRD_BACKUP_INTERVAL` and `MEDIAGARRD_RETENTION_COUNT` in `docker-compose.yml` only set the initial values. Once a value has been saved through setup or the API, the stored value is used. + +The database is checked on startup and whenever its schema changes underneath the server. If it is deleted, has a table dropped, or is replaced by an older copy, it is rebuilt or upgraded automatically. A corrupt database is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty one, after which settings and services must be configured again (restart the server to get a new setup PIN). + +## Updating +```bash +git pull +docker compose up --build -d +``` +Settings, services, and archives live in the mounted `./data/server` volumes and are kept. + +## How backups work +On every backup run the server creates (but never starts) a small helper container per service with its paths mounted read-only, and streams them into the backup archive through the Docker API. The helper container is reused until the service's paths change. + +### Archive layout +Every entry in a backup zip sits at its absolute host path without the leading `/`, with no per-service folder. A service backing up `/etc/nginx/sites-available/default` and `/srv/radarr/config` produces: +``` +etc/nginx/sites-available/default +srv/radarr/config/ +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. + +### 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 .zip -C / +``` +Extract into an empty directory with `-C ` to inspect a backup first. + +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) diff --git a/build.gradle.kts b/build.gradle.kts index 745262c..49a78a2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,9 @@ plugins { id("io.spring.dependency-management") version "1.1.6" } +extra["httpclient5.version"] = "5.4.4" +extra["httpcore5.version"] = "5.3.4" + repositories { mavenCentral() } @@ -15,6 +18,9 @@ dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter") implementation("org.xerial:sqlite-jdbc:3.44.0.0") + implementation("com.github.docker-java:docker-java-core:3.5.1") + implementation("com.github.docker-java:docker-java-transport-httpclient5:3.5.1") + implementation("org.apache.commons:commons-compress:1.27.1") compileOnly("org.projectlombok:lombok:1.18.48") annotationProcessor("org.projectlombok:lombok:1.18.48") } @@ -26,24 +32,5 @@ java { } tasks.test { - useJUnitPlatform { - excludeTags("real-runners") - } -} - -tasks.register("realRunnersPromptCheck") { - description = "Runs interactive real-environment runner checks (prompts for credentials and endpoints)." - group = "verification" - classpath = sourceSets["test"].runtimeClasspath - mainClass.set("wellatleastitried.mediagarrdServer.service.RealRunnersInteractiveCheck") - standardInput = System.`in` - dependsOn(tasks.testClasses) -} - -tasks.register("realRunnersEnvTest") { - description = "Runs env-backed real runner integration test using .env.test or .env values." - group = "verification" - useJUnitPlatform { - includeTags("real-runners") - } + useJUnitPlatform() } diff --git a/docker-compose.example.yml b/docker-compose.example.yml index a1c4c39..14dc853 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -4,12 +4,14 @@ services: context: . dockerfile: Dockerfile container_name: mediagarrd-server - env_file: - - ./dockerenv/server.env + environment: + - SERVER_PORT=38471 + - MEDIAGARRD_BACKUP_INTERVAL=PT12H + - MEDIAGARRD_RETENTION_COUNT=10 ports: - "38471:38471" volumes: - "./data/server/backups:/var/lib/mediagarrd/backups" - - "/srv/jellyfin:/srv/sources/jellyfin:ro" - - "/home/user/sonarr:/srv/sources/sonarr:ro" + - "./data/server/db:/var/lib/mediagarrd/db" + - /var/run/docker.sock:/var/run/docker.sock restart: unless-stopped diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..d997cfc60f4cff0e7451d19d49a82fa986695d07 GIT binary patch literal 48966 zcma&NW0WmQwk%w>ZQHhO+qUi6W!pA(xoVef+k2O7+pkXd9rt^$@9p#T8Y9=Q^(R-x zjL3*NQ$ZRS1O)&B0s;U4fbe_$e;)(@NB~(;6+v1_IWc+}NnuerWl>cXPyoQcezKvZ z?Yzc@<~LK@Yhh-7jwvSDadFw~t7KfJ%AUfU*p0wc+3m9#p=Zo4`H`aA_wBL6 z9Q`7!;Ok~8YhZ^Vt#N97bt5aZ#mQc8r~hs3;R?H6V4(!oxSADTK|DR2PL6SQ3v6jM<>eLMh9 zAsd(APyxHNFK|G4hA_zi+YV?J+3K_*DIrdla>calRjaE)4(?YnX+AMqEM!Y|ED{^2 zI5gZ%nG-1qAVtl==8o0&F1N+aPj`Oo99RfDNP#ZHw}}UKV)zw6yy%~8Se#sKr;3?g zJGOkV2luy~HgMlEJB+L<_$@9sUXM7@bI)>-K!}JQUCUwuMdq@68q*dV+{L#Vc?r<( z?Wf1HbqxnI6=(Aw!Vv*Z1H_SoPtQTiy^bDVD8L=rRZ`IoIh@}a`!hY>VN&316I#k} z1Sg~_3ApcIFaoZ+d}>rz0Z8DL*zGq%zU1vF1z1D^YDnQrG3^QourmO6;_SrGg3?qWd9R1GMnKV>0++L*NTt>aF2*kcZ;WaudfBhTaqikS(+iNzDggUqvhh?g ziJCF8kA+V@7zi30n=b(3>X0X^lcCCKT(CI)fz-wfOA1P()V)1OciPu4b_B5ORPq&l zchP6l3u9{2on%uTwo>b-v0sIrRwPOzG;Wcq8mstd&?Pgb9rRqF#Yol1d|Q6 z7O20!+zXL(B%tC}@3QOs&T8B=I*k{!Y74nv#{M<0_g4BCf1)-f)6~`;(P-= zPqqH2%j0LDX2k5|_)zavpD{L1BW?<+s$>F&1VNb3T+gu!Dgd{W+na9(yV`M7UaCBuJZg1Y)y6{U}0=LTvxBDApz@r>dGt(m^v|jy&aLA zdsOeJcquuj3G^NkH)g)z@gTzgpr!zpE$0>$aT^{((&VA>+(nQB!M(NnPvEP}ZRz+6 zE!=UW!r7sbX3>{1{XW1?hSDNsur6cNeYxE{$bFwZzZ597{pDqjr%ag85sIns_Xz%= zqY{h#z8J6GA~vfLQ2-jWWcloE5LA62jta=C*1KxAL}jugoPqj4el4R4g3zC4nE#2-NeS{c3#!2tIS|1h8*|kpw2VSH9OcIQZx0Yh!8~P&p}fI$4Bj9Z zr5Yv?i-PfO#<}clM>mO(D0wHniZZdv8pOuJFW z+-u}BH84PQCgT~VWBM88vtCly1y$uEGJ<7vnW%!2yV>l>dxA0X0q{cN6y3u$8R-*f z-4^OlZ1HmxCv`dFW%quP<7xzAbtiFxvY0M1&2ng&A}QXAVR=prc_5m(D+_?hv#$M^ zG#MQ#fHMc!+S%HgU^Qv7Z9eu6eNqpSr3e8(;No*YfovbJ;60LjCzv9O~^>gFKO>t zGZg9`a5;$hksp*fHp{7&RE@DM&Pa@a>Kwk%*F7UGO|}^Z0ho1U$THOgX9jtCW6N$v zLOm}xcMBtw)CC(;LLX!R9jp|UsBWGfs@HaMiosA3#hFee7(4vLY}IrhD++}>pY zo+=_h+uJ;j^CP*OGQ9$0q+%}UB`4`5c766d#)*Czs<91wxw)jI^IdvyjT%<8OqI=i zNn0OUqW#POg^4ma)e2b?*Xv;dri*N0SJ7_{&0>;S!)!YV1TQuiT1C3ZFDvThe}yTCmErx#6yyQ4X@OAbHhdEV!K2%;7J>tiUZF)>Z|eRVDwtDC~=J z*M8|WEgzsyNH@-5lJE+P6HrurgY!PqtWk z^69SOHZ*}xn|j2FDVg`qRT}ob*1XiGo=x8MDEX)duljcVO}oJjuAbB$Z+f&!{z3k< zO6+{@O#2^s4qT`6k}Nw?DKV1DU~}0jVA)(kNz$c-p`*FNG#Gb&o?ko70F||R^y*hD z6HD|hJzF)G&^K=vuN$@b2fIfHVFw@hC_-0hPnB!1{=Nn~ran4VeTMM(Xx2A3h95U} z&J#Kw4>*V(LHOA<3Dy{sbW-9k5M2<%yDw~ce0+aez8 z04skG8@QEESIL;m-@Mf_hY!)KkEUowHu(>)Inz(pM`@pkxz z1_K#Qs6$E^c$7w=JLy>nSY)>aY;x2z`LW-$$rnY0!suTZSG)^0ZMeT#$0_oER zfZ1Hf>#TP|;J^rzn3V^2)Dy!goj6roAho>c=?28yjzQ>N-yU)XduKq8Lb3+ZA|#-{ z?34)Ml8%)3F1}oF;q9XFxoM}Zn{~2>kr%X_=WMen%b>n))hx6kHWNoKUBAz?($h(m(l;U*Gq7;p5J{B;kfO^C%C9HhtW!=O3-h>$U zI2=uaEymeK^h#QuB8a?1Qr0Gn;ZZ@;otg2l>gf= z$_mO!iis+#(8-GZw`ZiCnt}>qKmghHCb)`6U!8qS*DhBANfGj|U2C->7>*Bqe5h<% zF+9uy>$;#cZB>?Wdz3mqi2Y>+6-#!Dd56@$WF{_^P2?6kNNfaw!r74>MZUNkFAt*H zvS@2hNmT%xnXp}_1gixv9!5#YI3ftgFXG20Vt1IQ(~+HmryrZI+r0(y2Scl+y=G^* zxt$Vvn&S=Vul-rgOlYNio7%ST_3!t`_`N@SCv$ppCqok(Q+i_?OL}2@TU$dr6B$c8 zQ$Z(lS6fp%7f}ymQwJAIdpkN~8$)O3|K7Z;{FD?hBSP-#pJgq0C_SFT;^sBc#da0M z;^UuXXq{!hEwQpp(o9+)jPM6ru1P$u0evVO(NJ;%0FgmMNlJ+BJ zf^`a|U*ab?uN*Ue>tHJ$Pl~chCwRnxi3%X06NxwlIAKa*KReLL^y1B^nuy|^SPj3} z5X|?1divh3@zci;648jb2qEOm!_8Tjh3gi;H%2`d`~Q(IL{Wcl1C18+&P>tU&0!nO z&+7mpvr2SsTj=@sX zxG=;T^f7Rg=c=V*u8X(fo)4;RYax^+=quviOJ{>r6{wgf)g){I&qe`=HL}6J>i6Ne zSZ*h9f&JG>Y`@Bg5Pb&>4&UqFp9I<8o`n4W_V=4AugM`RqUeS-!`OyNLyKMqa_Ct| zON-hyk#-}{lZZx>B1F@dF^8S>x|C*QAjKqn&Ej9H#z@Q#KA*ckBX@^;gIP&?aK15l z*EY@kG57oUcm(d{NyXg6$Kj#xR5XdZ1EBCT+Zy!gyXwN&b_zI&$$>7R#{ zh8U@H8NY-cA*CBfH$OCs^priPwtwrzFjDO}DBn#mgbI~hn}cp2U{yv@S)iy|jR9+E zgd(hF|1cyC#te0P;iFGqpNBqc(k<{p^1>wHE_c8Tr4|&NV4mzpzFe;Cr)C~qpVNjl z^u(^s5=kj{QBae)Y*#^A39jT4`!NuIUQzD#DOyfa!R=PrX6oS@x@kJV)Cn$!xTK9A&VI#F-Slt8I4|=$bcjaC5h=9E{51g8X5q1Qfg~~G>qAgy*7h4-WuqE zlIEx?Hu*%99?$6TheLAD4NIMO=Q@*;gaXDl6yLLXfFX0*1-9KQm42c%WX*AXFo$it z?FwnWn2tBHY&Qj6=PV?ergU$VKzu+`(5pCRqX}IoSFo?P!`sff%u1?N+(KsoL+K={ zi*JGl%_jiuB;&YW+n%1o^%5@!HB9}OlIdQZ*XzQ%vu!8p2gnKW+!X>@oC{gp3lNx^ z82|5Jdg9-B<1j|y(@3J;$D-lqdnf0Q6T~q7;#O}EMPV3k(bi$DpZwj9(UhU%_l&nN zR}8tN_NhDMhs)gtG*76~+W2yQ{!kDTE@X4gft2?W;S$BLp9X z;sh2jpm!mkfPX>Vuqxyt76<@f4fyY%&iuDfS1@#PHgzHqG;=X^`X}t2|Alr^lx^ja z1rhvG(PH(a0THitc?4hk=P*#IS;-`fjOKqJ4kgo@dAD@ob*))H)=)6s3cthp&4Q55 z4dQRdG0EveK*(ZUCFcCjILgS#$@%y=8leYxN-%zQaky@H?kjhyBrLYA!cv>kV5;i1 zZ^w&U7s&K8fNr4Pfy9GyTK2Tiay4Y_PsPWoWW5YA8nfUkoyjU)i@nKj@4rY13sxO6 z_NzYdG=Vr<@08Xi#8rnX&^d{Bl`oHXO6Y3!v2U~ZV>I*30X3X&4@zqqVO~RyF)6?a zD(<+33_9TqeHL)#Y?($m4_zZvaJXWXppZ4?wo?$wF)%M6rEVk2gM=l9k+=*Q+((fI zIUBH6)}M?ahSxD4lgmJ30ygk#4d!O@?%WNEONommx`ZK81ZV)mJpKB`PgQ}F>NGdV zkV|>^}oWQd6@Ay7$&)6!% zOu_p~TZ3A#G_UqiJ85&*$!(+!V*+*{&-JXb53gtc9n3>8)T$jUVXe+M6n$m633Mi? zlh5{_+6iZ<%gMWMrtHyDl(u-hMl^DViUDc50UD;0g_l$F`Hb(F=o+?94B0fjb;|?Q5c~TWX>t8i1RP@>Ccgm z?2=z0coeb?uvn44moKFb^+(#pAdHE7{EW(DxJE=@Z0^Am`dpm98e`*S+-~*zmhdQ7 zCNig0!yUu5U#>KKocrg-xMjQoNzQ`th0f{!0`ammp_KMFh?_zF4#YhF35bPE&Fq~_ z#VnniU6fso{!3Z^1C57q?0i!ok(a zL;-f$YlDk%qi%n637_$=Gw=bBY}8#meS~+#X}Oz~ZKd%q(UE>f%!qca?(u}) z!tLTuQadlAN;a#^A?!@V=T?oeJ1f7yRy)H1zn_+wARewYIYr`zD=^v+D|ObvH4rOB zT@duqF>$Dk6&i|pZh?%Wq-7_kyP4l)-nqBz#G0lqo3J2D%zmbU)>3)5e?sTZy8|~B zPC7!`eD+deR?L6$6 z-e{!ihef=f<4HPZ9rSt&yb=5Q)BFAXWPR^~a&Zru?8146wvlm;<)ugbd|!}O6aE0t z6`#KqcH#S#*yz-K90+!Fhv+ zKH+?!_0yl|gWXSaASLcB9a8g7i%qz*vbO)YW`Q@Nxpp*6TZ*OO8Z|5-UWihd@CUXF zY!aTAZ$c^?4hiaq34=s2il}#Pxu=#c2^=(PbHNAyUqy__kR+n?twKrQe^8l6rk=orf}Mk80viC1NZ^1q zeF~g*iGp0=jKncK%s@#jZcn6=EiR<8S#)yiEOuwbG;SV$4lB^R?7sxOf8)oq$sT)) zA&nBCFJxsnci+)owdCHV#cjP2|1j22xIRsxHrLLBk3GI|OppUv3%r>#;J|26!W>xC z9gq@NQWJ`|gH}F{-QG#R6xlT<;=43amaDT>VaG*;GfPZJ&W*rO8WAQQc^JGw-fz-| zzAe&RAnC(gAP#FoJtt~ynR3Z<)m_<9Oo)XW}CWd50^eI4!1p4}s(zLhBIDi5r zr{UH>YIz2!+&Cy(RI(;ja_>SUC2Q`ohWPlI+sK-6IU}*nIsT)vLnuVPFM%~gdel}S zUlY%>H$?-rQRGTdUM^p^FEkqnwC{^BGl|gM)h9zkXplL90;yOcgt(8&LJwOj!5Qgy zu$@^*k%9JoAzwj@iSB^SNu#YVl@&*g$uYxxsJBvIQ>bfuS97JccQcS7&a z)`1m2^@5c9pD`P$VqH*O*fxkvFRtH-@Pd0@3y2!jW>i=jabBCJ+bW@wwUkWjwx_WR zHH5*XR4hbQ1`D@4@unmyEX)!?^~_}~JQNvP4jO&F)CH9srkFhf8h*=P z;X1&vs_&v03#BGc`|#@!ZONxVj9Ssb#_d63jxA6dX_RBt(s;ig3#s(YU3P3klF;mc z%%@^IJUAlGE=cnsTH+(qb1SxN@HzfAjYcUCb(VU)JV^3ZC;#k!t?XjaC!|68eLE zU_hlvOSNj7Qlr{x)y$S$l^2DPCMA=pzapcSkjfk*r!iWU%T{?<3#Hw6s1ux1^Ao6o zR@5DIfo-|c9AaFw848Y!BVG-+vURe;I29F#hLu$9o}oSa9&2sgG#;lj@@)9|2Z3 zon?%NV&AYSVnd~eW~v0yoF$X^1FR@i2kin0mFLG8-aA>hYK;B%TJ~7%P4?_{Bu<0t zvmI)Uk-MRncVb)A890>OqnYf=wu-J5A~^%4jpK~*xp)=h0BZB4*5uWrP>iRV+|kMX zv+BEskY~(P-K)-!JSHR`$brY)HFI|L@YyrxheT3cgHu}KtF%s%k3B`X)E_lA=E>M4 z2VV3M{c0*)`qZAsJ==)F#D~2Ndzm@hKhSBL_Sf3{ctckh-rB`gkfC?Dp6FdM?p;vv z#UlQMp3H5*)8o#Ys@-aj7O#brUfgQ7BjG`7 ztoE7v-tH2%KVC$xKYf%uvZD!_uf3x>h?8r!zYHkcc7$Gdn(6cDmYL&p3pCfaSfY4$ zG|yuujr6!Wl0}V%* zQ;nY##kEdvo8YY=SVDb)M>^Ub9e#4c$O&urD$uaRtxm-UH=6_s0m^^5y^_+F^Q?;8 z+Fd?+De}er^2EmFNn&e8SyS*`*`e;KFIG&+x5iWCsrEyH*0SFBCMx?`m5~hl1BrT> zr8W3*3}Fwsx@%UOuxNoCSoL%AM{Uj|v@>l{pYYI&D$j`&**;?X`cuOOk~?;U{~xvDUjaiH^d`A+gQL#Z?*lm)x_n6R-S% zf6*=Q1m>mq5|Niefl8s=5F={ncn5S;6~&Ns2)yGZ@wt&u4c+)Sk?hdfI^b77@K-=y zM_k=j5hp&u`2nkJK+2Lw`uLypr4dO?Bm3BTZdtWnQa5unCoTKIiG81t4bG`epBU5| zG{toT`)LE}&j{P+AFj`YZrjF-^>k+`zCM`QcQz^Ba4BEte@S}j=Q_Opx14jq|DB}& zNB44BOJ`?GJM({v`gh9pzbg8-%Un=E@uLfJwGkagLEM^!`ct3s5@-xqq*xd+2C@eu z*1ge`retZK)=bPO<`>@62cLN?^S%v#EsiPQF`cg&I7{}l?)}O$!^wNJp4Zd;1yBbQ zv@_7x7d6aXJvGHkNNcOg?A};m_Nq7H=(+zqf9)e3&yP^EU63Ew!NW4CYj_!=OTVb* z-ijSrv0M)u=MF=@+`3ldT-hzOn$Ng><)WL0vqQ&jH>W7EmLLQY+c?%i9~f_x&{OYX z{?kyyNZ&gT*m$(%-OeDAJeC^c)X!k${D*c;c}9)0_7iWMbfu)!j3+{*!Dj|?C`sGz z2xWha)#`9@p*{-X2MN2a;%FM-WqB2h)GTqQH$ZsGD#Wi`;+$i?fk;23fLpYI^3TT3 z5+Zn3cu-_2Ck*@%3^L3}JpVN`5ZJ;gmKn>gm(Z)b%!v|RYf(qrmGL#0$WHQFw4mJqQ85w=$tn^7(z|eJ$3R0} z2k9^EU<^-$ygq!ZR+7wT0KViK8qkAO7xs*e@1dq{=M3haulHwA0~BYNytr7k2K*(W z755P9a^;Hdl2X;K{c}yWr|QH?PEuh6x)9n{^3m2QUfC_Q*BW&<9#^ZVwOolx@6y9- z-YF=S;mEypj68yxNxfJ56x%ES`z-5$M${V1HX(@#R>%$X`67*Ab8vC6UzvoDOY*P= zFbPXany0%>rqH1gi7d>e`=PWZTG>^=#PQf&iJjJ0&2dO(4b8) zCl%8xJg1mg4__!?t|y_roExn~%u@Eu|p9YFb`8_qP@v#KW#kFs4eVetJ+Q+s|Y0?#D z@?dt_BA7C4tGpjOB~*LFu0!5oU(_xj7xA$meN)Z;q4Z_Rb7jY1rJBzJPr0V=(y99F zh=V-NbK+64rd#ltw~7X-%kP$R896DxRuj)p7Zj@8&>IlP&}ME3s9eV2R>SpUnSxeg zmpm?HQJ^u1T;pvwvlc4F_)>3P~jlTch4+u6;o{@PtpnJcn~p0v_6Po%*KkTXV#2AGc) zv)jvvC?l#s$yvyy=>=7D3pkmV24xhd7<5}f_u5!8gmOU|4555dv`I=rLWW!W!Uxg| zFGXpH3~)9!C2|Y6oB~$gz(;$CTnw&R&psa+E!KNgrE1+WkLM6SOf$>sGW+Y{>u?Fw zTc!xG{pa3c#y@d$d0e7a9~e_xjGcaw5f6Fk>lg$Jm}cFd%BO_YT(9s+_Q;ft%1*k$ z_cXkf&QHkaQr9U?*Gr$r6|bCV>2S)Cedfk3rO?JbyabY zgqxm#BM7Sg6s-`5%(p@SxBJzR6w`O6`+Kuo36wwBzwf6K{0HENVz^^w|E$r zdZM%T0oy8OK|>>2vSzw5rqoqEroCZ%(^OmOSFN84B2-8Z?R1)Pn9|5Xkui(fQRl^zA35EH^(JbuQd@Uh z2FJ6C(5FDD(++_NLOG)1H<+X~pt68d@JiB8iUQSZ+?qc;Jr+aJ8bKF3z`K&zSl&C7 zEgl&!h?sc=}K7 ziEC(3IrY?h7|d= zVjh{@BGW^AaNcdRceoiKmQI+F$ITdcM$YigXtH)6<-7d@5DyyWw}s!`72j`A{QC~e ze-u0a6A;QSPT$vqf3f(kO1j^%GYap*vfWQ@X=n{lR9%HX^R~t+HoeaT5%L7XSTNn` zCzo})tF@DMZ$|t6$KTx+WQqu~PXPa9FL&shBGx3C>FlGz}7gjfv}(NKvjR#r5PL$a1>%asaylWA8^g!KJ=$}_UccHmi zAZd5c{I&Ywpi3a1#27C6TC~zm3y8D>_1an8XHGNgL?uT$p+a<5AdWLR6w9jdhUt9U zz?)93=1p$x;Qiq!CYbX&S}+IITWLkfu%T6X5(pk9-fs8lh9z8h?9+>GlFeFcs*Z>u zJSaL!2?L8LbOu_Ye!=4~ZKL?643lcsNn8>qUT|q&Rv+(z>Z9=tyG&5}zZK&Q?S!nG zR;Ui^<406=jLYA>zl!a-OXH#J-pP4A`=)r%9HV5m1qGZ1m*t^wi>3$JRcH)3Q(LQz z(3}~y3=QsUu!PN$$N~#yBP@=aJ+Bkp_hx8^x1Ou6+(Kk9l1CXr4p~IQvq@AUePuAj zcq5>YDr(JTmrAuLwn6sgohTR-vc^y^#I{grF7 zg}8?&5!^$|{X`C;YrZ7?rKH#`=n0zck(q37+5%U;Hmds2w+dLmm9|@`HqQ<5CUEz{I1eNIL?X~rd{f71y z>_<94#1G+j`d5|fKK@>QDK6|HRR|9UZvO6HdB1afJvuwUf8bw>_Fha)Ii8I}Gqw}p zdS~e^K4j{d%y+A#OBa1C4i0)sM=}tjd8fZ9#uY}{#G7rJp{t6?*5*A^KKhim06i{}OJ%eA@M~zIfA`h_gJ_o%w;FaFQMnVkBT|_ z(`m9r+11~EPh9f7>S=$F7|ibj=4Pt>WVzk6NfGRvI_aG66RHig-(S%WKRLP%_h0He``xT))N^RI@6!ADl=*vsqVb|7 zr~Lwl6qn|u!%is<{YA`Mde2Z${@EAHC^t>4`X;F9za=RC{{$4OcGmw%9+{$i@!cCn z;7w~r8HY->M@3OzYh+L7Z2Lc8AcP*FZbl6VVN*_sp}K zQP|=g@aFthq}*?|+Gm4@wbs_?Fx-HD2%)_UDJ);X88~7ch~d0cJ!<7;mv>iv!RS$a z;(-cYTW=K=|F0gIg3EW0%u2CSr(Kx}yLoki|KSIt$#P(O!=UjBGRzb3L3-?NGr7!! z^VC7_Q(GhT;C*(bLivfhlRDVdz7=h%ABuLA2g$qy)A}U@Kj_L-Jd|--fy#-*ESRo| zgu?*?jGEgs9y>1`t}|^Ucd1I=1N=mOo{8Ph zwZS(F%G?nfI{#%sGayNItK9J5P)Qk+^4$ZoXZJ0G1}hwcckJ0g-QJ<)3%`bF8}(ahYIjKFYMtg3X;e7J18ZvDkV@N=nxvDl zo?}lXoT3pZY;4$QKI`~GFuQKv;G6b<8;o89Hd2yu+|%sU(9C=h8ibwZ zARqZ#lk@kp4*#URe-YmpRc&=-b&QP>5b{9{(tH*)(@ZPKfOslBgwCPx6d*{XMX|Q{y0F!5a^ScCE;h8bQmTJR3*}A>aGcDF0?tU)Tnml z#DgruwAva-fiU3s*POY_ZHiJyW%v+733X`&ocwHz$uqJCOhrM;#u*V2eK$D5HiN(` zII{BEg(PV6#_Nv3rZBUyd+TI!>L72KW_Oml6L=pNv#aOl( zgpYxAH^@2aJQu3urlrCeanwSpHHD_Cxb+=cm49{ZU5Z@;{^{okEJ6&fpDD31w~$`% zcz@_REsC~Vq>3YF7yJ41ZEPBW&%|OwlnfG|QNpiX;fGR0f^3?PEf|-33P&LFGe`8^ zaX3M+*h+?6;s|=$j*d|S-r6PSHnmLqm9oshPNpGzlxV21cFrxcQLidd2%h>n%Mc4{ z|JWBvtbb;(-nhWpPO95hR>(e(H$n%*pCh0k4xE#I%xu=#B)zXSaH+azwCI;0@bY<*-10-Qyaq%5NxSlq_@YJUUwy z*d;qPjW^cuKxdXiOWwP}5FN6SZW~NqB%4?|WifPNZr&XNVkzF0n#Y)pbaEodqNO4F z2Bq#^Gr^Ji3!T9`_!D;a1lW$?!LQ-iYV_A{FQ~^C-Jp`_5uOC)6+mzBr4Nl3fHly% zcXeU3x-?#J`=p$6c~$T~V^!C0Bk_3#WYrtoFCx9_5quCQ*4*?XG0n_9%l_!n`M85^ z7}~Clj~ocls6)V&sWGs?B<`{Ob>vnbXZwdda%ipwbzOJ(V`W>KBF5zdCTE8;mc&xU z^clCzd0(T#8*(})tSYSNP1N{FnNVAU^M1S_pq4VEQ*#5nv`CoYSALMEB zf6egyuRMzK2?r^M0hCD*sU;On6c0^Vh|#tRG*n1p5R)QyVw%Va37nMSV%9&uq^hp| zCHeu}y{m=NsA=naDy;q`fd9t)I$Qd-A1Il$#0KyDc>X)hKJViqNB{HnQyf5D(ZJ*J z{-oGB-%Q|QZ%Pqu34>fCy)Asi}IY7luNR9ebgH4DAjCVvSWfa%PE16 zkC7EIuEK}?IR!jgP%eX%dcxk4%N!zIjW4wYMfIq@s%GetDs^g!^p}DH46EP`Nh_wD z4Rwc4ezh1U$Mc)Fe6ii6eD^*iB2MFp-B-HhGTR0tC2?bq$#^J!v1r+Z0y+& znVub*k=*^0yP(c#mEvX}@Abx%&}!W(1olcWEHAVgskbBrzx(f2v&}4~WkVN?af#yi z4IE-(_^)?4e3(d{F@0<~NV5|e0eaB!?(g%l&Hq$UqzC_Enuest?CL+IrSD`tv8|{C z=79vnL=P6ne+}6X1&cd$kam=jCcv`~^y#R{doTh?6D?H)^M7-P+=D@?H;bt$*V+)K z?+?Ex3Z@8JE3c4eHDYItB^tSot;@2p_fuZ8mW^i^a(L;Xn6K+1GuG0n$v(38;+<78 zC?eMzbQCW2%&;U>j}b>YEH5>RkP44$QlG6k(KwXtq{e#13wnx5Jh=uH?lQIl8%Qxr zq%pDC)mYYKa?N>%aF%YwA}CzV@IOV9&a81d9eiU-6F&lGvz68~%{&4LuwV_5{#km3(tf`fejjs%`{Y`|0p!6|-U z8XQA9Sl=*kM|(2KA!LWOCY3Qq4sZ7r&}__rR*Sj(9W8R1_RxI&4TI+_7RSJF&-363 zJvczH?1(`Jb+RDJL9$Whnj8qJRI+Mz9=Qjvubb=Lz8nWVXG{Te;$%s9-D#$)-!{~w zIM(vkr#OM>2F7W$$Lq%fEYl%e|Tsc>9rB9c8 zQoi4nXomx3&sBI9AwaHkoOp%SMDf2@T#73Bi?|!r!Q?wc(^b_u4ranezYx~=aRV-a zD|_WPK^iJh&=)~h{t<>_$VMXsee;{r-|`#H|1?DZgWvuc*!&C2*(yv(4G5s{8ZRzt zZMC~5gjiU@6fPGMN%X~pL};Q`|IfPfs0m9;RV}xSxjb)*gmvGO1`CQb~W1M1{KwXBLyPz0JQG=JkVX zlPq&zNZS59gf-?*5Z0IFitTX4T$1Oo#_~V%4q2vI?Y@UkSHh}H9xZ1va}^oBrCY{+ z3wwj*FHCsS2}GdSG7W(|k+MWu9h1Qs6cft~RH)n*!;)5HmPX1DqrJ3-Cs%i4q^{$N zC&skM7#8f{&S!9Eq-WqyY$u?uTgrSDt#NU%{3bQZtUSkUof4`Z1P8aLOKJ+^dKh%n zfEfQ zO|P*J>;{=`9@D)qpnt`#NH>}sir*&oFC+W!HR)ecHcPwjF-|)}8+tR#@A+~CLl+Ab zCqp+=Cuc(&VGC1ZYg4CxIXYL>33p^wjIWJSh6R=oq)jD52q3~KVGt=w_z(arS!gx^ zSd|?!rzDu1$>0o0Y0+!iZU=ew^Hr+cq(I(C>9}^sBc++0+S#I;js@_NLD9>MH(tN3 zE5F+J_bYdPfYm5%7-e=lm?!-xlvX~nDkBqu!Zf0ra65JD&@tYDW+c@P3W-YyWe4^6 zhW?FUJ;c{^?b`N)03>!@#JI)r2&!6An27q?*^wyUx3T4uyeIl4*(4CV5OTK#RSnYt zq<+RKCdrYIJtdmNC-NtfH)K&pytbM^Mi6JWjkzJo0TdX>HOjJaIQmQ?Q;l2)8oN@d zVyT=%y@TihQaJX7#B2wY#_ufuaF55-sWO{OwUx$2zRyW$YM(CFBs4Y;YmBk(4u&u- zEf@rIR~4#}IMeq$?T%z3s3RAR7m%M?8No;a=1HXKP?ia#uwy!`4v0GFSjZiMii@ib z#xRmA-v~CSVl8z9cEWVEk;9_BKPS6Y2|bk#PAb|}gPxHs-dt*k`5tU#FZL)FLodY8 zmb!m`DagEJ#q1VKwO~%zmw7;LESf5u!KJNm829pbY_w$P2}16`Bb?0uoL3~V71;_U z`B~wKOB7Bp!Vn!M@o?RHydmah!dHPaT`&idV83kQPxA>E=~YgJC<)rdM1#B$JIgnq z0V{p|Cm3eeMaO58Wrv^9-kAOJ+*HR!;;A9z&>78VsYmF9$U^*ZE=K%d7=MZ~G?~Hz zSHlKWK!Us^%?uE6`E|_XI+nC354jkbUPvedHbh(DkKGkquYf}=-EEB1g>RC{O9ORL371y8V*CR5EW z@lmFq%MWEBdeHR7%(Rpf!Yg52vX%D7#@*^M`fy7Srb z^Ta9wcwf$89uL61@qeg2vc&TAGKSLV>YKI3#5lfs#q5Zm`~Ogef!!CoWWyiA=J;js z%X_n!njeF2MZgaVoMh@S@8%lR)AsYyzmqkj+C8ghxI4G6O7ovK$udULO!2$(|__`2~6JjuoERet}kenJ%I0pU_O@tU*Fsd4gm&hV?p%Y{!;r}{S^Fv z_4EJbVjFv7>+dE9{rBS@8&_vbx9>4!8&g4JV^e2mSwlNR^Z&ujriy)b3jzqfYb35o z!;J+c>%LY+?P!IticwSrP;x2|k>j3Sxg2X%E2%57

`Lem|V$A>eR0uN8Y&sdjtu z%-lD<@61@6?qUPjUg|mF7!P7`hx+st`i!^L7HVHtzwnM z)LuOANIzT#9tU4)C^WIXhZWqrO;jr_O5aErkklzt)R-JmAh8xHMJ>x>OvTiuRi}FY z-o@0kFwwl7p|ro=*2q*cFRX5GCq-v!LPD)Sq+Uz~UkOwx-?X&!Q^4H)$|;=n9{idC z0mJl`tCTs3+e_EFVzQ}s`f_4fijsucWy5y zarHoT>Q06Z4yI1RPNpW`@4hSzZT|J`MU3i(GqNhm*9O@MndJ{31uA^i zXo&^c`EZ}5W)(|YMl##@MuSK#wyZ3dwJEz*n@C(Ry$|d`^D=thayXFqxt*WW&sWdI zdm1wv#VCKa<7d2Qc#qzvUvivhK5wq*djL7Wqjvf}-c~}d#G)eG`(u<`NGei`BFe4Q ztTSs?Gc8Ff%_5T4ce&J0v*FT`y_9r!Po=sPtHs5~BlV6VEUNzxU+)+sX}ffdPTRI^ z+qP}ns9yQgjY^t0ddMx1Yd`|OB{sHnUC-B;qum1|`tR#P_@llx>d z=qpNN&?nZib(t90A9F*U%1GbB+O;dq!cNgmmdCrK=(zS1zg*9(7VMfv)QMkt_F=wz zHX2p4X-R*=tJI4A)3SrL`H^peBNHh&XC#sVR3D zt17qeF>BaCZNlQO7n@@BuWs&l(FtRjaVn~wW^x-GsjpFH!ETyl7Od{Wf;4=bzL5nj zW9c^ZodMnN{3Jkz2j2;qhCm1ede*6891vR9?(Dy)N|iENw}HKLIOrjB0x)pEs-aS{ zZR$tEyZxbP(;(l43^KjRtSuirNmw~Bg&6p;)vqM*>S#L>0+Pw5CU%4@&)8OX2ykYQ z^f^hk-5%!QzuzYniL*1Gs#S5Kp_*ld1EAmkInP+^w?#(?rbC2Bm&0c5Ko@6`_ zi!Nvd391nu^@AmpZ$_0fPR2~kQGJS7lSGwA7U>s@+!d_`(P5y;MT#U~_ONSo9d+bf zVj6MgWN=|%#Qn;vl*TNLE$Mw|*89{yJ=WN>j{?T*vqa$U$2_dg46R)8wl&CNS&iK{ z>HDBC9e3b3roJd}gK!T>takKP);KLj_9T;%knG_fN^S$4hb`E|)qy__^=mm&Z{~CF zhc*PxdrJ@xRkQ-8lbh3Ys@2ZaR)Q3z**-VSgeMHE>c5AH1bpSUor&dgTiMd5Wn|(# z8Rwb{#uWZG(Jo0co98|mg5zF}M*d>gAg|Zdex@}Ps&`51({MmNyHF;GD4EBT`oP|X zd=Tq9JYz*IP%@2oujruVrK#jAT97|%ww60Ov2He^5zA4)VihJ$-bxoaqE7zU$rmK) z#O!xp&k$!TOEiC8+p6`Q)uNg4u8*chnx*aw=#oP~05DS&8gnL>^zpBkqqiSQA{Ita z%-)qosk1^`p&aB@rZ#)&3_|u{QqZO z{f{A3)XMprL}2{=pM$*`z*fY;{=4e=u7&=s+zI)ANd+V!L%#^2hpy@#N-WbB%U2Zl zgD_E0AVVWdMiFi_u2qqxeAsRzD%>l|g-|#$ayD3wHoT{EUS2Qe zEq=ryLi%iMZ`b}tSYzHInTJ{mY{OXy0)T&Rly3ippqpTk%A{T+e?K}j zURM^%!ZIWxW$32?Z&q9)Rao;#KQuLv+^ft>o|6c@QD=_}ql%5Th=cR{P)_51Qxjh# zRJW<|qmpRn3(K1lMwU-ayxjsgKS`Q7J5m0kw|LQb=CbyahnoQTWY z?g8-#_J+=*r`Jc|A0(MOvTc0kT-tBLIIFCd6Y5iCr>cqubJu0`Ox+FkDWs^L{;0mc zxk-nf?rxh(N<1B;<;9PSrR4D<*5!DvA()O7{vl9sps3x_-Y_w>qC3OI!_Wyza8K|E zAvJvWYyu)(z*TK7e+Q#dFWd_7%;fn4Ex*lEY2$X%SP9K9d6yWC2M!3>3>tu}g4R*V zRMC!~oYyF#Izu$lGjfQ?q}KD$rpDMRjF?f>6kuBlE`z4Yxy(Y(Y+Dr#PKA}UsSWD? zm|ER_O==Y22{m%cO1jhu`8bQ05@MlII86NP>-_`<|Q4g1f7Jh*4%=yY_ zafIlUJ2zA?dT8&WTGLE&gvPl|<0zKa=DLzzPOU7i#nate!Z3u|9R6E(6FZ|(EZ%+b zsB!MEkGz1K*oXGdp^tGOWyF0SI{tq>^nbgX|L>uTert_v9gIv#Ma|5OTy0(c_qQUz z!2+;T+eysD^IV+aC=aX$FPzbq+lZ7Gsa%r9l;b5{L-%qurFp89kpztdmZa8Uo!Btl zu7_NZMXQ=6T6+OFOCou6Xc_6tf!t+bSBNk)mLTlQ5ftr247OV6Mc0v+;x&BNW0wvJ zjRR9TWG^(<$&{@;eSs-b796_N#nMB4$rfzYM1jb>Gu$tEpL8-n>zGXVye2xB-qpV z&IZjhW#ka?h8F{QJqaK&xT~T;$AcKQD$V>$$-$x~1&qfWks(mJ8#7v7m4zpWw(NS( z5j0d&Bs4g)>{7yzl-7Fw`07Sj6{vw5nwVyVt8`;Rg5bzISP26=y}0htlPKRa8CaG# z=gw7__ltw`BWvICf>5(LFDFzC7u-Ij7*OKwd7685%wb6a=QD1CjpQs$^2~cx`@xS` zNMz6?Q4OgIR8LYa&m`q*QJ%!CbD#=ha?38!M&7yLA1Wn}M{$nV3-G0@@bD#WjCYI) zKFZ`bf$tFF#}GYZ7MK2U4AKI-GY*y(&DCt~4F1!3!{>cK+7XAfKw<)Jv$b1vHkpC;gl=VNy?f-RI(r=&j z@Dy@&vHYi$GBI*-`1j-=qpI@{qwt%et&>`VuG+PYzF>DUM1!h|8sz~*0>sA7|IH_y zskL`MJ4Yw|Ru~}gzgCOOEDSyuM+ivsjt@13h-SLD|INP2zRO|RKEDz$_zlt)ZWYQg zKHk`_;gygz9b$7*)WKC(<}zQUY8M94a#Tu_OEyX$Lej=Cs`b}zjTYvv-Jt6E^_bV) zCt>gvm2{y2tK8Uy*;ruhTa_?lSIlV;r8b zX?jME!z32pO8`g9ga%`RQ*v=F0O`bnPZebx@b#ZfQWvqZPAb@zl>ORo<_o7Dp&F?6 zP(tBH@~c-Zfx?Ulkb{F`C1S8y3F;;)^MwWBiBPQ1D=;yC{M-i~ILSfh3K!Ai{5c?J zdLm0OmDsWuV>%}MT*Qf<$UT+M=7pMVdJGRi-rdW>7iM&2UO%v@>_!inA`JD)lrKC& z75Y)Lg~PVq0Ge}-g$8cy0w@sHjUuwMm1|~u6X!*fGG>%bAbv5cEU3nR6&6o03J2ff z)*M)kj|gyvZ6Md8Y!m#IuWuP0<9daW2gPDp*=aQA2qm)VLJ($UUQ>-4&3LX|)=-g5 zDTzngTm?JwMM46$Z22o7jlr3Vp3K15k^@=c7JJx9WQg*XbLRkdC zYapmoZr8J8X5n5}a2xjY35bC^@Ez{}9JA&aex@>JiMr#&GtJGn$)Tt=HVKx@B+w50tPaNkh{N0!^9>r<#h(fr3kP@a(N1!O)$rdf&Dd!hhJNtXD zIbx!f3YSHV50oNza38Kzd9Vze|NZlyBd{fKzZOSB7NqO*qDh)*>XW~VnmJ^ zji(MF3D>tHCk-^y37b-c7t1Zrt)VBlefNnY+NH0u=9IPbDZ1z8XbK{5_W?~aGs@o& zTbi2gdn~PB;M%^{Q*d9xWhw;xy?E}nCbBs0rn@{51pJ@6e=LQg2dvlq_FM0;Iel9= zz?V~4Y+a&wJIgvt5@%1FDtB9(A<-f!NpP^nl51v_hp$v8$w{ z=Rh2*Y?stNGlx7wbOLqrFbxg3lqpaaN{@9c)nNxe#D=Xouh@g7Wd}stZ!B8jrc4HPmOW%Xt^a!LcN8M4^efD8wWziBkha6&KggDq^9beRoiLH_z9 zGUiqkIvsoqX!3F)6qr+_HfB$D%@)T=XV3YUews|Tg-Hwn^wh3)q=N>FC*4nHJ+L$K zpR;I6Gt%?U%!6mxrP$mlEEiT&BVf$x(VJRuEIXdqtS+qfX^-@UKefF=?Q z(jc2Y2oyEyr3_bP|F%)C?~RzdfbNXgw%b_zaAs2QbA_QL+IyP^@l+{#{17?2dn80k zljl~W{3$~wO4E?SSij&`vnbpKCUzN%8GY^!-wNR8=XKiz>yng^Xj99@bTW|TDw5XGfDje2@E z*~-mJF8z}cI1eTpHlg*7?K(U5q3H%{y84gCiDbksT+HB=ca!YVTu zgPDuJzB@76rs{is=F^_95WD#mg}F*~wRr~vgN4^*Gy=hUUD_~f0QPh!&J7XP9zv&H zY}Zm4O#rej< zQmBNK_0>1jXd)Y3cJi(*1U|!mL(;nU#j_WV33)oK-!s$XS(mQqWqQ7&ZZ54iT5+r| zi|MH>VJs`1ZQr<{eTMqC#Y~41>Ga4BuQynUV!QuZeaFa6aP(B)SxC~V-r0K5 z5BJ<3nuAkX12%0k5qI=#D*PNg{NNjn>VUnvH!{DfD}FX=e%E5lw-IZgDqD$1an(zv z95TXS9wGg?Bl{w91nOC8HvvD1&ENr~L>4u{^bNaBD>ZHXIw1Ko!;wjz1%zZMbWE8# z7f5xlDTQWK%rH+)0KY&O>*EHs@Ha5t9ltEE{qv`K0tO?W=jgzciZhHZ4As;i<7{@M(!#&K$4UGQ?~d6rbu|rCYd`D!Bgha2*v# z?6){N62Wq7br9`S=y(rk$xKExQsyv0H~Z<~f!Z7~Wt6SlJBO4_KeNahC?2rxh%Z14 z{6vx|=@Pd?8vwjCEbf?V*zgc>36eg4u4w8WMluPe+qB=i60{qnN+XKmud{LfKvd^Rf{8@jDa#RaXtvGeC92KvnMDV3m2 z4Xt7QB96VazV=Z?RrMXb$#mb85@y7X+OE;c6PL94T|ssUhD|n8IM`GhqU%%}=6E(! z@O+LF*%Uy084M_#De*pBSU<)G3|%go1vt<|<(ZKk{3&*44f?ftxS-a(+@u_92o7ot zYq%I+Ztyt1x5RPt_1it>&+05XbK1B{-T~aA+FN6BiF@>|QCJ`#y*u z@e*p+J|+Jzl4qtDnLJPde6Gl8Qfu5eP#Lr_}cyBzGaR912ca0h5s# zbgocm38uvIstvyAPMEgVj^>{XqR&db7$(XJRTRiR@!lH>>CTe{+zRJEgcn{?M627> zsw6}Y)J+s3)u#g*Mo19)oWp785&T@;fee1**^o5#bgS4epuPWP>~Y2v-~{)-me7SK zd!AQUXsd{A=;C;8>vRTE5Dol&>XJ&AYMijyXV3|_46Fr#lz`uF9dT^PhX2e>lDN?r z>wx*9-Pr~siloVs7@`dn*kGmY0xP)2odnz6S437Hi&}MSb1iiwEiwfy=f;yg# zDZojIe7{n|lnmh@$rU>6-%oUGrG#^0y%z_Niq4LG38Yq&Dq<~B-3qLMHLbL;&A)i3w zq0}L%{J2P1a z2OC$%f4j5C`~!#oBU=IP{19v?%zqxLR77sUDKZWk1TEdClEz1yHB10F7>l{;9l0L|=ADc&?i zK#F90YE|)m(u4LGC%M^0?53NrH3M`xl2{P!5+fC(H)Yt|t=X~m+os4b6}Wj|nDvL8 z8n=Bhi`Mq$&2sm(8n4F2)~_ylMf-R2rn!V)Bfzhv7v2SF{79o}>ITpgUpe=zcRpds zp^3fse>q!&ohi{7gYJM|qD$1?s^vyP1XP=26O)1AFu)?|OCYHCJm*LP4*zJ8Raq1u z)9(U+oYRkni_C&!f4&%ORK?w$g6<;rT((@LunPCC_#2P zxJ&Q13mCI_U+H?IvV89Y)i_#NnNt!>xavHwF$|O zXuHG5oCo;G6F&W`KV4I0A-(zyjQ;ws!05mAr~eli{U77e_#bTiA4Hr~$mBnaBxQ^3 zlOJG&4aI|YIUi&Z#TBHjLS(GmY^z5R28NolKW$l^Ym#0I3|0lI-ggSR?CgqX8f;MBaPl&YzSG} z4(9gprQ%M^N3g+r;f^a0BNw0BQ9}e{Op$ssU!0cTdbP z1%BNUh*RkAe#+jya`#(*p*uQ|spESDMarSs8h3e`E#gtvYi=8d#ADvy9g>R@*^D~F z2t#h@kzA0JK)w;AMPg^lWi2XAU}jpiDF!akXK|rSi6}wmaK)KT*81I6M}f%l3XCMR z-&LC;?s53?Q?B;UuDeB{5^S+oOfSGE^CnkvgEc9^13~<4(iGap$VY8}3$6;-sL}t1 z4d0l&nxB@pZuYHH` z{ONm|SH}iy2^)Zg%Ou?*Q?I+u&ZmckE<;nVG0STB`M9GzLE5UAMeRQQJzJxXBBwA&_T6LHe4yGpP7i~lax~#Ub5BlJE zg>YF0Yn0Wcsv`EJIW^d7i>M?PO5_+)OxDS;9?zPfCH;#_rpR4-*9!|aogttErPHlR zUf2d~4Xa7AEaZSe)Mn9=Nd;=@JUDKUaJU-Rx~HXERZPZJTiBwHdXup>tP-Z$yw6H? z{D8e~w09((x@w&~)75oSpJ7o&u#DUKXAP}9afG;3qf=+XWeC!=Ip8PJvw~{@B3H)k zZr>U-w?x^Y3%$zAfoF_*V2Mlr?I=_C57F2k-rurm=_3`CHmW^yY`ye5aJG#E#oU&y z^R4vJ!2z7aF;V5BD1dbHn6(R25;-0cu1Cet+$J~Uw}=H_%79gf!-W2#1g=S`%zSN- zwVT1}5o>Hi-DpkU76(;YW&Y92O;@cEU^coXt>XfiRWI$}_*t&RQ_K?A8!$gpQKZe> z6VsBW458Q0>X1E#m*K&U%))^SmEntSPBAZb7VW{C@EA7Plo3r-`7EMb;;WeQn0bRTSxW7MTSYNoW=(qCsKsMVCbY?$#Z{|k#%NHM zA*6=sc(VKVE`UVqumIooHMGYRSh$SD{ErAy8%i_*n<=4ODdFErVql6WIx-X4fyaoz&jU+aYlbi=W`&5GJ~zS*@5IRv9cn<|il?|!d8>N94!OI0)aLF!Q0nlhtv zV$SFv61Ek9=p#mMT*~J{BfjK)?1ss~7B8LE@RPM6>=Q&sCt<9ZWOlek61x3T53zDy z_Ki;P_XP~dr)aCdrp;^Xx&4zy791bkXYcFE&ul#uoMVnctVZzl-Azp*+fw1N@S40^ zWBY6U4w+j|T8!q!)5)=7rk~;72u(J{qztk$Rb^WOCbU62Z^s|pn=)TqT4{gYcX?y1 z?|~>Cvir?R7Ga#&UI_thW{axhKZmGsOKK2*Z5|H*2nrEoD6q0cA?LAuQGqE#iVxT) zkKFW#vDut&E=}&^_xyn@nKhBk4S$!WNK~%$ z0c&2{SDdyuxlzV0ph!Peph$e2NH|n4;u};Z5-fDRQCkV`hd9~Qhw#l z5yeB&7zlX?y>QU?3e8P%Gzk1X934Q9LPIvcZi~Q>$tU#A^%^O!FsqRvO1M){#{wo# zBk9bs(!8G_zMYJ-^KkkOmXlld6&M}R+at4#TYfha^(?3_OqFsw=T6Gudap+sqFPF0 z*6D8MYBS6E;rkj8{7GbNPpnUPv9*l#u0T^M#yAbod>pw)srdC}u6;9n!}f|*m@!$~ z1aL-1&ei+i_Mkf0!?>5p@ss}z+(4GaIZ0Tu^mr{+M1{}bS8k3r~HKz!?C`p>TW)1H#Yg*vr z7Y{a{9Z}e1N<7QR%urOa_cLshyVKNaKNU@l7j~j>PeI7MIZZ|r0*YSjU6P_&ia|jH zDoChFYF-JCkoNDw*&*{QG3x+J%2L5_4`n1Tg9hatvloFoYL01#hFFj~!}MRSdgSSl z=m-yq{#uwWUIpuCs@%BEy5ob11|s~&TVX8~-XV)oMfeNdXD?Z9E10-tP#Krhiv$@dBpKj5J%t@Y2xI!*8s~Z z29}0zR`_9s&89Brq4Tru3F{G&uQu{ujBFqN`NY$Hb>qnXc(a!g%hbv!R@n6sNonM) zg649UVVIiIE)_J6eMZ?R^6HGdRMn-UD36*c8_Z2r&xc^Cs2p^v6x-_j{J)k91n!wt9I-~_PA$GNiLi=u7ixtk`YUQ4uIF+`SI~U z1J;MiD+DHLSA)nBsc8CJW1Z4F5uFXI0GzFHhs4egAoxF&>1&8*Nl_OA^!wW4GJCRO zwS%7>sOyj*5EN! zUpux=mBP|Q*_J!@%f6V&EZf{?`H}D&1^^@HO#Gta8P{W+FkdO5OW;fnD1|4&tlh3} z@YGnJ3d(Y0t#ep+bksNs#e?8*u-V=@#Dvz21#EB=jam5x3MtG&IuRHU$pr(K+Y-AX zn7FqKEk!?hw{HWBS~^ioY8Dbe(VtwFva+1h5$-}M9!~UYHGIL>zwFFN1`lcLe zwaMY%;tKHw`EL=C_^}jKY3YhWzg-&!anlG&@4E|`Vl}0q!EvCtT1I@}=Ug2;8OzB) zmllrTJ}RHtO2N@|-7)oaf*v0`{>2c|j?-t&WbDWOUDsBIUR24HnS0{I;>(%9+r)y* zg2K$nGPerx{E6HXH@h?eRQC~Y44A2^$`xKRwnOj_7pT5_!?K%>JT+F+ z6(@ZUF%FqvCBG2v8WL04A5>D=m|;&N?Hzcdj=|%{4JK2j_;hMKOfU}I+5PVH87xo# zc>v2%1gFE>V^6x3$7#ymLM62}*)(ex+`ImB7=eUwa2O&zcN_th9iPz)#fXNbq_VnK zg>+Fagfb53(>-Y^v23^|gST@kT%3pG*YUyrd-zn|F0Cr_;Qh)MO;mTE$%x&%B^Oc= zO-<|3$Nplt0sdxXQO`|RVIbVxm_^24G_6XuTxk&{Yyl+?OeXa-!t}8&fuTGLZpS|{?$S9qu^8TDrgtdOu`4*Sqx20lCJ(;z6u7&0EbrB@495}e zvjfw8yG7#Eo7QX+`k$3*tbTCwGm9LGOvTam&Kk&4&(T!!b0d-h(+s160p@Pn+_M|) zwasiA7r)El>t5DJfiBLb@2=gQDN0N*FfYuh&F<6BNcc)=oqju*S(+ucbzy4pyN1%s zgS@}T`xoCKJdeoM>hW-Zt9xSNRYI8RfX^{UPSJ}y8$_k~4-2G8KZDJQl``0lf>>)j z^q^y@`VIX~W%W-QAF*8U#?c|>tGQ{a09;)CL{-NfEv_2<$o(R8`V7xFRTl$)d~KX! zxG^v#xd(Z9R*`P* z8NwYSrl;qaYDzF0iB%{|A(v0($}TDr##;!y6paThkw{fnuKExakKusCdM>46hESJo z6Z4inrJpt`IzSB{l1R?`XS)o3@M9OZsiP&{y4g5QBH!U*Fvdd|9inn^a}Nz>2&)`? zh!|tcpGBMA4e|H2Y3)~7iyNUBsc|aN0$HM9Uc2MDIL(61;J!I)NmIwv>&&25`&+6M zq1}!I%Azc>=L(6nYlCWwU59Ea*szPa>sE|5)2pJsAnOmce3ZqxF(4^b@uZ6D1K#-5 zD6|eu@+l+j4}V7yxluQ@oX?sla^=5dw}yP&j6E+69hswg1L1c=)OyvZ7^wHQJl;ml z_2lX#$i;=Fs}vkh=ukc4y2Vj2Lu7vAHQ*E%@5?3`^a{BzDVU zF)O4|`;uuAO@)kfdwp~fqS#rR$4Oj@c*zBS`-fL6qu8<7qzl8rl--^kjiCV!(vbxC2vIdMo2I^X@+ID zcT&$52_`~JOBXh&mXX+ceO*m*0_=9ArqG>xjMR;+M=q{e-N#QEj-BCAzAVeGSrXNh zCV`uX4qS?7l$u+*J~5P?9xlU2%6rgo30lJ)cd|FHtEmloD@8tO@5y7N5t*NZN|hrm z*0FP5k0_1u5$>dp#I>8az>my1NoIAqBZ!Lx(!ohP^U@&Vmqd8 zH=75V+`}JpR;Wj8!j6BT1WSjMs>H+3_*52JYs(04P<@$3WEVZ7V%N-CLN$onNB~*- za-hT{!s~K{EUyaw7zDbp7n5T~SRV3$*>Zhpg-*51L=Zj|oeHx)1Mr4juj_5;_<5%8 ziMWWR&MhgdLq0$}U0q=ol1xb)TQBdcV!(3$iF4x~ue+F-gFAGMn^|`*YBjuP=jx!~ z06>UuQAq?Ix&zn0^To|<4!CSXZW7o6VrM}5dYxV+Q~8-h^Y9DzNs{5%+kyFy5cysy za}2EkZyRxQ^Rgq)T6r=({uw7y@%D4S?wd{Ck@D0(;mjg4NbY$Z$xd6rCGrNITO04Y zO%6aZ!9hMp%kU=V6dLc($d`AHMbf`&G9BXY%xr$$hovCbBj@|K2-4_HjW4Xn{knIL zaKV)PQkC?JIKYK?u)1`rzd)G(eO222!%q#U6QaT;SUl*MO9AvJ_$WC-@uTOjb58L_ zQo63V8+G)0D~=S&a%3>qqG`7N+Wfi$Logc=SXGBq3&TV|=!!;Nzi4VeqP9=hV>H5k ziX8p2v_i>9nc1rQm(7T8t#sTSGnI9T#Ms(_k_%sm3mT6gc=YrdUm@Ip6xRqL0H93*Yx0O!3Qw+_Y!81*n-ovS%iBlXx62TFNbk8K-j=LOV=1s zwc7i_TsS%sk!R7r81r4v*Ec`Rrl_m zr2$@wBrDGJ1`%wG6Ar259e%+MkZzK88-X>M^WgfA@HcWJmPUeFdO?d0>gvCTn0-ZWgb;$}~gdQiffS0?*jk$T`izb=V-&N#O_U4yp?Y!Mdlk09!o82t}+5dEvSj%vN5 zCBperFlf(sXr6C$n?zYvm=YYyz=~W1tkhvu1wODh>tKoBEiRB9*Py%96luTxm11-k?Q=g$c>y=q9%J< zVbw|kc=&DAiz8G*&G@8XlevEthbWV6a7nM1@VjKNkP|sl%x3(c9h#|9HIdVuC_??C z!MaVTrRI4=oMEugDa}D)#f1zPsr&vLR0Zy!7;QA4?x1w?=X%tH7o_(2z@8LjA`t^# zft3pe@**E=P;MFXEB+)Zh$?+;5%i6ECfT?A^~N`o&QHR5@V8a13HuA~omH+0(xm&s zJn#ru(@aCcl%uY66t2-NPi-*^o`hAyJ}I5kdqib+qh*CNP|jg>f!Wj#HJ<4r?4uCX zvkf`dDbhurH>#bk@3|Ap%0+kV-0PkcrZb0Q6)EJKBfaiae*!zLC7wkQ?cY#avSAHH z-b1`V^N9SgFL7-JrVQZS2rsHMA5v)j^@ga==T4XfE9yy6w7~pXILh8O)Le{Zg)9`|o`-$nca zc~hvlgOB$pGXop$oW3PzOuUbE^uRf@bo%^%%GEHQ}3uc0E<9SxbN+Fk6DEin>4 zHcD4f(K{ENOe$J0HJ#urqwE!{iYCcrgQT6kUmRQ&pZsx(U*x5m938GK3cceA-25P7 z?4_>Rtm;@LOJc>-Es0d2lZed7(#_R8eGm|eZ(xhjbvF{TQvs1jaS#K%R>_hqN0n}TZ* zkc089?X9=$pO*FdJ8a~1LwKU&Tl*+PUpFFBdK=aX&m5jxjDg5G1pXXNL&FXtQoDIi z%I2VE+_J15PN$4XB^X2Yje8=^qT3Q6Up)7auJ|SXIn8t2lJM#_5ql$SZ|nXfb&U<5 z+WD;cxsrkAy@tew0gl8PHWX0(qf>97u#=sJz7BD=`gp*W%GmlPa|+rCER@9rjcWg_ zl26OYrAyJyc>(x*jhp9DekXff;UF2NN;Ui}MJ?5ICzv@f9ALbJ?E#ZUr9Ic3 zzA*o$&I=Ta@JfZOEAMmeNUz9k93p!8X=>FBD$#aW*rJBSOJG_{E4u;M3A)vn3ZA*FCGn+Fg(4w7}cEUuvHYjNe3srT? zjGbTt%LY~=@?&|zrxYJ%v<6_xj4<+!VwleU+BF+z4)}b&?KFik zy?KZ%qJSTxm)WSC(-)vC z_LTIFihr!^y%i5PBEEPCOyW1(0O<=Ad}++TAQlUVUet+p^E3c}!Hm6Ker0kttjBIWHFAYVE28@r68QPb>)Vg<;d0ndg zIOg|&%Z^&B5koUj%;;F55>#Cd>y`X1^41GHDSIjVmR%4uBt$XKaBh6+p3un1m6DKK zM5nC$KuQFHa!O+A!tnBN$&WmSvCPz#nQaEXC!g(?sW+Y@AB1kdg2dM^(Gjmzs6*J zi>IYc&r4tXJ{{+;xx*UGux7GmUyf}GKo{&yc+i^CQk+fM5xwnR=XN< z!u~>Gl{|8NtTsKC_us}+!JbSFv?wd*)?I^VPt2vT`c;a6orPS2Qhe`>N1KB~dB}yP zspLQzZ>`?Hbq-7qJC#l@Vh{gOd0-=i*!QkM8LpL1X8-}g1mS#mh6v^#lwH+V0EAht zLRoZn@;eAS)m=80s0Jn#+sLq@zuIq|XFXByZxLIoN4=#LqQuVVkJJJoqdv}YdIi8` za&=Ppx)n$aP&MKW_^PY6l=m-iPXIGakyd*1%=})EsxHySwRk^AE?qcrR8hTjF`nFh z)+UT>wL0VXkVCY=24X|7B}!a=Gf)c2+1jXZ;lwogP%J5l_LHb4lWDj;(dv}Vr1IJ% zBzmFhafX~i#<1bqv&puIYKuHOPY|K%X&v{<{=yTL{$8uDcy(HHi}VDVjHC}Z7W0`b zEvA9p60jBWkkB5Rk#%5BJPS(P7jy(H&ZM=!PzvrzF1=cb@j0B{!WqXMl>4hvAUG#n zJd@sf-hvm66(tgSb~I9O>_*OH9ggr<9(jkPzpUP5U;9oi{-`RXFkT6&7UzshGl7YK z=w!GA{fajfE6<@$!92K|Md|hQp!i-X2J~nt=D;7#M2;}9l3LG<6`3C2w+L(}Swn*C-B*?`-k7j87(HI0e zOg>|2NSSo0G$Db|yJ=}l3XfUHc3P)1NIM4OhMgn9utTLY8mQE#BnS7N{&WXwxbPTC zj>^Vmu=6JO$5zNwB5NNSl0w;}jb@J-VA6wNi{X~PSBBYYx)&mpWiwGyMd~%>340*O<^m+;13xv+nsl@@4vWer8?fJpf?QLDsIAYG$AW; zLaEVbXdlU68j5l)of@<#27i#8e9acN)RqV5SD02bMKnOYW!RB{72(fvCCTBSVi?ru zbgDA#*GRW68N(c0E>5u>u(SP<+gV#x)7`Bp@SBKiVu<5JAQnY_TkLETuOirHXdSvS zvj3FIepQF6dAlF4aI!UHW_6)6yAM7CrBvn^#Qb^(|KMPUas1SycQijlWVnLIlvayxabGnXVuaQ^dHa@y9)=$QZH>SPegN=OO*~ zE)SFDbmX`%K>u)QKvO4)0Q6_1yp?lfgooarhtt<$z~YTO+(JVl(~ASc`owLsRkis`U_?MIJW!nR@Mo{TY+o9Pv7gjq0Br6 z69CC^k3Y>byZiTYSu$_l7lJPB2#srl$j1$McL;9;1JwOOnTj&h4}mWH-Vn?pBA#s3 zjm-omv~5W85u0g%GVKXOn)WQaVM*sXOrslhX;tKH6?3k};k`m#5;f?oYG{A|jfzVI zEawoElA5$S+%=j>B{ljl6OB6dMOtiz$z|zws<7A7tg64qMADNf&^>0E_v(v4Xo_qH zV^U-nQmvG1&4lmI`ITySApjtTHJlbWG-M3T*jAxeFp8eXd~QuT_;Rtxq6gbbb-=tw zoQ(PY91W&wSS2@?%S!N+c&XI*-Qe>8h;>EoRGL|8iL5JVmPFo`8mCcY@G7$%vVy7X z7@ReiXO;L?;tk6Mm3?VrP%a+9@9N45(_m|XD$^pZCLI=|=N&b3Eye{UTf~qseLt&P z!#sl$Vu>mfVC$4UM*S1iA&A8WT0&j2yWtx^d_y<4cNyNemon|ChjXI5IDRb_6+)L6 zHL>y7N+Zt&p4YiL#W9q4j^;U#_Uo|iALm532s#R|g|RtF1ga%u9(|3q*VEV07-Y_# z={jfTg|b)%84CRox5B4Px#rve>wV`e>F+Ihvw2o<_Q-Nv6Oskz6Xf0(P5Qe*HQ7l- zcH%D^p0}1DkU?Oh5Luxsh!wO zKUM!6-)%F>W(*eN%I<=x(m0rDftloG$@?ufi_0FJPvZ3#aSQ)qBP??BlZ)n3kR!u( ztnUxe)+T0*JsBGnx*NQaQ*rbN@u7$&a*QhLA>#~Ru<77+YbIJviqYiex1fq>1{FT# zFdi=DsQwOIHD+foydCEv&;U6m{f)}zJS3hga=b91my!N=YxAFN>}t3rbzl6j(22F3 zN=wsJ^$u!O$eS~g%{1`E%Z4(MfN(74t3fvCmpBFL^Zwb}W|;;%1`>f&|3*$y)Z>cJ zb4L4u3{QiD>q8`;X78t!poKbPNQ3F!N5@gjzIaM@VHUUjjLWq@kvi9sqbqS?nXGE8 z#+GiOoSb3agPl)kT>OYk63q+oSkS>R1&~Kn8mWrR@Ghg2kK(O=B0gr7cqQS&ZU#=n z!fuWk@yB<^!ZQXKgv|$6V&t7P%_Pw;Z6eX>n7u0VO2tT?Md1A_{XTzc4f!^fy@J`@ zL_xHu4pQ2%+0gi2MYpK?iQ^gAY+ZY~Gl4zpRA+4JCqhte=){_!sS#6~-(u2O33{G&qyu-3N|Q&_I& zrYu8ewgXs?(VGq;pSXyDqUfrqm8MV7=*kn-gajV?A&2rCKCU2b%V#8DjIS?*Vby zKbhSHwl(aey@M#B8n8X&2S?C9fc+T=k|2m>1p1jE^8a*p7GPC1+y5t}yFEv0biZjerCkVf)}=vc*AQeLaes5@b#F77Z6qAz%l-99zN7!krPb@WE@*haV*6;&%ac`t z$p+!J!?T5Q(0fA5a}OU8+PZ!Ndhf30kT((m^9FiJ79WS^vcFZ6gGuSj{S`e2Q%u8$ z*$=`FNUwnT3MQXg2wm@iypIy_wtTRvyLm345nt~Hjh{W&yk9bNXi)x$TYOmqRkBjR z62UrkX=#b5CsQ=dI{nd9hLOmmydWim_?39xb1J`JjsCP(>wNM~^8+bwt(VJK^`0=s z%97EYPT=bjs((ZFX-|N_y>DS zvWRyIuDcghz}MpyZE#*nQw|a4uW0zgqtA>*CLBdpjUhRD`mJFRa&;l=cRkT3S(l<+ zO8=_HSCLh~y|ftK(ajUECd|EE=Wy?Hb%c%#nHYPZLw9akcR7u!w5#-PioD>8RhE)< zt{&UjCzWN|o#^vd8j;6KXf=4}kMkCW| zVSxvE=u0vh*r$0-S(9P7Q5CW%^7bKVu=| zk>ZOJ}2*@xw z%?i%k;pi|RUQ44_+hrd+)y{B|7lfBZp}F!E)I)8)h6ld30f2zQD zTA+dMr02cDX+vCzfK9iwIK=x(6Jyzg^uR7;c;;@nWi3y`O@AqwhJ>;X- zN7gfZGgG5gwbGh~E(12E`qln~DWZnEFRDh%yxmP)2=<8>_4(`U0+5>T-4EU{^0T?< z`+eP>KTJFH+2mikxF_l^Z@%c<4BZl2RS?NPZ1r~7eLM)%xk}0y=Acd)Cm(z~Xvwb0 zQk7zx^wnc%U@M7vM_a$zg(1pPLqISuKU(`;+GHB;XjQ`ED5yW)tP!0z#M2FKs+Ds` z@d($Yzm}Bw#6VTT%Ge5*n?cNZ-1wB^I44Q442Ll-=xb?uqN`n``RUrAJG2xmJW}#I zW1SCEJv%R%*ur!4a{!F-lTBUWI$4=GO;;xgrKZ*Jp3sa<>ilJ{rnNT~(~B#*XEmiU z1~Ed`QBgYpk>YsHbLx#%E)o9--i+ZC9f^_7T3q*re!~_iq1d4WhP8%?V(#=QM(g^7 z>2+F74STNRx~BuypUTi!+)M{gS@jyMH($ZDu zKjsY7wy_tY=^3B$W08}!&<@2c!l~K6&#D)VB-K$kGlCyqCHZOrNP@szFIP8$SAP6l zAIjazY5FRXfEyma)Kg?SYc6gqIrvj&$otnW`!RzBpQi4fq)s=P5CdQP@)yndY7bUH zan{vp_Qu7}wY$KTn$j1%Y@h6=n?MZNqDJhm%WboRANR6CQby3{gRzTJfUkwKimRra z>v20v{=}dJ`%D)e01bVn*OnnAnvxkDMidvnnJEF&DTbM&P+`Ujq+6c9syhcdm!joG z*1W2nVX)Y4=7jc_kF3u24hP6*6e_ugdd-Zx2G;^;ugxy^C3B;tZE{9i)S#}n+Tm^Wl z^%KpO#g^>$))G%Ak1-6LUD#ZTRTn(7!9<4(>I$Q9zeW_j9T{_T6J6i{a*yI=rhgd@ z)gG{9+1{|l$zFGeY|`t&%G=$#LakN(kclKjR)UF-Ix%+c&+>+~j$d4Qmb}LruYMO@ z`qpSxlDi`75!wy{eqU`gG<%ZOL3iz#AK@!h!=>|j1B+Oe$GKu9eUZ!k_(1T+S7_kA zbJn;fO_sAts`Puo#$t6E;ze2?q_a>$w#+0nuk}*bYY8_IQmYk^aF^PtEnm9%vS?g- zl=f(*i$v;};DFLu)Ie}{;wBfYcRZ;#gqu}?q$J)G2lLswTD<(sxB!k1pp9in$Y8=k z^3JyAcETT9MmAB~bYMX>W~mpKeS-AdzQ{3eH)NL0Fva9G(r77Eq^5@T^jqfFHlZW6 zX`)orA@BS6J(?KBp+#ABTs)dY-6)A)m=B$=fl;)gp0w5h=kVgFEy%>zT==t#)Oswq zTr?{tmWGWFbDOksn&?;8ZO@~z1|4maoHqnx;)hZai1Oa97qKZ2`=>=Tqbi7E&k^Na zZ{=(CC~B6eo5t-^lBcfd9J7-)zKvBA>K}~;QMU(%+w1B)Tm0HTIfLh#lU;3Yn~+}d zUP0S|jo8kZ7+vu!d=$BZlVeRdZn#XTYejHx3KQ;O9%HU#dW(r^FcXBZC(y~Sm~%N} z2AJNk$S5a5XzSgPM7Rj`gO_&{#IQ+BaJI7%Cg(lRcrdBsB{DM zT8d*WSa9l7$|3s+xddzetVv2FvHpTmi>HO0ST5olCxQvl(GCf3Q9y&j7i|TuS52RC z$Mq$-RNqf4At8+FuTKP}#H=tDX#`r?5dsa5dEA@$R5+ZaAl)jTIpWtmtDot`nN#*n zhU~NvwXJ2@?Ng4=Ga)ngqKekQp9>riEd9DzgA}4BUwqIm0%Wss9jHUl$nKYqO;2N7 zknpSn9IQrcJR>i>8i4TbCiE{yOjELbLUDeF)~y3Xq^W(@CXkZSMd`R;HHADm=DLkJ zS;1I$?g$Acj(p>KT3D?`z_4LUo}Uvij?k=_H9S~+>bx^)AG{@fB`}K$xi6WJ!FPJGW zB~LoXg!SC`+S#|tF_WQeoMF^8u?W?f)9v=3VwpXM#@dD`br&6k3%WzaC(pjfR0`fM zChRRAn~rhB-s|T5e1XI1$7!j+-kyB4Yw?uPR@@9KfpTk%nATjRS13yeX_R>U?NRR* zYr(<$9=%ADVmjc*1V?@FRwNrtIjAjb6~xw zC-sWFLtc2tkj`HGvT-)9R$lY{zLj=HPa%BG;Eej@!{!SgZ7uQSkiTpuyam5P z5rGi-YQWO|GMX=FapkU`5NRBgpyZCbC47f9)TZ5%PIz1ivCfeoh~;Vbi@p|Pw7gM> zwb+um?aH84>hd{#m`B&9Hw?kAeS3;L=R7r;t*zfqC&7JCTJ}UUynqaE9fG)Oeo+9~ z<)#K&_ox+Nw&lB+9i|2E!p?w#If|`6#-*70{+ZT9cyNps75*mHJhbjb(M$RiL#Im7 zkt@=c&>5xhMt!=^u@mJ>AD$D_6u+1VyRkNNNm4B-5;&h9$MT0M8s71AN$h*tvfb!k&(H`x-=+RpQI>om@b>eBy%{M}3KN2#u_7ZsoV&Xy#uDxoRl2 zhZ9oKR?*q};PbY(m7gWgt{z{7YV^%w zc`Y^X^W2*`zFzR@pZ`FAYXD7ajJxrE>}I9XGO?tURZlH3Izhh)mjN#;L|i9=q<*Nz zeJ$l3es%o;Vkm2YSg0p_sEJfD;4905eJ~)3KL*>sr?_0fwyGKtmV*Mx?gOY(=^nPy z75*rmkv2($3TAtHYhv>G)jB4hBOwj?+DEI7B7nKguhhz2Yd1 z5R{LN%C|hj+rB0#%?eMKUp2KkGARiM^w%6HC3B_ajcD)SC*>BKm^LzSenJ0Ao&OwF zP*SjP9n;qLfKIW#zSsN6#KjQ=N9BF<<&EVWEqo{0Wy95oba_&mA2}DQZ?GFIAE4+$ zTSWyjBPuJ{I>+2{`XjGQUK|-8z?*tIei@>sC0eceal?yJ)H4CGLcpm&tzj$W8yN`# zWW`Z58t<@KB$*M=mUB3S1Ewuu;KvZt)Q44I^sc9(<6KD zz8jzDcL^6W2q>?&+~@GAhGm!bSVyKo4FcZIG@w+Qpt=z*Ug35;iTEV_r3KuuIY@AP z86i%AyiC(GJ?msLDzV2q&uEWf<036blx`(bK34rhL@TD$CD~KAPmc@j?tv4i(U$`9 zcWk#E6!Y?LEsmMJ0&nlU1XdZxd)a(3uMfNLXuUp;?^_>tzV(jaTa$0?-?6+ps6I8M z^B+WMTXsb|tcon?N_dCOn5B9n=!X7x%?0 zTWoPArre~5nAqwvGIZK;G@h1ctA0q9aR>+@?}8?$AnXuMICs=!+GRwXA9E?Tb*cs~c2&|aJbq|eJ7f#q| zoxW$gW$NCNCCs5dI)Z^%IkU1tA%66_qyJRWe0$h5=C+eor|YD9VtX=mo9i~)qd6;iM;BM3`Er9%Vbh*xkQP$9s^g?<6<&loxpnjh84ZhlM9LxMJBc zLXJ0K3!L}(&LVO@gM{JDV-#1QVN~`dv!T2 z2Qn;Li&$}sd(ekuw=gm4*!C?zfH%!{5U? zO_#Y7qV!K-j*(lr3xK97+d&CUgC{~Jh<6M)O$r&FwN{1 z20nbi=4jRBh^n!*wjSy8azByNjBI_hrIYM>2DjX@lKe#Cjb~HNQHwH_8rD&4I!0l; z_yD1aD4HlIRpaTe{;-Dp(o62$P92GK;Vp2_eF?x?niw86wX|gzR^&6S9>(;XlZu!P zg%R|xezBab&$a_p^tvy_W@JtUC?XN}cgE^{$r@Jj0O-eGw1y~*_g%tgOnARkghNuL z-{~{vK;QbpL8{T(kM6bO^)h}ux~es@-LTd;R=9)sxy<}5O;v>vrHj%91Z$l;<`Y(w zbdlOcHl_DeY2!3@#q;ILT9*;B7%PjE-TI@nj;lVk>o~L@x38XcbQ>sb4Q_ergjle2 z=1TP)RfEaI9>j4(%Pj#eMlOU;E^SAsx1HlY$8Ha+YL5x9-9of5SP~`Q!TTkHjuEe( z^@Be9fgW2rMRKH_{6?-ncAL`peXi#-uUai?&<79D<|qcq#{*VhfR0^Bu#$m}waU-a zf?oVYeZ&@3KR+@Wsj@7H(vYJuPF8)?g;g1qgAbPp;Ih|4hUftITYkRimR-QPGaWd7JcGhKSRpMGT&ZPF3KZi+UYK+VsaLymr zv>(Eeqzvw$N+M$wu# z>3e49=_k#bazg|41_rGVT0nT<(dcOP7(s1Ur0>eqr0e92dZHT8*{A<=?8f_)wMpo0 z{|aanXhtrN0z4$6y^uuRVHQ*`pV$MvaOW$EvoxJGG@+{pg z{B(^TDMUY~v>>L4)O#sr#wBegOIOE&*2iEbQW`BhEFF0u>@prRi!1xGtL|1g#KAS$ z2z`cSn6L;ja0_%*HV*2mK3AE;kjTw^YqTooD;21_$*D_&YbZt7kr0YIgDiIM+h3av zgXsG{{f0}-p6NrnC_K3|jZ}V2#|Q~}&q&yQGGhGuzGQpOxN92O13je4X(I|k==cr~ z){SHv(u91WcbB0wZRt+%i7bMlv;!;=?yyQRrb<4vGj{OKNm9nxng!4NsvZZwIjObb z@KC~nsdPY69@6BqZ5_xo2)t2U7f?&S-~;ZL?M-P+2NvUqJyv1rd0k&{^ggm|X#DvU zA1-EY8=0$XfC4GdfipYcF7$esav-K`gw%(SpA#*Orbj6niv@8kHC8^~J1)}`9(X#r zWe+dN@#5LahIxdUkkOvtdVCuX)hsK*ev-=yc~?~I&5QnUdA&FOi2aQH#JHqpMANea zI;p)iNmoZdlH(Y%N7`Q z$tJQ{7&y_+s7g)E&Jh({721M{ps2~O(9SBcraCmcZ0}dc5$rEJ!v9Pbl&6ubxH@S& ztYob|2_`2;c^Oa>H*AXv!H4p7jIMDi7;0~m>)a$fmh^tqSUKkGutJV0J%@winXVE} z1%Efz)uZZ}4@jH2eb^k(9K)`8{RrURx2bPm4BcAoetOQG1Yd9lGtN|#HSUjX16N>h zgp&z_RHqL2#CB%Ab+D{k$HbPfS>)o3Tge}(!1u2$?BrpEgXExq>_cGo??dcNzwR(V z`2az=)m9(}T9VsMQ)TcvTmoO*co=y?Ehmv68vM8`XAYc}We zjk&~={oCs$W&`ksP}g8;6e0#Qzfi1(I;sI<8?wAN#=S{q>b48Z8FtBqMe3Lo?t!EY z^itX@b~44Vwu5KIb~f1^NSYKTZoKLnZZe6uiSTR9JbuYG=>r+hd$|$O8?Z9?6eW!k zTvcHux%(;faiU}^r84lESQ4bMI=%MtQE>xOs(mCe>RrTGIvDfQnE0D5LQjK%wz@pq z{80dAMVzvl{BgUGwK)lIPb$1`LijJNSCwa+)WkhJcWqqlj9V`-C$fYU5EheRA zYafq_r_hB0^C}Z2UoB0XSs!8%AUq)yVUO) zwX6RI_&)zfJ?O}QN})B zszeLFN+26+QHH@RthaWS#8B>Gj$1KjY3qnj(efg95O48)}Hn;x28!H&jZ`_1+LeOo1{$L zw1a-o%V@mzgD3f2q79xeeEC1aKOyC7B61gS*S?_Zh`&^p>&?}@RO{q0!(DW^ec6;M zYT#36iu`t^u4YK394UnkPHrG6(vS#2#W7^a)DseTl(SK{_mRx$SSO(;R_bGn<;tZ{ z)`77$`ig8YMyqtHF!Oe^VW=Tk_L10)5Fg6Lmp5r4<(4)Vuimrx8er5B(n2pC(7r5? z#p<4o`2yc+!ZWADaFv&@35Yi_ve!%T@*JOz%$|SD0Vg&dWx_ie8OD<1#3l8(_F|Jo zCmXF1Uv%5xfF-Fk3?4k)4sbvl&!T!idJn0sbY#s!A+COh21I8hGu6fXK(MHhwc<^7 zjk#}tUy&wBpV8PzVY|f#+K#Y!YbCTm*g~AP zgs!E>RURoH8CYZ1E6;(H%K|7or+2N9^-bbqr-9b9nv)Xdd--LXSApu89O>+r&{j(e zsoCK3=YM5>U@;s1%m%t8n8Ez6Tl$-szkla^0A(mQvov>gGWtbU4d3`(1<+GX_por* zJEnKK!ZAfXWakj?oanK>w98Y9u$CH^O}GD3ny%d#s%lo*wAAtBn7P_V4@?f6B`EFdP27|nUbv{J6fxz z&di#|ozz#*%c7NKR-|Rr$zJ`G^W7UZb$KrG$#u0iQ!4Pom1;dBDrR`K5>p%fuIim| z)uO7-JkL@}EF$p2sMc%(@TkgyPCk7K`eakofj`y_h6>Tv{FFOv?|n8K1nWY~c$J7O zo$OnJ8VwVPt8`m#*V2+6*PL2&p-b36MazIZ^`hSGmUdct9ltF~lGm8yY_CPrcVPqF zbm=0sw{Pc%=v4NPkOWx#dk#Lxd4?Z0s9pr?U_k))RlmZg8}zO3szcme$P5m32;ToK?74f|_(j%4_CBhdvdOZ zAAS*wBz1AnzmDxfU@^OsTn#5a;%Jrku_al3e{

1bvi{DS7E@q1{$_8->K{_OWv2 zCZTgG2Pr3n8|ec9kIu&uC|d?k4-cQ4#}Z`qDX5Y2mhC(jR1Ms;UG4Ho$DE|+SeJ@{ zJQQhAXj|<)*t3KiOWTuh{Wd^mS{u{&ERV)OpZwiQ%#1->r9p zSK_^*U~=?ywH~4IUxb}{0J!SmL!z2Tzq_PpetoC^_az1JFg0=gMcQADuOP%3=H1hH zH_=dG(PD;d*037Ov5G1924U#Zns?~fs+eh1%-bWqa%ssm3=nio1r3J<4G0IBETtr? zycs~0JIOn;MecYG=~OQsYHIrf?~A5>_ob%8+uOrVA+VCJw}{lygrBBdY1k<8B^wf6 zl|<%N$7)fOZX$%y>4ueco_Gb1H@B%XrKVwrn6hUOecnc^PU0rFuCB5=*2;|u-`o(@ zL*tr4bnQzXYLc4XqFbv5sK0}A)`}`8iM8ehtj#Oc5DrE;0VxbPmL@BUa_BQwa$EW~sU#-LP0?sGmqfUGhGWcciGZ*4(}u3z=@b>Ow9DQe7lcO3K}BG3j(t& zH10>sK!&4Q5-=gN@Nxj6{|*nuyqw7KZJ1?p)NUJ?U0bOigGdsOk}Iz&9PmN_5=W*Z9M zy^pA`&dX0oo6?CSuhE~(pYbLuTPp1a1Fa@e3Lu&mmgd$;D}&g-i=D-{sv?J9kIr9r zrX&Z)aFGK^kNY{LxrotP0}k*;uN12i_2a_JJhKwh zBt{D-JRxC$8U+-`u1xD>gJ^H4lbW;7spI-=H506i=ncdK;xq*L6f7jVz$XGMg5aQk zHRJY&$@g}i_SP##iC?lR?ltnWUTT-UDlq(*BTQaYNkg zNG#sNoo{WmP+Vl}U~?+T?g25b$E-7iwhu=VVgw3JdFXm~ba+LC4p>CP3~rNTiNBl7 zL{RfLLepNPEtZj}yL_#R{(^MqIlG)c0Va}>U|9Pl&B_3tV;Ps{r)WqBznD7FcTlP4 z`JQe2DvGhmeeHGGX39zGyOOxZ3tq~Dft(BQ;mDXwwJi?sBtxo$Gf1SS2w*eQ0p&RVMNVi@d zY8v4J0(n}%6*Rw(g~l@sUuxpiJ*Y}7TzBQyU+>-qWm*InUeGt@)T9g^0J#z4){Lw* zT;69if~U9DXBR9fgVPlYy7aDhJU)gDC?_GHQtwa6QXNaah7-CzA|Fx-lH7d@N9>38 zX(F&fd3w7AkZ+ha8-gKfX%@_~<#HDs?kBg5zW>V3%Xw5jwPs6uni{7r zd`EfPYrA*SU;xDtm@E>5TrJKlg5o=h;NSXk)pt4K)GbpP0xkUg>2o|oG=`UnX7^Un zb&@8d6Fj1cBWW^c(K#Csc8xEBa4KfHY>8Lp^77-lhzgWr9kR9_p+g|-9r?VSv?qA%^1O;cqgke)%AqHlR$B{!Y1Mq zj|)Ecg?{_!>kGDAwGa7%cwSUb{BcayJihkv$}ql+yu=O}jVvAFdC{Hjh$4}u+$mx% z5V$sUiGCX%D3A>bKwY8HR)Gv*lisI4q^3vJ*nDwj|mtr!0r!~+Qoe2cw^jPCXkT7tI*01|w@ z&gPC`?O1w7hQ%=&bcHi7(fqhY3${~JepA7y@^aLwHpew^Yk$;R4v{ASHjXjXtaTc_ zuz5*nXB&PrcyWx#gQ%?HyxawmS+Wu(7ssvB1UMh!1$to&o(mv_f=9~!9@VsJCGxpu z`>g5Sp=xDhpsiCy^y>=fI0DON$&pb7o7^d{@@&hj3!6PUd=vA;G;#7&8ChamsE{`^ zY8pDra8Jntp62Ivi)Y`*XbpM60s06v@Rz^-g)TW_F@B!~y7!4AJ>37mAuz!(!C+xQ zSR61?u!{N|qHWOeR%$RXRL~vpN0SGri7-klNHEJuivbi=0qSbdV4&ghf4i|7?$>z( zI{qH?i}`~a7GyB6|8pZRq982+P*r1+m-t&(%U5#ZWFQd-(CXKLHeN@y(c z;wqq1hzE@q1b$GG0VQ_)`{MeylBlVfy%UHR=;Z98>T3M&;{0i?+0T-Bck?I)AUQrz zeF**_iGu$JlCpLnFv`D9?q6R51jKPM{Rd6!0FF#KP=O|b3iQX*TqXSjO?gXaXAmLr zU#g&%@+XpjVArlGkfaPKk^PUSnMLsjlK<9nH*zxl^V2-jGC$4+HGE%?F3%4|y9>HN z|FJgz*HW$VwU8$RNtuBf(2vdZhW3x;R6%eoJM(|2zvKebxCh$s5J-*fhZ75B_yeUs zFTrToFiB^SNH?gV2>l?G&h!UD>UP%uKh1L;Er59!q&NoZRe$VEf?5Ar^&iUad&2gQ z&WE`E%lTg=_3XQT@gJOjkAi-Hbbqrl{(pA<>_GH4O8+xI^=IAhS#v+$vmgOK=>C!~_xFg-pLM>6kUfy=zL|u~KkNJ< z$L?p*?;%(Ze6w%%M(zjE|4dH&5$)_}mG3z{KUQ6s!Y@_+kInPH;kAC&{T^5HKmqz@ z@+!aA{YNIy&r;uKTz=r6e6v>d-%9<%_4R!+-iN^8H#0N(rQbiu-u&}-|2`q@k1agM zdHkW_1&%VDD_|I;NpK*OZfAjAb z`Ttl8km0{|{F`kWKWltH$^Ech;G2y`{7&N^%H;d0$cGv7Z^oJNOSiwAFaP<=em}wX z<8AA6<}bbeZc_7S=ii6PALi)3nOXL)o&Uj%-OnQ52M&L%(%ZaWiu^(R{b!Bu2WJl< h$Zw`p^gE5e2}ml*LW4$nU|{5+pXG<~Ugg7I{||-5t(pJ; literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/install.sh b/install.sh deleted file mode 100755 index 09027d2..0000000 --- a/install.sh +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -source ./scripts/install-util.sh - -prompt server_port "MediaGarrd-Server host port [$PORT_DEFAULT]: " "$PORT_DEFAULT" -prompt backup_interval "Server automatic backup interval in ISO-8601 format [$INTERVAL_DEFAULT]: " "$INTERVAL_DEFAULT" -prompt backup_root_host "Server backup host path [$BACKUP_LOC_DEFAULT]: " "$BACKUP_LOC_DEFAULT" -prompt backup_retention "Maximum number of backups to keep [$BACKUP_RETENTION_DEFAULT]: " "$BACKUP_RETENTION_DEFAULT" - -yes_no jellyfin_enabled "Enable Jellyfin backups? [Y/n]: " "y" -if [[ "$jellyfin_enabled" == "true" ]]; then - prompt jellyfin_path "Jellyfin source base directory [$DEFAULT_APPDATA_DIR/jellyfin]: " "$DEFAULT_APPDATA_DIR/jellyfin" -fi - -yes_no radarr_enabled "Enable Radarr backups? [Y/n]: " "y" -if [[ "$radarr_enabled" == "true" ]]; then - prompt radarr_path "Radarr source base directory [$DEFAULT_APPDATA_DIR/radarr]: " "$DEFAULT_APPDATA_DIR/radarr" -fi - -yes_no sonarr_enabled "Enable Sonarr backups? [Y/n]: " "y" -if [[ "$sonarr_enabled" == "true" ]]; then - prompt sonarr_path "Sonarr source base directory [$DEFAULT_APPDATA_DIR/sonarr]: " "$DEFAULT_APPDATA_DIR/sonarr" -fi - -yes_no prowlarr_enabled "Enable Prowlarr backups? [Y/n]: " "y" -if [[ "$prowlarr_enabled" == "true" ]]; then - prompt prowlarr_path "Prowlarr source base directory [$DEFAULT_APPDATA_DIR/prowlarr]: " "$DEFAULT_APPDATA_DIR/prowlarr" -fi - -yes_no tdarr_enabled "Enable Tdarr backups? [Y/n]: " "y" -if [[ "$tdarr_enabled" == "true" ]]; then - prompt tdarr_path "Tdarr source base directory [$DEFAULT_APPDATA_DIR/tdarr]: " "$DEFAULT_APPDATA_DIR/tdarr" -fi - -yes_no qbittorrent_enabled "Enable qBittorrent backups? [Y/n]: " "y" -if [[ "$qbittorrent_enabled" == "true" ]]; then - prompt qbittorrent_path "qBittorrent source base directory [$DEFAULT_APPDATA_DIR/qbittorrent]: " "$DEFAULT_APPDATA_DIR/qbittorrent" - - yes_no has_saved_torrents "Would you like to add an additional path for stored .torrent files? [Y/n]: " "n" - if [[ "$has_saved_torrents" == "true" ]]; then - prompt qbittorrent_saved_torrents_path "qBittorrent saved-torrents source directory [$MNT_DIR/torrents]: " "$MNT_DIR/torrents" - fi -fi - -{ - cat < "$ENV_FILE" - -{ - cat < "$SERVER_ENV_FILE" - - rm -f "$CLIENT_ENV_FILE" - -{ - cat < "$COMPOSE_FILE" - -echo "" -echo "Created: $COMPOSE_FILE" -echo "Created: $ENV_FILE" -echo "Created: $SERVER_ENV_FILE" -echo "" -echo "Next steps:" -echo "1. Review .env" -echo "2. Review dockerenv/server.env" -echo "3. Review docker-compose.yml" -echo "4. Start services with: docker compose up --build -d" diff --git a/ref/services/ADD_NEW_SERVICE.md b/ref/services/ADD_NEW_SERVICE.md deleted file mode 100644 index 0b2c454..0000000 --- a/ref/services/ADD_NEW_SERVICE.md +++ /dev/null @@ -1,16 +0,0 @@ -# Adding a new service - -The following is the process for adding support for a new service. - -## Open an issue -Go the [issues page](https://github.com/MediaGarrd/Server/issues) and use the template for `New Service Request`. - -## Contributing -If there is an existing issue for the service you want and it has a `Status: Approved` label on it, a PR can be opened. Be sure to read the [CONTRIBUTING.md](../../CONTRIBUTING.md) guide before starting any changes. - -### Implementation -When adding a new service to the project, doing the following will make it easy: -```bash -rg //@ADD_NEW_SERVICE -``` -in the repository root to identify the files that require changes to support a new service. These files will always require modification when adding a new service, but there may be more to do depending on the implementation. diff --git a/ref/services/SUPPORTED_SERVICES b/ref/services/SUPPORTED_SERVICES deleted file mode 100644 index 659cab9..0000000 --- a/ref/services/SUPPORTED_SERVICES +++ /dev/null @@ -1,8 +0,0 @@ -//@ADD_NEW_SERVICE - -Jellyfin -Prowlarr -QBittorrent -Radarr -Sonarr -Tdarr diff --git a/scripts/dry_test.sh b/scripts/dry_test.sh new file mode 100755 index 0000000..55e5d7f --- /dev/null +++ b/scripts/dry_test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +DRY_DIR=vendor/dry4java + +JAR="$DRY_DIR/target/dry4java-0.1.0-SNAPSHOT.jar" +LONG_THRESHOLD=10 +read -r groups locations long < <( + java -jar "$JAR" ./src | tee /dev/stderr | awk -v thr="$LONG_THRESHOLD" ' + /^DUPLICATE/ { g++; next } + match($0, /:[0-9]+-[0-9]+/) { + split(substr($0, RSTART+1, RLENGTH-1), r, "-") + if (r[2] - r[1] + 1 > thr) l++ + n++ + } + END { print g+0, n+0, l+0 }' +) +echo "duplicate groups: $groups, long blocks: $long" +GROUP_THRESHOLD=5 +(( groups > GROUP_THRESHOLD )) && { echo "Too many duplicate groups"; exit 1; } +(( long > LONG_THRESHOLD )) && { echo "Too many long duplicates"; exit 2; } +exit 0 diff --git a/scripts/install-util.sh b/scripts/install-util.sh deleted file mode 100644 index 4e881f7..0000000 --- a/scripts/install-util.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DOCKERENV_DIR="$ROOT_DIR/dockerenv" -COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" -ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$DOCKERENV_DIR/server.env" -CLIENT_ENV_FILE="$DOCKERENV_DIR/client.env" - -PORT_DEFAULT="38471" -INTERVAL_DEFAULT="PT12H" -BACKUP_LOC_DEFAULT="./data/server/backups" -BACKUP_RETENTION_DEFAULT="10" - -MNT_DIR="/mnt" -DEFAULT_APPDATA_DIR="$MNT_DIR/appdata" - -mkdir -p "$DOCKERENV_DIR" - -prompt() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-}" - local value="" - - read -r -p "$prompt_text" value - if [[ -z "$value" ]]; then - value="$default_value" - fi - - printf -v "$var_name" '%s' "$value" -} - -yes_no() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-y}" - local response - - read -r -p "$prompt_text" response - response="${response:-$default_value}" - if [[ "$response" =~ ^[Yy]([Ee][Ss])?$ ]]; then - printf -v "$var_name" 'true' - else - printf -v "$var_name" 'false' - fi -} - diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java index 9f32db2..261d170 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java @@ -3,8 +3,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.DefaultDockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; +import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; + @SpringBootApplication @EnableScheduling @EnableConfigurationProperties(MediaGarrdProperties.class) @@ -13,4 +19,14 @@ public class MediaGarrd { public static void main(String[] args) { SpringApplication.run(MediaGarrd.class, args); } + + @Bean + DockerClient dockerClient() { + var config = DefaultDockerClientConfig.createDefaultConfigBuilder().build(); + var httpClient = new ApacheDockerHttpClient.Builder() + .dockerHost(config.getDockerHost()) + .sslConfig(config.getSSLConfig()) + .build(); + return DockerClientImpl.getInstance(config, httpClient); + } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java deleted file mode 100644 index b3f0784..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; - -public class MediaGarrdConfig { - - public static MediaGarrdConfig buildConfigFromRequest(ConfigUpdateRequest request) { - // TODO: Not yet implemented - return new MediaGarrdConfig(); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 15d62b2..26a2705 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -1,14 +1,11 @@ package wellatleastitried.mediagarrdServer; import java.time.Duration; -import java.util.EnumMap; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Getter; import lombok.Setter; -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; @Getter @Setter @@ -16,14 +13,8 @@ public class MediaGarrdProperties { private Duration backupInterval = Duration.ofHours(12); - private String backupRoot = "./data/server/backups"; + private String backupRoot = "/var/lib/mediagarrd/backups"; private int retentionCount = 10; - private ServicesProperties services = new ServicesProperties(); - private MediaGarrdConfig config = new MediaGarrdConfig(); - - public EnumMap getServiceConfigs() { - return services.toRuntimeConfigs(); - } - - + private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; + private String helperImage = "busybox:stable"; } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java deleted file mode 100644 index d4eaaba..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/ServicesProperties.java +++ /dev/null @@ -1,85 +0,0 @@ -package wellatleastitried.mediagarrdServer; - -import java.util.EnumMap; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class ServicesProperties { - - //@ADD_NEW_SERVICE - private CommonServiceConfig jellyfin; - private CommonServiceConfig radarr; - private CommonServiceConfig sonarr; - private CommonServiceConfig prowlarr; - private CommonServiceConfig tdarr; - private QBittorrentServiceConfig qbittorrent; - - public EnumMap toRuntimeConfigs() { - EnumMap configs = new EnumMap<>(Services.class); - put(configs, Services.JELLYFIN, jellyfin); - put(configs, Services.RADARR, radarr); - put(configs, Services.SONARR, sonarr); - put(configs, Services.PROWLARR, prowlarr); - put(configs, Services.TDARR, tdarr); - put(configs, Services.QBITTORRENT, qbittorrent); - return configs; - } - - private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { - if (config != null) { - configs.put(service, config); - } - } - - public CommonServiceConfig getJellyfin() { - return jellyfin; - } - - public void setJellyfin(CommonServiceConfig jellyfin) { - this.jellyfin = jellyfin; - } - - public CommonServiceConfig getRadarr() { - return radarr; - } - - public void setRadarr(CommonServiceConfig radarr) { - this.radarr = radarr; - } - - public CommonServiceConfig getSonarr() { - return sonarr; - } - - public void setSonarr(CommonServiceConfig sonarr) { - this.sonarr = sonarr; - } - - public CommonServiceConfig getProwlarr() { - return prowlarr; - } - - public void setProwlarr(CommonServiceConfig prowlarr) { - this.prowlarr = prowlarr; - } - - public CommonServiceConfig getTdarr() { - return tdarr; - } - - public void setTdarr(CommonServiceConfig tdarr) { - this.tdarr = tdarr; - } - - public QBittorrentServiceConfig getQbittorrent() { - return qbittorrent; - } - - public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { - this.qbittorrent = qbittorrent; - } - -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java new file mode 100644 index 0000000..2d12820 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java @@ -0,0 +1,28 @@ +package wellatleastitried.mediagarrdServer; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import wellatleastitried.mediagarrdServer.api.SetupInterceptor; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final SetupInterceptor setupInterceptor; + + public WebMvcConfig(SetupInterceptor setupInterceptor) { + this.setupInterceptor = setupInterceptor; + } + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/config").setViewName("forward:/config.html"); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(setupInterceptor); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java new file mode 100644 index 0000000..fb33dbc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.util.Map; +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.BackupInProgressException; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.RunRejectedException; + +@RestControllerAdvice +public class ApiExceptionHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class); + + @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) + public ResponseEntity> handle(RuntimeException e) { + HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST + : e instanceof RunRejectedException || e instanceof BackupInProgressException ? HttpStatus.CONFLICT + : HttpStatus.INTERNAL_SERVER_ERROR; + if (status.is5xxServerError()) { + LOGGER.error("Request failed: {}", e.getMessage()); + } else { + LOGGER.warn("Rejected request: {}", e.getMessage()); + } + return error(status, e.getMessage()); + } + + static ResponseEntity> error(HttpStatus status, String message) { + return ResponseEntity.status(status).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index ecaca2d..1ca9085 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -24,7 +24,6 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.dto.BackupDto; import wellatleastitried.mediagarrdServer.dto.BackupRunDto; import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; @@ -42,27 +41,16 @@ public class BackupController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestratorService; - private final MediaGarrdProperties properties; - public BackupController( - BackupArchiveService archiveService, - BackupOrchestratorService orchestratorService, - MediaGarrdProperties properties - ) { + public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService) { this.archiveService = archiveService; this.orchestratorService = orchestratorService; - this.properties = properties; } @GetMapping("/health") public ServerStatusDto health() { LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - orchestratorService.getInterval() - ); + return status(orchestratorService.getInterval()); } @PutMapping("/schedule") @@ -70,12 +58,7 @@ public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); Duration updated = orchestratorService.updateInterval(request.backupInterval()); LOGGER.info("Schedule updated: newInterval={}", updated); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - updated - ); + return status(updated); } @GetMapping("/backups") @@ -168,6 +151,10 @@ private ResponseEntity downloadResponse(BackupArchive archive) { } } + private ServerStatusDto status(Duration interval) { + return new ServerStatusDto(true, orchestratorService.isRunning(), archiveService.retentionCount(), interval); + } + private BackupDto toDto(BackupArchive archive) { return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java index 0497292..d1ca6d1 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -1,46 +1,128 @@ package wellatleastitried.mediagarrdServer.api; +import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; + +import java.util.List; +import java.util.Optional; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import wellatleastitried.mediagarrdServer.MediaGarrdConfig; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; import wellatleastitried.mediagarrdServer.dto.ServerConfigDto; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.service.DockerService; @RestController -@RequestMapping ("/api/v1") +@RequestMapping("/api/v1") public class ConfigController { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class); - private final MediaGarrdProperties properties; + private final BackupArchiveService archiveService; + private final BackupOrchestratorService orchestrator; + private final DatabaseService db; + private final DockerService docker; public ConfigController( - MediaGarrdProperties properties + BackupArchiveService archiveService, + BackupOrchestratorService orchestrator, + DatabaseService db, + DockerService docker ) { - this.properties = properties; + this.archiveService = archiveService; + this.orchestrator = orchestrator; + this.db = db; + this.docker = docker; } @GetMapping("/config") public ServerConfigDto config() { LOGGER.info("GET /api/v1/config"); - return new ServerConfigDto( - properties.getConfig() - ); + return currentConfig(); } - @PostMapping("/config/update") + @PutMapping("/config") public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { - LOGGER.info("GET /api/v1/config"); - var config = MediaGarrdConfig.buildConfigFromRequest(request); - properties.setConfig(config); + LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", request.backupLocation(), request.retentionCount()); + return orchestrator.whileIdle(() -> { + archiveService.updateSettings(request.backupLocation(), request.retentionCount()); + return currentConfig(); + }); + } + + @GetMapping("/services") + public List services() { + LOGGER.info("GET /api/v1/services"); + return db.fetchServices(); + } + + @PostMapping("/services") + public ResponseEntity addService(@RequestBody ServiceDefinition request) { + ServiceDefinition service = request.validate(); + LOGGER.info("POST /api/v1/services, name={}, paths={}", service.name(), service.paths()); + return orchestrator.whileIdle(() -> { + if (db.fetchService(service.name()).isPresent()) { + return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); + } + db.addService(service); + return ResponseEntity.status(HttpStatus.CREATED).body(service); + }); + } + + @PutMapping("/services/{name}") + public ResponseEntity updateService(@PathVariable String name, @RequestBody ServiceDefinition request) { + ServiceDefinition service = request.validate(); + LOGGER.info("PUT /api/v1/services/{}, name={}, paths={}", name, service.name(), service.paths()); + return orchestrator.whileIdle(() -> { + Optional existing = db.fetchService(name); + if (existing.isEmpty()) { + return error(HttpStatus.NOT_FOUND, "Service not found: " + name); + } + String currentName = existing.get().name(); + if (!service.name().equalsIgnoreCase(currentName) && db.fetchService(service.name()).isPresent()) { + return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); + } + db.updateService(currentName, service); + if (!service.name().equals(currentName)) { + docker.removeContainers(currentName); + } + return ResponseEntity.ok(service); + }); + } + + @DeleteMapping("/services/{name}") + public ResponseEntity removeService(@PathVariable String name) { + LOGGER.info("DELETE /api/v1/services/{}", name); + return orchestrator.whileIdle(() -> { + Optional existing = db.fetchService(name); + if (existing.isEmpty()) { + return error(HttpStatus.NOT_FOUND, "Service not found: " + name); + } + db.removeService(existing.get().name()); + docker.removeContainers(existing.get().name()); + return ResponseEntity.noContent().build(); + }); + } + + private ServerConfigDto currentConfig() { return new ServerConfigDto( - properties.getConfig() + archiveService.rootDirectory().toString(), + archiveService.retentionCount(), + orchestrator.getInterval() ); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java new file mode 100644 index 0000000..e02d508 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java @@ -0,0 +1,79 @@ +package wellatleastitried.mediagarrdServer.api; + +import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; +import static wellatleastitried.mediagarrdServer.api.SetupInterceptor.SESSION_COOKIE; + +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdServer.dto.SetupSessionRequest; +import wellatleastitried.mediagarrdServer.dto.SetupStatusDto; +import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@RestController +@RequestMapping("/api/v1/setup") +public class SetupController { + + private static final Logger LOGGER = LoggerFactory.getLogger(SetupController.class); + + private final SetupService setup; + private final DatabaseService db; + + public SetupController(SetupService setup, DatabaseService db) { + this.setup = setup; + this.db = db; + } + + @GetMapping + public SetupStatusDto status(HttpServletRequest request) { + return new SetupStatusDto(setup.isCompleted(), setup.canConfigure(SetupInterceptor.sessionToken(request))); + } + + @PostMapping("/session") + public ResponseEntity startSession(@RequestBody SetupSessionRequest request) { + LOGGER.info("POST /api/v1/setup/session"); + if (setup.isCompleted()) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + Optional session = setup.startSession(request.pin()); + if (session.isEmpty()) { + return error(HttpStatus.UNAUTHORIZED, "Invalid PIN, check the server logs for the current PIN"); + } + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie(session.get(), -1).toString()).build(); + } + + @PostMapping("/complete") + public ResponseEntity complete() { + LOGGER.info("POST /api/v1/setup/complete"); + if (setup.isCompleted()) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + if (db.fetchServices().isEmpty()) { + return error(HttpStatus.CONFLICT, "Add at least one service before finishing setup"); + } + setup.complete(); + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", 0).toString()).build(); + } + + private static ResponseCookie cookie(String value, long maxAgeSeconds) { + return ResponseCookie.from(SESSION_COOKIE, value) + .httpOnly(true) + .sameSite("Strict") + .path("/") + .maxAge(maxAgeSeconds) + .build(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java new file mode 100644 index 0000000..354fbbb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Component +public class SetupInterceptor implements HandlerInterceptor { + + static final String SESSION_COOKIE = "mediagarrd-setup"; + private static final List SETUP_PAGE_PATHS = List.of("/config", "/config.html", "/css/", "/js/"); + private static final List CONFIG_API_PATHS = List.of("/api/v1/config", "/api/v1/services", "/api/v1/setup/complete"); + + private final SetupService setup; + + public SetupInterceptor(SetupService setup) { + this.setup = setup; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + String path = request.getRequestURI(); + if (matches(path, SETUP_PAGE_PATHS) && setup.isCompleted()) { + response.sendError(HttpStatus.NOT_FOUND.value()); + return false; + } + if (matches(path, CONFIG_API_PATHS) && !setup.canConfigure(sessionToken(request))) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write("{\"error\":\"Setup session required, reload /config and enter the PIN from the server logs\"}"); + return false; + } + return true; + } + + static String sessionToken(HttpServletRequest request) { + Cookie[] cookies = request.getCookies(); + if (cookies == null) { + return null; + } + return Arrays.stream(cookies) + .filter(cookie -> SESSION_COOKIE.equals(cookie.getName())) + .map(Cookie::getValue) + .findFirst() + .orElse(null); + } + + private static boolean matches(String path, List prefixes) { + return prefixes.stream().anyMatch(prefix -> prefix.endsWith("/") + ? path.startsWith(prefix) + : path.equals(prefix) || path.startsWith(prefix + "/")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java index 59ab359..4e576b1 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java @@ -1,4 +1,3 @@ package wellatleastitried.mediagarrdServer.dto; -// TODO: Determine what fields will be passed -public record ConfigUpdateRequest() {} +public record ConfigUpdateRequest(String backupLocation, Integer retentionCount) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java index d6def7e..028618d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java @@ -1,5 +1,5 @@ package wellatleastitried.mediagarrdServer.dto; -import wellatleastitried.mediagarrdServer.MediaGarrdConfig; +import java.time.Duration; -public record ServerConfigDto(MediaGarrdConfig config) {} +public record ServerConfigDto(String backupLocation, int retentionCount, Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java new file mode 100644 index 0000000..3071eaa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupSessionRequest(String pin) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java new file mode 100644 index 0000000..59d6f77 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupStatusDto(boolean completed, boolean authorized) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index 3ff5942..4f1bb69 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -1,11 +1,14 @@ package wellatleastitried.mediagarrdServer.model; import java.io.IOException; -import java.math.BigInteger; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.security.DigestInputStream; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.HexFormat; public record BackupArchive( String id, @@ -15,25 +18,11 @@ public record BackupArchive( Instant createdAt ) { public String generateChecksum() { - try { - byte[] data = Files.readAllBytes(path); - byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); - String checksum = new BigInteger(1, hash).toString(16); - return checksum; - } catch (Exception e) {} - return ""; - } - - public int fileSize() { - long size; - try { size = Files.size(path); } - catch (IOException iE) { size = 0; } - - if (size > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; + try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), MessageDigest.getInstance("SHA-256"))) { + in.transferTo(OutputStream.nullOutputStream()); + return HexFormat.of().formatHex(in.getMessageDigest().digest()); + } catch (IOException | NoSuchAlgorithmException e) { + return ""; } - - return (int) size; - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java new file mode 100644 index 0000000..715364c --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java @@ -0,0 +1,44 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +public record ServiceDefinition(String name, List paths) { + + private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); + + public ServiceDefinition { + name = name == null ? "" : name.strip(); + paths = paths == null ? List.of() : paths.stream() + .filter(Objects::nonNull) + .map(String::strip) + .filter(path -> !path.isEmpty()) + .map(path -> path.startsWith("/") ? Path.of(path).normalize().toString() : path) + .distinct() + .toList(); + } + + public ServiceDefinition validate() { + if (!VALID_NAME.matcher(name).matches()) { + throw new IllegalArgumentException( + "Service name must be 1-64 characters of letters, digits, '.', '_' or '-' and start with a letter or digit"); + } + if (paths.isEmpty()) { + throw new IllegalArgumentException("Service '" + name + "' needs at least one path"); + } + for (String path : paths) { + if (!path.startsWith("/")) { + throw new IllegalArgumentException("Path must be absolute: " + path); + } + if (path.equals("/")) { + throw new IllegalArgumentException("Path must not be the filesystem root"); + } + if (path.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Path must not contain control characters: " + path); + } + } + return this; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index a8911a3..ca4f5f8 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -1,24 +1,29 @@ package wellatleastitried.mediagarrdServer.service; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_ROOT_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; + import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; 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.List; import java.util.Optional; +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 java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; +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; @@ -35,13 +40,22 @@ public class BackupArchiveService { private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") .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 final MediaGarrdProperties properties; + private final DatabaseService db; private final AtomicReference> cachedArchives = new AtomicReference<>(null); private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); - - public BackupArchiveService(MediaGarrdProperties properties) { - this.properties = properties; + private volatile Path root; + private volatile int retentionCount; + + public BackupArchiveService(MediaGarrdProperties properties, DatabaseService db) { + this.db = db; + this.root = Path.of(db.fetchSetting(BACKUP_ROOT_SETTING).orElse(properties.getBackupRoot())) + .toAbsolutePath() + .normalize(); + this.retentionCount = db.fetchSetting(RETENTION_COUNT_SETTING) + .flatMap(BackupArchiveService::parseRetention) + .orElse(Math.max(1, properties.getRetentionCount())); } @PostConstruct @@ -91,26 +105,70 @@ public void cleanupStaleArtifactsOnStartup() { } public Path rootDirectory() { - return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); + return root; + } + + public int retentionCount() { + return retentionCount; + } + + public synchronized void updateSettings(String location, Integer retention) { + if (location == null && retention == null) { + throw new IllegalArgumentException("Nothing to update, provide backupLocation and/or retentionCount"); + } + if (retention != null && retention < 1) { + throw new IllegalArgumentException("Retention count must be at least 1"); + } + if (location != null) { + updateRootDirectory(location); + } + if (retention != null) { + db.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); + retentionCount = retention; + LOGGER.info("Retention count changed to {}, applied on the next backup run", retention); + } + } + + public Path updateRootDirectory(String location) { + if (location == null || location.isBlank()) { + throw new IllegalArgumentException("Backup location is required"); + } + Path requested = Path.of(location.strip()); + if (!requested.isAbsolute()) { + throw new IllegalArgumentException("Backup location must be an absolute path"); + } + Path normalized = requested.normalize(); + try { + Files.createDirectories(normalized); + } catch (IOException | SecurityException e) { + throw new IllegalArgumentException("Unable to create backup location " + normalized); + } + if (!Files.isWritable(normalized)) { + throw new IllegalArgumentException("Backup location is not writable: " + normalized); + } + + db.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); + root = normalized; + invalidateCache(); + LOGGER.info("Backup location changed to {}", normalized); + return normalized; } public BackupArchive createArchive(Path runDirectory) { Instant createdAt = Instant.now(); - String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; + String fileName = FILE_DATE_FORMAT.format(createdAt) + ARCHIVE_SUFFIX; Path root = rootDirectory(); Path archivePath = root.resolve(fileName); LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); try { Files.createDirectories(root); - zipDirectory(runDirectory, archivePath); + mergeParts(runDirectory, archivePath); enforceRetention(); long size = Files.size(archivePath); LOGGER.info("Archive created: {} ({} bytes)", fileName, size); - // Invalidate cache after new archive created - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); + invalidateCache(); return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); } catch (IOException e) { @@ -132,20 +190,11 @@ public List listArchives() { } // Cache miss -> rebuild list - Path root = rootDirectory(); List archives; - if (!Files.exists(root)) { - archives = List.of(); - } else { - try (var stream = Files.list(root)) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .map(this::toArchive) - .toList(); - } catch (IOException e) { - throw new IllegalStateException("Failed to list archives", e); - } + try { + archives = scanArchives(); + } catch (IOException e) { + throw new IllegalStateException("Failed to list archives", e); } cachedArchives.set(archives); @@ -170,10 +219,9 @@ public boolean deleteById(String id) { try { Files.deleteIfExists(archive.get().path()); + db.deleteBackupRecordById(id); LOGGER.info("Archive deleted: {}", id); - cacheLastUpdatedMs.set(0); - - cachedArchives.set(null); + invalidateCache(); return true; } catch (IOException e) { @@ -211,43 +259,74 @@ public void removeRunDirectory(Path runDirectory) { } private void enforceRetention() throws IOException { - int retain = Math.max(1, properties.getRetentionCount()); - List archives; - try (var stream = Files.list(rootDirectory())) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .toList(); + List archives = scanArchives(); + for (BackupArchive archive : archives.subList(Math.min(retentionCount, archives.size()), archives.size())) { + LOGGER.info("Retention: deleting old archive: {}", archive.fileName()); + Files.deleteIfExists(archive.path()); + db.deleteBackupRecordById(archive.id()); } - for (int i = retain; i < archives.size(); i++) { - Path toDelete = archives.get(i); - LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); - Files.deleteIfExists(toDelete); + } + + private List scanArchives() throws IOException { + Path root = rootDirectory(); + if (!Files.exists(root)) { + return List.of(); + } + try (var stream = Files.list(root)) { + return stream + .filter(path -> path.getFileName().toString().endsWith(ARCHIVE_SUFFIX)) + .map(this::toArchive) + .sorted(Comparator.comparing(BackupArchive::createdAt).reversed()) + .toList(); } } - private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { - Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); - try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - ZipOutputStream zipOut = new ZipOutputStream(fileOut); - var paths = Files.walk(sourceDir)) { + private void invalidateCache() { + cacheLastUpdatedMs.set(0); + cachedArchives.set(null); + } - paths.filter(Files::isRegularFile).forEach(path -> { - Path relative = sourceDir.relativize(path); - try { - zipOut.putNextEntry(new ZipEntry(relative.toString())); - try (InputStream in = Files.newInputStream(path)) { - in.transferTo(zipOut); - } - zipOut.closeEntry(); - } catch (IOException e) { - throw new IllegalStateException("Failed to zip file " + path, e); + private void mergeParts(Path runDirectory, Path zipPath) throws IOException { + List parts; + try (var walk = Files.walk(runDirectory)) { + parts = walk + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(".zip")) + .sorted() + .toList(); + } + + Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + List openParts = new ArrayList<>(); + SortedMap entries = new TreeMap<>(); + try { + for (Path part : parts) { + ZipFile zip = ZipFile.builder().setPath(part).get(); + openParts.add(zip); + for (ZipArchiveEntry entry : Collections.list(zip.getEntriesInPhysicalOrder())) { + 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())); + } + } + } 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()); } + private record ZipEntrySource(ZipFile zip, ZipArchiveEntry entry) {} + private BackupArchive toArchive(Path path) { String fileName = path.getFileName().toString(); return new BackupArchive( @@ -259,6 +338,15 @@ private BackupArchive toArchive(Path path) { ); } + private static Optional parseRetention(String stored) { + try { + return Optional.of(Integer.parseInt(stored)).filter(count -> count >= 1); + } catch (NumberFormatException e) { + LOGGER.warn("Ignoring invalid stored retention count: {}", stored); + return Optional.empty(); + } + } + private String toId(String fileName) { return fileName.replace(".zip", ""); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index bdecb5c..07d88b1 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -11,15 +11,17 @@ import java.time.Instant; import java.util.List; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -28,11 +30,10 @@ import org.springframework.stereotype.Service; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.services.runner.Runner; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; @Service public class BackupOrchestratorService { @@ -44,30 +45,24 @@ public class BackupOrchestratorService { private static final long SCHEDULED_CHECK_INTERVAL_MS = 30000; private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); - private final MediaGarrdProperties properties; - private final RunnerFactory runnerFactory; + private final ServiceBackupRunner runner; private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; private final DatabaseService db; - // private final DockerService dockerService; private final AtomicBoolean running = new AtomicBoolean(false); + private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); private final ExecutorService runnerExecutor = createRunnerExecutor(); - // TODO: public BackupOrchestratorService( - MediaGarrdProperties properties, - RunnerFactory runnerFactory, + ServiceBackupRunner runner, BackupArchiveService archiveService, BackupScheduleService scheduleService, - DatabaseService db/*, - DockerService dockerService*/ + DatabaseService db ) { - this.properties = properties; - this.runnerFactory = runnerFactory; + this.runner = runner; this.archiveService = archiveService; this.scheduleService = scheduleService; this.db = db; - // this.dockerService = dockerService } private static ExecutorService createRunnerExecutor() { @@ -107,15 +102,16 @@ public void scheduledRun() { public BackupRunResult runBackup() { if (!running.compareAndSet(false, true)) { LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new IllegalStateException("A backup run is already in progress"); + throw new RunRejectedException("A backup run is already in progress"); } + configLock.readLock().lock(); Path runDirectory = null; try { - List runners = runnerFactory.build(properties.getServiceConfigs()); - if (runners.isEmpty()) { + List services = db.fetchServices(); + if (services.isEmpty()) { LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); - throw new IllegalStateException("No services are configured for backup"); + throw new RunRejectedException("No services are configured for backup"); } scheduleService.markRunStarted(); @@ -124,50 +120,42 @@ public BackupRunResult runBackup() { Instant startedAt = Instant.now(); LOGGER.info("Backup run started: runDir={}, services={}", - runDir, runners.stream().map(Runner::getServiceName).toList()); + runDir, services.stream().map(ServiceDefinition::name).toList()); - List> futures = runners.stream() - .map(r -> CompletableFuture - .supplyAsync(() -> runSingleRunner(r, runDir), runnerExecutor) + List> futures = services.stream() + .map(service -> CompletableFuture + .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) .exceptionally(t -> { Throwable cause = unwrap(t); - LOGGER.warn("Runner {} failed unexpectedly", r.getServiceName(), cause); - return failedResult(r.getServiceName(), cause); + LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); + return failedResult(service.name(), cause); })) .toList(); - try { - CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Backup run interrupted", ex); - } catch (ExecutionException ex) { - // Unreachable - throw new IllegalStateException("Unexpected failure collecting runner results", ex.getCause()); - } - List serviceRunResults = futures.stream() .map(CompletableFuture::join) .toList(); - for (BackupServiceResult result : serviceRunResults) { - if (COMPLETED.equals(result.status())) { - LOGGER.info("Runner succeeded: {}", result.serviceName()); - } else { - LOGGER.warn("Runner failed (non-fatal): {}", result.serviceName()); - } - } - - int successfulRunnerCount = (int) serviceRunResults.stream() - .filter(r -> COMPLETED.equals(r.status())) - .count(); - LOGGER.info("All runners finished: succeeded={}/{}", successfulRunnerCount, runners.size()); - - String errorMessage = serviceRunResults.stream() + List incomplete = serviceRunResults.stream() .filter(r -> !COMPLETED.equals(r.status())) + .toList(); + int succeeded = services.size() - incomplete.size(); + LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); + incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); + + String errorMessage = incomplete.stream() .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) .collect(Collectors.joining("\n")); + if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { + String runId = "failed-" + UUID.randomUUID(); + serviceRunResults.forEach(r -> r.setId(runId)); + db.addNewBackupRecord(new BackupRunResult( + runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); + LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); + throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + } + BackupArchive archive = archiveService.createArchive(runDirectory); serviceRunResults.forEach(r -> r.setId(archive.id())); @@ -176,9 +164,7 @@ public BackupRunResult runBackup() { archive.fileName(), archive.sizeBytes(), durationMs, serviceRunResults.stream().map(BackupServiceResult::serviceName).toList()); - String status = successfulRunnerCount == runners.size() ? COMPLETED - : successfulRunnerCount > 0 ? PARTIAL - : FAILED; + String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; BackupRunResult backupRecord = new BackupRunResult( archive.id(), formatTime(startedAt), recordCurrentTime(), status, @@ -190,6 +176,7 @@ public BackupRunResult runBackup() { archiveService.removeRunDirectory(runDirectory); LOGGER.debug("Run directory cleaned up: {}", runDirectory); } + configLock.readLock().unlock(); running.set(false); } } @@ -210,6 +197,17 @@ private static BackupServiceResult failedResult(String serviceName, Throwable ca ); } + public T whileIdle(Supplier configChange) { + if (!configLock.writeLock().tryLock()) { + throw new BackupInProgressException("Configuration cannot be changed while a backup is running, try again once it finishes"); + } + try { + return configChange.get(); + } finally { + configLock.writeLock().unlock(); + } + } + public boolean isRunning() { return running.get(); } @@ -227,29 +225,15 @@ public void shutdownRunnerExecutor() { runnerExecutor.shutdownNow(); } - private BackupServiceResult runSingleRunner(Runner runner, Path runDirectory) { - String serviceName = runner.getServiceName(); - LOGGER.info("[{}] Runner starting", serviceName); - long startNanos = System.nanoTime(); - try { - runner.run(runDirectory); - LOGGER.info("[{}] Runner finished in {}ms", serviceName, elapsedMs(startNanos)); - } catch (RuntimeException ex) { - LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", - serviceName, elapsedMs(startNanos), ex); + public static class RunRejectedException extends IllegalStateException { + public RunRejectedException(String message) { + super(message); } - - return new BackupServiceResult( - null, - runner.getRunnerStatus(), - runner.getRunnerStartTime(), - runner.getRunnerEndTime(), - runner.getServiceName(), - runner.getRunnerException() - ); } - private static long elapsedMs(long startNanos) { - return (System.nanoTime() - startNanos) / 1_000_000L; + public static class BackupInProgressException extends IllegalStateException { + public BackupInProgressException(String message) { + super(message); + } } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index f9be79f..ba01349 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -1,7 +1,11 @@ package wellatleastitried.mediagarrdServer.service; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; + import java.time.Duration; import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; @@ -15,11 +19,15 @@ public class BackupScheduleService { private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); + private final DatabaseService db; private final AtomicReference currentInterval; private final AtomicReference nextRun; - public BackupScheduleService(MediaGarrdProperties properties) { - Duration interval = safe(properties.getBackupInterval()); + public BackupScheduleService(MediaGarrdProperties properties, DatabaseService db) { + this.db = db; + Duration interval = db.fetchSetting(BACKUP_INTERVAL_SETTING) + .flatMap(BackupScheduleService::parse) + .orElseGet(() -> safe(properties.getBackupInterval())); this.currentInterval = new AtomicReference<>(interval); this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); @@ -35,6 +43,7 @@ public Instant getNextRun() { public Duration updateInterval(Duration interval) { Duration safe = safe(interval); + db.saveSetting(BACKUP_INTERVAL_SETTING, safe.toString()); currentInterval.set(safe); Instant next = Instant.now().plus(safe); nextRun.set(next); @@ -54,11 +63,21 @@ public void markRunStarted() { LOGGER.info("Backup run started: nextScheduledRun={}", next); } - private Duration safe(Duration interval) { - if (interval == null || interval.isNegative() || interval.isZero()) { - // Default to 12 hours if the provided interval is invalid - return Duration.ofHours(12); + private static Optional parse(String stored) { + try { + return Optional.of(Duration.parse(stored)).filter(BackupScheduleService::isValid); + } catch (DateTimeParseException e) { + LOGGER.warn("Ignoring invalid stored backup interval: {}", stored); + return Optional.empty(); } - return interval; + } + + private static boolean isValid(Duration interval) { + return interval != null && !interval.isNegative() && !interval.isZero(); + } + + private static Duration safe(Duration interval) { + // Default to 12 hours if the provided interval is invalid + return isValid(interval) ? interval : Duration.ofHours(12); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 01900b8..69c2c7f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -3,62 +3,214 @@ import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_RECORD; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_SERVICE_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_SERVICE; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_ALL_SERVICES; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LATEST_RECORD; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_RECORD_BY_ID; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICES_FROM_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICE_BY_NAME; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SETTING; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPDATE_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPSERT_SETTING; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SQLITE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.databasePath; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.sqlite.SQLiteErrorCode; +import org.sqlite.SQLiteException; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; @Service public class DatabaseService { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final TypeReference> PATH_LIST = new TypeReference<>() {}; + + private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss") + .withZone(ZoneOffset.UTC); + private static final List DATABASE_FILE_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + private final Path databaseFile; + private final String databaseUrl; + private volatile SchemaFingerprint verifiedSchema; + + private record SchemaFingerprint(int userVersion, int schemaVersion) {} - public DatabaseService() { + public DatabaseService(MediaGarrdProperties properties) { + databaseFile = Path.of(properties.getDatabasePath()).toAbsolutePath(); + databaseUrl = SQLITE + databaseFile; verifyDatabaseIntegrity(); } protected Connection getConnection() throws SQLException { - return DriverManager.getConnection(SQLITE + databasePath); + Connection connection = DriverManager.getConnection(databaseUrl); + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA foreign_keys = ON"); + } catch (SQLException sE) { + connection.close(); + throw sE; + } + return connection; + } + + protected synchronized boolean verifyDatabaseIntegrity() { + verifiedSchema = null; + try { + rebuildIfNeeded(); + return true; + } catch (SQLException sE) { + if (!isCorrupt(sE) || !quarantineDatabase()) { + LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + return false; + } + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + try { + rebuildIfNeeded(); + return true; + } catch (Exception e) { + LOGGER.warn("Unable to create a new database after moving the corrupt one aside", e); + return false; + } } - protected boolean verifyDatabaseIntegrity() { + private void rebuildIfNeeded() throws SQLException { + try { + Files.createDirectories(databaseFile.getParent()); + } catch (IOException iE) { + LOGGER.warn("Unable to create database directory " + databaseFile.getParent(), iE); + } try (var connection = getConnection()) { + checkNotCorrupt(connection); connection.setAutoCommit(false); ensureTablesExist(connection); runNeededMigrations(connection); - } catch (SQLException sE) { - LOGGER.warn("An error occurred while verifying the integrity of the database", sE); + verifiedSchema = fingerprint(connection); + } + } + + private Connection openVerifiedConnection() throws SQLException { + SchemaFingerprint expected = verifiedSchema; + if (expected != null) { + Connection connection = null; + try { + connection = getConnection(); + if (fingerprint(connection).equals(expected)) { + return connection; + } + } catch (SQLException sE) { + LOGGER.debug("Unable to read the database schema fingerprint", sE); + } + if (connection != null) { + connection.close(); + } + LOGGER.info("Database does not match the verified schema, rebuilding it"); + } + if (!verifyDatabaseIntegrity()) { + throw new SQLException("Database integrity check failed"); + } + return getConnection(); + } + + private static SchemaFingerprint fingerprint(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); + var rs = statement.executeQuery("SELECT user_version, schema_version FROM pragma_user_version, pragma_schema_version")) { + return new SchemaFingerprint(rs.getInt(1), rs.getInt(2)); + } + } + + private static void checkNotCorrupt(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); var rs = statement.executeQuery("PRAGMA quick_check")) { + String result = rs.next() ? rs.getString(1) : "no result"; + if (!"ok".equals(result)) { + throw new CorruptDatabaseException("Database failed its integrity check: " + result); + } + } + } + + private boolean invalidateIfDamaged(SQLException e) { + String message = String.valueOf(e.getMessage()); + boolean damaged = isCorrupt(e) || message.contains("no such table") || message.contains("no such column"); + if (damaged) { + verifiedSchema = null; + } + return damaged; + } + + private static boolean isCorrupt(SQLException e) { + if (e instanceof CorruptDatabaseException) { + return true; + } + if (e instanceof SQLiteException sqlite) { + int code = sqlite.getResultCode().code & 0xFF; + return code == SQLiteErrorCode.SQLITE_CORRUPT.code || code == SQLiteErrorCode.SQLITE_NOTADB.code; + } + return false; + } + + private boolean quarantineDatabase() { + if (!Files.isRegularFile(databaseFile)) { return false; - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + } + String suffix = ".corrupt-" + QUARANTINE_FORMAT.format(Instant.now()); + try { + for (String fileSuffix : DATABASE_FILE_SUFFIXES) { + Path file = Path.of(databaseFile + fileSuffix); + if (Files.isRegularFile(file)) { + Files.move(file, Path.of(file + suffix)); + } + } + } catch (IOException iE) { + LOGGER.error("Database {} is corrupt and could not be moved aside", databaseFile, iE); return false; } - + LOGGER.error("Database {} was corrupt, moved it to {}{} and created a new one. Settings and services must be configured again", + databaseFile, databaseFile, suffix); return true; } + private static class CorruptDatabaseException extends SQLException { + CorruptDatabaseException(String message) { + super(message); + } + } + private void ensureTablesExist(Connection connection) throws SQLException { try (var statement = connection.createStatement()) { for (String sql : CREATE_TABLES.split(";")) { @@ -88,7 +240,7 @@ private void runNeededMigrations(Connection connection) throws SQLException { } for (Migration migration : MIGRATIONS) { - if (currentVersion > migration.version()) { + if (currentVersion >= migration.version()) { continue; } @@ -130,47 +282,53 @@ protected void setDatabaseVersion(Connection connection, int version) { } public void addNewBackupRecord(BackupRunResult backupRecord) { - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not log record of backup: " + backupRecord.runId()); - return; - } - - try (var connection = getConnection()) { + try (var connection = openVerifiedConnection()) { connection.setAutoCommit(false); - addMasterBackup(connection, backupRecord); - addServiceBackups(connection, backupRecord.serviceResults()); + Integer backupId = addMasterBackup(connection, backupRecord); + if (backupId != null) { + addServiceBackups(connection, backupId, backupRecord.serviceResults()); + } } catch (SQLException sE) { - LOGGER.warn("An error occurred while attempting to open a connection to the database", sE); + 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); } } - private void addMasterBackup(Connection connection, BackupRunResult backupRecord) { + private Integer addMasterBackup(Connection connection, BackupRunResult backupRecord) { try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { statement.setString(1, backupRecord.runId()); statement.setString(2, backupRecord.startTime()); statement.setString(3, backupRecord.endTime()); statement.setString(4, backupRecord.status()); - statement.setString(5, backupRecord.archive().generateChecksum()); - statement.setString(6, backupRecord.archive().path().toString()); - statement.setInt(7, backupRecord.archive().fileSize()); - statement.setString(8, formatTime(backupRecord.archive().createdAt())); + BackupArchive archive = backupRecord.archive(); + statement.setString(5, archive == null ? null : archive.generateChecksum()); + statement.setString(6, archive == null ? null : archive.path().toString()); + statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); + statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); statement.setString(9, backupRecord.errorMessage()); statement.executeUpdate(); + int backupId; + try (var idQuery = connection.createStatement(); + var keys = idQuery.executeQuery("SELECT last_insert_rowid()")) { + backupId = keys.getInt(1); + } connection.commit(); + return backupId; } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("An error occurred while logging a new backup record", sE); handleSqlException(connection); } catch (Exception e) { LOGGER.warn("An unknown error occurred while logging a new backup record", e); } + return null; } - private void addServiceBackups(Connection connection, List serviceResults) { + private void addServiceBackups(Connection connection, int backupId, List serviceResults) { for (BackupServiceResult service : serviceResults) { try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { - statement.setString(1, service.runId()); + statement.setInt(1, backupId); statement.setString(2, service.serviceName()); statement.setString(3, service.status()); statement.setString(4, service.startTime()); @@ -179,6 +337,7 @@ private void addServiceBackups(Connection connection, List statement.executeUpdate(); connection.commit(); } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); handleSqlException(connection); } @@ -203,19 +362,15 @@ private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs public Optional fetchBackupById(String archiveId) { FetchedBackupRecord backupRecord = null; - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not fetch backup record by archive_id (" + archiveId + ")"); - } else { - try (var connection = getConnection()) { - backupRecord = fetchMasterRecordById(connection, archiveId); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - 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); + try (var connection = openVerifiedConnection()) { + backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); } + } catch (SQLException sE) { + 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); } return Optional.ofNullable(backupRecord); @@ -227,6 +382,7 @@ private FetchedBackupRecord fetchMasterRecordById(Connection connection, String var rs = statement.executeQuery(); return buildFetchedBackupRecordFromQueryResult(rs); } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", sE); return null; } @@ -234,19 +390,15 @@ private FetchedBackupRecord fetchMasterRecordById(Connection connection, String public Optional fetchLatestBackupRecord() { FetchedBackupRecord backupRecord = null; - if (!verifyDatabaseIntegrity()) { - LOGGER.warn("Could not fetch latest backup record"); - } else { - try (var connection = getConnection()) { - backupRecord = fetchLatestMasterRecord(connection); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - 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); + try (var connection = openVerifiedConnection()) { + backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); } + } catch (SQLException sE) { + 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); } return Optional.ofNullable(backupRecord); @@ -257,6 +409,7 @@ private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { var rs = statement.executeQuery(FETCH_LATEST_RECORD); return buildFetchedBackupRecordFromQueryResult(rs); } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("Error fetching latest backup record", sE); return null; } @@ -284,6 +437,7 @@ private FetchedBackupRecord populateFetchedRecordWithServices(Connection connect } return backupRecord; } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("Error populating backup record with related services", sE); return null; } @@ -298,12 +452,104 @@ private void handleSqlException(Connection connection) { } public void deleteBackupRecordById(String archiveId) { - try (var connection = getConnection(); + try (var connection = openVerifiedConnection(); var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { statement.setString(1, archiveId); statement.executeUpdate(); } catch (SQLException sE) { + invalidateIfDamaged(sE); LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); } } + + public List fetchServices() { + return query("fetch configured services", FETCH_ALL_SERVICES, DatabaseService::toServiceDefinition); + } + + public Optional fetchService(String name) { + return query("fetch service " + name, FETCH_SERVICE_BY_NAME, DatabaseService::toServiceDefinition, name) + .stream().findFirst(); + } + + public void addService(ServiceDefinition service) { + update("add service " + service.name(), ADD_SERVICE, service.name(), toJson(service.paths())); + } + + public boolean updateService(String name, ServiceDefinition service) { + return update("update service " + name, UPDATE_SERVICE, service.name(), toJson(service.paths()), name) > 0; + } + + public boolean removeService(String name) { + return update("remove service " + name, DELETE_SERVICE, name) > 0; + } + + public Optional fetchSetting(String key) { + return query("fetch setting " + key, FETCH_SETTING, rs -> rs.getString("value"), key).stream().findFirst(); + } + + public void saveSetting(String key, String value) { + update("save setting " + key, UPSERT_SETTING, key, value); + } + + @FunctionalInterface + private interface RowMapper { + T map(ResultSet rs) throws SQLException; + } + + @FunctionalInterface + private interface StatementWork { + T run(PreparedStatement statement) throws SQLException; + } + + private List query(String action, String sql, RowMapper mapper, String... params) { + return execute(action, sql, params, statement -> { + try (var rs = statement.executeQuery()) { + List rows = new ArrayList<>(); + while (rs.next()) { + rows.add(mapper.map(rs)); + } + return rows; + } + }); + } + + private int update(String action, String sql, String... params) { + return execute(action, sql, params, PreparedStatement::executeUpdate); + } + + 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); + } + LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", sE.getMessage()); + } + } + } + + private static void bind(PreparedStatement statement, String... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + statement.setString(i + 1, params[i]); + } + } + + private static ServiceDefinition toServiceDefinition(ResultSet rs) throws SQLException { + try { + return new ServiceDefinition(rs.getString("name"), JSON.readValue(rs.getString("paths"), PATH_LIST)); + } catch (JsonProcessingException jE) { + throw new SQLException("Corrupt paths for service " + rs.getString("name"), jE); + } + } + + private static String toJson(List paths) { + try { + return JSON.writeValueAsString(paths); + } catch (JsonProcessingException jE) { + throw new IllegalStateException("Failed to serialize service paths", jE); + } + } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java index 6e73b65..0349418 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -1,6 +1,132 @@ package wellatleastitried.mediagarrdServer.service; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.MountType; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + @Service -public class DockerService {} +public class DockerService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DockerService.class); + + static final String SERVICE_LABEL = "mediagarrd.service"; + static final String CONFIG_HASH_LABEL = "mediagarrd.config-hash"; + static final String MOUNT_ROOT = "/mnt"; + private static final long IMAGE_PULL_TIMEOUT_MINUTES = 10; + + private final DockerClient client; + private final String helperImage; + + public DockerService(DockerClient client, MediaGarrdProperties properties) { + this.client = client; + this.helperImage = properties.getHelperImage(); + } + + public String containerFor(ServiceDefinition service) { + String hash = configHash(service); + for (Container container : managedContainers(service.name())) { + if (hash.equals(container.getLabels().get(CONFIG_HASH_LABEL))) { + LOGGER.debug("[{}] Reusing helper container {}", service.name(), container.getId()); + return container.getId(); + } + LOGGER.info("[{}] Service config changed, removing stale helper container {}", service.name(), container.getId()); + removeContainer(container.getId()); + } + return createContainer(service, hash); + } + + public InputStream copyFrom(String containerId, String hostPath) { + return client.copyArchiveFromContainerCmd(containerId, containerPath(hostPath)).exec(); + } + + public void removeContainers(String serviceName) { + try { + managedContainers(serviceName).forEach(container -> removeContainer(container.getId())); + } catch (RuntimeException e) { + LOGGER.warn("[{}] Unable to remove helper containers", serviceName, e); + } + } + + static String containerPath(String hostPath) { + return MOUNT_ROOT + hostPath; + } + + String configHash(ServiceDefinition service) { + String fingerprint = helperImage + "\n" + String.join("\n", service.paths().stream().sorted().toList()); + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(fingerprint.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private List managedContainers(String serviceName) { + return client.listContainersCmd() + .withShowAll(true) + .withLabelFilter(Map.of(SERVICE_LABEL, serviceName)) + .exec(); + } + + private String createContainer(ServiceDefinition service, String hash) { + ensureHelperImage(); + List mounts = service.paths().stream() + .map(path -> new Mount() + .withType(MountType.BIND) + .withSource(path) + .withTarget(containerPath(path)) + .withReadOnly(true)) + .toList(); + String id = client.createContainerCmd(helperImage) + .withName("mediagarrd-backup-" + service.name()) + .withLabels(Map.of(SERVICE_LABEL, service.name(), CONFIG_HASH_LABEL, hash)) + .withHostConfig(HostConfig.newHostConfig().withMounts(mounts).withNetworkMode("none")) + .exec() + .getId(); + LOGGER.info("[{}] Created helper container {} with {} mount(s)", service.name(), id, mounts.size()); + return id; + } + + private synchronized void ensureHelperImage() { + try { + client.inspectImageCmd(helperImage).exec(); + } catch (NotFoundException e) { + LOGGER.info("Pulling helper image {}", helperImage); + try { + if (!client.pullImageCmd(helperImage).start().awaitCompletion(IMAGE_PULL_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { + throw new IllegalStateException("Timed out pulling helper image " + helperImage); + } + } catch (InterruptedException iE) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, iE); + } + } + } + + private void removeContainer(String containerId) { + try { + client.removeContainerCmd(containerId).withForce(true).exec(); + } catch (NotFoundException e) { + LOGGER.debug("Helper container {} already removed", containerId); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java deleted file mode 100644 index ac21af2..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunnerFactory.java +++ /dev/null @@ -1,121 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.services.runner.JellyfinRunner; -import wellatleastitried.mediagarrdServer.services.runner.ProwlarrRunner; -import wellatleastitried.mediagarrdServer.services.runner.QBittorrentRunner; -import wellatleastitried.mediagarrdServer.services.runner.RadarrRunner; -import wellatleastitried.mediagarrdServer.services.runner.Runner; -import wellatleastitried.mediagarrdServer.services.runner.SonarrRunner; -import wellatleastitried.mediagarrdServer.services.runner.TdarrRunner; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -@Component -public class RunnerFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); - - public List build(EnumMap serviceConfigMap) { - List runners = new ArrayList<>(); - - for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { - AbstractServiceConfig config = entry.getValue(); - if (config == null || !config.isEnabled()) { - LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); - continue; - } - - validate(entry.getKey(), config); - - Services key = entry.getKey(); - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - runners.add(new JellyfinRunner(config)); - LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); - yield null; - } - case RADARR -> { - runners.add(new RadarrRunner(config)); - LOGGER.info("Registered runner: radarr"); - yield null; - } - case SONARR -> { - runners.add(new SonarrRunner(config)); - LOGGER.info("Registered runner: sonarr"); - yield null; - } - case PROWLARR -> { - runners.add(new ProwlarrRunner(config)); - LOGGER.info("Registered runner: prowlarr"); - yield null; - } - case TDARR -> { - runners.add(new TdarrRunner(config)); - LOGGER.info("Registered runner: tdarr"); - yield null; - } - case QBITTORRENT -> { - runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); - LOGGER.info("Registered runner: qbittorrent"); - yield null; - } - }; - } - - LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); - return runners; - } - - private void validate(Services key, AbstractServiceConfig config) { - boolean supported = SUPPORTED_SERVICES.entrySet() - .stream() - .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); - String serviceName = SUPPORTED_SERVICES.get(key); - if (!supported) { - throw new IllegalArgumentException("Unsupported service configured: " + serviceName); - } - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - requirePath(serviceName, "configPath", config.getConfigPath()); - yield null; - } - case RADARR, SONARR, PROWLARR, TDARR -> { - requirePath(serviceName, "path", config.getPath()); - yield null; - } - case QBITTORRENT -> { - if (!(config instanceof QBittorrentServiceConfig)) { - throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); - } - - QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; - requirePath(serviceName, "path", qbConfig.getPath()); - requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); - yield null; - } - }; - } - - private void requirePath(String serviceName, String fieldName, String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java new file mode 100644 index 0000000..2040666 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java @@ -0,0 +1,193 @@ +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 static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +@Service +public class ServiceBackupRunner { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBackupRunner.class); + + static final String PART_SUFFIX = ".zip"; + static final String LINKS_PART_SUFFIX = "-links.zip"; + + private final DockerService docker; + + public ServiceBackupRunner(DockerService docker) { + this.docker = docker; + } + + public BackupServiceResult run(ServiceDefinition service, Path runDirectory) { + String startTime = recordCurrentTime(); + Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); + List errors = new ArrayList<>(); + int copied = 0; + + try { + Files.createDirectories(serviceDirectory); + String containerId = docker.containerFor(service); + for (int i = 0; i < service.paths().size(); i++) { + String hostPath = service.paths().get(i); + Path part = serviceDirectory.resolve(i + PART_SUFFIX); + try (InputStream tar = docker.copyFrom(containerId, hostPath)) { + int entries = archive(tar, hostPath, part); + copied++; + LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, entries); + } catch (IOException | RuntimeException e) { + discard(part); + LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); + errors.add(hostPath + ": " + describe(e)); + } + } + } catch (IOException | RuntimeException e) { + LOGGER.warn("[{}] Unable to prepare helper container", service.name(), e); + errors.add(describe(e)); + } + + String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; + return new BackupServiceResult(null, status, startTime, recordCurrentTime(), service.name(), + errors.isEmpty() ? null : String.join("; ", errors)); + } + + static int archive(InputStream tarStream, String hostPath, Path part) throws IOException { + Path source = Path.of(hostPath); + Path base = Objects.requireNonNullElse(source.getParent(), source.getRoot()); + Set names = new HashSet<>(); + Map hardLinks = new LinkedHashMap<>(); + + try (var tar = new TarArchiveInputStream(tarStream); var zip = new ZipArchiveOutputStream(part)) { + TarArchiveEntry entry; + while ((entry = tar.getNextEntry()) != null) { + String name = entryName(base, source, entry.getName(), entry.isDirectory()); + if (!names.add(name)) { + continue; + } + if (entry.isFIFO() || entry.isCharacterDevice() || entry.isBlockDevice()) { + names.remove(name); + LOGGER.warn("Skipping special file {} in {}", entry.getName(), hostPath); + } else if (entry.isDirectory()) { + write(zip, entry, name, UnixStat.DIR_FLAG, null); + } else if (entry.isSymbolicLink()) { + byte[] target = entry.getLinkName().getBytes(StandardCharsets.UTF_8); + write(zip, entry, name, UnixStat.LINK_FLAG, new ByteArrayInputStream(target)); + } else if (entry.isLink()) { + hardLinks.put(name, entryName(base, source, entry.getLinkName(), false)); + } else if (entry.isFile()) { + write(zip, entry, name, UnixStat.FILE_FLAG, tar); + } else { + names.remove(name); + LOGGER.warn("Skipping unsupported entry {} in {}", entry.getName(), hostPath); + } + } + } + + if (!hardLinks.isEmpty()) { + writeHardLinks(part, hardLinks); + } + return names.size(); + } + + static String entryName(Path base, Path source, String tarName, boolean directory) throws IOException { + Path resolved = base.resolve(tarName).normalize(); + if (!resolved.startsWith(source)) { + throw new IOException("Archive entry escapes " + source + ": " + tarName); + } + String name = source.getRoot().relativize(resolved).toString(); + return directory ? name + "/" : name; + } + + private static void write(ZipArchiveOutputStream zip, TarArchiveEntry source, String name, int type, InputStream content) + throws IOException { + ZipArchiveEntry entry = new ZipArchiveEntry(name); + entry.setUnixMode(type | (source.getMode() & 07777)); + entry.setTime(source.getModTime().getTime()); + entry.addExtraField(owner(source.getLongUserId(), source.getLongGroupId())); + zip.putArchiveEntry(entry); + if (content != null) { + content.transferTo(zip); + } + zip.closeArchiveEntry(); + } + + private static void writeHardLinks(Path part, Map hardLinks) throws IOException { + Path linksPart = linksPart(part); + try (ZipFile written = ZipFile.builder().setPath(part).get(); var zip = new ZipArchiveOutputStream(linksPart)) { + for (var link : hardLinks.entrySet()) { + ZipArchiveEntry target = written.getEntry(link.getValue()); + if (target == null) { + throw new IOException("Hard link " + link.getKey() + " points to a missing entry " + link.getValue()); + } + zip.addRawArchiveEntry(renamed(target, link.getKey()), written.getRawInputStream(target)); + } + } catch (IOException e) { + Files.deleteIfExists(linksPart); + throw e; + } + } + + private static ZipArchiveEntry renamed(ZipArchiveEntry target, String name) { + ZipArchiveEntry entry = new ZipArchiveEntry(name); + entry.setMethod(target.getMethod()); + entry.setCrc(target.getCrc()); + entry.setSize(target.getSize()); + entry.setCompressedSize(target.getCompressedSize()); + entry.setUnixMode(target.getUnixMode()); + entry.setTime(target.getTime()); + entry.setExtraFields(target.getExtraFields()); + return entry; + } + + private static X7875_NewUnix owner(long uid, long gid) { + X7875_NewUnix owner = new X7875_NewUnix(); + owner.setUID(uid); + owner.setGID(gid); + return owner; + } + + private static void discard(Path part) { + try { + Files.deleteIfExists(part); + Files.deleteIfExists(linksPart(part)); + } catch (IOException e) { + LOGGER.warn("Unable to remove incomplete archive part {}", part, e); + } + } + + private static Path linksPart(Path part) { + return part.resolveSibling(part.getFileName().toString().replace(PART_SUFFIX, LINKS_PART_SUFFIX)); + } + + private static String describe(Throwable e) { + return Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java new file mode 100644 index 0000000..5985220 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java @@ -0,0 +1,94 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SETUP_COMPLETED_SETTING; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.HexFormat; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +@Service +@Lazy(false) +public class SetupService { + + private static final Logger LOGGER = LoggerFactory.getLogger(SetupService.class); + + static final int MAX_FAILED_ATTEMPTS = 5; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final DatabaseService db; + private final Set sessions = ConcurrentHashMap.newKeySet(); + private volatile boolean completed; + private String pin; + private int failedAttempts; + + public SetupService(DatabaseService db) { + this.db = db; + this.completed = db.fetchSetting(SETUP_COMPLETED_SETTING).isPresent(); + if (completed) { + LOGGER.info("Setup already completed, the web setup page is disabled"); + } else { + rotatePin(); + } + } + + public boolean isCompleted() { + return completed; + } + + public boolean canConfigure(String sessionToken) { + return completed || (sessionToken != null && sessions.contains(sessionToken)); + } + + public synchronized Optional startSession(String candidate) { + if (completed) { + return Optional.empty(); + } + if (candidate == null || !MessageDigest.isEqual(bytes(pin), bytes(candidate.strip()))) { + failedAttempts++; + LOGGER.warn("Rejected setup PIN attempt ({}/{})", failedAttempts, MAX_FAILED_ATTEMPTS); + if (failedAttempts >= MAX_FAILED_ATTEMPTS) { + rotatePin(); + } + return Optional.empty(); + } + byte[] token = new byte[32]; + RANDOM.nextBytes(token); + String session = HexFormat.of().formatHex(token); + sessions.add(session); + LOGGER.info("Setup PIN accepted, a new PIN is required for any other device"); + rotatePin(); + return Optional.of(session); + } + + public synchronized void complete() { + db.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); + completed = true; + sessions.clear(); + pin = null; + LOGGER.info("Setup completed, the web setup page is now disabled"); + } + + synchronized String currentPin() { + return pin; + } + + private void rotatePin() { + pin = "%06d".formatted(RANDOM.nextInt(1_000_000)); + failedAttempts = 0; + LOGGER.warn("Setup PIN: {} (single use, enter it at http://:/config)", pin); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java deleted file mode 100644 index 6a72476..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/AbstractServiceConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -//@ADD_NEW_SERVICE -abstract public class AbstractServiceConfig { - - private boolean enabled; - private String path; - private String configPath; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getConfigPath() { - return configPath; - } - - public void setConfigPath(String configPath) { - this.configPath = configPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java deleted file mode 100644 index 20482e2..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/CommonServiceConfig.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -// For services that require only one path to backup, this can be used. -// Otherwise, create a new config for a service-specific config. -public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java deleted file mode 100644 index a6dbe04..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/config/QBittorrentServiceConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.config; - -public class QBittorrentServiceConfig extends AbstractServiceConfig { - - private String savedTorrentsPath; - - public String getSavedTorrentsPath() { - return savedTorrentsPath; - } - - public void setSavedTorrentsPath(String savedTorrentsPath) { - this.savedTorrentsPath = savedTorrentsPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java deleted file mode 100644 index 29d54a1..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractContainerCopyRunner.java +++ /dev/null @@ -1,4 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -// TODO: Not yet implemented -public abstract class AbstractContainerCopyRunner {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java deleted file mode 100644 index 626a3e6..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/AbstractLocalCopyRunner.java +++ /dev/null @@ -1,188 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; - -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.List; -import java.util.Locale; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -//@ADD_NEW_SERVICE -public abstract class AbstractLocalCopyRunner implements Runner { - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); - - private final String serviceName; - - private String startTime; - private String endTime; - private String status; - private String errorMessage; - - protected AbstractLocalCopyRunner(String serviceName) { - this.serviceName = serviceName; - status = "idle"; - startTime = endTime = errorMessage = ""; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getRunnerStartTime() { - return startTime; - } - - @Override - public String getRunnerEndTime() { - return endTime; - } - - @Override - public String getRunnerStatus() { - return status; - } - - @Override - public String getRunnerException() { - return errorMessage; - } - - @Override - public void run(Path outputDirectory) { - startTime = recordCurrentTime(); - status = "running"; - Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); - try { - Files.createDirectories(serviceDirectory); - } catch (IOException e) { - errorMessage = "Unable to create output directory for " + serviceName; - status = "failed"; - throw new IllegalStateException("Unable to create output directory for " + serviceName, e); - } - - List specs = copySpecs(); - LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); - int succeeded = 0; - for (CopySpec spec : specs) { - try { - copySpec(spec, serviceDirectory); - succeeded++; - } catch (RuntimeException ex) { - LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); - } - } - LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); - if (succeeded == specs.size()) { - status = "completed"; - } else if (succeeded < specs.size() && succeeded > 0) { - status = "partial"; - } else { - status = "failed"; - } - endTime = recordCurrentTime(); - } - - protected abstract List copySpecs(); - - protected CopySpec dir(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, true); - } - - protected CopySpec file(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, false); - } - - private void copySpec(CopySpec spec, Path serviceDirectory) { - if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - errorMessage = serviceName + " runner missing source path for " + spec.targetName(); - status = "failed"; - throw new IllegalArgumentException(errorMessage); - } - - Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); - if (!Files.exists(source)) { - errorMessage = serviceName + " source path not found: " + source; - status = "failed"; - throw new IllegalStateException(errorMessage); - } - - Path target = serviceDirectory.resolve(spec.targetName()); - - try { - if (spec.directory()) { - if (!Files.isDirectory(source)) { - throw new IllegalStateException(serviceName + " expected directory path: " + source); - } - copyDirectory(source, target); - } else { - if (!Files.isRegularFile(source)) { - throw new IllegalStateException(serviceName + " expected file path: " + source); - } - Path parent = target.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied file: {}", serviceName, target); - } - } catch (IOException e) { - status = "failed"; - throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); - } - } - - - private void copyDirectory(Path source, Path target) throws IOException { - Files.createDirectories(target); - FileVisitor visitor = new SimpleFileVisitor<>() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(dir); - Path destination = target.resolve(relative); - Files.createDirectories(destination); - LOGGER.debug("[{}] Created dir: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(file); - Path destination = target.resolve(relative); - Path parent = destination.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - - // This will be used on all files including databases. There is a risk of corruption - // when copying a database as it could be in-use, but this is unlikely AND the fact - // that multiple backups will be retained mitigates this risk. This may be changed - // in the future with an OPTION to stop services during backup, but for now it will - // be a basic copy. - Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); - return FileVisitResult.CONTINUE; - } - }; - Files.walkFileTree(source, visitor); - } - - protected record CopySpec(String sourcePath, String targetName, boolean directory) {} -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java deleted file mode 100644 index e3077da..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ArrRunner.java +++ /dev/null @@ -1,36 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; - -public abstract class ArrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public ArrRunner(String service, AbstractServiceConfig config) { - super(service); - this.config = config; - } - - @Override - protected List copySpecs() { - List specs = new ArrayList<>(); - specs.add(dir(config.getConfigPath(), "config")); - - Path data = Path.of(config.getPath()).resolve("data"); - if (Files.isDirectory(data)) { - specs.add(dir(data.toString(), "data")); - } - - Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); - if (Files.isRegularFile(compose)) { - specs.add(file(compose.toString(), "docker-compose.yml")); - } - - return specs; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java deleted file mode 100644 index dd4e29a..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/JellyfinRunner.java +++ /dev/null @@ -1,23 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class JellyfinRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public JellyfinRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getConfigPath(), "config")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java deleted file mode 100644 index 05c41f8..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/ProwlarrRunner.java +++ /dev/null @@ -1,12 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class ProwlarrRunner extends ArrRunner { - public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR), config); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java deleted file mode 100644 index ab4004c..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/QBittorrentRunner.java +++ /dev/null @@ -1,39 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class QBittorrentRunner extends AbstractLocalCopyRunner { - - private final QBittorrentServiceConfig config; - - public QBittorrentRunner(QBittorrentServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); - this.config = config; - } - - @Override - protected List copySpecs() { - List specs = new ArrayList<>(); - specs.add(dir(config.getConfigPath(), "config")); - - String savedTorrentPath = config.getSavedTorrentsPath(); - if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { - specs.add(dir(savedTorrentPath, "saved-torrents")); - } - - Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); - if (Files.isRegularFile(compose)) { - specs.add(file(compose.toString(), "docker-compose.yml")); - } - - return specs; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java deleted file mode 100644 index 4578685..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/RadarrRunner.java +++ /dev/null @@ -1,12 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class RadarrRunner extends ArrRunner { - public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR), config); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java deleted file mode 100644 index 095420b..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/Runner.java +++ /dev/null @@ -1,18 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import java.nio.file.Path; - -public interface Runner { - - String getServiceName(); - - String getRunnerStartTime(); - - String getRunnerEndTime(); - - String getRunnerStatus(); - - String getRunnerException(); - - void run(Path outputDirectory); -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java deleted file mode 100644 index a3a0dc5..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/SonarrRunner.java +++ /dev/null @@ -1,12 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public class SonarrRunner extends ArrRunner { - public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR), config); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java deleted file mode 100644 index 459134b..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/services/runner/TdarrRunner.java +++ /dev/null @@ -1,46 +0,0 @@ -package wellatleastitried.mediagarrdServer.services.runner; - -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -// Tdarr has a different structure than radarr/sonarr/prowlarr, so it will -// use the AbstractLocalCopyRunner instead of ArrRunner. -public class TdarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public TdarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.TDARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - List specs = new ArrayList<>(); - specs.add(dir(config.getConfigPath(), "configs")); - - Path server = Path.of(config.getPath()).resolve("server"); - if (Files.isDirectory(server)) { - specs.add(dir(server.toString(), "server")); - } - - Path logs = Path.of(config.getPath()).resolve("logs"); - if (Files.isDirectory(logs)) { - specs.add(dir(logs.toString(), "logs")); - } - - Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); - if (Files.isRegularFile(compose)) { - specs.add(file(compose.toString(), "docker-compose.yml")); - } - - return specs; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java deleted file mode 100644 index 07fcf4f..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/ServiceConstants.java +++ /dev/null @@ -1,28 +0,0 @@ -package wellatleastitried.mediagarrdServer.utilities; - -import java.util.EnumMap; - -//@ADD_NEW_SERVICE -public class ServiceConstants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java index a6ca71d..2a23d30 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java @@ -31,6 +31,17 @@ FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, UNIQUE (backup_id, service_name) ); + CREATE TABLE IF NOT EXISTS services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + paths TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); """; @@ -81,11 +92,46 @@ INSERT INTO backup_services ( WHERE archive_id = ?; """; + public static final String FETCH_ALL_SERVICES = """ + SELECT name, paths FROM services + ORDER BY name COLLATE NOCASE; + """; + + public static final String FETCH_SERVICE_BY_NAME = """ + SELECT name, paths FROM services + WHERE name = ?; + """; + + public static final String ADD_SERVICE = """ + INSERT INTO services (name, paths) VALUES (?, ?); + """; + + public static final String UPDATE_SERVICE = """ + UPDATE services SET name = ?, paths = ? + WHERE name = ?; + """; + + public static final String DELETE_SERVICE = """ + DELETE FROM services + WHERE name = ?; + """; + + public static final String FETCH_SETTING = """ + SELECT value FROM settings + WHERE key = ?; + """; + + public static final String UPSERT_SETTING = """ + INSERT INTO settings (key, value) VALUES (?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value; + """; + public record Migration(int version, String sql) {} public static final List MIGRATIONS; static { MIGRATIONS = new ArrayList(); // Migration versions will start at 2, as the initial tables will be schema v1 + MIGRATIONS.add(new Migration(2, "DELETE FROM backup_services WHERE backup_id NOT IN (SELECT id FROM backups)")); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java index 5372a7a..25e529c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java @@ -3,7 +3,10 @@ public class DatabaseUtils { public static final String SQLITE = "jdbc:sqlite:"; - public static final String databasePath = "/var/lib/mediagarrd/mediagarrd.db"; + public static final String BACKUP_ROOT_SETTING = "backup_root"; + public static final String SETUP_COMPLETED_SETTING = "setup_completed"; + public static final String BACKUP_INTERVAL_SETTING = "backup_interval"; + public static final String RETENTION_COUNT_SETTING = "retention_count"; // Status used for the overall backup AND the individual service runners public class Status { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index f2a7d0e..c0984fa 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -3,31 +3,7 @@ server: mediagarrd: backup-interval: ${MEDIAGARRD_BACKUP_INTERVAL:PT12H} - backup-root: ${MEDIAGARRD_BACKUP_ROOT:./data/server/backups} + backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} - services: - jellyfin: - enabled: ${JELLYFIN_ENABLED:false} - path: ${JELLYFIN_PATH:/srv/sources/jellyfin} - config-path: ${JELLYFIN_CONFIG_PATH:/srv/sources/jellyfin/config} - radarr: - enabled: ${RADARR_ENABLED:false} - path: ${RADARR_PATH:/srv/sources/radarr} - config-path: ${RADARR_CONFIG_PATH:/srv/sources/radarr/config} - sonarr: - enabled: ${SONARR_ENABLED:false} - path: ${SONARR_PATH:/srv/sources/sonarr} - config-path: ${SONARR_CONFIG_PATH:/srv/sources/sonarr/config} - prowlarr: - enabled: ${PROWLARR_ENABLED:false} - path: ${PROWLARR_PATH:/srv/sources/prowlarr} - config-path: ${PROWLARR_CONFIG_PATH:/srv/sources/prowlarr/config} - tdarr: - enabled: ${TDARR_ENABLED:false} - path: ${TDARR_PATH:/srv/sources/tdarr} - config-path: ${TDARR_CONFIG_PATH:/srv/sources/tdarr/configs} - qbittorrent: - enabled: ${QBITTORRENT_ENABLED:false} - path: ${QBITTORRENT_PATH:/srv/sources/qbittorrent} - config-path: ${QBITTORRENT_CONFIG_PATH:/srv/sources/qbittorrent/config} - saved-torrents-path: ${QBITTORRENT_SAVED_TORRENTS_PATH} + database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} + helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} diff --git a/src/main/resources/static/config.html b/src/main/resources/static/config.html new file mode 100644 index 0000000..aced9f0 --- /dev/null +++ b/src/main/resources/static/config.html @@ -0,0 +1,108 @@ + + + + + + MediaGarrd Server Configuration + + + + +

+
+ MediaGarrd + Server Configuration +
+
+ + +
Setup PIN
+
+
+ + +

+
+ +
+
+ +
+ + +
+
+
Backup Settings
+
+
+ + +

Must be on a mounted volume, otherwise archives are lost when the container is recreated.

+
+
+ + +
+
+ + +
+
+
+
+ +
+
Finish Setup
+
+

Once finished, this page is disabled. Later changes go through the API or the MediaGarrd Client.

+
+
+
+
+ +
+
Add Service
+
+
+ + +
+
+ Host paths to back up +
+ +
+
+ + +
+
+ + + + + +
Configured Services
+ + + +
NamePaths
+

No services configured yet.

+
+
+ + diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css new file mode 100644 index 0000000..8e2fdc0 --- /dev/null +++ b/src/main/resources/static/css/mediagarrd.css @@ -0,0 +1,148 @@ +:root { + --bg: #000; + --surface: #0a0a0a; + --surface-raised: #111; + --ink: #f5f5f5; + --muted: #737373; + --subtle: #404040; + --border: #1f1f1f; + --border-mid: #2e2e2e; + --accent: #f5f5f5; + --accent-dim: #d4d4d4; + --ok: #22c55e; + --warn: #ef4444; + --mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; +} + +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +body { + font-family: "Space Grotesk", "Inter", "Avenir Next", ui-sans-serif, system-ui, sans-serif; + background: var(--bg); + color: var(--ink); + min-height: 100vh; + font-size: 14px; + line-height: 1.5; +} + +[hidden] { display: none !important; } + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.85rem 1.5rem; + border-bottom: 1px solid var(--border); + background: var(--surface); + position: sticky; + top: 0; + z-index: 10; +} + +.brand { display: flex; flex-direction: column; } +.brand-title { font-size: 1rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; } +.brand-sub { font-size: 0.72rem; color: var(--muted); letter-spacing: 0.05em; } + +.workspace { + max-width: 1200px; + margin: 0 auto; + padding: 1.5rem; + display: grid; + grid-template-columns: 360px 1fr; + gap: 1rem; + align-items: start; +} + +@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } + +.panel { background: var(--surface); border: 1px solid var(--border); } +.panel.wide { grid-column: 1 / -1; } +.stack { display: flex; flex-direction: column; gap: 1rem; } + +dialog.panel { color: var(--ink); margin: auto; width: min(360px, calc(100% - 2rem)); } +dialog::backdrop { background: rgba(0, 0, 0, 0.8); } +.error-text { color: #fca5a5; } +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--border); +} +.panel-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent-dim); } +.panel-body { padding: 1rem; } + +.field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } +.field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } +.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } +.button-row { display: flex; gap: 0.5rem; } +.note + .button-row { margin-top: 0.75rem; } + +input { + width: 100%; + background: var(--bg); + color: var(--ink); + border: 1px solid var(--border-mid); + padding: 0.5rem 0.65rem; + font: inherit; + font-size: 0.85rem; + outline: none; + transition: border-color 150ms; +} +input:focus { border-color: var(--subtle); } +input::placeholder { color: var(--muted); } + +button { + background: var(--accent); + color: #000; + border: 1px solid var(--accent); + padding: 0.5rem 0.85rem; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; + white-space: nowrap; + transition: background 120ms, color 120ms, border-color 120ms, transform 70ms; +} +button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } +button:active { transform: translateY(1px) scale(0.98); } +button:disabled { cursor: not-allowed; opacity: 0.62; transform: none; } +button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } +button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } +button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } +button.danger:hover { background: #1c0606; } + +table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } +thead th { + padding: 0.5rem 0.75rem; + text-align: left; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + border-bottom: 1px solid var(--border-mid); +} +tbody tr { border-bottom: 1px solid var(--border); transition: background 100ms; } +tbody tr:last-child { border-bottom: none; } +tbody tr:hover { background: var(--surface-raised); } +tbody td { padding: 0.55rem 0.75rem; vertical-align: top; } +.td-mono { font-family: var(--mono); font-size: 0.78rem; color: var(--accent-dim); white-space: pre-line; word-break: break-all; } +.actions-cell { text-align: right; white-space: nowrap; } +.actions-cell button + button { margin-left: 0.4rem; } +.empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } + +.banner { + display: none; + grid-column: 1 / -1; + padding: 0.65rem 1rem; + font-size: 0.82rem; + background: #1c0606; + border: 1px solid #3b1111; + color: #fca5a5; +} +.banner.visible { display: block; } +.banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 8095409..d75d8b1 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -8,5 +8,6 @@

MediaGarrd Server

API is available under /api/v1.

+

Configure services and backup location

diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js new file mode 100644 index 0000000..7b8cd87 --- /dev/null +++ b/src/main/resources/static/js/api.js @@ -0,0 +1,27 @@ +async function request(method, url, body) { + const response = await fetch(url, { + method, + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => ({})); + throw new Error(data.error || `${method} ${url} failed (${response.status})`); + } + return response.status === 204 ? null : response.json(); +} + +const servicePath = (name) => `/api/v1/services/${encodeURIComponent(name)}`; + +export const api = { + getConfig: () => request('GET', '/api/v1/config'), + updateConfig: (settings) => request('PUT', '/api/v1/config', settings), + updateSchedule: (backupInterval) => request('PUT', '/api/v1/schedule', { backupInterval }), + listServices: () => request('GET', '/api/v1/services'), + addService: (service) => request('POST', '/api/v1/services', service), + updateService: (name, service) => request('PUT', servicePath(name), service), + removeService: (name) => request('DELETE', servicePath(name)), + setupStatus: () => request('GET', '/api/v1/setup'), + startSetupSession: (pin) => request('POST', '/api/v1/setup/session', { pin }), + completeSetup: () => request('POST', '/api/v1/setup/complete'), +}; diff --git a/src/main/resources/static/js/config.js b/src/main/resources/static/js/config.js new file mode 100644 index 0000000..5824f97 --- /dev/null +++ b/src/main/resources/static/js/config.js @@ -0,0 +1,30 @@ +import { initServices } from './services.js'; +import { initSettings } from './settings.js'; +import { initFinish, unlock } from './setup.js'; + +const workspace = document.querySelector('.workspace'); +const banner = document.getElementById('banner'); + +function show(message, kind) { + banner.textContent = message; + banner.className = `banner visible ${kind}`; +} + +const notify = { + ok: (message) => show(message, 'ok'), + error: (error) => show(error.message || String(error), 'error'), +}; + +function start() { + workspace.hidden = false; + initSettings(document.getElementById('settingsForm'), notify); + initServices(document.getElementById('services'), notify); + initFinish(document.getElementById('finish'), notify, () => { + workspace.querySelectorAll('[data-setup]').forEach((element) => element.remove()); + }); +} + +unlock(document.getElementById('pinDialog')).then(start).catch((error) => { + workspace.hidden = false; + notify.error(error); +}); diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js new file mode 100644 index 0000000..45913a3 --- /dev/null +++ b/src/main/resources/static/js/services.js @@ -0,0 +1,91 @@ +import { api } from './api.js'; + +export function initServices(root, notify) { + const form = root.querySelector('form'); + const title = root.querySelector('[data-form-title]'); + const paths = root.querySelector('[data-paths]'); + const cancel = root.querySelector('[data-cancel]'); + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const pathTemplate = root.querySelector('#pathTemplate'); + const rowTemplate = root.querySelector('#serviceTemplate'); + let editing = null; + + function addPathInput(value = '') { + const row = pathTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('input').value = value; + row.querySelector('button').addEventListener('click', () => { + row.remove(); + if (!paths.children.length) addPathInput(); + }); + paths.append(row); + } + + function resetForm() { + editing = null; + form.reset(); + paths.replaceChildren(); + addPathInput(); + title.textContent = 'Add Service'; + cancel.hidden = true; + } + + function editService(service) { + editing = service.name; + form.elements.name.value = service.name; + paths.replaceChildren(); + service.paths.forEach(addPathInput); + title.textContent = `Edit ${service.name}`; + cancel.hidden = false; + form.elements.name.focus(); + } + + async function removeService(service) { + if (!confirm(`Remove ${service.name}? Existing backups are kept.`)) return; + try { + await api.removeService(service.name); + if (editing === service.name) resetForm(); + notify.ok(`Removed ${service.name}`); + await refresh(); + } catch (error) { + notify.error(error); + } + } + + function renderRow(service) { + const row = rowTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('[data-name]').textContent = service.name; + row.querySelector('[data-paths]').textContent = service.paths.join('\n'); + row.querySelector('[data-edit]').addEventListener('click', () => editService(service)); + row.querySelector('[data-remove]').addEventListener('click', () => removeService(service)); + return row; + } + + async function refresh() { + const services = await api.listServices(); + rows.replaceChildren(...services.map(renderRow)); + empty.hidden = services.length > 0; + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const service = { + name: form.elements.name.value, + paths: [...paths.querySelectorAll('input')].map((input) => input.value), + }; + try { + const saved = editing ? await api.updateService(editing, service) : await api.addService(service); + notify.ok(`Saved ${saved.name}`); + resetForm(); + await refresh(); + } catch (error) { + notify.error(error); + } + }); + + root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); + cancel.addEventListener('click', resetForm); + + resetForm(); + refresh().catch(notify.error); +} diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js new file mode 100644 index 0000000..c397d73 --- /dev/null +++ b/src/main/resources/static/js/settings.js @@ -0,0 +1,34 @@ +import { api } from './api.js'; + +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/; + +function toHours(duration) { + const [, hours = 0, minutes = 0, seconds = 0] = ISO_DURATION.exec(duration) || []; + return Number(hours) + Number(minutes) / 60 + Number(seconds) / 3600; +} + +const toDuration = (hours) => `PT${Math.round(hours * 60)}M`; + +export function initSettings(form, notify) { + const { backupLocation, intervalHours, retentionCount } = form.elements; + + function show(config) { + backupLocation.value = config.backupLocation; + intervalHours.value = toHours(config.backupInterval); + retentionCount.value = config.retentionCount; + } + + api.getConfig().then(show).catch(notify.error); + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + const config = await api.updateConfig({ backupLocation: backupLocation.value, retentionCount: Number(retentionCount.value) }); + const { backupInterval } = await api.updateSchedule(toDuration(Number(intervalHours.value))); + show({ ...config, backupInterval }); + notify.ok('Backup settings saved'); + } catch (error) { + notify.error(error); + } + }); +} diff --git a/src/main/resources/static/js/setup.js b/src/main/resources/static/js/setup.js new file mode 100644 index 0000000..94dedad --- /dev/null +++ b/src/main/resources/static/js/setup.js @@ -0,0 +1,38 @@ +import { api } from './api.js'; + +export async function unlock(dialog) { + const status = await api.setupStatus(); + if (status.authorized) return; + + const form = dialog.querySelector('form'); + const error = dialog.querySelector('[data-error]'); + dialog.addEventListener('cancel', (event) => event.preventDefault()); + dialog.showModal(); + + await new Promise((resolve) => { + form.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + await api.startSetupSession(form.elements.pin.value); + dialog.close(); + resolve(); + } catch (e) { + error.textContent = e.message; + form.reset(); + } + }); + }); +} + +export function initFinish(root, notify, onComplete) { + root.querySelector('button').addEventListener('click', async () => { + if (!confirm('Finish setup? This page will be disabled and further changes must go through the API or the MediaGarrd Client.')) return; + try { + await api.completeSetup(); + onComplete(); + notify.ok('Setup complete. This page is now disabled, further changes go through the API or the MediaGarrd Client.'); + } catch (error) { + notify.error(error); + } + }); +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 31ad00b..f817fe9 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -1,27 +1,17 @@ package wellatleastitried.mediagarrdServer; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import java.util.EnumMap; +import java.time.Duration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - @SpringBootTest(properties = { - "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-properties-test", - "mediagarrd.services.jellyfin.enabled=false", - "mediagarrd.services.radarr.enabled=false", - "mediagarrd.services.sonarr.enabled=false", - "mediagarrd.services.prowlarr.enabled=false", - "mediagarrd.services.tdarr.enabled=false", - "mediagarrd.services.qbittorrent.enabled=false" + "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-binding-test/backups", + "mediagarrd.database-path=${java.io.tmpdir}/mediagarrd-binding-test/mediagarrd.db", + "mediagarrd.helper-image=alpine:3" }) class MediaGarrdPropertiesBindingTest { @@ -29,11 +19,13 @@ class MediaGarrdPropertiesBindingTest { private MediaGarrdProperties properties; @Test - void bindsConcreteServiceConfigurations() { - EnumMap configs = properties.getServiceConfigs(); - - assertEquals(6, configs.size()); - assertInstanceOf(CommonServiceConfig.class, configs.get(Services.RADARR)); - assertInstanceOf(QBittorrentServiceConfig.class, configs.get(Services.QBITTORRENT)); + void bindsApplicationProperties() { + String tmp = System.getProperty("java.io.tmpdir"); + + assertEquals(Duration.ofHours(12), properties.getBackupInterval()); + assertEquals(10, properties.getRetentionCount()); + assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); + assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); + assertEquals("alpine:3", properties.getHelperImage()); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 6e66556..b9b3d5a 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -18,11 +18,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(BackupController.class) class BackupControllerTest { @@ -36,17 +36,27 @@ class BackupControllerTest { BackupOrchestratorService orchestratorService; @MockBean - MediaGarrdProperties properties; + SetupService setup; @Test void healthReturnsServerStatus() throws Exception { when(orchestratorService.isRunning()).thenReturn(false); when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); - when(properties.getRetentionCount()).thenReturn(10); + when(archiveService.retentionCount()).thenReturn(7); mockMvc.perform(get("/api/v1/health")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.healthy").value(true)); + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupRetentionCount").value(7)); + } + + @Test + void clientEndpointsNeverRequireSetupSession() throws Exception { + when(archiveService.listArchives()).thenReturn(List.of()); + when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); + + mockMvc.perform(get("/api/v1/health")).andExpect(status().isOk()); + mockMvc.perform(get("/api/v1/backups")).andExpect(status().isOk()); } @Test @@ -79,4 +89,22 @@ void runAndListBackups() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(1))); } + + @Test + void rejectedRunReturnsConflictWithReason() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new BackupOrchestratorService.RunRejectedException("A backup run is already in progress")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("A backup run is already in progress")); + } + + @Test + void failedRunReturnsServerErrorWithReason() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new IllegalStateException("Every service failed, no archive created: radarr: boom")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Every service failed, no archive created: radarr: boom")); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java index 245682d..8e59147 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -1,4 +1,260 @@ package wellatleastitried.mediagarrdServer.api; -// TODO: Not yet implemented -public class ConfigControllerTest {} +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(ConfigController.class) +class ConfigControllerTest { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); + private static final String RADARR_JSON = """ + {"name": "radarr", "paths": ["/srv/radarr"]} + """; + + @Autowired + MockMvc mockMvc; + + @MockBean + BackupArchiveService archiveService; + + @MockBean + DatabaseService db; + + @MockBean + DockerService docker; + + @MockBean + SetupService setup; + + @MockBean + BackupOrchestratorService orchestrator; + + @BeforeEach + void setUp() { + when(setup.canConfigure(any())).thenReturn(true); + when(orchestrator.whileIdle(any())).thenAnswer(invocation -> invocation.>getArgument(0).get()); + when(orchestrator.getInterval()).thenReturn(Duration.ofHours(6)); + when(archiveService.retentionCount()).thenReturn(4); + } + + @Test + void rejectsConfigChangesWhileBackupIsRunning() throws Exception { + doThrow(new BackupOrchestratorService.BackupInProgressException("busy")).when(orchestrator).whileIdle(any()); + + mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("busy")); + mockMvc.perform(delete("/api/v1/services/radarr")).andExpect(status().isConflict()); + mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)).andExpect(status().isConflict()); + mockMvc.perform(json(put("/api/v1/config"), "{\"retentionCount\": 3}")).andExpect(status().isConflict()); + + verify(db, never()).addService(any()); + verify(db, never()).removeService(anyString()); + verify(archiveService, never()).updateSettings(any(), any()); + } + + @Test + void requiresSetupSessionUntilSetupIsComplete() throws Exception { + when(setup.canConfigure(any())).thenReturn(false); + + mockMvc.perform(get("/api/v1/services")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) + .andExpect(status().isUnauthorized()); + + verify(db, never()).fetchServices(); + verify(db, never()).addService(any()); + verify(archiveService, never()).updateSettings(any(), any()); + } + + @Test + void returnsBackupLocation() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/backups")); + + mockMvc.perform(get("/api/v1/config")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/backups")) + .andExpect(jsonPath("$.retentionCount").value(4)) + .andExpect(jsonPath("$.backupInterval").exists()); + } + + @Test + void updatesBackupLocationAndRetentionCount() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/new")); + + mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 4}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/new")) + .andExpect(jsonPath("$.retentionCount").value(4)); + + verify(archiveService).updateSettings("/new", 4); + } + + @Test + void passesOmittedFieldsAsNull() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/backups")); + + mockMvc.perform(json(put("/api/v1/config"), "{\"retentionCount\": 4}")) + .andExpect(status().isOk()); + + verify(archiveService).updateSettings(isNull(), eq(4)); + } + + @Test + void rejectsInvalidBackupLocation() throws Exception { + doThrow(new IllegalArgumentException("must be absolute")).when(archiveService).updateSettings("relative", null); + + mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"relative\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("must be absolute")); + } + + @Test + void listsServices() throws Exception { + when(db.fetchServices()).thenReturn(List.of(RADARR)); + + mockMvc.perform(get("/api/v1/services")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].name").value("radarr")) + .andExpect(jsonPath("$[0].paths[0]").value("/srv/radarr")); + } + + @Test + void addsNormalizedService() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(json(post("/api/v1/services"), "{\"name\": \" radarr \", \"paths\": [\"/srv/radarr/\", \"\"]}")) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("radarr")) + .andExpect(jsonPath("$.paths", hasSize(1))); + + verify(db).addService(RADARR); + } + + @Test + void rejectsDuplicateService() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").exists()); + + verify(db, never()).addService(any()); + } + + @Test + void rejectsInvalidService() throws Exception { + mockMvc.perform(json(post("/api/v1/services"), "{\"name\": \"radarr\", \"paths\": [\"relative\"]}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Path must be absolute: relative")); + + verify(db, never()).addService(any()); + } + + @Test + void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"radarr\", \"paths\": [\"/srv/other\"]}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.paths[0]").value("/srv/other")); + + verify(db).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(docker, never()).removeContainers(anyString()); + } + + @Test + void renamingServiceRemovesOldContainers() throws Exception { + when(db.fetchService("RADARR")).thenReturn(Optional.of(RADARR)); + when(db.fetchService("movies")).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/v1/services/RADARR"), "{\"name\": \"movies\", \"paths\": [\"/srv/radarr\"]}")) + .andExpect(status().isOk()); + + verify(db).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); + verify(docker).removeContainers("radarr"); + } + + @Test + void renamingOntoExistingServiceConflicts() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + when(db.fetchService("sonarr")).thenReturn(Optional.of(new ServiceDefinition("sonarr", List.of("/srv/sonarr")))); + + mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"sonarr\", \"paths\": [\"/srv/radarr\"]}")) + .andExpect(status().isConflict()); + + verify(db, never()).updateService(anyString(), any()); + } + + @Test + void updatingMissingServiceReturnsNotFound() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) + .andExpect(status().isNotFound()); + } + + @Test + void removesServiceAndItsContainers() throws Exception { + when(db.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(delete("/api/v1/services/Radarr")) + .andExpect(status().isNoContent()); + + verify(db).removeService("radarr"); + verify(docker).removeContainers("radarr"); + } + + @Test + void removingMissingServiceReturnsNotFound() throws Exception { + when(db.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(delete("/api/v1/services/radarr")) + .andExpect(status().isNotFound()); + + verify(docker, never()).removeContainers(anyString()); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java new file mode 100644 index 0000000..049aa09 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java @@ -0,0 +1,141 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.RequestBuilder; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(SetupController.class) +class SetupControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + SetupService setup; + + @MockBean + DatabaseService db; + + @Test + void reportsStatusForTheCallersSession() throws Exception { + when(setup.canConfigure("token")).thenReturn(true); + + mockMvc.perform(get("/api/v1/setup").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "token"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.completed").value(false)) + .andExpect(jsonPath("$.authorized").value(true)); + + mockMvc.perform(get("/api/v1/setup")) + .andExpect(jsonPath("$.authorized").value(false)); + } + + @Test + void correctPinSetsHttpOnlySessionCookie() throws Exception { + when(setup.startSession("123456")).thenReturn(Optional.of("token")); + + mockMvc.perform(pin("123456")) + .andExpect(status().isNoContent()) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString(SetupInterceptor.SESSION_COOKIE + "=token"))) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("HttpOnly"))) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("SameSite=Strict"))); + } + + @Test + void wrongPinIsUnauthorized() throws Exception { + when(setup.startSession("000000")).thenReturn(Optional.empty()); + + mockMvc.perform(pin("000000")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()) + .andExpect(header().doesNotExist(HttpHeaders.SET_COOKIE)); + } + + @Test + void pinIsGoneAfterSetupCompletes() throws Exception { + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(pin("123456")).andExpect(status().isGone()); + + verify(setup, never()).startSession(any()); + } + + @Test + void completeRequiresSession() throws Exception { + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + + verify(setup, never()).complete(); + } + + @Test + void completeRequiresAtLeastOneService() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(db.fetchServices()).thenReturn(List.of()); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("Add at least one service before finishing setup")); + + verify(setup, never()).complete(); + } + + @Test + void completeFinishesSetupAndClearsCookie() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(db.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isNoContent()) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Max-Age=0"))); + + verify(setup).complete(); + } + + @Test + void completeIsGoneWhenAlreadyCompleted() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(setup.canConfigure(any())).thenReturn(true); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isGone()); + + verify(setup, never()).complete(); + } + + @Test + void setupPageIsServedOnlyUntilSetupCompletes() throws Exception { + mockMvc.perform(get("/config")).andExpect(status().isOk()); + + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config.html")).andExpect(status().isNotFound()); + mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); + } + + private static RequestBuilder pin(String pin) { + return post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java new file mode 100644 index 0000000..b98caa6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java @@ -0,0 +1,41 @@ +package wellatleastitried.mediagarrdServer.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BackupArchiveTest { + + @TempDir + Path tempDir; + + @Test + void checksumIsFullLengthSha256Hex() throws Exception { + Path file = Files.writeString(tempDir.resolve("a.zip"), "abc"); + + assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", archive(file).generateChecksum()); + } + + @Test + void checksumKeepsLeadingZeros() throws Exception { + Path file = Files.writeString(tempDir.resolve("b.zip"), "message digest 179"); + + String checksum = archive(file).generateChecksum(); + + assertEquals(64, checksum.length()); + } + + @Test + void missingFileHasEmptyChecksum() { + assertEquals("", archive(tempDir.resolve("missing.zip")).generateChecksum()); + } + + private static BackupArchive archive(Path path) { + return new BackupArchive("id", path.getFileName().toString(), path, 0, Instant.EPOCH); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java new file mode 100644 index 0000000..80fa721 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java @@ -0,0 +1,57 @@ +package wellatleastitried.mediagarrdServer.model; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class ServiceDefinitionTest { + + @Test + void normalizesNameAndPaths() { + ServiceDefinition service = new ServiceDefinition(" radarr ", + Arrays.asList(" /srv/radarr/config/ ", null, "", "/srv/radarr/./data", "/srv/radarr/config")); + + assertEquals("radarr", service.name()); + assertEquals(List.of("/srv/radarr/config", "/srv/radarr/data"), service.paths()); + } + + @Test + void treatsMissingFieldsAsEmpty() { + ServiceDefinition service = new ServiceDefinition(null, null); + + assertEquals("", service.name()); + assertEquals(List.of(), service.paths()); + } + + @ParameterizedTest + @ValueSource(strings = {"radarr", "Radarr-4K", "qbit.torrent", "a", "service_2"}) + void acceptsValidNames(String name) { + assertDoesNotThrow(() -> new ServiceDefinition(name, List.of("/srv/data")).validate()); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"../etc", "-radarr", ".hidden", "has space", "a/b", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}) + void rejectsInvalidNames(String name) { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition(name, List.of("/srv/data")).validate()); + } + + @ParameterizedTest + @ValueSource(strings = {"relative/path", "/", "/..", "/srv/bad\npath"}) + void rejectsInvalidPaths(String path) { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("radarr", List.of(path)).validate()); + } + + @Test + void requiresAtLeastOnePath() { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("radarr", List.of(" ")).validate()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 1b4de04..947f80e 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -1,38 +1,301 @@ package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.contents; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.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.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; class BackupArchiveServiceTest { @TempDir Path tempDir; - @Test - void createsArchiveAndEnforcesRetention() throws Exception { - MediaGarrdProperties properties = new MediaGarrdProperties(); + private MediaGarrdProperties properties; + private DatabaseService db; + private BackupArchiveService service; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); properties.setBackupRoot(tempDir.resolve("backups").toString()); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); properties.setRetentionCount(2); + db = new DatabaseService(properties); + service = new BackupArchiveService(properties, db); + } + + @Test + void mergesEveryServiceIntoOneArchiveLaidOutByAbsolutePath() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr/config", tar(dir("config/"), file("config/config.xml", ""))); + part(run, "nginx", 0, "/etc/nginx/sites-available/default", tar(file("default", "server {}"))); + part(run, "nginx", 1, "/etc/nginx/sites-enabled", + tar(dir("sites-enabled/"), link("sites-enabled/default", TarConstants.LF_SYMLINK, "../sites-available/default"))); + + BackupArchive archive = service.createArchive(run); + service.removeRunDirectory(run); + + assertTrue(archive.fileName().endsWith(BackupArchiveService.ARCHIVE_SUFFIX)); + assertEquals(archive.fileName().replace(".zip", ""), archive.id()); + assertFalse(Files.exists(run)); + assertEquals(archive.id(), service.latest().orElseThrow().id()); + assertEquals( + List.of("etc/nginx/sites-available/default", "etc/nginx/sites-enabled/", "etc/nginx/sites-enabled/default", + "srv/radarr/config/", "srv/radarr/config/config.xml"), + List.copyOf(contents(archive.path()).keySet())); + assertEquals("", contents(archive.path()).get("srv/radarr/config/config.xml")); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + ZipArchiveEntry link = zip.getEntry("etc/nginx/sites-enabled/default"); + assertTrue(link.isUnixSymlink()); + assertEquals("../sites-available/default", zip.getUnixSymlink(link)); + } + } + + @Test + void mergeKeepsMetadataAndIncludesHardLinkParts() throws Exception { + Path run = service.createRunDirectory(); + Item secret = file("ssh/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setUserId(1000); + part(run, "ssh", 0, "/home/user/ssh", + tar(dir("ssh/"), secret, link("ssh/id_rsa.bak", TarConstants.LF_LINK, "ssh/id_rsa"))); + + BackupArchive archive = service.createArchive(run); + + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + ZipArchiveEntry key = zip.getEntry("home/user/ssh/id_rsa"); + assertEquals(UnixStat.FILE_FLAG | 0600, key.getUnixMode()); + assertEquals(1000, ((X7875_NewUnix) key.getExtraField(new X7875_NewUnix().getHeaderId())).getUID()); + assertEquals(UnixStat.FILE_FLAG | 0600, zip.getEntry("home/user/ssh/id_rsa.bak").getUnixMode()); + } + assertEquals("key", contents(archive.path()).get("home/user/ssh/id_rsa.bak")); + } + + @Test + void overlappingPathsAcrossServicesAppearOnce() throws Exception { + Path run = service.createRunDirectory(); + part(run, "a", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); + part(run, "b", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); + + BackupArchive archive = service.createArchive(run); + + assertEquals(Map.of("srv/shared/", "", "srv/shared/x", "1"), contents(archive.path())); + } + + @Test + void directoriesPrecedeTheirContentsAcrossParts() throws Exception { + Path run = service.createRunDirectory(); + Item restricted = dir("a/"); + restricted.entry().setMode(040700); + part(run, "child", 0, "/srv/a/b", tar(dir("b/"), file("b/x", "1"))); + part(run, "parent", 0, "/srv/a", tar(restricted, dir("a/b/"), file("a/b/x", "1"), file("a/y", "2"))); + + BackupArchive archive = service.createArchive(run); - BackupArchiveService service = new BackupArchiveService(properties); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + List order = java.util.Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList(); + assertEquals(List.of("srv/a/", "srv/a/b/", "srv/a/b/x", "srv/a/y"), order); + assertEquals(UnixStat.DIR_FLAG | 0700, zip.getEntry("srv/a/").getUnixMode()); + } + } + + @Test + void ignoresStrayFilesInRunDirectory() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("notes.txt"), "not a part"); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x"))); + + assertEquals(Map.of("srv/radarr", "x"), contents(service.createArchive(run).path())); + } + + @Test + void failedMergeLeavesNoArchiveBehind() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("corrupt.zip"), "not a zip"); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + } + } + + @Test + void retentionKeepsNewestArchivesAndIgnoresUnrelatedZips() throws Exception { + Path unrelated = Files.createDirectories(service.rootDirectory()).resolve("keep-me.zip"); + Files.writeString(unrelated, "not a backup"); for (int i = 0; i < 3; i++) { - Path run = service.createRunDirectory(); - Files.writeString(run.resolve("marker" + i + ".txt"), "ok"); - service.createArchive(run); - service.removeRunDirectory(run); + createArchive(); Thread.sleep(10); } assertEquals(2, service.listArchives().size()); - assertTrue(service.latest().isPresent()); + assertTrue(Files.exists(unrelated)); + } + + @Test + void deletesArchiveAndItsRecordById() throws Exception { + BackupArchive archive = createArchive(); + + assertTrue(service.deleteById(archive.id())); + + assertFalse(service.deleteById(archive.id())); + assertTrue(service.listArchives().isEmpty()); + assertTrue(db.fetchBackupById(archive.id()).isEmpty()); + } + + @Test + void retentionDeletesRecordsOfRemovedArchives() throws Exception { + BackupArchive oldest = createArchive(); + Thread.sleep(10); + createArchive(); + Thread.sleep(10); + BackupArchive newest = createArchive(); + + assertTrue(db.fetchBackupById(oldest.id()).isEmpty()); + assertTrue(db.fetchBackupById(newest.id()).isPresent()); + } + + @Test + void updatesAndPersistsRootDirectory() { + Path newRoot = tempDir.resolve("elsewhere/backups"); + + assertEquals(newRoot, service.updateRootDirectory(" " + newRoot + "/ ")); + + assertEquals(newRoot, service.rootDirectory()); + assertTrue(Files.isDirectory(newRoot)); + assertEquals(newRoot, new BackupArchiveService(properties, db).rootDirectory()); + } + + @Test + void createsArchivesInUpdatedRootDirectory() throws Exception { + Path newRoot = tempDir.resolve("moved"); + service.updateRootDirectory(newRoot.toString()); + + BackupArchive archive = createArchive(); + + assertEquals(newRoot, archive.path().getParent()); + assertEquals(1, service.listArchives().size()); + } + + @Test + void rejectsInvalidRootDirectories() throws Exception { + Path file = Files.writeString(tempDir.resolve("file"), "x"); + + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(null)); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(" ")); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("relative/backups")); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(file.toString())); + assertEquals(tempDir.resolve("backups"), service.rootDirectory()); + } + + @Test + void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { + for (int i = 0; i < 2; i++) { + createArchive(); + Thread.sleep(10); + } + + service.updateSettings(null, 1); + + assertEquals(1, service.retentionCount()); + assertEquals(2, service.listArchives().size()); + createArchive(); + assertEquals(1, service.listArchives().size()); + assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + } + + @Test + void usesPropertyRetentionUntilOneIsSaved() { + assertEquals(2, service.retentionCount()); + + properties.setRetentionCount(0); + assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + } + + @Test + void ignoresCorruptStoredRetention() { + db.saveSetting(RETENTION_COUNT_SETTING, "lots"); + assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + + db.saveSetting(RETENTION_COUNT_SETTING, "0"); + assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + } + + @Test + void updatesLocationAndRetentionTogether() { + Path newRoot = tempDir.resolve("both"); + + service.updateSettings(newRoot.toString(), 5); + + BackupArchiveService restarted = new BackupArchiveService(properties, db); + assertEquals(newRoot, restarted.rootDirectory()); + assertEquals(5, restarted.retentionCount()); + } + + @Test + void rejectsInvalidSettingsWithoutPartialWrites() { + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(null, null)); + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(null, 0)); + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(tempDir.resolve("never").toString(), -1)); + + assertFalse(Files.exists(tempDir.resolve("never"))); + assertEquals(tempDir.resolve("backups"), service.rootDirectory()); + assertEquals(2, service.retentionCount()); + assertTrue(db.fetchSetting(RETENTION_COUNT_SETTING).isEmpty()); + } + + @Test + void startupCleanupRemovesStaleArtifacts() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("partial.txt"), "x"); + Path tempZip = Files.writeString(service.rootDirectory().resolve("old" + BackupArchiveService.ARCHIVE_SUFFIX + ".tmp"), "x"); + + service.cleanupStaleArtifactsOnStartup(); + + assertFalse(Files.exists(run)); + assertFalse(Files.exists(tempZip)); + } + + 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)); + } + + private BackupArchive createArchive() throws Exception { + Path run = service.createRunDirectory(); + part(run, "marker", 0, "/srv/marker", tar(file("marker", "ok"))); + BackupArchive archive = service.createArchive(run); + service.removeRunDirectory(run); + db.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + return archive; } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java new file mode 100644 index 0000000..5c6f7fe --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -0,0 +1,229 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +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 static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +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 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); + + private final ServiceBackupRunner runner = mock(ServiceBackupRunner.class); + 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); + + @BeforeEach + void setUp() { + when(archives.createRunDirectory()).thenReturn(RUN_DIR); + when(archives.createArchive(RUN_DIR)).thenReturn(ARCHIVE); + } + + @AfterEach + void tearDown() { + orchestrator.shutdownRunnerExecutor(); + } + + @Test + void refusesToRunWithoutServices() { + when(db.fetchServices()).thenReturn(List.of()); + + assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + + verify(archives, never()).createRunDirectory(); + assertFalse(orchestrator.isRunning()); + } + + @Test + void completedWhenEveryServiceSucceeds() { + givenResults(COMPLETED, COMPLETED); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(COMPLETED, result.status()); + assertEquals("", result.errorMessage()); + assertEquals(List.of("radarr", "sonarr"), result.serviceNames()); + result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); + verify(schedule).markRunStarted(); + verify(db).addNewBackupRecord(result); + verify(archives).removeRunDirectory(RUN_DIR); + } + + @Test + void partialWhenSomeServicesFail() { + givenResults(COMPLETED, FAILED); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("sonarr: boom", result.errorMessage()); + } + + @Test + void failedWhenNoServiceCompletes() { + givenResults(PARTIAL, FAILED); + + assertEquals(FAILED, orchestrator.runBackup().status()); + } + + @Test + void skipsArchiveWhenEveryServiceFails() { + givenResults(FAILED, FAILED); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertTrue(e.getMessage().contains("radarr: boom\nsonarr: boom")); + verify(archives, never()).createArchive(any()); + verify(archives).removeRunDirectory(RUN_DIR); + assertFalse(orchestrator.isRunning()); + + ArgumentCaptor recorded = ArgumentCaptor.forClass(BackupRunResult.class); + verify(db).addNewBackupRecord(recorded.capture()); + BackupRunResult run = recorded.getValue(); + assertEquals(FAILED, run.status()); + assertNull(run.archive()); + assertEquals("radarr: boom\nsonarr: boom", run.errorMessage()); + run.serviceResults().forEach(r -> assertEquals(run.runId(), r.runId())); + } + + @Test + void runnerExceptionsBecomeFailedResults() { + when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(runner.run(RADARR, RUN_DIR)).thenThrow(new IllegalStateException("crashed")); + when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", COMPLETED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("radarr: crashed", result.errorMessage()); + } + + @Test + void cleansUpWhenArchivingFails() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(archives).removeRunDirectory(RUN_DIR); + verify(db, never()).addNewBackupRecord(any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void rejectsConcurrentRuns() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertTrue(orchestrator.isRunning()); + assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + + release.countDown(); + assertEquals(COMPLETED, first.get(5, TimeUnit.SECONDS).status()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void configChangesRunWhileIdle() { + assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + } + + @Test + void configChangesAreRejectedDuringABackupRun() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + + CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertThrows(BackupOrchestratorService.BackupInProgressException.class, () -> orchestrator.whileIdle(() -> "changed")); + + release.countDown(); + run.get(5, TimeUnit.SECONDS); + assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + } + + @Test + void backupWaitsForInFlightConfigChange() throws Exception { + CountDownLatch changing = new CountDownLatch(1); + CountDownLatch finishChange = new CountDownLatch(1); + givenResults(COMPLETED, COMPLETED); + + CompletableFuture change = CompletableFuture.supplyAsync(() -> orchestrator.whileIdle(() -> { + changing.countDown(); + try { + finishChange.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "changed"; + })); + assertTrue(changing.await(5, TimeUnit.SECONDS)); + + CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); + Thread.sleep(100); + assertFalse(run.isDone()); + verify(db, never()).fetchServices(); + + finishChange.countDown(); + assertEquals("changed", change.get(5, TimeUnit.SECONDS)); + assertEquals(COMPLETED, run.get(5, TimeUnit.SECONDS).status()); + } + + private void givenResults(String radarrStatus, String sonarrStatus) { + when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(runner.run(RADARR, RUN_DIR)).thenReturn(result("radarr", radarrStatus)); + when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", sonarrStatus)); + } + + 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/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index f54453e..e54ab04 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -3,31 +3,84 @@ 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 wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; +import java.nio.file.Path; import java.time.Duration; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; class BackupScheduleServiceTest { - @Test - void updatesAndEvaluatesDueState() { - MediaGarrdProperties props = new MediaGarrdProperties(); - props.setBackupInterval(Duration.ofMillis(1)); + @TempDir + Path tempDir; + + private MediaGarrdProperties properties; + private DatabaseService db; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new DatabaseService(properties); + } - BackupScheduleService service = new BackupScheduleService(props); + @Test + void updatesAndEvaluatesDueState() throws Exception { + BackupScheduleService service = new BackupScheduleService(properties, db); service.updateInterval(Duration.ofMillis(1)); assertEquals(Duration.ofMillis(1), service.getInterval()); - assertFalse(service.dueNow()); - try { - Thread.sleep(5); - } catch (InterruptedException ignored) { - } + Thread.sleep(5); assertTrue(service.dueNow()); } + + @Test + void notDueUntilIntervalElapses() { + BackupScheduleService service = new BackupScheduleService(properties, db); + + assertFalse(service.dueNow()); + } + + @Test + void usesPropertyIntervalUntilOneIsSaved() { + properties.setBackupInterval(Duration.ofHours(3)); + + assertEquals(Duration.ofHours(3), new BackupScheduleService(properties, db).getInterval()); + } + + @Test + void persistsUpdatedIntervalAcrossRestarts() { + properties.setBackupInterval(Duration.ofHours(3)); + new BackupScheduleService(properties, db).updateInterval(Duration.ofMinutes(45)); + + assertEquals(Optional.of("PT45M"), db.fetchSetting(BACKUP_INTERVAL_SETTING)); + assertEquals(Duration.ofMinutes(45), new BackupScheduleService(properties, db).getInterval()); + } + + @Test + void invalidIntervalsFallBackToTwelveHours() { + BackupScheduleService service = new BackupScheduleService(properties, db); + + assertEquals(Duration.ofHours(12), service.updateInterval(null)); + assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ZERO)); + assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ofMinutes(-5))); + } + + @Test + void ignoresCorruptStoredInterval() { + properties.setBackupInterval(Duration.ofHours(2)); + db.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); + assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + + db.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); + assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java index 8ddd9b0..6c74602 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java @@ -1,162 +1,342 @@ package wellatleastitried.mediagarrdServer.service; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; -import static wellatleastitried.mediagarrdServer.utilities.ServiceConstants.SUPPORTED_SERVICES; +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.assertTrue; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Proxy; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.time.Instant; import java.util.List; import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.AfterEach; 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.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; -import wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status; - -public class DatabaseServiceTest { - - String testBackupId = "testId"; - String testStartTime = "testStartTime"; - String testEndTime = "testEndTime"; - String testFilename = "testFilename"; - Path testFilePath = Paths.get("testFilePath"); - long testFileSize = 1337; - Instant testInstant = Instant.now(); - BackupArchive testArchive = new BackupArchive(testBackupId, testFilename, testFilePath, testFileSize, testInstant); - String testErrorMessage = "testErrorMessage"; - - String serviceOneStartTime = "testStartTime1"; - String serviceOneEndTime = "testEndTime1"; - String serviceTwoStartTime = "testStartTime2"; - String serviceTwoEndTime = "testEndTime2"; - String serviceThreeStartTime = "testStartTime3"; - String serviceThreeEndTime = null; - - private DatabaseService databaseService; - private Connection testConnection; - - private Connection wrapUncloseable(Connection real) { - return (Connection) Proxy.newProxyInstance( - Connection.class.getClassLoader(), - new Class[] { Connection.class }, - (proxy, method, args) -> { - // Need to "swallor" null so the in-memory database survives - if ("close".equals(method.getName())) { - return null; - } - try { - return method.invoke(real, args); - } catch (InvocationTargetException e) { - throw e.getCause(); - } - } - ); - } +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class DatabaseServiceTest { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @TempDir + Path tempDir; + + private MediaGarrdProperties properties; + private DatabaseService db; @BeforeEach - public void setUp() throws SQLException { - testConnection = DriverManager.getConnection("jdbc:sqlite::memory:"); - Connection uncloseable = wrapUncloseable(testConnection); - databaseService = new DatabaseService() { + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("nested/mediagarrd.db").toString()); + db = new DatabaseService(properties); + } + + @Test + void createsDatabaseFileAndParentDirectories() { + assertTrue(Files.isRegularFile(tempDir.resolve("nested/mediagarrd.db"))); + assertTrue(db.verifyDatabaseIntegrity()); + assertTrue(db.verifyDatabaseIntegrity()); + } + + @Test + void storesBackupRecordWithEveryServiceResult() { + db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", + serviceResult("jellyfin", COMPLETED, null), + serviceResult("sonarr", PARTIAL, "one path failed"), + serviceResult("qbittorrent", FAILED, "no paths copied"))); + + FetchedBackupRecord record = db.fetchBackupById("run-1").orElseThrow(); + + assertEquals("run-1", record.archiveId()); + assertEquals("2026-01-01 00:00:00", record.startTime()); + assertEquals(COMPLETED, record.status()); + assertEquals(Path.of("run-1.zip").toString(), record.filePath()); + assertEquals( + Set.of( + new FetchedBackupServiceRecord("jellyfin", COMPLETED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", null), + new FetchedBackupServiceRecord("sonarr", PARTIAL, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "one path failed"), + new FetchedBackupServiceRecord("qbittorrent", FAILED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "no paths copied")), + Set.copyOf(record.fetchedServices())); + } + + @Test + void storesFailedRunWithoutArchive() { + db.addNewBackupRecord(new BackupRunResult("failed-1", "2026-01-01 00:00:00", "2026-01-01 00:00:01", FAILED, + List.of(serviceResult("radarr", FAILED, "boom")), null, "radarr: boom")); + + FetchedBackupRecord record = db.fetchBackupById("failed-1").orElseThrow(); + + assertEquals(FAILED, record.status()); + assertNull(record.filePath()); + assertEquals("radarr: boom", record.errorMessage()); + assertEquals(1, record.fetchedServices().size()); + } + + @Test + void fetchesLatestBackupRecordByStartTime() { + db.addNewBackupRecord(backupRun("older", "2026-01-01 00:00:00")); + db.addNewBackupRecord(backupRun("newer", "2026-02-01 00:00:00")); + + assertEquals("newer", db.fetchLatestBackupRecord().orElseThrow().archiveId()); + } + + @Test + void returnsEmptyForMissingBackupRecords() { + assertTrue(db.fetchBackupById("missing").isEmpty()); + assertTrue(db.fetchLatestBackupRecord().isEmpty()); + } + + @Test + void deletesBackupRecord() { + db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00")); + + db.deleteBackupRecordById("run-1"); + + assertTrue(db.fetchBackupById("run-1").isEmpty()); + } + + @Test + void deletingBackupRecordCascadesToServiceRows() throws Exception { + db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + assertEquals(1, count("backup_services")); + + db.deleteBackupRecordById("run-1"); + + assertEquals(0, count("backup_services")); + } + + @Test + void migrationRemovesOrphanedServiceRows() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + new DatabaseService(properties); + + assertEquals(0, count("backup_services")); + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("PRAGMA user_version")) { + assertEquals(2, rs.getInt(1)); + } + } + + @Test + void storesAndFetchesServicesWithPathOrderPreserved() { + assertEquals(List.of(), db.fetchServices()); + + db.addService(RADARR); + + assertEquals(Optional.of(RADARR), db.fetchService("radarr")); + assertEquals(Optional.of(RADARR), db.fetchService("RADARR")); + assertEquals(List.of(RADARR), db.fetchServices()); + } + + @Test + void listsServicesSortedByNameIgnoringCase() { + db.addService(new ServiceDefinition("sonarr", List.of("/a"))); + db.addService(new ServiceDefinition("Jellyfin", List.of("/b"))); + db.addService(new ServiceDefinition("radarr", List.of("/c"))); + + assertEquals(List.of("Jellyfin", "radarr", "sonarr"), db.fetchServices().stream().map(ServiceDefinition::name).toList()); + } + + @Test + void rejectsDuplicateServiceNamesIgnoringCase() { + db.addService(RADARR); + + assertThrows(IllegalStateException.class, () -> db.addService(new ServiceDefinition("Radarr", List.of("/other")))); + } + + @Test + void updatesServiceNameAndPaths() { + db.addService(RADARR); + ServiceDefinition renamed = new ServiceDefinition("radarr-4k", List.of("/srv/radarr-4k")); + + assertTrue(db.updateService("radarr", renamed)); + + assertTrue(db.fetchService("radarr").isEmpty()); + assertEquals(Optional.of(renamed), db.fetchService("radarr-4k")); + assertFalse(db.updateService("missing", renamed)); + } + + @Test + void removesService() { + db.addService(RADARR); + + assertTrue(db.removeService("radarr")); + assertFalse(db.removeService("radarr")); + assertEquals(List.of(), db.fetchServices()); + } + + @Test + void savesAndOverwritesSettings() { + assertTrue(db.fetchSetting("backup_root").isEmpty()); + + db.saveSetting("backup_root", "/first"); + db.saveSetting("backup_root", "/second"); + + assertEquals(Optional.of("/second"), db.fetchSetting("backup_root")); + } + + @Test + void persistsDataAcrossInstances() { + db.addService(RADARR); + db.saveSetting("backup_root", "/backups"); + + DatabaseService reopened = new DatabaseService(properties); + + assertEquals(List.of(RADARR), reopened.fetchServices()); + assertEquals(Optional.of("/backups"), reopened.fetchSetting("backup_root")); + } + + @Test + void failsLoudlyWhenDatabaseIsUnusable() { + properties.setDatabasePath(tempDir.toString()); + DatabaseService broken = new DatabaseService(properties); + + assertFalse(broken.verifyDatabaseIntegrity()); + assertThrows(IllegalStateException.class, broken::fetchServices); + assertThrows(IllegalStateException.class, () -> broken.addService(RADARR)); + assertThrows(IllegalStateException.class, () -> broken.fetchSetting("backup_root")); + } + + @Test + void verifiesOnlyOnceWhileTheSchemaIsUnchanged() { + AtomicInteger verifications = new AtomicInteger(); + DatabaseService counted = new DatabaseService(properties) { @Override - protected Connection getConnection() throws SQLException { - return uncloseable; + protected synchronized boolean verifyDatabaseIntegrity() { + verifications.incrementAndGet(); + return super.verifyDatabaseIntegrity(); } }; + + counted.addService(RADARR); + counted.fetchServices(); + counted.fetchSetting("backup_root"); + + assertEquals(1, verifications.get()); } - @AfterEach - public void tearDown() throws SQLException { - testConnection.close(); + @Test + void rebuildsWhenTheDatabaseFileIsDeleted() throws Exception { + db.addService(RADARR); + + Files.delete(databaseFile()); + + assertEquals(List.of(), db.fetchServices()); + db.addService(RADARR); + assertEquals(List.of(RADARR), db.fetchServices()); } @Test - public void testDatabaseIntegrity() { - boolean hasIntegrity = databaseService.verifyDatabaseIntegrity(); - assertEquals(true, hasIntegrity); + void rebuildsWhenTheDatabaseDirectoryIsDeleted() throws Exception { + Files.delete(databaseFile()); + Files.delete(databaseFile().getParent()); + + db.saveSetting("backup_root", "/backups"); + + assertEquals(Optional.of("/backups"), db.fetchSetting("backup_root")); } @Test - public void testConnection() throws SQLException { - try (var connection = databaseService.getConnection()) { - assertEquals(true, connection.isValid(10)); - } catch (SQLException sE) { fail(sE); } + void rebuildsWhenATableIsDropped() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("DROP TABLE services"); + } + + db.addService(RADARR); + + assertEquals(List.of(RADARR), db.fetchServices()); } - private BackupRunResult buildTestBackupRunResult() { - List testServiceResults = List.of( - new BackupServiceResult(testBackupId, Status.COMPLETED, serviceOneStartTime, serviceOneEndTime, SUPPORTED_SERVICES.get(Services.JELLYFIN), testErrorMessage), - new BackupServiceResult(testBackupId, Status.PARTIAL, serviceTwoStartTime, serviceTwoEndTime, SUPPORTED_SERVICES.get(Services.SONARR), testErrorMessage), - new BackupServiceResult(testBackupId, Status.FAILED, serviceThreeStartTime, serviceThreeEndTime, SUPPORTED_SERVICES.get(Services.QBITTORRENT), testErrorMessage) - ); - return new BackupRunResult( - testBackupId, - testStartTime, - testEndTime, - Status.COMPLETED, - testServiceResults, - testArchive, - testErrorMessage - ); + @Test + void migratesWhenAnOlderDatabaseIsSwappedIn() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + db.fetchServices(); + + assertEquals(0, count("backup_services")); } @Test - public void testAddingBackupRecord() { - BackupRunResult testBackupRecord = buildTestBackupRunResult(); + void movesACorruptDatabaseAsideOnStartup() throws Exception { + Files.writeString(databaseFile(), "x".repeat(4096)); - databaseService.addNewBackupRecord(testBackupRecord); + DatabaseService recovered = new DatabaseService(properties); - Optional optionalTestRecord = databaseService.fetchBackupById(testArchive.id()); - FetchedBackupRecord testRecord = optionalTestRecord.isPresent() ? optionalTestRecord.orElseThrow() : null; + recovered.addService(RADARR); + assertEquals(List.of(RADARR), recovered.fetchServices()); + assertEquals(List.of("x".repeat(4096)), quarantinedContents()); + } - assertEquals(testBackupId, testRecord.archiveId()); - assertEquals(testFilePath.toString(), testRecord.filePath()); - assertEquals(testStartTime, testRecord.startTime()); - assertEquals(testEndTime, testRecord.endTime()); - for (FetchedBackupServiceRecord testServiceResult : testRecord.fetchedServices()) { - if (SUPPORTED_SERVICES.get(Services.JELLYFIN).equals(testServiceResult.serviceName())) { - assertEquals(serviceOneStartTime, testServiceResult.startTime()); - assertEquals(serviceOneEndTime, testServiceResult.endTime()); - assertEquals(Status.COMPLETED, testServiceResult.status()); - assertEquals(testErrorMessage, testServiceResult.errorMessage()); + @Test + void movesACorruptDatabaseAsideWhileRunning() throws Exception { + db.addService(RADARR); + Files.writeString(databaseFile(), "x".repeat(4096)); - } else if (SUPPORTED_SERVICES.get(Services.SONARR).equals(testServiceResult.serviceName())) { - assertEquals(serviceTwoStartTime, testServiceResult.startTime()); - assertEquals(serviceTwoEndTime, testServiceResult.endTime()); - assertEquals(Status.PARTIAL, testServiceResult.status()); - assertEquals(testErrorMessage, testServiceResult.errorMessage()); - } else if (SUPPORTED_SERVICES.get(Services.QBITTORRENT).equals(testServiceResult.serviceName())) { - assertEquals(serviceThreeStartTime, testServiceResult.startTime()); - assertEquals(serviceThreeEndTime, testServiceResult.endTime()); - assertEquals(Status.FAILED, testServiceResult.status()); - assertEquals(testErrorMessage, testServiceResult.errorMessage()); - } else { - fail("UNREACHABLE"); - } + assertEquals(List.of(), db.fetchServices()); + assertEquals(1, quarantinedContents().size()); + } + + private Path databaseFile() { + return Path.of(properties.getDatabasePath()); + } + + private List quarantinedContents() throws IOException { + try (var files = Files.list(databaseFile().getParent())) { + return files + .filter(file -> file.getFileName().toString().startsWith("mediagarrd.db.corrupt-")) + .map(file -> { + try { + return Files.readString(file); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) + .toList(); } } - @Test - public void testDeletingBackupRecord() { - BackupRunResult testBackupRecord = buildTestBackupRunResult(); - databaseService.addNewBackupRecord(testBackupRecord); - databaseService.deleteBackupRecordById(testBackupRecord.runId()); - Optional optionalTestFetchedBackupRecord = databaseService.fetchBackupById(testBackupRecord.runId()); - assertEquals(true, optionalTestFetchedBackupRecord.isEmpty()); - System.out.println("TEST"); + private Connection rawConnection() throws SQLException { + return DriverManager.getConnection("jdbc:sqlite:" + properties.getDatabasePath()); + } + + private int count(String table) throws SQLException { + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM " + table)) { + return rs.getInt(1); + } + } + + private static BackupRunResult backupRun(String id, String startTime, BackupServiceResult... services) { + BackupArchive archive = new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, Instant.parse("2026-01-01T00:00:00Z")); + return new BackupRunResult(id, startTime, startTime, COMPLETED, List.of(services), archive, null); + } + + private static BackupServiceResult serviceResult(String name, String status, String error) { + return new BackupServiceResult(null, status, "2026-01-01 00:00:00", "2026-01-01 00:00:01", name, error); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java new file mode 100644 index 0000000..d9fca86 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java @@ -0,0 +1,179 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_SELF; +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.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.MountType; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class DockerServiceTest { + + private static final String IMAGE = "busybox:stable"; + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + private final DockerClient client = mock(DockerClient.class); + private final ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF); + private final CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF); + private final RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF); + private final InspectImageCmd inspectCmd = mock(InspectImageCmd.class); + private DockerService docker; + + @BeforeEach + void setUp() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setHelperImage(IMAGE); + docker = new DockerService(client, properties); + + when(client.listContainersCmd()).thenReturn(listCmd); + when(client.createContainerCmd(IMAGE)).thenReturn(createCmd); + when(client.removeContainerCmd(anyString())).thenReturn(removeCmd); + when(client.inspectImageCmd(IMAGE)).thenReturn(inspectCmd); + CreateContainerResponse created = new CreateContainerResponse(); + created.setId("new-id"); + when(createCmd.exec()).thenReturn(created); + } + + @Test + void createsReadOnlyNetworklessHelperContainer() { + when(listCmd.exec()).thenReturn(List.of()); + + assertEquals("new-id", docker.containerFor(RADARR)); + + verify(listCmd).withLabelFilter(Map.of(DockerService.SERVICE_LABEL, "radarr")); + verify(createCmd).withName("mediagarrd-backup-radarr"); + verify(createCmd).withLabels(Map.of( + DockerService.SERVICE_LABEL, "radarr", + DockerService.CONFIG_HASH_LABEL, docker.configHash(RADARR))); + ArgumentCaptor hostConfig = ArgumentCaptor.forClass(HostConfig.class); + verify(createCmd).withHostConfig(hostConfig.capture()); + assertEquals("none", hostConfig.getValue().getNetworkMode()); + assertEquals( + List.of(bind("/srv/radarr/config"), bind("/srv/radarr/data")), + hostConfig.getValue().getMounts().stream().map(DockerServiceTest::describe).toList()); + verify(client, never()).startContainerCmd(anyString()); + } + + @Test + void reusesContainerWithMatchingConfigHash() { + Container existing = container("existing", docker.configHash(RADARR)); + when(listCmd.exec()).thenReturn(List.of(existing)); + + assertEquals("existing", docker.containerFor(RADARR)); + + verify(client, never()).createContainerCmd(anyString()); + verify(client, never()).removeContainerCmd(anyString()); + } + + @Test + void replacesContainerWhenConfigChanged() { + Container stale = container("stale", "old-hash"); + when(listCmd.exec()).thenReturn(List.of(stale)); + + assertEquals("new-id", docker.containerFor(RADARR)); + + verify(client).removeContainerCmd("stale"); + verify(removeCmd).withForce(true); + } + + @Test + void pullsHelperImageOnlyWhenMissing() throws Exception { + when(listCmd.exec()).thenReturn(List.of()); + when(inspectCmd.exec()).thenThrow(new NotFoundException("missing")); + PullImageCmd pullCmd = mock(PullImageCmd.class); + PullImageResultCallback callback = mock(PullImageResultCallback.class); + when(client.pullImageCmd(IMAGE)).thenReturn(pullCmd); + when(pullCmd.start()).thenReturn(callback); + when(callback.awaitCompletion(anyLong(), any(TimeUnit.class))).thenReturn(true); + + docker.containerFor(RADARR); + + verify(client).pullImageCmd(IMAGE); + } + + @Test + void failsWhenHelperImagePullTimesOut() throws Exception { + when(listCmd.exec()).thenReturn(List.of()); + when(inspectCmd.exec()).thenThrow(new NotFoundException("missing")); + PullImageCmd pullCmd = mock(PullImageCmd.class); + PullImageResultCallback callback = mock(PullImageResultCallback.class); + when(client.pullImageCmd(IMAGE)).thenReturn(pullCmd); + when(pullCmd.start()).thenReturn(callback); + when(callback.awaitCompletion(anyLong(), any(TimeUnit.class))).thenReturn(false); + + assertThrows(IllegalStateException.class, () -> docker.containerFor(RADARR)); + verify(client, never()).createContainerCmd(anyString()); + } + + @Test + void removeContainersNeverThrows() { + List containers = List.of(container("a", "x"), container("b", "y")); + when(listCmd.exec()).thenReturn(containers); + when(removeCmd.exec()).thenThrow(new NotFoundException("gone")).thenThrow(new RuntimeException("daemon down")); + + docker.removeContainers("radarr"); + + verify(client).removeContainerCmd("a"); + verify(client).removeContainerCmd("b"); + } + + @Test + void configHashDependsOnPathsNotTheirOrder() { + ServiceDefinition reordered = new ServiceDefinition("other", List.of("/srv/radarr/data", "/srv/radarr/config")); + ServiceDefinition changed = new ServiceDefinition("radarr", List.of("/srv/radarr/config")); + + assertEquals(docker.configHash(RADARR), docker.configHash(reordered)); + assertNotEquals(docker.configHash(RADARR), docker.configHash(changed)); + } + + @Test + void mapsHostPathsUnderMountRoot() { + assertEquals("/mnt/srv/radarr/config", DockerService.containerPath("/srv/radarr/config")); + } + + private static Container container(String id, String hash) { + Container container = mock(Container.class); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(Map.of(DockerService.SERVICE_LABEL, "radarr", DockerService.CONFIG_HASH_LABEL, hash)); + return container; + } + + private static String bind(String hostPath) { + return MountType.BIND + " " + hostPath + " -> /mnt" + hostPath + " ro=true"; + } + + private static String describe(Mount mount) { + return mount.getType() + " " + mount.getSource() + " -> " + mount.getTarget() + " ro=" + mount.getReadOnly(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java deleted file mode 100644 index 4c1c9c0..0000000 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RealRunnersInteractiveCheck.java +++ /dev/null @@ -1,120 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.services.runner.Runner; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -public final class RealRunnersInteractiveCheck { - - private RealRunnersInteractiveCheck() { - } - - public static void main(String[] args) throws Exception { - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - - System.out.println("=== Real Runner Integration Check ==="); - System.out.println("This check prompts for local directory/file paths on the server host."); - System.out.println("Any service you skip will not be run."); - - EnumMap configs = new EnumMap<>(Services.class); - configs.put(Services.JELLYFIN, promptJellyfin(reader)); - configs.put(Services.RADARR, promptPathService(reader, "Radarr")); - configs.put(Services.SONARR, promptPathService(reader, "Sonarr")); - configs.put(Services.PROWLARR, promptPathService(reader, "Prowlarr")); - configs.put(Services.TDARR, promptPathService(reader, "Tdarr")); - configs.put(Services.QBITTORRENT, promptQbittorrent(reader)); - - RunnerFactory factory = new RunnerFactory(); - List runners = factory.build(configs); - if (runners.isEmpty()) { - throw new IllegalStateException("No runners enabled. Re-run and enable at least one service."); - } - - Path output = Files.createTempDirectory("real-runner-output-"); - - System.out.println("Running " + runners.size() + " runners..."); - for (Runner runner : runners) { - System.out.println("- Running: " + runner.getServiceName()); - runner.run(output); - } - - long fileCount; - try (var walk = Files.walk(output)) { - fileCount = walk.filter(Files::isRegularFile).count(); - } - - if (fileCount <= 0) { - throw new IllegalStateException("No files were discovered/written by enabled runners."); - } - - System.out.println("Runner output directory: " + output); - System.out.println("Total files discovered: " + fileCount); - } - - private static AbstractServiceConfig promptJellyfin(BufferedReader reader) throws Exception { - CommonServiceConfig config = new CommonServiceConfig(); - boolean enabled = askYesNo(reader, "Enable Jellyfin runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - config.setConfigPath(ask(reader, "Jellyfin config directory", "/mnt/appdata/jellyfin/config")); - return config; - } - - private static AbstractServiceConfig promptPathService(BufferedReader reader, String label) throws Exception { - CommonServiceConfig config = new CommonServiceConfig(); - boolean enabled = askYesNo(reader, "Enable " + label + " runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - String lower = label.toLowerCase(Locale.ROOT); - config.setPath(ask(reader, label + " base directory", "/mnt/appdata/" + lower)); - return config; - } - - private static AbstractServiceConfig promptQbittorrent(BufferedReader reader) throws Exception { - QBittorrentServiceConfig config = new QBittorrentServiceConfig(); - boolean enabled = askYesNo(reader, "Enable qBittorrent runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - config.setPath(ask(reader, "qBittorrent base directory", "/mnt/appdata/qbittorrent")); - config.setSavedTorrentsPath(ask(reader, "qBittorrent saved torrents directory", "/mnt/media/saved-torrents")); - return config; - } - - private static String ask(BufferedReader reader, String prompt, String defaultValue) throws Exception { - System.out.print(prompt + (defaultValue == null || defaultValue.isBlank() ? ": " : " [" + defaultValue + "]: ")); - String line = reader.readLine(); - if (line == null) { - return defaultValue == null ? "" : defaultValue; - } - String trimmed = line.trim(); - if (trimmed.isEmpty()) { - return defaultValue == null ? "" : defaultValue; - } - return trimmed; - } - - private static boolean askYesNo(BufferedReader reader, String prompt, boolean defaultValue) throws Exception { - String fallback = defaultValue ? "y" : "n"; - String answer = ask(reader, prompt, fallback).toLowerCase(Locale.ROOT); - return answer.equals("y") || answer.equals("yes") || answer.equals("true"); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java deleted file mode 100644 index 8c625e7..0000000 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/RunnersIntegrationTest.java +++ /dev/null @@ -1,201 +0,0 @@ -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.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrdServer.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrdServer.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrdServer.services.runner.Runner; -import wellatleastitried.mediagarrdServer.utilities.ServiceConstants.Services; - -@Tag("real-runners") -class RunnersIntegrationTest { - - @TempDir - Path tempDir; - - @Test - void enabledRunnersCopyFilesFromConfiguredPaths() throws Exception { - Map env = loadEnv(); - - EnumMap configs = new EnumMap<>(Services.class); - - addJellyfin(configs, env); - addPathService(configs, env, Services.RADARR); - addPathService(configs, env, Services.SONARR); - addPathService(configs, env, Services.PROWLARR); - addPathService(configs, env, Services.TDARR); - addQbittorrent(configs, env); - - RunnerFactory factory = new RunnerFactory(); - List runners = factory.build(configs); - assertFalse(runners.isEmpty(), "No runners enabled in .env/.env.test."); - - Path outputDirectory = tempDir.resolve("runner-output"); - Files.createDirectories(outputDirectory); - - for (Runner runner : runners) { - runner.run(outputDirectory); - } - - assertEquals(configs.size(), runners.size()); - for (Runner runner : runners) { - Path serviceOutput = outputDirectory.resolve(runner.getServiceName().toLowerCase(Locale.ROOT)); - assertTrue(Files.exists(serviceOutput), "Missing service output directory: " + serviceOutput); - - try (var walk = Files.walk(serviceOutput)) { - assertTrue( - walk.anyMatch(Files::isRegularFile), - "No files copied for service " + runner.getServiceName() - ); - } - } - } - - private void addJellyfin(EnumMap configs, Map env) { - boolean enabled = booleanValue(env, "JELLYFIN_ENABLED", "jellyfin_enabled", false); - if (!enabled) { - return; - } - - CommonServiceConfig config = new CommonServiceConfig(); - config.setEnabled(true); - config.setConfigPath(required(env, "JELLYFIN_CONFIG_PATH", "jellyfin_config_path")); - - configs.put(Services.JELLYFIN, config); - } - - private void addQbittorrent(EnumMap configs, Map env) { - boolean enabled = booleanValue(env, "QBITTORRENT_ENABLED", "qbittorrent_enabled", false); - if (!enabled) { - return; - } - - QBittorrentServiceConfig config = new QBittorrentServiceConfig(); - config.setEnabled(true); - config.setPath(required(env, "QBITTORRENT_PATH", "qbittorrent_path")); - config.setSavedTorrentsPath(required(env, "QBITTORRENT_SAVED_TORRENTS_PATH", "qbittorrent_saved_torrents_path")); - - configs.put(Services.QBITTORRENT, config); - } - - private void addPathService( - EnumMap configs, - Map env, - Services service - ) { - String key = service.name().toLowerCase(Locale.ROOT); - String upper = service.name(); - boolean enabled = booleanValue(env, upper + "_ENABLED", key + "_enabled", false); - if (!enabled) { - return; - } - - CommonServiceConfig config = new CommonServiceConfig(); - config.setEnabled(true); - config.setPath(required(env, upper + "_PATH", key + "_path")); - - configs.put(service, config); - } - - private Map loadEnv() throws IOException { - Map merged = new HashMap<>(); - merged.putAll(parseDotEnv(resolveEnvFile())); - merged.putAll(System.getenv()); - return merged; - } - - private Path resolveEnvFile() { - String override = System.getenv("MEDIAGARRD_TEST_ENV_FILE"); - if (override != null && !override.isBlank()) { - Path explicit = Path.of(override).toAbsolutePath().normalize(); - if (Files.exists(explicit)) { - return explicit; - } - throw new IllegalStateException("MEDIAGARRD_TEST_ENV_FILE not found: " + explicit); - } - - Path current = Path.of("").toAbsolutePath(); - for (int i = 0; i < 8 && current != null; i++) { - Path testEnv = current.resolve(".env.test"); - if (Files.exists(testEnv)) { - return testEnv; - } - Path prodEnv = current.resolve(".env"); - if (Files.exists(prodEnv)) { - return prodEnv; - } - current = current.getParent(); - } - - throw new IllegalStateException("No .env.test or .env found. Create one from .env.test.example or .env.example."); - } - - private Map parseDotEnv(Path file) throws IOException { - Map values = new HashMap<>(); - List lines = Files.readAllLines(file); - for (String rawLine : lines) { - if (rawLine == null) { - continue; - } - String line = rawLine.trim(); - if (line.isBlank() || line.startsWith("#")) { - continue; - } - int idx = line.indexOf('='); - if (idx <= 0) { - continue; - } - String key = line.substring(0, idx).trim(); - String value = line.substring(idx + 1).trim(); - if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) { - value = value.substring(1, value.length() - 1); - } - values.put(key, value); - } - return values; - } - - private String required(Map env, String... keys) { - String value = firstPresent(env, keys); - if (value == null || value.isBlank()) { - throw new IllegalStateException("Missing required .env key. Expected one of: " + String.join(", ", keys)); - } - return value; - } - - private boolean booleanValue(Map env, String keyUpper, String keyLower, boolean fallback) { - String value = firstPresent(env, keyUpper, keyLower); - if (value == null || value.isBlank()) { - return fallback; - } - String normalized = value.trim().toLowerCase(Locale.ROOT); - return normalized.equals("1") || normalized.equals("true") || normalized.equals("yes") || normalized.equals("y") || normalized.equals("on"); - } - - private String firstPresent(Map env, String... keys) { - for (String key : keys) { - String value = env.get(key); - if (value != null) { - return value; - } - } - return null; - } - -} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java new file mode 100644 index 0000000..62fee1b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java @@ -0,0 +1,277 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.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.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class ServiceBackupRunnerTest { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @TempDir + Path runDir; + + private final DockerService docker = mock(DockerService.class); + private final ServiceBackupRunner runner = new ServiceBackupRunner(docker); + + @Test + void storesDirectoryContentsUnderTheirAbsolutePaths() throws Exception { + when(docker.containerFor(RADARR)).thenReturn("cid"); + when(docker.copyFrom("cid", "/srv/radarr/config")).thenReturn(tar( + dir("config/"), file("config/config.xml", ""), dir("config/empty/"), file("config/logs/app.log", "log"))); + when(docker.copyFrom("cid", "/srv/radarr/data")).thenReturn(tar(dir("data/"), file("data/radarr.db", "db"))); + + BackupServiceResult result = runner.run(RADARR, runDir); + + assertEquals(COMPLETED, result.status()); + assertNull(result.errorMessage()); + Map config = contents(runDir.resolve("radarr/0.zip")); + assertEquals(List.of("srv/radarr/config/", "srv/radarr/config/config.xml", "srv/radarr/config/empty/", "srv/radarr/config/logs/app.log"), + List.copyOf(config.keySet())); + assertEquals("", config.get("srv/radarr/config/config.xml")); + assertEquals("db", contents(runDir.resolve("radarr/1.zip")).get("srv/radarr/data/radarr.db")); + } + + @Test + void storesOnlyTheFileWhenPathIsAFile() throws Exception { + ServiceDefinition nginx = new ServiceDefinition("nginx", List.of("/etc/nginx/sites-available/config")); + when(docker.containerFor(nginx)).thenReturn("cid"); + when(docker.copyFrom("cid", "/etc/nginx/sites-available/config")).thenReturn(tar(file("config", "server {}"))); + + assertEquals(COMPLETED, runner.run(nginx, runDir).status()); + + assertEquals(Map.of("etc/nginx/sites-available/config", "server {}"), contents(runDir.resolve("nginx/0.zip"))); + } + + static Stream archivedEntries() { + return Stream.of( + Arguments.of("top-level path", "/opt", + new Item[] {dir("opt/"), file("opt/app.conf", "x")}, + Map.of("opt/", "", "opt/app.conf", "x")), + Arguments.of("special files are skipped", "/srv/data", + new Item[] {dir("data/"), special("data/pipe", TarConstants.LF_FIFO), special("data/tty", TarConstants.LF_CHR), file("data/real", "ok")}, + Map.of("srv/data/", "", "srv/data/real", "ok")), + Arguments.of("first copy of a duplicate is kept", "/srv/data", + new Item[] {file("data/a", "first"), file("data/a", "second")}, + Map.of("srv/data/a", "first"))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("archivedEntries") + void archivesExpectedEntries(String description, String hostPath, Item[] items, Map expected) throws Exception { + Path part = runDir.resolve("part.zip"); + + assertEquals(expected.size(), ServiceBackupRunner.archive(tar(items), hostPath, part)); + + assertEquals(expected, contents(part)); + } + + @Test + void preservesModeOwnerAndModificationTime() throws Exception { + Path part = runDir.resolve("part.zip"); + Item secret = file("config/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setUserId(1000); + secret.entry().setGroupId(1001); + secret.entry().setModTime(new Date(1_700_000_000_000L)); + Item folder = dir("config/"); + folder.entry().setMode(040750); + + ServiceBackupRunner.archive(tar(folder, secret), "/home/user/config", part); + + try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + ZipArchiveEntry key = zip.getEntry("home/user/config/id_rsa"); + assertEquals(UnixStat.FILE_FLAG | 0600, key.getUnixMode()); + assertEquals(1_700_000_000_000L, key.getTime()); + X7875_NewUnix owner = (X7875_NewUnix) key.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(1000, owner.getUID()); + assertEquals(1001, owner.getGID()); + assertEquals(UnixStat.DIR_FLAG | 0750, zip.getEntry("home/user/config/").getUnixMode()); + } + } + + @Test + void storesSymbolicLinksAsLinks() throws Exception { + Path part = runDir.resolve("part.zip"); + Item symlink = link("sites-enabled/default", TarConstants.LF_SYMLINK, "/etc/nginx/sites-available/default"); + + ServiceBackupRunner.archive(tar(dir("sites-enabled/"), symlink), "/etc/nginx/sites-enabled", part); + + try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + ZipArchiveEntry entry = zip.getEntry("etc/nginx/sites-enabled/default"); + assertTrue(entry.isUnixSymlink()); + assertEquals("/etc/nginx/sites-available/default", zip.getUnixSymlink(entry)); + } + } + + @Test + void copiesHardLinksIntoALinksPart() throws Exception { + Path part = runDir.resolve("0.zip"); + Item hardLink = link("data/link", TarConstants.LF_LINK, "data/original"); + + assertEquals(3, ServiceBackupRunner.archive(tar(dir("data/"), file("data/original", "same"), hardLink), "/srv/data", part)); + + assertFalse(contents(part).containsKey("srv/data/link")); + assertEquals(Map.of("srv/data/link", "same"), contents(runDir.resolve("0-links.zip"))); + } + + @Test + void reportsPartialAndDiscardsOnlyTheFailedPath() throws Exception { + when(docker.containerFor(RADARR)).thenReturn("cid"); + when(docker.copyFrom("cid", "/srv/radarr/config")).thenReturn(tar(file("config/config.xml", ""))); + when(docker.copyFrom("cid", "/srv/radarr/data")).thenReturn(truncatedTar()); + + BackupServiceResult result = runner.run(RADARR, runDir); + + assertEquals(PARTIAL, result.status()); + assertTrue(result.errorMessage().startsWith("/srv/radarr/data: ")); + assertTrue(Files.exists(runDir.resolve("radarr/0.zip"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.zip"))); + } + + @Test + void reportsFailedWhenNoPathsCopy() { + when(docker.containerFor(RADARR)).thenReturn("cid"); + when(docker.copyFrom("cid", "/srv/radarr/config")).thenThrow(new RuntimeException("a")); + when(docker.copyFrom("cid", "/srv/radarr/data")).thenThrow(new RuntimeException("b")); + + BackupServiceResult result = runner.run(RADARR, runDir); + + assertEquals(FAILED, result.status()); + assertEquals("/srv/radarr/config: a; /srv/radarr/data: b", result.errorMessage()); + } + + @Test + void reportsFailedWhenContainerCannotBePrepared() { + when(docker.containerFor(RADARR)).thenThrow(new IllegalStateException("bind source path does not exist")); + + BackupServiceResult result = runner.run(RADARR, runDir); + + assertEquals(FAILED, result.status()); + assertEquals("bind source path does not exist", result.errorMessage()); + } + + @Test + void rejectsEntriesOutsideTheBackedUpPath() { + Path part = runDir.resolve("part.zip"); + + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("../escaped.txt", "x")), "/srv/data", part)); + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("other/file", "x")), "/srv/data", part)); + } + + @Test + void rejectsHardLinksOutsideTheBackedUpPath() { + Item hardLink = link("data/link", TarConstants.LF_LINK, "../etc/shadow"); + + assertThrows(IOException.class, + () -> ServiceBackupRunner.archive(tar(dir("data/"), hardLink), "/srv/data", runDir.resolve("part.zip"))); + } + + @Test + void buildsEntryNamesFromAbsolutePaths() throws IOException { + assertEquals("etc/nginx/nginx.conf", ServiceBackupRunner.entryName(Path.of("/etc/nginx"), Path.of("/etc/nginx/nginx.conf"), "nginx.conf", false)); + assertEquals("etc/nginx/", ServiceBackupRunner.entryName(Path.of("/etc"), Path.of("/etc/nginx"), "nginx/", true)); + assertEquals("srv/", ServiceBackupRunner.entryName(Path.of("/"), Path.of("/srv"), "srv/", true)); + } + + static Map contents(Path zipPath) throws IOException { + Map entries = new TreeMap<>(); + try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { + for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { + try (InputStream in = zip.getInputStream(entry)) { + entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } + return entries; + } + + record Item(TarArchiveEntry entry, byte[] content) {} + + static Item dir(String name) { + TarArchiveEntry entry = new TarArchiveEntry(name); + entry.setMode(040755); + return new Item(entry, null); + } + + static Item file(String name, String content) { + byte[] data = content.getBytes(StandardCharsets.UTF_8); + TarArchiveEntry entry = new TarArchiveEntry(name); + entry.setMode(0100644); + entry.setSize(data.length); + entry.setModTime(new Date(0)); + return new Item(entry, data); + } + + static Item link(String name, byte type, String target) { + TarArchiveEntry entry = new TarArchiveEntry(name, type); + entry.setLinkName(target); + return new Item(entry, null); + } + + static Item special(String name, byte type) { + return new Item(new TarArchiveEntry(name, type), null); + } + + static InputStream tar(Item... items) throws IOException { + return new ByteArrayInputStream(tarBytes(items)); + } + + private static byte[] tarBytes(Item... items) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (var out = new TarArchiveOutputStream(bytes)) { + out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); + for (Item item : items) { + out.putArchiveEntry(item.entry()); + if (item.content() != null) { + out.write(item.content()); + } + out.closeArchiveEntry(); + } + } + return bytes.toByteArray(); + } + + private static InputStream truncatedTar() throws IOException { + byte[] full = tarBytes(file("data/radarr.db", "x".repeat(4096))); + return new ByteArrayInputStream(Arrays.copyOf(full, 1024)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/SetupServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/SetupServiceTest.java new file mode 100644 index 0000000..56c0249 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/SetupServiceTest.java @@ -0,0 +1,105 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.nio.file.Path; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +class SetupServiceTest { + + @TempDir + Path tempDir; + + private DatabaseService db; + private SetupService setup; + + @BeforeEach + void setUp() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new DatabaseService(properties); + setup = new SetupService(db); + } + + @Test + void startsInSetupModeWithSixDigitPin() { + assertFalse(setup.isCompleted()); + assertTrue(setup.currentPin().matches("[0-9]{6}")); + assertFalse(setup.canConfigure(null)); + assertFalse(setup.canConfigure("made-up")); + } + + @Test + void correctPinStartsSession() { + Optional session = setup.startSession(" " + setup.currentPin() + " "); + + assertTrue(session.isPresent()); + assertTrue(setup.canConfigure(session.get())); + assertFalse(setup.canConfigure("made-up")); + } + + @Test + void wrongPinIsRejected() { + assertTrue(setup.startSession(null).isEmpty()); + assertTrue(setup.startSession("not-the-pin").isEmpty()); + } + + @Test + void pinIsSingleUse() { + String pin = setup.currentPin(); + assertTrue(setup.startSession(pin).isPresent()); + assumeFalse(pin.equals(setup.currentPin())); + + assertTrue(setup.startSession(pin).isEmpty()); + assertTrue(setup.startSession(setup.currentPin()).isPresent()); + } + + @Test + void rotatesPinAfterTooManyFailedAttempts() { + String pin = setup.currentPin(); + for (int i = 0; i < SetupService.MAX_FAILED_ATTEMPTS; i++) { + setup.startSession("wrong"); + } + assumeFalse(pin.equals(setup.currentPin())); + + assertTrue(setup.startSession(pin).isEmpty()); + } + + @Test + void completingSetupPersistsAndDisablesSessions() { + String session = setup.startSession(setup.currentPin()).orElseThrow(); + + setup.complete(); + + assertTrue(setup.isCompleted()); + assertNull(setup.currentPin()); + assertTrue(setup.startSession("123456").isEmpty()); + assertTrue(setup.canConfigure(null)); + assertTrue(setup.canConfigure(session)); + + SetupService restarted = new SetupService(db); + assertTrue(restarted.isCompleted()); + assertNull(restarted.currentPin()); + } + + @Test + void restartWhileInSetupIssuesFreshPin() { + String session = setup.startSession(setup.currentPin()).orElseThrow(); + + SetupService restarted = new SetupService(db); + + assertFalse(restarted.isCompleted()); + assertFalse(restarted.canConfigure(session)); + assertEquals(6, restarted.currentPin().length()); + } +} diff --git a/vendor/dry4java/.gitignore b/vendor/dry4java/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/vendor/dry4java/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/vendor/dry4java/README.md b/vendor/dry4java/README.md new file mode 100644 index 0000000..3e0c957 --- /dev/null +++ b/vendor/dry4java/README.md @@ -0,0 +1,58 @@ +# dry4java + +dry4java finds candidate duplicate Java code across files and directories. It reports fuzzy structural matches by filename and line range so another mechanism can evaluate and reduce duplication. + +## Overview + +dry4java parses Java source with JavaParser, selects Java declarations as comparison candidates, normalizes each candidate's AST, and compares sets of structural fingerprints with Jaccard similarity: + +```text +score = shared fingerprints / all fingerprints seen in either candidate +``` + +Names and literal values normalize away, while Java syntax shape remains. Classes, interfaces, records, enums, annotation declarations, methods, constructors, fields, enum constants, initializer blocks, lambdas, expressions, statements, modifiers, and operators all contribute structural nodes. + +## Usage + +```bash +mvn -q -DskipTests package +java -jar target/dry4java-0.1.0-SNAPSHOT.jar [options] [file-or-directory ...] +``` + +Options: + +```text +--threshold N Minimum structural similarity score, default 0.82 +--min-lines N Minimum source lines in a candidate declaration, default 4 +--min-nodes N Minimum normalized syntax nodes, default 20 +--format F text or edn, default text +--edn Same as --format edn +--text Same as --format text +``` + +When no paths are provided, dry4java scans `src`. Directory arguments recursively include `.java` files. + +Default text output: + +```text +DUPLICATE score=0.89 + src/main/java/app/Invoice.java:12-25 + src/main/java/app/Receipt.java:30-44 +``` + +EDN output: + +```clojure +{:candidates + [{:score 0.8909090909090909 + :left {:file "src/main/java/app/Invoice.java", :start-line 12, :end-line 25} + :right {:file "src/main/java/app/Receipt.java", :start-line 30, :end-line 44} + :left-nodes 88 + :right-nodes 91}]} +``` + +## Development + +```bash +mvn test +``` diff --git a/vendor/dry4java/pom.xml b/vendor/dry4java/pom.xml new file mode 100644 index 0000000..068ab87 --- /dev/null +++ b/vendor/dry4java/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.unclebob + dry4java + 0.1.0-SNAPSHOT + + + 21 + UTF-8 + 5.11.4 + 3.26.3 + + + + + com.github.javaparser + javaparser-core + ${javaparser.version} + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + false + + + dry4java.Dry4Java + + + + + + + + + diff --git a/vendor/dry4java/src/main/java/dry4java/Candidate.java b/vendor/dry4java/src/main/java/dry4java/Candidate.java new file mode 100644 index 0000000..0af3705 --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/Candidate.java @@ -0,0 +1,4 @@ +package dry4java; + +public record Candidate(double score, Location left, Location right, int leftNodes, int rightNodes) { +} diff --git a/vendor/dry4java/src/main/java/dry4java/Dry4Java.java b/vendor/dry4java/src/main/java/dry4java/Dry4Java.java new file mode 100644 index 0000000..6da55ef --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/Dry4Java.java @@ -0,0 +1,91 @@ +package dry4java; + +import java.util.List; +import java.util.Locale; + +public final class Dry4Java { + public static final String USAGE = String.join(System.lineSeparator(), + "Usage: dry4java [options] [file-or-directory ...]", + "", + "Options:", + " --threshold N Minimum structural similarity score, default 0.82", + " --min-lines N Minimum source lines in a candidate declaration, default 4", + " --min-nodes N Minimum normalized syntax nodes, default 20", + " --format F text or edn, default text", + " --edn Same as --format edn", + " --text Same as --format text"); + + private Dry4Java() { + } + + public static void main(String... args) { + Options options = Options.parse(args); + if (options.help()) { + System.out.println(USAGE); + return; + } + + List candidates = new JavaDuplicateFinder().findDuplicates(options); + switch (options.format()) { + case "edn" -> System.out.println(toEdn(candidates)); + case "text" -> printText(candidates); + default -> { + System.err.println("Unknown format: " + options.format()); + System.exit(2); + } + } + } + + static void printText(List candidates) { + if (candidates.isEmpty()) { + System.out.println("No duplicate candidates found."); + return; + } + for (int i = 0; i < candidates.size(); i++) { + if (i > 0) { + System.out.println(); + } + System.out.println(formatCandidate(candidates.get(i))); + } + } + + static String formatCandidate(Candidate candidate) { + return "DUPLICATE score=" + String.format(Locale.US, "%.2f", candidate.score()) + "\n" + + " " + lineRange(candidate.left()) + "\n" + + " " + lineRange(candidate.right()); + } + + static String toEdn(List candidates) { + if (candidates.isEmpty()) { + return "{:candidates []}"; + } + StringBuilder builder = new StringBuilder("{:candidates\n ["); + for (int i = 0; i < candidates.size(); i++) { + if (i > 0) { + builder.append("\n "); + } + Candidate candidate = candidates.get(i); + builder.append("{:score ").append(candidate.score()) + .append("\n :left ").append(locationEdn(candidate.left())) + .append("\n :right ").append(locationEdn(candidate.right())) + .append("\n :left-nodes ").append(candidate.leftNodes()) + .append("\n :right-nodes ").append(candidate.rightNodes()) + .append("}"); + } + builder.append("]}"); + return builder.toString(); + } + + private static String locationEdn(Location location) { + return "{:file \"" + escape(location.file()) + "\", :start-line " + location.startLine() + + ", :end-line " + location.endLine() + "}"; + } + + private static String escape(String text) { + return text.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private static String lineRange(Location location) { + return location.file() + ":" + location.startLine() + "-" + location.endLine(); + } +} diff --git a/vendor/dry4java/src/main/java/dry4java/JavaDuplicateFinder.java b/vendor/dry4java/src/main/java/dry4java/JavaDuplicateFinder.java new file mode 100644 index 0000000..0a5c3d9 --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/JavaDuplicateFinder.java @@ -0,0 +1,164 @@ +package dry4java; + +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.InitializerDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.RecordDeclaration; +import com.github.javaparser.ast.expr.LambdaExpr; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; + +public final class JavaDuplicateFinder { + static { + StaticJavaParser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_21); + } + + private final JavaNormalizer normalizer = new JavaNormalizer(); + + public List findDuplicates() { + return findDuplicates(Options.defaults()); + } + + public List findDuplicates(Options options) { + List entries = scan(options.paths()).stream() + .filter(entry -> entry.lines() >= options.minLines()) + .filter(entry -> entry.nodes >= options.minNodes()) + .toList(); + List candidates = new ArrayList<>(); + + for (int i = 0; i < entries.size(); i++) { + for (int j = i + 1; j < entries.size(); j++) { + Entry left = entries.get(i); + Entry right = entries.get(j); + double score = similarity(left, right); + if (!left.overlaps(right) && score >= options.threshold()) { + candidates.add(new Candidate(score, left.location(), right.location(), left.nodes, right.nodes)); + } + } + } + + candidates.sort(Comparator + .comparingDouble(Candidate::score).reversed() + .thenComparing(candidate -> candidate.left().file()) + .thenComparingInt(candidate -> candidate.left().startLine()) + .thenComparing(candidate -> candidate.right().file()) + .thenComparingInt(candidate -> candidate.right().startLine())); + return candidates; + } + + private List scan(List paths) { + return paths.stream() + .flatMap(path -> javaFiles(Path.of(path)).stream()) + .sorted() + .flatMap(path -> scanFile(path).stream()) + .toList(); + } + + private List javaFiles(Path path) { + if (Files.isRegularFile(path) && path.toString().endsWith(".java")) { + return List.of(path); + } + if (!Files.isDirectory(path)) { + return List.of(); + } + try (Stream walk = Files.walk(path)) { + return walk.filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".java")) + .sorted() + .toList(); + } catch (IOException e) { + throw new IllegalStateException("Unable to scan " + path, e); + } + } + + private List scanFile(Path file) { + try { + CompilationUnit unit = StaticJavaParser.parse(file); + List entries = new ArrayList<>(); + collectEntries(file, unit, entries); + return entries; + } catch (IOException | ParseProblemException e) { + throw new IllegalStateException("Unable to parse " + file, e); + } + } + + private void collectEntries(Path file, Node node, List entries) { + if (isCandidateRoot(node)) { + entries.add(entry(file, node)); + } + for (Node child : node.getChildNodes()) { + collectEntries(file, child, entries); + } + } + + private boolean isCandidateRoot(Node node) { + return node instanceof ClassOrInterfaceDeclaration + || node instanceof RecordDeclaration + || node instanceof EnumDeclaration + || node instanceof AnnotationDeclaration + || node instanceof MethodDeclaration + || node instanceof ConstructorDeclaration + || node instanceof FieldDeclaration + || node instanceof InitializerDeclaration + || node instanceof EnumConstantDeclaration + || node instanceof LambdaExpr; + } + + private Entry entry(Path file, Node node) { + int startLine = node.getRange().map(range -> range.begin.line).orElse(1); + int endLine = node.getRange().map(range -> range.end.line).orElse(startLine); + NormalizedNode normalized = normalizer.normalize(node); + return new Entry( + file.toString(), + startLine, + endLine, + normalized.nodeCount(), + normalized.fingerprints()); + } + + private double similarity(Entry left, Entry right) { + Set intersection = new HashSet<>(left.fingerprints); + intersection.retainAll(right.fingerprints); + Set union = new HashSet<>(left.fingerprints); + union.addAll(right.fingerprints); + if (union.isEmpty()) { + return 0.0; + } + return (double) intersection.size() / union.size(); + } + + private record Entry(String file, int startLine, int endLine, int nodes, Set fingerprints) { + int lines() { + return endLine - startLine + 1; + } + + Location location() { + return new Location(file, startLine, endLine); + } + + boolean overlaps(Entry other) { + return file.equals(other.file) + && startLine <= other.endLine + && other.startLine <= endLine; + } + } +} diff --git a/vendor/dry4java/src/main/java/dry4java/JavaNormalizer.java b/vendor/dry4java/src/main/java/dry4java/JavaNormalizer.java new file mode 100644 index 0000000..1e6760a --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/JavaNormalizer.java @@ -0,0 +1,84 @@ +package dry4java; + +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.expr.AssignExpr; +import com.github.javaparser.ast.expr.BinaryExpr; +import com.github.javaparser.ast.expr.LambdaExpr; +import com.github.javaparser.ast.expr.UnaryExpr; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.nodeTypes.NodeWithModifiers; +import com.github.javaparser.ast.stmt.SwitchEntry; +import com.github.javaparser.ast.type.PrimitiveType; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +final class JavaNormalizer { + NormalizedNode normalize(Node node) { + List children = new ArrayList<>(); + for (String marker : markers(node)) { + children.add(new NormalizedNode(marker, List.of())); + } + for (Node child : node.getChildNodes()) { + if (keepsStructuralChild(child)) { + children.add(normalize(child)); + } + } + return new NormalizedNode(tag(node), children); + } + + private String tag(Node node) { + if (node instanceof EnumConstantDeclaration) { + return "EnumConstant"; + } + return node.getClass().getSimpleName(); + } + + private boolean keepsStructuralChild(Node child) { + String simpleName = child.getClass().getSimpleName(); + return !simpleName.equals("SimpleName") + && !simpleName.endsWith("LiteralExpr") + && !simpleName.equals("Name") + && !simpleName.equals("NameExpr") + && !simpleName.equals("Comment"); + } + + private List markers(Node node) { + List markers = new ArrayList<>(); + if (node instanceof BodyDeclaration bodyDeclaration) { + bodyDeclaration.getAnnotations().forEach(annotation -> markers.add("annotation")); + } + if (node instanceof NodeWithModifiers withModifiers) { + withModifiers.getModifiers().stream() + .map(Modifier::getKeyword) + .map(Enum::name) + .sorted() + .forEach(modifier -> markers.add("modifier:" + modifier)); + } + if (node instanceof BinaryExpr binaryExpr) { + markers.add("operator:" + binaryExpr.getOperator().name()); + } else if (node instanceof UnaryExpr unaryExpr) { + markers.add("operator:" + unaryExpr.getOperator().name()); + } else if (node instanceof AssignExpr assignExpr) { + markers.add("operator:" + assignExpr.getOperator().name()); + } else if (node instanceof VariableDeclarationExpr variableDeclarationExpr) { + variableDeclarationExpr.getModifiers().stream() + .map(Modifier::getKeyword) + .map(Enum::name) + .sorted() + .forEach(modifier -> markers.add("modifier:" + modifier)); + } else if (node instanceof PrimitiveType primitiveType) { + markers.add("primitive:" + primitiveType.getType().name()); + } else if (node instanceof SwitchEntry switchEntry) { + markers.add("switch:" + switchEntry.getType().name()); + } else if (node instanceof LambdaExpr lambdaExpr && lambdaExpr.isEnclosingParameters()) { + markers.add("lambda:parenthesized"); + } + markers.sort(Comparator.naturalOrder()); + return markers; + } +} diff --git a/vendor/dry4java/src/main/java/dry4java/Location.java b/vendor/dry4java/src/main/java/dry4java/Location.java new file mode 100644 index 0000000..ef1ed69 --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/Location.java @@ -0,0 +1,4 @@ +package dry4java; + +public record Location(String file, int startLine, int endLine) { +} diff --git a/vendor/dry4java/src/main/java/dry4java/NormalizedNode.java b/vendor/dry4java/src/main/java/dry4java/NormalizedNode.java new file mode 100644 index 0000000..f25865c --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/NormalizedNode.java @@ -0,0 +1,63 @@ +package dry4java; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; + +final class NormalizedNode { + private final String tag; + private final List children; + + NormalizedNode(String tag, List children) { + this.tag = tag; + this.children = List.copyOf(children); + } + + int nodeCount() { + int count = 1; + for (NormalizedNode child : children) { + count += child.nodeCount(); + } + return count; + } + + Set fingerprints() { + Set result = new TreeSet<>(); + collectFingerprints(result); + return result; + } + + private void collectFingerprints(Set result) { + result.add(toFingerprint()); + for (NormalizedNode child : children) { + child.collectFingerprints(result); + } + } + + private String toFingerprint() { + if (children.isEmpty()) { + return tag; + } + List parts = new ArrayList<>(); + parts.add(tag); + for (NormalizedNode child : children) { + parts.add(child.toFingerprint()); + } + return "(" + String.join(" ", parts) + ")"; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof NormalizedNode that)) { + return false; + } + return Objects.equals(tag, that.tag) && Objects.equals(children, that.children); + } + + @Override + public int hashCode() { + return Objects.hash(tag, children); + } +} diff --git a/vendor/dry4java/src/main/java/dry4java/Options.java b/vendor/dry4java/src/main/java/dry4java/Options.java new file mode 100644 index 0000000..af687ae --- /dev/null +++ b/vendor/dry4java/src/main/java/dry4java/Options.java @@ -0,0 +1,85 @@ +package dry4java; + +import java.util.ArrayList; +import java.util.List; + +public final class Options { + private final List paths; + private final double threshold; + private final int minLines; + private final int minNodes; + private final String format; + private final boolean help; + + public Options(List paths, double threshold, int minLines, int minNodes, String format, boolean help) { + this.paths = List.copyOf(paths); + this.threshold = threshold; + this.minLines = minLines; + this.minNodes = minNodes; + this.format = format; + this.help = help; + } + + public static Options defaults() { + return new Options(List.of("src"), 0.82, 4, 20, "text", false); + } + + public static Options parse(String... args) { + List paths = new ArrayList<>(); + double threshold = 0.82; + int minLines = 4; + int minNodes = 20; + String format = "text"; + boolean help = false; + + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--threshold" -> threshold = Double.parseDouble(valueFor(args, ++i, arg)); + case "--min-lines" -> minLines = Integer.parseInt(valueFor(args, ++i, arg)); + case "--min-nodes" -> minNodes = Integer.parseInt(valueFor(args, ++i, arg)); + case "--format" -> format = valueFor(args, ++i, arg); + case "--edn" -> format = "edn"; + case "--text" -> format = "text"; + case "--help", "-h" -> help = true; + default -> paths.add(arg); + } + } + + if (paths.isEmpty()) { + paths.add("src"); + } + return new Options(paths, threshold, minLines, minNodes, format, help); + } + + private static String valueFor(String[] args, int index, String option) { + if (index >= args.length) { + throw new IllegalArgumentException("Missing value for " + option); + } + return args[index]; + } + + public List paths() { + return paths; + } + + public double threshold() { + return threshold; + } + + public int minLines() { + return minLines; + } + + public int minNodes() { + return minNodes; + } + + public String format() { + return format; + } + + public boolean help() { + return help; + } +} diff --git a/vendor/dry4java/src/test/java/dry4java/JavaDuplicateFinderTest.java b/vendor/dry4java/src/test/java/dry4java/JavaDuplicateFinderTest.java new file mode 100644 index 0000000..08af1c6 --- /dev/null +++ b/vendor/dry4java/src/test/java/dry4java/JavaDuplicateFinderTest.java @@ -0,0 +1,181 @@ +package dry4java; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JavaDuplicateFinderTest { + @Test + void reportsStructuralDuplicateCandidatesWithFileAndLineRanges() throws Exception { + Path dir = Files.createTempDirectory("dry4java"); + Path left = writeSource(dir, "Left.java", """ + package sample; + + class Left { + int alpha(List xs) { + var ys = xs.stream().filter(x -> x % 2 == 1).toList(); + return ys.stream().mapToInt(x -> x + 1).sum(); + } + } + """); + Path right = writeSource(dir, "Right.java", """ + package sample; + + class Right { + int beta(List items) { + var kept = items.stream().filter(item -> item % 2 == 0).toList(); + return kept.stream().mapToInt(item -> item - 1).sum(); + } + } + """); + + List candidates = new JavaDuplicateFinder().findDuplicates( + new Options(List.of(dir.toString()), 0.50, 3, 8, "text", false)); + + Candidate candidate = candidates.stream() + .filter(each -> each.left().file().equals(left.toString())) + .filter(each -> each.right().file().equals(right.toString())) + .filter(each -> each.left().startLine() == 4) + .filter(each -> each.right().startLine() == 4) + .findFirst() + .orElseThrow(); + assertEquals(4, candidate.left().startLine()); + assertEquals(7, candidate.left().endLine()); + assertEquals(4, candidate.right().startLine()); + assertEquals(7, candidate.right().endLine()); + } + + @Test + void matchesRecordsWithDifferentNamesAndLiteralValues() throws Exception { + Path dir = Files.createTempDirectory("dry4java"); + writeSource(dir, "One.java", """ + record Invoice(String id, int amount) { + boolean payable() { + return id != null && amount > 0; + } + } + """); + writeSource(dir, "Two.java", """ + record Receipt(String code, int total) { + boolean closed() { + return code != null && total > 10; + } + } + """); + + List candidates = new JavaDuplicateFinder().findDuplicates( + new Options(List.of(dir.toString()), 0.80, 3, 8, "text", false)); + + assertTrue(candidates.stream().anyMatch(candidate -> + candidate.left().file().endsWith("One.java") + && candidate.right().file().endsWith("Two.java"))); + } + + @Test + void matchesEnumsAndConstantsStructurally() throws Exception { + Path dir = Files.createTempDirectory("dry4java"); + writeSource(dir, "One.java", """ + enum One { + READY(1), DONE(2); + private final int code; + One(int code) { + this.code = code; + } + } + """); + writeSource(dir, "Two.java", """ + enum Two { + OPEN(10), CLOSED(20); + private final int value; + Two(int value) { + this.value = value; + } + } + """); + + List candidates = new JavaDuplicateFinder().findDuplicates( + new Options(List.of(dir.toString()), 0.80, 3, 8, "text", false)); + + assertTrue(candidates.stream().anyMatch(candidate -> + candidate.left().file().endsWith("One.java") + && candidate.right().file().endsWith("Two.java"))); + } + + @Test + void filtersCandidatesShorterThanTheMinimumLineCount() throws Exception { + Path dir = Files.createTempDirectory("dry4java"); + writeSource(dir, "One.java", "class One { int a(int x) { return x + 1; } }\n"); + writeSource(dir, "Two.java", "class Two { int b(int y) { return y + 2; } }\n"); + + List candidates = new JavaDuplicateFinder().findDuplicates( + new Options(List.of(dir.toString()), 0.80, 3, 1, "text", false)); + + assertEquals(List.of(), candidates); + } + + @Test + void parsesCommandLineOptionsAndPaths() { + Options options = Options.parse("--threshold", "0.9", + "--min-lines", "5", + "--min-nodes", "30", + "--edn", + "spec"); + + assertEquals(List.of("spec"), options.paths()); + assertEquals(0.9, options.threshold()); + assertEquals(5, options.minLines()); + assertEquals(30, options.minNodes()); + assertEquals("edn", options.format()); + } + + @Test + void defaultsToSrcWhenNoPathsAreProvided() { + assertEquals(List.of("src"), Options.parse().paths()); + } + + @Test + void formatsTextOutputWithLineRanges() { + Candidate candidate = new Candidate( + 0.875, + new Location("a.java", 10, 14), + new Location("b.java", 20, 24), + 88, + 91); + + assertEquals("DUPLICATE score=0.88\n a.java:10-14\n b.java:20-24", + Dry4Java.formatCandidate(candidate)); + } + + @Test + void printsClearMessageWhenNoTextCandidatesExist() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + PrintStream original = System.out; + System.setOut(new PrintStream(bytes)); + try { + Dry4Java.printText(List.of()); + } finally { + System.setOut(original); + } + + assertEquals("No duplicate candidates found.\n", bytes.toString()); + } + + @Test + void printsEdn() { + assertEquals("{:candidates []}", Dry4Java.toEdn(List.of())); + } + + private Path writeSource(Path dir, String name, String text) throws Exception { + Path file = dir.resolve(name); + Files.createDirectories(file.getParent()); + Files.writeString(file, text); + return file; + } +} From 9367fb82a915b976292b0b3c524b635024c04e4f Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Mon, 26 Oct 2026 19:46:23 -0500 Subject: [PATCH 16/26] Updating CHANGELOG --- CHANGELOG | 2 +- .../mediagarrdServer/service/DatabaseService.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 0b71e66..23fc174 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ # CHANGELOG -## TBD +## 10-26-26 - Fixed logic issue with migration versioning - Added Structurizr diagrams to visualize workflow - Added Lombok for simpler model classes diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index 69c2c7f..0918d5b 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -35,9 +35,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; import org.sqlite.SQLiteErrorCode; import org.sqlite.SQLiteException; -import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -59,8 +59,10 @@ public class DatabaseService { private static final ObjectMapper JSON = new ObjectMapper(); private static final TypeReference> PATH_LIST = new TypeReference<>() {}; - private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss") + private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter + .ofPattern("yyyyMMdd-HHmmss") .withZone(ZoneOffset.UTC); + private static final List DATABASE_FILE_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private final Path databaseFile; From 533622d6c54874601d4f3c47b67ca3249c79457c Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Mon, 26 Oct 2026 20:41:34 -0500 Subject: [PATCH 17/26] Delete .factorypath Meant to exclude this --- .factorypath | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .factorypath diff --git a/.factorypath b/.factorypath deleted file mode 100644 index b702554..0000000 --- a/.factorypath +++ /dev/null @@ -1,3 +0,0 @@ - - - From 700546aa90f298cb95421072a9397eba8a30cbe4 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 10:32:44 -0600 Subject: [PATCH 18/26] Update LICENSE file --- LICENSE | 695 ++------------------------------------------------------ 1 file changed, 21 insertions(+), 674 deletions(-) diff --git a/LICENSE b/LICENSE index f288702..ba28e3b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2026 Jackson Swindell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 581d237efdf51ebe9c631149ce97418c89093857 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 5 Nov 2026 13:36:22 -0600 Subject: [PATCH 19/26] Add the MediaGarrd itself as a backup target to preserve run-history in an outage. --- CHANGELOG | 8 + CLAUDE.md | 1 + README.md | 4 + .../service/BackupArchiveService.java | 21 ++- .../service/BackupOrchestratorService.java | 33 +++- .../service/ContainerEnvironment.java | 75 +++++++++ .../service/DatabaseHostPathResolver.java | 84 ++++++++++ .../service/DatabaseService.java | 97 ++++++++++- .../service/DatabaseSnapshotService.java | 87 ++++++++++ .../service/DockerService.java | 6 + .../service/ServiceBackupRunner.java | 2 +- .../service/BackupArchiveServiceTest.java | 48 ++++++ .../BackupOrchestratorServiceTest.java | 62 ++++++- .../service/ContainerEnvironmentTest.java | 84 ++++++++++ .../service/DatabaseHostPathResolverTest.java | 153 ++++++++++++++++++ .../service/DatabaseServiceTest.java | 146 +++++++++++++++++ .../service/DatabaseSnapshotServiceTest.java | 133 +++++++++++++++ 17 files changed, 1029 insertions(+), 15 deletions(-) create mode 100644 CLAUDE.md create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java 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..5c7f395 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,6 +77,8 @@ 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. 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()); + } + } + } +} From e4f37e42baca2e90cbb06cca933659d0b94cb00c Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 17:57:43 -0600 Subject: [PATCH 20/26] Update LICENSE in README.md. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c7f395..f963bc2 100644 --- a/README.md +++ b/README.md @@ -84,4 +84,4 @@ Info-ZIP `unzip -o .zip -d /` restores contents, permissions, and symbo > **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) From ab978f3801bba65fe18f93829f6d7aa215608439 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 18:38:22 -0600 Subject: [PATCH 21/26] Update alerting. --- CHANGELOG | 69 ++-- README.md | 22 ++ build.gradle.kts | 6 + .../MediaGarrdProperties.java | 3 + .../api/BackupController.java | 13 +- .../api/ConfigController.java | 15 +- .../api/RunEventsController.java | 49 +++ .../api/VersionController.java | 24 ++ .../mediagarrdServer/dto/CheckState.java | 8 + .../dto/VersionStatusDto.java | 13 + .../service/BackupOrchestratorService.java | 226 ++++++----- .../service/BackupScheduleService.java | 18 + .../service/RunStatusBroadcaster.java | 228 +++++++++++ .../service/UpdateCheckService.java | 171 +++++++++ .../mediagarrdServer/utilities/SemVer.java | 78 ++++ src/main/resources/application.yml | 9 + .../MediaGarrdPropertiesBindingTest.java | 5 +- .../api/BackupControllerTest.java | 36 ++ .../api/ConfigControllerTest.java | 21 ++ .../api/RunEventsControllerTest.java | 72 ++++ .../api/VersionControllerTest.java | 63 ++++ .../BackupOrchestratorServiceTest.java | 232 +++++++++++- .../service/BackupScheduleServiceTest.java | 37 ++ .../service/RunStatusBroadcasterTest.java | 356 ++++++++++++++++++ .../service/UpdateCheckServiceTest.java | 285 ++++++++++++++ .../utilities/SemVerTest.java | 66 ++++ 26 files changed, 2002 insertions(+), 123 deletions(-) create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java diff --git a/CHANGELOG b/CHANGELOG index f3c0b04..a483054 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,44 +1,55 @@ # CHANGELOG +## 11-12-26 +- A run rejected before it starts (such as no services configured) publishes no run events +- A scheduled check with nothing to back up now waits one full interval instead of retrying every 30 seconds, and adding or editing a service makes the schedule due again right away +- `GET /api/v1/events` also sends `backups-changed` (backup deleted, backup location changed) and `config-changed` (schedule, settings, or services changed), each as `{"at":""}` +- `GET /api/v1/health` and `GET /api/v1/backups` are logged at DEBUG, so polling no longer fills the log + +## 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 +- At most 16 listeners are served (more get `503`), a slow or dead listener is dropped without slowing a backup, and each stream ends cleanly after 4.5 minutes so clients reconnect without errors in the log +- Fixed a failed delete of a run's temporary directory leaving the server stuck on "running" and rejecting configuration changes until restart +- The server knows its version (`0.1.0`) and checks GitHub for the latest `MediaGarrd/Server` release shortly after starting and then daily +- `GET /api/v1/version` (no setup session needed) reports the current and latest version, whether an update is available, the release link, when the last check ran, and its state (`OK`, `NO_RELEASES`, `ERROR`, or `NOT_CHECKED`) +- A failed check (offline, rate limited, no release yet) is logged once, shown as a state, and never affects backups +- `MEDIAGARRD_UPDATE_REPOSITORY`, `MEDIAGARRD_GITHUB_API_URL`, and `MEDIAGARRD_UPDATE_CHECK_INTERVAL` change the repository, API address, and check interval (at least `PT1H`, or the server refuses to start) +- Scheduled tasks run on two threads (`spring.task.scheduling.pool.size: 2`), so a slow GitHub check cannot delay backups + ## 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 +- Every archive includes a consistent snapshot of the server's own database (settings, services, backup records) 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. If that or the snapshot fails, the run is partial with the error logged, and a corrupt or missing database is never replaced by an empty one +- Database operations wait while the snapshot is taken, so nothing is written mid-copy +- The snapshot appears as `_mediagarrd-server` in service results and service names, and a service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to it - Documented how to restore the database from an archive ## 10-26-26 -- Fixed logic issue with migration versioning -- Added Structurizr diagrams to visualize workflow -- Added Lombok for simpler model classes -- Services are now stored in the database and managed from the `/config` web page or `/api/v1/services`, any service can be backed up +- Services are stored in the database and managed from `/config` or `/api/v1/services`, and any service can be backed up - Backup location can be changed at runtime from `/config` or `PUT /api/v1/config` -- Replaced the per-service runners with a single runner that copies each service's paths through a cached, read-only helper container via the Docker socket -- Added integration test and issue label workflows +- Backup interval and retention count are stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting +- Configuration changes are rejected while a backup is running, so a run never sees its services change +- One runner now copies each service's paths through a cached, read-only helper container via the Docker socket, replacing the per-service runners - Added first-time web setup reachable from the network, unlocked with a single-use PIN printed in the server logs and disabled once setup is finished -- `docker-compose.example.yml` now works without `install.sh` -- Backup interval and retention count are now stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting -- Configuration changes are rejected while a backup is running so a run never sees its services change underneath it -- Added a pull request check that requires every linked issue to be approved -- Backup archives are laid out by absolute host path with no per-service folder, so they can be restored with `bsdtar -xpf -C /` -- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy no longer leaves partial files in the archive +- `docker-compose.example.yml` works without `install.sh` +- Archives are laid out by absolute host path with no per-service folder, so `bsdtar -xpf -C /` restores them +- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy leaves no partial files - Fixed special files (pipes, devices) being archived as empty regular files -- Fixed backup checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly -- Every API endpoint now returns errors as `{"error": "..."}` with a matching status code -- The database schema is verified once and then re-checked with a single query per call, rebuilding or upgrading the database whenever it is deleted, altered, or replaced, and moving a corrupt database aside +- Fixed checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly +- Every API endpoint returns errors as `{"error": "..."}` with a matching status code +- The database schema is verified once and then re-checked with one query per call, rebuilding or upgrading the database when it is deleted, altered, or replaced, and moving a corrupt one aside +- Fixed migration versioning +- Added Structurizr diagrams, Lombok for model classes, integration test and issue label workflows, and a pull request check that requires every linked issue to be approved ## 9-23-26 -- Add database for keeping records of backups -- Add thorough testing of database functionality -- Add issue templates -- Removed auto-routing to appdata/ within archive to retain actual paths of configs +- Added a database for backup records, with thorough tests +- Added issue templates +- Removed auto-routing to `appdata/` within archives so configs keep their actual paths ## 9-16-26 -- Adding more detailed logging for service runners -- Renaming QBittorrent's "graveyard" directory to "saved-torrents" to make it less ambiguous +- More detailed logging for service runners +- Renamed QBittorrent's "graveyard" directory to "saved-torrents" ## 9-6-26 -- Abstracting services to make adding new ones easier -- Adding new tests -- Project renaming +- Abstracted services to make adding new ones easier +- Added new tests +- Renamed the project diff --git a/README.md b/README.md index f963bc2..ee6464f 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,10 @@ Every setting is stored in the database and survives restarts and container rebu | Time between backups (ISO-8601) | `PUT /api/v1/schedule` with `{"backupInterval": "PT12H"}` | | List / add services | `GET` / `POST /api/v1/services` with `{"name": "radarr", "paths": ["/srv/radarr/config"]}` | | Update / remove a service | `PUT` / `DELETE /api/v1/services/{name}` | +| Server version and update status (no setup session needed) | `GET /api/v1/version` | +| Live run status stream (no setup session needed) | `GET /api/v1/events` | + +`GET /api/v1/events` is a Server-Sent Events stream (`text/event-stream`) of run status. It sends `state` (`{"running":false,"at":"..."}`) as soon as you connect, `run-started` (`{"running":true,"startedAt":"..."}`) and `run-finished` (`{"running":false,"status":"COMPLETED","startedAt":"...","finishedAt":"..."}`, status is `COMPLETED`, `PARTIAL`, or `FAILED`) when a run begins and ends, `backups-changed` and `config-changed` (both `{"at":"..."}`) after a backup is deleted or the backup location changes, and after the schedule, settings, or services change, and a `ping` (`{}`) every 20 seconds. A run that is rejected before it starts (such as no services configured) publishes no run events. A scheduled check with nothing to back up waits one full interval, and adding or editing a service makes the schedule due again right away. Up to 16 listeners are served at once (more get `503`), and each stream ends cleanly after 4.5 minutes so listeners should reconnect. The MediaGarrd Client uses it to show Running and Idle the moment a run starts or ends, and falls back to polling `/api/v1/health` when it is unavailable. Configuration changes are rejected with `409 Conflict` while a backup is running. A lower retention count takes effect on the next backup run. @@ -48,6 +52,24 @@ Configuration changes are rejected with `409 Conflict` while a backup is running The database is checked on startup and whenever its schema changes underneath the server. If it is deleted, has a table dropped, or is replaced by an older copy, it is rebuilt or upgraded automatically. A corrupt database is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty one, after which settings and services must be configured again (restart the server to get a new setup PIN). +## Update alerts +The server checks the latest release of `MediaGarrd/Server` on GitHub a few seconds after starting and then once a day, and keeps the result in memory. `GET /api/v1/version` returns it and needs no setup session: + +```json +{ + "currentVersion": "0.1.0", + "latestVersion": "0.2.0", + "releaseUrl": "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", + "updateAvailable": true, + "checkState": "OK", + "checkedAt": "2026-11-11T18:00:00Z", + "message": null +} +``` +`checkState` is `NOT_CHECKED` until the first check finishes, `OK` when a release was found, `NO_RELEASES` when none has been published yet, and `ERROR` when GitHub could not be asked (`message` says why). A failed check never affects backups and is tried again at the next interval. The MediaGarrd Client shows the result in its Versions panel. + +To change what is checked, set `MEDIAGARRD_UPDATE_REPOSITORY` (default `MediaGarrd/Server`), `MEDIAGARRD_GITHUB_API_URL` (default `https://api.github.com`), or `MEDIAGARRD_UPDATE_CHECK_INTERVAL` (ISO-8601, default `PT24H`, minimum `PT1H`) in `environment`. + ## Updating ```bash git pull diff --git a/build.gradle.kts b/build.gradle.kts index 49a78a2..b749201 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,8 @@ plugins { id("io.spring.dependency-management") version "1.1.6" } +version = "0.1.0" + extra["httpclient5.version"] = "5.4.4" extra["httpcore5.version"] = "5.3.4" @@ -31,6 +33,10 @@ java { } } +springBoot { + buildInfo() +} + tasks.test { useJUnitPlatform() } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 26a2705..b50e931 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -17,4 +17,7 @@ public class MediaGarrdProperties { private int retentionCount = 10; private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; private String helperImage = "busybox:stable"; + private String updateRepository = "MediaGarrd/Server"; + private String githubApiBaseUrl = "https://api.github.com"; + private Duration updateCheckInterval = Duration.ofHours(24); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 1ca9085..0158ca2 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -32,6 +32,7 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; @RestController @RequestMapping("/api/v1") @@ -41,15 +42,17 @@ public class BackupController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestratorService; + private final RunStatusBroadcaster broadcaster; - public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService) { + public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService, RunStatusBroadcaster broadcaster) { this.archiveService = archiveService; this.orchestratorService = orchestratorService; + this.broadcaster = broadcaster; } @GetMapping("/health") public ServerStatusDto health() { - LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + LOGGER.debug("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); return status(orchestratorService.getInterval()); } @@ -58,14 +61,15 @@ public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); Duration updated = orchestratorService.updateInterval(request.backupInterval()); LOGGER.info("Schedule updated: newInterval={}", updated); + broadcaster.publishConfigChanged(); return status(updated); } @GetMapping("/backups") public List listBackups() { - LOGGER.info("GET /api/v1/backups"); + LOGGER.debug("GET /api/v1/backups"); List backups = archiveService.listArchives().stream().map(this::toDto).toList(); - LOGGER.info("Returning {} backup(s)", backups.size()); + LOGGER.debug("Returning {} backup(s)", backups.size()); return backups; } @@ -111,6 +115,7 @@ public ResponseEntity deleteBackup(@PathVariable String id) { return ResponseEntity.notFound().build(); } LOGGER.info("Backup deleted: {}", id); + broadcaster.publishBackupsChanged(); return ResponseEntity.noContent().build(); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java index d1ca6d1..420e896 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -25,6 +25,7 @@ import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; import wellatleastitried.mediagarrdServer.service.DatabaseService; import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; @RestController @RequestMapping("/api/v1") @@ -36,17 +37,20 @@ public class ConfigController { private final BackupOrchestratorService orchestrator; private final DatabaseService db; private final DockerService docker; + private final RunStatusBroadcaster broadcaster; public ConfigController( BackupArchiveService archiveService, BackupOrchestratorService orchestrator, DatabaseService db, - DockerService docker + DockerService docker, + RunStatusBroadcaster broadcaster ) { this.archiveService = archiveService; this.orchestrator = orchestrator; this.db = db; this.docker = docker; + this.broadcaster = broadcaster; } @GetMapping("/config") @@ -60,6 +64,10 @@ public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", request.backupLocation(), request.retentionCount()); return orchestrator.whileIdle(() -> { archiveService.updateSettings(request.backupLocation(), request.retentionCount()); + if (request.backupLocation() != null) { + broadcaster.publishBackupsChanged(); + } + broadcaster.publishConfigChanged(); return currentConfig(); }); } @@ -79,6 +87,8 @@ public ResponseEntity addService(@RequestBody ServiceDefinition request) { return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); } db.addService(service); + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); return ResponseEntity.status(HttpStatus.CREATED).body(service); }); } @@ -100,6 +110,8 @@ public ResponseEntity updateService(@PathVariable String name, @RequestBody S if (!service.name().equals(currentName)) { docker.removeContainers(currentName); } + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); return ResponseEntity.ok(service); }); } @@ -114,6 +126,7 @@ public ResponseEntity removeService(@PathVariable String name) { } db.removeService(existing.get().name()); docker.removeContainers(existing.get().name()); + broadcaster.publishConfigChanged(); return ResponseEntity.noContent().build(); }); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java new file mode 100644 index 0000000..c4f2f86 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster.SubscriberLimitException; + +@RestController +@RequestMapping("/api/v1") +public class RunEventsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunEventsController.class); + + private final RunStatusBroadcaster broadcaster; + + public RunEventsController(RunStatusBroadcaster broadcaster) { + this.broadcaster = broadcaster; + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity events() { + try { + return ResponseEntity.ok() + .cacheControl(CacheControl.noCache()) + .header("X-Accel-Buffering", "no") + .body(broadcaster.subscribe()); + } catch (SubscriberLimitException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build(); + } + } + + @ExceptionHandler({AsyncRequestTimeoutException.class, AsyncRequestNotUsableException.class}) + public void streamEnded(Exception e, HttpServletResponse response) { + LOGGER.debug("Event stream ended: {}", e.toString()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java new file mode 100644 index 0000000..99bb197 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@RestController +@RequestMapping("/api/v1") +public class VersionController { + + private final UpdateCheckService updateCheckService; + + public VersionController(UpdateCheckService updateCheckService) { + this.updateCheckService = updateCheckService; + } + + @GetMapping("/version") + public VersionStatusDto version() { + return updateCheckService.status(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java new file mode 100644 index 0000000..96f73ce --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.dto; + +public enum CheckState { + NOT_CHECKED, + OK, + NO_RELEASES, + ERROR +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java new file mode 100644 index 0000000..18fb393 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record VersionStatusDto( + String currentVersion, + String latestVersion, + String releaseUrl, + boolean updateAvailable, + CheckState checkState, + Instant checkedAt, + String message +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 2729377..4130464 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -52,7 +52,9 @@ public class BackupOrchestratorService { private final BackupScheduleService scheduleService; private final DatabaseSnapshotService snapshotService; private final DatabaseService db; + private final RunStatusBroadcaster broadcaster; private final AtomicBoolean running = new AtomicBoolean(false); + private final Object transitionLock = new Object(); private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); private final ExecutorService runnerExecutor = createRunnerExecutor(); @@ -61,13 +63,15 @@ public BackupOrchestratorService( BackupArchiveService archiveService, BackupScheduleService scheduleService, DatabaseSnapshotService snapshotService, - DatabaseService db + DatabaseService db, + RunStatusBroadcaster broadcaster ) { this.runner = runner; this.archiveService = archiveService; this.scheduleService = scheduleService; this.snapshotService = snapshotService; this.db = db; + this.broadcaster = broadcaster; } private static ExecutorService createRunnerExecutor() { @@ -98,104 +102,148 @@ public void scheduledRun() { } LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); try { - runBackup(); + runBackup(true); + } catch (RunRejectedException ex) { + LOGGER.warn("Scheduled backup skipped: {}", ex.getMessage()); } catch (RuntimeException ex) { LOGGER.error("Scheduled backup run failed", ex); } } public BackupRunResult runBackup() { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new RunRejectedException("A backup run is already in progress"); - } + return runBackup(false); + } - configLock.readLock().lock(); - Path runDirectory = null; - try { - List services = db.fetchServices(); - if (services.isEmpty()) { - LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); - throw new RunRejectedException("No services are configured for backup"); + BackupRunResult runBackup(boolean scheduled) { + Instant startedAt = Instant.now(); + String finalStatus = FAILED; + boolean started = false; + synchronized (transitionLock) { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new RunRejectedException("A backup run is already in progress"); } - - scheduleService.markRunStarted(); - runDirectory = archiveService.createRunDirectory(); - final Path runDir = runDirectory; - Instant startedAt = Instant.now(); - - LOGGER.info("Backup run started: runDir={}, services={}", - runDir, services.stream().map(ServiceDefinition::name).toList()); - - List> futures = services.stream() - .map(service -> CompletableFuture - .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) - .exceptionally(t -> { - Throwable cause = unwrap(t); - LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); - return failedResult(service.name(), cause); - })) - .toList(); - - List serviceRunResults = futures.stream() - .map(CompletableFuture::join) - .toList(); - - List incomplete = serviceRunResults.stream() - .filter(r -> !COMPLETED.equals(r.status())) - .toList(); - int succeeded = services.size() - incomplete.size(); - LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); - incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); - - String errorMessage = incomplete.stream() - .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) - .collect(Collectors.joining("\n")); - - if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { - String runId = "failed-" + UUID.randomUUID(); - serviceRunResults.forEach(r -> r.setId(runId)); - db.addNewBackupRecord(new BackupRunResult( - runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); - LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); - throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + } + try { + configLock.readLock().lock(); + Path runDirectory = null; + try { + List services = db.fetchServices(); + if (services.isEmpty()) { + LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); + if (scheduled) { + scheduleService.deferNextRun(); + } + throw new RunRejectedException("No services are configured for backup"); + } + started = true; + publishStarted(startedAt); + + scheduleService.markRunStarted(); + runDirectory = archiveService.createRunDirectory(); + final Path runDir = runDirectory; + + LOGGER.info("Backup run started: runDir={}, services={}", + runDir, services.stream().map(ServiceDefinition::name).toList()); + + List> futures = services.stream() + .map(service -> CompletableFuture + .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); + return failedResult(service.name(), cause); + })) + .toList(); + + List serviceRunResults = futures.stream() + .map(CompletableFuture::join) + .toList(); + + List incomplete = serviceRunResults.stream() + .filter(r -> !COMPLETED.equals(r.status())) + .toList(); + int succeeded = services.size() - incomplete.size(); + LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); + incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); + + String errorMessage = incomplete.stream() + .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) + .collect(Collectors.joining("\n")); + + if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { + String runId = "failed-" + UUID.randomUUID(); + serviceRunResults.forEach(r -> r.setId(runId)); + db.addNewBackupRecord(new BackupRunResult( + runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); + LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); + 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); + 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, + 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, + recordedResults, archive, errorMessage); + db.addNewBackupRecord(backupRecord); + finalStatus = status; + return backupRecord; + } finally { + try { + if (runDirectory != null) { + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } + } catch (RuntimeException e) { + LOGGER.error("Failed to clean up run directory {}", runDirectory, e); + } finally { + configLock.readLock().unlock(); + } } - - 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; + } finally { + synchronized (transitionLock) { + running.set(false); + if (started) { + publishFinished(finalStatus, startedAt); + } } + } + } - BackupArchive archive = archiveService.createArchive(runDirectory); - 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, - recordedResults.stream().map(BackupServiceResult::serviceName).toList()); - - String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; - if (snapshotFailed && COMPLETED.equals(status)) { - status = PARTIAL; - } + private void publishStarted(Instant startedAt) { + try { + broadcaster.publishStarted(startedAt); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-started event", e); + } + } - BackupRunResult backupRecord = new BackupRunResult( - archive.id(), formatTime(startedAt), recordCurrentTime(), status, - recordedResults, archive, errorMessage); - db.addNewBackupRecord(backupRecord); - return backupRecord; - } finally { - if (runDirectory != null) { - archiveService.removeRunDirectory(runDirectory); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } - configLock.readLock().unlock(); - running.set(false); + private void publishFinished(String status, Instant startedAt) { + try { + broadcaster.publishFinished(status, startedAt, Instant.now()); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-finished event", e); } } @@ -235,6 +283,10 @@ public T whileIdle(Supplier configChange) { } } + public void servicesChanged() { + scheduleService.releaseDeferral(); + } + public boolean isRunning() { return running.get(); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index ba01349..1b21d86 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -6,6 +6,7 @@ import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; @@ -22,6 +23,7 @@ public class BackupScheduleService { private final DatabaseService db; private final AtomicReference currentInterval; private final AtomicReference nextRun; + private final AtomicBoolean deferred = new AtomicBoolean(); public BackupScheduleService(MediaGarrdProperties properties, DatabaseService db) { this.db = db; @@ -47,6 +49,7 @@ public Duration updateInterval(Duration interval) { currentInterval.set(safe); Instant next = Instant.now().plus(safe); nextRun.set(next); + deferred.set(false); LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); return safe; } @@ -60,9 +63,24 @@ public boolean dueNow() { public void markRunStarted() { Instant next = Instant.now().plus(currentInterval.get()); nextRun.set(next); + deferred.set(false); LOGGER.info("Backup run started: nextScheduledRun={}", next); } + public void deferNextRun() { + Instant next = Instant.now().plus(currentInterval.get()); + nextRun.set(next); + deferred.set(true); + LOGGER.info("Nothing to back up yet, next scheduled check at {}", next); + } + + public void releaseDeferral() { + if (deferred.compareAndSet(true, false)) { + nextRun.set(Instant.now()); + LOGGER.info("Services are configured, the next scheduled backup is due now"); + } + } + private static Optional parse(String stored) { try { return Optional.of(Duration.parse(stored)).filter(BackupScheduleService::isValid); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java new file mode 100644 index 0000000..0a19f73 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java @@ -0,0 +1,228 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.annotation.PreDestroy; + +@Service +public class RunStatusBroadcaster { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunStatusBroadcaster.class); + + static final int MAX_SUBSCRIBERS = 16; + static final long EMITTER_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(6); + static final long ROLLOVER_MS = TimeUnit.SECONDS.toMillis(270); + static final long PING_INTERVAL_MS = TimeUnit.SECONDS.toMillis(20); + static final int QUEUE_CAPACITY = 8; + + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); + private static final Message CLOSE = new Message("close", ""); + + private final Object lock = new Object(); + private final List subscribers = new ArrayList<>(); + private final int maxSubscribers; + private final long emitterTimeoutMs; + private final long pingIntervalMs; + private final long rolloverMs; + private final ThreadFactory threadFactory; + private boolean running; + private boolean shutdown; + + public RunStatusBroadcaster() { + this(MAX_SUBSCRIBERS, EMITTER_TIMEOUT_MS, PING_INTERVAL_MS, ROLLOVER_MS, RunStatusBroadcaster::newWriterThread); + } + + RunStatusBroadcaster(int maxSubscribers, long emitterTimeoutMs, long pingIntervalMs, long rolloverMs, ThreadFactory threadFactory) { + this.maxSubscribers = maxSubscribers; + this.emitterTimeoutMs = emitterTimeoutMs; + this.pingIntervalMs = pingIntervalMs; + this.rolloverMs = rolloverMs; + this.threadFactory = threadFactory; + } + + private static Thread newWriterThread(Runnable runnable) { + Thread thread = new Thread(runnable, "run-events-writer-" + THREAD_COUNTER.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + + public SseEmitter subscribe() { + return subscribe(new SseEmitter(emitterTimeoutMs)); + } + + SseEmitter subscribe(SseEmitter emitter) { + Subscriber subscriber = new Subscriber(emitter); + synchronized (lock) { + if (shutdown || subscribers.size() >= maxSubscribers) { + throw new SubscriberLimitException("Too many event stream subscribers"); + } + subscriber.queue.offer(new Message("state", stateJson(running, Instant.now()))); + subscribers.add(subscriber); + } + emitter.onTimeout(subscriber::close); + emitter.onCompletion(subscriber::ended); + emitter.onError(error -> subscriber.ended()); + Thread writer = threadFactory.newThread(subscriber::writeLoop); + writer.start(); + return emitter; + } + + public void publishStarted(Instant startedAt) { + publish("run-started", Boolean.TRUE, "{\"running\":true,\"startedAt\":\"" + startedAt + "\"}"); + } + + public void publishFinished(String status, Instant startedAt, Instant finishedAt) { + publish("run-finished", Boolean.FALSE, "{\"running\":false,\"status\":\"" + status.toUpperCase(Locale.ROOT) + + "\",\"startedAt\":\"" + startedAt + "\",\"finishedAt\":\"" + finishedAt + "\"}"); + } + + public void publishBackupsChanged() { + publish("backups-changed", null, atJson()); + } + + public void publishConfigChanged() { + publish("config-changed", null, atJson()); + } + + private static String atJson() { + return "{\"at\":\"" + Instant.now() + "\"}"; + } + + private void publish(String name, Boolean nowRunning, String json) { + Message message = new Message(name, json); + synchronized (lock) { + if (nowRunning != null) { + running = nowRunning; + } + for (Subscriber subscriber : new ArrayList<>(subscribers)) { + if (!subscriber.queue.offer(message)) { + LOGGER.warn("Event stream subscriber is not keeping up, dropping it"); + subscribers.remove(subscriber); + subscriber.close(); + } + } + } + } + + int subscriberCount() { + synchronized (lock) { + return subscribers.size(); + } + } + + @PreDestroy + public void shutdown() { + List toClose; + synchronized (lock) { + shutdown = true; + toClose = new ArrayList<>(subscribers); + subscribers.clear(); + } + toClose.forEach(Subscriber::close); + } + + private static String stateJson(boolean running, Instant at) { + return "{\"running\":" + running + ",\"at\":\"" + at + "\"}"; + } + + private record Message(String name, String data) { + } + + public static class SubscriberLimitException extends RuntimeException { + public SubscriberLimitException(String message) { + super(message); + } + } + + private final class Subscriber { + + private final SseEmitter emitter; + private final BlockingQueue queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY); + private final AtomicBoolean closed = new AtomicBoolean(); + private final AtomicBoolean ended = new AtomicBoolean(); + + Subscriber(SseEmitter emitter) { + this.emitter = emitter; + } + + void close() { + closed.set(true); + queue.offer(CLOSE); + } + + void ended() { + ended.set(true); + synchronized (lock) { + subscribers.remove(this); + } + close(); + } + + void writeLoop() { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(rolloverMs); + try { + while (!closed.get()) { + long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMs <= 0) { + break; + } + Message message = queue.poll(Math.min(pingIntervalMs, remainingMs), TimeUnit.MILLISECONDS); + if (message == null) { + if (System.nanoTime() - deadline >= 0) { + break; + } + message = new Message("ping", "{}"); + } + if (message == CLOSE || closed.get()) { + break; + } + emitter.send(SseEmitter.event().name(message.name()).data(message.data())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Event stream write failed, dropping subscriber: {}", e.toString()); + closed.set(true); + synchronized (lock) { + subscribers.remove(this); + } + finish(e); + return; + } + synchronized (lock) { + subscribers.remove(this); + } + finish(null); + } + + private void finish(Exception error) { + if (ended.get()) { + return; + } + try { + if (error == null) { + emitter.complete(); + } else { + emitter.completeWithError(error); + } + } catch (RuntimeException e) { + LOGGER.debug("Completing the event stream failed: {}", e.toString()); + } + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java new file mode 100644 index 0000000..799880e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java @@ -0,0 +1,171 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.net.http.HttpClient; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.context.annotation.Lazy; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.utilities.SemVer; + +@Service +@Lazy(false) +public class UpdateCheckService { + + @JsonIgnoreProperties(ignoreUnknown = true) + record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("html_url") String htmlUrl) { + } + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCheckService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration READ_TIMEOUT = Duration.ofSeconds(5); + static final Duration MIN_INTERVAL = Duration.ofHours(1); + + private final String currentVersion; + private final Optional current; + private final String repository; + private final Clock clock; + private final RestClient client; + private final AtomicReference status; + + @Autowired + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { + this(properties, versionOf(buildProperties), Clock.systemUTC()); + } + + UpdateCheckService(MediaGarrdProperties properties, String currentVersion, Clock clock) { + Duration interval = properties.getUpdateCheckInterval(); + if (interval == null || interval.compareTo(MIN_INTERVAL) < 0) { + throw new IllegalStateException("mediagarrd.update-check-interval must be at least " + MIN_INTERVAL + ", was " + interval); + } + this.currentVersion = currentVersion; + this.current = SemVer.parse(currentVersion); + this.repository = properties.getUpdateRepository(); + this.clock = clock; + HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + requestFactory.setReadTimeout(READ_TIMEOUT); + this.client = RestClient.builder() + .baseUrl(properties.getGithubApiBaseUrl().replaceAll("/+$", "")) + .requestFactory(requestFactory) + .defaultHeader(HttpHeaders.USER_AGENT, "MediaGarrd-Server/" + (currentVersion == null ? "unknown" : currentVersion)) + .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github+json") + .build(); + this.status = new AtomicReference<>(result(CheckState.NOT_CHECKED, null, null, null)); + } + + public VersionStatusDto status() { + return status.get(); + } + + @Scheduled(initialDelayString = "PT5S", fixedDelayString = "${mediagarrd.update-check-interval:PT24H}") + public void check() { + VersionStatusDto previous = status.get(); + VersionStatusDto next = fetch(); + status.set(next); + logChange(previous, next); + } + + private VersionStatusDto fetch() { + if (current.isEmpty()) { + return result(CheckState.ERROR, null, null, "Current version is unknown"); + } + try { + GithubRelease release = client.get() + .uri("/repos/" + repository + "/releases/latest") + .retrieve() + .body(GithubRelease.class); + return fromRelease(release); + } catch (RestClientResponseException e) { + return fromHttpFailure(e); + } catch (ResourceAccessException e) { + LOGGER.debug("GitHub is unreachable", e); + return result(CheckState.ERROR, null, null, "GitHub is unreachable"); + } catch (RuntimeException e) { + LOGGER.debug("Unexpected update check failure", e); + return result(CheckState.ERROR, null, null, "Unexpected response from GitHub"); + } + } + + private VersionStatusDto fromRelease(GithubRelease release) { + Optional latest = release == null ? Optional.empty() : SemVer.parse(release.tagName()); + if (latest.isEmpty()) { + return result(CheckState.ERROR, null, null, "Latest release has an unrecognized version tag"); + } + String url = release.htmlUrl() == null || release.htmlUrl().isBlank() + ? "https://github.com/" + repository + "/releases/tag/" + release.tagName().strip() + : release.htmlUrl(); + return result(CheckState.OK, latest.get(), url, null); + } + + private VersionStatusDto fromHttpFailure(RestClientResponseException e) { + int code = e.getStatusCode().value(); + if (code == HttpStatus.NOT_FOUND.value()) { + return result(CheckState.NO_RELEASES, null, null, null); + } + boolean limitExhausted = code == HttpStatus.FORBIDDEN.value() + && e.getResponseHeaders() != null + && "0".equals(e.getResponseHeaders().getFirst("X-RateLimit-Remaining")); + if (code == HttpStatus.TOO_MANY_REQUESTS.value() || limitExhausted) { + return result(CheckState.ERROR, null, null, "GitHub rate limit reached"); + } + return result(CheckState.ERROR, null, null, "GitHub returned HTTP " + code); + } + + private VersionStatusDto result(CheckState state, SemVer latest, String url, String message) { + boolean update = state == CheckState.OK && latest != null && current.isPresent() && latest.compareTo(current.get()) > 0; + return new VersionStatusDto( + currentVersion, + latest == null ? null : latest.toString(), + url, + update, + state, + state == CheckState.NOT_CHECKED ? null : clock.instant(), + message); + } + + private static void logChange(VersionStatusDto previous, VersionStatusDto next) { + boolean changed = previous.checkState() != next.checkState() + || !Objects.equals(previous.latestVersion(), next.latestVersion()) + || !Objects.equals(previous.message(), next.message()); + if (!changed) { + LOGGER.debug("Update check unchanged: {}", next.checkState()); + } else if (next.checkState() == CheckState.ERROR) { + LOGGER.warn("Update check failed: {}", next.message()); + } else if (next.updateAvailable()) { + LOGGER.info("Update available: {} -> {} ({})", next.currentVersion(), next.latestVersion(), next.releaseUrl()); + } else { + LOGGER.info("Update check: {}, running {}", next.checkState(), next.currentVersion()); + } + } + + private static String versionOf(ObjectProvider buildProperties) { + BuildProperties build = buildProperties.getIfAvailable(); + return build == null ? null : build.getVersion(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java new file mode 100644 index 0000000..1a10f86 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java @@ -0,0 +1,78 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public record SemVer(long major, long minor, long patch, List prerelease) implements Comparable { + + private static final String IDENTIFIERS = "[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*"; + private static final Pattern PATTERN = Pattern.compile( + "v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-(" + IDENTIFIERS + "))?(?:\\+" + IDENTIFIERS + ")?"); + + public static Optional parse(String text) { + if (text == null) { + return Optional.empty(); + } + Matcher matcher = PATTERN.matcher(text.strip()); + if (!matcher.matches()) { + return Optional.empty(); + } + try { + List prerelease = matcher.group(4) == null ? List.of() : Arrays.asList(matcher.group(4).split("\\.")); + return Optional.of(new SemVer( + Long.parseLong(matcher.group(1)), + Long.parseLong(matcher.group(2)), + Long.parseLong(matcher.group(3)), + prerelease)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + @Override + public int compareTo(SemVer other) { + int result = Long.compare(major, other.major); + if (result == 0) { + result = Long.compare(minor, other.minor); + } + if (result == 0) { + result = Long.compare(patch, other.patch); + } + return result != 0 ? result : comparePrerelease(prerelease, other.prerelease); + } + + @Override + public String toString() { + String core = major + "." + minor + "." + patch; + return prerelease.isEmpty() ? core : core + "-" + String.join(".", prerelease); + } + + private static int comparePrerelease(List left, List right) { + if (left.isEmpty() || right.isEmpty()) { + return Boolean.compare(left.isEmpty(), right.isEmpty()); + } + for (int i = 0; i < Math.min(left.size(), right.size()); i++) { + int result = compareIdentifier(left.get(i), right.get(i)); + if (result != 0) { + return result; + } + } + return Integer.compare(left.size(), right.size()); + } + + private static int compareIdentifier(String left, String right) { + boolean leftNumeric = left.chars().allMatch(Character::isDigit); + boolean rightNumeric = right.chars().allMatch(Character::isDigit); + if (leftNumeric && rightNumeric) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + if (leftNumeric != rightNumeric) { + return leftNumeric ? -1 : 1; + } + return left.compareTo(right); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index c0984fa..2ce92ec 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,9 +1,18 @@ server: port: ${SERVER_PORT:8080} +spring: + task: + scheduling: + pool: + size: 2 + mediagarrd: backup-interval: ${MEDIAGARRD_BACKUP_INTERVAL:PT12H} backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} + update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} + github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} + update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index f817fe9..8f0185b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -11,7 +11,8 @@ @SpringBootTest(properties = { "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-binding-test/backups", "mediagarrd.database-path=${java.io.tmpdir}/mediagarrd-binding-test/mediagarrd.db", - "mediagarrd.helper-image=alpine:3" + "mediagarrd.helper-image=alpine:3", + "mediagarrd.github-api-base-url=http://127.0.0.1:1" }) class MediaGarrdPropertiesBindingTest { @@ -27,5 +28,7 @@ void bindsApplicationProperties() { assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); assertEquals("alpine:3", properties.getHelperImage()); + assertEquals("MediaGarrd/Server", properties.getUpdateRepository()); + assertEquals("http://127.0.0.1:1", properties.getGithubApiBaseUrl()); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index b9b3d5a..29f5e25 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -22,6 +22,7 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(BackupController.class) @@ -35,6 +36,9 @@ class BackupControllerTest { @MockBean BackupOrchestratorService orchestratorService; + @MockBean + RunStatusBroadcaster broadcaster; + @MockBean SetupService setup; @@ -107,4 +111,36 @@ void failedRunReturnsServerErrorWithReason() throws Exception { .andExpect(status().isInternalServerError()) .andExpect(jsonPath("$.error").value("Every service failed, no archive created: radarr: boom")); } + + @Test + void deletingABackupPublishesBackupsChanged() throws Exception { + when(archiveService.deleteById("backup-1")).thenReturn(true); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")) + .andExpect(status().isNoContent()); + + org.mockito.Mockito.verify(broadcaster).publishBackupsChanged(); + } + + @Test + void deletingAMissingBackupPublishesNothing() throws Exception { + when(archiveService.deleteById("nope")).thenReturn(false); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/nope")) + .andExpect(status().isNotFound()); + + org.mockito.Mockito.verify(broadcaster, org.mockito.Mockito.never()).publishBackupsChanged(); + } + + @Test + void updatingTheSchedulePublishesConfigChanged() throws Exception { + when(orchestratorService.updateInterval(Duration.ofHours(2))).thenReturn(Duration.ofHours(2)); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put("/api/v1/schedule") + .contentType(org.springframework.http.MediaType.APPLICATION_JSON) + .content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isOk()); + + org.mockito.Mockito.verify(broadcaster).publishConfigChanged(); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java index 8e59147..9fee6ce 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -36,6 +36,7 @@ import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; import wellatleastitried.mediagarrdServer.service.DatabaseService; import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(ConfigController.class) @@ -58,6 +59,9 @@ class ConfigControllerTest { @MockBean DockerService docker; + @MockBean + RunStatusBroadcaster broadcaster; + @MockBean SetupService setup; @@ -86,6 +90,8 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { verify(db, never()).addService(any()); verify(db, never()).removeService(anyString()); verify(archiveService, never()).updateSettings(any(), any()); + verify(broadcaster, never()).publishConfigChanged(); + verify(broadcaster, never()).publishBackupsChanged(); } @Test @@ -126,6 +132,8 @@ void updatesBackupLocationAndRetentionCount() throws Exception { .andExpect(jsonPath("$.retentionCount").value(4)); verify(archiveService).updateSettings("/new", 4); + verify(broadcaster).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -136,6 +144,8 @@ void passesOmittedFieldsAsNull() throws Exception { .andExpect(status().isOk()); verify(archiveService).updateSettings(isNull(), eq(4)); + verify(broadcaster, never()).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -168,6 +178,8 @@ void addsNormalizedService() throws Exception { .andExpect(jsonPath("$.paths", hasSize(1))); verify(db).addService(RADARR); + verify(orchestrator).servicesChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -179,6 +191,8 @@ void rejectsDuplicateService() throws Exception { .andExpect(jsonPath("$.error").exists()); verify(db, never()).addService(any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); } @Test @@ -199,7 +213,9 @@ void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { .andExpect(jsonPath("$.paths[0]").value("/srv/other")); verify(db).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(orchestrator).servicesChanged(); verify(docker, never()).removeContainers(anyString()); + verify(broadcaster).publishConfigChanged(); } @Test @@ -223,6 +239,8 @@ void renamingOntoExistingServiceConflicts() throws Exception { .andExpect(status().isConflict()); verify(db, never()).updateService(anyString(), any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); } @Test @@ -231,6 +249,8 @@ void updatingMissingServiceReturnsNotFound() throws Exception { mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) .andExpect(status().isNotFound()); + + verify(orchestrator, never()).servicesChanged(); } @Test @@ -242,6 +262,7 @@ void removesServiceAndItsContainers() throws Exception { verify(db).removeService("radarr"); verify(docker).removeContainers("radarr"); + verify(broadcaster).publishConfigChanged(); } @Test diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java new file mode 100644 index 0000000..e4c64e9 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java @@ -0,0 +1,72 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Timeout(30) +@WebMvcTest(RunEventsController.class) +class RunEventsControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + RunStatusBroadcaster broadcaster; + + @MockBean + SetupService setup; + + @Test + void streamsEventsWithoutASetupSession() throws Exception { + when(setup.isCompleted()).thenReturn(false); + when(setup.canConfigure(null)).thenReturn(false); + when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()); + } + + @Test + void streamsEventsAfterSetupToo() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()); + } + + @Test + void answers503WhenTooManySubscribers() throws Exception { + when(broadcaster.subscribe()).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isServiceUnavailable()); + } + + @Test + void aTimedOutStreamEndsQuietlyWithoutAnErrorPage() throws Exception { + when(broadcaster.subscribe()).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); + + var result = mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isOk()) + .andReturn(); + + assertEquals("", result.getResponse().getContentAsString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java new file mode 100644 index 0000000..6027d77 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.SetupService; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@WebMvcTest(VersionController.class) +class VersionControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + UpdateCheckService updateCheckService; + + @MockBean + SetupService setup; + + @Test + void reportsTheVersionStatusWithoutASetupSession() throws Exception { + when(setup.isCompleted()).thenReturn(false); + when(setup.canConfigure(null)).thenReturn(false); + when(updateCheckService.status()).thenReturn(new VersionStatusDto( + "0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, + CheckState.OK, Instant.parse("2026-11-11T18:00:00Z"), null)); + + mockMvc.perform(get("/api/v1/version")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.currentVersion").value("0.1.0")) + .andExpect(jsonPath("$.latestVersion").value("0.2.0")) + .andExpect(jsonPath("$.releaseUrl").value("https://github.com/MediaGarrd/Server/releases/tag/v0.2.0")) + .andExpect(jsonPath("$.updateAvailable").value(true)) + .andExpect(jsonPath("$.checkState").value("OK")) + .andExpect(jsonPath("$.checkedAt").value("2026-11-11T18:00:00Z")) + .andExpect(jsonPath("$.message").doesNotExist()); + } + + @Test + void reportsAFailedCheckAsAState() throws Exception { + when(updateCheckService.status()).thenReturn(new VersionStatusDto( + "0.1.0", null, null, false, CheckState.ERROR, Instant.parse("2026-11-11T18:00:00Z"), "GitHub is unreachable")); + + mockMvc.perform(get("/api/v1/version")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.checkState").value("ERROR")) + .andExpect(jsonPath("$.updateAvailable").value(false)) + .andExpect(jsonPath("$.message").value("GitHub is unreachable")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index 33d03c2..a999d67 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -7,6 +7,8 @@ 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.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -22,17 +24,21 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.mockito.ArgumentCaptor; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +@Timeout(30) class BackupOrchestratorServiceTest { private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); @@ -46,7 +52,8 @@ class BackupOrchestratorServiceTest { private final BackupScheduleService schedule = mock(BackupScheduleService.class); private final DatabaseService db = mock(DatabaseService.class); private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); - private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db); + private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db, broadcaster); @BeforeEach void setUp() { @@ -68,6 +75,62 @@ void refusesToRunWithoutServices() { verify(archives, never()).createRunDirectory(); assertFalse(orchestrator.isRunning()); + verify(broadcaster, never()).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + verify(schedule, never()).deferNextRun(); + } + + @Test + void aRejectedManualRunLeavesTheRealScheduleUntouched() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + BackupScheduleService realSchedule = new BackupScheduleService(properties, db); + BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, db, broadcaster); + when(db.fetchServices()).thenReturn(List.of()); + Instant before = realSchedule.getNextRun(); + + assertThrows(BackupOrchestratorService.RunRejectedException.class, manual::runBackup); + + assertEquals(before, realSchedule.getNextRun()); + manual.shutdownRunnerExecutor(); + } + + @Test + void aScheduledRunWithoutServicesDefersTheNextCheck() { + when(schedule.dueNow()).thenReturn(true); + when(db.fetchServices()).thenReturn(List.of()); + + orchestrator.scheduledRun(); + + verify(schedule).deferNextRun(); + verify(broadcaster, never()).publishStarted(any()); + } + + @Test + void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + when(schedule.dueNow()).thenReturn(true); + + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(BackupOrchestratorService.RunRejectedException.class, () -> orchestrator.runBackup(true)); + + verify(schedule, never()).deferNextRun(); + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + } + + @Test + void changingServicesReleasesTheDeferral() { + orchestrator.servicesChanged(); + + verify(schedule).releaseDeferral(); } @Test @@ -271,6 +334,173 @@ void backupWaitsForInFlightConfigChange() throws Exception { assertEquals(COMPLETED, run.get(5, TimeUnit.SECONDS).status()); } + @Test + void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { + givenResults(COMPLETED, COMPLETED); + + orchestrator.runBackup(); + + var order = inOrder(broadcaster, runner, db); + order.verify(db).fetchServices(); + order.verify(broadcaster).publishStarted(any()); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).run(any(), any()); + order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); + } + + @Test + void publishesPartialWhenSomeServicesFail() { + givenResults(COMPLETED, FAILED); + + orchestrator.runBackup(); + + verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); + } + + @Test + void publishesFailedWhenEveryServiceFails() { + givenResults(FAILED, FAILED); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void publishesFailedWhenArchivingThrows() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void publishesFailedWhenTheRunDirectoryCannotBeCreated() { + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(archives.createRunDirectory()).thenThrow(new IllegalStateException("no space")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishStarted(any()); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void publishesFailedWhenRecordingTheRunThrows() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("db locked")).when(db).addNewBackupRecord(any()); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void runningIsFalseWhenFinishedIsPublished() { + givenResults(COMPLETED, COMPLETED); + AtomicBoolean runningAtFinish = new AtomicBoolean(true); + doAnswer(invocation -> { + runningAtFinish.set(orchestrator.isRunning()); + return null; + }).when(broadcaster).publishFinished(any(), any(), any()); + + orchestrator.runBackup(); + + assertFalse(runningAtFinish.get()); + } + + @Test + void aFailingCleanupDoesNotStickTheRunningFlag() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(COMPLETED, result.status()); + assertFalse(orchestrator.isRunning()); + verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals(COMPLETED, orchestrator.runBackup().status()); + } + + @Test + void aFailingCleanupDoesNotHideTheRunsOwnFailure() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertEquals("disk full", e.getMessage()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aFailingPublishNeverBreaksTheRun() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishStarted(any()); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishFinished(any(), any(), any()); + + assertEquals(COMPLETED, orchestrator.runBackup().status()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(eq(COMPLETED), any(), any()); + } + + @Test + void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { + givenResults(COMPLETED, COMPLETED); + CountDownLatch inFinish = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + inFinish.countDown(); + release.await(); + return null; + }).doNothing().when(broadcaster).publishFinished(any(), any(), any()); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(inFinish.await(5, TimeUnit.SECONDS)); + CompletableFuture second = CompletableFuture.supplyAsync(orchestrator::runBackup); + Thread.sleep(200); + + assertFalse(second.isDone()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + var order = inOrder(broadcaster); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + } + private void givenResults(String radarrStatus, String sonarrStatus) { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); when(runner.run(RADARR, RUN_DIR)).thenReturn(result("radarr", radarrStatus)); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index e54ab04..ba05b43 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -83,4 +83,41 @@ void ignoresCorruptStoredInterval() { db.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); } + + @Test + void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() throws Exception { + BackupScheduleService service = new BackupScheduleService(properties, db); + service.updateInterval(Duration.ofMillis(1)); + Thread.sleep(5); + assertTrue(service.dueNow()); + + service.updateInterval(Duration.ofHours(1)); + Thread.sleep(5); + service.deferNextRun(); + + assertFalse(service.dueNow()); + assertTrue(service.getNextRun().isAfter(java.time.Instant.now().plus(Duration.ofMinutes(59)))); + } + + @Test + void addingAServiceAfterADeferralMakesTheScheduleDueNow() { + BackupScheduleService service = new BackupScheduleService(properties, db); + service.deferNextRun(); + assertFalse(service.dueNow()); + + service.releaseDeferral(); + + assertTrue(service.dueNow()); + } + + @Test + void releasingWithoutADeferralChangesNothing() { + BackupScheduleService service = new BackupScheduleService(properties, db); + java.time.Instant before = service.getNextRun(); + + service.releaseDeferral(); + + assertEquals(before, service.getNextRun()); + assertFalse(service.dueNow()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java new file mode 100644 index 0000000..ce5274b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java @@ -0,0 +1,356 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +@Timeout(30) +class RunStatusBroadcasterTest { + + private static final Instant STARTED = Instant.parse("2026-11-11T10:00:00Z"); + private static final Instant FINISHED = Instant.parse("2026-11-11T10:05:00Z"); + + private final CountDownLatch writerExited = new CountDownLatch(1); + private final List emitters = new ArrayList<>(); + private RunStatusBroadcaster broadcaster = newBroadcaster(16, 60_000); + + @AfterEach + void tearDown() { + broadcaster.shutdown(); + } + + @Test + void sendsTheCurrentStateFirstWhenIdle() throws Exception { + TestEmitter emitter = subscribe(); + + String frame = emitter.next(); + + assertTrue(frame.startsWith("event:state\ndata:{\"running\":false,\"at\":\""), frame); + assertTrue(frame.endsWith("\"}\n\n"), frame); + } + + @Test + void sendsRunningStateToLateSubscribers() throws Exception { + broadcaster.publishStarted(STARTED); + + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":true,\"at\":\"")); + + broadcaster.publishFinished("completed", STARTED, FINISHED); + + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":false,\"at\":\"")); + } + + @Test + void fansStartedAndFinishedOutToEverySubscriber() throws Exception { + TestEmitter first = subscribe(); + TestEmitter second = subscribe(); + first.next(); + second.next(); + + broadcaster.publishStarted(STARTED); + broadcaster.publishFinished("partial", STARTED, FINISHED); + + for (TestEmitter emitter : List.of(first, second)) { + assertEquals("event:run-started\ndata:{\"running\":true,\"startedAt\":\"2026-11-11T10:00:00Z\"}\n\n", emitter.next()); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\"," + + "\"startedAt\":\"2026-11-11T10:00:00Z\",\"finishedAt\":\"2026-11-11T10:05:00Z\"}\n\n", emitter.next()); + } + } + + @Test + void publishesBackupsAndConfigChangesWithoutTouchingTheRunState() throws Exception { + broadcaster.publishStarted(STARTED); + TestEmitter emitter = subscribe(); + assertTrue(emitter.next().startsWith("event:state\ndata:{\"running\":true")); + + broadcaster.publishBackupsChanged(); + broadcaster.publishConfigChanged(); + + String backups = emitter.next(); + String config = emitter.next(); + assertTrue(backups.matches("event:backups-changed\\ndata:\\{\"at\":\"[^\"]+\"\\}\\n\\n"), backups); + assertTrue(config.matches("event:config-changed\\ndata:\\{\"at\":\"[^\"]+\"\\}\\n\\n"), config); + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":true")); + } + + @Test + void changeNoticesNeverBlockOnAStuckSubscriber() throws Exception { + TestEmitter stuck = new TestEmitter(); + stuck.blockSends = new CountDownLatch(1); + broadcaster.subscribe(stuck); + emitters.add(stuck); + assertTrue(stuck.sendEntered.await(5, TimeUnit.SECONDS)); + + CompletableFuture.runAsync(() -> { + for (int i = 0; i < 40; i++) { + broadcaster.publishBackupsChanged(); + broadcaster.publishConfigChanged(); + } + }).get(5, TimeUnit.SECONDS); + + awaitCount(0); + stuck.blockSends.countDown(); + } + + @Test + void sendsANamedPingWhenIdle() throws Exception { + broadcaster = newBroadcaster(16, 30); + TestEmitter emitter = subscribe(); + emitter.next(); + + assertEquals("event:ping\ndata:{}\n\n", emitter.next()); + assertEquals("event:ping\ndata:{}\n\n", emitter.next()); + } + + @Test + void rejectsSubscribersBeyondTheCap() { + broadcaster = newBroadcaster(2, 60_000); + subscribe(); + subscribe(); + + assertThrows(RunStatusBroadcaster.SubscriberLimitException.class, () -> broadcaster.subscribe(new TestEmitter())); + assertEquals(2, broadcaster.subscriberCount()); + } + + @Test + void completionFreesASlot() throws Exception { + broadcaster = newBroadcaster(1, 60_000); + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.completion.get().run(); + + awaitCount(0); + subscribe(); + } + + @Test + void errorFreesASlotWithoutCompletingAgain() throws Exception { + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.error.get().accept(new IOException("reset")); + + awaitCount(0); + assertTrue(writerExited.await(5, TimeUnit.SECONDS)); + assertEquals(1, emitter.completes.getCount()); + assertEquals(1, emitter.errors.getCount()); + } + + @Test + void timeoutCompletesTheEmitterOnTheWriterThread() throws Exception { + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.timeout.get().run(); + + assertTrue(emitter.completes.await(5, TimeUnit.SECONDS)); + assertTrue(emitter.completedOn.get().startsWith("run-events-writer-"), emitter.completedOn.get()); + awaitCount(0); + } + + @Test + void aFailingSendDropsOnlyThatSubscriber() throws Exception { + TestEmitter broken = subscribe(); + TestEmitter healthy = subscribe(); + healthy.next(); + broken.failSends = true; + + broadcaster.publishStarted(STARTED); + + assertTrue(healthy.next().startsWith("event:run-started")); + awaitCount(1); + assertTrue(broken.errors.await(5, TimeUnit.SECONDS)); + } + + @Test + void publishingNeverBlocksOnASubscriberStuckInAWrite() throws Exception { + TestEmitter stuck = new TestEmitter(); + stuck.blockSends = new CountDownLatch(1); + broadcaster.subscribe(stuck); + emitters.add(stuck); + assertTrue(stuck.sendEntered.await(5, TimeUnit.SECONDS)); + + long begin = System.nanoTime(); + CompletableFuture publishing = CompletableFuture.runAsync(() -> { + for (int i = 0; i < 40; i++) { + broadcaster.publishStarted(STARTED); + broadcaster.publishFinished("completed", STARTED, FINISHED); + } + }); + publishing.get(5, TimeUnit.SECONDS); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin); + + assertTrue(elapsedMs < 1000, "publish took " + elapsedMs + "ms"); + awaitCount(0); + assertEquals(1, stuck.completes.getCount()); + + stuck.blockSends.countDown(); + assertTrue(stuck.completes.await(5, TimeUnit.SECONDS)); + assertTrue(stuck.completedOn.get().startsWith("run-events-writer-"), stuck.completedOn.get()); + } + + @Test + void shutdownCompletesEverySubscriberAndRefusesNewOnes() throws Exception { + TestEmitter first = subscribe(); + TestEmitter second = subscribe(); + first.next(); + second.next(); + + broadcaster.shutdown(); + + assertTrue(first.completes.await(5, TimeUnit.SECONDS)); + assertTrue(second.completes.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + assertThrows(RunStatusBroadcaster.SubscriberLimitException.class, () -> broadcaster.subscribe(new TestEmitter())); + } + + @Test + void createsAnEmitterWithAFiniteTimeout() { + RunStatusBroadcaster real = new RunStatusBroadcaster(); + try { + SseEmitter emitter = real.subscribe(); + assertNotNull(emitter); + assertEquals(RunStatusBroadcaster.EMITTER_TIMEOUT_MS, emitter.getTimeout()); + } finally { + real.shutdown(); + } + } + + @Test + void theWriterEndsTheStreamItselfAtTheRolloverAge() throws Exception { + broadcaster.shutdown(); + broadcaster = new RunStatusBroadcaster(16, 60_000, 20, 150, runnable -> { + Thread thread = new Thread(runnable, "run-events-writer-test"); + thread.setDaemon(true); + return thread; + }); + TestEmitter emitter = subscribe(); + emitter.next(); + + assertTrue(emitter.completes.await(5, TimeUnit.SECONDS)); + assertEquals(1, emitter.errors.getCount()); + assertTrue(emitter.completedOn.get().startsWith("run-events-writer-"), emitter.completedOn.get()); + awaitCount(0); + } + + @Test + void rolloverComesBeforeTheEmitterTimeout() { + assertTrue(RunStatusBroadcaster.ROLLOVER_MS < RunStatusBroadcaster.EMITTER_TIMEOUT_MS); + } + + private RunStatusBroadcaster newBroadcaster(int cap, long pingMs) { + return new RunStatusBroadcaster(cap, 60_000, pingMs, 60_000, runnable -> { + Thread thread = new Thread(() -> { + try { + runnable.run(); + } finally { + writerExited.countDown(); + } + }, "run-events-writer-test"); + thread.setDaemon(true); + return thread; + }); + } + + private TestEmitter subscribe() { + TestEmitter emitter = new TestEmitter(); + emitters.add(emitter); + broadcaster.subscribe(emitter); + return emitter; + } + + private void awaitCount(int expected) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (broadcaster.subscriberCount() != expected && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals(expected, broadcaster.subscriberCount()); + } + + static class TestEmitter extends SseEmitter { + + final BlockingQueue frames = new LinkedBlockingQueue<>(); + final CountDownLatch completes = new CountDownLatch(1); + final CountDownLatch errors = new CountDownLatch(1); + final CountDownLatch sendEntered = new CountDownLatch(1); + final AtomicReference timeout = new AtomicReference<>(); + final AtomicReference completion = new AtomicReference<>(); + final AtomicReference> error = new AtomicReference<>(); + final AtomicReference completedOn = new AtomicReference<>(); + volatile boolean failSends; + volatile CountDownLatch blockSends; + + TestEmitter() { + super(60_000L); + } + + String next() throws InterruptedException { + String frame = frames.poll(5, TimeUnit.SECONDS); + assertNotNull(frame, "no frame received"); + return frame; + } + + @Override + public synchronized void send(SseEventBuilder builder) throws IOException { + sendEntered.countDown(); + if (blockSends != null) { + try { + blockSends.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + if (failSends) { + throw new IOException("broken pipe"); + } + StringBuilder frame = new StringBuilder(); + builder.build().forEach(part -> frame.append(part.getData())); + frames.add(frame.toString()); + } + + @Override + public void complete() { + completedOn.set(Thread.currentThread().getName()); + completes.countDown(); + } + + @Override + public void completeWithError(Throwable ex) { + errors.countDown(); + } + + @Override + public void onTimeout(Runnable callback) { + timeout.set(callback); + } + + @Override + public void onCompletion(Runnable callback) { + completion.set(callback); + } + + @Override + public void onError(Consumer callback) { + error.set(callback); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java new file mode 100644 index 0000000..1488833 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java @@ -0,0 +1,285 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; + +class UpdateCheckServiceTest { + + private static final Instant NOW = Instant.parse("2026-11-11T18:00:00Z"); + + private final List requests = new ArrayList<>(); + private final List userAgents = new ArrayList<>(); + private final MediaGarrdProperties properties = new MediaGarrdProperties(); + private HttpServer server; + private int status = 200; + private String rateLimitRemaining; + private String response = ""; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + properties.setGithubApiBaseUrl("http://127.0.0.1:" + server.getAddress().getPort() + "/"); + properties.setUpdateRepository("MediaGarrd/Server"); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + private UpdateCheckService service(String currentVersion) { + return new UpdateCheckService(properties, currentVersion, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static String release(String tag) { + return "{\"tag_name\": \"" + tag + "\", \"html_url\": \"https://github.com/MediaGarrd/Server/releases/tag/" + tag + + "\", \"draft\": false, \"prerelease\": false, \"id\": 1}"; + } + + @Test + void reportsNotCheckedBeforeTheFirstRun() { + VersionStatusDto result = service("0.1.0").status(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null), result); + assertTrue(requests.isEmpty()); + } + + @Test + void reportsAnUpdateWhenTheLatestReleaseIsNewer() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, CheckState.OK, NOW, null), service.status()); + assertEquals(List.of("/repos/MediaGarrd/Server/releases/latest"), requests); + assertEquals(List.of("MediaGarrd-Server/0.1.0"), userAgents); + } + + @Test + void reportsUpToDateWhenTheLatestReleaseIsTheSameVersion() { + response = release("v0.1.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertEquals("0.1.0", service.status().latestVersion()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void neverReportsAnOlderReleaseAsAnUpdate() { + response = release("v0.1.0"); + UpdateCheckService service = service("0.2.0"); + + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void treatsAPrereleaseOfTheRunningVersionAsOlder() { + response = release("v0.2.0-rc.1"); + UpdateCheckService service = service("0.2.0"); + + service.check(); + + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsNoReleasesOnNotFound() { + status = 404; + response = "{\"message\": \"Not Found\"}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NO_RELEASES, NOW, null), service.status()); + } + + @Test + void reportsRateLimitingAsAnError() { + status = 403; + rateLimitRemaining = "0"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub rate limit reached", service.status().message()); + assertFalse(service.status().updateAvailable()); + + status = 429; + rateLimitRemaining = null; + service.check(); + assertEquals("GitHub rate limit reached", service.status().message()); + } + + @Test + void reportsAForbiddenResponseWithoutAnExhaustedLimitAsAPlainHttpError() { + status = 403; + UpdateCheckService service = service("0.1.0"); + + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 403", service.status().message()); + + rateLimitRemaining = "12"; + service.check(); + assertEquals("GitHub returned HTTP 403", service.status().message()); + } + + @Test + void rejectsCheckIntervalsBelowOneHour() { + properties.setUpdateCheckInterval(Duration.ofMinutes(59)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> service("0.1.0")); + assertTrue(failure.getMessage().contains("at least PT1H")); + + properties.setUpdateCheckInterval(Duration.ZERO); + assertThrows(IllegalStateException.class, () -> service("0.1.0")); + + properties.setUpdateCheckInterval(Duration.ofHours(1)); + service("0.1.0"); + } + + @Test + void reportsServerErrorsAsAnError() { + status = 500; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 500", service.status().message()); + assertEquals(NOW, service.status().checkedAt()); + } + + @Test + void reportsAnUnreachableGithubAsAnErrorWithoutThrowing() { + server.stop(0); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub is unreachable", service.status().message()); + } + + @Test + void reportsMalformedResponsesAsAnError() { + response = "not json"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsAnUnrecognizedTagAsAnError() { + response = release("nightly"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("Latest release has an unrecognized version tag", service.status().message()); + } + + @Test + void reportsAnErrorWithoutCallingGithubWhenTheCurrentVersionIsUnknown() { + response = release("v9.9.9"); + + for (String unknown : new String[] {null, "unspecified"}) { + UpdateCheckService service = service(unknown); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + assertEquals("Current version is unknown", service.status().message()); + } + assertTrue(requests.isEmpty()); + } + + @Test + void buildsTheReleaseUrlWhenGithubOmitsIt() { + response = "{\"tag_name\": \"v0.3.0\"}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals("https://github.com/MediaGarrd/Server/releases/tag/v0.3.0", service.status().releaseUrl()); + } + + @Test + void recoversOnTheNextCheckAfterAFailure() { + status = 500; + UpdateCheckService service = service("0.1.0"); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + + status = 200; + response = release("v0.2.0"); + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertTrue(service.status().updateAvailable()); + assertNull(service.status().message()); + } + + @Test + void usesTheConfiguredRepository() { + properties.setUpdateRepository("someone/else"); + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(List.of("/repos/someone/else/releases/latest"), requests); + } + + private void handle(HttpExchange exchange) throws IOException { + requests.add(exchange.getRequestURI().getPath()); + userAgents.add(exchange.getRequestHeaders().getFirst("User-Agent")); + byte[] body = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (rateLimitRemaining != null) { + exchange.getResponseHeaders().add("X-RateLimit-Remaining", rateLimitRemaining); + } + exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); + if (body.length > 0) { + exchange.getResponseBody().write(body); + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java new file mode 100644 index 0000000..0d1c1f5 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java @@ -0,0 +1,66 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class SemVerTest { + + private static SemVer v(String text) { + return SemVer.parse(text).orElseThrow(); + } + + @Test + void parsesWithAndWithoutLeadingV() { + assertEquals(new SemVer(0, 1, 0, List.of()), v("0.1.0")); + assertEquals(new SemVer(0, 1, 0, List.of()), v("v0.1.0")); + assertEquals(new SemVer(12, 34, 56, List.of()), v(" v12.34.56 ")); + } + + @Test + void parsesPrereleaseAndIgnoresBuildMetadata() { + assertEquals(new SemVer(1, 0, 0, List.of("rc", "1")), v("v1.0.0-rc.1+build.5")); + assertEquals(0, v("1.0.0+a").compareTo(v("1.0.0+b"))); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "1", "1.2", "v1.2", "1.2.3.4", "latest", "1.2.x", "1.2.3-", "1.2.3-a..b", "vv1.2.3", "1.2.3 beta", "99999999999999999999.0.0"}) + void rejectsInvalidVersions(String text) { + assertEquals(Optional.empty(), SemVer.parse(text)); + } + + @Test + void rejectsNull() { + assertEquals(Optional.empty(), SemVer.parse(null)); + } + + @Test + void comparesNumericallyNotLexically() { + assertTrue(v("0.10.0").compareTo(v("0.9.0")) > 0); + assertTrue(v("1.0.0").compareTo(v("0.99.99")) > 0); + assertTrue(v("0.1.10").compareTo(v("0.1.9")) > 0); + assertTrue(v("0.1.0").compareTo(v("0.2.0")) < 0); + assertEquals(0, v("v0.1.0").compareTo(v("0.1.0"))); + } + + @Test + void ordersPrereleasesPerSemver() { + List ascending = List.of("1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"); + for (int i = 0; i < ascending.size() - 1; i++) { + assertTrue(v(ascending.get(i)).compareTo(v(ascending.get(i + 1))) < 0, ascending.get(i) + " < " + ascending.get(i + 1)); + assertTrue(v(ascending.get(i + 1)).compareTo(v(ascending.get(i))) > 0); + } + } + + @Test + void rendersWithoutPrefixOrMetadata() { + assertEquals("0.2.0", v("v0.2.0").toString()); + assertEquals("1.0.0-rc.1", v("v1.0.0-rc.1+x").toString()); + } +} From 320688d18c875f440e8a12d717bd6a5d444c4043 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 12 Nov 2026 17:16:43 -0600 Subject: [PATCH 22/26] Simplify README.md --- README.md | 95 ++++++------------------------------------------ docs/API.md | 41 +++++++++++++++++++++ docs/database.md | 43 ++++++++++++++++++++++ docs/settings.md | 21 +++++++++++ 4 files changed, 117 insertions(+), 83 deletions(-) create mode 100644 docs/API.md create mode 100644 docs/database.md create mode 100644 docs/settings.md diff --git a/README.md b/README.md index ee6464f..15ecfeb 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ # Server -This is the official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +The official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). It backs up the configuration of the services on its host into a single zip archive on a schedule, and the [MediaGarrd Client](https://github.com/MediaGarrd/Client) manages it and downloads the archives to another machine. + +Full documentation, including configuration, archives and restoring, is on the [MediaGarrd website](https://mediagarrd.github.io/MediaGarrd/). + +## Docs +- [settings.md](./docs/settings.md): every environment variable and its default. +- [API.md](./docs/API.md): every HTTP endpoint and what it returns. +- [database.md](./docs/database.md): recovering the server's database from a backup. ## Requirements -- A Linux host running Docker with Compose v2 (`docker compose ...`) -- The host paths of the services you want to back up +- A Linux host running Docker with Compose v2 ## Installation ```bash @@ -14,96 +20,19 @@ cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` -The defaults in `docker-compose.yml` work as-is. To change them before the first start: -- **Port:** change both `SERVER_PORT` and the `ports` mapping (default `38471`). -- **Where archives are stored on the host:** change the left side of the `./data/server/backups` volume. -- **Where the database is stored on the host:** change the left side of the `./data/server/db` volume. This holds every setting and service, so keep it on persistent storage. - -## First-time setup -Until setup is finished, the server prints a single-use setup PIN to its logs: +Then get the single-use setup PIN from the logs: ```bash docker logs mediagarrd-server 2>&1 | grep "Setup PIN" ``` -From any device on the network, open `http://:38471/config` and enter the PIN. A new PIN is logged each time one is used, after 5 wrong attempts, and on every restart. - -On the setup page: -1. **Backup Settings:** the backup location (a path *inside* the container that must be on a mounted volume, default `/var/lib/mediagarrd/backups`), the hours between backups, and how many backups to keep. -2. **Services:** add each service with a name and the absolute **host** paths to back up. Any service can be backed up. A path can be a directory (everything inside it is included) or a single file (only that file is included). -3. **Finish Setup:** available once at least one service exists. The setup page is then disabled for good. - -## Configuration after setup -Every setting is stored in the database and survives restarts and container rebuilds. After setup, change them through the API or the MediaGarrd Client: - -| Setting | Endpoint | -|---------|----------| -| Read all settings | `GET /api/v1/config` | -| Backup location and/or backups to keep | `PUT /api/v1/config` with `{"backupLocation": "/path", "retentionCount": 10}` | -| Time between backups (ISO-8601) | `PUT /api/v1/schedule` with `{"backupInterval": "PT12H"}` | -| List / add services | `GET` / `POST /api/v1/services` with `{"name": "radarr", "paths": ["/srv/radarr/config"]}` | -| Update / remove a service | `PUT` / `DELETE /api/v1/services/{name}` | -| Server version and update status (no setup session needed) | `GET /api/v1/version` | -| Live run status stream (no setup session needed) | `GET /api/v1/events` | - -`GET /api/v1/events` is a Server-Sent Events stream (`text/event-stream`) of run status. It sends `state` (`{"running":false,"at":"..."}`) as soon as you connect, `run-started` (`{"running":true,"startedAt":"..."}`) and `run-finished` (`{"running":false,"status":"COMPLETED","startedAt":"...","finishedAt":"..."}`, status is `COMPLETED`, `PARTIAL`, or `FAILED`) when a run begins and ends, `backups-changed` and `config-changed` (both `{"at":"..."}`) after a backup is deleted or the backup location changes, and after the schedule, settings, or services change, and a `ping` (`{}`) every 20 seconds. A run that is rejected before it starts (such as no services configured) publishes no run events. A scheduled check with nothing to back up waits one full interval, and adding or editing a service makes the schedule due again right away. Up to 16 listeners are served at once (more get `503`), and each stream ends cleanly after 4.5 minutes so listeners should reconnect. The MediaGarrd Client uses it to show Running and Idle the moment a run starts or ends, and falls back to polling `/api/v1/health` when it is unavailable. - -Configuration changes are rejected with `409 Conflict` while a backup is running. A lower retention count takes effect on the next backup run. - -`MEDIAGARRD_BACKUP_INTERVAL` and `MEDIAGARRD_RETENTION_COUNT` in `docker-compose.yml` only set the initial values. Once a value has been saved through setup or the API, the stored value is used. - -The database is checked on startup and whenever its schema changes underneath the server. If it is deleted, has a table dropped, or is replaced by an older copy, it is rebuilt or upgraded automatically. A corrupt database is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty one, after which settings and services must be configured again (restart the server to get a new setup PIN). - -## Update alerts -The server checks the latest release of `MediaGarrd/Server` on GitHub a few seconds after starting and then once a day, and keeps the result in memory. `GET /api/v1/version` returns it and needs no setup session: - -```json -{ - "currentVersion": "0.1.0", - "latestVersion": "0.2.0", - "releaseUrl": "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", - "updateAvailable": true, - "checkState": "OK", - "checkedAt": "2026-11-11T18:00:00Z", - "message": null -} -``` -`checkState` is `NOT_CHECKED` until the first check finishes, `OK` when a release was found, `NO_RELEASES` when none has been published yet, and `ERROR` when GitHub could not be asked (`message` says why). A failed check never affects backups and is tried again at the next interval. The MediaGarrd Client shows the result in its Versions panel. - -To change what is checked, set `MEDIAGARRD_UPDATE_REPOSITORY` (default `MediaGarrd/Server`), `MEDIAGARRD_GITHUB_API_URL` (default `https://api.github.com`), or `MEDIAGARRD_UPDATE_CHECK_INTERVAL` (ISO-8601, default `PT24H`, minimum `PT1H`) in `environment`. +Open `http://:38471/config`, enter the PIN, add the services to back up, and finish setup. ## Updating ```bash git pull docker compose up --build -d ``` -Settings, services, and archives live in the mounted `./data/server` volumes and are kept. - -## How backups work -On every backup run the server creates (but never starts) a small helper container per service with its paths mounted read-only, and streams them into the backup archive through the Docker API. The helper container is reused until the service's paths change. - -### Archive layout -Every entry in a backup zip sits at its absolute host path without the leading `/`, with no per-service folder. A service backing up `/etc/nginx/sites-available/default` and `/srv/radarr/config` produces: -``` -etc/nginx/sites-available/default -srv/radarr/config/ -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 .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. +> **Security:** the server mounts `/var/run/docker.sock`, which gives it root-equivalent access to the host, and its API is unauthenticated after setup. Do not expose its port to untrusted networks. ## License [MIT](./LICENSE) diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..f6743eb --- /dev/null +++ b/docs/API.md @@ -0,0 +1,41 @@ +# Server API + +All endpoints are under `/api/v1`. Errors are returned as `{"error": "..."}` with a matching status code. + +## Status +| Endpoint | Returns | +|---|---| +| `GET /health` | The server's health, whether a backup is running, the number of backups to keep, and the time between backups. | +| `GET /version` | The running version and the result of the daily check for a newer GitHub release. | +| `GET /events` | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | + +## Setup +| Endpoint | Returns | +|---|---| +| `GET /setup` | Whether first-time setup is finished and whether the caller holds a setup session. | +| `POST /setup/session` | An empty `204` and a setup session cookie when the posted PIN is correct. | +| `POST /setup/complete` | An empty `204` once setup is finished, after which the setup page is disabled. | + +The setup page itself is served at `GET /config` until setup is finished. + +## Configuration +| Endpoint | Returns | +|---|---| +| `GET /config` | The backup location, the number of backups to keep, and the time between backups. | +| `PUT /config` | The updated configuration after changing the backup location and/or the number of backups to keep. | +| `PUT /schedule` | The server status after changing the time between backups. | +| `GET /services` | Every configured service with its host paths. | +| `POST /services` | The added service, with `201`. | +| `PUT /services/{name}` | The updated service. | +| `DELETE /services/{name}` | An empty `204` once the service is removed. | + +## Backups +| Endpoint | Returns | +|---|---| +| `GET /backups` | Every archive with its id, file name, size, and creation time. | +| `GET /backups/latest` | The newest archive's details. | +| `GET /backups/{id}` | One archive's details. | +| `GET /backups/latest/download` | The newest archive as a zip file. | +| `GET /backups/{id}/download` | One archive as a zip file. | +| `DELETE /backups/{id}` | An empty `204` once the archive is deleted. | +| `POST /backups/run` | The run id, start and end time, services that ran, and the new archive, once the backup finishes. | diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 0000000..f2bf1ed --- /dev/null +++ b/docs/database.md @@ -0,0 +1,43 @@ +# Recovering the database + +Every backup archive contains a consistent copy of the server's own database: its settings, services, and backup records. The copy is taken while no other database operation runs, so it is never half written. It does not contain the record of the run that created it. + +## Where the copy is in the archive +The copy sits at the database file's absolute host path, without the leading `/`. With the example `docker-compose.yml`, which mounts `./data/server/db` at `/var/lib/mediagarrd/db`, that is something like: +``` +home/you/Server/data/server/db/mediagarrd.db +``` +To find it in an archive: +```bash +bsdtar -tf .zip | grep 'mediagarrd\.db$' +``` +If the copy could not be taken, the archive has no database entry and the run was reported as partial with the error listed under `_mediagarrd-server`. + +On Docker Desktop (macOS and Windows) the path is one inside Docker's VM, so it will not match your real host path. The file name is still `mediagarrd.db`. + +## Restoring it +Never restore over the database of a running server. + +1. Stop the server: + ```bash + docker compose stop + ``` +2. Extract the copy into an empty directory: + ```bash + mkdir restore + bsdtar -xpf .zip -C restore '' + ``` +3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): + ```bash + cp restore/ ./data/server/db/mediagarrd.db + rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm + ``` +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. + +## If the database is damaged +The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..a1a3df3 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,21 @@ +# Settings + +Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for example `PT12H`. + +| Variable | Default | What it does | +|---|---|---| +| `SERVER_PORT` | `8080` (`38471` in the example compose file) | The port of the API and setup page. Change the `ports` mapping to match. | +| `MEDIAGARRD_BACKUP_INTERVAL` | `PT12H` | The time between scheduled backups. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. | +| `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_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. | +| `MEDIAGARRD_UPDATE_CHECK_INTERVAL` | `PT24H` | How often the release check runs. Minimum `PT1H`. | + +To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: +- `./data/server/backups`: the archives. +- `./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. From fa08d04c33d19e251e11b0044612ef2bcf92dc87 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 12 Nov 2026 17:49:15 -0600 Subject: [PATCH 23/26] Optimize hashing, compression, and memory. --- CHANGELOG | 9 + Dockerfile | 18 +- build.gradle.kts | 30 +- docs/database.md | 4 +- docs/settings.md | 11 + .../MediaGarrdProperties.java | 1 + .../mediagarrdServer/model/BackupArchive.java | 11 +- .../service/BackupArchiveService.java | 62 +-- .../service/BackupOrchestratorService.java | 102 ++++- .../service/DatabaseService.java | 2 +- .../service/DatabaseSnapshotService.java | 60 ++- .../service/PathCoverage.java | 60 +++ .../service/ServiceBackupRunner.java | 221 ++++++----- .../service/ZipCompression.java | 48 +++ .../mediagarrdServer/service/ZipFormat.java | 232 +++++++++++ .../service/ZipPartIndex.java | 27 ++ .../service/ZipPartMerger.java | 221 +++++++++++ .../service/ZipPartWriter.java | 364 ++++++++++++++++++ src/main/resources/application.yml | 1 + .../MediaGarrdPropertiesBindingTest.java | 1 + .../service/ArchiveInteropTest.java | 102 +++++ .../service/ArchiveScaleTest.java | 144 +++++++ .../service/ArchiveTestSupport.java | 92 +++++ .../service/BackupArchiveServiceTest.java | 123 +++++- .../service/BackupCopyRoundsTest.java | 318 +++++++++++++++ .../BackupOrchestratorServiceTest.java | 57 +-- .../service/CoveredSymlinkTest.java | 97 +++++ .../service/DatabaseSnapshotServiceTest.java | 4 +- .../service/GeneratedTar.java | 107 +++++ .../service/PathCoverageTest.java | 48 +++ .../service/ServiceBackupRunnerTest.java | 199 ++++++++-- .../mediagarrdServer/service/TallyTest.java | 47 +++ .../service/ZipCompressionBindingTest.java | 54 +++ .../service/ZipCompressionTest.java | 82 ++++ .../service/ZipFormatTest.java | 36 ++ .../service/ZipPartWriterTest.java | 267 +++++++++++++ 36 files changed, 2994 insertions(+), 268 deletions(-) create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java diff --git a/CHANGELOG b/CHANGELOG index a483054..5fb07d1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -5,6 +5,15 @@ - A scheduled check with nothing to back up now waits one full interval instead of retrying every 30 seconds, and adding or editing a service makes the schedule due again right away - `GET /api/v1/events` also sends `backups-changed` (backup deleted, backup location changed) and `config-changed` (schedule, settings, or services changed), each as `{"at":""}` - `GET /api/v1/health` and `GET /api/v1/backups` are logged at DEBUG, so polling no longer fills the log +- An archive's SHA-256 is now computed while it is written instead of by reading the finished file again, which saves a full pass over every backup +- Archives are compressed at a lighter level by default (`MEDIAGARRD_COMPRESSION_LEVEL`, `0` to `9`, default `1`), and already-compressed files (images, video, audio, zip, gz and similar) are stored as they are +- Backups use a fixed amount of memory regardless of how many files or how much data they hold: archives are written as a stream with an on-disk index, so any backup that fits on disk completes +- The archive writer is our own: zip64 is used automatically for entries over 4 GB, archives over 4 GB, and more than 65,535 entries, and entries now also carry an exact UTC modification time +- Entry owners are always written as a 4-byte uid/gid (`0x7875`), because bsdtar reads only 2- or 4-byte widths and ignored the shorter form, so `bsdtar -xp` now restores small uids such as 33 (www-data) correctly; the NTFS extra (`0x000A`) is no longer written +- A symlink inside a copied path that is also configured as its own path is not stored; the configured path is copied from its real content instead, so restoring that path no longer hits a link-versus-directory conflict and the merge never sees a duplicate name +- A path nested inside another configured path is no longer copied twice: it is skipped when the outer copy includes it, and copied on its own if the outer copy failed, and each service's result reflects its own outcome +- The database snapshot is taken first, and the live database and its `-journal`, `-wal`, and `-shm` files are left out of service copies only when the snapshot succeeded +- The container image is pinned to `eclipse-temurin:21.0.13_9-jre` and starts the JVM with G1, a small starting heap, periodic heap trimming, and `-XX:+ExitOnOutOfMemoryError`; the heap cap follows the container memory (`JAVA_TOOL_OPTIONS`, see `docs/settings.md`), and lazy initialization is no longer used ## 11-11-26 - `GET /api/v1/events` is a live Server-Sent Events stream that needs no setup session: `state` on connect, `run-started` and `run-finished` (`COMPLETED`, `PARTIAL`, or `FAILED`) the moment a run begins and ends, and a `ping` every 20 seconds diff --git a/Dockerfile b/Dockerfile index 45dd5a5..53332a9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,16 +3,20 @@ WORKDIR /workspace COPY . . RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all -FROM eclipse-temurin:21-jre +FROM eclipse-temurin:21.0.13_9-jre WORKDIR /app COPY --from=build /workspace/build/libs/*.jar app.jar EXPOSE 8080 +ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=50" + ENTRYPOINT ["java", \ - "-Xms32m", \ - "-XX:+UseZGC", \ - "-XX:+ZUncommit", \ - "-XX:ZUncommitDelay=30", \ - "-XX:+UseContainerSupport", \ - "-Dspring.main.lazy-initialization=true", \ + "-XX:+UseG1GC", \ + "-Xms16m", \ + "-XX:MinHeapFreeRatio=10", \ + "-XX:MaxHeapFreeRatio=30", \ + "-XX:G1PeriodicGCInterval=60000", \ + "-XX:-G1PeriodicGCInvokesConcurrent", \ + "-XX:TrimNativeHeapInterval=10000", \ + "-XX:+ExitOnOutOfMemoryError", \ "-jar", "/app/app.jar"] diff --git a/build.gradle.kts b/build.gradle.kts index b749201..c641e5f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -38,5 +38,33 @@ springBoot { } tasks.test { - useJUnitPlatform() + useJUnitPlatform { + excludeTags("scale") + } +} + +tasks.register("scaleTest") { + group = "verification" + description = "Builds very large archives under a small heap" + testClassesDirs = sourceSets.test.get().output.classesDirs + classpath = sourceSets.test.get().runtimeClasspath + useJUnitPlatform { + includeTags("scale") + } + val scratch = layout.buildDirectory.dir("scale-tmp").get().asFile + maxHeapSize = "64m" + jvmArgs("-XX:+UseG1GC", "-Xms16m", "-XX:MinHeapFreeRatio=10", "-XX:MaxHeapFreeRatio=30", "-XX:+ExitOnOutOfMemoryError") + systemProperty("java.io.tmpdir", scratch.absolutePath) + doFirst { + scratch.deleteRecursively() + scratch.mkdirs() + } + doLast { + scratch.deleteRecursively() + } + testLogging { + showStandardStreams = true + events("passed", "failed", "skipped") + } + shouldRunAfter(tasks.test) } diff --git a/docs/database.md b/docs/database.md index f2bf1ed..d92dab6 100644 --- a/docs/database.md +++ b/docs/database.md @@ -25,7 +25,7 @@ Never restore over the database of a running server. 2. Extract the copy into an empty directory: ```bash mkdir restore - bsdtar -xpf .zip -C restore '' + bsdtar -xpPf .zip -C restore '' ``` 3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): ```bash @@ -37,7 +37,7 @@ Never restore over the database of a running server. docker compose start ``` -`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. +`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. `-P` lets it extract through symbolic links stored in the archive. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. ## If the database is damaged The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. diff --git a/docs/settings.md b/docs/settings.md index a1a3df3..30dfbad 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -9,6 +9,7 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | `MEDIAGARRD_RETENTION_COUNT` | `10` | How many backups to keep. Only the initial value, like the interval. | | `MEDIAGARRD_BACKUP_ROOT` | `/var/lib/mediagarrd/backups` | Where archives are stored, inside the container. Only the initial value. It must be on a mounted volume. | | `MEDIAGARRD_DATABASE_PATH` | `/var/lib/mediagarrd/db/mediagarrd.db` | The database file, inside the container. It must be on a mounted volume. | +| `MEDIAGARRD_COMPRESSION_LEVEL` | `1` | How hard files are compressed in archives, from `0` (store, no compression) to `9` (smallest, slowest). Files that are already compressed (zip, gz, tgz, bz2, xz, zst, 7z, rar, jpg, jpeg, png, gif, webp, mp4, mkv, mp3, flac, ogg, mov, avi, webm, m4v, m4a, aac, opus, heic, avif, lz4, zstd, jar, docx, xlsx, pptx) are always stored. The server refuses to start with a value outside 0 to 9. | | `MEDIAGARRD_HELPER_IMAGE` | `busybox:stable` | The image used for the helper containers that read each service's files. | | `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Server` | The GitHub repository checked for new releases. | | `MEDIAGARRD_GITHUB_API_URL` | `https://api.github.com` | The GitHub API used for the release check. | @@ -19,3 +20,13 @@ To change where data is kept on the host, change the left side of the volumes in - `./data/server/db`: the database, which holds every setting and service. Keep it on persistent storage. The server also needs `/var/run/docker.sock` mounted to run its helper containers. + +## Memory + +The server idles at roughly 100 to 150 MB and uses a fixed amount of memory while backing up, however many files or however much data a backup holds. Archives are written to disk as a stream, so the only requirement is free disk space: about twice the size of the archive while a run is in progress (the per-path parts plus the merged archive). + +The JVM is tuned in the `Dockerfile`: G1 with a small starting heap that shrinks back after a backup, native memory trimming, and `-XX:+ExitOnOutOfMemoryError` so the container restarts instead of hanging. + +The heap cap defaults to half of the container's memory limit (`JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=50`). Without a memory limit on the container this is half of the host's RAM. To change it, set `JAVA_TOOL_OPTIONS` in `environment`, for example `JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=70` or `JAVA_TOOL_OPTIONS=-Xmx256m`. Setting it replaces the whole default value, and the JVM prints `Picked up JAVA_TOOL_OPTIONS` at startup when it is in effect. + +The image is pinned to `eclipse-temurin:21.0.13_9-jre` because `-XX:TrimNativeHeapInterval` needs Java 21.0.3 or newer. To check the flags against another image, run `docker run --rm java -XX:TrimNativeHeapInterval=10000 -XX:+UseG1GC -version`. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index b50e931..41ea9c5 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -16,6 +16,7 @@ public class MediaGarrdProperties { private String backupRoot = "/var/lib/mediagarrd/backups"; private int retentionCount = 10; private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; + private int compressionLevel = 1; private String helperImage = "busybox:stable"; private String updateRepository = "MediaGarrd/Server"; private String githubApiBaseUrl = "https://api.github.com"; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index 4f1bb69..3322f4e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -15,8 +15,17 @@ public record BackupArchive( String fileName, Path path, long sizeBytes, - Instant createdAt + Instant createdAt, + String checksum ) { + public BackupArchive(String id, String fileName, Path path, long sizeBytes, Instant createdAt) { + this(id, fileName, path, sizeBytes, createdAt, null); + } + + public String resolvedChecksum() { + return checksum != null ? checksum : generateChecksum(); + } + public String generateChecksum() { try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), MessageDigest.getInstance("SHA-256"))) { in.transferTo(OutputStream.nullOutputStream()); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index 43354ad..49d1ebf 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -10,22 +10,13 @@ import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -43,7 +34,6 @@ public class BackupArchiveService { .withZone(ZoneOffset.UTC); private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds static final String ARCHIVE_SUFFIX = "-media-backup.zip"; - private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private final DatabaseService db; private final AtomicReference> cachedArchives = new AtomicReference<>(null); @@ -166,14 +156,14 @@ public BackupArchive createArchive(Path runDirectory) { LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); try { Files.createDirectories(root); - mergeParts(runDirectory, archivePath); + String checksum = mergeParts(runDirectory, archivePath); enforceRetention(); long size = Files.size(archivePath); LOGGER.info("Archive created: {} ({} bytes)", fileName, size); invalidateCache(); - return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); + return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt, checksum); } catch (IOException e) { LOGGER.error("Failed to create backup archive: {}", fileName, e); throw new IllegalStateException("Failed to create backup archive", e); @@ -289,63 +279,33 @@ private void invalidateCache() { cachedArchives.set(null); } - private void mergeParts(Path runDirectory, Path zipPath) throws IOException { + private String mergeParts(Path runDirectory, Path zipPath) throws IOException { List parts; try (var walk = Files.walk(runDirectory)) { parts = walk .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip")) + .filter(path -> path.getFileName().toString().endsWith(ZipPartWriter.PART_SUFFIX)) .sorted() .toList(); } Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); Path snapshotDirectory = runDirectory.resolve(DatabaseSnapshotService.PART_DIRECTORY); - List openParts = new ArrayList<>(); - SortedMap entries = new TreeMap<>(); - Set reserved = new HashSet<>(); + ZipPartMerger.Result result; try { - for (Path part : parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList()) { - ZipFile zip = ZipFile.builder().setPath(part).get(); - openParts.add(zip); - for (ZipArchiveEntry entry : Collections.list(zip.getEntriesInPhysicalOrder())) { - entries.put(entry.getName(), new ZipEntrySource(zip, entry)); - if (!entry.isDirectory()) { - DATABASE_SIDECAR_SUFFIXES.forEach(suffix -> reserved.add(entry.getName() + suffix)); - } - } - } - for (Path part : parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList()) { - ZipFile zip = ZipFile.builder().setPath(part).get(); - openParts.add(zip); - for (ZipArchiveEntry entry : Collections.list(zip.getEntriesInPhysicalOrder())) { - if (reserved.contains(entry.getName())) { - LOGGER.warn("Dropping {} from {}, the database snapshot owns that path", entry.getName(), part); - continue; - } - entries.putIfAbsent(entry.getName(), new ZipEntrySource(zip, entry)); - } - } - // Sorted names put every directory before its contents, so unzip applies directory modes and times - try (var out = new ZipArchiveOutputStream(tempZip)) { - for (ZipEntrySource source : entries.values()) { - out.addRawArchiveEntry(source.entry(), source.zip().getRawInputStream(source.entry())); - } - } + result = ZipPartMerger.merge( + parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList(), + parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList(), + tempZip, runDirectory); } catch (IOException | RuntimeException e) { Files.deleteIfExists(tempZip); throw e; - } finally { - for (ZipFile zip : openParts) { - zip.close(); - } } Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - LOGGER.info("Merged {} part(s) into {} entries", parts.size(), entries.size()); + LOGGER.info("Merged {} part(s) into {} entries", parts.size(), result.entries()); + return result.checksum(); } - private record ZipEntrySource(ZipFile zip, ZipArchiveEntry entry) {} - private BackupArchive toArchive(Path path) { String fileName = path.getFileName().toString(); return new BackupArchive( diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 4130464..f9501b9 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -10,8 +10,12 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -146,19 +150,13 @@ BackupRunResult runBackup(boolean scheduled) { LOGGER.info("Backup run started: runDir={}, services={}", runDir, services.stream().map(ServiceDefinition::name).toList()); - List> futures = services.stream() - .map(service -> CompletableFuture - .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) - .exceptionally(t -> { - Throwable cause = unwrap(t); - LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); - return failedResult(service.name(), cause); - })) - .toList(); + DatabaseSnapshotService.Outcome snapshot = snapshotDatabase(runDir); + BackupServiceResult snapshotResult = snapshot.result(); + Set excluded = COMPLETED.equals(snapshotResult.status()) && snapshot.hostPath() != null + ? DatabaseSnapshotService.reservedNames(snapshot.hostPath()) + : Set.of(); - List serviceRunResults = futures.stream() - .map(CompletableFuture::join) - .toList(); + List serviceRunResults = copyServices(services, runDir, excluded); List incomplete = serviceRunResults.stream() .filter(r -> !COMPLETED.equals(r.status())) @@ -180,7 +178,6 @@ BackupRunResult runBackup(boolean scheduled) { throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); } - BackupServiceResult snapshotResult = snapshotDatabase(runDir); List recordedResults = new ArrayList<>(serviceRunResults); recordedResults.add(snapshotResult); boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status()); @@ -247,12 +244,85 @@ private void publishFinished(String status, Instant startedAt) { } } - private BackupServiceResult snapshotDatabase(Path runDir) { + private List copyServices(List services, Path runDir, Set excluded) { + Map tallies = new LinkedHashMap<>(); + List unresolved = new ArrayList<>(); + for (ServiceDefinition service : services) { + tallies.put(service.name(), new ServiceBackupRunner.Tally(service.name())); + for (int i = 0; i < service.paths().size(); i++) { + unresolved.add(new PathCoverage.Item(service, i)); + } + } + + int round = 0; + while (!unresolved.isEmpty()) { + round++; + List owners = PathCoverage.plan(unresolved); + Map> byService = new LinkedHashMap<>(); + owners.forEach(owner -> byService.computeIfAbsent(owner.item().service().name(), name -> new ArrayList<>()).add(owner)); + LOGGER.debug("Copy round {}: {} path(s), {} left", round, owners.size(), unresolved.size()); + + Map> futures = new LinkedHashMap<>(); + byService.forEach((name, serviceOwners) -> { + ServiceDefinition service = serviceOwners.get(0).item().service(); + List indexes = serviceOwners.stream().map(owner -> owner.item().index()).toList(); + List> covered = serviceOwners.stream() + .map(owner -> owner.covered().stream().map(PathCoverage.Item::key).collect(Collectors.toUnmodifiableSet())) + .toList(); + futures.put(name, CompletableFuture + .supplyAsync(() -> runner.copyPaths(service, indexes, runDir, excluded, covered), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", name, cause); + return failedRound(service, indexes, cause); + })); + }); + + Map copies = new HashMap<>(); + futures.forEach((name, future) -> { + ServiceBackupRunner.ServiceRound finished = future.join(); + tallies.get(name).add(finished); + ServiceDefinition service = byService.get(name).get(0).item().service(); + finished.paths().forEach(copy -> copies.put(new PathCoverage.Item(service, copy.index()), copy)); + }); + + List resolved = new ArrayList<>(); + for (PathCoverage.Owner owner : owners) { + resolved.add(owner.item()); + ServiceBackupRunner.PathCopy copy = copies.get(owner.item()); + if (copy == null || !copy.copied()) { + owner.covered().forEach(item -> LOGGER.info("[{}] {} was covered by {} which failed, copying it on its own", + item.service().name(), item.path(), owner.item().path())); + continue; + } + for (PathCoverage.Item item : owner.covered()) { + if (copy.confirmed().contains(item.key())) { + tallies.get(item.service().name()).addCovered(1); + resolved.add(item); + LOGGER.info("[{}] {} is included in {} ({})", item.service().name(), item.path(), owner.item().path(), owner.item().service().name()); + } else { + LOGGER.info("[{}] {} was not found inside {}, copying it on its own", item.service().name(), item.path(), owner.item().path()); + } + } + } + unresolved.removeAll(resolved); + } + return tallies.values().stream().map(ServiceBackupRunner.Tally::result).toList(); + } + + private static ServiceBackupRunner.ServiceRound failedRound(ServiceDefinition service, List indexes, Throwable cause) { + List copies = indexes.stream() + .map(index -> new ServiceBackupRunner.PathCopy(index, service.paths().get(index), false, null, Set.of())) + .toList(); + return new ServiceBackupRunner.ServiceRound(Objects.requireNonNullElse(cause.getMessage(), cause.toString()), copies); + } + + private DatabaseSnapshotService.Outcome snapshotDatabase(Path runDir) { try { - return snapshotService.snapshot(runDir); + return snapshotService.snapshotWithHostPath(runDir); } catch (RuntimeException e) { LOGGER.warn("[{}] Failed to snapshot database", SNAPSHOT_NAME, e); - return failedResult(SNAPSHOT_NAME, e); + return new DatabaseSnapshotService.Outcome(failedResult(SNAPSHOT_NAME, e), null); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java index ac34cfc..d76ca4a 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java @@ -313,7 +313,7 @@ private Integer addMasterBackup(Connection connection, BackupRunResult backupRec statement.setString(3, backupRecord.endTime()); statement.setString(4, backupRecord.status()); BackupArchive archive = backupRecord.archive(); - statement.setString(5, archive == null ? null : archive.generateChecksum()); + statement.setString(5, archive == null ? null : archive.resolvedChecksum()); statement.setString(6, archive == null ? null : archive.path().toString()); statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java index 03a9ecf..506cbbe 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -5,16 +5,18 @@ import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.sql.SQLException; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -28,52 +30,76 @@ public class DatabaseSnapshotService { static final String SERVICE_NAME = "_mediagarrd-server"; static final String PART_DIRECTORY = ".mediagarrd-server"; - static final String PART_NAME = "database.zip"; + static final String PART_NAME = "database" + ZipPartWriter.PART_SUFFIX; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private static final String SNAPSHOT_FILE = "snapshot.db"; private final DatabaseService db; private final DatabaseHostPathResolver hostPaths; + private final ZipCompression compression; - public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths) { + public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { this.db = db; this.hostPaths = hostPaths; + this.compression = compression; } + public record Outcome(BackupServiceResult result, Path hostPath) {} + public BackupServiceResult snapshot(Path runDirectory) { + return snapshotWithHostPath(runDirectory).result(); + } + + public Outcome snapshotWithHostPath(Path runDirectory) { String startTime = recordCurrentTime(); Path directory = runDirectory.resolve(PART_DIRECTORY); Path snapshot = directory.resolve(SNAPSHOT_FILE); Path part = directory.resolve(PART_NAME); + Path hostPath = null; try { if (!Files.isRegularFile(db.databaseFile())) { throw new IOException("Database file " + db.databaseFile() + " does not exist"); } - Path hostPath = hostPaths.resolve(db.databaseFile()); + hostPath = hostPaths.resolve(db.databaseFile()); Files.createDirectories(directory); db.snapshotTo(snapshot); writePart(snapshot, hostPath, part); LOGGER.info("[{}] Snapshotted database {} as {}", SERVICE_NAME, db.databaseFile(), hostPath); - return new BackupServiceResult(null, COMPLETED, startTime, recordCurrentTime(), SERVICE_NAME, null); + return new Outcome(new BackupServiceResult(null, COMPLETED, startTime, recordCurrentTime(), SERVICE_NAME, null), hostPath); } catch (IOException | SQLException | RuntimeException e) { LOGGER.warn("[{}] Failed to snapshot database", SERVICE_NAME, e); - deleteQuietly(part); - return new BackupServiceResult(null, FAILED, startTime, recordCurrentTime(), SERVICE_NAME, - Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName())); + discardQuietly(part); + return new Outcome(new BackupServiceResult(null, FAILED, startTime, recordCurrentTime(), SERVICE_NAME, + Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName())), hostPath); } finally { deleteQuietly(snapshot); } } + static String entryName(Path hostPath) { + return hostPath.getRoot().relativize(hostPath).toString(); + } + + static Set reservedNames(Path hostPath) { + String name = entryName(hostPath); + return DATABASE_SIDECAR_SUFFIXES.stream().map(suffix -> name + suffix).collect(Collectors.toUnmodifiableSet()); + } + private void writePart(Path snapshot, Path hostPath, Path part) throws IOException { Map attributes = Files.readAttributes(db.databaseFile(), "unix:mode,uid,gid,lastModifiedTime"); - ZipArchiveEntry entry = new ZipArchiveEntry(hostPath.getRoot().relativize(hostPath).toString()); - entry.setUnixMode(UnixStat.FILE_FLAG | ((Integer) attributes.get("mode") & 07777)); - entry.setTime(((FileTime) attributes.get("lastModifiedTime")).toMillis()); - entry.addExtraField(ServiceBackupRunner.owner(((Integer) attributes.get("uid")).longValue(), ((Integer) attributes.get("gid")).longValue())); - try (var zip = new ZipArchiveOutputStream(part)) { - zip.putArchiveEntry(entry); - Files.copy(snapshot, zip); - zip.closeArchiveEntry(); + try (var writer = new ZipPartWriter(part, compression); InputStream content = Files.newInputStream(snapshot)) { + writer.addEntry(entryName(hostPath), UnixStat.FILE_FLAG | ((Integer) attributes.get("mode") & 07777), + ((Integer) attributes.get("uid")).longValue(), ((Integer) attributes.get("gid")).longValue(), + ((FileTime) attributes.get("lastModifiedTime")).toMillis(), Files.size(snapshot), content); + writer.complete(); + } + } + + private static void discardQuietly(Path part) { + try { + ZipPartWriter.discard(part); + } catch (IOException e) { + LOGGER.warn("Unable to remove {}", part, e); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java new file mode 100644 index 0000000..71a7d2d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java @@ -0,0 +1,60 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +final class PathCoverage { + + private static final Comparator TIE_BREAK = Comparator.comparing((Item item) -> item.service().name()).thenComparingInt(Item::index); + + record Item(ServiceDefinition service, int index) { + + String path() { + return service.paths().get(index); + } + + Path location() { + return Path.of(path()); + } + + String key() { + Path location = location(); + return location.getRoot() == null ? path() : location.getRoot().relativize(location).toString(); + } + } + + record Owner(Item item, List covered) {} + + private PathCoverage() {} + + static List plan(List unresolved) { + List owners = new ArrayList<>(); + for (Item candidate : unresolved) { + if (unresolved.stream().noneMatch(other -> other != candidate && covers(other, candidate))) { + owners.add(new Owner(candidate, new ArrayList<>())); + } + } + for (Item candidate : unresolved) { + if (owners.stream().noneMatch(owner -> owner.item() == candidate)) { + owners.stream() + .filter(owner -> candidate.location().startsWith(owner.item().location())) + .findFirst() + .ifPresent(owner -> owner.covered().add(candidate)); + } + } + return owners; + } + + private static boolean covers(Item other, Item candidate) { + Path otherLocation = other.location(); + Path candidateLocation = candidate.location(); + if (candidateLocation.equals(otherLocation)) { + return TIE_BREAK.compare(other, candidate) < 0; + } + return candidateLocation.startsWith(otherLocation); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java index cff0ff2..71e4394 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java @@ -13,19 +13,14 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.stream.IntStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.UnixStat; -import org.apache.commons.compress.archivers.zip.X7875_NewUnix; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -38,83 +33,164 @@ public class ServiceBackupRunner { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBackupRunner.class); - static final String PART_SUFFIX = ".zip"; - static final String LINKS_PART_SUFFIX = "-links.zip"; + static final String PART_SUFFIX = ZipPartWriter.PART_SUFFIX; + + public record PathCopy(int index, String path, boolean copied, String error, Set confirmed) {} + + public record ServiceRound(String error, List paths) {} + + record ArchiveResult(int entries, Set confirmed) {} + + public static final class Tally { + + private final String serviceName; + private final String startTime = recordCurrentTime(); + private final List errors = new ArrayList<>(); + private String endTime = startTime; + private int copied; + + public Tally(String serviceName) { + this.serviceName = serviceName; + } + + public void add(ServiceRound round) { + if (round.error() != null && !errors.contains(round.error())) { + errors.add(round.error()); + } + for (PathCopy path : round.paths()) { + if (path.copied()) { + copied++; + } else if (path.error() != null) { + errors.add(path.error()); + } + } + endTime = recordCurrentTime(); + } + + public void addCovered(int paths) { + copied += paths; + endTime = recordCurrentTime(); + } + + public BackupServiceResult result() { + String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; + return new BackupServiceResult(null, status, startTime, endTime, serviceName, + errors.isEmpty() ? null : String.join("; ", errors)); + } + } private final DockerService docker; + private final ZipCompression compression; - public ServiceBackupRunner(DockerService docker) { + public ServiceBackupRunner(DockerService docker, ZipCompression compression) { this.docker = docker; + this.compression = compression; } public BackupServiceResult run(ServiceDefinition service, Path runDirectory) { - String startTime = recordCurrentTime(); - Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); - List errors = new ArrayList<>(); - int copied = 0; + Tally tally = new Tally(service.name()); + tally.add(copyPaths(service, IntStream.range(0, service.paths().size()).boxed().toList(), runDirectory, Set.of(), List.of())); + return tally.result(); + } + public ServiceRound copyPaths(ServiceDefinition service, List indexes, Path runDirectory, Set excluded, List> covered) { + Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); + List copies = new ArrayList<>(); try { Files.createDirectories(serviceDirectory); String containerId = docker.containerFor(service); - for (int i = 0; i < service.paths().size(); i++) { - String hostPath = service.paths().get(i); - Path part = serviceDirectory.resolve(i + PART_SUFFIX); - try (InputStream tar = docker.copyFrom(containerId, hostPath)) { - int entries = archive(tar, hostPath, part); - copied++; - LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, entries); - } catch (IOException | RuntimeException e) { - discard(part); - LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); - errors.add(hostPath + ": " + describe(e)); - } + for (int i = 0; i < indexes.size(); i++) { + copies.add(copyPath(containerId, service, indexes.get(i), serviceDirectory, excluded, covered.isEmpty() ? Set.of() : covered.get(i))); } + return new ServiceRound(null, copies); } catch (IOException | RuntimeException e) { LOGGER.warn("[{}] Unable to prepare helper container", service.name(), e); - errors.add(describe(e)); + for (int i = copies.size(); i < indexes.size(); i++) { + int index = indexes.get(i); + copies.add(new PathCopy(index, service.paths().get(index), false, null, Set.of())); + } + return new ServiceRound(describe(e), copies); } + } - String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; - return new BackupServiceResult(null, status, startTime, recordCurrentTime(), service.name(), - errors.isEmpty() ? null : String.join("; ", errors)); + private PathCopy copyPath(String containerId, ServiceDefinition service, int index, Path serviceDirectory, Set excluded, Set covered) { + String hostPath = service.paths().get(index); + Path part = serviceDirectory.resolve(index + PART_SUFFIX); + try (InputStream tar = docker.copyFrom(containerId, hostPath)) { + ArchiveResult result = archive(tar, hostPath, part, compression, excluded, covered); + LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, result.entries()); + return new PathCopy(index, hostPath, true, null, result.confirmed()); + } catch (IOException | RuntimeException e) { + discard(part); + LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); + return new PathCopy(index, hostPath, false, hostPath + ": " + describe(e), Set.of()); + } + } + + static int archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression) throws IOException { + return archive(tarStream, hostPath, part, compression, Set.of(), Set.of()).entries(); } - static int archive(InputStream tarStream, String hostPath, Path part) throws IOException { + static ArchiveResult archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression, Set excluded, Set covered) + throws IOException { Path source = Path.of(hostPath); Path base = Objects.requireNonNullElse(source.getParent(), source.getRoot()); - Set names = new HashSet<>(); - Map hardLinks = new LinkedHashMap<>(); + Set confirmed = new HashSet<>(); - try (var tar = new TarArchiveInputStream(tarStream); var zip = new ZipArchiveOutputStream(part)) { + try (var tar = new TarArchiveInputStream(tarStream); var writer = new ZipPartWriter(part, compression)) { TarArchiveEntry entry; while ((entry = tar.getNextEntry()) != null) { String name = entryName(base, source, entry.getName(), entry.isDirectory()); - if (!names.add(name)) { + if (excluded.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Skipping {} in {}, the database snapshot owns that path", name, hostPath); continue; } + if (writer.contains(name)) { + continue; + } + long modified = entry.getModTime().getTime(); + boolean content = false; if (entry.isFIFO() || entry.isCharacterDevice() || entry.isBlockDevice()) { - names.remove(name); + writer.markSkipped(name); LOGGER.warn("Skipping special file {} in {}", entry.getName(), hostPath); } else if (entry.isDirectory()) { - write(zip, entry, name, UnixStat.DIR_FLAG, null); + writer.addEntry(name, UnixStat.DIR_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, 0, + InputStream.nullInputStream()); + content = true; + } else if (entry.isSymbolicLink() && covered.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Not storing symlink {} in {}, it is configured as its own path and is copied from its target", name, hostPath); } else if (entry.isSymbolicLink()) { byte[] target = entry.getLinkName().getBytes(StandardCharsets.UTF_8); - write(zip, entry, name, UnixStat.LINK_FLAG, new ByteArrayInputStream(target)); + writer.addEntry(name, UnixStat.LINK_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + target.length, new ByteArrayInputStream(target)); } else if (entry.isLink()) { - hardLinks.put(name, entryName(base, source, entry.getLinkName(), false)); + if (writer.addCopy(name, entryName(base, source, entry.getLinkName(), false))) { + content = true; + } else { + writer.markSkipped(name); + LOGGER.warn("Skipping hard link {} in {}, its target was skipped", entry.getName(), hostPath); + } } else if (entry.isFile()) { - write(zip, entry, name, UnixStat.FILE_FLAG, tar); + writer.addEntry(name, UnixStat.FILE_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + entry.getRealSize(), tar); + content = true; } else { - names.remove(name); + writer.markSkipped(name); LOGGER.warn("Skipping unsupported entry {} in {}", entry.getName(), hostPath); } + if (content) { + String key = name.endsWith("/") ? name.substring(0, name.length() - 1) : name; + if (covered.contains(key)) { + confirmed.add(key); + } + } } + int entries = writer.entryCount(); + writer.complete(); + return new ArchiveResult(entries, confirmed); } - - if (!hardLinks.isEmpty()) { - writeHardLinks(part, hardLinks); - } - return names.size(); } static String entryName(Path base, Path source, String tarName, boolean directory) throws IOException { @@ -126,67 +202,14 @@ static String entryName(Path base, Path source, String tarName, boolean director return directory ? name + "/" : name; } - private static void write(ZipArchiveOutputStream zip, TarArchiveEntry source, String name, int type, InputStream content) - throws IOException { - ZipArchiveEntry entry = new ZipArchiveEntry(name); - entry.setUnixMode(type | (source.getMode() & 07777)); - entry.setTime(source.getModTime().getTime()); - entry.addExtraField(owner(source.getLongUserId(), source.getLongGroupId())); - zip.putArchiveEntry(entry); - if (content != null) { - content.transferTo(zip); - } - zip.closeArchiveEntry(); - } - - private static void writeHardLinks(Path part, Map hardLinks) throws IOException { - Path linksPart = linksPart(part); - try (ZipFile written = ZipFile.builder().setPath(part).get(); var zip = new ZipArchiveOutputStream(linksPart)) { - for (var link : hardLinks.entrySet()) { - ZipArchiveEntry target = written.getEntry(link.getValue()); - if (target == null) { - throw new IOException("Hard link " + link.getKey() + " points to a missing entry " + link.getValue()); - } - zip.addRawArchiveEntry(renamed(target, link.getKey()), written.getRawInputStream(target)); - } - } catch (IOException e) { - Files.deleteIfExists(linksPart); - throw e; - } - } - - private static ZipArchiveEntry renamed(ZipArchiveEntry target, String name) { - ZipArchiveEntry entry = new ZipArchiveEntry(name); - entry.setMethod(target.getMethod()); - entry.setCrc(target.getCrc()); - entry.setSize(target.getSize()); - entry.setCompressedSize(target.getCompressedSize()); - entry.setUnixMode(target.getUnixMode()); - entry.setTime(target.getTime()); - entry.setExtraFields(target.getExtraFields()); - return entry; - } - - static X7875_NewUnix owner(long uid, long gid) { - X7875_NewUnix owner = new X7875_NewUnix(); - owner.setUID(uid); - owner.setGID(gid); - return owner; - } - private static void discard(Path part) { try { - Files.deleteIfExists(part); - Files.deleteIfExists(linksPart(part)); + ZipPartWriter.discard(part); } catch (IOException e) { LOGGER.warn("Unable to remove incomplete archive part {}", part, e); } } - private static Path linksPart(Path part) { - return part.resolveSibling(part.getFileName().toString().replace(PART_SUFFIX, LINKS_PART_SUFFIX)); - } - private static String describe(Throwable e) { return Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java new file mode 100644 index 0000000..f8b7d9f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java @@ -0,0 +1,48 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.Locale; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Component +public class ZipCompression { + + static final int MIN_LEVEL = 0; + static final int MAX_LEVEL = 9; + private static final Set ALREADY_COMPRESSED = Set.of( + "zip", "gz", "tgz", "bz2", "xz", "zst", "7z", "rar", + "jpg", "jpeg", "png", "gif", "webp", + "mp4", "mkv", "mp3", "flac", "ogg", + "mov", "avi", "webm", "m4v", "m4a", "aac", "opus", "heic", "avif", + "lz4", "zstd", "jar", "docx", "xlsx", "pptx"); + + private final int level; + + @Autowired + public ZipCompression(MediaGarrdProperties properties) { + this(properties.getCompressionLevel()); + } + + public ZipCompression(int level) { + if (level < MIN_LEVEL || level > MAX_LEVEL) { + throw new IllegalStateException("mediagarrd.compression-level must be between " + MIN_LEVEL + " and " + MAX_LEVEL + ", was " + level); + } + this.level = level; + } + + public int level() { + return level; + } + + boolean stores(String name) { + if (level == 0) { + return true; + } + int dot = name.lastIndexOf('.'); + return dot >= 0 && dot > name.lastIndexOf('/') && ALREADY_COMPRESSED.contains(name.substring(dot + 1).toLowerCase(Locale.ROOT)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java new file mode 100644 index 0000000..30cfc6b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java @@ -0,0 +1,232 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; + +final class ZipFormat { + + static final int STORED = 0; + static final int DEFLATED = 8; + static final long ZIP64_LIMIT = 0xFFFFFFFFL; + static final long UINT32_MAX = 0xFFFFFFFFL; + static final long ZIP64_LOCAL_THRESHOLD = 0xF0000000L; + static final int LOCAL_HEADER_SIZE = 30; + static final int CRC_OFFSET = 14; + static final int ZIP64_FIELD_BYTES = 16; + static final int MAX_NAME_BYTES = 0xFFFF; + + private static final int LOCAL_SIGNATURE = 0x04034b50; + private static final int CENTRAL_SIGNATURE = 0x02014b50; + private static final int END_SIGNATURE = 0x06054b50; + private static final int ZIP64_END_SIGNATURE = 0x06064b50; + private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50; + private static final int UTF8_FLAG = 0x0800; + private static final int VERSION_DEFAULT = 20; + private static final int VERSION_ZIP64 = 45; + private static final int MADE_BY_UNIX = 0x0314; + private static final int MADE_BY_UNIX_ZIP64 = 0x032D; + private static final int ZIP64_ID = 0x0001; + private static final int TIMESTAMP_ID = 0x5455; + private static final int OWNER_ID = 0x7875; + private static final int DOS_BEFORE_1980 = 1 << 21 | 1 << 16; + private static final int DOS_MAX_YEAR = 2107; + + private ZipFormat() {} + + record Entry(String name, long localOffset, long dataOffset, int method, long crc, long compressedSize, long size, + int mode, long uid, long gid, long modified, boolean localZip64) {} + + static byte[] nameBytes(String name) throws IOException { + byte[] bytes = name.getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_NAME_BYTES) { + throw new IOException("Entry name is too long for a zip archive: " + name.substring(0, 64) + "..."); + } + return bytes; + } + + static byte[] localHeader(byte[] name, int method, long modified, long uid, long gid, boolean zip64, long crc, long compressedSize, long size) { + byte[] extra = localExtra(modified, uid, gid, zip64, compressedSize, size); + byte[] header = new byte[LOCAL_HEADER_SIZE + name.length + extra.length]; + put32(header, 0, LOCAL_SIGNATURE); + put16(header, 4, zip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 6, UTF8_FLAG); + put16(header, 8, method); + put32(header, 10, dosTime(modified)); + System.arraycopy(localSizes(zip64, crc, compressedSize, size), 0, header, CRC_OFFSET, 12); + put16(header, 26, name.length); + put16(header, 28, extra.length); + System.arraycopy(name, 0, header, LOCAL_HEADER_SIZE, name.length); + System.arraycopy(extra, 0, header, LOCAL_HEADER_SIZE + name.length, extra.length); + return header; + } + + static byte[] localSizes(boolean zip64, long crc, long compressedSize, long size) { + byte[] sizes = new byte[12]; + put32(sizes, 0, crc); + put32(sizes, 4, zip64 ? ZIP64_LIMIT : compressedSize); + put32(sizes, 8, zip64 ? ZIP64_LIMIT : size); + return sizes; + } + + static byte[] zip64LocalExtra(long compressedSize, long size) { + byte[] extra = new byte[4 + ZIP64_FIELD_BYTES]; + put16(extra, 0, ZIP64_ID); + put16(extra, 2, ZIP64_FIELD_BYTES); + put64(extra, 4, size); + put64(extra, 12, compressedSize); + return extra; + } + + private static byte[] localExtra(long modified, long uid, long gid, boolean zip64, long compressedSize, long size) { + byte[] ownerData = ownerData(uid, gid); + boolean timestamp = fitsUnixTime(modified); + byte[] extra = new byte[(zip64 ? 4 + ZIP64_FIELD_BYTES : 0) + (timestamp ? 9 : 0) + 4 + ownerData.length]; + int pos = 0; + if (zip64) { + byte[] field = zip64LocalExtra(compressedSize, size); + System.arraycopy(field, 0, extra, pos, field.length); + pos += field.length; + } + if (timestamp) { + pos = putTimestamp(extra, pos, modified); + } + put16(extra, pos, OWNER_ID); + put16(extra, pos + 2, ownerData.length); + System.arraycopy(ownerData, 0, extra, pos + 4, ownerData.length); + return extra; + } + + static byte[] ownerData(long uid, long gid) { + byte[] data = new byte[11]; + data[0] = 1; + data[1] = 4; + put32(data, 2, Math.max(0, Math.min(uid, UINT32_MAX))); + data[6] = 4; + put32(data, 7, Math.max(0, Math.min(gid, UINT32_MAX))); + return data; + } + + static byte[] centralHeader(Entry entry, long offset) throws IOException { + byte[] name = nameBytes(entry.name()); + boolean overflowSize = entry.size() >= ZIP64_LIMIT; + boolean overflowCompressed = entry.compressedSize() >= ZIP64_LIMIT; + boolean overflowOffset = offset >= ZIP64_LIMIT; + int zip64Fields = (overflowSize ? 1 : 0) + (overflowCompressed ? 1 : 0) + (overflowOffset ? 1 : 0); + boolean zip64 = zip64Fields > 0; + boolean timestamp = fitsUnixTime(entry.modified()); + int extraLength = (zip64 ? 4 + 8 * zip64Fields : 0) + (timestamp ? 9 : 0) + 4; + byte[] header = new byte[46 + name.length + extraLength]; + boolean needsZip64 = zip64 || entry.localZip64(); + put32(header, 0, CENTRAL_SIGNATURE); + put16(header, 4, needsZip64 ? MADE_BY_UNIX_ZIP64 : MADE_BY_UNIX); + put16(header, 6, needsZip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 8, UTF8_FLAG); + put16(header, 10, entry.method()); + put32(header, 12, dosTime(entry.modified())); + put32(header, 16, entry.crc()); + put32(header, 20, overflowCompressed ? ZIP64_LIMIT : entry.compressedSize()); + put32(header, 24, overflowSize ? ZIP64_LIMIT : entry.size()); + put16(header, 28, name.length); + put16(header, 30, extraLength); + put32(header, 38, externalAttributes(entry.mode(), entry.name().endsWith("/"))); + put32(header, 42, overflowOffset ? ZIP64_LIMIT : offset); + System.arraycopy(name, 0, header, 46, name.length); + int pos = 46 + name.length; + if (zip64) { + put16(header, pos, ZIP64_ID); + put16(header, pos + 2, 8 * zip64Fields); + pos += 4; + if (overflowSize) { + put64(header, pos, entry.size()); + pos += 8; + } + if (overflowCompressed) { + put64(header, pos, entry.compressedSize()); + pos += 8; + } + if (overflowOffset) { + put64(header, pos, offset); + pos += 8; + } + } + if (timestamp) { + pos = putTimestamp(header, pos, entry.modified()); + } + put16(header, pos, OWNER_ID); + put16(header, pos + 2, 0); + return header; + } + + static byte[] endOfArchive(long entries, long centralSize, long centralOffset) { + boolean zip64 = entries >= 0xFFFF || centralSize >= ZIP64_LIMIT || centralOffset >= ZIP64_LIMIT; + byte[] tail = new byte[(zip64 ? 56 + 20 : 0) + 22]; + int pos = 0; + if (zip64) { + put32(tail, 0, ZIP64_END_SIGNATURE); + put64(tail, 4, 44); + put16(tail, 12, MADE_BY_UNIX_ZIP64); + put16(tail, 14, VERSION_ZIP64); + put64(tail, 24, entries); + put64(tail, 32, entries); + put64(tail, 40, centralSize); + put64(tail, 48, centralOffset); + put32(tail, 56, ZIP64_LOCATOR_SIGNATURE); + put64(tail, 64, centralOffset + centralSize); + put32(tail, 72, 1); + pos = 76; + } + put32(tail, pos, END_SIGNATURE); + put16(tail, pos + 8, Math.min(entries, 0xFFFF)); + put16(tail, pos + 10, Math.min(entries, 0xFFFF)); + put32(tail, pos + 12, Math.min(centralSize, ZIP64_LIMIT)); + put32(tail, pos + 16, Math.min(centralOffset, ZIP64_LIMIT)); + return tail; + } + + static long externalAttributes(int mode, boolean directory) { + return ((long) mode << 16) | ((mode & 0200) == 0 ? 1 : 0) | (directory ? 0x10 : 0); + } + + static boolean fitsUnixTime(long millis) { + long seconds = Math.floorDiv(millis, 1000L); + return seconds >= 0 && seconds <= Integer.MAX_VALUE; + } + + static long dosTime(long millis) { + LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); + if (time.getYear() < 1980) { + return DOS_BEFORE_1980; + } + if (time.getYear() > DOS_MAX_YEAR) { + time = LocalDateTime.of(DOS_MAX_YEAR, 12, 31, 23, 59, 58); + } + return ((long) (time.getYear() - 1980) << 25 | (long) time.getMonthValue() << 21 | (long) time.getDayOfMonth() << 16 + | (long) time.getHour() << 11 | (long) time.getMinute() << 5 | time.getSecond() >> 1) & 0xFFFFFFFFL; + } + + private static int putTimestamp(byte[] target, int pos, long modified) { + put16(target, pos, TIMESTAMP_ID); + put16(target, pos + 2, 5); + target[pos + 4] = 1; + put32(target, pos + 5, Math.floorDiv(modified, 1000L)); + return pos + 9; + } + + static void put16(byte[] target, int pos, long value) { + target[pos] = (byte) value; + target[pos + 1] = (byte) (value >> 8); + } + + static void put32(byte[] target, int pos, long value) { + put16(target, pos, value); + put16(target, pos + 2, value >> 16); + } + + static void put64(byte[] target, int pos, long value) { + put32(target, pos, value); + put32(target, pos + 4, value >> 32); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java new file mode 100644 index 0000000..6503070 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java @@ -0,0 +1,27 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +final class ZipPartIndex { + + private static final int CACHE_KIB = 2048; + + private ZipPartIndex() {} + + static Connection open(Path file) throws SQLException { + Connection connection = DriverManager.getConnection("jdbc:sqlite:" + file.toAbsolutePath()); + try (Statement statement = connection.createStatement()) { + statement.execute("PRAGMA journal_mode=OFF"); + statement.execute("PRAGMA synchronous=OFF"); + statement.execute("PRAGMA cache_size=-" + CACHE_KIB); + } catch (SQLException e) { + connection.close(); + throw e; + } + return connection; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java new file mode 100644 index 0000000..76ee8f0 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java @@ -0,0 +1,221 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; + +final class ZipPartMerger { + + private static final Logger LOGGER = LoggerFactory.getLogger(ZipPartMerger.class); + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + record Result(String checksum, long entries, long bytes) {} + + private ZipPartMerger() {} + + static Result merge(List snapshotParts, List parts, Path output, Path scratchDirectory) throws IOException { + Path names = scratchDirectory.resolve("merge-names" + ZipPartWriter.INDEX_SUFFIX); + MessageDigest digest = sha256(); + try (OutputStream file = Files.newOutputStream(output); Sink sink = new Sink(file, digest); NameIndex seen = new NameIndex(names)) { + List ordered = new ArrayList<>(snapshotParts); + ordered.addAll(parts); + long[] bases = new long[ordered.size()]; + for (int i = 0; i < ordered.size(); i++) { + bases[i] = sink.written(); + copyData(ordered.get(i), sink); + } + + Set reserved = new HashSet<>(); + long centralStart = sink.written(); + long entries = 0; + for (int i = 0; i < ordered.size(); i++) { + boolean snapshot = i < snapshotParts.size(); + entries += writeCentral(ordered.get(i), bases[i], snapshot, reserved, seen, sink); + } + long centralSize = sink.written() - centralStart; + sink.write(ZipFormat.endOfArchive(entries, centralSize, centralStart)); + sink.flush(); + LOGGER.debug("Merged {} part(s) into {} entries", ordered.size(), entries); + return new Result(HexFormat.of().formatHex(digest.digest()), entries, sink.written()); + } finally { + Files.deleteIfExists(names); + } + } + + private static void copyData(Path part, Sink sink) throws IOException { + byte[] chunk = new byte[BUFFER_SIZE]; + try (InputStream in = Files.newInputStream(part)) { + int read; + while ((read = in.read(chunk)) != -1) { + sink.write(chunk, 0, read); + } + } + } + + private static long writeCentral(Path part, long base, boolean snapshot, Set reserved, NameIndex seen, Sink sink) throws IOException { + Path index = ZipPartWriter.indexOf(part); + if (!Files.isRegularFile(index)) { + throw new IOException("Archive part " + part + " has no index"); + } + long count = 0; + try (Connection connection = ZipPartIndex.open(index); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT name,lfh_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64 FROM entries ORDER BY id")) { + while (rows.next()) { + String name = rows.getString(1); + if (snapshot) { + if (!name.endsWith("/")) { + DATABASE_SIDECAR_SUFFIXES.forEach(suffix -> reserved.add(name + suffix)); + } + } else if (reserved.contains(name)) { + throw new IOException("Archive part " + part + " contains " + name + ", which the database snapshot owns"); + } + seen.add(name, part); + Entry entry = new Entry(name, rows.getLong(2), 0, rows.getInt(3), rows.getLong(4), rows.getLong(5), rows.getLong(6), + rows.getInt(7), rows.getLong(8), rows.getLong(9), rows.getLong(10), rows.getInt(11) != 0); + sink.write(ZipFormat.centralHeader(entry, base + entry.localOffset())); + count++; + } + } catch (SQLException e) { + throw new IOException("Unable to read the index of archive part " + part, e); + } + return count; + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + private static final class NameIndex implements AutoCloseable { + + private final Connection connection; + private final PreparedStatement insert; + private int pending; + + NameIndex(Path file) throws IOException { + Connection opened = null; + try { + Files.deleteIfExists(file); + opened = ZipPartIndex.open(file); + try (Statement statement = opened.createStatement()) { + statement.execute("CREATE TABLE names(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + opened.setAutoCommit(false); + insert = opened.prepareStatement("INSERT INTO names(name) VALUES(?)"); + connection = opened; + } catch (SQLException | IOException e) { + if (opened != null) { + try { + opened.close(); + } catch (SQLException ignored) { + LOGGER.debug("Unable to close the name index", ignored); + } + } + throw e instanceof IOException io ? io : new IOException("Unable to create the merge name index", e); + } + } + + void add(String name, Path part) throws IOException { + try { + insert.setString(1, name); + insert.executeUpdate(); + if (++pending >= COMMIT_INTERVAL) { + connection.commit(); + pending = 0; + } + } catch (SQLException e) { + throw new IOException("Duplicate or unrecordable entry " + name + " in archive part " + part, e); + } + } + + @Override + public void close() throws IOException { + try { + insert.close(); + connection.close(); + } catch (SQLException e) { + throw new IOException("Unable to close the merge name index", e); + } + } + } + + private static final class Sink extends OutputStream { + + private final OutputStream out; + private final MessageDigest digest; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private int buffered; + private long written; + + Sink(OutputStream out, MessageDigest digest) { + this.out = out; + this.digest = digest; + } + + long written() { + return written; + } + + @Override + public void write(int b) throws IOException { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + digest.update(data, offset, length); + out.write(data, offset, length); + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + written += length; + } + + @Override + public void flush() throws IOException { + if (buffered > 0) { + digest.update(buffer, 0, buffered); + out.write(buffer, 0, buffered); + buffered = 0; + } + } + + @Override + public void close() throws IOException { + flush(); + out.flush(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java new file mode 100644 index 0000000..317aa19 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java @@ -0,0 +1,364 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.zip.CRC32; +import java.util.zip.Deflater; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; + +final class ZipPartWriter implements Closeable { + + static final String PART_SUFFIX = ".part"; + static final String INDEX_SUFFIX = ".idx"; + static final String PARTIAL_SUFFIX = ".partial"; + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final String COLUMNS = "name,lfh_offset,data_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64"; + + private final Path part; + private final Path partial; + private final Path index; + private final ZipCompression compression; + private final FileChannel channel; + private final Connection connection; + private final PreparedStatement insert; + private final PreparedStatement exists; + private final PreparedStatement lookup; + private final PreparedStatement skip; + private final PreparedStatement skipped; + private final Deflater deflater; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private final byte[] chunk = new byte[BUFFER_SIZE]; + private final byte[] compressed = new byte[BUFFER_SIZE]; + private int buffered; + private long position; + private int entries; + private int pendingRows; + private boolean completed; + private boolean closed; + + ZipPartWriter(Path part, ZipCompression compression) throws IOException { + this.part = part; + this.partial = partialOf(part); + this.index = indexOf(part); + this.compression = compression; + this.deflater = new Deflater(Math.max(compression.level(), 1), true); + FileChannel opened = null; + Connection connected = null; + try { + Files.deleteIfExists(index); + opened = FileChannel.open(partial, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.READ, StandardOpenOption.WRITE); + connected = ZipPartIndex.open(index); + try (Statement statement = connected.createStatement()) { + statement.execute("CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, lfh_offset INTEGER NOT NULL, data_offset INTEGER NOT NULL, " + + "method INTEGER NOT NULL, crc INTEGER NOT NULL, csize INTEGER NOT NULL, usize INTEGER NOT NULL, mode INTEGER NOT NULL, " + + "uid INTEGER NOT NULL, gid INTEGER NOT NULL, mtime INTEGER NOT NULL, zip64 INTEGER NOT NULL)"); + statement.execute("CREATE TABLE skipped(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + connected.setAutoCommit(false); + this.insert = connected.prepareStatement("INSERT INTO entries(" + COLUMNS + ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); + this.exists = connected.prepareStatement("SELECT 1 FROM entries WHERE name=?"); + this.lookup = connected.prepareStatement("SELECT " + COLUMNS + " FROM entries WHERE name=?"); + this.skip = connected.prepareStatement("INSERT OR IGNORE INTO skipped(name) VALUES(?)"); + this.skipped = connected.prepareStatement("SELECT 1 FROM skipped WHERE name=?"); + this.channel = opened; + this.connection = connected; + } catch (SQLException | IOException | RuntimeException e) { + deflater.end(); + closeQuietly(connected); + closeQuietly(opened); + deleteQuietly(partial); + deleteQuietly(index); + throw e instanceof IOException io ? io : new IOException("Unable to create archive part " + part, e); + } + } + + static Path partialOf(Path part) { + return part.resolveSibling(part.getFileName() + PARTIAL_SUFFIX); + } + + static Path indexOf(Path part) { + return part.resolveSibling(part.getFileName() + INDEX_SUFFIX); + } + + static void discard(Path part) throws IOException { + Files.deleteIfExists(part); + Files.deleteIfExists(partialOf(part)); + Files.deleteIfExists(indexOf(part)); + } + + int entryCount() { + return entries; + } + + boolean contains(String name) throws IOException { + try { + exists.setString(1, name); + try (ResultSet rows = exists.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void markSkipped(String name) throws IOException { + try { + skip.setString(1, name); + skip.executeUpdate(); + } catch (SQLException e) { + throw new IOException("Unable to update the archive part index", e); + } + } + + boolean wasSkipped(String name) throws IOException { + try { + skipped.setString(1, name); + try (ResultSet rows = skipped.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void addEntry(String name, int mode, long uid, long gid, long modified, long size, InputStream content) throws IOException { + int method = compression.stores(name) ? ZipFormat.STORED : ZipFormat.DEFLATED; + boolean zip64 = size >= ZipFormat.ZIP64_LOCAL_THRESHOLD; + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, method, modified, uid, gid, zip64, 0, 0, 0); + write(header, 0, header.length); + long dataOffset = localOffset + header.length; + + CRC32 crc = new CRC32(); + long total = 0; + long compressedSize = 0; + if (method == ZipFormat.STORED) { + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + write(chunk, 0, read); + total += read; + } + compressedSize = total; + } else { + deflater.reset(); + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + total += read; + deflater.setInput(chunk, 0, read); + compressedSize += drain(false); + } + deflater.finish(); + compressedSize += drain(true); + } + if (total != size) { + throw new EOFException("Entry " + name + " has " + total + " bytes but its header says " + size); + } + if (!zip64 && (compressedSize >= ZipFormat.ZIP64_LIMIT || total >= ZipFormat.ZIP64_LIMIT)) { + throw new IOException("Entry " + name + " outgrew its header, size " + total + ", compressed " + compressedSize); + } + patchSizes(localOffset, nameBytes.length, zip64, crc.getValue(), compressedSize, total); + record(new Entry(name, localOffset, dataOffset, method, crc.getValue(), compressedSize, total, mode, uid, gid, modified, zip64)); + } + + boolean addCopy(String name, String targetName) throws IOException { + Entry target = find(targetName); + if (target == null) { + if (wasSkipped(targetName)) { + return false; + } + throw new IOException("Hard link " + name + " points to a missing entry " + targetName); + } + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, target.method(), target.modified(), target.uid(), target.gid(), target.localZip64(), + target.crc(), target.compressedSize(), target.size()); + flush(); + write(header, 0, header.length); + long remaining = target.compressedSize(); + long from = target.dataOffset(); + while (remaining > 0) { + int length = (int) Math.min(chunk.length, remaining); + ByteBuffer slice = ByteBuffer.wrap(chunk, 0, length); + while (slice.hasRemaining()) { + int read = channel.read(slice, from + slice.position()); + if (read < 0) { + throw new EOFException("Archive part ended while copying " + targetName); + } + } + write(chunk, 0, length); + from += length; + remaining -= length; + } + record(new Entry(name, localOffset, localOffset + header.length, target.method(), target.crc(), target.compressedSize(), target.size(), + target.mode(), target.uid(), target.gid(), target.modified(), target.localZip64())); + return true; + } + + void complete() throws IOException { + flush(); + try { + connection.commit(); + } catch (SQLException e) { + throw new IOException("Unable to save the archive part index", e); + } + release(); + Files.move(partial, part, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + completed = true; + } + + @Override + public void close() { + release(); + if (!completed) { + deleteQuietly(partial); + deleteQuietly(index); + } + } + + private Entry find(String name) throws IOException { + try { + lookup.setString(1, name); + try (ResultSet rows = lookup.executeQuery()) { + if (!rows.next()) { + return null; + } + return new Entry(rows.getString(1), rows.getLong(2), rows.getLong(3), rows.getInt(4), rows.getLong(5), rows.getLong(6), rows.getLong(7), + rows.getInt(8), rows.getLong(9), rows.getLong(10), rows.getLong(11), rows.getInt(12) != 0); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + private void record(Entry entry) throws IOException { + try { + insert.setString(1, entry.name()); + insert.setLong(2, entry.localOffset()); + insert.setLong(3, entry.dataOffset()); + insert.setInt(4, entry.method()); + insert.setLong(5, entry.crc()); + insert.setLong(6, entry.compressedSize()); + insert.setLong(7, entry.size()); + insert.setInt(8, entry.mode()); + insert.setLong(9, entry.uid()); + insert.setLong(10, entry.gid()); + insert.setLong(11, entry.modified()); + insert.setInt(12, entry.localZip64() ? 1 : 0); + insert.executeUpdate(); + entries++; + if (++pendingRows >= COMMIT_INTERVAL) { + connection.commit(); + pendingRows = 0; + } + } catch (SQLException e) { + throw new IOException("Unable to record " + entry.name() + " in the archive part index", e); + } + } + + private long drain(boolean finish) throws IOException { + long produced = 0; + while (finish ? !deflater.finished() : !deflater.needsInput()) { + int length = deflater.deflate(compressed); + if (length > 0) { + write(compressed, 0, length); + produced += length; + } + } + return produced; + } + + private void patchSizes(long localOffset, int nameLength, boolean zip64, long crc, long compressedSize, long size) throws IOException { + flush(); + writeAt(localOffset + ZipFormat.CRC_OFFSET, ZipFormat.localSizes(zip64, crc, compressedSize, size)); + if (zip64) { + writeAt(localOffset + ZipFormat.LOCAL_HEADER_SIZE + nameLength, ZipFormat.zip64LocalExtra(compressedSize, size)); + } + } + + private void writeAt(long at, byte[] data) throws IOException { + ByteBuffer source = ByteBuffer.wrap(data); + long written = at; + while (source.hasRemaining()) { + written += channel.write(source, written); + } + } + + private void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + ByteBuffer source = ByteBuffer.wrap(data, offset, length); + while (source.hasRemaining()) { + channel.write(source); + } + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + position += length; + } + + private void flush() throws IOException { + if (buffered > 0) { + ByteBuffer source = ByteBuffer.wrap(buffer, 0, buffered); + while (source.hasRemaining()) { + channel.write(source); + } + buffered = 0; + } + } + + private void release() { + if (closed) { + return; + } + closed = true; + deflater.end(); + closeQuietly(skipped); + closeQuietly(skip); + closeQuietly(lookup); + closeQuietly(exists); + closeQuietly(insert); + closeQuietly(connection); + closeQuietly(channel); + } + + private static void closeQuietly(AutoCloseable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (Exception e) { + return; + } + } + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + return; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 2ce92ec..00b03a2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -12,6 +12,7 @@ mediagarrd: backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} + compression-level: ${MEDIAGARRD_COMPRESSION_LEVEL:1} helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index 8f0185b..40a1715 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -27,6 +27,7 @@ void bindsApplicationProperties() { assertEquals(10, properties.getRetentionCount()); assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); + assertEquals(1, properties.getCompressionLevel()); assertEquals("alpine:3", properties.getHelperImage()); assertEquals("MediaGarrd/Server", properties.getUpdateRepository()); assertEquals("http://127.0.0.1:1", properties.getGithubApiBaseUrl()); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java new file mode 100644 index 0000000..c4fac32 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java @@ -0,0 +1,102 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Date; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(120) +class ArchiveInteropTest { + + private static final long MTIME = 1_700_000_001_000L; + + @TempDir + Path dir; + + private Path archive() throws Exception { + Item folder = dir("data/"); + folder.entry().setMode(040750); + folder.entry().setModTime(new Date(MTIME)); + folder.entry().setUserId(1000); + folder.entry().setGroupId(1001); + Item secret = file("data/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setModTime(new Date(MTIME)); + secret.entry().setUserId(1000); + secret.entry().setGroupId(1001); + Item text = file("data/café ünï.txt", "compressible ".repeat(1000)); + text.entry().setModTime(new Date(MTIME + 2000)); + text.entry().setUserId(5); + text.entry().setGroupId(6); + Item empty = dir("data/empty/"); + empty.entry().setModTime(new Date(MTIME)); + Item symlink = link("data/latest", TarConstants.LF_SYMLINK, "id_rsa"); + symlink.entry().setModTime(new Date(MTIME)); + Item hardLink = link("data/id_rsa.bak", TarConstants.LF_LINK, "data/id_rsa"); + Path part = dir.resolve("0.part"); + ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink), "/srv/data", part, new ZipCompression(1)); + return ArchiveTestSupport.merge(dir, part); + } + + @Test + void bsdtarRestoresContentsModesTimesAndSymlinksFromSeekableAndStreamedArchives() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + for (boolean streamed : new boolean[] {false, true}) { + Path target = Files.createDirectories(dir.resolve(streamed ? "streamed" : "seekable")); + if (streamed) { + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", target.toString()); + } else { + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + } + + Path data = target.resolve("srv/data"); + assertEquals("key", Files.readString(data.resolve("id_rsa"))); + assertEquals("key", Files.readString(data.resolve("id_rsa.bak"))); + assertEquals("compressible ".repeat(1000), Files.readString(data.resolve("café ünï.txt"), StandardCharsets.UTF_8)); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(data.resolve("id_rsa")))); + assertEquals("rwxr-x---", PosixFilePermissions.toString(Files.getPosixFilePermissions(data))); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data.resolve("id_rsa")).toMillis() / 1000); + assertEquals((MTIME + 2000) / 1000, Files.getLastModifiedTime(data.resolve("café ünï.txt")).toMillis() / 1000); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data).toMillis() / 1000); + assertTrue(Files.isSymbolicLink(data.resolve("latest"))); + assertEquals("id_rsa", Files.readSymbolicLink(data.resolve("latest")).toString()); + assertTrue(Files.isDirectory(data.resolve("empty"))); + } + } + + @Test + void listingsShowNumericOwnersFromTheLocalHeaders() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + + for (String listing : new String[] { + ArchiveTestSupport.run(null, "bsdtar", "-tvf", archive.toString(), "--numeric-owner"), + ArchiveTestSupport.run(archive, "bsdtar", "-tvf", "-", "--numeric-owner")}) { + assertTrue(listing.matches("(?s).*-rw-------\\s+\\d+\\s+1000\\s+1001\\s+3\\s.*id_rsa\\n.*"), listing); + assertTrue(listing.matches("(?s).*\\s5\\s+6\\s.*caf.*"), listing); + assertTrue(listing.matches("(?s).*drwxr-x---\\s+\\d+\\s+1000\\s+1001.*srv/data/\\n.*"), listing); + } + } + + @Test + void everyReaderAcceptsTheArchive() throws Exception { + ZipPartWriterTest.verifyWithTools(archive(), 6); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java new file mode 100644 index 0000000..09b32d9 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java @@ -0,0 +1,144 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.GeneratedTar.Spec; + +@Tag("scale") +@Timeout(value = 60, unit = java.util.concurrent.TimeUnit.MINUTES) +class ArchiveScaleTest { + + private static final long FOUR_GIB = 0x100000000L; + private static final byte[] SMALL = "small file content\n".getBytes(java.nio.charset.StandardCharsets.UTF_8); + + @TempDir + Path dir; + + private Thread sampler; + private volatile boolean sampling; + private volatile long peakHeap; + private long started; + + @BeforeEach + void startSampling() { + assumeTrue(Runtime.getRuntime().maxMemory() <= 128L * 1024 * 1024, "run through scaleTest, which caps the heap"); + started = System.nanoTime(); + sampling = true; + sampler = new Thread(() -> { + while (sampling) { + Runtime runtime = Runtime.getRuntime(); + peakHeap = Math.max(peakHeap, runtime.totalMemory() - runtime.freeMemory()); + try { + Thread.sleep(20); + } catch (InterruptedException e) { + return; + } + } + }, "heap-sampler"); + sampler.setDaemon(true); + sampler.start(); + } + + @AfterEach + void report(org.junit.jupiter.api.TestInfo info) throws Exception { + sampling = false; + sampler.join(); + System.out.printf("SCALE %s: %d s, max heap %d MiB, peak sampled used heap %d MiB, tmpdir %s%n", info.getDisplayName(), + (System.nanoTime() - started) / 1_000_000_000L, Runtime.getRuntime().maxMemory() >> 20, peakHeap >> 20, System.getProperty("java.io.tmpdir")); + } + + private static byte[] randomBlock() { + byte[] block = new byte[64 * 1024]; + new Random(42).nextBytes(block); + return block; + } + + private Path archive(Iterator specs, String hostPath, int level) throws Exception { + Path part = dir.resolve("0.part"); + try (var tar = new GeneratedTar(specs)) { + ServiceBackupRunner.archive(tar, hostPath, part, new ZipCompression(level)); + } + System.out.printf("SCALE part %d MiB%n", Files.size(part) >> 20); + Path merged = dir.resolve("merged.zip"); + ZipPartMerger.Result result = ZipPartMerger.merge(List.of(), List.of(part), merged, dir); + Files.delete(part); + Files.delete(ZipPartWriter.indexOf(part)); + System.out.printf("SCALE archive %d MiB, %d entries, sha256 %s%n", Files.size(merged) >> 20, result.entries(), result.checksum()); + return merged; + } + + @Test + void threeHundredThousandSmallFilesBuildAnArchiveReadableByEveryTool() throws Exception { + int count = 300_000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.directory("many/")), + IntStream.range(0, count).mapToObj(i -> Spec.file("many/dir" + (i % 100) + "/file-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/many", 1); + + ZipPartWriterTest.verifyWithTools(merged, count + 1); + } + + @Test + void aStoredEntryJustUnderFourGiBUsesALocalZip64ExtraWithClassicCentralSizes() throws Exception { + long size = 0xF0000000L + 0x100000L; + + Path merged = archive(List.of(Spec.file("movies/film.mkv", size, randomBlock())).iterator(), "/srv/movies", 1); + + assertTrue(size < 0xFFFFFFFFL); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + @Test + void aStoredEntryOverFourGiBFollowedBySmallEntriesPushesOffsetsPastFourGiB() throws Exception { + long size = FOUR_GIB + 300_000_000L; + int small = 1000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.file("movies/big.mkv", size, randomBlock())), + IntStream.range(0, small).mapToObj(i -> Spec.file("movies/small-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/movies", 1); + + assertTrue(Files.size(merged) > FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, small + 1); + extractOne(merged, "srv/movies/small-999.txt", new String(SMALL, java.nio.charset.StandardCharsets.UTF_8)); + } + + @Test + void aDeflatedEntryOverFourGiBOfRepeatedBytesOverflowsOnlyTheUncompressedSize() throws Exception { + long size = FOUR_GIB + 200_000_000L; + + Path merged = archive(List.of(Spec.file("logs/huge.log", size, new byte[64 * 1024])).iterator(), "/srv/logs", 1); + + assertTrue(Files.size(merged) < FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + private void extractOne(Path archive, String name, String expected) throws IOException, InterruptedException { + if (ArchiveTestSupport.available("bsdtar")) { + assertEquals(expected, ArchiveTestSupport.run(null, "bsdtar", "-xOf", archive.toString(), name)); + assertEquals(expected, ArchiveTestSupport.run(archive, "bsdtar", "-xOf", "-", name)); + } + if (ArchiveTestSupport.available("unzip")) { + assertEquals(expected, ArchiveTestSupport.run(null, "unzip", "-p", archive.toString(), name)); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java new file mode 100644 index 0000000..066fd67 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java @@ -0,0 +1,92 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; + +final class ArchiveTestSupport { + + private ArchiveTestSupport() {} + + static Path merge(Path scratch, Path... parts) throws IOException { + return merge(scratch, List.of(), List.of(parts)); + } + + static Path merge(Path scratch, List snapshotParts, List parts) throws IOException { + Path archive = scratch.resolve("merged-" + System.nanoTime() + ".zip"); + ZipPartMerger.merge(snapshotParts, parts, archive, scratch); + return archive; + } + + static Map contents(Path zipPath) throws IOException { + Map entries = new TreeMap<>(); + try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { + for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { + try (InputStream in = zip.getInputStream(entry)) { + entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } + return entries; + } + + static Map partContents(Path scratch, Path... parts) throws IOException { + return contents(merge(scratch, parts)); + } + + static boolean available(String tool) { + try { + Process process = new ProcessBuilder(tool, "--help").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); + process.waitFor(20, TimeUnit.SECONDS); + return true; + } catch (IOException | InterruptedException e) { + return false; + } + } + + record Output(String text, long lines) {} + + static String run(Path stdin, String... command) throws IOException, InterruptedException { + return runCounting(stdin, command).text(); + } + + static Output runCounting(Path stdin, String... command) throws IOException, InterruptedException { + Path output = Files.createTempFile("tool-output", ".txt"); + try { + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()); + if (stdin != null) { + builder.redirectInput(stdin.toFile()); + } + Process process = builder.start(); + if (!process.waitFor(30, TimeUnit.MINUTES)) { + process.destroyForcibly(); + throw new IOException("Timed out: " + String.join(" ", command)); + } + String text = head(output); + assertEquals(0, process.exitValue(), String.join(" ", command) + "\n" + text); + try (var lines = Files.lines(output, StandardCharsets.ISO_8859_1)) { + return new Output(text, lines.count()); + } + } finally { + Files.deleteIfExists(output); + } + } + + private static String head(Path file) throws IOException { + try (InputStream in = Files.newInputStream(file)) { + return new String(in.readNBytes(1_000_000), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 9a1cfa6..1fc30cc 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -7,7 +7,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; -import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.contents; +import static wellatleastitried.mediagarrdServer.service.ArchiveTestSupport.contents; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; @@ -28,6 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; @@ -102,29 +103,37 @@ void mergeKeepsMetadataAndIncludesHardLinkParts() throws Exception { } @Test - void overlappingPathsAcrossServicesAppearOnce() throws Exception { + void aDuplicateNameAcrossPartsFailsTheMergeAndLeavesNoArchive() throws Exception { Path run = service.createRunDirectory(); part(run, "a", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); part(run, "b", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); - BackupArchive archive = service.createArchive(run); + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); - assertEquals(Map.of("srv/shared/", "", "srv/shared/x", "1"), contents(archive.path())); + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + } + assertFalse(Files.exists(run.resolve("merge-names.idx"))); } @Test - void directoriesPrecedeTheirContentsAcrossParts() throws Exception { + void partsAreWrittenInSortedPathOrderWithTheSnapshotFirst() throws Exception { + db.saveSetting("backup_root", "/marker"); + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); Path run = service.createRunDirectory(); Item restricted = dir("a/"); restricted.entry().setMode(040700); - part(run, "child", 0, "/srv/a/b", tar(dir("b/"), file("b/x", "1"))); - part(run, "parent", 0, "/srv/a", tar(restricted, dir("a/b/"), file("a/b/x", "1"), file("a/y", "2"))); + part(run, "second", 0, "/srv/b", tar(dir("b/"), file("b/x", "1"))); + part(run, "first", 1, "/srv/a", tar(restricted, dir("a/c/"), file("a/c/x", "1"), file("a/y", "2"))); + part(run, "first", 0, "/srv/a0", tar(file("a0", "0"))); + assertEquals(COMPLETED, new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run).status()); BackupArchive archive = service.createArchive(run); try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { List order = java.util.Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList(); - assertEquals(List.of("srv/a/", "srv/a/b/", "srv/a/b/x", "srv/a/y"), order); + assertEquals(List.of("srv/zzz/mediagarrd.db", "srv/a0", "srv/a/", "srv/a/c/", "srv/a/c/x", "srv/a/y", "srv/b/", "srv/b/x"), order); assertEquals(UnixStat.DIR_FLAG | 0700, zip.getEntry("srv/a/").getUnixMode()); } } @@ -141,7 +150,7 @@ void ignoresStrayFilesInRunDirectory() throws Exception { @Test void failedMergeLeavesNoArchiveBehind() throws Exception { Path run = service.createRunDirectory(); - Files.writeString(run.resolve("corrupt.zip"), "not a zip"); + Files.writeString(run.resolve("corrupt.part"), "not a part"); assertThrows(IllegalStateException.class, () -> service.createArchive(run)); @@ -289,22 +298,23 @@ void startupCleanupRemovesStaleArtifacts() throws Exception { } @Test - void theDatabaseSnapshotAlwaysWinsOverServiceCopiesOfTheSamePath() throws Exception { + void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throws Exception { db.saveSetting("backup_root", "/marker"); DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); String entry = "srv/mediagarrd/db/mediagarrd.db"; when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/" + entry)); Path run = service.createRunDirectory(); - part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar( + var excluded = DatabaseSnapshotService.reservedNames(Path.of("/" + entry)); + Path directory = Files.createDirectories(run.resolve("Mediagarrd")); + ServiceBackupRunner.archive(tar( dir("db/"), file("db/mediagarrd.db", "LIVE COPY"), file("db/mediagarrd.db-journal", "stale journal"), file("db/mediagarrd.db-wal", "wal"), file("db/mediagarrd.db-shm", "shm"), - file("db/notes.txt", "keep"))); - part(run, "0radarr", 0, "/srv/mediagarrd/db/mediagarrd.db", tar(file("mediagarrd.db", "LIVE COPY 2"))); + file("db/notes.txt", "keep")), "/srv/mediagarrd/db", directory.resolve("0.part"), new ZipCompression(1), excluded, java.util.Set.of()); - var snapshot = new DatabaseSnapshotService(db, hostPaths).snapshot(run); + var snapshot = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); BackupArchive archive = service.createArchive(run); assertEquals(COMPLETED, snapshot.status()); @@ -323,6 +333,84 @@ void theDatabaseSnapshotAlwaysWinsOverServiceCopiesOfTheSamePath() throws Except } } + @Test + void aLiveDatabaseCopyThatSlippedPastTheExclusionFailsTheMerge() throws Exception { + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); + Path run = service.createRunDirectory(); + part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar(dir("db/"), file("db/mediagarrd.db-wal", "wal"))); + new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + } + } + + @Test + @Timeout(30) + void carriesAChecksumOfTheFinalFileComputedWhileWriting() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x".repeat(100_000)))); + part(run, "plex", 0, "/srv/plex/movie.mkv", tar(file("movie.mkv", "y".repeat(50_000)))); + + BackupArchive archive = service.createArchive(run); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + assertEquals(java.util.HexFormat.of().formatHex(expected), archive.checksum()); + assertEquals(archive.checksum(), archive.resolvedChecksum()); + assertEquals(Files.size(archive.path()), archive.sizeBytes()); + assertFalse(Files.exists(archive.path().resolveSibling(archive.fileName() + ".tmp"))); + } + + @Test + @Timeout(30) + void storesTheChecksumFromWritingInTheBackupRecord() throws Exception { + BackupArchive archive = createArchive(); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + tempDir.resolve("mediagarrd.db")); + var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT checksum FROM backups")) { + assertEquals(java.util.HexFormat.of().formatHex(expected), result.getString(1)); + } + } + + @Test + @Timeout(30) + void mergesPartsWithMixedStoredAndDeflatedEntries() throws Exception { + String text = "compressible text ".repeat(2000); + Path run = service.createRunDirectory(); + partWith(run, "stored", 0, "/srv/stored", tar(dir("stored/"), file("stored/a.txt", text)), 0); + partWith(run, "mixed", 0, "/srv/mixed", tar(file("mixed/b.txt", text), file("mixed/c.mkv", text)), 9); + partWith(run, "fast", 0, "/srv/fast", tar(file("fast/d.txt", text)), 1); + + BackupArchive archive = service.createArchive(run); + + assertEquals(text, contents(archive.path()).get("srv/stored/a.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/b.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/c.mkv")); + assertEquals(text, contents(archive.path()).get("srv/fast/d.txt")); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/stored/a.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/mixed/b.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/mixed/c.mkv").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/fast/d.txt").getMethod()); + for (ZipArchiveEntry entry : java.util.Collections.list(zip.getEntries())) { + assertFalse(entry.getGeneralPurposeBit().usesDataDescriptor(), entry.getName()); + } + } + java.util.Map streamed = new java.util.TreeMap<>(); + try (var in = new org.apache.commons.compress.archivers.zip.ZipArchiveInputStream(Files.newInputStream(archive.path()))) { + ZipArchiveEntry entry; + while ((entry = in.getNextEntry()) != null) { + streamed.put(entry.getName(), new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + } + } + assertEquals(contents(archive.path()), streamed); + } + @Test void archivesWithoutASnapshotPartStillMerge() throws Exception { Path run = service.createRunDirectory(); @@ -333,9 +421,14 @@ void archivesWithoutASnapshotPartStillMerge() throws Exception { assertEquals(List.of("srv/radarr"), List.copyOf(contents(archive.path()).keySet())); } + private static void partWith(Path run, String service, int index, String hostPath, java.io.InputStream tar, int level) throws Exception { + Path directory = Files.createDirectories(run.resolve(service)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(level)); + } + private static void part(Path run, String service, int index, String hostPath, java.io.InputStream tar) throws Exception { Path directory = Files.createDirectories(run.resolve(service)); - ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(1)); } private BackupArchive createArchive() throws Exception { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java new file mode 100644 index 0000000..41fa227 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java @@ -0,0 +1,318 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(60) +class BackupCopyRoundsTest { + + private static final BackupArchive ARCHIVE = new BackupArchive("archive-1", "archive-1.zip", Path.of("archive-1.zip"), 1, Instant.EPOCH); + private static final Path DATABASE = Path.of("/srv/app/db/mediagarrd.db"); + + @TempDir + Path run; + + private final DockerService docker = mock(DockerService.class); + private final BackupArchiveService archives = mock(BackupArchiveService.class); + private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); + private final DatabaseService db = mock(DatabaseService.class); + private final Map> sources = new HashMap<>(); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService( + new ServiceBackupRunner(docker, new ZipCompression(1)), archives, mock(BackupScheduleService.class), snapshots, db, mock(RunStatusBroadcaster.class)); + + @BeforeEach + void setUp() throws Exception { + when(archives.createRunDirectory()).thenReturn(run); + when(archives.createArchive(run)).thenReturn(ARCHIVE); + when(docker.containerFor(any())).thenReturn("cid"); + when(docker.copyFrom(eq("cid"), anyString())).thenAnswer(invocation -> { + Supplier source = sources.get(invocation.getArgument(1)); + if (source == null) { + throw new IllegalStateException("no such path"); + } + return source.get(); + }); + snapshotSucceeds(); + } + + @AfterEach + void tearDown() { + orchestrator.shutdownRunnerExecutor(); + } + + private void snapshotSucceeds() { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", COMPLETED), DATABASE)); + } + + private static BackupServiceResult result(String name, String status) { + return new BackupServiceResult(null, status, "start", "end", name, null); + } + + private void serve(String path, Item... items) { + sources.put(path, () -> { + try { + return tar(items); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + } + + private BackupRunResult runBackup(ServiceDefinition... services) { + when(db.fetchServices()).thenReturn(List.of(services)); + return orchestrator.runBackup(); + } + + private Map part(String service, int index) throws IOException { + return ArchiveTestSupport.partContents(run, run.resolve(service).resolve(index + ServiceBackupRunner.PART_SUFFIX)); + } + + private static BackupServiceResult resultOf(BackupRunResult run, String service) { + return run.serviceResults().stream().filter(r -> r.serviceName().equals(service)).findFirst().orElseThrow(); + } + + @Test + void aNestedPathIsSkippedWhenItsOwnerCopiedItAndCountsAsCompleted() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media", "/srv/media/config")); + serve("/srv/media", dir("media/"), file("media/a", "1"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "media").status()); + verify(docker, times(1)).copyFrom(eq("cid"), eq("/srv/media")); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + assertEquals(Map.of("srv/media/", "", "srv/media/a", "1", "srv/media/config/", "", "srv/media/config/c", "2"), part("media", 0)); + assertFalse(Files.exists(run.resolve("media/1.part"))); + } + + @Test + void aNestedPathInAnotherServiceIsSkippedAndReportedByItsOwnOutcome() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + serve("/srv/media", dir("media/"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertNull(resultOf(result, "config").errorMessage()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + } + + @Test + void whenTheOwnerFailsTheCoveredPathIsCopiedOnItsOwn() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/media/config", dir("config/"), file("config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "media").status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertEquals(Map.of("srv/media/config/", "", "srv/media/config/c", "2"), part("config", 0)); + } + + @Test + void aCoveredPathThatFailsOnItsOwnAfterAFailedOwnerFailsOnlyItsService() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + ServiceDefinition other = new ServiceDefinition("other", List.of("/srv/other")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/other", dir("other/")); + + BackupRunResult result = runBackup(media, config, other); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "config").status()); + assertEquals("/srv/media/config: no such path", resultOf(result, "config").errorMessage()); + } + + @Test + void aSymbolicLinkAtTheCoveredPathIsNotStoredSoTheCoveredPathIsCopiedItself() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/a")); + ServiceDefinition linked = new ServiceDefinition("linked", List.of("/srv/a/link")); + serve("/srv/a", dir("a/"), link("a/link", TarConstants.LF_SYMLINK, "/mnt/x")); + serve("/srv/a/link", dir("link/"), file("link/data", "real")); + + BackupRunResult result = runBackup(media, linked); + + assertEquals(COMPLETED, result.status()); + verify(docker).copyFrom("cid", "/srv/a/link"); + assertEquals(Map.of("srv/a/link/", "", "srv/a/link/data", "real"), part("linked", 0)); + assertFalse(part("media", 0).containsKey("srv/a/link")); + } + + @Test + void aChainOfNestedPathsFallsBackOneRoundAtATimeWithoutDuplicates() throws Exception { + ServiceDefinition outer = new ServiceDefinition("outer", List.of("/srv/a")); + ServiceDefinition middle = new ServiceDefinition("middle", List.of("/srv/a/b")); + ServiceDefinition inner = new ServiceDefinition("inner", List.of("/srv/a/b/c")); + sources.put("/srv/a", () -> { + throw new IllegalStateException("outer broke"); + }); + serve("/srv/a/b", dir("b/"), dir("b/c/"), file("b/c/x", "1")); + + BackupRunResult result = runBackup(outer, middle, inner); + + assertEquals(FAILED, resultOf(result, "outer").status()); + assertEquals(COMPLETED, resultOf(result, "middle").status()); + assertEquals(COMPLETED, resultOf(result, "inner").status()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/a/b/c")); + assertEquals(3, part("middle", 0).size()); + } + + @Test + void ofSeveralServicesWithTheSamePathOnlyTheFirstByNameCopiesIt() throws Exception { + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + serve("/srv/shared", dir("shared/"), file("shared/x", "1")); + + BackupRunResult result = runBackup(b, a, c); + + assertEquals(COMPLETED, result.status()); + verify(docker, times(1)).copyFrom("cid", "/srv/shared"); + assertTrue(Files.exists(run.resolve("a/0.part"))); + assertFalse(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void whenTheOwnerOfSeveralEqualPathsFailsExactlyOneOtherCopiesIt() throws Exception { + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + int[] calls = {0}; + sources.put("/srv/shared", () -> { + if (calls[0]++ == 0) { + throw new IllegalStateException("first broke"); + } + try { + return tar(dir("shared/"), file("shared/x", "1")); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + BackupRunResult result = runBackup(a, b, c); + + assertEquals(2, calls[0]); + assertEquals(FAILED, resultOf(result, "a").status()); + assertEquals(COMPLETED, resultOf(result, "b").status()); + assertEquals(COMPLETED, resultOf(result, "c").status()); + assertTrue(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void aServiceKeepsItsOwnPathsWhileOneOfThemIsCoveredElsewhere() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition mixed = new ServiceDefinition("mixed", List.of("/srv/media/config", "/etc/mixed")); + serve("/srv/media", dir("media/"), dir("media/config/")); + serve("/etc/mixed", dir("mixed/"), file("mixed/m", "m")); + + BackupRunResult result = runBackup(media, mixed); + + assertEquals(COMPLETED, resultOf(result, "mixed").status()); + assertFalse(Files.exists(run.resolve("mixed/0.part"))); + assertEquals(Map.of("etc/mixed/", "", "etc/mixed/m", "m"), part("mixed", 1)); + } + + @Test + void theDatabaseAndItsSidecarsAreLeftOutOfServiceCopiesWhenTheSnapshotSucceeded() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal"), + file("app/db/mediagarrd.db-shm", "shm"), file("app/db/mediagarrd.db-journal", "j"), link("app/db/hard", TarConstants.LF_LINK, "app/db/mediagarrd.db"), + file("app/db/notes", "keep")); + + runBackup(app); + + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/notes", "keep"), part("app", 0)); + } + + @Test + void theLiveDatabaseIsKeptWhenTheSnapshotFails() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", FAILED), DATABASE)); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/mediagarrd.db", "live", "srv/app/db/mediagarrd.db-wal", "wal"), part("app", 0)); + } + + @Test + void nothingIsExcludedWhenTheSnapshotThrows() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenThrow(new IllegalStateException("docker down")); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), file("app/mediagarrd.db", "live")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/mediagarrd.db", "live"), part("app", 0)); + verify(archives, atLeastOnce()).createArchive(run); + } + + @Test + void theSnapshotIsTakenOnceBeforeAnyCopyStarts() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/")); + + runBackup(app); + + var order = org.mockito.Mockito.inOrder(snapshots, docker); + order.verify(snapshots).snapshotWithHostPath(run); + order.verify(docker).copyFrom("cid", "/srv/app"); + verify(snapshots, times(1)).snapshotWithHostPath(run); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index a999d67..145ad75 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -21,6 +21,7 @@ import java.nio.file.Path; import java.time.Instant; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -59,7 +60,7 @@ class BackupOrchestratorServiceTest { void setUp() { when(archives.createRunDirectory()).thenReturn(RUN_DIR); when(archives.createArchive(RUN_DIR)).thenReturn(ARCHIVE); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(COMPLETED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(COMPLETED)); } @AfterEach @@ -110,10 +111,10 @@ void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); when(schedule.dueNow()).thenReturn(true); @@ -161,7 +162,7 @@ void partialWhenSomeServicesFail() { @Test void partialWhenOnlyTheDatabaseSnapshotFails() { givenResults(COMPLETED, COMPLETED); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); BackupRunResult result = orchestrator.runBackup(); @@ -175,7 +176,7 @@ void partialWhenOnlyTheDatabaseSnapshotFails() { @Test void snapshotFailureIsAddedToTheServiceErrors() { givenResults(COMPLETED, FAILED); - when(snapshots.snapshot(RUN_DIR)).thenReturn(snapshotResult(FAILED)); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); BackupRunResult result = orchestrator.runBackup(); @@ -186,7 +187,7 @@ void snapshotFailureIsAddedToTheServiceErrors() { @Test void aThrowingSnapshotStillProducesAPartialArchive() { givenResults(COMPLETED, COMPLETED); - when(snapshots.snapshot(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); BackupRunResult result = orchestrator.runBackup(); @@ -197,13 +198,14 @@ void aThrowingSnapshotStillProducesAPartialArchive() { } @Test - void snapshotRunsBeforeTheArchiveIsCreated() { + void snapshotRunsBeforeTheCopiesAndTheArchiveIsCreatedLast() { givenResults(COMPLETED, COMPLETED); orchestrator.runBackup(); - var order = inOrder(snapshots, archives); - order.verify(snapshots).snapshot(RUN_DIR); + var order = inOrder(snapshots, runner, archives); + order.verify(snapshots).snapshotWithHostPath(RUN_DIR); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), eq(RUN_DIR), any(), any()); order.verify(archives).createArchive(RUN_DIR); } @@ -222,7 +224,6 @@ void skipsArchiveWhenEveryServiceFails() { assertTrue(e.getMessage().contains("radarr: boom\nsonarr: boom")); verify(archives, never()).createArchive(any()); - verify(snapshots, never()).snapshot(any()); verify(archives).removeRunDirectory(RUN_DIR); assertFalse(orchestrator.isRunning()); @@ -238,8 +239,8 @@ void skipsArchiveWhenEveryServiceFails() { @Test void runnerExceptionsBecomeFailedResults() { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); - when(runner.run(RADARR, RUN_DIR)).thenThrow(new IllegalStateException("crashed")); - when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", COMPLETED)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, COMPLETED)); BackupRunResult result = orchestrator.runBackup(); @@ -264,10 +265,10 @@ void rejectsConcurrentRuns() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -291,10 +292,10 @@ void configChangesAreRejectedDuringABackupRun() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -343,7 +344,7 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { var order = inOrder(broadcaster, runner, db); order.verify(db).fetchServices(); order.verify(broadcaster).publishStarted(any()); - order.verify(runner, org.mockito.Mockito.atLeastOnce()).run(any(), any()); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), any(), any(), any()); order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); @@ -455,10 +456,10 @@ void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); when(db.fetchServices()).thenReturn(List.of(RADARR)); - when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); - return result("radarr", COMPLETED); + return round(RADARR, COMPLETED); }); CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); @@ -503,12 +504,22 @@ void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { private void givenResults(String radarrStatus, String sonarrStatus) { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); - when(runner.run(RADARR, RUN_DIR)).thenReturn(result("radarr", radarrStatus)); - when(runner.run(SONARR, RUN_DIR)).thenReturn(result("sonarr", sonarrStatus)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, radarrStatus)); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, sonarrStatus)); } - private static BackupServiceResult snapshotResult(String status) { - return result(SNAPSHOT, status); + private static DatabaseSnapshotService.Outcome snapshotOutcome(String status) { + return new DatabaseSnapshotService.Outcome(result(SNAPSHOT, status), Path.of("/srv/mediagarrd/db/mediagarrd.db")); + } + + private static ServiceBackupRunner.ServiceRound round(ServiceDefinition service, String status) { + String path = service.paths().get(0); + return switch (status) { + case COMPLETED -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()))); + case PARTIAL -> new ServiceBackupRunner.ServiceRound(null, List.of( + new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()), new ServiceBackupRunner.PathCopy(1, path, false, "boom", Set.of()))); + default -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, false, "boom", Set.of()))); + }; } private static BackupServiceResult result(String name, String status) { diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java new file mode 100644 index 0000000..facaf5b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java @@ -0,0 +1,97 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +@Timeout(120) +class CoveredSymlinkTest { + + private static final ZipCompression COMPRESSION = new ZipCompression(1); + + @TempDir + Path dir; + + private Path owner(String name, ServiceBackupRunner.ArchiveResult[] result, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve(name + ".part"); + result[0] = ServiceBackupRunner.archive(tar(items), "/srv/a", part, COMPRESSION, Set.of(), Set.of("srv/a/covered")); + return part; + } + + private Path fallback(String hostPath, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve("fallback.part"); + ServiceBackupRunner.archive(tar(items), hostPath, part, COMPRESSION, Set.of(), Set.of()); + return part; + } + + private void extract(Path archive, Path target) throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Files.createDirectories(target); + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + Path streamed = dir.resolve("streamed"); + Files.createDirectories(streamed); + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", streamed.toString()); + assertEquals(Files.isSymbolicLink(target.resolve("srv/a/other")), Files.isSymbolicLink(streamed.resolve("srv/a/other"))); + } + + @Test + void aSymlinkToAFileAtACoveredPathIsLeftOutAndTheRealFileTakesItsName() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/x"), + link("a/other", TarConstants.LF_SYMLINK, "keep")); + Path fallbackPart = fallback("/srv/a/covered", file("covered", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertEquals("real", contents.get("srv/a/covered")); + assertEquals("keep", contents.get("srv/a/other")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertEquals("real", Files.readString(target.resolve("srv/a/covered"))); + assertFalse(Files.isSymbolicLink(target.resolve("srv/a/covered"))); + assertTrue(Files.isSymbolicLink(target.resolve("srv/a/other"))); + assertEquals("keep", Files.readSymbolicLink(target.resolve("srv/a/other")).toString()); + } + + @Test + void aSymlinkToADirectoryAtACoveredPathIsLeftOutAndTheRealDirectoryIsRestored() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/dir")); + Path fallbackPart = fallback("/srv/a/covered", dir("covered/"), file("covered/data", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertFalse(contents.containsKey("srv/a/covered")); + assertTrue(contents.containsKey("srv/a/covered/")); + assertEquals("real", contents.get("srv/a/covered/data")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertTrue(Files.isDirectory(target.resolve("srv/a/covered"), java.nio.file.LinkOption.NOFOLLOW_LINKS)); + assertEquals("real", Files.readString(target.resolve("srv/a/covered/data"))); + } + + @Test + void aSymlinkAtANameThatIsNotCoveredIsStillStoredAsASymlink() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), link("a/other", TarConstants.LF_SYMLINK, "/mnt/x")); + + assertEquals("/mnt/x", ArchiveTestSupport.partContents(dir, ownerPart).get("srv/a/other")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java index 5ee1cb7..fba6743 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -46,7 +46,7 @@ void setUp() throws Exception { db = new DatabaseService(properties); hostPaths = mock(DatabaseHostPathResolver.class); when(hostPaths.resolve(db.databaseFile())).thenReturn(HOST_DATABASE); - snapshots = new DatabaseSnapshotService(db, hostPaths); + snapshots = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)); run = Files.createDirectories(tempDir.resolve("run")); } @@ -62,7 +62,7 @@ void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { assertEquals(COMPLETED, result.status()); assertEquals(DatabaseSnapshotService.SERVICE_NAME, result.serviceName()); Path part = run.resolve(DatabaseSnapshotService.PART_DIRECTORY).resolve(DatabaseSnapshotService.PART_NAME); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(tempDir, part)).get()) { assertEquals(List.of("srv/mediagarrd/db/mediagarrd.db"), Collections.list(zip.getEntries()).stream().map(ZipArchiveEntry::getName).toList()); ZipArchiveEntry entry = zip.getEntry("srv/mediagarrd/db/mediagarrd.db"); assertEquals(0640, entry.getUnixMode() & 07777); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java new file mode 100644 index 0000000..a1330cd --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java @@ -0,0 +1,107 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.Iterator; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; + +final class GeneratedTar extends InputStream { + + record Spec(String name, long size, byte[] pattern) { + + static Spec directory(String name) { + return new Spec(name, -1, null); + } + + static Spec file(String name, long size, byte[] pattern) { + return new Spec(name, size, pattern); + } + } + + private static final int BLOCK = 512; + + private final Iterator specs; + private final byte[] header = new byte[BLOCK]; + private int headerPosition = BLOCK; + private long contentRemaining; + private long contentOffset; + private byte[] pattern; + private int padding; + private int trailer = 2 * BLOCK; + + GeneratedTar(Iterator specs) { + this.specs = specs; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int read = read(one, 0, 1); + return read < 0 ? -1 : one[0] & 0xFF; + } + + @Override + public int read(byte[] target, int offset, int length) throws IOException { + if (length == 0) { + return 0; + } + while (true) { + if (headerPosition < BLOCK) { + int count = Math.min(length, BLOCK - headerPosition); + System.arraycopy(header, headerPosition, target, offset, count); + headerPosition += count; + return count; + } + if (contentRemaining > 0) { + int count = (int) Math.min(length, contentRemaining); + for (int i = 0; i < count; i++) { + target[offset + i] = pattern[(int) ((contentOffset + i) % pattern.length)]; + } + contentOffset += count; + contentRemaining -= count; + if (contentRemaining == 0) { + padding = (int) ((BLOCK - contentOffset % BLOCK) % BLOCK); + } + return count; + } + if (padding > 0) { + int count = Math.min(length, padding); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + padding -= count; + return count; + } + if (specs.hasNext()) { + begin(specs.next()); + continue; + } + if (trailer > 0) { + int count = Math.min(length, trailer); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + trailer -= count; + return count; + } + return -1; + } + } + + private void begin(Spec spec) { + TarArchiveEntry entry = new TarArchiveEntry(spec.name()); + entry.setModTime(new Date(1_700_000_000_000L)); + entry.setUserId(1000); + entry.setGroupId(1000); + if (spec.size() < 0) { + entry.setMode(040755); + } else { + entry.setMode(0100644); + entry.setSize(spec.size()); + } + java.util.Arrays.fill(header, (byte) 0); + entry.writeEntryHeader(header); + headerPosition = 0; + contentRemaining = Math.max(spec.size(), 0); + contentOffset = 0; + pattern = spec.pattern(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java new file mode 100644 index 0000000..582634e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/PathCoverageTest.java @@ -0,0 +1,48 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.PathCoverage.Item; +import wellatleastitried.mediagarrdServer.service.PathCoverage.Owner; + +class PathCoverageTest { + + private static Item item(String service, String path) { + return new Item(new ServiceDefinition(service, List.of(path)), 0); + } + + @Test + void anAncestorOwnsEveryDescendantAndSiblingsStaySeparate() { + Item a = item("a", "/srv/a"); + Item inner = item("b", "/srv/a/b/c"); + Item middle = item("c", "/srv/a/b"); + Item sibling = item("d", "/srv/ab"); + + List owners = PathCoverage.plan(List.of(inner, a, sibling, middle)); + + assertEquals(List.of(a, sibling), owners.stream().map(Owner::item).toList()); + assertEquals(List.of(inner, middle), owners.get(0).covered()); + assertEquals(List.of(), owners.get(1).covered()); + } + + @Test + void equalPathsAreOwnedByTheServiceThatSortsFirst() { + Item b = item("b", "/srv/x"); + Item a = item("a", "/srv/x"); + + List owners = PathCoverage.plan(List.of(b, a)); + + assertEquals(List.of(a), owners.stream().map(Owner::item).toList()); + assertEquals(List.of(b), owners.get(0).covered()); + } + + @Test + void keysAreEntryNamesWithoutTheLeadingSlash() { + assertEquals("srv/a/b", item("a", "/srv/a/b").key()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java index 62fee1b..63e3696 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunnerTest.java @@ -19,12 +19,12 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; -import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; -import java.util.TreeMap; import java.util.stream.Stream; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; @@ -34,10 +34,12 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; @@ -50,7 +52,7 @@ class ServiceBackupRunnerTest { Path runDir; private final DockerService docker = mock(DockerService.class); - private final ServiceBackupRunner runner = new ServiceBackupRunner(docker); + private final ServiceBackupRunner runner = new ServiceBackupRunner(docker, new ZipCompression(1)); @Test void storesDirectoryContentsUnderTheirAbsolutePaths() throws Exception { @@ -63,11 +65,11 @@ void storesDirectoryContentsUnderTheirAbsolutePaths() throws Exception { assertEquals(COMPLETED, result.status()); assertNull(result.errorMessage()); - Map config = contents(runDir.resolve("radarr/0.zip")); + Map config = contents(runDir.resolve("radarr/0.part")); assertEquals(List.of("srv/radarr/config/", "srv/radarr/config/config.xml", "srv/radarr/config/empty/", "srv/radarr/config/logs/app.log"), List.copyOf(config.keySet())); assertEquals("", config.get("srv/radarr/config/config.xml")); - assertEquals("db", contents(runDir.resolve("radarr/1.zip")).get("srv/radarr/data/radarr.db")); + assertEquals("db", contents(runDir.resolve("radarr/1.part")).get("srv/radarr/data/radarr.db")); } @Test @@ -78,7 +80,7 @@ void storesOnlyTheFileWhenPathIsAFile() throws Exception { assertEquals(COMPLETED, runner.run(nginx, runDir).status()); - assertEquals(Map.of("etc/nginx/sites-available/config", "server {}"), contents(runDir.resolve("nginx/0.zip"))); + assertEquals(Map.of("etc/nginx/sites-available/config", "server {}"), contents(runDir.resolve("nginx/0.part"))); } static Stream archivedEntries() { @@ -99,7 +101,7 @@ static Stream archivedEntries() { void archivesExpectedEntries(String description, String hostPath, Item[] items, Map expected) throws Exception { Path part = runDir.resolve("part.zip"); - assertEquals(expected.size(), ServiceBackupRunner.archive(tar(items), hostPath, part)); + assertEquals(expected.size(), ServiceBackupRunner.archive(tar(items), hostPath, part, new ZipCompression(1))); assertEquals(expected, contents(part)); } @@ -111,16 +113,16 @@ void preservesModeOwnerAndModificationTime() throws Exception { secret.entry().setMode(0100600); secret.entry().setUserId(1000); secret.entry().setGroupId(1001); - secret.entry().setModTime(new Date(1_700_000_000_000L)); + secret.entry().setModTime(new Date(1_700_000_001_000L)); Item folder = dir("config/"); folder.entry().setMode(040750); - ServiceBackupRunner.archive(tar(folder, secret), "/home/user/config", part); + ServiceBackupRunner.archive(tar(folder, secret), "/home/user/config", part, new ZipCompression(1)); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { ZipArchiveEntry key = zip.getEntry("home/user/config/id_rsa"); assertEquals(UnixStat.FILE_FLAG | 0600, key.getUnixMode()); - assertEquals(1_700_000_000_000L, key.getTime()); + assertEquals(1_700_000_001_000L, key.getTime()); X7875_NewUnix owner = (X7875_NewUnix) key.getExtraField(new X7875_NewUnix().getHeaderId()); assertEquals(1000, owner.getUID()); assertEquals(1001, owner.getGID()); @@ -128,14 +130,96 @@ void preservesModeOwnerAndModificationTime() throws Exception { } } + @ParameterizedTest(name = "level {0}") + @ValueSource(ints = {0, 1, 9}) + @Timeout(30) + void picksEntryMethodsByLevelAndExtensionAndRoundTripsContents(int level) throws Exception { + Path part = runDir.resolve("part.zip"); + String text = "compressible text ".repeat(2000); + Item notes = file("data/notes.txt", text); + notes.entry().setMode(0100640); + notes.entry().setUserId(1000); + notes.entry().setGroupId(1001); + notes.entry().setModTime(new Date(1_700_000_000_000L)); + Item movie = file("data/movie.MKV", text); + movie.entry().setMode(0100600); + movie.entry().setUserId(7); + movie.entry().setGroupId(8); + + ServiceBackupRunner.archive(tar(dir("data/"), notes, movie, file("data/empty.txt", "")), "/srv/data", part, new ZipCompression(level)); + + assertEquals(text, contents(part).get("srv/data/notes.txt")); + assertEquals(text, contents(part).get("srv/data/movie.MKV")); + assertEquals("", contents(part).get("srv/data/empty.txt")); + CRC32 crc = new CRC32(); + crc.update(text.getBytes(StandardCharsets.UTF_8)); + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { + ZipArchiveEntry stored = zip.getEntry("srv/data/movie.MKV"); + assertEquals(ZipEntry.STORED, stored.getMethod()); + assertEquals(text.length(), stored.getSize()); + assertEquals(text.length(), stored.getCompressedSize()); + assertEquals(crc.getValue(), stored.getCrc()); + assertEquals(UnixStat.FILE_FLAG | 0600, stored.getUnixMode()); + X7875_NewUnix owner = (X7875_NewUnix) stored.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(7, owner.getUID()); + assertEquals(8, owner.getGID()); + + ZipArchiveEntry notesEntry = zip.getEntry("srv/data/notes.txt"); + assertEquals(level == 0 ? ZipEntry.STORED : ZipEntry.DEFLATED, notesEntry.getMethod()); + assertEquals(level == 0, notesEntry.getCompressedSize() == notesEntry.getSize()); + assertEquals(UnixStat.FILE_FLAG | 0640, notesEntry.getUnixMode()); + assertEquals(1_700_000_000_000L, notesEntry.getTime()); + X7875_NewUnix notesOwner = (X7875_NewUnix) notesEntry.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(1000, notesOwner.getUID()); + assertEquals(1001, notesOwner.getGID()); + assertEquals(UnixStat.DIR_FLAG | 0755, zip.getEntry("srv/data/").getUnixMode()); + } + } + + @Test + @Timeout(30) + void higherLevelsProduceSmallerPartsForCompressibleData() throws Exception { + String text = "compressible text ".repeat(20000); + Path none = runDir.resolve("none.zip"); + Path fast = runDir.resolve("fast.zip"); + Path best = runDir.resolve("best.zip"); + + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", none, new ZipCompression(0)); + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", fast, new ZipCompression(1)); + ServiceBackupRunner.archive(tar(file("f/a.txt", text)), "/srv/f", best, new ZipCompression(9)); + + assertTrue(Files.size(none) > text.length()); + assertTrue(Files.size(fast) < text.length() / 10); + assertTrue(Files.size(best) <= Files.size(fast)); + } + + @Test + @Timeout(30) + void hardLinksToStoredAndDeflatedEntriesKeepTheirMethods() throws Exception { + Path part = runDir.resolve("part.zip"); + Item stored = file("data/clip.mp4", "video".repeat(500)); + Item deflated = file("data/log.txt", "text".repeat(500)); + Item linkStored = link("data/clip-link.mp4", TarConstants.LF_LINK, "data/clip.mp4"); + Item linkDeflated = link("data/log-link.txt", TarConstants.LF_LINK, "data/log.txt"); + + ServiceBackupRunner.archive(tar(dir("data/"), stored, deflated, linkStored, linkDeflated), "/srv/data", part, new ZipCompression(1)); + + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { + assertEquals(ZipEntry.STORED, zip.getEntry("srv/data/clip-link.mp4").getMethod()); + assertEquals(ZipEntry.DEFLATED, zip.getEntry("srv/data/log-link.txt").getMethod()); + } + assertEquals("video".repeat(500), contents(part).get("srv/data/clip-link.mp4")); + assertEquals("text".repeat(500), contents(part).get("srv/data/log-link.txt")); + } + @Test void storesSymbolicLinksAsLinks() throws Exception { Path part = runDir.resolve("part.zip"); Item symlink = link("sites-enabled/default", TarConstants.LF_SYMLINK, "/etc/nginx/sites-available/default"); - ServiceBackupRunner.archive(tar(dir("sites-enabled/"), symlink), "/etc/nginx/sites-enabled", part); + ServiceBackupRunner.archive(tar(dir("sites-enabled/"), symlink), "/etc/nginx/sites-enabled", part, new ZipCompression(1)); - try (ZipFile zip = ZipFile.builder().setPath(part).get()) { + try (ZipFile zip = ZipFile.builder().setPath(merged(part)).get()) { ZipArchiveEntry entry = zip.getEntry("etc/nginx/sites-enabled/default"); assertTrue(entry.isUnixSymlink()); assertEquals("/etc/nginx/sites-available/default", zip.getUnixSymlink(entry)); @@ -143,14 +227,65 @@ void storesSymbolicLinksAsLinks() throws Exception { } @Test - void copiesHardLinksIntoALinksPart() throws Exception { - Path part = runDir.resolve("0.zip"); + void storesHardLinksAsRegularCopiesOfTheirTarget() throws Exception { + Path part = runDir.resolve("0.part"); Item hardLink = link("data/link", TarConstants.LF_LINK, "data/original"); - assertEquals(3, ServiceBackupRunner.archive(tar(dir("data/"), file("data/original", "same"), hardLink), "/srv/data", part)); + assertEquals(3, ServiceBackupRunner.archive(tar(dir("data/"), file("data/original", "same"), hardLink), "/srv/data", part, new ZipCompression(1))); + + assertEquals(Map.of("srv/data/", "", "srv/data/original", "same", "srv/data/link", "same"), contents(part)); + } + + @Test + void excludedNamesAndHardLinksToThemAreSkipped() throws Exception { + Path part = runDir.resolve("0.part"); + Item hardLink = link("data/db-link", TarConstants.LF_LINK, "data/live.db"); + + ServiceBackupRunner.ArchiveResult result = ServiceBackupRunner.archive( + tar(dir("data/"), file("data/live.db", "live"), hardLink, file("data/keep", "k")), "/srv/data", part, new ZipCompression(1), + java.util.Set.of("srv/data/live.db"), java.util.Set.of()); + + assertEquals(2, result.entries()); + assertEquals(Map.of("srv/data/", "", "srv/data/keep", "k"), contents(part)); + } + + @Test + void aHardLinkToASkippedSpecialFileIsSkippedInsteadOfFailingThePath() throws Exception { + Path part = runDir.resolve("0.part"); + + int entries = ServiceBackupRunner.archive( + tar(dir("data/"), special("data/pipe", TarConstants.LF_FIFO), link("data/pipe2", TarConstants.LF_LINK, "data/pipe"), file("data/f", "x")), + "/srv/data", part, new ZipCompression(1)); + + assertEquals(2, entries); + assertEquals(Map.of("srv/data/", "", "srv/data/f", "x"), contents(part)); + } + + @Test + void hardLinksToHardLinksResolveAndUnknownTargetsFailThePath() throws Exception { + Path part = runDir.resolve("0.part"); + + ServiceBackupRunner.archive(tar(file("data/a", "same"), link("data/b", TarConstants.LF_LINK, "data/a"), link("data/c", TarConstants.LF_LINK, "data/b")), + "/srv/data", part, new ZipCompression(1)); + + assertEquals(Map.of("srv/data/a", "same", "srv/data/b", "same", "srv/data/c", "same"), contents(part)); + Path broken = runDir.resolve("broken.part"); + assertThrows(IOException.class, + () -> ServiceBackupRunner.archive(tar(link("data/b", TarConstants.LF_LINK, "data/nothing")), "/srv/data", broken, new ZipCompression(1))); + assertFalse(Files.exists(broken)); + assertFalse(Files.exists(ZipPartWriter.indexOf(broken))); + } + + @Test + void confirmsCoveredPathsOnlyWhenTheirDirectoryOrFileWasStored() throws Exception { + Path part = runDir.resolve("0.part"); + + ServiceBackupRunner.ArchiveResult result = ServiceBackupRunner.archive( + tar(dir("a/"), dir("a/dir/"), file("a/file", "f"), link("a/link", TarConstants.LF_SYMLINK, "/mnt/x"), dir("a/other/")), + "/srv/a", part, new ZipCompression(1), + java.util.Set.of(), java.util.Set.of("srv/a/dir", "srv/a/file", "srv/a/link", "srv/a/missing", "srv/a")); - assertFalse(contents(part).containsKey("srv/data/link")); - assertEquals(Map.of("srv/data/link", "same"), contents(runDir.resolve("0-links.zip"))); + assertEquals(java.util.Set.of("srv/a/dir", "srv/a/file", "srv/a"), result.confirmed()); } @Test @@ -163,8 +298,10 @@ void reportsPartialAndDiscardsOnlyTheFailedPath() throws Exception { assertEquals(PARTIAL, result.status()); assertTrue(result.errorMessage().startsWith("/srv/radarr/data: ")); - assertTrue(Files.exists(runDir.resolve("radarr/0.zip"))); - assertFalse(Files.exists(runDir.resolve("radarr/1.zip"))); + assertTrue(Files.exists(runDir.resolve("radarr/0.part"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part.partial"))); + assertFalse(Files.exists(runDir.resolve("radarr/1.part.idx"))); } @Test @@ -193,8 +330,8 @@ void reportsFailedWhenContainerCannotBePrepared() { void rejectsEntriesOutsideTheBackedUpPath() { Path part = runDir.resolve("part.zip"); - assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("../escaped.txt", "x")), "/srv/data", part)); - assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("other/file", "x")), "/srv/data", part)); + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("../escaped.txt", "x")), "/srv/data", part, new ZipCompression(1))); + assertThrows(IOException.class, () -> ServiceBackupRunner.archive(tar(file("other/file", "x")), "/srv/data", part, new ZipCompression(1))); } @Test @@ -202,7 +339,7 @@ void rejectsHardLinksOutsideTheBackedUpPath() { Item hardLink = link("data/link", TarConstants.LF_LINK, "../etc/shadow"); assertThrows(IOException.class, - () -> ServiceBackupRunner.archive(tar(dir("data/"), hardLink), "/srv/data", runDir.resolve("part.zip"))); + () -> ServiceBackupRunner.archive(tar(dir("data/"), hardLink), "/srv/data", runDir.resolve("part.zip"), new ZipCompression(1))); } @Test @@ -212,16 +349,12 @@ void buildsEntryNamesFromAbsolutePaths() throws IOException { assertEquals("srv/", ServiceBackupRunner.entryName(Path.of("/"), Path.of("/srv"), "srv/", true)); } - static Map contents(Path zipPath) throws IOException { - Map entries = new TreeMap<>(); - try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { - for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { - try (InputStream in = zip.getInputStream(entry)) { - entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); - } - } - } - return entries; + static Path merged(Path part) throws IOException { + return ArchiveTestSupport.merge(part.getParent(), part); + } + + static Map contents(Path part) throws IOException { + return ArchiveTestSupport.contents(merged(part)); } record Item(TarArchiveEntry entry, byte[] content) {} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java new file mode 100644 index 0000000..c6738b6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/TallyTest.java @@ -0,0 +1,47 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.PathCopy; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.ServiceRound; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunner.Tally; + +class TallyTest { + + private static ServiceRound failed(String error, String... paths) { + return new ServiceRound(error, java.util.Arrays.stream(paths).map(p -> new PathCopy(0, p, false, null, Set.of())).toList()); + } + + @Test + void theSameServiceLevelErrorInSeveralRoundsIsReportedOnce() { + Tally tally = new Tally("media"); + tally.add(failed("no helper", "/a")); + tally.add(failed("no helper", "/b")); + + BackupServiceResult result = tally.result(); + + assertEquals(FAILED, result.status()); + assertEquals("no helper", result.errorMessage()); + } + + @Test + void differentErrorsAreAllKeptInOrder() { + Tally tally = new Tally("media"); + tally.add(failed("no helper", "/a")); + tally.add(new ServiceRound(null, List.of(new PathCopy(1, "/b", false, "/b: boom", Set.of()), new PathCopy(2, "/c", true, null, Set.of())))); + tally.add(failed("other", "/d")); + + BackupServiceResult result = tally.result(); + + assertEquals(PARTIAL, result.status()); + assertEquals("no helper; /b: boom; other", result.errorMessage()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java new file mode 100644 index 0000000..1fc4dac --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionBindingTest.java @@ -0,0 +1,54 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Timeout(30) +class ZipCompressionBindingTest { + + private final ApplicationContextRunner runner = new ApplicationContextRunner().withUserConfiguration(Config.class); + + @Test + void bindsALevelInRange() { + runner.withPropertyValues("mediagarrd.compression-level=5").run(context -> { + assertTrue(context.getStartupFailure() == null); + assertEquals(5, context.getBean(ZipCompression.class).level()); + }); + } + + @Test + void defaultsToOne() { + runner.run(context -> assertEquals(1, context.getBean(ZipCompression.class).level())); + } + + @Test + void failsStartupForALevelOutOfRange() { + runner.withPropertyValues("mediagarrd.compression-level=12").run(context -> { + assertTrue(context.getStartupFailure() != null); + assertTrue(rootMessages(context.getStartupFailure()).contains("mediagarrd.compression-level must be between 0 and 9, was 12")); + }); + } + + private static String rootMessages(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable t = failure; t != null; t = t.getCause()) { + messages.append(t.getMessage()).append('\n'); + } + return messages.toString(); + } + + @Configuration + @EnableConfigurationProperties(MediaGarrdProperties.class) + @Import(ZipCompression.class) + static class Config { + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java new file mode 100644 index 0000000..afef227 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipCompressionTest.java @@ -0,0 +1,82 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Timeout(30) +class ZipCompressionTest { + + @ParameterizedTest + @ValueSource(ints = {-1, 10, 100}) + void rejectsLevelsOutsideZeroToNine(int level) { + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZipCompression(level)); + + assertTrue(e.getMessage().contains("mediagarrd.compression-level must be between 0 and 9"), e.getMessage()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 5, 9}) + void acceptsLevelsZeroToNine(int level) { + assertEquals(level, new ZipCompression(level).level()); + } + + @Test + void defaultsToLevelOneFromProperties() { + assertEquals(1, new ZipCompression(new MediaGarrdProperties()).level()); + } + + @Test + void rejectsAnInvalidLevelFromProperties() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setCompressionLevel(12); + + assertThrows(IllegalStateException.class, () -> new ZipCompression(properties)); + } + + @ParameterizedTest + @ValueSource(strings = {"a.zip", "a.gz", "a.tgz", "a.bz2", "a.xz", "a.zst", "a.7z", "a.rar", "a.jpg", "a.jpeg", "a.png", + "a.gif", "a.webp", "a.mp4", "a.mkv", "a.mp3", "a.flac", "a.ogg", "a.mov", "a.avi", "a.webm", "a.m4v", "a.m4a", "a.aac", + "a.opus", "a.heic", "a.avif", "a.lz4", "a.zstd", "a.jar", "a.docx", "a.xlsx", "a.pptx", "dir/Photo.JPG", "x/y.tar.gz"}) + void storesAlreadyCompressedFilesAtAnyNonZeroLevel(String name) { + for (int level : new int[] {1, 9}) { + assertTrue(new ZipCompression(level).stores(name), name); + } + } + + @ParameterizedTest + @ValueSource(strings = {"a.txt", "a.db", "a.xml", "noextension", "dir.zip/file", "dir.png/readme", "a.", "gz", ".hidden"}) + void deflatesEverythingElseAtNonZeroLevels(String name) { + for (int level : new int[] {1, 9}) { + assertFalse(new ZipCompression(level).stores(name), name); + } + } + + @Test + void levelZeroStoresEverything() { + ZipCompression none = new ZipCompression(0); + + assertTrue(none.stores("a.txt")); + assertTrue(none.stores("a.jpg")); + assertTrue(none.stores("noextension")); + } + + @Test + void storesAlreadyCompressedFilesAtLevelOneAndReportsItsLevel() { + ZipCompression one = new ZipCompression(1); + + assertEquals(1, one.level()); + assertTrue(one.stores("a.mkv")); + assertFalse(one.stores("a.txt")); + assertEquals(0, new ZipCompression(0).level()); + assertTrue(new ZipCompression(0).stores("a.txt")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java new file mode 100644 index 0000000..83f9649 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipFormatTest.java @@ -0,0 +1,36 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +@Timeout(30) +class ZipFormatTest { + + @Test + void theExtendedTimestampCoversOnlyTimesFromTheEpochToTheSignedLimit() { + assertFalse(ZipFormat.fitsUnixTime(-1L)); + assertFalse(ZipFormat.fitsUnixTime(-631_152_000_000L)); + assertTrue(ZipFormat.fitsUnixTime(0L)); + assertTrue(ZipFormat.fitsUnixTime(Integer.MAX_VALUE * 1000L)); + assertFalse(ZipFormat.fitsUnixTime((Integer.MAX_VALUE + 1L) * 1000L)); + } + + @Test + void ownerDataIsAlwaysFourByteIdsInLittleEndian() { + assertArrayEquals(new byte[] {1, 4, 33, 0, 0, 0, 4, (byte) 0xE8, 3, 0, 0}, ZipFormat.ownerData(33, 1000)); + assertArrayEquals(new byte[] {1, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0}, ZipFormat.ownerData(0, 0)); + } + + @Test + void ownerIdsOutsideThirtyTwoBitsAreClamped() { + byte[] data = ZipFormat.ownerData(0x100000005L, -7); + + assertEquals(11, data.length); + assertArrayEquals(new byte[] {1, 4, -1, -1, -1, -1, 4, 0, 0, 0, 0}, data); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java new file mode 100644 index 0000000..deaba30 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ZipPartWriterTest.java @@ -0,0 +1,267 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.ByteArrayInputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; + +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +class ZipPartWriterTest { + + private static final int FILE = UnixStat.FILE_FLAG | 0644; + private static final int DIRECTORY = UnixStat.DIR_FLAG | 0755; + + @TempDir + Path dir; + + private static InputStream bytes(String text) { + return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); + } + + private void add(ZipPartWriter writer, String name, String text) throws IOException { + writer.addEntry(name, FILE, 1000, 1001, 1_700_000_001_000L, text.getBytes(StandardCharsets.UTF_8).length, bytes(text)); + } + + @Test + void writesEntriesWithMetadataThatReadersAndExactTimesRoundTrip() throws Exception { + Path part = dir.resolve("0.part"); + String text = "compressible text ".repeat(500); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("srv/data/", DIRECTORY, 0, 0, 1_700_000_001_000L, 0, bytes("")); + writer.addEntry("srv/data/notes.txt", UnixStat.FILE_FLAG | 0640, 1000, 1001, 1_700_000_001_000L, text.length(), bytes(text)); + writer.addEntry("srv/data/movie.mkv", UnixStat.FILE_FLAG | 0400, 7, 8, 1_700_000_003_000L, text.length(), bytes(text)); + writer.addEntry("srv/data/empty.txt", FILE, 1, 2, 1_700_000_005_000L, 0, bytes("")); + writer.complete(); + assertEquals(4, writer.entryCount()); + } + assertTrue(Files.exists(part)); + assertFalse(Files.exists(ZipPartWriter.partialOf(part))); + + CRC32 crc = new CRC32(); + crc.update(text.getBytes(StandardCharsets.UTF_8)); + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(dir, part)).get()) { + assertEquals(List.of("srv/data/", "srv/data/notes.txt", "srv/data/movie.mkv", "srv/data/empty.txt"), + Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList()); + ZipArchiveEntry notes = zip.getEntry("srv/data/notes.txt"); + assertEquals(ZipEntry.DEFLATED, notes.getMethod()); + assertEquals(text.length(), notes.getSize()); + assertTrue(notes.getCompressedSize() < text.length() / 4); + assertEquals(crc.getValue(), notes.getCrc()); + assertEquals(UnixStat.FILE_FLAG | 0640, notes.getUnixMode()); + assertEquals(1_700_000_001_000L, notes.getTime()); + assertEquals(1_700_000_001L, ((X5455_ExtendedTimestamp) notes.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)).getModifyJavaTime().getTime() / 1000); + assertEquals(text, new String(zip.getInputStream(notes).readAllBytes(), StandardCharsets.UTF_8)); + + ZipArchiveEntry movie = zip.getEntry("srv/data/movie.mkv"); + assertEquals(ZipEntry.STORED, movie.getMethod()); + assertEquals(text.length(), movie.getCompressedSize()); + assertEquals(UnixStat.FILE_FLAG | 0400, movie.getUnixMode()); + assertEquals(1_700_000_003_000L, movie.getTime()); + assertEquals(text, new String(zip.getInputStream(movie).readAllBytes(), StandardCharsets.UTF_8)); + + assertEquals(UnixStat.DIR_FLAG | 0755, zip.getEntry("srv/data/").getUnixMode()); + assertTrue(zip.getEntry("srv/data/").isDirectory()); + assertEquals("", new String(zip.getInputStream(zip.getEntry("srv/data/empty.txt")).readAllBytes(), StandardCharsets.UTF_8)); + } + } + + @Test + void writesOwnerOnlyInTheLocalHeaderAndTimesOutsideTheExtendedRangeAsDosOnly() throws Exception { + Path part = dir.resolve("0.part"); + long before1980 = 100_000_000L; + long after2038 = 4_300_000_000_000L; + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("old", FILE, 1000, 1001, before1980, 1, bytes("x")); + writer.addEntry("pre1970", FILE, 1000, 1001, -1_000_000_000_000L, 1, bytes("z")); + writer.addEntry("future", FILE, 3000000000L, 1001, after2038, 1, bytes("y")); + writer.complete(); + } + + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(dir, part)).get()) { + ZipArchiveEntry old = zip.getEntry("old"); + assertNotNull(old.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + assertNull(zip.getEntry("pre1970").getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + ZipArchiveEntry future = zip.getEntry("future"); + assertNull(future.getExtraField(X5455_ExtendedTimestamp.HEADER_ID)); + assertTrue(future.getTime() > 0); + X7875_NewUnix owner = (X7875_NewUnix) future.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(3000000000L, owner.getUID()); + } + assumeTrue(ArchiveTestSupport.available("bsdtar")); + String listing = ArchiveTestSupport.run(null, "bsdtar", "-tvf", ArchiveTestSupport.merge(dir, part).toString(), "--numeric-owner"); + assertTrue(listing.matches("(?s).*\\b3000000000\\s+1001\\b.*"), listing); + assertTrue(listing.matches("(?s).*\\b1000\\s+1001\\b.*"), listing); + } + + @Test + void copiesHardLinkTargetsUnderTheLinkNameAndKeepsTheirMethod() throws Exception { + Path part = dir.resolve("0.part"); + String text = "video".repeat(500); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("a/clip.mp4", FILE, 1, 2, 1_700_000_000_000L, text.length(), bytes(text)); + writer.addEntry("a/log.txt", FILE, 1, 2, 1_700_000_000_000L, text.length(), bytes(text)); + assertTrue(writer.addCopy("a/clip-link.mp4", "a/clip.mp4")); + assertTrue(writer.addCopy("a/log-link.txt", "a/log.txt")); + assertTrue(writer.addCopy("a/log-link-link.txt", "a/log-link.txt")); + writer.complete(); + assertEquals(5, writer.entryCount()); + } + + Path archive = ArchiveTestSupport.merge(dir, part); + assertEquals(text, ArchiveTestSupport.contents(archive).get("a/clip-link.mp4")); + assertEquals(text, ArchiveTestSupport.contents(archive).get("a/log-link-link.txt")); + try (ZipFile zip = ZipFile.builder().setPath(archive).get()) { + assertEquals(ZipEntry.STORED, zip.getEntry("a/clip-link.mp4").getMethod()); + assertEquals(ZipEntry.DEFLATED, zip.getEntry("a/log-link.txt").getMethod()); + assertEquals(zip.getEntry("a/log.txt").getCrc(), zip.getEntry("a/log-link.txt").getCrc()); + } + } + + @Test + void hardLinksToMissingTargetsFailButSkippedTargetsAreIgnored() throws Exception { + try (var writer = new ZipPartWriter(dir.resolve("0.part"), new ZipCompression(1))) { + add(writer, "a/one", "1"); + writer.markSkipped("a/pipe"); + + assertFalse(writer.addCopy("a/pipe-link", "a/pipe")); + assertThrows(IOException.class, () -> writer.addCopy("a/link", "a/missing")); + assertTrue(writer.contains("a/one")); + assertFalse(writer.contains("a/pipe-link")); + } + } + + @Test + void anEntryShorterThanItsDeclaredSizeFailsAndClosingDiscardsTheIncompletePart() throws Exception { + Path part = dir.resolve("0.part"); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + assertThrows(EOFException.class, () -> writer.addEntry("a", FILE, 1, 1, 0, 10, bytes("short"))); + } + + assertFalse(Files.exists(part)); + assertFalse(Files.exists(ZipPartWriter.partialOf(part))); + assertFalse(Files.exists(ZipPartWriter.indexOf(part))); + } + + @Test + void mergeFailsOnADuplicateNameAcrossPartsAndOnAReservedNameInAServicePart() throws Exception { + Path first = dir.resolve("0.part"); + Path second = dir.resolve("1.part"); + Path snapshot = dir.resolve("snap.part"); + Path live = dir.resolve("live.part"); + for (Path part : List.of(first, second)) { + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + add(writer, "a/same", "x"); + writer.complete(); + } + } + try (var writer = new ZipPartWriter(snapshot, new ZipCompression(1))) { + add(writer, "db/mediagarrd.db", "snapshot"); + writer.complete(); + } + try (var writer = new ZipPartWriter(live, new ZipCompression(1))) { + add(writer, "db/mediagarrd.db-wal", "live"); + writer.complete(); + } + + Path out = dir.resolve("out.zip"); + assertThrows(IOException.class, () -> ZipPartMerger.merge(List.of(), List.of(first, second), out, dir)); + assertThrows(IOException.class, () -> ZipPartMerger.merge(List.of(snapshot), List.of(live), out, dir)); + assertFalse(Files.exists(dir.resolve("merge-names.idx"))); + } + + @Test + void mergeChecksumMatchesTheWrittenFileAndOffsetsSurviveSeveralParts() throws Exception { + Path first = dir.resolve("0.part"); + Path second = dir.resolve("1.part"); + for (Path part : List.of(first, second)) { + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + add(writer, part.getFileName() + "/x", "data " + part.getFileName()); + add(writer, part.getFileName() + "/y.mp4", "stored " + part.getFileName()); + writer.complete(); + } + } + Path out = dir.resolve("out.zip"); + + ZipPartMerger.Result result = ZipPartMerger.merge(List.of(), List.of(first, second), out, dir); + + assertEquals(4, result.entries()); + assertEquals(Files.size(out), result.bytes()); + assertEquals(java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(out))), result.checksum()); + assertEquals("stored 1.part", ArchiveTestSupport.contents(out).get("1.part/y.mp4")); + } + + @Test + @Timeout(120) + void manyEntriesBeyondTheClassicLimitUseZip64AndReadBack() throws Exception { + Path part = dir.resolve("0.part"); + int count = 70_000; + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + for (int i = 0; i < count; i++) { + add(writer, "many/f" + i, Integer.toString(i)); + } + writer.complete(); + } + Path archive = ArchiveTestSupport.merge(dir, part); + + try (ZipFile zip = ZipFile.builder().setPath(archive).get()) { + assertEquals(count, Collections.list(zip.getEntries()).size()); + assertEquals("69999", new String(zip.getInputStream(zip.getEntry("many/f69999")).readAllBytes(), StandardCharsets.UTF_8)); + } + verifyWithTools(archive, count); + } + + @Test + void smallArchiveIsAcceptedByExternalTools() throws Exception { + Path part = dir.resolve("0.part"); + try (var writer = new ZipPartWriter(part, new ZipCompression(1))) { + writer.addEntry("srv/", DIRECTORY, 0, 0, 1_700_000_001_000L, 0, bytes("")); + add(writer, "srv/a.txt", "hello".repeat(100)); + add(writer, "srv/b.mp4", "world".repeat(100)); + assertTrue(writer.addCopy("srv/c.txt", "srv/a.txt")); + writer.complete(); + } + + verifyWithTools(ArchiveTestSupport.merge(dir, part), 4); + } + + static void verifyWithTools(Path archive, int entries) throws Exception { + if (ArchiveTestSupport.available("unzip")) { + String output = ArchiveTestSupport.run(null, "unzip", "-tq", archive.toString()); + assertTrue(output.contains("No errors"), output); + } + if (ArchiveTestSupport.available("bsdtar")) { + assertEquals(entries, ArchiveTestSupport.runCounting(null, "bsdtar", "-tf", archive.toString()).lines()); + assertEquals(entries, ArchiveTestSupport.runCounting(archive, "bsdtar", "-tf", "-").lines()); + } + if (ArchiveTestSupport.available("python3")) { + ArchiveTestSupport.run(null, "python3", "-I", "-m", "zipfile", "-t", archive.toString()); + } + if (ArchiveTestSupport.available("7z")) { + String output = ArchiveTestSupport.run(null, "7z", "t", archive.toString()); + assertTrue(output.contains("Everything is Ok"), output); + } + } +} From 57a3a2450a89f4b7b4f5d9b1dbdd5e1f002c27ee Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sat, 14 Nov 2026 15:25:03 -0600 Subject: [PATCH 24/26] Update docs to reflect new recovery tool --- docs/database.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/database.md b/docs/database.md index d92dab6..4e8cabc 100644 --- a/docs/database.md +++ b/docs/database.md @@ -22,22 +22,30 @@ Never restore over the database of a running server. ```bash docker compose stop ``` -2. Extract the copy into an empty directory: +2. Restore the archive into a new directory with [mgrecover](https://github.com/MediaGarrd/Recovery): + ```bash + curl -fLO https://github.com/MediaGarrd/Recovery/releases/latest/download/mgrecover.sh + chmod +x mgrecover.sh + ./mgrecover.sh -C restore .zip + ``` + `-C` restores the whole archive under `restore` (created if missing), so it can be large. It prints a plan and asks for confirmation (`-y` skips it and is required without a terminal). It creates no symbolic links and writes nothing outside that directory. With `-C`, files are restored without their original owners (they belong to you); step 3 copies the database back as root into the server's existing directory, which keeps its owner and mode. + + To extract only the database instead (this needs the directory to exist): ```bash mkdir restore - bsdtar -xpPf .zip -C restore '' + bsdtar -xpf .zip -C restore '' ``` 3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): ```bash - cp restore/ ./data/server/db/mediagarrd.db - rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm + sudo cp restore/ ./data/server/db/mediagarrd.db + sudo rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm ``` 4. Start the server again: ```bash docker compose start ``` -`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. `-P` lets it extract through symbolic links stored in the archive. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. +mgrecover needs `bsdtar` (the `libarchive-tools` package on Debian and Ubuntu). A full restore with `sudo ./mgrecover.sh .zip` puts back every file in the archive, not only the database, and writes the database to its host path. That is only safe while the server is stopped; remove the `-journal`, `-wal` and `-shm` files as in step 3 before starting the server. ## If the database is damaged The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. From 59536a759cd18b932ec1d96a878010fc9b962366 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 19 Nov 2026 15:18:15 -0600 Subject: [PATCH 25/26] Added auth, code quality refactors --- .dockerignore | 15 +- CHANGELOG | 59 ++ Dockerfile | 3 + README.md | 11 +- build.gradle.kts | 13 +- docs/API.md | 94 ++- docs/database.md | 10 +- docs/https.md | 84 +++ docs/settings.md | 52 +- .../MediaGarrdProperties.java | 1 + .../mediagarrdServer/WebMvcConfig.java | 8 +- .../api/ApiAuthInterceptor.java | 93 +++ .../api/ApiErrorController.java | 30 + .../api/ApiExceptionHandler.java | 123 +++- .../api/BackupController.java | 60 +- .../api/ConfigController.java | 88 +-- .../api/PairingController.java | 67 ++ .../mediagarrdServer/api/PublicEndpoint.java | 15 + .../api/RequestBodyLimitFilter.java | 139 ++++ .../api/RunEventsController.java | 17 +- .../api/SecurityHeadersFilter.java | 44 ++ .../mediagarrdServer/api/SetupController.java | 41 +- .../api/SetupInterceptor.java | 20 +- .../api/SetupSessionAllowed.java | 13 + .../api/VersionController.java | 1 + .../api/WebhookController.java | 54 ++ .../mediagarrdServer/dto/PairRequest.java | 3 + .../mediagarrdServer/dto/PairResponse.java | 3 + .../mediagarrdServer/dto/PairedClientDto.java | 5 + .../mediagarrdServer/dto/PairingCodeDto.java | 5 + .../mediagarrdServer/dto/PublicHealthDto.java | 5 + .../dto/SetupCompleteDto.java | 3 + .../dto/WebhookStatusDto.java | 3 + .../mediagarrdServer/dto/WebhookTestDto.java | 3 + .../dto/WebhookUpdateRequest.java | 9 + .../mediagarrdServer/model/BackupArchive.java | 10 +- .../mediagarrdServer/model/PairedClient.java | 5 + .../model/ServiceDefinition.java | 8 + .../repository/BackupRecordRepository.java | 249 +++++++ .../repository/DatabaseQuarantine.java | 76 ++ .../repository/DatabaseRebuildListener.java | 7 + .../repository/DatabaseSchema.java | 125 ++++ .../repository/PairedClientRepository.java | 59 ++ .../repository/ServiceRepository.java | 70 ++ .../repository/SettingsRepository.java | 26 + .../repository/SqliteDatabase.java | 279 ++++++++ .../service/AttemptLimiter.java | 49 ++ .../service/BackupArchiveService.java | 126 +++- .../service/BackupFailedException.java | 8 + .../service/BackupInProgressException.java | 8 + .../service/BackupNotFoundException.java | 8 + .../service/BackupOrchestratorService.java | 248 +++---- .../service/BackupRunLifecycle.java | 111 +++ .../service/BackupScheduleService.java | 132 +++- .../service/ContainerEnvironment.java | 7 +- .../service/DatabaseRebuildHandler.java | 32 + .../service/DatabaseService.java | 638 ----------------- .../service/DatabaseSnapshotService.java | 5 +- .../service/DockerService.java | 28 +- .../service/LockedOutException.java | 22 + .../service/PairingException.java | 17 + .../service/PairingService.java | 249 +++++++ .../service/RateLimitedException.java | 17 + .../service/RunRejectedException.java | 8 + .../service/RunStatusBroadcaster.java | 34 +- .../service/ServiceConfigService.java | 82 +++ .../service/ServiceConflictException.java | 8 + .../service/ServiceNotFoundException.java | 8 + .../SetupAlreadyCompleteException.java | 8 + .../service/SetupService.java | 183 ++++- .../service/WebhookService.java | 316 +++++++++ .../mediagarrdServer/service/WebhookUrl.java | 68 ++ .../service/ZipPartMerger.java | 15 +- .../utilities/FilePermissions.java | 57 ++ .../utilities/LogSanitizer.java | 24 + .../utilities/MediaGarrdUtils.java | 6 +- .../mediagarrdServer/utilities/Sha256.java | 27 + .../utilities/database/DatabaseQueries.java | 43 ++ .../utilities/database/DatabaseUtils.java | 1 + src/main/resources/application.yml | 1 + src/main/resources/static/config.html | 146 ++-- src/main/resources/static/css/mediagarrd.css | 41 +- src/main/resources/static/index.html | 2 +- src/main/resources/static/js/api.js | 8 +- src/main/resources/static/js/config.js | 12 +- src/main/resources/static/js/settings.js | 17 +- src/main/resources/static/js/setup.js | 59 +- src/main/resources/static/js/webhook.js | 63 ++ .../api/ApiAuthSetupPhaseFullContextTest.java | 226 ++++++ .../api/ApiAuthTokenFullContextTest.java | 288 ++++++++ .../api/ApiExceptionHandlerTest.java | 61 ++ .../mediagarrdServer/api/ApiTestAuth.java | 46 ++ .../api/BackupControllerTest.java | 219 +++++- .../api/ConfigControllerTest.java | 128 ++-- .../api/DtoWireFormatTest.java | 296 ++++++++ .../api/FullContextSupport.java | 42 ++ .../api/PairingControllerTest.java | 142 ++++ .../api/RealServletFullContextTest.java | 171 +++++ .../api/RequestBodyLimitFilterTest.java | 65 ++ .../api/RunEventsControllerTest.java | 67 +- .../api/ScheduleIntervalApiTest.java | 117 ++++ .../api/SetupControllerTest.java | 99 ++- .../api/SetupPageAssetsTest.java | 166 +++++ .../api/VersionControllerTest.java | 27 +- .../api/WebhookControllerTest.java | 217 ++++++ .../model/ServiceDefinitionTest.java | 10 + .../BackupRecordRepositoryTest.java | 96 +++ .../repository/DatabaseTestBase.java | 75 ++ .../PairedClientRepositoryTest.java | 58 ++ .../repository/ServiceRepositoryTest.java | 66 ++ .../repository/SettingsRepositoryTest.java | 21 + .../repository/SqliteDatabaseTest.java | 371 ++++++++++ .../repository/TestDatabase.java | 24 + .../service/ArchiveInteropTest.java | 6 +- .../service/BackupArchiveServiceTest.java | 231 ++++-- .../service/BackupCopyRoundsTest.java | 8 +- .../BackupOrchestratorServiceTest.java | 274 ++++++-- .../service/BackupRunLifecycleTest.java | 128 ++++ .../service/BackupScheduleServiceTest.java | 351 +++++++++- .../service/ContainerEnvironmentTest.java | 8 - .../service/DatabaseHostPathResolverTest.java | 7 - .../service/DatabaseRebuildHandlerTest.java | 178 +++++ .../service/DatabaseServiceTest.java | 488 ------------- .../service/DatabaseSnapshotServiceTest.java | 31 +- .../service/DockerServiceTest.java | 26 +- .../service/MutableClock.java | 31 + .../service/PairingServiceTest.java | 663 ++++++++++++++++++ .../service/PathCoverageTest.java | 5 - .../service/RunStatusBroadcasterTest.java | 19 +- .../service/ServiceBackupRunnerTest.java | 98 +-- .../service/SetupServiceTest.java | 247 ++++++- .../service/SqliteVersionTest.java | 28 + .../service/UpdateCheckServiceTest.java | 52 +- .../service/WebhookServiceTest.java | 633 +++++++++++++++++ .../service/ZipCompressionBindingTest.java | 14 - .../service/ZipCompressionTest.java | 30 +- .../service/ZipPartWriterTest.java | 14 - .../utilities/LogSanitizerTest.java | 29 + .../utilities/NoPolymorphicTypingTest.java | 47 ++ .../utilities/SemVerTest.java | 7 +- 140 files changed, 9664 insertions(+), 2137 deletions(-) create mode 100644 docs/https.md create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/FilePermissions.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java create mode 100644 src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java create mode 100644 src/main/resources/static/js/webhook.js create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java delete mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/SqliteVersionTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/service/WebhookServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdServer/utilities/NoPolymorphicTypingTest.java diff --git a/.dockerignore b/.dockerignore index 7b657fc..6826209 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,9 @@ .git .github +.claude +.jj +ref +vendor .vscode build **/build @@ -17,7 +21,16 @@ install-util.sh install.sh LICENSE README.md -docker-compose.yml.example +docker-compose.example.yml +docker-compose.yml +Makefile .project +.classpath +bin/ +test/ .settings/ .note.xnote +.env +.env.* +**/.env +**/.env.* diff --git a/CHANGELOG b/CHANGELOG index 5fb07d1..479b93e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,64 @@ # CHANGELOG +Everything in this file is part of version 0.1.0, the first release. Entries are grouped by the date they were made. + +## 11-24-26 +- Archives are ordered, listed and pruned by the UTC timestamp in their file name (`yyyyMMdd-HHmmss-SSS-media-backup.zip`) instead of the file's last-modified time, so copying or restoring files no longer changes which archive is the newest or gets deleted by retention; `createdAt` in `GET /api/v1/backups` comes from the same timestamp (millisecond precision), and an archive whose name has no valid timestamp still uses its last-modified time +- If the database is found corrupt while the server is running, it is moved aside and replaced as before, and now setup also reopens without a restart: a new Setup PIN is logged, `/config` works again, paired Clients must pair again (they get `401` until then), open event streams are closed and unconfirmed pairings are dropped, and the backup location, retention and schedule go back to the defaults until set again +- The API docs list the `409` answers for `POST /backups/run` (a run is already in progress, or no services are configured), for `PUT /config` and the service endpoints while a backup is running, and for a service name that already exists +- The start page says the `/config` setup page is only available until setup is finished +- `.dockerignore` skips `bin/`, `.classpath` and `test/` + +## 11-22-26 +- Backup run scratch space is now `.mediagarrd-runs/` inside the backup folder instead of `runs/`, and startup cleanup only removes folders in it and `*-media-backup.zip.tmp` files; a `runs/` folder or other `.zip.tmp` files you keep in the backup folder are left alone +- A finished archive is flushed to disk before it is moved into place and the backup folder is flushed after the move, both before retention deletes any older archive, so a power loss cannot leave a truncated newest archive next to an already deleted good one +- The image has a health check against `/api/v1/health` on `SERVER_PORT` (default `8080`) and `.dockerignore` skips `.claude`, `.jj`, `ref`, `vendor` and the compose files +- Restore docs use `sudo` for `mgrecover` and `bsdtar`, because archives belong to root +- The backup interval must be between 15 minutes and 365 days: `PUT /api/v1/schedule` answers `400` for a missing, zero, negative, shorter or longer value and saves nothing; a stored or `MEDIAGARRD_BACKUP_INTERVAL` value outside that range is ignored with a warning (the default is `PT12H`); the setup page limits the hours field to 0.25 to 8760 +- The pair-before-setup `409` now says `This server has not finished setup yet. Finish it on the server's /config page, then pair.` +- Setup page: the Setup PIN error is red and Finish Setup sits under Configured Services +- `POST /api/v1/setup/complete` answers `200` with `{"pairingPin": "NNNNNN"}` instead of an empty `204` (`pairingPin` is `null` when no PIN applies), and the setup page shows the Pairing PIN with a copy button after Finish Setup; it is still printed in the logs +- Pairing is confirmed by the Client's first request with its token: `POST /pair` creates a pending pairing in memory, and only the first authenticated request with that token stores the client and closes PIN pairing or spends the pairing code. A Client whose reply was lost can pair again with the same PIN or code +- A pending pairing expires after 5 minutes, at most 10 are kept, a restart drops them, and they are not listed or counted as paired clients; if several pair with one PIN or code, the first to confirm wins and the others get `401` +- A pairing code that confirms the first stored client also closes PIN pairing; `POST /setup/complete` answers `410` for a second concurrent finish instead of rotating the PIN, and the setup page disables Finish while it is in flight +- Pairing PIN is checked without resetting the wrong-attempt counter until pairing closes +- Older Clients keep working: they store the token without confirming, and their first request with it (within 5 minutes) confirms the pairing. A new Client confirms against any Server straight away +- No database change + +## 11-21-26 +- Added an optional failure webhook: when a backup run fails or only partly succeeds (scheduled or manual), the server posts a message to a URL you set, so a failed scheduled backup (which only retries after the next interval) is noticed. Set it on the setup page, with `PUT /api/v1/notifications/webhook`, or from the Client; `GET` reports only `configured` and `scheme://host`, and `POST /api/v1/notifications/webhook/test` sends a test (one every 10 seconds, `429` with `Retry-After` otherwise) +- The message is a Discord body (with `allowed_mentions` blocking pings), a Slack body, or a generic JSON body with `event`, `time`, `error`, `failedServices`, `archiveId`, `content` and `text`, chosen by host; it is sent in the background with timeouts, no redirects and no retry, and a failed delivery is only a warning that names the host +- The webhook URL is never returned, logged or echoed in an error, and is kept in plain text in the settings database, so it is also inside backup archives +- Fixed scheduled backups never running on a server restarted more often than its backup interval: the next backup is now due one interval after the last completed or partial backup, and an overdue one runs within about 30 seconds of start +- A server with no completed backup runs its first one soon after setup is finished; while setup is still open, and for installs that never finished setup and have no backup yet, it waits one interval from start +- Changing the backup interval counts from the last completed or partial backup instead of from the change +- Fixed the setup page being wider than a phone screen: grid columns, form rows and notes shrink to the screen and the webhook buttons wrap + +## 11-19-26 +- Every error answers `{"error": ""}`, including `404`, `405` and the missing-backup and delete cases that used Spring's default body; a `5xx` says `Internal error`, except a failed `POST /backups/run`, which keeps the run's failure reason in the `500` body for the Client dashboard +- Request bodies over 64 KiB answer `413`, a service may have at most 32 paths of 4096 characters, and a PIN, code or backup location has a length limit +- Responses carry `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, a `default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'` Content-Security-Policy and `Cache-Control: no-store` (not on the setup page's css and js) +- The setup cookie is `Secure` over HTTPS or `X-Forwarded-Proto: https`, and a setup session expires after 30 minutes without use +- Backup folders and the data folder the server creates are `0700`, archives and the database file `0600`; restore with `sudo` +- Retention deletes only archives the server has a record of; others are kept and listed +- Unpairing the last Client reopens pairing and logs a fresh `Pairing PIN`; opening or closing pairing no longer clears a lockout +- Before setup is finished the `401` message says so +- Fixed a helper container left behind when a stale one was listed after the matching one, and archive ids that dropped every `.zip` in a name +- The setup page keeps the workspace hidden when unlocking fails, shows the lockout wait, labels its path fields and table, shows a visible focus outline and scrolls its table on narrow screens +- Log values from requests have line breaks removed +- After setup, every `/api/v1` endpoint except `GET /health` (reduced), `GET /version`, `GET /setup`, `POST /setup/session` and `POST /pair` needs `Authorization: Bearer `, and anything not on that list is refused by default, including `/events` and backup downloads +- A client gets its token with `POST /api/v1/pair` and the PIN printed in the logs as `Pairing PIN`; the token is returned once, only its SHA-256 hash is stored (new `paired_clients` table), and it is never logged +- When setup is finished the PIN is replaced with a fresh `Pairing PIN`, and it stops working as soon as one client pairs; an install with no paired client (including every install upgraded from an earlier version) prints a `Pairing PIN` on start +- `MEDIAGARRD_OPEN_PAIRING=true` opens pairing with a new PIN on start even when clients are paired, and logs a warning on every start while it is set +- A paired client can create a single-use pairing code valid for 10 minutes (`POST /api/v1/pairing-codes`), list paired clients (`GET /api/v1/clients`), and unpair any client including itself (`DELETE /api/v1/clients/{id}`), which also closes that client's event streams +- Five wrong PINs lock the setup PIN and the pairing PIN together for 10 minutes (`429` with `Retry-After`), and ten wrong pairing codes lock codes separately; the setup PIN had no time lock before +- `GET /api/v1/health` returns only `healthy` and `backupInterval` without a token, the full status with one, and `401` for a token that is not valid +- Setup page endpoints accept the setup session only until setup is finished, and the check no longer depends on the raw URL, so path variants such as `/api/v1/services;x` no longer bypass it +- A request body that is missing or not JSON is answered with `400` and `{"error": "..."}` +- Every response carries `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so the setup page cannot be embedded in another page +- An unexpected failure (HTTP 500) answers with `{"error": "Internal error"}` and keeps the details in the log; a backup run where every service failed still reports its reason +- New `docs/https.md` for running the Server behind nginx or Caddy + ## 11-12-26 - A run rejected before it starts (such as no services configured) publishes no run events - 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 diff --git a/Dockerfile b/Dockerfile index 53332a9..85ec6f6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,9 @@ EXPOSE 8080 ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=50" +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ + CMD curl -fsS -o /dev/null http://127.0.0.1:${SERVER_PORT:-8080}/api/v1/health + ENTRYPOINT ["java", \ "-XX:+UseG1GC", \ "-Xms16m", \ diff --git a/README.md b/README.md index 15ecfeb..9d816f7 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Full documentation, including configuration, archives and restoring, is on the [ - [settings.md](./docs/settings.md): every environment variable and its default. - [API.md](./docs/API.md): every HTTP endpoint and what it returns. - [database.md](./docs/database.md): recovering the server's database from a backup. +- [https.md](./docs/https.md): serving the API over HTTPS behind nginx or Caddy. ## Requirements - A Linux host running Docker with Compose v2 @@ -26,13 +27,21 @@ docker logs mediagarrd-server 2>&1 | grep "Setup PIN" ``` Open `http://:38471/config`, enter the PIN, add the services to back up, and finish setup. +Then pair the [MediaGarrd Client](https://github.com/MediaGarrd/Client). When you press Finish Setup, the page shows a `Pairing PIN` once, with a copy button, and the logs show it too: +```bash +docker logs mediagarrd-server 2>&1 | grep "Pairing PIN" +``` +Enter it in the Client when it asks. The Client receives a token, uses it once to confirm the pairing and sends it with every request, and the PIN stops working once that is done. To pair another Client, create a pairing code from a paired one, or restart the server with `MEDIAGARRD_OPEN_PAIRING=true` to print a new PIN (remove it afterwards). If you are upgrading from a version without pairing, the logs show a `Pairing PIN` on the first start. + ## Updating ```bash git pull docker compose up --build -d ``` -> **Security:** the server mounts `/var/run/docker.sock`, which gives it root-equivalent access to the host, and its API is unauthenticated after setup. Do not expose its port to untrusted networks. +> **Security:** the server mounts `/var/run/docker.sock`, which gives it root-equivalent access to the host. After setup its API needs a token from pairing, but the PIN and token travel in plain text over HTTP, so put it behind HTTPS ([docs/https.md](./docs/https.md)) before exposing it beyond a trusted network. +> +> A paired Client is treated as the owner of the host: it can choose which host paths are backed up and where archives are written. Only pair Clients you trust. Backup folders and archives created by the server are readable by their owner only (the server runs as root), so restore with `sudo`. See [docs/settings.md](./docs/settings.md#security-notes). ## License [MIT](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index c641e5f..afffa02 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,25 +1,22 @@ plugins { java - id("org.springframework.boot") version "3.3.5" - id("io.spring.dependency-management") version "1.1.6" + id("org.springframework.boot") version "4.1.3" + id("io.spring.dependency-management") version "1.1.7" } version = "0.1.0" -extra["httpclient5.version"] = "5.4.4" -extra["httpcore5.version"] = "5.3.4" - repositories { mavenCentral() } dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") - testImplementation("org.xerial:sqlite-jdbc:3.44.0.0") + testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test") testRuntimeOnly("org.junit.platform:junit-platform-launcher") - implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-webmvc") implementation("org.springframework.boot:spring-boot-starter") - implementation("org.xerial:sqlite-jdbc:3.44.0.0") + implementation("org.xerial:sqlite-jdbc:3.54.1.0") implementation("com.github.docker-java:docker-java-core:3.5.1") implementation("com.github.docker-java:docker-java-transport-httpclient5:3.5.1") implementation("org.apache.commons:commons-compress:1.27.1") diff --git a/docs/API.md b/docs/API.md index f6743eb..f23cef3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,41 +1,107 @@ # Server API -All endpoints are under `/api/v1`. Errors are returned as `{"error": "..."}` with a matching status code. +All endpoints are under `/api/v1`. Every error is returned as `{"error": ""}` with a matching status code: a 4xx carries the reason, and a 5xx carries `{"error": "Internal error"}` (the detail is only in the server log), with one exception: a failed `POST /backups/run` answers 500 with the run's failure reason in `error`, because the Client dashboard shows it and a paired Client is the owner. This includes `404` and `405` from the framework (`{"error": "Not Found"}`, `{"error": "Method Not Allowed"}` with an `Allow` header) and `413` for a request body over 64 KiB. Missing backups answer `404` with `Backup not found` or `No backup archives found`. -## Status -| Endpoint | Returns | +Every response carries `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer` and a `Content-Security-Policy` of `default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`, and everything except the setup page's `/css` and `/js` files is sent with `Cache-Control: no-store`. Request limits: 64 KiB per body, 32 paths of at most 4096 characters per service, a backup location of at most 4096 characters, and a PIN or pairing code of at most 64 characters (`400` otherwise). + +## Authentication +After setup, every endpoint except the ones marked open needs the header `Authorization: Bearer `. A client gets its token by pairing (see below). Before setup is finished the `401` message says setup is not finished. A missing, malformed, unknown or revoked token is answered with `401`, `WWW-Authenticate: Bearer` and `{"error": "..."}`. Tokens are never logged and are only ever sent in the reply to `POST /pair`. + +Open endpoints (no token): `GET /health` (reduced, see below), `GET /version`, `GET /setup`, `POST /setup/session`, `POST /pair`. Everything else under `/api/v1`, including paths that do not exist, answers `401` without a token, except that a wrong method on an existing path answers `405` (it reveals only that the route exists). + +Before setup is finished, the setup page's endpoints (`/config`, `/schedule`, `/services`, `/notifications/webhook`, `/setup/complete`) also accept the setup session cookie instead of a token. After setup is finished that cookie is ignored. + +## Pairing +| Endpoint | Auth | Returns | +|---|---|---| +| `POST /pair` | open | `{"token": "...", "id": "...", "name": "..."}` when the body's `pin` is the current pairing PIN or a valid pairing code. The pairing is pending until the token is used (see below). | +| `POST /pairing-codes` | token | `{"code": "ABCDE-FGHJK", "expiresAt": ""}`, a single-use code for pairing another client. | +| `GET /clients` | token | Every paired client as `{"id", "name", "createdAt", "lastUsedAt", "current"}`; `current` is true for the caller. `lastUsedAt` is `null` until first use and is updated at most once a minute. | +| `DELETE /clients/{id}` | token | An empty `204` once that client is unpaired, or `404` for an unknown id. A client may unpair itself with its own id. | + +`POST /pair` takes `{"pin": "<6-digit PIN or pairing code>", "name": ""}`. The label is 1 to 64 characters (letters, digits, spaces and `. _ - ( ) ' @ +`); one is generated when it is left out. The reply carries the token once and the server keeps only its SHA-256 hash. + +The PIN is the one printed in the logs as `Pairing PIN: NNNNNN`. The setup PIN only unlocks the setup page. When setup is finished a new PIN is printed as `Pairing PIN` and is also returned by `POST /setup/complete`, and it works until one client has paired. A server that finished setup earlier prints one on start while no client is paired. A pairing code is created by an already paired client, expires after 10 minutes and works once. + +A successful `POST /pair` creates a pending pairing, kept in memory only. The first authenticated request with the new token (any endpoint, for example `GET /health` with the `Authorization` header) confirms it: only then is the client stored and listed, and only then does the PIN stop working or the pairing code get spent. Until then the same PIN or code can be used again, so a client whose reply was lost simply pairs again. A pending pairing that is not confirmed within 5 minutes is dropped, at most 10 are kept (the oldest is dropped first), and a restart drops them all. Pending pairings are not listed by `GET /clients`, do not count as a paired client, and `DELETE /clients/{id}` answers `404` for them. If several clients pair with the same PIN before any confirms, the first to confirm wins and the others' tokens are then answered with `401`; the same holds for a pairing code. A pairing made with a code is still confirmed if the code expired in the meantime, but not if the code was dropped because 10 newer codes were created. A PIN pairing confirmed after pairing was closed and reopened (the last client was unpaired) is refused. A code pairing that inserts the first confirmed client also closes PIN pairing. + +Statuses of `POST /pair`: +| Status | Meaning | |---|---| -| `GET /health` | The server's health, whether a backup is running, the number of backups to keep, and the time between backups. | -| `GET /version` | The running version and the result of the daily check for a newer GitHub release. | -| `GET /events` | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | +| `200` | Pairing started. Use the token once to confirm it. | +| `400` | The body is missing, is not JSON, has no `pin`, or has an invalid `name`. | +| `401` | The PIN or code is wrong, expired or already used. | +| `403` | Pairing is closed: a client has already confirmed a pairing with the PIN. Use a pairing code, or restart the server with `MEDIAGARRD_OPEN_PAIRING=true`. | +| `409` | Setup is not finished. Finish it at `/config` first. | +| `429` | Locked after too many wrong attempts. `Retry-After` gives the seconds left. | + +Five wrong PINs lock PIN entry (setup page and pairing share this counter) for 10 minutes. Ten wrong pairing codes lock code entry, separately, for 10 minutes. The locks are global, not per address, and a restart clears them. Opening or closing pairing never clears a lock. Anything that is not exactly six digits is treated as a pairing code. + +Unpairing the last paired client reopens pairing: a fresh `Pairing PIN` is logged and `POST /pair` accepts it. This does not clear a lockout, which is independent of whether pairing is open. + +Revoking a client takes effect on its next request and closes that client's open `/events` streams at once. + +## Status +| Endpoint | Auth | Returns | +|---|---|---| +| `GET /health` | open, token optional | Without a token: `{"healthy", "backupInterval"}`. With a valid token: `{"healthy", "running", "backupRetentionCount", "backupInterval"}`. A token that is present but invalid answers `401`. | +| `GET /version` | open | The running version and the result of the daily check for a newer GitHub release. | +| `GET /events` | token | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | ## Setup -| Endpoint | Returns | -|---|---| -| `GET /setup` | Whether first-time setup is finished and whether the caller holds a setup session. | -| `POST /setup/session` | An empty `204` and a setup session cookie when the posted PIN is correct. | -| `POST /setup/complete` | An empty `204` once setup is finished, after which the setup page is disabled. | +| Endpoint | Auth | Returns | +|---|---|---| +| `GET /setup` | open | Whether first-time setup is finished and whether the caller holds a setup session. | +| `POST /setup/session` | open | An empty `204` and a setup session cookie (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS or with `X-Forwarded-Proto: https`; the session ends after 30 minutes without use) when the posted PIN is correct, `401` for a wrong PIN, `410` once setup is finished, `429` while locked. | +| `POST /setup/complete` | setup session | `200` and `{"pairingPin": "NNNNNN"}` once setup is finished, after which the setup page is disabled. A second finish answers `410`, and finishing with no service configured answers `409` with `Add at least one service before finishing setup`. `pairingPin` is `null` when no PIN applies, for example when a client is already paired. The same PIN is printed in the logs as `Pairing PIN`. The reply is the only place the PIN is returned and is sent with `Cache-Control: no-store`. | The setup page itself is served at `GET /config` until setup is finished. ## Configuration +Setup session before setup is finished, token afterwards. + | Endpoint | Returns | |---|---| | `GET /config` | The backup location, the number of backups to keep, and the time between backups. | | `PUT /config` | The updated configuration after changing the backup location and/or the number of backups to keep. | -| `PUT /schedule` | The server status after changing the time between backups. | +| `PUT /schedule` | The server status after changing the time between backups. The interval is an ISO-8601 duration or a number of seconds and must be between 15 minutes and 365 days, both inclusive. A missing, `null`, zero, negative, shorter or longer interval answers `400` with `Backup interval must be between 15 minutes and 365 days` and nothing is saved. | | `GET /services` | Every configured service with its host paths. | | `POST /services` | The added service, with `201`. | | `PUT /services/{name}` | The updated service. | | `DELETE /services/{name}` | An empty `204` once the service is removed. | +Statuses: +| Status | Meaning | +|---|---| +| `409` | `PUT /config`, `POST /services`, `PUT /services/{name}` and `DELETE /services/{name}` answer `Configuration cannot be changed while a backup is running, try again once it finishes` while a backup run is going. `POST /services` also answers `409` with `Service already exists: ` when the name is taken, and so does `PUT /services/{name}` when it renames the service to a name that is taken (the comparison ignores case). | + +## Failure webhook +Setup session before setup is finished, token afterwards. An optional webhook URL that receives a message when a backup run fails or only partly succeeds (scheduled and manual runs). The full URL is a secret (Discord and Slack webhook URLs carry a token), so no endpoint ever returns it: only whether one is set and its `scheme://host[:port]`. + +| Endpoint | Returns | +|---|---| +| `GET /notifications/webhook` | `{"configured": true, "target": "https://discord.com"}`, or `{"configured": false, "target": null}`. | +| `PUT /notifications/webhook` | The same shape as `GET`, after saving. The body is `{"url": "https://..."}`; an empty string, `null` or a missing `url` clears the webhook. | +| `POST /notifications/webhook/test` | `{"delivered": true, "status": 200, "error": null}` after sending a `test` event to the saved URL and waiting up to 5 seconds. When it is not delivered, `delivered` is `false`, `status` is the receiver's HTTP status or `null`, and `error` is a short reason: `Webhook answered 404`, `Timed out`, `Could not connect` or `Delivery failed`. The reply never contains the URL or the receiver's body. | + +Statuses: +| Status | Meaning | +|---|---| +| `200` | Saved, or the test was attempted (check `delivered`). | +| `400` | The URL is not valid (`Webhook URL is not a valid URL`, `must use http or https`, `must not contain user info`, `must not contain a fragment`, `must not contain spaces or control characters`, `must have a valid host name`, `is too long`), or a test was requested with no webhook configured (`No webhook is configured`). | +| `429` | A test was sent less than 10 seconds ago. The limit is global, counts attempts, and `Retry-After` gives the seconds left. | + +A URL must be absolute `http` or `https`, at most 2048 characters, with a host name, without user info (`user:pass@`), a fragment (`#`), or whitespace. A host name with an underscore (for example `http://home_assistant:8123`) is refused: use the IP address or a DNS name. The three message shapes are described in [settings.md](./settings.md#failure-webhook). + ## Backups +Token required. + | Endpoint | Returns | |---|---| -| `GET /backups` | Every archive with its id, file name, size, and creation time. | +| `GET /backups` | Every archive with its id, file name, size, and creation time, newest first. Both the order and the creation time come from the timestamp in the file name (`yyyyMMdd-HHmmss-SSS`, UTC); only an archive whose name has no valid timestamp uses the file's last-modified time. | | `GET /backups/latest` | The newest archive's details. | | `GET /backups/{id}` | One archive's details. | | `GET /backups/latest/download` | The newest archive as a zip file. | | `GET /backups/{id}/download` | One archive as a zip file. | | `DELETE /backups/{id}` | An empty `204` once the archive is deleted. | -| `POST /backups/run` | The run id, start and end time, services that ran, and the new archive, once the backup finishes. | +| `POST /backups/run` | The run id, start and end time, services that ran, and the new archive, once the backup finishes. If the run fails, `500` with the failure reason in `error` (the one 5xx that is not `Internal error`). `409` when a run is already in progress (`A backup run is already in progress`) or when no services are configured (`No services are configured for backup`). | diff --git a/docs/database.md b/docs/database.md index 4e8cabc..acbe951 100644 --- a/docs/database.md +++ b/docs/database.md @@ -2,6 +2,8 @@ Every backup archive contains a consistent copy of the server's own database: its settings, services, and backup records. The copy is taken while no other database operation runs, so it is never half written. It does not contain the record of the run that created it. +The database also holds the paired clients (name, creation and last-use time, and a SHA-256 hash of each token). Tokens themselves are never stored, so an archive cannot be used to sign in, but it does keep clients that were paired when it was taken. Restoring an old copy therefore brings back clients that were unpaired since, and their tokens work again. After a restore, check `GET /api/v1/clients` and unpair anything that should be gone, or pair again with `MEDIAGARRD_OPEN_PAIRING=true`. + ## Where the copy is in the archive The copy sits at the database file's absolute host path, without the leading `/`. With the example `docker-compose.yml`, which mounts `./data/server/db` at `/var/lib/mediagarrd/db`, that is something like: ``` @@ -26,14 +28,14 @@ Never restore over the database of a running server. ```bash curl -fLO https://github.com/MediaGarrd/Recovery/releases/latest/download/mgrecover.sh chmod +x mgrecover.sh - ./mgrecover.sh -C restore .zip + sudo ./mgrecover.sh -C restore .zip ``` - `-C` restores the whole archive under `restore` (created if missing), so it can be large. It prints a plan and asks for confirmation (`-y` skips it and is required without a terminal). It creates no symbolic links and writes nothing outside that directory. With `-C`, files are restored without their original owners (they belong to you); step 3 copies the database back as root into the server's existing directory, which keeps its owner and mode. + `-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 (with `sudo` they belong to root); 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 .zip -C restore '' + sudo bsdtar -xpf .zip -C restore '' ``` 3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): ```bash @@ -48,4 +50,4 @@ Never restore over the database of a running server. mgrecover needs `bsdtar` (the `libarchive-tools` package on Debian and Ubuntu). A full restore with `sudo ./mgrecover.sh .zip` puts back every file in the archive, not only the database, and writes the database to its host path. That is only safe while the server is stopped; remove the `-journal`, `-wal` and `-shm` files as in step 3 before starting the server. ## If the database is damaged -The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. +The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server carries on with no settings, services or paired clients. This also happens while the server is running: the server then behaves as it does on a first start, without a restart. Setup opens again, a new `Setup PIN` is written to the log (look for the `The database was damaged` line), pairing and the web setup page at `/config` work as on a fresh install, and every Client that was paired gets `401` until it is paired again. The backup location, retention count and backup schedule are read again from the new database, so they go back to the defaults (or the `MEDIAGARRD_` environment values) until you set them again. Open event streams are closed, pairings that had not been confirmed are dropped, and a backup that is running at that moment is not stopped. Restore a copy from the newest archive as above to get your settings back (stop the server first), or use the new Setup PIN to configure the server again. diff --git a/docs/https.md b/docs/https.md new file mode 100644 index 0000000..6fe251d --- /dev/null +++ b/docs/https.md @@ -0,0 +1,84 @@ +# HTTPS + +The Server speaks plain HTTP. To serve it over HTTPS, put a reverse proxy in front of it. This matters because the PIN and the token travel in plain text over HTTP. On a network you do not control, use HTTPS. The Client has its own page for the dashboard side: [Client docs/https.md](https://github.com/MediaGarrd/Client/blob/main/docs/https.md). + +The Server has no built-in TLS settings. + +## 1. Keep the plain port private +`docker-compose.example.yml` publishes the Server with `"38471:38471"`. Remove that mapping so the plain port is not reachable from outside, and put the Server and the proxy on a shared Docker network. The proxy reaches it by container name. + +```yaml +services: + mediagarrd-server: + build: + context: . + dockerfile: Dockerfile + container_name: mediagarrd-server + environment: + - SERVER_PORT=38471 + - MEDIAGARRD_BACKUP_INTERVAL=PT12H + - MEDIAGARRD_RETENTION_COUNT=10 + volumes: + - "./data/server/backups:/var/lib/mediagarrd/backups" + - "./data/server/db:/var/lib/mediagarrd/db" + - /var/run/docker.sock:/var/run/docker.sock + networks: + - proxy + restart: unless-stopped + +networks: + proxy: + name: proxy +``` + +Run the proxy on the same network (`proxy`) and send traffic to `mediagarrd-server:38471`. The Server's `/config` setup page is also served through the proxy, so do the first setup over HTTPS too. + +## 2. Reverse proxy examples +Both examples assume the proxy is a container on the `proxy` network and the Server is reached at `https://mediagarrd.example.com`. + +### Caddy +Caddy gets and renews a certificate by itself for a public domain. +``` +mediagarrd.example.com { + reverse_proxy mediagarrd-server:38471 { + flush_interval -1 + } +} +``` +`flush_interval -1` sends the live event stream (`/api/v1/events`) through immediately. Caddy sets no time limit on a response, so large backup downloads are not cut off. + +### nginx +```nginx +server { + listen 443 ssl http2; + server_name mediagarrd.example.com; + + ssl_certificate /etc/ssl/mediagarrd/fullchain.pem; + ssl_certificate_key /etc/ssl/mediagarrd/privkey.pem; + + location / { + proxy_pass http://mediagarrd-server:38471; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} +``` +- On nginx 1.25.1 or newer, `http2 on;` as its own directive replaces the `http2` parameter on `listen`; the parameter still works there but is deprecated. +- `proxy_buffering off` lets the event stream through and avoids writing multi-gigabyte archives to the proxy's disk. +- The one-hour timeouts keep a slow download from being cut off, and a backup run started through the API (`POST /api/v1/backups/run`) waits for the backup to finish, which can take a while. Raise them if your backups take longer. +- The Authorization header is passed to the Server by default. + +## 3. Connect the Client +Give the Client the `https://` address, for example `https://mediagarrd.example.com`. Without a port it uses 443. A token is tied to the exact address it was paired on, so switching from `http://:38471` to `https://...` means pairing again with a PIN or a pairing code. + +The Client does not follow redirects when it talks to the Server, so a proxy rule that redirects HTTP to HTTPS makes an `http://` address fail. For a Server that is already selected the dashboard reports the address the redirect points to; while connecting ("Connect by IP" or `MEDIAGARRD_SERVER_IP`) you only see that no server was found. Use the `https://` address. + +### Certificates from your own authority or self-signed +A certificate from a public authority (Let's Encrypt, Caddy's automatic certificates, Tailscale) needs nothing extra. For a private or self-signed certificate, give the Client the certificate authority with `MEDIAGARRD_SERVER_CA`, described in the Client's [docs/https.md](https://github.com/MediaGarrd/Client/blob/main/docs/https.md). If you reach the Server by IP address, the certificate needs that IP in its Subject Alternative Names. + +## Tailscale +If both machines are on the same tailnet, `tailscale serve` or a Tailscale certificate for the machine name gives you HTTPS without exposing anything to the internet. diff --git a/docs/settings.md b/docs/settings.md index 30dfbad..01605a2 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -5,16 +5,66 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | Variable | Default | What it does | |---|---|---| | `SERVER_PORT` | `8080` (`38471` in the example compose file) | The port of the API and setup page. Change the `ports` mapping to match. | -| `MEDIAGARRD_BACKUP_INTERVAL` | `PT12H` | The time between scheduled backups. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. | +| `MEDIAGARRD_BACKUP_INTERVAL` | `PT12H` | The time between scheduled backups, from `PT15M` (15 minutes) to `P365D` (365 days). A value outside that range is ignored with a warning and `PT12H` is used, and a stored value outside it is ignored the same way. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. The next backup is due one interval after the last completed or partial backup (a failed run does not count), so restarting the server does not postpone it: an overdue backup runs within about 30 seconds of start. A server with no completed backup yet runs its first one soon after setup is finished, or one interval after start while setup is still open. Deleting the newest archive also removes its record, so after a restart or an interval change the schedule counts from the previous backup. | | `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_OPEN_PAIRING` | `false` | Set to `true` to open pairing on start and print a new `Pairing PIN` in the logs even when clients are already paired. A warning is logged on every start while it is set, so remove it once the new client is paired. | | `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. | | `MEDIAGARRD_UPDATE_CHECK_INTERVAL` | `PT24H` | How often the release check runs. Minimum `PT1H`. | +## Failure webhook +An optional URL that gets a message when a backup run ends `failed` or `partial`, so a failed scheduled backup (which only retries after the next interval) does not go unnoticed. Set it on the setup page, through `PUT /api/v1/notifications/webhook` (see [API.md](./API.md#failure-webhook)), or from the Client dashboard. It is stored in the settings table; empty means disabled. Use the **Send Test** button or `POST /api/v1/notifications/webhook/test` to check it. + +When it is sent: +- `backup.failed`: every service failed (no archive), a run ended with no service completed, or the run threw after it started (for example the archive could not be written; the message is the exception text). +- `backup.partial`: some services, or only the database snapshot, failed. The archive was created. +- Not sent on a successful run, on a run that is rejected (one already running, no services configured), or on an error before the run starts (for example the service list could not be read). +- `test`: only from the test endpoint. + +The message is sent once, in the background, so it never slows or fails the backup: one attempt, 5 seconds to connect, 10 seconds in total, redirects are not followed, and a failed delivery is only logged as a warning with the host name (never the path or query). At most 16 messages wait in the queue; more are dropped with a warning. Clearing the webhook stops messages not yet sent. + +The body depends on the host, because Discord and Slack do not document how they treat unknown fields: +- `discord.com`, `discordapp.com` and their subdomains: `{"content": "...", "allowed_mentions": {"parse": []}}`. The reason is placed in an inline code span, and `allowed_mentions` stops `@everyone`, `@here` and role or user pings. +- `hooks.slack.com`, and a Discord URL whose path ends in `/slack` (Discord's Slack-compatible endpoint): `{"text": "..."}` with `&`, `<` and `>` escaped. Discord's `/github` endpoint expects GitHub's payloads and is not supported; use the plain webhook URL. +- Any other host (n8n, Home Assistant, ntfy and so on): `{"event", "time", "error", "failedServices", "archiveId", "content", "text"}`. `event` is `backup.failed`, `backup.partial` or `test`, `time` is ISO-8601 UTC (the run's end time, or the moment of the event for an error or a test), `error` is the run's failure reason (one line per service joined with `; `, at most 1000 characters, `null` for a test), `failedServices` lists the service names (empty when not applicable), `archiveId` is present whenever the run created an archive (a partial run, or a failed one that still produced an archive) and omitted otherwise, and `content` and `text` hold the same short message. There is no server name field. + +Every message is at most 1900 characters, has line breaks removed, and has `@` and `<` followed by a zero-width space so no mention or link markup is active. + +Security notes for the webhook: +- **The URL is a secret.** It is never returned by the API (only `scheme://host`), never logged and never part of an error message. It is stored in plain text in the settings database, which is included in the database snapshot inside every backup archive. If an archive leaks, rotate the webhook. +- **Private addresses are allowed on purpose.** Only the owner (the setup session or a paired Client) can set the URL, and people run ntfy or Home Assistant on their LAN, so the server does not block loopback, private or link-local addresses. Redirects are not followed and the test reply carries only the status code, so the test cannot be used to read a response from an internal service. +- **Error text goes to the receiver.** Service names and failure reasons (paths, Docker messages) are sent to whatever you configure. +- The test is limited to one every 10 seconds. +- Host names with an underscore are refused because the JDK HTTP client cannot reach them either. + +## Pairing +Once setup is finished the API needs a token, which a client gets by pairing with a PIN (see [API.md](./API.md#pairing)). +- A new install prints a `Setup PIN` for the `/config` page. When setup is finished, a fresh `Pairing PIN` is shown on the setup page (with a copy button, once) and printed in the logs. It works until one client has paired: the pairing is confirmed when the Client first uses its token, which the Client does straight away. +- An install that finished setup before pairing existed, or that has no paired client, prints a `Pairing PIN` on every start until a client pairs. +- To pair another client, either create a pairing code from a paired client (valid for 10 minutes, one use), or restart the server with `MEDIAGARRD_OPEN_PAIRING=true` and read the new PIN from the logs: `docker logs mediagarrd-server 2>&1 | grep "Pairing PIN"`. Remove the variable afterwards. +- Five wrong PINs lock PIN entry for 10 minutes. Restarting the server clears the lock. +- A paired client can be unpaired from the API (`DELETE /api/v1/clients/{id}`) or the Client. When the last client is unpaired, pairing reopens and a fresh `Pairing PIN` is logged. + +Serve the API over HTTPS when it is reachable beyond a network you trust, because the token and the PIN travel in plain text over HTTP. See [https.md](./https.md). + +## Security notes +- **A paired Client is the owner.** Once paired, a Client can add services with any absolute host path (except `/`), which the server bind-mounts read-only into a helper container and archives, and it can set the backup location to any path the server can write. Treat a pairing PIN or code like a root credential for the host, and unpair Clients you no longer use. +- **The server runs as root** and mounts `/var/run/docker.sock`, which is root-equivalent on the host. This is by design and is not changed by the app. +- **Permissions.** Directories the server creates (the backup folder, `.mediagarrd-runs/`, the data folder) are `0700`, and archives and the database file are `0600`, where the file system supports POSIX permissions. Existing directories you chose are never changed, and archives made by earlier versions keep their mode. Because the files belong to root, read or restore them with `sudo` (for example `sudo mgrecover ...` or `sudo bsdtar -xf `). +- **Retention only deletes archives the server recorded.** An old archive with no database record (left from before an upgrade, or after a database was moved aside as corrupt) is kept and still listed. The same applies to an archive whose record could not be written (the server logs "this archive will not be pruned"); such archives are never deleted automatically. Delete it by hand or with `DELETE /api/v1/backups/{id}`. +- **SQLite side files.** The database file is `0600`, but its `-journal` and `-wal` files follow the process umask, and a data folder that already existed keeps its mode. They hold token hashes and settings only; restrict the data folder itself (`chmod 700`) if others share the host. +- **PINs are logged** in plain text by design, so protect the container logs. The Pairing PIN is also returned once in the reply to Finish Setup. +- **The PIN stays usable until a Client confirms.** After a correct PIN it keeps working; an unconfirmed pairing is dropped after 5 minutes. Several Clients may pair meanwhile and only the first to confirm is kept. The Client stores its token before confirming, so a confirmation whose replies were lost is completed by its next request and never leaves the Client unpaired; if the pending pairing expired first, the Client is asked to pair again and the PIN is still open. A correct PIN does not reset the wrong-attempt counter until pairing closes. A lockout that rotates the PIN does not cancel a pairing already started with the old one. +- **Lockouts are global.** Anyone who can reach the port can lock PIN entry for 10 minutes by sending wrong PINs, and the PIN is replaced when that happens. This is an accepted trade-off; restart the server or wait to recover. +- **Unpairing the last Client reopens pairing** and prints a fresh `Pairing PIN` in the logs, so the server is never stranded. +- **Limits.** Request bodies over 64 KiB are refused with `413`. A service has at most 32 paths of at most 4096 characters, and a PIN or code is at most 64 characters. +- **Setup sessions** expire after 30 minutes without use, and the setup cookie is `Secure` when the request is HTTPS or carries `X-Forwarded-Proto: https`. +- **Pairing codes:** creating one when 10 are open drops the oldest, so a paired Client can invalidate another's code. + To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: - `./data/server/backups`: the archives. - `./data/server/db`: the database, which holds every setting and service. Keep it on persistent storage. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 41ea9c5..b9a7254 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -21,4 +21,5 @@ public class MediaGarrdProperties { private String updateRepository = "MediaGarrd/Server"; private String githubApiBaseUrl = "https://api.github.com"; private Duration updateCheckInterval = Duration.ofHours(24); + private boolean openPairing = false; } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java index 2d12820..7d9e83c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java @@ -5,15 +5,18 @@ import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import wellatleastitried.mediagarrdServer.api.ApiAuthInterceptor; import wellatleastitried.mediagarrdServer.api.SetupInterceptor; @Configuration public class WebMvcConfig implements WebMvcConfigurer { private final SetupInterceptor setupInterceptor; + private final ApiAuthInterceptor apiAuthInterceptor; - public WebMvcConfig(SetupInterceptor setupInterceptor) { + public WebMvcConfig(SetupInterceptor setupInterceptor, ApiAuthInterceptor apiAuthInterceptor) { this.setupInterceptor = setupInterceptor; + this.apiAuthInterceptor = apiAuthInterceptor; } @Override @@ -23,6 +26,7 @@ public void addViewControllers(ViewControllerRegistry registry) { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(setupInterceptor); + registry.addInterceptor(setupInterceptor).addPathPatterns(SetupInterceptor.SETUP_PAGE_PATTERNS); + registry.addInterceptor(apiAuthInterceptor).addPathPatterns("/api/v1/**"); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java new file mode 100644 index 0000000..0b16d7b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java @@ -0,0 +1,93 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.util.Locale; +import java.util.Map; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; + +import tools.jackson.databind.json.JsonMapper; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Component +public class ApiAuthInterceptor implements HandlerInterceptor { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + static final String CLIENT_ID_ATTRIBUTE = "mediagarrd.clientId"; + private static final String BEARER_PREFIX = "bearer "; + private static final String SETUP_MESSAGE = "Setup session required, reload /config and enter the PIN from the server logs"; + private static final String UNFINISHED_MESSAGE = "Setup is not finished, open /config and finish it first, then pair this client"; + private static final String MISSING_MESSAGE = "Authorization required, pair this client and send Authorization: Bearer "; + private static final String INVALID_MESSAGE = "Invalid or revoked token, pair this client again"; + + private final SetupService setup; + private final PairingService pairing; + + public ApiAuthInterceptor(SetupService setup, PairingService pairing) { + this.setup = setup; + this.pairing = pairing; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + if (request.getDispatcherType() != DispatcherType.REQUEST) { + return true; + } + HandlerMethod method = handler instanceof HandlerMethod handlerMethod ? handlerMethod : null; + PublicEndpoint open = method == null ? null : method.getMethodAnnotation(PublicEndpoint.class); + boolean setupAllowed = method != null && method.hasMethodAnnotation(SetupSessionAllowed.class); + String header = request.getHeader(HttpHeaders.AUTHORIZATION); + + if (open != null && (!open.tokenOptional() || header == null)) { + return true; + } + boolean setupOpen = setupAllowed && !setup.isCompleted(); + if (setupOpen && setup.canConfigure(SetupInterceptor.sessionToken(request))) { + return true; + } + if (header == null) { + return reject(response, rejection(setupAllowed, MISSING_MESSAGE)); + } + String token = bearerToken(header); + PairedClient client = token == null ? null : pairing.authenticate(token).orElse(null); + if (client == null) { + return reject(response, INVALID_MESSAGE); + } + request.setAttribute(CLIENT_ID_ATTRIBUTE, client.id()); + return true; + } + + private String rejection(boolean setupAllowed, String pairedMessage) { + if (setup.isCompleted()) { + return pairedMessage; + } + return setupAllowed ? SETUP_MESSAGE : UNFINISHED_MESSAGE; + } + + private static String bearerToken(String header) { + String value = header.strip(); + if (value.length() <= BEARER_PREFIX.length() || !value.toLowerCase(Locale.ROOT).startsWith(BEARER_PREFIX)) { + return null; + } + return value.substring(BEARER_PREFIX.length()).strip(); + } + + private static boolean reject(HttpServletResponse response, String message) throws IOException { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", message))); + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java new file mode 100644 index 0000000..c6d4ca6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java @@ -0,0 +1,30 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.util.Map; + +import org.springframework.boot.webmvc.error.ErrorController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; + +@RestController +public class ApiErrorController implements ErrorController { + + @RequestMapping("/error") + public ResponseEntity> error(HttpServletRequest request) { + HttpStatus status = statusOf(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)); + return ApiExceptionHandler.error(status, status.is4xxClientError() ? status.getReasonPhrase() : ApiExceptionHandler.INTERNAL_ERROR); + } + + private static HttpStatus statusOf(Object code) { + if (code == null) { + return HttpStatus.NOT_FOUND; + } + HttpStatus status = code instanceof Integer value ? HttpStatus.resolve(value) : null; + return status != null && status.isError() ? status : HttpStatus.INTERNAL_SERVER_ERROR; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java index fb33dbc..33c4dc6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java @@ -1,37 +1,148 @@ package wellatleastitried.mediagarrdServer.api; +import java.io.EOFException; +import java.time.Duration; import java.util.Map; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.ErrorResponse; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; -import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.BackupInProgressException; -import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.RunRejectedException; +import jakarta.servlet.http.HttpServletResponse; + +import wellatleastitried.mediagarrdServer.service.BackupFailedException; +import wellatleastitried.mediagarrdServer.service.BackupInProgressException; +import wellatleastitried.mediagarrdServer.service.BackupNotFoundException; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingException; +import wellatleastitried.mediagarrdServer.service.RateLimitedException; +import wellatleastitried.mediagarrdServer.service.RunRejectedException; +import wellatleastitried.mediagarrdServer.service.ServiceConflictException; +import wellatleastitried.mediagarrdServer.service.ServiceNotFoundException; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @RestControllerAdvice public class ApiExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class); + static final String INTERNAL_ERROR = "Internal error"; @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) public ResponseEntity> handle(RuntimeException e) { HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST : e instanceof RunRejectedException || e instanceof BackupInProgressException ? HttpStatus.CONFLICT : HttpStatus.INTERNAL_SERVER_ERROR; - if (status.is5xxServerError()) { + if (e instanceof BackupFailedException) { LOGGER.error("Request failed: {}", e.getMessage()); - } else { - LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(status, e.getMessage()); + } + if (status.is5xxServerError()) { + LOGGER.error("Request failed", e); + return error(status, INTERNAL_ERROR); } + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); return error(status, e.getMessage()); } + @ExceptionHandler(ServiceConflictException.class) + public ResponseEntity> serviceConflict(ServiceConflictException e) { + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); + return error(HttpStatus.CONFLICT, e.getMessage()); + } + + @ExceptionHandler({ServiceNotFoundException.class, BackupNotFoundException.class}) + public ResponseEntity> notFound(RuntimeException e) { + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); + return error(HttpStatus.NOT_FOUND, e.getMessage()); + } + + @ExceptionHandler(LockedOutException.class) + public ResponseEntity> locked(LockedOutException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return tooManyRequests(e.getMessage(), e.retryAfter()); + } + + @ExceptionHandler(RateLimitedException.class) + public ResponseEntity> rateLimited(RateLimitedException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return tooManyRequests(e.getMessage(), e.retryAfter()); + } + + private static ResponseEntity> tooManyRequests(String message, Duration retryAfter) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(Math.max(1, retryAfter.toSeconds()))) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("error", message)); + } + + @ExceptionHandler(PairingException.class) + public ResponseEntity> pairingRejected(PairingException e) { + HttpStatus status = switch (e.reason()) { + case SETUP_INCOMPLETE -> HttpStatus.CONFLICT; + case CLOSED -> HttpStatus.FORBIDDEN; + case INVALID -> HttpStatus.UNAUTHORIZED; + }; + LOGGER.warn("Rejected pairing request: {}", LogSanitizer.clean(e.getMessage())); + return error(status, e.getMessage()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> unreadableBody(HttpMessageNotReadableException e) { + return error(HttpStatus.BAD_REQUEST, "Request body is missing or not valid JSON"); + } + + @ExceptionHandler(TypeMismatchException.class) + public ResponseEntity> badParameter(TypeMismatchException e) { + return error(HttpStatus.BAD_REQUEST, "Request parameter is not valid"); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> unexpected(Exception e, HttpServletResponse response) { + if (response.isCommitted()) { + if (isClientGone(e)) { + LOGGER.debug("Request ended after the response was started: {}", e.toString()); + } else { + LOGGER.warn("Request failed after the response was started", e); + } + return null; + } + if (e instanceof ErrorResponse rejected && rejected.getStatusCode().is4xxClientError()) { + HttpStatus status = HttpStatus.valueOf(rejected.getStatusCode().value()); + LOGGER.warn("Rejected request: {}", status.getReasonPhrase()); + return ResponseEntity.status(status) + .headers(rejected.getHeaders()) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("error", status.getReasonPhrase())); + } + LOGGER.error("Request failed", e); + HttpStatus status = e instanceof ErrorResponse failed && failed.getStatusCode().is5xxServerError() + ? HttpStatus.valueOf(failed.getStatusCode().value()) + : HttpStatus.INTERNAL_SERVER_ERROR; + return error(status, INTERNAL_ERROR); + } + + private static boolean isClientGone(Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.getCause() == cause ? null : cause.getCause()) { + if (cause instanceof AsyncRequestNotUsableException || cause instanceof AsyncRequestTimeoutException + || cause instanceof EOFException || cause.getClass().getSimpleName().equals("ClientAbortException")) { + return true; + } + } + return false; + } + static ResponseEntity> error(HttpStatus status, String message) { - return ResponseEntity.status(status).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); + return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 0158ca2..1008f52 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -11,7 +11,7 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; +import org.springframework.http.ContentDisposition; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -19,20 +19,23 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; import wellatleastitried.mediagarrdServer.dto.BackupDto; import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.PublicHealthDto; import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupNotFoundException; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @RestController @RequestMapping("/api/v1") @@ -50,12 +53,17 @@ public BackupController(BackupArchiveService archiveService, BackupOrchestratorS this.broadcaster = broadcaster; } + @PublicEndpoint(tokenOptional = true) @GetMapping("/health") - public ServerStatusDto health() { + public Object health(@RequestAttribute(name = ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE, required = false) String clientId) { LOGGER.debug("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + if (clientId == null) { + return new PublicHealthDto(true, orchestratorService.getInterval()); + } return status(orchestratorService.getInterval()); } + @SetupSessionAllowed @PutMapping("/schedule") public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); @@ -75,46 +83,44 @@ public List listBackups() { @GetMapping("/backups/latest") public BackupDto latestBackup() { - LOGGER.info("GET /api/v1/backups/latest"); + LOGGER.debug("GET /api/v1/backups/latest"); BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("No backup archives found")); - LOGGER.info("Latest backup: {}", archive.fileName()); + .orElseThrow(() -> new BackupNotFoundException("No backup archives found")); + LOGGER.debug("Latest backup: {}", archive.fileName()); return toDto(archive); } @GetMapping("/backups/{id}") public BackupDto backupById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}", id); + LOGGER.debug("GET /api/v1/backups/{}", LogSanitizer.clean(id)); return archiveService.byId(id) .map(this::toDto) - .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); + .orElseThrow(() -> new BackupNotFoundException("Backup not found")); } @GetMapping("/backups/{id}/download") public ResponseEntity downloadById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}/download", id); + LOGGER.debug("GET /api/v1/backups/{}/download", LogSanitizer.clean(id)); BackupArchive archive = archiveService.byId(id) - .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); + .orElseThrow(() -> new BackupNotFoundException("Backup not found")); return downloadResponse(archive); } @GetMapping("/backups/latest/download") public ResponseEntity downloadLatest() { - LOGGER.info("GET /api/v1/backups/latest/download"); + LOGGER.debug("GET /api/v1/backups/latest/download"); BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); + .orElseThrow(() -> new BackupNotFoundException("No backup archives found")); return downloadResponse(archive); } @DeleteMapping("/backups/{id}") public ResponseEntity deleteBackup(@PathVariable String id) { - LOGGER.info("DELETE /api/v1/backups/{}", id); - boolean deleted = archiveService.deleteById(id); - if (!deleted) { - LOGGER.warn("Delete failed: backup not found: {}", id); - return ResponseEntity.notFound().build(); + LOGGER.info("DELETE /api/v1/backups/{}", LogSanitizer.clean(id)); + if (!archiveService.deleteById(id)) { + throw new BackupNotFoundException("Backup not found"); } - LOGGER.info("Backup deleted: {}", id); + LOGGER.info("Backup deleted: {}", LogSanitizer.clean(id)); broadcaster.publishBackupsChanged(); return ResponseEntity.noContent().build(); } @@ -139,20 +145,19 @@ public BackupRunDto runBackup() { private ResponseEntity downloadResponse(BackupArchive archive) { Resource file = new FileSystemResource(archive.path()); if (!file.exists()) { - LOGGER.error("Archive file missing on disk: {}", archive.path()); - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); + LOGGER.error("Archive file missing on disk: {}", LogSanitizer.clean(archive.path())); + throw new BackupNotFoundException("Backup file missing on disk"); } try { LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") + .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(archive.fileName()).build().toString()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(file.contentLength()) .body(file); } catch (IOException e) { - LOGGER.error("Failed to read backup file: {}", archive.path(), e); - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); + throw new IllegalStateException("Failed to read backup file", e); } } @@ -163,13 +168,4 @@ private ServerStatusDto status(Duration interval) { private BackupDto toDto(BackupArchive archive) { return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); } - - private ResponseStatusException notFound(String logMessage) { - return notFound(logMessage, logMessage); - } - - private ResponseStatusException notFound(String logMessage, String responseMessage) { - LOGGER.warn(logMessage); - return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java index 420e896..f152815 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -1,9 +1,6 @@ package wellatleastitried.mediagarrdServer.api; -import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; - import java.util.List; -import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,9 +20,10 @@ import wellatleastitried.mediagarrdServer.model.ServiceDefinition; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; -import wellatleastitried.mediagarrdServer.service.DatabaseService; -import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.BackupRunLifecycle; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.ServiceConfigService; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @RestController @RequestMapping("/api/v1") @@ -35,34 +33,36 @@ public class ConfigController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestrator; - private final DatabaseService db; - private final DockerService docker; + private final BackupRunLifecycle lifecycle; + private final ServiceConfigService serviceConfig; private final RunStatusBroadcaster broadcaster; public ConfigController( BackupArchiveService archiveService, BackupOrchestratorService orchestrator, - DatabaseService db, - DockerService docker, + BackupRunLifecycle lifecycle, + ServiceConfigService serviceConfig, RunStatusBroadcaster broadcaster ) { this.archiveService = archiveService; this.orchestrator = orchestrator; - this.db = db; - this.docker = docker; + this.lifecycle = lifecycle; + this.serviceConfig = serviceConfig; this.broadcaster = broadcaster; } + @SetupSessionAllowed @GetMapping("/config") public ServerConfigDto config() { - LOGGER.info("GET /api/v1/config"); + LOGGER.debug("GET /api/v1/config"); return currentConfig(); } + @SetupSessionAllowed @PutMapping("/config") public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { - LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", request.backupLocation(), request.retentionCount()); - return orchestrator.whileIdle(() -> { + LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", LogSanitizer.clean(request.backupLocation()), request.retentionCount()); + return lifecycle.whileIdle(() -> { archiveService.updateSettings(request.backupLocation(), request.retentionCount()); if (request.backupLocation() != null) { broadcaster.publishBackupsChanged(); @@ -72,63 +72,35 @@ public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { }); } + @SetupSessionAllowed @GetMapping("/services") public List services() { - LOGGER.info("GET /api/v1/services"); - return db.fetchServices(); + LOGGER.debug("GET /api/v1/services"); + return serviceConfig.list(); } + @SetupSessionAllowed @PostMapping("/services") - public ResponseEntity addService(@RequestBody ServiceDefinition request) { + public ResponseEntity addService(@RequestBody ServiceDefinition request) { ServiceDefinition service = request.validate(); - LOGGER.info("POST /api/v1/services, name={}, paths={}", service.name(), service.paths()); - return orchestrator.whileIdle(() -> { - if (db.fetchService(service.name()).isPresent()) { - return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); - } - db.addService(service); - orchestrator.servicesChanged(); - broadcaster.publishConfigChanged(); - return ResponseEntity.status(HttpStatus.CREATED).body(service); - }); + LOGGER.info("POST /api/v1/services, name={}, paths={}", LogSanitizer.clean(service.name()), LogSanitizer.clean(service.paths())); + return ResponseEntity.status(HttpStatus.CREATED).body(serviceConfig.add(service)); } + @SetupSessionAllowed @PutMapping("/services/{name}") - public ResponseEntity updateService(@PathVariable String name, @RequestBody ServiceDefinition request) { + public ResponseEntity updateService(@PathVariable String name, @RequestBody ServiceDefinition request) { ServiceDefinition service = request.validate(); - LOGGER.info("PUT /api/v1/services/{}, name={}, paths={}", name, service.name(), service.paths()); - return orchestrator.whileIdle(() -> { - Optional existing = db.fetchService(name); - if (existing.isEmpty()) { - return error(HttpStatus.NOT_FOUND, "Service not found: " + name); - } - String currentName = existing.get().name(); - if (!service.name().equalsIgnoreCase(currentName) && db.fetchService(service.name()).isPresent()) { - return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); - } - db.updateService(currentName, service); - if (!service.name().equals(currentName)) { - docker.removeContainers(currentName); - } - orchestrator.servicesChanged(); - broadcaster.publishConfigChanged(); - return ResponseEntity.ok(service); - }); + LOGGER.info("PUT /api/v1/services/{}, name={}, paths={}", LogSanitizer.clean(name), LogSanitizer.clean(service.name()), LogSanitizer.clean(service.paths())); + return ResponseEntity.ok(serviceConfig.update(name, service)); } + @SetupSessionAllowed @DeleteMapping("/services/{name}") - public ResponseEntity removeService(@PathVariable String name) { - LOGGER.info("DELETE /api/v1/services/{}", name); - return orchestrator.whileIdle(() -> { - Optional existing = db.fetchService(name); - if (existing.isEmpty()) { - return error(HttpStatus.NOT_FOUND, "Service not found: " + name); - } - db.removeService(existing.get().name()); - docker.removeContainers(existing.get().name()); - broadcaster.publishConfigChanged(); - return ResponseEntity.noContent().build(); - }); + public ResponseEntity removeService(@PathVariable String name) { + LOGGER.info("DELETE /api/v1/services/{}", LogSanitizer.clean(name)); + serviceConfig.remove(name); + return ResponseEntity.noContent().build(); } private ServerConfigDto currentConfig() { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java new file mode 100644 index 0000000..05e8339 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java @@ -0,0 +1,67 @@ +package wellatleastitried.mediagarrdServer.api; + +import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.PairRequest; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairedClientDto; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@RestController +@RequestMapping("/api/v1") +public class PairingController { + + private static final Logger LOGGER = LoggerFactory.getLogger(PairingController.class); + + private final PairingService pairing; + + public PairingController(PairingService pairing) { + this.pairing = pairing; + } + + @PublicEndpoint + @PostMapping("/pair") + public PairResponse pair(@RequestBody PairRequest request) { + LOGGER.info("POST /api/v1/pair"); + return pairing.pair(request.pin(), request.name()); + } + + @PostMapping("/pairing-codes") + public PairingCodeDto createCode() { + LOGGER.info("POST /api/v1/pairing-codes"); + return pairing.createCode(); + } + + @GetMapping("/clients") + public List clients(@RequestAttribute(ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE) String currentId) { + return pairing.list().stream() + .map(client -> new PairedClientDto(client.id(), client.name(), client.createdAt(), client.lastUsedAt(), client.id().equals(currentId))) + .toList(); + } + + @DeleteMapping("/clients/{id}") + public ResponseEntity revoke(@PathVariable String id) { + LOGGER.info("DELETE /api/v1/clients/{}", LogSanitizer.clean(id)); + if (!pairing.revoke(id)) { + return error(HttpStatus.NOT_FOUND, "Client not found"); + } + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java b/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java new file mode 100644 index 0000000..721d8f1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java @@ -0,0 +1,15 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface PublicEndpoint { + + boolean tokenOptional() default false; +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java new file mode 100644 index 0000000..631d442 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java @@ -0,0 +1,139 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.ByteArrayInputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Set; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import tools.jackson.databind.json.JsonMapper; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class RequestBodyLimitFilter extends OncePerRequestFilter { + + public static final int MAX_BODY_BYTES = 64 * 1024; + static final String MESSAGE = "Request body is too large"; + static final String UNSUPPORTED_CHARSET_MESSAGE = "Unsupported charset in Content-Type"; + private static final Set BODYLESS_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return BODYLESS_METHODS.contains(request.getMethod()); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (request.getContentLengthLong() > MAX_BODY_BYTES) { + reject(response); + return; + } + if (request.getCharacterEncoding() != null && charset(request.getCharacterEncoding()) == null) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", UNSUPPORTED_CHARSET_MESSAGE))); + return; + } + byte[] body = request.getInputStream().readNBytes(MAX_BODY_BYTES + 1); + if (body.length > MAX_BODY_BYTES) { + reject(response); + return; + } + chain.doFilter(new BufferedBodyRequest(request, body), response); + } + + private static Charset charset(String name) { + try { + return Charset.forName(name); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static void reject(HttpServletResponse response) throws IOException { + response.setStatus(HttpStatus.CONTENT_TOO_LARGE.value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setHeader("Connection", "close"); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", MESSAGE))); + } + + private static final class BufferedBodyRequest extends HttpServletRequestWrapper { + + private final byte[] body; + + BufferedBodyRequest(HttpServletRequest request, byte[] body) { + super(request); + this.body = body; + } + + @Override + public ServletInputStream getInputStream() { + ByteArrayInputStream source = new ByteArrayInputStream(body); + return new ServletInputStream() { + @Override + public int read() { + return source.read(); + } + + @Override + public int read(byte[] buffer, int offset, int length) { + return source.read(buffer, offset, length); + } + + @Override + public boolean isFinished() { + return source.available() == 0; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener listener) { + throw new IllegalStateException("Asynchronous reads are not supported"); + } + }; + } + + @Override + public BufferedReader getReader() { + String encoding = getCharacterEncoding(); + Charset charset = encoding == null ? null : charset(encoding); + if (charset == null) { + charset = StandardCharsets.UTF_8; + } + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } + + @Override + public int getContentLength() { + return body.length; + } + + @Override + public long getContentLengthLong() { + return body.length; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java index c4f2f86..e82f3c0 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java @@ -2,12 +2,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.CacheControl; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.AsyncRequestNotUsableException; @@ -15,6 +15,7 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.PairingService; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster.SubscriberLimitException; @@ -25,18 +26,24 @@ public class RunEventsController { private static final Logger LOGGER = LoggerFactory.getLogger(RunEventsController.class); private final RunStatusBroadcaster broadcaster; + private final PairingService pairing; - public RunEventsController(RunStatusBroadcaster broadcaster) { + public RunEventsController(RunStatusBroadcaster broadcaster, PairingService pairing) { this.broadcaster = broadcaster; + this.pairing = pairing; } @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public ResponseEntity events() { + public ResponseEntity events(@RequestAttribute(ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE) String clientId) { try { + SseEmitter emitter = broadcaster.subscribe(clientId); + if (!pairing.isPaired(clientId)) { + broadcaster.closeClient(clientId); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } return ResponseEntity.ok() - .cacheControl(CacheControl.noCache()) .header("X-Accel-Buffering", "no") - .body(broadcaster.subscribe()); + .body(emitter); } catch (SubscriberLimitException e) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build(); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java new file mode 100644 index 0000000..6b8d5c7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java @@ -0,0 +1,44 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SecurityHeadersFilter extends OncePerRequestFilter { + + static final String CONTENT_SECURITY_POLICY = "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + private static final String[] CACHEABLE_PREFIXES = {"/css/", "/js/"}; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + response.setHeader("X-Frame-Options", "DENY"); + response.setHeader("Content-Security-Policy", CONTENT_SECURITY_POLICY); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.setHeader("Referrer-Policy", "no-referrer"); + if (!cacheable(request.getRequestURI())) { + response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store"); + } + chain.doFilter(request, response); + } + + private static boolean cacheable(String uri) { + for (String prefix : CACHEABLE_PREFIXES) { + if (uri.startsWith(prefix)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java index e02d508..9f95f09 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java @@ -18,9 +18,11 @@ import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdServer.dto.SetupCompleteDto; import wellatleastitried.mediagarrdServer.dto.SetupSessionRequest; import wellatleastitried.mediagarrdServer.dto.SetupStatusDto; -import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.SetupAlreadyCompleteException; import wellatleastitried.mediagarrdServer.service.SetupService; @RestController @@ -30,20 +32,22 @@ public class SetupController { private static final Logger LOGGER = LoggerFactory.getLogger(SetupController.class); private final SetupService setup; - private final DatabaseService db; + private final ServiceRepository services; - public SetupController(SetupService setup, DatabaseService db) { + public SetupController(SetupService setup, ServiceRepository services) { this.setup = setup; - this.db = db; + this.services = services; } + @PublicEndpoint @GetMapping public SetupStatusDto status(HttpServletRequest request) { return new SetupStatusDto(setup.isCompleted(), setup.canConfigure(SetupInterceptor.sessionToken(request))); } + @PublicEndpoint @PostMapping("/session") - public ResponseEntity startSession(@RequestBody SetupSessionRequest request) { + public ResponseEntity startSession(@RequestBody SetupSessionRequest request, HttpServletRequest http) { LOGGER.info("POST /api/v1/setup/session"); if (setup.isCompleted()) { return error(HttpStatus.GONE, "Setup is already complete"); @@ -52,25 +56,40 @@ public ResponseEntity startSession(@RequestBody SetupSessionRequest request) if (session.isEmpty()) { return error(HttpStatus.UNAUTHORIZED, "Invalid PIN, check the server logs for the current PIN"); } - return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie(session.get(), -1).toString()).build(); + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie(session.get(), -1, http).toString()).build(); } + @SetupSessionAllowed @PostMapping("/complete") - public ResponseEntity complete() { + public ResponseEntity complete(HttpServletRequest http) { LOGGER.info("POST /api/v1/setup/complete"); if (setup.isCompleted()) { return error(HttpStatus.GONE, "Setup is already complete"); } - if (db.fetchServices().isEmpty()) { + if (services.fetchServices().isEmpty()) { return error(HttpStatus.CONFLICT, "Add at least one service before finishing setup"); } - setup.complete(); - return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", 0).toString()).build(); + String pairingPin; + try { + pairingPin = setup.complete(); + } catch (SetupAlreadyCompleteException e) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie("", 0, http).toString()).body(new SetupCompleteDto(pairingPin)); + } + + private static boolean secure(HttpServletRequest request) { + return request.isSecure() || forwardedHttps(request.getHeader("X-Forwarded-Proto")); + } + + private static boolean forwardedHttps(String header) { + return header != null && "https".equalsIgnoreCase(header.split(",")[0].strip()); } - private static ResponseCookie cookie(String value, long maxAgeSeconds) { + private static ResponseCookie cookie(String value, long maxAgeSeconds, HttpServletRequest request) { return ResponseCookie.from(SESSION_COOKIE, value) .httpOnly(true) + .secure(secure(request)) .sameSite("Strict") .path("/") .maxAge(maxAgeSeconds) diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java index 354fbbb..5265b88 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java @@ -2,10 +2,8 @@ import java.io.IOException; import java.util.Arrays; -import java.util.List; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; @@ -18,8 +16,7 @@ public class SetupInterceptor implements HandlerInterceptor { static final String SESSION_COOKIE = "mediagarrd-setup"; - private static final List SETUP_PAGE_PATHS = List.of("/config", "/config.html", "/css/", "/js/"); - private static final List CONFIG_API_PATHS = List.of("/api/v1/config", "/api/v1/services", "/api/v1/setup/complete"); + public static final String[] SETUP_PAGE_PATTERNS = {"/config", "/config.html", "/css/**", "/js/**"}; private final SetupService setup; @@ -29,17 +26,10 @@ public SetupInterceptor(SetupService setup) { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { - String path = request.getRequestURI(); - if (matches(path, SETUP_PAGE_PATHS) && setup.isCompleted()) { + if (setup.isCompleted()) { response.sendError(HttpStatus.NOT_FOUND.value()); return false; } - if (matches(path, CONFIG_API_PATHS) && !setup.canConfigure(sessionToken(request))) { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.getWriter().write("{\"error\":\"Setup session required, reload /config and enter the PIN from the server logs\"}"); - return false; - } return true; } @@ -54,10 +44,4 @@ static String sessionToken(HttpServletRequest request) { .findFirst() .orElse(null); } - - private static boolean matches(String path, List prefixes) { - return prefixes.stream().anyMatch(prefix -> prefix.endsWith("/") - ? path.startsWith(prefix) - : path.equals(prefix) || path.startsWith(prefix + "/")); - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java new file mode 100644 index 0000000..9c14b90 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface SetupSessionAllowed { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java index 99bb197..57f640f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java @@ -17,6 +17,7 @@ public VersionController(UpdateCheckService updateCheckService) { this.updateCheckService = updateCheckService; } + @PublicEndpoint @GetMapping("/version") public VersionStatusDto version() { return updateCheckService.status(); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java new file mode 100644 index 0000000..4305cc5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java @@ -0,0 +1,54 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdServer.dto.WebhookTestDto; +import wellatleastitried.mediagarrdServer.dto.WebhookUpdateRequest; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.WebhookService; + +@RestController +@RequestMapping("/api/v1/notifications/webhook") +public class WebhookController { + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookController.class); + + private final WebhookService webhook; + private final RunStatusBroadcaster broadcaster; + + public WebhookController(WebhookService webhook, RunStatusBroadcaster broadcaster) { + this.webhook = webhook; + this.broadcaster = broadcaster; + } + + @SetupSessionAllowed + @GetMapping + public WebhookStatusDto status() { + LOGGER.debug("GET /api/v1/notifications/webhook"); + return webhook.status(); + } + + @SetupSessionAllowed + @PutMapping + public WebhookStatusDto update(@RequestBody WebhookUpdateRequest request) { + LOGGER.info("PUT /api/v1/notifications/webhook"); + WebhookStatusDto updated = webhook.update(request.url()); + broadcaster.publishConfigChanged(); + return updated; + } + + @SetupSessionAllowed + @PostMapping("/test") + public WebhookTestDto test() { + LOGGER.info("POST /api/v1/notifications/webhook/test"); + return webhook.test(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java new file mode 100644 index 0000000..334df5d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record PairRequest(String pin, String name) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java new file mode 100644 index 0000000..836ec31 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record PairResponse(String token, String id, String name) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java new file mode 100644 index 0000000..5342358 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record PairedClientDto(String id, String name, Instant createdAt, Instant lastUsedAt, boolean current) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java new file mode 100644 index 0000000..c207405 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record PairingCodeDto(String code, Instant expiresAt) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java new file mode 100644 index 0000000..1484ca9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record PublicHealthDto(boolean healthy, Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java new file mode 100644 index 0000000..5c9be87 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupCompleteDto(String pairingPin) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java new file mode 100644 index 0000000..e99e274 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookStatusDto(boolean configured, String target) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java new file mode 100644 index 0000000..4f1710d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookTestDto(boolean delivered, Integer status, String error) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java new file mode 100644 index 0000000..7ede1a9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookUpdateRequest(String url) { + + @Override + public String toString() { + return "WebhookUpdateRequest[url=]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java index 3322f4e..aab071d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -5,10 +5,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; -import java.util.HexFormat; +import wellatleastitried.mediagarrdServer.utilities.Sha256; public record BackupArchive( String id, @@ -27,10 +25,10 @@ public String resolvedChecksum() { } public String generateChecksum() { - try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), MessageDigest.getInstance("SHA-256"))) { + try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), Sha256.newDigest())) { in.transferTo(OutputStream.nullOutputStream()); - return HexFormat.of().formatHex(in.getMessageDigest().digest()); - } catch (IOException | NoSuchAlgorithmException e) { + return Sha256.hex(in.getMessageDigest().digest()); + } catch (IOException e) { return ""; } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java b/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java new file mode 100644 index 0000000..1d9ec27 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.time.Instant; + +public record PairedClient(String id, String name, Instant createdAt, Instant lastUsedAt) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java index 715364c..3245550 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java @@ -7,6 +7,8 @@ public record ServiceDefinition(String name, List paths) { + public static final int MAX_PATHS = 32; + public static final int MAX_PATH_LENGTH = 4096; private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); public ServiceDefinition { @@ -28,7 +30,13 @@ public ServiceDefinition validate() { if (paths.isEmpty()) { throw new IllegalArgumentException("Service '" + name + "' needs at least one path"); } + if (paths.size() > MAX_PATHS) { + throw new IllegalArgumentException("Service '" + name + "' has more than " + MAX_PATHS + " paths"); + } for (String path : paths) { + if (path.length() > MAX_PATH_LENGTH) { + throw new IllegalArgumentException("Path is longer than " + MAX_PATH_LENGTH + " characters"); + } if (!path.startsWith("/")) { throw new IllegalArgumentException("Path must be absolute: " + path); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java new file mode 100644 index 0000000..78a9261 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java @@ -0,0 +1,249 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.parseTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_SERVICE_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LAST_SUCCESSFUL_START; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LATEST_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICES_FROM_RECORD; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.ParseException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Repository; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +@Repository +public class BackupRecordRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupRecordRepository.class); + + private final SqliteDatabase database; + + public BackupRecordRepository(SqliteDatabase database) { + this.database = database; + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + connection.setAutoCommit(false); + Integer backupId = addMasterBackup(connection, backupRecord); + if (backupId != null) { + addServiceBackups(connection, backupId, backupRecord.serviceResults()); + } else if (backupRecord.archive() != null) { + LOGGER.warn("Could not record backup {}; this archive will not be pruned by retention", backupRecord.runId()); + } + } catch (SQLException e) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId(), e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } finally { + database.readLock().unlock(); + } + } + + public Optional fetchBackupById(String archiveId) { + FetchedBackupRecord backupRecord = null; + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException e) { + LOGGER.warn("An error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); + } finally { + database.readLock().unlock(); + } + + return Optional.ofNullable(backupRecord); + } + + public Optional fetchLatestBackupRecord() { + FetchedBackupRecord backupRecord = null; + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException e) { + LOGGER.warn("An error occurred while fetching the latest backup record", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while fetching the latest backup record", e); + } finally { + database.readLock().unlock(); + } + + return Optional.ofNullable(backupRecord); + } + + public Optional fetchLastSuccessfulStartTime() { + return database.query("fetch the last successful backup", FETCH_LAST_SUCCESSFUL_START, rs -> rs.getString("start_time")) + .stream() + .findFirst() + .map(BackupRecordRepository::parseStartTime); + } + + private static Instant parseStartTime(String startTime) { + try { + return parseTime(startTime); + } catch (ParseException | NullPointerException e) { + throw new IllegalStateException("Unreadable backup start time: " + startTime, e); + } + } + + public void deleteBackupRecordById(String archiveId) { + database.readLock().lock(); + try (var connection = database.openVerifiedConnection(); + var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { + statement.setString(1, archiveId); + statement.executeUpdate(); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", e); + } finally { + database.readLock().unlock(); + } + } + + private Integer addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try { + return database.inTransaction(connection, transaction -> insertMasterBackup(transaction, backupRecord)); + } catch (SQLException e) { + LOGGER.warn("An error occurred while logging a new backup record", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + return null; + } + + private static int insertMasterBackup(Connection connection, BackupRunResult backupRecord) throws SQLException { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + BackupArchive archive = backupRecord.archive(); + statement.setString(5, archive == null ? null : archive.resolvedChecksum()); + statement.setString(6, archive == null ? null : archive.path().toString()); + statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); + statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + } + try (var idQuery = connection.createStatement(); + var keys = idQuery.executeQuery("SELECT last_insert_rowid()")) { + return keys.getInt(1); + } + } + + private void addServiceBackups(Connection connection, int backupId, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try { + database.inTransaction(connection, transaction -> insertServiceBackup(transaction, backupId, service)); + } catch (SQLException e) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), e); + } + } + } + + private static Void insertServiceBackup(Connection connection, int backupId, BackupServiceResult service) throws SQLException { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setInt(1, backupId); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + } + return null; + } + + private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { + try (var statement = connection.prepareStatement(FETCH_RECORD_BY_ID)) { + statement.setString(1, archiveId); + var rs = statement.executeQuery(); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", e); + return null; + } + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error fetching latest backup record", e); + return null; + } + } + + private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + + int id = rs.getInt("id"); + String archiveId = rs.getString("archive_id"); + String backupStartTime = rs.getString("start_time"); + String backupEndTime = rs.getString("end_time"); + String status = rs.getString("status"); + String filePath = rs.getString("file_path"); + String errorMessage = rs.getString("error_message"); + + return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + String endTime = rs.getString("end_time"); + String errorMessage = rs.getString("error_message"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime, + endTime, + errorMessage + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error populating backup record with related services", e); + return null; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java new file mode 100644 index 0000000..2cc6378 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java @@ -0,0 +1,76 @@ +package wellatleastitried.mediagarrdServer.repository; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sqlite.SQLiteErrorCode; +import org.sqlite.SQLiteException; + +final class DatabaseQuarantine { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseQuarantine.class); + + private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter + .ofPattern("yyyyMMdd-HHmmss") + .withZone(ZoneOffset.UTC); + + private static final List DATABASE_FILE_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + private DatabaseQuarantine() {} + + static void checkNotCorrupt(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); var rs = statement.executeQuery("PRAGMA quick_check")) { + String result = rs.next() ? rs.getString(1) : "no result"; + if (!"ok".equals(result)) { + throw new CorruptDatabaseException("Database failed its integrity check: " + result); + } + } + } + + static boolean isCorrupt(SQLException e) { + if (e instanceof CorruptDatabaseException) { + return true; + } + if (e instanceof SQLiteException sqlite) { + int code = sqlite.getResultCode().code & 0xFF; + return code == SQLiteErrorCode.SQLITE_CORRUPT.code || code == SQLiteErrorCode.SQLITE_NOTADB.code; + } + return false; + } + + static boolean quarantine(Path databaseFile) { + if (!Files.isRegularFile(databaseFile)) { + return false; + } + String suffix = ".corrupt-" + QUARANTINE_FORMAT.format(Instant.now()); + try { + for (String fileSuffix : DATABASE_FILE_SUFFIXES) { + Path file = Path.of(databaseFile + fileSuffix); + if (Files.isRegularFile(file)) { + Files.move(file, Path.of(file + suffix)); + } + } + } catch (IOException e) { + LOGGER.error("Database {} is corrupt and could not be moved aside", databaseFile, e); + return false; + } + LOGGER.error("Database {} was corrupt, moved it to {}{} and created a new one. Settings and services must be configured again", + databaseFile, databaseFile, suffix); + return true; + } + + private static class CorruptDatabaseException extends SQLException { + CorruptDatabaseException(String message) { + super(message); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java new file mode 100644 index 0000000..0aab8be --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java @@ -0,0 +1,7 @@ +package wellatleastitried.mediagarrdServer.repository; + +@FunctionalInterface +public interface DatabaseRebuildListener { + + void databaseRebuilt(); +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java new file mode 100644 index 0000000..3038c6f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java @@ -0,0 +1,125 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; + +final class DatabaseSchema { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSchema.class); + + private static final List REQUIRED_TABLES = List.of("backups", "backup_services", "services", "settings"); + + record Fingerprint(int userVersion, int schemaVersion) {} + + private DatabaseSchema() {} + + static Fingerprint fingerprint(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); + var rs = statement.executeQuery("SELECT user_version, schema_version FROM pragma_user_version, pragma_schema_version")) { + return new Fingerprint(rs.getInt(1), rs.getInt(2)); + } + } + + static void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + for (String sql : CREATE_TABLES.split(";")) { + String createStatement = sql.trim(); + if (!createStatement.isEmpty()) { + statement.execute(createStatement); + } + } + + connection.commit(); + } catch (SQLException e) { + LOGGER.warn("Failed to verify if tables exist in database.", e); + rollback(connection); + throw e; + } + } + + static void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = databaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion >= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException e) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + e + ); + rollback(connection); + throw e; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + static void requireCompleteSchema(Connection connection) throws SQLException { + if (databaseVersion(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); + } + } + + static void rollback(Connection connection) { + try { + connection.rollback(); + } catch (SQLException e) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } + + private static int databaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + return result.getInt(1); + } catch (SQLException e) { + LOGGER.warn("Failed to fetch database version", e); + return -1; + } + } + + private static void setDatabaseVersion(Connection connection, int version) { + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException e) { + LOGGER.warn("Failed to set new database version", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java new file mode 100644 index 0000000..cbf92d7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java @@ -0,0 +1,59 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_PAIRED_CLIENT; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.COUNT_PAIRED_CLIENTS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_PAIRED_CLIENT; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_PAIRED_CLIENTS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_PAIRED_CLIENT_BY_HASH; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.TOUCH_PAIRED_CLIENT; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +import wellatleastitried.mediagarrdServer.model.PairedClient; + +@Repository +public class PairedClientRepository { + + private final SqliteDatabase database; + + public PairedClientRepository(SqliteDatabase database) { + this.database = database; + } + + public void addPairedClient(String id, String name, String tokenHash, Instant createdAt) { + database.update("add paired client " + id, ADD_PAIRED_CLIENT, id, name, tokenHash, createdAt.toString()); + } + + public List fetchPairedClients() { + return database.query("fetch paired clients", FETCH_PAIRED_CLIENTS, PairedClientRepository::toPairedClient); + } + + public Optional fetchPairedClientByTokenHash(String tokenHash) { + return database.query("fetch paired client by token", FETCH_PAIRED_CLIENT_BY_HASH, PairedClientRepository::toPairedClient, tokenHash) + .stream().findFirst(); + } + + public boolean removePairedClient(String id) { + return database.update("remove paired client " + id, DELETE_PAIRED_CLIENT, id) > 0; + } + + public void touchPairedClient(String id, Instant usedAt) { + database.update("update paired client " + id, TOUCH_PAIRED_CLIENT, usedAt.toString(), id); + } + + public int countPairedClients() { + return database.query("count paired clients", COUNT_PAIRED_CLIENTS, rs -> rs.getInt(1)).get(0); + } + + private static PairedClient toPairedClient(ResultSet rs) throws SQLException { + String lastUsed = rs.getString("last_used_at"); + return new PairedClient(rs.getString("id"), rs.getString("name"), Instant.parse(rs.getString("created_at")), + lastUsed == null ? null : Instant.parse(lastUsed)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java new file mode 100644 index 0000000..bbd1a07 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java @@ -0,0 +1,70 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_ALL_SERVICES; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICE_BY_NAME; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPDATE_SERVICE; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +@Repository +public class ServiceRepository { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final TypeReference> PATH_LIST = new TypeReference<>() {}; + + private final SqliteDatabase database; + + public ServiceRepository(SqliteDatabase database) { + this.database = database; + } + + public List fetchServices() { + return database.query("fetch configured services", FETCH_ALL_SERVICES, ServiceRepository::toServiceDefinition); + } + + public Optional fetchService(String name) { + return database.query("fetch service " + name, FETCH_SERVICE_BY_NAME, ServiceRepository::toServiceDefinition, name) + .stream().findFirst(); + } + + public void addService(ServiceDefinition service) { + database.update("add service " + service.name(), ADD_SERVICE, service.name(), toJson(service.paths())); + } + + public boolean updateService(String name, ServiceDefinition service) { + return database.update("update service " + name, UPDATE_SERVICE, service.name(), toJson(service.paths()), name) > 0; + } + + public boolean removeService(String name) { + return database.update("remove service " + name, DELETE_SERVICE, name) > 0; + } + + private static ServiceDefinition toServiceDefinition(ResultSet rs) throws SQLException { + try { + return new ServiceDefinition(rs.getString("name"), JSON.readValue(rs.getString("paths"), PATH_LIST)); + } catch (JacksonException e) { + throw new SQLException("Corrupt paths for service " + rs.getString("name"), e); + } + } + + private static String toJson(List paths) { + try { + return JSON.writeValueAsString(paths); + } catch (JacksonException e) { + throw new IllegalStateException("Failed to serialize service paths", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java new file mode 100644 index 0000000..ed62062 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java @@ -0,0 +1,26 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPSERT_SETTING; + +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +@Repository +public class SettingsRepository { + + private final SqliteDatabase database; + + public SettingsRepository(SqliteDatabase database) { + this.database = database; + } + + public Optional fetchSetting(String key) { + return database.query("fetch setting " + key, FETCH_SETTING, rs -> rs.getString("value"), key).stream().findFirst(); + } + + public void saveSetting(String key, String value) { + database.update("save setting " + key, UPSERT_SETTING, key, value); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java new file mode 100644 index 0000000..a0267da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java @@ -0,0 +1,279 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SQLITE; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import jakarta.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.sqlite.SQLiteConfig; +import org.sqlite.SQLiteOpenMode; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.utilities.FilePermissions; + +@Component +public class SqliteDatabase { + + private static final Logger LOGGER = LoggerFactory.getLogger(SqliteDatabase.class); + + private final ReentrantReadWriteLock databaseLock = new ReentrantReadWriteLock(); + private final Path databaseFile; + private final String databaseUrl; + private final List rebuildListeners = new CopyOnWriteArrayList<>(); + private final ExecutorService rebuildNotifier = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "database-rebuild-notifier"); + thread.setDaemon(true); + return thread; + }); + private volatile DatabaseSchema.Fingerprint verifiedSchema; + + public SqliteDatabase(MediaGarrdProperties properties) { + databaseFile = Path.of(properties.getDatabasePath()).toAbsolutePath(); + databaseUrl = SQLITE + databaseFile; + verifyDatabaseIntegrity(); + } + + @PreDestroy + void shutdownRebuildNotifier() { + rebuildNotifier.shutdownNow(); + } + + @FunctionalInterface + interface RowMapper { + T map(ResultSet rs) throws SQLException; + } + + @FunctionalInterface + interface TransactionWork { + T run(Connection connection) throws SQLException; + } + + @FunctionalInterface + private interface StatementWork { + T run(PreparedStatement statement) throws SQLException; + } + + public void addRebuildListener(DatabaseRebuildListener listener) { + rebuildListeners.add(listener); + } + + public Path databaseFile() { + return databaseFile; + } + + protected Connection getConnection() throws SQLException { + Connection connection = DriverManager.getConnection(databaseUrl); + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA foreign_keys = ON"); + } catch (SQLException e) { + connection.close(); + throw e; + } + return connection; + } + + protected synchronized boolean verifyDatabaseIntegrity() { + verifiedSchema = null; + try { + rebuildIfNeeded(); + return true; + } catch (SQLException e) { + if (!DatabaseQuarantine.isCorrupt(e) || !DatabaseQuarantine.quarantine(databaseFile)) { + LOGGER.warn("An error occurred while verifying the integrity of the database", e); + return false; + } + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + try { + rebuildIfNeeded(); + notifyRebuilt(); + return true; + } catch (Exception e) { + LOGGER.warn("Unable to create a new database after moving the corrupt one aside", e); + return false; + } + } + + private void notifyRebuilt() { + for (DatabaseRebuildListener listener : rebuildListeners) { + rebuildNotifier.execute(() -> { + try { + listener.databaseRebuilt(); + } catch (RuntimeException e) { + LOGGER.error("Unable to reset the server after the database was rebuilt, restart the server", e); + } + }); + } + } + + private void rebuildIfNeeded() throws SQLException { + try { + FilePermissions.createPrivateDirectories(databaseFile.getParent()); + if (Files.exists(databaseFile)) { + FilePermissions.restrictFile(databaseFile); + } else { + FilePermissions.createPrivateFile(databaseFile); + } + } catch (IOException e) { + LOGGER.warn("Unable to prepare the database location " + databaseFile.getParent(), e); + } + try (var connection = getConnection()) { + DatabaseQuarantine.checkNotCorrupt(connection); + connection.setAutoCommit(false); + DatabaseSchema.ensureTablesExist(connection); + DatabaseSchema.runNeededMigrations(connection); + verifiedSchema = DatabaseSchema.fingerprint(connection); + } + } + + Lock readLock() { + return databaseLock.readLock(); + } + + Connection openVerifiedConnection() throws SQLException { + DatabaseSchema.Fingerprint expected = verifiedSchema; + if (expected != null) { + Connection connection = null; + try { + connection = getConnection(); + if (DatabaseSchema.fingerprint(connection).equals(expected)) { + return connection; + } + } catch (SQLException e) { + LOGGER.debug("Unable to read the database schema fingerprint", e); + } + if (connection != null) { + connection.close(); + } + LOGGER.info("Database does not match the verified schema, rebuilding it"); + } + if (!verifyDatabaseIntegrity()) { + throw new SQLException("Database integrity check failed"); + } + return getConnection(); + } + + boolean invalidateIfDamaged(SQLException e) { + String message = String.valueOf(e.getMessage()); + boolean damaged = DatabaseQuarantine.isCorrupt(e) || message.contains("no such table") || message.contains("no such column"); + if (damaged) { + verifiedSchema = null; + } + return damaged; + } + + T inTransaction(Connection connection, TransactionWork work) throws SQLException { + try { + T result = work.run(connection); + connection.commit(); + return result; + } catch (SQLException e) { + invalidateIfDamaged(e); + DatabaseSchema.rollback(connection); + throw e; + } + } + + List query(String action, String sql, RowMapper mapper, String... params) { + return execute(action, sql, params, statement -> { + try (var rs = statement.executeQuery()) { + List rows = new ArrayList<>(); + while (rs.next()) { + rows.add(mapper.map(rs)); + } + return rows; + } + }); + } + + int update(String action, String sql, String... params) { + return execute(action, sql, params, PreparedStatement::executeUpdate); + } + + private T execute(String action, String sql, String[] params, StatementWork work) { + 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 e) { + if (attempt > 1 || !invalidateIfDamaged(e)) { + throw new IllegalStateException("Failed to " + action, e); + } + LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", e.getMessage()); + } + } + } finally { + databaseLock.readLock().unlock(); + } + } + + 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"); + } + try (var connection = openSnapshotConnection(databaseFile)) { + DatabaseQuarantine.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)) { + DatabaseQuarantine.checkNotCorrupt(connection); + DatabaseSchema.requireCompleteSchema(connection); + } + } + + private static void bind(PreparedStatement statement, String... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + statement.setString(i + 1, params[i]); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java b/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java new file mode 100644 index 0000000..0ee3183 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; + +final class AttemptLimiter { + + private final int maxFailures; + private final Duration lockDuration; + private final Clock clock; + private int failures; + private Instant lockedUntil; + + AttemptLimiter(int maxFailures, Duration lockDuration, Clock clock) { + this.maxFailures = maxFailures; + this.lockDuration = lockDuration; + this.clock = clock; + } + + synchronized void checkNotLocked() { + if (lockedUntil == null) { + return; + } + Instant now = clock.instant(); + if (now.isBefore(lockedUntil)) { + throw new LockedOutException(Duration.between(now, lockedUntil)); + } + lockedUntil = null; + failures = 0; + } + + synchronized int recordFailure() { + failures++; + if (failures >= maxFailures) { + lockedUntil = clock.instant().plus(lockDuration); + } + return failures; + } + + synchronized boolean isLockedNow() { + return lockedUntil != null && clock.instant().isBefore(lockedUntil); + } + + synchronized void reset() { + failures = 0; + lockedUntil = null; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java index 49d1ebf..9b71b06 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -4,17 +4,19 @@ import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; import java.io.IOException; +import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; @@ -24,6 +26,10 @@ import jakarta.annotation.PostConstruct; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.FilePermissions; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @Service public class BackupArchiveService { @@ -34,35 +40,54 @@ 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"; + static final String ZIP_EXTENSION = ".zip"; + static final String RUNS_DIRECTORY = ".mediagarrd-runs"; + static final String TEMP_SUFFIX = ARCHIVE_SUFFIX + ".tmp"; + static final int MAX_LOCATION_LENGTH = 4096; + + private final MediaGarrdProperties properties; + private final SettingsRepository settings; + private final BackupRecordRepository backups; + private final AtomicReference archiveCache = new AtomicReference<>(null); + private record ArchiveSnapshot(List archives, long loadedAtMs) {} - private final DatabaseService db; - private final AtomicReference> cachedArchives = new AtomicReference<>(null); - private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); private volatile Path root; private volatile int retentionCount; - public BackupArchiveService(MediaGarrdProperties properties, DatabaseService db) { - this.db = db; - this.root = Path.of(db.fetchSetting(BACKUP_ROOT_SETTING).orElse(properties.getBackupRoot())) + public BackupArchiveService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups) { + this.properties = properties; + this.settings = settings; + this.backups = backups; + loadSettings(); + } + + private void loadSettings() { + this.root = Path.of(settings.fetchSetting(BACKUP_ROOT_SETTING).orElse(properties.getBackupRoot())) .toAbsolutePath() .normalize(); - this.retentionCount = db.fetchSetting(RETENTION_COUNT_SETTING) + this.retentionCount = settings.fetchSetting(RETENTION_COUNT_SETTING) .flatMap(BackupArchiveService::parseRetention) .orElse(Math.max(1, properties.getRetentionCount())); } + public synchronized void reloadFromSettings() { + loadSettings(); + invalidateCache(); + LOGGER.info("Backup location and retention reloaded from the settings: location={}, retentionCount={}", LogSanitizer.clean(root), retentionCount); + } + @PostConstruct public void cleanupStaleArtifactsOnStartup() { Path root = rootDirectory(); - Path runsRoot = root.resolve("runs"); + Path runsRoot = root.resolve(RUNS_DIRECTORY); try { - Files.createDirectories(root); + FilePermissions.createPrivateDirectories(root); try (var stream = Files.list(root)) { stream .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) + .filter(path -> path.getFileName().toString().endsWith(TEMP_SUFFIX)) .forEach(path -> { try { Files.deleteIfExists(path); @@ -116,7 +141,7 @@ public synchronized void updateSettings(String location, Integer retention) { updateRootDirectory(location); } if (retention != null) { - db.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); + settings.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); retentionCount = retention; LOGGER.info("Retention count changed to {}, applied on the next backup run", retention); } @@ -126,13 +151,19 @@ public Path updateRootDirectory(String location) { if (location == null || location.isBlank()) { throw new IllegalArgumentException("Backup location is required"); } + if (location.length() > MAX_LOCATION_LENGTH) { + throw new IllegalArgumentException("Backup location must be at most " + MAX_LOCATION_LENGTH + " characters"); + } + if (location.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Backup location must not contain control characters"); + } Path requested = Path.of(location.strip()); if (!requested.isAbsolute()) { throw new IllegalArgumentException("Backup location must be an absolute path"); } Path normalized = requested.normalize(); try { - Files.createDirectories(normalized); + FilePermissions.createPrivateDirectories(normalized); } catch (IOException | SecurityException e) { throw new IllegalArgumentException("Unable to create backup location " + normalized); } @@ -140,10 +171,10 @@ public Path updateRootDirectory(String location) { throw new IllegalArgumentException("Backup location is not writable: " + normalized); } - db.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); + settings.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); root = normalized; invalidateCache(); - LOGGER.info("Backup location changed to {}", normalized); + LOGGER.info("Backup location changed to {}", LogSanitizer.clean(normalized)); return normalized; } @@ -155,7 +186,7 @@ public BackupArchive createArchive(Path runDirectory) { LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); try { - Files.createDirectories(root); + FilePermissions.createPrivateDirectories(root); String checksum = mergeParts(runDirectory, archivePath); enforceRetention(); long size = Files.size(archivePath); @@ -172,14 +203,11 @@ public BackupArchive createArchive(Path runDirectory) { public List listArchives() { long now = System.currentTimeMillis(); - long lastUpdate = cacheLastUpdatedMs.get(); + ArchiveSnapshot cached = archiveCache.get(); - if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { - List cached = cachedArchives.get(); - if (cached != null) { - LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); - return cached; - } + if (cached != null && now - cached.loadedAtMs() < ARCHIVE_CACHE_TTL_MS) { + LOGGER.debug("Returning cached archive list ({}ms old)", now - cached.loadedAtMs()); + return cached.archives(); } // Cache miss -> rebuild list @@ -190,8 +218,7 @@ public List listArchives() { throw new IllegalStateException("Failed to list archives", e); } - cachedArchives.set(archives); - cacheLastUpdatedMs.set(now); + archiveCache.set(new ArchiveSnapshot(archives, now)); LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); return archives; } @@ -212,7 +239,7 @@ public boolean deleteById(String id) { try { Files.deleteIfExists(archive.get().path()); - db.deleteBackupRecordById(id); + backups.deleteBackupRecordById(id); LOGGER.info("Archive deleted: {}", id); invalidateCache(); return true; @@ -224,9 +251,9 @@ public boolean deleteById(String id) { } public Path createRunDirectory() { - Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); + Path runDir = rootDirectory().resolve(RUNS_DIRECTORY).resolve(UUID.randomUUID().toString()); try { - Files.createDirectories(runDir); + FilePermissions.createPrivateDirectories(runDir); return runDir; } catch (IOException e) { throw new IllegalStateException("Failed to create run directory", e); @@ -254,9 +281,13 @@ public void removeRunDirectory(Path runDirectory) { private void enforceRetention() throws IOException { List archives = scanArchives(); for (BackupArchive archive : archives.subList(Math.min(retentionCount, archives.size()), archives.size())) { + if (backups.fetchBackupById(archive.id()).isEmpty()) { + LOGGER.info("Retention: keeping {} because this server has no record of creating it", archive.fileName()); + continue; + } LOGGER.info("Retention: deleting old archive: {}", archive.fileName()); Files.deleteIfExists(archive.path()); - db.deleteBackupRecordById(archive.id()); + backups.deleteBackupRecordById(archive.id()); } } @@ -275,8 +306,7 @@ private List scanArchives() throws IOException { } private void invalidateCache() { - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); + archiveCache.set(null); } private String mergeParts(Path runDirectory, Path zipPath) throws IOException { @@ -290,6 +320,8 @@ private String mergeParts(Path runDirectory, Path zipPath) throws IOException { } Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + Files.deleteIfExists(tempZip); + FilePermissions.createPrivateFile(tempZip); Path snapshotDirectory = runDirectory.resolve(DatabaseSnapshotService.PART_DIRECTORY); ZipPartMerger.Result result; try { @@ -297,15 +329,31 @@ private String mergeParts(Path runDirectory, Path zipPath) throws IOException { parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList(), parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList(), tempZip, runDirectory); + syncFile(tempZip); + Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (IOException | RuntimeException e) { Files.deleteIfExists(tempZip); throw e; } - Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + syncDirectory(zipPath.getParent()); LOGGER.info("Merged {} part(s) into {} entries", parts.size(), result.entries()); return result.checksum(); } + static void syncFile(Path file) throws IOException { + try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE)) { + channel.force(true); + } + } + + static void syncDirectory(Path directory) { + try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { + channel.force(true); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Could not sync directory {}: {}", directory, e.toString()); + } + } + private BackupArchive toArchive(Path path) { String fileName = path.getFileName().toString(); return new BackupArchive( @@ -313,10 +361,20 @@ private BackupArchive toArchive(Path path) { fileName, path, fileSize(path), - lastModified(path) + createdAt(path) ); } + private Instant createdAt(Path path) { + String fileName = path.getFileName().toString(); + String stamp = fileName.substring(0, fileName.length() - ARCHIVE_SUFFIX.length()); + try { + return FILE_DATE_FORMAT.parse(stamp, Instant::from); + } catch (DateTimeParseException e) { + return lastModified(path); + } + } + private static Optional parseRetention(String stored) { try { return Optional.of(Integer.parseInt(stored)).filter(count -> count >= 1); @@ -327,7 +385,7 @@ private static Optional parseRetention(String stored) { } private String toId(String fileName) { - return fileName.replace(".zip", ""); + return fileName.endsWith(ZIP_EXTENSION) ? fileName.substring(0, fileName.length() - ZIP_EXTENSION.length()) : fileName; } private long fileSize(Path path) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java new file mode 100644 index 0000000..a274e62 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupFailedException extends IllegalStateException { + + public BackupFailedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java new file mode 100644 index 0000000..f173dea --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupInProgressException extends IllegalStateException { + + public BackupInProgressException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java new file mode 100644 index 0000000..753e585 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupNotFoundException extends RuntimeException { + + public BackupNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index f9501b9..8317521 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -23,10 +23,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -39,6 +36,8 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; @Service public class BackupOrchestratorService { @@ -55,11 +54,10 @@ public class BackupOrchestratorService { private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; private final DatabaseSnapshotService snapshotService; - private final DatabaseService db; - private final RunStatusBroadcaster broadcaster; - private final AtomicBoolean running = new AtomicBoolean(false); - private final Object transitionLock = new Object(); - private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); + private final ServiceRepository services; + private final BackupRecordRepository backups; + private final BackupRunLifecycle lifecycle; + private final WebhookService webhook; private final ExecutorService runnerExecutor = createRunnerExecutor(); public BackupOrchestratorService( @@ -67,15 +65,19 @@ public BackupOrchestratorService( BackupArchiveService archiveService, BackupScheduleService scheduleService, DatabaseSnapshotService snapshotService, - DatabaseService db, - RunStatusBroadcaster broadcaster + ServiceRepository services, + BackupRecordRepository backups, + BackupRunLifecycle lifecycle, + WebhookService webhook ) { this.runner = runner; this.archiveService = archiveService; this.scheduleService = scheduleService; this.snapshotService = snapshotService; - this.db = db; - this.broadcaster = broadcaster; + this.services = services; + this.backups = backups; + this.lifecycle = lifecycle; + this.webhook = webhook; } private static ExecutorService createRunnerExecutor() { @@ -97,7 +99,7 @@ private static ExecutorService createRunnerExecutor() { @Scheduled(fixedDelay = SCHEDULED_CHECK_INTERVAL_MS) public void scheduledRun() { - if (running.get()) { + if (lifecycle.isRunning()) { LOGGER.debug("Scheduled check skipped, backup already in progress"); return; } @@ -120,127 +122,106 @@ public BackupRunResult runBackup() { BackupRunResult runBackup(boolean scheduled) { Instant startedAt = Instant.now(); - String finalStatus = FAILED; + return lifecycle.run(startedAt, run -> execute(run, startedAt, scheduled)); + } + + private BackupRunResult execute(BackupRunLifecycle.Run run, Instant startedAt, boolean scheduled) { + Path runDirectory = null; boolean started = false; - synchronized (transitionLock) { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new RunRejectedException("A backup run is already in progress"); - } - } + boolean notified = false; try { - configLock.readLock().lock(); - Path runDirectory = null; - try { - List services = db.fetchServices(); - if (services.isEmpty()) { - LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); - if (scheduled) { - scheduleService.deferNextRun(); - } - throw new RunRejectedException("No services are configured for backup"); - } - started = true; - publishStarted(startedAt); - - scheduleService.markRunStarted(); - runDirectory = archiveService.createRunDirectory(); - final Path runDir = runDirectory; - - LOGGER.info("Backup run started: runDir={}, services={}", - runDir, services.stream().map(ServiceDefinition::name).toList()); - - DatabaseSnapshotService.Outcome snapshot = snapshotDatabase(runDir); - BackupServiceResult snapshotResult = snapshot.result(); - Set excluded = COMPLETED.equals(snapshotResult.status()) && snapshot.hostPath() != null - ? DatabaseSnapshotService.reservedNames(snapshot.hostPath()) - : Set.of(); - - List serviceRunResults = copyServices(services, runDir, excluded); - - List incomplete = serviceRunResults.stream() - .filter(r -> !COMPLETED.equals(r.status())) - .toList(); - int succeeded = services.size() - incomplete.size(); - LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); - incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); - - String errorMessage = incomplete.stream() - .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) - .collect(Collectors.joining("\n")); - - if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { - String runId = "failed-" + UUID.randomUUID(); - serviceRunResults.forEach(r -> r.setId(runId)); - db.addNewBackupRecord(new BackupRunResult( - runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); - LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); - throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + List configured = services.fetchServices(); + if (configured.isEmpty()) { + LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); + if (scheduled) { + scheduleService.deferNextRun(); } + throw new RunRejectedException("No services are configured for backup"); + } + run.markStarted(); + started = true; + + scheduleService.markRunStarted(); + runDirectory = archiveService.createRunDirectory(); + final Path runDir = runDirectory; + + LOGGER.info("Backup run started: runDir={}, services={}", + runDir, configured.stream().map(ServiceDefinition::name).toList()); + + DatabaseSnapshotService.Outcome snapshot = snapshotDatabase(runDir); + BackupServiceResult snapshotResult = snapshot.result(); + Set excluded = COMPLETED.equals(snapshotResult.status()) && snapshot.hostPath() != null + ? DatabaseSnapshotService.reservedNames(snapshot.hostPath()) + : Set.of(); + + List serviceRunResults = copyServices(configured, runDir, excluded); + + List incomplete = serviceRunResults.stream() + .filter(r -> !COMPLETED.equals(r.status())) + .toList(); + int succeeded = configured.size() - incomplete.size(); + LOGGER.info("All runners finished: succeeded={}/{}", succeeded, configured.size()); + incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); + + String errorMessage = incomplete.stream() + .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) + .collect(Collectors.joining("\n")); + + if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { + String runId = "failed-" + UUID.randomUUID(); + serviceRunResults.forEach(r -> r.setId(runId)); + BackupRunResult failedRecord = new BackupRunResult( + runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage); + backups.addNewBackupRecord(failedRecord); + LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); + notified = true; + webhook.notifyRun(failedRecord); + throw new BackupFailedException("Every service failed, no archive created: " + errorMessage); + } - 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; - } + 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); - recordedResults.forEach(r -> r.setId(archive.id())); + BackupArchive archive = archiveService.createArchive(runDirectory); + 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, - recordedResults.stream().map(BackupServiceResult::serviceName).toList()); + long durationMs = Duration.between(startedAt, Instant.now()).toMillis(); + LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), archive.sizeBytes(), durationMs, + recordedResults.stream().map(BackupServiceResult::serviceName).toList()); - String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; - if (snapshotFailed && COMPLETED.equals(status)) { - status = PARTIAL; - } + String status = succeeded == configured.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; + if (snapshotFailed && COMPLETED.equals(status)) { + status = PARTIAL; + } - BackupRunResult backupRecord = new BackupRunResult( - archive.id(), formatTime(startedAt), recordCurrentTime(), status, - recordedResults, archive, errorMessage); - db.addNewBackupRecord(backupRecord); - finalStatus = status; - return backupRecord; - } finally { + BackupRunResult backupRecord = new BackupRunResult( + archive.id(), formatTime(startedAt), recordCurrentTime(), status, + recordedResults, archive, errorMessage); + backups.addNewBackupRecord(backupRecord); + notified = true; + webhook.notifyRun(backupRecord); + return backupRecord; + } catch (RuntimeException e) { + if (started && !notified) { + webhook.notifyFailure(e.getMessage()); + } + throw e; + } finally { + if (runDirectory != null) { try { - if (runDirectory != null) { - archiveService.removeRunDirectory(runDirectory); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); } catch (RuntimeException e) { LOGGER.error("Failed to clean up run directory {}", runDirectory, e); - } finally { - configLock.readLock().unlock(); } } - } finally { - synchronized (transitionLock) { - running.set(false); - if (started) { - publishFinished(finalStatus, startedAt); - } - } - } - } - - private void publishStarted(Instant startedAt) { - try { - broadcaster.publishStarted(startedAt); - } catch (RuntimeException e) { - LOGGER.warn("Failed to publish run-started event", e); - } - } - - private void publishFinished(String status, Instant startedAt) { - try { - broadcaster.publishFinished(status, startedAt, Instant.now()); - } catch (RuntimeException e) { - LOGGER.warn("Failed to publish run-finished event", e); } } @@ -342,23 +323,12 @@ private static BackupServiceResult failedResult(String serviceName, Throwable ca ); } - public T whileIdle(Supplier configChange) { - if (!configLock.writeLock().tryLock()) { - throw new BackupInProgressException("Configuration cannot be changed while a backup is running, try again once it finishes"); - } - try { - return configChange.get(); - } finally { - configLock.writeLock().unlock(); - } - } - public void servicesChanged() { scheduleService.releaseDeferral(); } public boolean isRunning() { - return running.get(); + return lifecycle.isRunning(); } public Duration getInterval() { @@ -373,16 +343,4 @@ public Duration updateInterval(Duration duration) { public void shutdownRunnerExecutor() { runnerExecutor.shutdownNow(); } - - public static class RunRejectedException extends IllegalStateException { - public RunRejectedException(String message) { - super(message); - } - } - - public static class BackupInProgressException extends IllegalStateException { - public BackupInProgressException(String message) { - super(message); - } - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java new file mode 100644 index 0000000..e3c8feb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java @@ -0,0 +1,111 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Supplier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; + +@Component +public class BackupRunLifecycle { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupRunLifecycle.class); + + private final RunStatusBroadcaster broadcaster; + private final AtomicBoolean running = new AtomicBoolean(false); + private final Object transitionLock = new Object(); + private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); + + public BackupRunLifecycle(RunStatusBroadcaster broadcaster) { + this.broadcaster = broadcaster; + } + + @FunctionalInterface + public interface RunBody { + BackupRunResult execute(Run run); + } + + public final class Run { + + private final Instant startedAt; + private boolean started; + + private Run(Instant startedAt) { + this.startedAt = startedAt; + } + + public void markStarted() { + if (started) { + return; + } + started = true; + publishStarted(startedAt); + } + } + + public BackupRunResult run(Instant startedAt, RunBody body) { + synchronized (transitionLock) { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new RunRejectedException("A backup run is already in progress"); + } + } + Run run = new Run(startedAt); + String finalStatus = FAILED; + try { + configLock.readLock().lock(); + try { + BackupRunResult result = body.execute(run); + finalStatus = result.status(); + return result; + } finally { + configLock.readLock().unlock(); + } + } finally { + synchronized (transitionLock) { + running.set(false); + if (run.started) { + publishFinished(finalStatus, startedAt); + } + } + } + } + + public T whileIdle(Supplier configChange) { + if (!configLock.writeLock().tryLock()) { + throw new BackupInProgressException("Configuration cannot be changed while a backup is running, try again once it finishes"); + } + try { + return configChange.get(); + } finally { + configLock.writeLock().unlock(); + } + } + + public boolean isRunning() { + return running.get(); + } + + private void publishStarted(Instant startedAt) { + try { + broadcaster.publishStarted(startedAt); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-started event", e); + } + } + + private void publishFinished(String status, Instant startedAt) { + try { + broadcaster.publishFinished(status, startedAt, Instant.now()); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-finished event", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index 1b21d86..1034c12 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -2,6 +2,7 @@ import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; @@ -11,30 +12,65 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @Service public class BackupScheduleService { + public static final Duration MIN_INTERVAL = Duration.ofMinutes(15); + public static final Duration MAX_INTERVAL = Duration.ofDays(365); + private static final Duration DEFAULT_INTERVAL = Duration.ofHours(12); private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); - private final DatabaseService db; + private final MediaGarrdProperties properties; + private final SettingsRepository settings; + private final Clock clock; private final AtomicReference currentInterval; private final AtomicReference nextRun; private final AtomicBoolean deferred = new AtomicBoolean(); + private final AtomicBoolean awaitingSetup = new AtomicBoolean(); + private final AtomicReference lastRunStarted = new AtomicReference<>(); + private final BackupRecordRepository backups; + private final SetupService setup; + + @Autowired + public BackupScheduleService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups, SetupService setup) { + this(properties, settings, backups, setup, Clock.systemUTC()); + } - public BackupScheduleService(MediaGarrdProperties properties, DatabaseService db) { - this.db = db; - Duration interval = db.fetchSetting(BACKUP_INTERVAL_SETTING) - .flatMap(BackupScheduleService::parse) - .orElseGet(() -> safe(properties.getBackupInterval())); + BackupScheduleService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups, SetupService setup, Clock clock) { + this.properties = properties; + this.settings = settings; + this.backups = backups; + this.setup = setup; + this.clock = clock; + Duration interval = storedOrConfiguredInterval(); this.currentInterval = new AtomicReference<>(interval); - this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); + this.nextRun = new AtomicReference<>(computeNextRun(interval)); LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); } + private Duration storedOrConfiguredInterval() { + return settings.fetchSetting(BACKUP_INTERVAL_SETTING) + .flatMap(BackupScheduleService::parse) + .orElseGet(() -> fromProperties(properties.getBackupInterval())); + } + + public void reloadFromSettings() { + Duration interval = storedOrConfiguredInterval(); + Instant next = computeNextRun(interval); + currentInterval.set(interval); + nextRun.set(next); + deferred.set(false); + LOGGER.info("Backup schedule reloaded from the settings: interval={}, nextRunAt={}", interval, next); + } + public Duration getInterval() { return currentInterval.get(); } @@ -44,58 +80,106 @@ public Instant getNextRun() { } public Duration updateInterval(Duration interval) { - Duration safe = safe(interval); - db.saveSetting(BACKUP_INTERVAL_SETTING, safe.toString()); - currentInterval.set(safe); - Instant next = Instant.now().plus(safe); + validate(interval); + Instant next = computeNextRun(interval); + settings.saveSetting(BACKUP_INTERVAL_SETTING, interval.toString()); + currentInterval.set(interval); nextRun.set(next); deferred.set(false); - LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); - return safe; + LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", interval, next); + return interval; } public boolean dueNow() { - Instant now = Instant.now(); + Instant now = clock.instant(); + if (awaitingSetup.get() && setup.isCompleted() && awaitingSetup.compareAndSet(true, false)) { + nextRun.set(now); + LOGGER.info("Setup is completed, the first scheduled backup is due now"); + } Instant current = nextRun.get(); return !now.isBefore(current); } public void markRunStarted() { - Instant next = Instant.now().plus(currentInterval.get()); + lastRunStarted.set(clock.instant()); + Instant next = clock.instant().plus(currentInterval.get()); nextRun.set(next); + awaitingSetup.set(false); deferred.set(false); LOGGER.info("Backup run started: nextScheduledRun={}", next); } public void deferNextRun() { - Instant next = Instant.now().plus(currentInterval.get()); + Instant next = clock.instant().plus(currentInterval.get()); nextRun.set(next); + awaitingSetup.set(false); deferred.set(true); LOGGER.info("Nothing to back up yet, next scheduled check at {}", next); } public void releaseDeferral() { if (deferred.compareAndSet(true, false)) { - nextRun.set(Instant.now()); + nextRun.set(clock.instant()); LOGGER.info("Services are configured, the next scheduled backup is due now"); } } + private Instant computeNextRun(Duration interval) { + Instant now = clock.instant(); + awaitingSetup.set(false); + Optional recorded; + try { + recorded = backups.fetchLastSuccessfulStartTime(); + } catch (RuntimeException e) { + LOGGER.warn("Could not read the last successful backup, the next scheduled backup is one interval from now", e); + return now.plus(interval); + } + Optional last = recorded.map(this::laterThanThisRun).or(() -> Optional.ofNullable(lastRunStarted.get())); + if (last.isPresent()) { + Instant due = last.get().plus(interval); + return due.isAfter(now) && !last.get().isAfter(now) ? due : now; + } + if (setup.isCompleted()) { + return now; + } + awaitingSetup.set(true); + return now.plus(interval); + } + + private Instant laterThanThisRun(Instant recorded) { + Instant started = lastRunStarted.get(); + return started != null && started.isAfter(recorded) && !started.isAfter(clock.instant()) ? started : recorded; + } + private static Optional parse(String stored) { try { - return Optional.of(Duration.parse(stored)).filter(BackupScheduleService::isValid); + Duration interval = Duration.parse(stored); + if (!inRange(interval)) { + LOGGER.warn("Ignoring out-of-range stored backup interval: {}", LogSanitizer.clean(stored)); + return Optional.empty(); + } + return Optional.of(interval); } catch (DateTimeParseException e) { - LOGGER.warn("Ignoring invalid stored backup interval: {}", stored); + LOGGER.warn("Ignoring invalid stored backup interval: {}", LogSanitizer.clean(stored)); return Optional.empty(); } } - private static boolean isValid(Duration interval) { - return interval != null && !interval.isNegative() && !interval.isZero(); + private static Duration fromProperties(Duration configured) { + if (!inRange(configured)) { + LOGGER.warn("Ignoring out-of-range MEDIAGARRD_BACKUP_INTERVAL {}, using {}", configured, DEFAULT_INTERVAL); + return DEFAULT_INTERVAL; + } + return configured; } - private static Duration safe(Duration interval) { - // Default to 12 hours if the provided interval is invalid - return isValid(interval) ? interval : Duration.ofHours(12); + private static boolean inRange(Duration interval) { + return interval != null && interval.compareTo(MIN_INTERVAL) >= 0 && interval.compareTo(MAX_INTERVAL) <= 0; + } + + private static void validate(Duration interval) { + if (!inRange(interval)) { + throw new IllegalArgumentException("Backup interval must be between 15 minutes and 365 days"); + } } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java index ded1f51..bd05951 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java @@ -3,7 +3,6 @@ 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; @@ -44,16 +43,12 @@ public boolean insideContainer() { } 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; + return name == null || name.isBlank() ? List.of() : List.of(name.strip()); } private Optional mountedContainerId() { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java new file mode 100644 index 0000000..d98e0df --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java @@ -0,0 +1,32 @@ +package wellatleastitried.mediagarrdServer.service; + +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.repository.SqliteDatabase; + +@Component +@Lazy(false) +public class DatabaseRebuildHandler { + + private final PairingService pairing; + private final RunStatusBroadcaster broadcaster; + private final BackupArchiveService archives; + private final BackupScheduleService schedule; + + public DatabaseRebuildHandler(SqliteDatabase database, PairingService pairing, RunStatusBroadcaster broadcaster, + BackupArchiveService archives, BackupScheduleService schedule) { + this.pairing = pairing; + this.broadcaster = broadcaster; + this.archives = archives; + this.schedule = schedule; + database.addRebuildListener(this::reset); + } + + void reset() { + pairing.resetAfterRebuild(); + archives.reloadFromSettings(); + schedule.reloadFromSettings(); + broadcaster.closeAll(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java deleted file mode 100644 index d76ca4a..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ /dev/null @@ -1,638 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_RECORD; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_SERVICE_RECORD; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_SERVICE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_SERVICE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_ALL_SERVICES; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LATEST_RECORD; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_RECORD_BY_ID; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICES_FROM_RECORD; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICE_BY_NAME; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SETTING; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPDATE_SERVICE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPSERT_SETTING; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SQLITE; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -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; -import com.fasterxml.jackson.databind.ObjectMapper; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; -import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import wellatleastitried.mediagarrdServer.model.ServiceDefinition; -import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; - -@Service -public class DatabaseService { - - private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); - private static final ObjectMapper JSON = new ObjectMapper(); - private static final TypeReference> PATH_LIST = new TypeReference<>() {}; - - private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter - .ofPattern("yyyyMMdd-HHmmss") - .withZone(ZoneOffset.UTC); - - 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; - - private record SchemaFingerprint(int userVersion, int schemaVersion) {} - - public DatabaseService(MediaGarrdProperties properties) { - databaseFile = Path.of(properties.getDatabasePath()).toAbsolutePath(); - databaseUrl = SQLITE + databaseFile; - verifyDatabaseIntegrity(); - } - - protected Connection getConnection() throws SQLException { - Connection connection = DriverManager.getConnection(databaseUrl); - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA foreign_keys = ON"); - } catch (SQLException sE) { - connection.close(); - throw sE; - } - return connection; - } - - protected synchronized boolean verifyDatabaseIntegrity() { - verifiedSchema = null; - try { - rebuildIfNeeded(); - return true; - } catch (SQLException sE) { - if (!isCorrupt(sE) || !quarantineDatabase()) { - LOGGER.warn("An error occurred while verifying the integrity of the database", sE); - return false; - } - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); - return false; - } - - try { - rebuildIfNeeded(); - return true; - } catch (Exception e) { - LOGGER.warn("Unable to create a new database after moving the corrupt one aside", e); - return false; - } - } - - private void rebuildIfNeeded() throws SQLException { - try { - Files.createDirectories(databaseFile.getParent()); - } catch (IOException iE) { - LOGGER.warn("Unable to create database directory " + databaseFile.getParent(), iE); - } - try (var connection = getConnection()) { - checkNotCorrupt(connection); - connection.setAutoCommit(false); - ensureTablesExist(connection); - runNeededMigrations(connection); - verifiedSchema = fingerprint(connection); - } - } - - private Connection openVerifiedConnection() throws SQLException { - SchemaFingerprint expected = verifiedSchema; - if (expected != null) { - Connection connection = null; - try { - connection = getConnection(); - if (fingerprint(connection).equals(expected)) { - return connection; - } - } catch (SQLException sE) { - LOGGER.debug("Unable to read the database schema fingerprint", sE); - } - if (connection != null) { - connection.close(); - } - LOGGER.info("Database does not match the verified schema, rebuilding it"); - } - if (!verifyDatabaseIntegrity()) { - throw new SQLException("Database integrity check failed"); - } - return getConnection(); - } - - private static SchemaFingerprint fingerprint(Connection connection) throws SQLException { - try (var statement = connection.createStatement(); - var rs = statement.executeQuery("SELECT user_version, schema_version FROM pragma_user_version, pragma_schema_version")) { - return new SchemaFingerprint(rs.getInt(1), rs.getInt(2)); - } - } - - private static void checkNotCorrupt(Connection connection) throws SQLException { - try (var statement = connection.createStatement(); var rs = statement.executeQuery("PRAGMA quick_check")) { - String result = rs.next() ? rs.getString(1) : "no result"; - if (!"ok".equals(result)) { - throw new CorruptDatabaseException("Database failed its integrity check: " + result); - } - } - } - - private boolean invalidateIfDamaged(SQLException e) { - String message = String.valueOf(e.getMessage()); - boolean damaged = isCorrupt(e) || message.contains("no such table") || message.contains("no such column"); - if (damaged) { - verifiedSchema = null; - } - return damaged; - } - - private static boolean isCorrupt(SQLException e) { - if (e instanceof CorruptDatabaseException) { - return true; - } - if (e instanceof SQLiteException sqlite) { - int code = sqlite.getResultCode().code & 0xFF; - return code == SQLiteErrorCode.SQLITE_CORRUPT.code || code == SQLiteErrorCode.SQLITE_NOTADB.code; - } - return false; - } - - private boolean quarantineDatabase() { - if (!Files.isRegularFile(databaseFile)) { - return false; - } - String suffix = ".corrupt-" + QUARANTINE_FORMAT.format(Instant.now()); - try { - for (String fileSuffix : DATABASE_FILE_SUFFIXES) { - Path file = Path.of(databaseFile + fileSuffix); - if (Files.isRegularFile(file)) { - Files.move(file, Path.of(file + suffix)); - } - } - } catch (IOException iE) { - LOGGER.error("Database {} is corrupt and could not be moved aside", databaseFile, iE); - return false; - } - LOGGER.error("Database {} was corrupt, moved it to {}{} and created a new one. Settings and services must be configured again", - databaseFile, databaseFile, suffix); - return true; - } - - private static class CorruptDatabaseException extends SQLException { - CorruptDatabaseException(String message) { - super(message); - } - } - - private void ensureTablesExist(Connection connection) throws SQLException { - try (var statement = connection.createStatement()) { - for (String sql : CREATE_TABLES.split(";")) { - String CREATE_STATEMENT = sql.trim(); - if (!CREATE_STATEMENT.isEmpty()) { - statement.execute(CREATE_STATEMENT); - } - } - - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("Failed to verify if tables exist in database.", sE); - handleSqlException(connection); - throw sE; - } - } - - private void runNeededMigrations(Connection connection) throws SQLException { - int currentVersion = getDatabaseVersion(connection); - if (currentVersion == -1) return; - - // 0 means it is a brand new database, or it was created before migrations existed - if (currentVersion == 0) { - // Initial tables will be "v1" - currentVersion = 1; - setDatabaseVersion(connection, currentVersion); - } - - for (Migration migration : MIGRATIONS) { - if (currentVersion >= migration.version()) { - continue; - } - - try (var statement = connection.createStatement()) { - statement.execute(migration.sql()); - } catch (SQLException sE) { - LOGGER.warn( - "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", - sE - ); - handleSqlException(connection); - throw sE; - } - - currentVersion = migration.version(); - setDatabaseVersion(connection, currentVersion); - } - - connection.commit(); - } - - protected int getDatabaseVersion(Connection connection) { - try (var statement = connection.createStatement(); - var result = statement.executeQuery("PRAGMA user_version")) { - - return result.getInt(1); - } catch (SQLException sE) { - LOGGER.warn("Failed to fetch database version", sE); - return -1; - } - } - - protected void setDatabaseVersion(Connection connection, int version) { - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA user_version = " + version); - } catch (SQLException sE) { - LOGGER.warn("Failed to set new database version", sE); - } - } - - public void addNewBackupRecord(BackupRunResult backupRecord) { - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - connection.setAutoCommit(false); - Integer backupId = addMasterBackup(connection, backupRecord); - if (backupId != null) { - addServiceBackups(connection, backupId, backupRecord.serviceResults()); - } - } catch (SQLException sE) { - 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(); - } - } - - private Integer addMasterBackup(Connection connection, BackupRunResult backupRecord) { - try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { - statement.setString(1, backupRecord.runId()); - statement.setString(2, backupRecord.startTime()); - statement.setString(3, backupRecord.endTime()); - statement.setString(4, backupRecord.status()); - BackupArchive archive = backupRecord.archive(); - statement.setString(5, archive == null ? null : archive.resolvedChecksum()); - statement.setString(6, archive == null ? null : archive.path().toString()); - statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); - statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); - statement.setString(9, backupRecord.errorMessage()); - statement.executeUpdate(); - int backupId; - try (var idQuery = connection.createStatement(); - var keys = idQuery.executeQuery("SELECT last_insert_rowid()")) { - backupId = keys.getInt(1); - } - connection.commit(); - return backupId; - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("An error occurred while logging a new backup record", sE); - handleSqlException(connection); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while logging a new backup record", e); - } - return null; - } - - private void addServiceBackups(Connection connection, int backupId, List serviceResults) { - for (BackupServiceResult service : serviceResults) { - try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { - statement.setInt(1, backupId); - statement.setString(2, service.serviceName()); - statement.setString(3, service.status()); - statement.setString(4, service.startTime()); - statement.setString(5, service.endTime()); - statement.setString(6, service.errorMessage()); - statement.executeUpdate(); - connection.commit(); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); - handleSqlException(connection); - } - } - } - - private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs) throws SQLException { - if (!rs.next()) { - return null; - } - - int id = rs.getInt("id"); - String archiveId = rs.getString("archive_id"); - String backupStartTime = rs.getString("start_time"); - String backupEndTime = rs.getString("end_time"); - String status = rs.getString("status"); - String filePath = rs.getString("file_path"); - String errorMessage = rs.getString("error_message"); - - return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); - } - - public Optional fetchBackupById(String archiveId) { - FetchedBackupRecord backupRecord = null; - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - backupRecord = fetchMasterRecordById(connection, archiveId); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - 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); - } - - private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { - try (var statement = connection.prepareStatement(FETCH_RECORD_BY_ID)) { - statement.setString(1, archiveId); - var rs = statement.executeQuery(); - return buildFetchedBackupRecordFromQueryResult(rs); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", sE); - return null; - } - } - - public Optional fetchLatestBackupRecord() { - FetchedBackupRecord backupRecord = null; - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - backupRecord = fetchLatestMasterRecord(connection); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - 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); - } - - private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { - try (var statement = connection.createStatement()) { - var rs = statement.executeQuery(FETCH_LATEST_RECORD); - return buildFetchedBackupRecordFromQueryResult(rs); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { - try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_RECORD)) { - statement.setInt(1, backupRecord.id()); - var rs = statement.executeQuery(); - - while (rs.next()) { - String serviceName = rs.getString("service_name"); - String status = rs.getString("status"); - String startTime = rs.getString("start_time"); - String endTime = rs.getString("end_time"); - String errorMessage = rs.getString("error_message"); - var serviceRecord = new FetchedBackupServiceRecord( - serviceName, - status, - startTime, - endTime, - errorMessage - ); - backupRecord.fetchedServices().add(serviceRecord); - } - return backupRecord; - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error populating backup record with related services", sE); - return null; - } - } - - private void handleSqlException(Connection connection) { - try { - connection.rollback(); - } catch (SQLException rollbackException) { - LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); - } - } - - 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); - statement.executeUpdate(); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); - } finally { - databaseLock.readLock().unlock(); - } - } - - public List fetchServices() { - return query("fetch configured services", FETCH_ALL_SERVICES, DatabaseService::toServiceDefinition); - } - - public Optional fetchService(String name) { - return query("fetch service " + name, FETCH_SERVICE_BY_NAME, DatabaseService::toServiceDefinition, name) - .stream().findFirst(); - } - - public void addService(ServiceDefinition service) { - update("add service " + service.name(), ADD_SERVICE, service.name(), toJson(service.paths())); - } - - public boolean updateService(String name, ServiceDefinition service) { - return update("update service " + name, UPDATE_SERVICE, service.name(), toJson(service.paths()), name) > 0; - } - - public boolean removeService(String name) { - return update("remove service " + name, DELETE_SERVICE, name) > 0; - } - - public Optional fetchSetting(String key) { - return query("fetch setting " + key, FETCH_SETTING, rs -> rs.getString("value"), key).stream().findFirst(); - } - - public void saveSetting(String key, String value) { - update("save setting " + key, UPSERT_SETTING, key, value); - } - - @FunctionalInterface - private interface RowMapper { - T map(ResultSet rs) throws SQLException; - } - - @FunctionalInterface - private interface StatementWork { - T run(PreparedStatement statement) throws SQLException; - } - - private List query(String action, String sql, RowMapper mapper, String... params) { - return execute(action, sql, params, statement -> { - try (var rs = statement.executeQuery()) { - List rows = new ArrayList<>(); - while (rs.next()) { - rows.add(mapper.map(rs)); - } - return rows; - } - }); - } - - private int update(String action, String sql, String... params) { - return execute(action, sql, params, PreparedStatement::executeUpdate); - } - - private T execute(String action, String sql, String[] params, StatementWork work) { - 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"); - } - 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); - } - } - } - - private static void bind(PreparedStatement statement, String... params) throws SQLException { - for (int i = 0; i < params.length; i++) { - statement.setString(i + 1, params[i]); - } - } - - private static ServiceDefinition toServiceDefinition(ResultSet rs) throws SQLException { - try { - return new ServiceDefinition(rs.getString("name"), JSON.readValue(rs.getString("paths"), PATH_LIST)); - } catch (JsonProcessingException jE) { - throw new SQLException("Corrupt paths for service " + rs.getString("name"), jE); - } - } - - private static String toJson(List paths) { - try { - return JSON.writeValueAsString(paths); - } catch (JsonProcessingException jE) { - throw new IllegalStateException("Failed to serialize service paths", jE); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java index 506cbbe..9f9d541 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -22,6 +22,7 @@ import org.springframework.stereotype.Service; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.repository.SqliteDatabase; @Service public class DatabaseSnapshotService { @@ -34,11 +35,11 @@ public class DatabaseSnapshotService { private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private static final String SNAPSHOT_FILE = "snapshot.db"; - private final DatabaseService db; + private final SqliteDatabase db; private final DatabaseHostPathResolver hostPaths; private final ZipCompression compression; - public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { + public DatabaseSnapshotService(SqliteDatabase db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { this.db = db; this.hostPaths = hostPaths; this.compression = compression; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java index eb36c32..a937f2d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -1,10 +1,6 @@ package wellatleastitried.mediagarrdServer.service; import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -23,6 +19,7 @@ import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.utilities.Sha256; @Service public class DockerService { @@ -44,15 +41,17 @@ public DockerService(DockerClient client, MediaGarrdProperties properties) { public String containerFor(ServiceDefinition service) { String hash = configHash(service); + String reusable = null; for (Container container : managedContainers(service.name())) { - if (hash.equals(container.getLabels().get(CONFIG_HASH_LABEL))) { - LOGGER.debug("[{}] Reusing helper container {}", service.name(), container.getId()); - return container.getId(); + if (reusable == null && hash.equals(container.getLabels().get(CONFIG_HASH_LABEL))) { + reusable = container.getId(); + LOGGER.debug("[{}] Reusing helper container {}", service.name(), reusable); + continue; } - LOGGER.info("[{}] Service config changed, removing stale helper container {}", service.name(), container.getId()); + LOGGER.info("[{}] Removing stale helper container {}", service.name(), container.getId()); removeContainer(container.getId()); } - return createContainer(service, hash); + return reusable != null ? reusable : createContainer(service, hash); } public InputStream copyFrom(String containerId, String hostPath) { @@ -78,12 +77,7 @@ static String containerPath(String hostPath) { String configHash(ServiceDefinition service) { String fingerprint = helperImage + "\n" + String.join("\n", service.paths().stream().sorted().toList()); - try { - byte[] digest = MessageDigest.getInstance("SHA-256").digest(fingerprint.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } + return Sha256.hex(fingerprint); } private List managedContainers(String serviceName) { @@ -121,9 +115,9 @@ private synchronized void ensureHelperImage() { if (!client.pullImageCmd(helperImage).start().awaitCompletion(IMAGE_PULL_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { throw new IllegalStateException("Timed out pulling helper image " + helperImage); } - } catch (InterruptedException iE) { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, iE); + throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, ex); } } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java new file mode 100644 index 0000000..36040fa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; + +public class LockedOutException extends RuntimeException { + + private final Duration retryAfter; + + public LockedOutException(Duration retryAfter) { + super("Too many wrong attempts, try again in " + describe(retryAfter)); + this.retryAfter = retryAfter; + } + + public Duration retryAfter() { + return retryAfter; + } + + private static String describe(Duration duration) { + long minutes = (duration.toSeconds() + 59) / 60; + return minutes <= 1 ? "a minute" : minutes + " minutes"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java new file mode 100644 index 0000000..7429ea9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdServer.service; + +public class PairingException extends RuntimeException { + + public enum Reason { SETUP_INCOMPLETE, CLOSED, INVALID } + + private final Reason reason; + + public PairingException(Reason reason, String message) { + super(message); + this.reason = reason; + } + + public Reason reason() { + return reason; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java new file mode 100644 index 0000000..7a4639b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java @@ -0,0 +1,249 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; +import wellatleastitried.mediagarrdServer.utilities.Sha256; + +@Service +public class PairingService { + + private static final Logger LOGGER = LoggerFactory.getLogger(PairingService.class); + + static final Duration CODE_TTL = Duration.ofMinutes(10); + static final Duration CODE_LOCK_DURATION = Duration.ofMinutes(10); + static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1); + static final int MAX_CODE_FAILURES = 10; + static final Duration PENDING_TTL = Duration.ofMinutes(5); + static final int MAX_OPEN_CODES = 10; + static final int MAX_PENDING = 10; + static final int CODE_LENGTH = 10; + static final int MAX_TOKEN_LENGTH = 256; + static final int MAX_CREDENTIAL_LENGTH = 64; + private static final String CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; + private static final Pattern PIN_SHAPE = Pattern.compile("[0-9]{6}"); + private static final Pattern NAME_PATTERN = Pattern.compile("[\\p{L}\\p{N} ._()'@+-]{1,64}"); + private static final SecureRandom RANDOM = new SecureRandom(); + + private final SetupService setup; + private final PairedClientRepository pairedClients; + private final RunStatusBroadcaster broadcaster; + private final Clock clock; + private final AttemptLimiter codeLimiter; + private final Map codes = new LinkedHashMap<>(); + private final Map pending = new LinkedHashMap<>(); + private final Map lastTouched = new ConcurrentHashMap<>(); + + private record PendingPairing(String id, String name, Instant expiresAt, String codeHash, long epoch) {} + + @Autowired + public PairingService(SetupService setup, PairedClientRepository pairedClients, RunStatusBroadcaster broadcaster) { + this(setup, pairedClients, broadcaster, Clock.systemUTC()); + } + + PairingService(SetupService setup, PairedClientRepository pairedClients, RunStatusBroadcaster broadcaster, Clock clock) { + this.setup = setup; + this.pairedClients = pairedClients; + this.broadcaster = broadcaster; + this.clock = clock; + this.codeLimiter = new AttemptLimiter(MAX_CODE_FAILURES, CODE_LOCK_DURATION, clock); + } + + public synchronized PairResponse pair(String credential, String requestedName) { + String name = cleanName(requestedName); + String value = credential == null ? "" : credential.strip(); + if (value.isEmpty()) { + throw new IllegalArgumentException("A PIN or pairing code is required"); + } + if (value.length() > MAX_CREDENTIAL_LENGTH) { + throw new IllegalArgumentException("The PIN or pairing code is too long"); + } + if (!setup.isCompleted()) { + throw new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair."); + } + if (PIN_SHAPE.matcher(value).matches()) { + return registerPending(name, null, setup.checkPairingPin(value)); + } + return registerPending(name, checkCode(value), 0); + } + + public synchronized PairingCodeDto createCode() { + Instant now = clock.instant(); + codes.values().removeIf(expiry -> !expiry.isAfter(now)); + while (codes.size() >= MAX_OPEN_CODES) { + String evicted = codes.keySet().iterator().next(); + codes.remove(evicted); + pending.values().removeIf(entry -> evicted.equals(entry.codeHash())); + } + StringBuilder code = new StringBuilder(CODE_LENGTH); + for (int i = 0; i < CODE_LENGTH; i++) { + code.append(CODE_ALPHABET.charAt(RANDOM.nextInt(CODE_ALPHABET.length()))); + } + Instant expiresAt = now.plus(CODE_TTL); + codes.put(hashToken(code.toString()), expiresAt); + LOGGER.info("Pairing code created, it expires at {}", expiresAt); + return new PairingCodeDto(code.substring(0, CODE_LENGTH / 2) + "-" + code.substring(CODE_LENGTH / 2), expiresAt); + } + + public Optional authenticate(String token) { + if (token == null || token.isEmpty() || token.length() > MAX_TOKEN_LENGTH) { + return Optional.empty(); + } + String tokenHash = hashToken(token); + Optional client = pairedClients.fetchPairedClientByTokenHash(tokenHash); + if (client.isEmpty()) { + client = confirm(tokenHash); + } + client.ifPresent(this::recordUse); + return client; + } + + public List list() { + return pairedClients.fetchPairedClients(); + } + + public boolean isPaired(String id) { + return pairedClients.fetchPairedClients().stream().anyMatch(client -> client.id().equals(id)); + } + + public synchronized boolean revoke(String id) { + boolean removed = pairedClients.removePairedClient(id); + if (removed) { + lastTouched.remove(id); + broadcaster.closeClient(id); + LOGGER.info("Client {} was unpaired", LogSanitizer.clean(id)); + if (pairedClients.countPairedClients() == 0) { + LOGGER.info("No Client is paired any more, opening pairing again"); + setup.reopenPairing(); + } + } + return removed; + } + + synchronized void resetAfterRebuild() { + codes.clear(); + pending.clear(); + lastTouched.clear(); + codeLimiter.reset(); + setup.resetAfterRebuild(); + } + + public static String hashToken(String token) { + return Sha256.hex(token); + } + + private synchronized Optional confirm(String tokenHash) { + Optional existing = pairedClients.fetchPairedClientByTokenHash(tokenHash); + if (existing.isPresent()) { + return existing; + } + PendingPairing entry = pending.get(tokenHash); + if (entry == null) { + return Optional.empty(); + } + Instant now = clock.instant(); + if (!entry.expiresAt().isAfter(now)) { + pending.remove(tokenHash); + return Optional.empty(); + } + boolean viaPin = entry.codeHash() == null; + if (viaPin && !setup.isPairingOpen(entry.epoch())) { + pending.remove(tokenHash); + return Optional.empty(); + } + boolean firstClient = pairedClients.countPairedClients() == 0; + pairedClients.addPairedClient(entry.id(), entry.name(), tokenHash, now); + pending.remove(tokenHash); + if (!viaPin && firstClient) { + setup.closeCurrentPairing(); + pending.values().removeIf(other -> other.codeHash() == null); + } + if (viaPin) { + setup.closePairing(entry.epoch()); + pending.values().removeIf(other -> other.codeHash() == null); + } else { + codes.remove(entry.codeHash()); + pending.values().removeIf(other -> entry.codeHash().equals(other.codeHash())); + } + LOGGER.info("Client {} confirmed its pairing ({})", LogSanitizer.clean(entry.name()), entry.id()); + return pairedClients.fetchPairedClientByTokenHash(tokenHash); + } + + private String checkCode(String candidate) { + codeLimiter.checkNotLocked(); + String normalized = candidate.replace("-", "").replace(" ", "").toUpperCase(Locale.ROOT); + String codeHash = hashToken(normalized); + Instant expiry = codes.get(codeHash); + if (expiry == null || !expiry.isAfter(clock.instant())) { + int failures = codeLimiter.recordFailure(); + LOGGER.warn("Rejected pairing code attempt ({}/{})", failures, MAX_CODE_FAILURES); + throw new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code"); + } + codeLimiter.reset(); + return codeHash; + } + + private PairResponse registerPending(String requestedName, String codeHash, long epoch) { + Instant now = clock.instant(); + pending.values().removeIf(entry -> !entry.expiresAt().isAfter(now)); + while (pending.size() >= MAX_PENDING) { + pending.remove(pending.keySet().iterator().next()); + } + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + byte[] idBytes = new byte[8]; + RANDOM.nextBytes(idBytes); + String id = HexFormat.of().formatHex(idBytes); + String name = requestedName != null ? requestedName : "Client " + id.substring(0, 6); + pending.put(hashToken(token), new PendingPairing(id, name, now.plus(PENDING_TTL), codeHash, epoch)); + LOGGER.info("Client pairing started: {} ({}), it is confirmed by the Client's first request with its token", LogSanitizer.clean(name), id); + return new PairResponse(token, id, name); + } + + private void recordUse(PairedClient client) { + Instant now = clock.instant(); + Instant last = lastTouched.get(client.id()); + if (last != null && now.isBefore(last.plus(TOUCH_INTERVAL))) { + return; + } + lastTouched.put(client.id(), now); + try { + pairedClients.touchPairedClient(client.id(), now); + } catch (IllegalStateException e) { + LOGGER.debug("Unable to record last use for client {}: {}", client.id(), e.getMessage()); + } + } + + private static String cleanName(String name) { + if (name == null || name.isBlank()) { + return null; + } + String stripped = name.strip(); + if (!NAME_PATTERN.matcher(stripped).matches()) { + throw new IllegalArgumentException("Name must be 1 to 64 characters: letters, digits, spaces and . _ - ( ) ' @ +"); + } + return stripped; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java new file mode 100644 index 0000000..ebb99e4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; + +public class RateLimitedException extends RuntimeException { + + private final Duration retryAfter; + + public RateLimitedException(String message, Duration retryAfter) { + super(message); + this.retryAfter = retryAfter; + } + + public Duration retryAfter() { + return retryAfter; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java new file mode 100644 index 0000000..be998c9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class RunRejectedException extends IllegalStateException { + + public RunRejectedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java index 0a19f73..b9edf53 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java @@ -62,11 +62,19 @@ private static Thread newWriterThread(Runnable runnable) { } public SseEmitter subscribe() { - return subscribe(new SseEmitter(emitterTimeoutMs)); + return subscribe(new SseEmitter(emitterTimeoutMs), null); + } + + public SseEmitter subscribe(String clientId) { + return subscribe(new SseEmitter(emitterTimeoutMs), clientId); } SseEmitter subscribe(SseEmitter emitter) { - Subscriber subscriber = new Subscriber(emitter); + return subscribe(emitter, null); + } + + SseEmitter subscribe(SseEmitter emitter, String clientId) { + Subscriber subscriber = new Subscriber(emitter, clientId); synchronized (lock) { if (shutdown || subscribers.size() >= maxSubscribers) { throw new SubscriberLimitException("Too many event stream subscribers"); @@ -119,6 +127,24 @@ private void publish(String name, Boolean nowRunning, String json) { } } + public void closeClient(String clientId) { + List toClose; + synchronized (lock) { + toClose = subscribers.stream().filter(subscriber -> clientId.equals(subscriber.clientId)).toList(); + subscribers.removeAll(toClose); + } + toClose.forEach(Subscriber::close); + } + + public void closeAll() { + List toClose; + synchronized (lock) { + toClose = new ArrayList<>(subscribers); + subscribers.clear(); + } + toClose.forEach(Subscriber::close); + } + int subscriberCount() { synchronized (lock) { return subscribers.size(); @@ -152,12 +178,14 @@ public SubscriberLimitException(String message) { private final class Subscriber { private final SseEmitter emitter; + private final String clientId; private final BlockingQueue queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY); private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicBoolean ended = new AtomicBoolean(); - Subscriber(SseEmitter emitter) { + Subscriber(SseEmitter emitter, String clientId) { this.emitter = emitter; + this.clientId = clientId; } void close() { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java new file mode 100644 index 0000000..1a7b381 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java @@ -0,0 +1,82 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.List; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; + +@Service +public class ServiceConfigService { + + private final ServiceRepository services; + private final DockerService docker; + private final BackupOrchestratorService orchestrator; + private final BackupRunLifecycle lifecycle; + private final RunStatusBroadcaster broadcaster; + + public ServiceConfigService( + ServiceRepository services, + DockerService docker, + BackupOrchestratorService orchestrator, + BackupRunLifecycle lifecycle, + RunStatusBroadcaster broadcaster + ) { + this.services = services; + this.docker = docker; + this.orchestrator = orchestrator; + this.lifecycle = lifecycle; + this.broadcaster = broadcaster; + } + + public List list() { + return services.fetchServices(); + } + + public ServiceDefinition add(ServiceDefinition service) { + return lifecycle.whileIdle(() -> { + requireNameFree(service.name()); + services.addService(service); + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); + return service; + }); + } + + public ServiceDefinition update(String name, ServiceDefinition service) { + return lifecycle.whileIdle(() -> { + String currentName = require(name).name(); + if (!service.name().equalsIgnoreCase(currentName)) { + requireNameFree(service.name()); + } + services.updateService(currentName, service); + if (!service.name().equals(currentName)) { + docker.removeContainers(currentName); + } + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); + return service; + }); + } + + public void remove(String name) { + lifecycle.whileIdle(() -> { + String currentName = require(name).name(); + services.removeService(currentName); + docker.removeContainers(currentName); + broadcaster.publishConfigChanged(); + return null; + }); + } + + private ServiceDefinition require(String name) { + return services.fetchService(name).orElseThrow(() -> new ServiceNotFoundException("Service not found: " + name)); + } + + private void requireNameFree(String name) { + if (services.fetchService(name).isPresent()) { + throw new ServiceConflictException("Service already exists: " + name); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java new file mode 100644 index 0000000..d60c501 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class ServiceConflictException extends RuntimeException { + + public ServiceConflictException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java new file mode 100644 index 0000000..9bad642 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class ServiceNotFoundException extends RuntimeException { + + public ServiceNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java new file mode 100644 index 0000000..019c011 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class SetupAlreadyCompleteException extends IllegalStateException { + + public SetupAlreadyCompleteException() { + super("Setup is already complete"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java index 5985220..f2f79cb 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java @@ -6,16 +6,24 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.HexFormat; import java.util.Optional; -import java.util.Set; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; + @Service @Lazy(false) public class SetupService { @@ -23,21 +31,64 @@ public class SetupService { private static final Logger LOGGER = LoggerFactory.getLogger(SetupService.class); static final int MAX_FAILED_ATTEMPTS = 5; + static final Duration LOCK_DURATION = Duration.ofMinutes(10); + static final Duration SESSION_IDLE_TIMEOUT = Duration.ofMinutes(30); + static final int MAX_PIN_LENGTH = 64; private static final SecureRandom RANDOM = new SecureRandom(); - private final DatabaseService db; - private final Set sessions = ConcurrentHashMap.newKeySet(); + private final SettingsRepository settings; + private final PairedClientRepository pairedClients; + private final AttemptLimiter limiter; + private final Clock clock; + private final boolean openPairingOnStart; + private final Map sessions = new ConcurrentHashMap<>(); private volatile boolean completed; + private boolean pairingOpen; + private long pairingEpoch; private String pin; - private int failedAttempts; - public SetupService(DatabaseService db) { - this.db = db; - this.completed = db.fetchSetting(SETUP_COMPLETED_SETTING).isPresent(); - if (completed) { - LOGGER.info("Setup already completed, the web setup page is disabled"); + @Autowired + public SetupService(SettingsRepository settings, PairedClientRepository pairedClients, MediaGarrdProperties properties) { + this(settings, pairedClients, properties.isOpenPairing(), Clock.systemUTC()); + } + + SetupService(SettingsRepository settings, PairedClientRepository pairedClients, boolean openPairing, Clock clock) { + this.settings = settings; + this.pairedClients = pairedClients; + this.clock = clock; + this.limiter = new AttemptLimiter(MAX_FAILED_ATTEMPTS, LOCK_DURATION, clock); + this.openPairingOnStart = openPairing; + applyStoredState(); + } + + synchronized void resetAfterRebuild() { + sessions.clear(); + limiter.reset(); + pairingOpen = false; + pairingEpoch++; + pin = null; + applyStoredState(); + if (!completed) { + LOGGER.warn("The database was damaged and has been replaced with an empty one. Setup is open again with the Setup PIN logged above: " + + "enter it at /config to configure the server again, or restore an archive first. Paired Clients must pair again"); } else { + LOGGER.warn("The database was damaged and has been replaced. Clients that paired before must pair again"); + } + } + + private void applyStoredState() { + this.completed = settings.fetchSetting(SETUP_COMPLETED_SETTING).isPresent(); + if (!completed) { rotatePin(); + } else if (openPairingOnStart) { + LOGGER.warn("MEDIAGARRD_OPEN_PAIRING is set, pairing is open on every start while it is set. Remove it once the Client is paired"); + openPairing(); + } else if (pairedClients.countPairedClients() == 0) { + LOGGER.info("Setup is completed but no Client is paired"); + openPairing(); + } else { + LOGGER.info("Setup already completed, the web setup page is disabled and pairing is closed. " + + "Request a pairing code from a paired Client, or restart with MEDIAGARRD_OPEN_PAIRING=true to print a new PIN"); } } @@ -46,46 +97,134 @@ public boolean isCompleted() { } public boolean canConfigure(String sessionToken) { - return completed || (sessionToken != null && sessions.contains(sessionToken)); + if (completed || sessionToken == null) { + return false; + } + Instant now = clock.instant(); + return sessions.computeIfPresent(sessionToken, (token, lastSeen) -> expired(lastSeen, now) ? null : now) != null; + } + + public synchronized boolean isPairingOpen() { + return pairingOpen; } public synchronized Optional startSession(String candidate) { if (completed) { return Optional.empty(); } - if (candidate == null || !MessageDigest.isEqual(bytes(pin), bytes(candidate.strip()))) { - failedAttempts++; - LOGGER.warn("Rejected setup PIN attempt ({}/{})", failedAttempts, MAX_FAILED_ATTEMPTS); - if (failedAttempts >= MAX_FAILED_ATTEMPTS) { - rotatePin(); - } + if (candidate != null && candidate.length() > MAX_PIN_LENGTH) { + throw new IllegalArgumentException("PIN is too long"); + } + limiter.checkNotLocked(); + if (!pinMatches(candidate)) { + rejectPin("setup"); return Optional.empty(); } + limiter.reset(); byte[] token = new byte[32]; RANDOM.nextBytes(token); String session = HexFormat.of().formatHex(token); - sessions.add(session); + Instant now = clock.instant(); + sessions.values().removeIf(lastSeen -> expired(lastSeen, now)); + sessions.put(session, now); LOGGER.info("Setup PIN accepted, a new PIN is required for any other device"); rotatePin(); return Optional.of(session); } - public synchronized void complete() { - db.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); + public synchronized String complete() { + if (completed) { + throw new SetupAlreadyCompleteException(); + } + settings.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); completed = true; sessions.clear(); - pin = null; + limiter.reset(); LOGGER.info("Setup completed, the web setup page is now disabled"); + if (pairedClients.countPairedClients() == 0) { + openPairing(); + } else { + pin = null; + } + return pin; + } + + synchronized long checkPairingPin(String candidate) { + if (!completed) { + throw new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair."); + } + limiter.checkNotLocked(); + if (!pairingOpen) { + throw new PairingException(PairingException.Reason.CLOSED, + "Pairing is closed. Ask a paired Client for a pairing code, or restart the server with MEDIAGARRD_OPEN_PAIRING=true"); + } + if (!pinMatches(candidate)) { + rejectPin("pairing"); + throw new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code"); + } + LOGGER.info("Pairing PIN accepted, pairing closes once the Client has used its token"); + return pairingEpoch; + } + + synchronized boolean isPairingOpen(long epoch) { + return pairingOpen && pairingEpoch == epoch; + } + + synchronized boolean closePairing(long epoch) { + if (!isPairingOpen(epoch)) { + return false; + } + limiter.reset(); + pairingOpen = false; + pin = null; + LOGGER.info("Pairing is now closed"); + return true; + } + + synchronized boolean closeCurrentPairing() { + return closePairing(pairingEpoch); + } + + synchronized void reopenPairing() { + if (completed && !pairingOpen) { + openPairing(); + } } synchronized String currentPin() { return pin; } + private void openPairing() { + pairingOpen = true; + pairingEpoch++; + rotatePin(); + } + + private static boolean expired(Instant lastSeen, Instant now) { + return !lastSeen.plus(SESSION_IDLE_TIMEOUT).isAfter(now); + } + + private void rejectPin(String purpose) { + int failures = limiter.recordFailure(); + LOGGER.warn("Rejected {} PIN attempt ({}/{})", purpose, failures, MAX_FAILED_ATTEMPTS); + if (limiter.isLockedNow()) { + LOGGER.warn("PIN entry is locked for {} minutes after too many wrong attempts", LOCK_DURATION.toMinutes()); + rotatePin(); + } + } + + private boolean pinMatches(String candidate) { + return pin != null && candidate != null && MessageDigest.isEqual(bytes(pin), bytes(candidate.strip())); + } + private void rotatePin() { pin = "%06d".formatted(RANDOM.nextInt(1_000_000)); - failedAttempts = 0; - LOGGER.warn("Setup PIN: {} (single use, enter it at http://:/config)", pin); + if (completed) { + LOGGER.warn("Pairing PIN: {} (enter it in the MediaGarrd Client, it stops working once a Client has paired)", pin); + } else { + LOGGER.warn("Setup PIN: {} (single use, enter it at http://:/config)", pin); + } } private static byte[] bytes(String value) { diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java new file mode 100644 index 0000000..fc51854 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java @@ -0,0 +1,316 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.FAILURE_WEBHOOK_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.IOException; +import java.net.URI; +import java.text.ParseException; +import java.net.http.HttpClient; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import jakarta.annotation.PreDestroy; +import tools.jackson.databind.json.JsonMapper; +import wellatleastitried.mediagarrdServer.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdServer.dto.WebhookTestDto; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; +import wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils; + +@Service +public class WebhookService { + + public static final String EVENT_FAILED = "backup.failed"; + public static final String EVENT_PARTIAL = "backup.partial"; + public static final String EVENT_TEST = "test"; + + static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5); + static final Duration DELIVERY_TIMEOUT = Duration.ofSeconds(10); + static final Duration TEST_TIMEOUT = Duration.ofSeconds(5); + static final Duration TEST_COOLDOWN = Duration.ofSeconds(10); + static final int QUEUE_CAPACITY = 16; + static final int MAX_MESSAGE_LENGTH = 1900; + static final int MAX_ERROR_LENGTH = 1000; + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookService.class); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ZERO_WIDTH_SPACE = "​"; + + record Event(String name, Instant time, String error, List failedServices, String archiveId) {} + + private record Outcome(boolean delivered, Integer status, String error) {} + + private final SettingsRepository settings; + private final HttpClient client; + private final Clock clock; + private final Duration deliveryTimeout; + private final Duration testTimeout; + private final ThreadPoolExecutor executor; + private final AtomicReference lastTest = new AtomicReference<>(); + + @Autowired + public WebhookService(SettingsRepository settings) { + this(settings, HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .build(), Clock.systemUTC(), DELIVERY_TIMEOUT, TEST_TIMEOUT); + } + + WebhookService(SettingsRepository settings, HttpClient client, Clock clock, Duration deliveryTimeout, Duration testTimeout) { + this.settings = settings; + this.client = client; + this.clock = clock; + this.deliveryTimeout = deliveryTimeout; + this.testTimeout = testTimeout; + this.executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY), runnable -> { + Thread thread = new Thread(runnable, "webhook-delivery"); + thread.setDaemon(true); + return thread; + }); + } + + public WebhookStatusDto status() { + Optional url = configuredUrl(); + return new WebhookStatusDto(url.isPresent(), url.map(WebhookUrl::target).orElse(null)); + } + + public WebhookStatusDto update(String raw) { + if (raw == null || raw.isBlank()) { + settings.saveSetting(FAILURE_WEBHOOK_SETTING, ""); + LOGGER.info("Failure webhook cleared"); + return status(); + } + String url = WebhookUrl.validate(raw); + settings.saveSetting(FAILURE_WEBHOOK_SETTING, url); + LOGGER.info("Failure webhook set, target={}", WebhookUrl.target(url)); + return status(); + } + + public WebhookTestDto test() { + String url = configuredUrl().orElseThrow(() -> new IllegalArgumentException("No webhook is configured")); + claimTestSlot(); + Instant now = clock.instant(); + Outcome outcome = deliver(url, new Event(EVENT_TEST, now, null, List.of(), null), testTimeout); + LOGGER.info("Webhook test to {}: {}", WebhookUrl.host(url), outcome.delivered() ? "delivered" : outcome.error()); + return new WebhookTestDto(outcome.delivered(), outcome.status(), outcome.error()); + } + + public void notifyRun(BackupRunResult result) { + try { + String event = FAILED.equals(result.status()) ? EVENT_FAILED : PARTIAL.equals(result.status()) ? EVENT_PARTIAL : null; + if (event == null) { + return; + } + List failed = result.serviceResults().stream() + .filter(r -> !COMPLETED.equals(r.status())) + .map(BackupServiceResult::serviceName) + .toList(); + String archiveId = result.archive() == null ? null : result.archive().id(); + enqueue(new Event(event, eventTime(result), result.errorMessage(), failed, archiveId)); + } catch (RuntimeException e) { + LOGGER.warn("Could not queue the failure webhook: {}", e.getClass().getSimpleName()); + } + } + + private Instant eventTime(BackupRunResult result) { + try { + return result.endTime() == null ? clock.instant() : MediaGarrdUtils.parseTime(result.endTime()); + } catch (ParseException | RuntimeException e) { + return clock.instant(); + } + } + + public void notifyFailure(String reason) { + try { + enqueue(new Event(EVENT_FAILED, clock.instant(), reason, List.of(), null)); + } catch (RuntimeException e) { + LOGGER.warn("Could not queue the failure webhook: {}", e.getClass().getSimpleName()); + } + } + + @PreDestroy + public void shutdown() { + executor.shutdownNow(); + try { + executor.awaitTermination(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private Optional configuredUrl() { + return settings.fetchSetting(FAILURE_WEBHOOK_SETTING).filter(url -> !url.isBlank()); + } + + private void claimTestSlot() { + Instant now = clock.instant(); + while (true) { + Instant last = lastTest.get(); + if (last != null && now.isBefore(last.plus(TEST_COOLDOWN))) { + Duration remaining = Duration.between(now, last.plus(TEST_COOLDOWN)); + long seconds = Math.max(1, (remaining.toMillis() + 999) / 1000); + throw new RateLimitedException("Wait " + seconds + " seconds before sending another test", Duration.ofSeconds(seconds)); + } + if (lastTest.compareAndSet(last, now)) { + return; + } + } + } + + private void enqueue(Event event) { + if (configuredUrl().isEmpty()) { + return; + } + try { + executor.execute(() -> sendQueued(event)); + } catch (RejectedExecutionException e) { + LOGGER.warn("Failure webhook dropped, the delivery queue is full or stopped"); + } + } + + private void sendQueued(Event event) { + try { + Optional url = configuredUrl(); + if (url.isEmpty()) { + return; + } + Outcome outcome = deliver(url.get(), event, deliveryTimeout); + if (outcome.delivered()) { + LOGGER.info("Failure webhook delivered to {} ({})", WebhookUrl.host(url.get()), event.name()); + } else { + LOGGER.warn("Failure webhook to {} failed: {}", WebhookUrl.host(url.get()), outcome.error()); + } + } catch (RuntimeException e) { + LOGGER.warn("Failure webhook failed: {}", e.getClass().getSimpleName()); + } + } + + private Outcome deliver(String url, Event event, Duration timeout) { + try { + URI uri = WebhookUrl.parse(url); + HttpRequest request = HttpRequest.newBuilder(uri) + .timeout(timeout) + .header("Content-Type", "application/json") + .header("User-Agent", "MediaGarrd-Server") + .POST(HttpRequest.BodyPublishers.ofString(payload(uri.getHost(), uri.getPath(), event))) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.discarding()); + int status = response.statusCode(); + if (status >= 200 && status < 300) { + return new Outcome(true, status, null); + } + return new Outcome(false, status, "Webhook answered " + status); + } catch (HttpConnectTimeoutException e) { + return new Outcome(false, null, "Could not connect"); + } catch (HttpTimeoutException e) { + return new Outcome(false, null, "Timed out"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new Outcome(false, null, "Interrupted"); + } catch (IOException e) { + return new Outcome(false, null, "Could not connect"); + } catch (RuntimeException e) { + return new Outcome(false, null, "Delivery failed"); + } + } + + static String payload(String host, String path, Event event) { + String lowerHost = host == null ? "" : host.toLowerCase(Locale.ROOT); + Map body = new LinkedHashMap<>(); + boolean discord = isHostOrSubdomain(lowerHost, "discord.com") || isHostOrSubdomain(lowerHost, "discordapp.com"); + boolean slackShape = lowerHost.equals("hooks.slack.com") || (discord && path != null && path.toLowerCase(Locale.ROOT).endsWith("/slack")); + if (discord && !slackShape) { + body.put("content", cap(message(event, true))); + body.put("allowed_mentions", Map.of("parse", List.of())); + } else if (slackShape) { + body.put("text", cap(escapeSlack(message(event, false)))); + } else { + String message = cap(message(event, false)); + body.put("event", event.name()); + body.put("time", event.time().toString()); + body.put("error", event.error() == null ? null : sanitize(event.error(), MAX_ERROR_LENGTH)); + body.put("failedServices", event.failedServices().stream().map(name -> sanitize(name, 128)).toList()); + if (event.archiveId() != null) { + body.put("archiveId", event.archiveId()); + } + body.put("content", message); + body.put("text", message); + } + return JSON.writeValueAsString(body); + } + + private static boolean isHostOrSubdomain(String host, String domain) { + return host.equals(domain) || host.endsWith("." + domain); + } + + private static String message(Event event, boolean discord) { + return switch (event.name()) { + case EVENT_TEST -> "MediaGarrd test notification at " + event.time(); + case EVENT_PARTIAL -> { + List names = event.failedServices().stream().map(name -> sanitize(name, 128)).toList(); + String detail = names.isEmpty() ? "see the server log" : String.join(", ", names); + yield "MediaGarrd backup partially failed (" + event.failedServices().size() + " service(s)): " + quote(detail, discord); + } + default -> { + String reason = event.error() == null || event.error().isBlank() ? "see the server log" : sanitize(event.error(), MAX_ERROR_LENGTH); + yield "MediaGarrd backup failed at " + event.time() + ": " + quote(reason, discord); + } + }; + } + + private static String quote(String text, boolean discord) { + return discord ? "`" + text.replace("`", "'") + "`" : text; + } + + static String sanitize(String text, int max) { + List lines = new ArrayList<>(); + for (String line : text.split("\\R")) { + if (!line.isBlank()) { + lines.add(LogSanitizer.clean(line.strip())); + } + } + String joined = String.join("; ", lines); + if (joined.length() > max) { + joined = joined.substring(0, max - 3) + "..."; + } + return neutralizeMentions(joined); + } + + private static String neutralizeMentions(String text) { + return text.replace("@", "@" + ZERO_WIDTH_SPACE).replace("<", "<" + ZERO_WIDTH_SPACE); + } + + private static String escapeSlack(String text) { + return text.replace("&", "&").replace("<", "<").replace(">", ">"); + } + + private static String cap(String text) { + return text.length() <= MAX_MESSAGE_LENGTH ? text : text.substring(0, MAX_MESSAGE_LENGTH - 3) + "..."; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java new file mode 100644 index 0000000..b2fbdb3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java @@ -0,0 +1,68 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +final class WebhookUrl { + + static final int MAX_LENGTH = 2048; + + private WebhookUrl() {} + + static String validate(String raw) { + String url = raw.strip(); + if (url.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Webhook URL is too long"); + } + if (url.codePoints().anyMatch(c -> Character.isWhitespace(c) || Character.isISOControl(c) || Character.isSpaceChar(c))) { + throw new IllegalArgumentException("Webhook URL must not contain spaces or control characters"); + } + URI uri = parse(url); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + if (!scheme.equals("http") && !scheme.equals("https")) { + throw new IllegalArgumentException("Webhook URL must use http or https"); + } + if (uri.getRawUserInfo() != null) { + throw new IllegalArgumentException("Webhook URL must not contain user info"); + } + if (uri.getHost() == null || uri.getHost().isEmpty()) { + throw new IllegalArgumentException("Webhook URL must have a valid host name"); + } + if (url.indexOf('#') >= 0) { + throw new IllegalArgumentException("Webhook URL must not contain a fragment"); + } + return url; + } + + static URI parse(String url) { + try { + return new URI(url); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Webhook URL is not a valid URL"); + } + } + + static String host(String url) { + try { + String host = new URI(url).getHost(); + return host == null ? "unknown host" : host; + } catch (URISyntaxException e) { + return "unknown host"; + } + } + + static String target(String url) { + URI uri; + try { + uri = new URI(url); + } catch (URISyntaxException e) { + return null; + } + if (uri.getScheme() == null || uri.getHost() == null || uri.getHost().isEmpty()) { + return null; + } + String port = uri.getPort() < 0 ? "" : ":" + uri.getPort(); + return uri.getScheme().toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + port; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java index 76ee8f0..fac0d9e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java @@ -6,7 +6,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -14,7 +13,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Set; @@ -22,6 +20,7 @@ import org.slf4j.LoggerFactory; import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; +import wellatleastitried.mediagarrdServer.utilities.Sha256; final class ZipPartMerger { @@ -37,7 +36,7 @@ private ZipPartMerger() {} static Result merge(List snapshotParts, List parts, Path output, Path scratchDirectory) throws IOException { Path names = scratchDirectory.resolve("merge-names" + ZipPartWriter.INDEX_SUFFIX); - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newDigest(); try (OutputStream file = Files.newOutputStream(output); Sink sink = new Sink(file, digest); NameIndex seen = new NameIndex(names)) { List ordered = new ArrayList<>(snapshotParts); ordered.addAll(parts); @@ -58,7 +57,7 @@ static Result merge(List snapshotParts, List parts, Path output, Pat sink.write(ZipFormat.endOfArchive(entries, centralSize, centralStart)); sink.flush(); LOGGER.debug("Merged {} part(s) into {} entries", ordered.size(), entries); - return new Result(HexFormat.of().formatHex(digest.digest()), entries, sink.written()); + return new Result(Sha256.hex(digest.digest()), entries, sink.written()); } finally { Files.deleteIfExists(names); } @@ -104,14 +103,6 @@ private static long writeCentral(Path part, long base, boolean snapshot, Set OWNER_ONLY_DIRECTORY = PosixFilePermissions.fromString("rwx------"); + private static final Set OWNER_ONLY_FILE = PosixFilePermissions.fromString("rw-------"); + private static final boolean POSIX = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + + private FilePermissions() {} + + public static Path createPrivateDirectories(Path directory) throws IOException { + if (!POSIX) { + return Files.createDirectories(directory); + } + return Files.createDirectories(directory, directoryAttribute()); + } + + public static Path createPrivateFile(Path file) throws IOException { + if (!POSIX) { + return Files.createFile(file); + } + return Files.createFile(file, fileAttribute()); + } + + public static void restrictFile(Path file) { + if (!POSIX) { + return; + } + try { + Files.setPosixFilePermissions(file, OWNER_ONLY_FILE); + } catch (IOException | RuntimeException e) { + LOGGER.warn("Unable to restrict permissions of {}", LogSanitizer.clean(file), e); + } + } + + private static FileAttribute> directoryAttribute() { + return PosixFilePermissions.asFileAttribute(OWNER_ONLY_DIRECTORY); + } + + private static FileAttribute> fileAttribute() { + return PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java new file mode 100644 index 0000000..fa47a33 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.utilities; + +public final class LogSanitizer { + + private static final int MAX_LENGTH = 256; + + private LogSanitizer() {} + + public static String clean(Object value) { + if (value == null) { + return "null"; + } + String text = value.toString(); + StringBuilder cleaned = new StringBuilder(Math.min(text.length(), MAX_LENGTH + 3)); + for (int i = 0; i < text.length() && cleaned.length() < MAX_LENGTH; i++) { + char c = text.charAt(i); + cleaned.append(Character.isISOControl(c) || c == '
' || c == '
' ? '_' : c); + } + if (cleaned.length() < text.length()) { + cleaned.append("..."); + } + return cleaned.toString(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java index 19043a9..9d7b135 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java @@ -20,13 +20,17 @@ public static String formatTime(Instant instant) { return formattedTime; } + public static Instant parseTime(String time) throws ParseException { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).toInstant(); + } + public static long getDurationMs(String startTimeStr, String endTimeStr) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startDate = sdf.parse(startTimeStr); Date endDate = sdf.parse(endTimeStr); return endDate.getTime() - startDate.getTime(); - } catch (ParseException pE) {} + } catch (ParseException e) {} return -1; } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java new file mode 100644 index 0000000..e98b791 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java @@ -0,0 +1,27 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +public final class Sha256 { + + private Sha256() {} + + public static MessageDigest newDigest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + public static String hex(String value) { + return hex(newDigest().digest(value.getBytes(StandardCharsets.UTF_8))); + } + + public static String hex(byte[] digest) { + return HexFormat.of().formatHex(digest); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java index 2a23d30..bbabaf1 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java @@ -42,6 +42,14 @@ CREATE TABLE IF NOT EXISTS settings ( value TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS paired_clients ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + created_at TEXT NOT NULL, + last_used_at TEXT + ); + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); """; @@ -77,6 +85,13 @@ INSERT INTO backup_services ( LIMIT 1; """; + public static final String FETCH_LAST_SUCCESSFUL_START = """ + SELECT start_time FROM backups + WHERE status IN ('completed', 'partial') + ORDER BY start_time DESC + LIMIT 1; + """; + public static final String FETCH_RECORD_BY_ID = """ SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups WHERE archive_id = ?; @@ -126,6 +141,34 @@ INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value; """; + public static final String ADD_PAIRED_CLIENT = """ + INSERT INTO paired_clients (id, name, token_hash, created_at) VALUES (?, ?, ?, ?); + """; + + public static final String FETCH_PAIRED_CLIENTS = """ + SELECT id, name, created_at, last_used_at FROM paired_clients + ORDER BY created_at, id; + """; + + public static final String FETCH_PAIRED_CLIENT_BY_HASH = """ + SELECT id, name, created_at, last_used_at FROM paired_clients + WHERE token_hash = ?; + """; + + public static final String DELETE_PAIRED_CLIENT = """ + DELETE FROM paired_clients + WHERE id = ?; + """; + + public static final String TOUCH_PAIRED_CLIENT = """ + UPDATE paired_clients SET last_used_at = ? + WHERE id = ?; + """; + + public static final String COUNT_PAIRED_CLIENTS = """ + SELECT COUNT(*) FROM paired_clients; + """; + public record Migration(int version, String sql) {} public static final List MIGRATIONS; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java index 25e529c..c6a2f0f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java @@ -7,6 +7,7 @@ public class DatabaseUtils { public static final String SETUP_COMPLETED_SETTING = "setup_completed"; public static final String BACKUP_INTERVAL_SETTING = "backup_interval"; public static final String RETENTION_COUNT_SETTING = "retention_count"; + public static final String FAILURE_WEBHOOK_SETTING = "failure_webhook_url"; // Status used for the overall backup AND the individual service runners public class Status { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 00b03a2..0dee2d0 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -17,3 +17,4 @@ mediagarrd: update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} + open-pairing: ${MEDIAGARRD_OPEN_PAIRING:false} diff --git a/src/main/resources/static/config.html b/src/main/resources/static/config.html index aced9f0..1f021d6 100644 --- a/src/main/resources/static/config.html +++ b/src/main/resources/static/config.html @@ -15,21 +15,42 @@ - -
Setup PIN
+ + + +
Setup PIN
- -

+ +
- +
+ +
Backup Settings
@@ -41,7 +62,7 @@
- +
@@ -51,58 +72,81 @@ +
+
Failure Notifications
+
+
+ + +

Sends a message when a backup fails or only partly succeeds. Works with Discord, Slack and any receiver that accepts JSON. The saved address is never shown again.

+

Not configured

+
+
+ + + +
+
+
+
+ +
+
+
Add Service
+
+
+ + +
+
+
+ Host paths to back up +
+ +
+
+
+ + +
+
+ + + + + +
Configured Services
+
+ + + + +
Configured services
NamePathsActions
+
+

No services configured yet.

+
Finish Setup

Once finished, this page is disabled. Later changes go through the API or the MediaGarrd Client.

-
+
- -
-
Add Service
-
-
- - -
-
- Host paths to back up -
- -
-
- - -
-
- - - - - -
Configured Services
- - - -
NamePaths
-

No services configured yet.

-
diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css index 8e2fdc0..fa64743 100644 --- a/src/main/resources/static/css/mediagarrd.css +++ b/src/main/resources/static/css/mediagarrd.css @@ -48,12 +48,14 @@ body { margin: 0 auto; padding: 1.5rem; display: grid; - grid-template-columns: 360px 1fr; + grid-template-columns: 360px minmax(0, 1fr); gap: 1rem; align-items: start; } -@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } +.workspace > * { min-width: 0; } + +@media (max-width: 900px) { .workspace { grid-template-columns: minmax(0, 1fr); } } .panel { background: var(--surface); border: 1px solid var(--border); } .panel.wide { grid-column: 1 / -1; } @@ -61,7 +63,7 @@ body { dialog.panel { color: var(--ink); margin: auto; width: min(360px, calc(100% - 2rem)); } dialog::backdrop { background: rgba(0, 0, 0, 0.8); } -.error-text { color: #fca5a5; } +.error-text, .note.error-text { color: #fca5a5; } .panel-header { display: flex; align-items: center; @@ -74,23 +76,26 @@ dialog::backdrop { background: rgba(0, 0, 0, 0.8); } .field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } .field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } -.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } -.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } -.button-row { display: flex; gap: 0.5rem; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; overflow-wrap: anywhere; } +.input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.5rem; } +.button-row { display: flex; flex-wrap: wrap; gap: 0.5rem; } .note + .button-row { margin-top: 0.75rem; } +.pin-row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; margin-top: 0.75rem; } +.pin-value { font-size: 1.6rem; font-weight: 700; letter-spacing: 0.2em; color: var(--ink); } input { width: 100%; + min-width: 0; background: var(--bg); color: var(--ink); border: 1px solid var(--border-mid); padding: 0.5rem 0.65rem; font: inherit; font-size: 0.85rem; - outline: none; transition: border-color 150ms; } -input:focus { border-color: var(--subtle); } +input:focus { border-color: var(--muted); } +input:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } input::placeholder { color: var(--muted); } button { @@ -146,3 +151,23 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: top; } } .banner.visible { display: block; } .banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } + +.table-wrap { overflow-x: auto; } +.field-set { border: 0; min-width: 0; } +.fatal { max-width: 480px; margin: 2rem auto; } +.sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + margin: -1px; + padding: 0; + border: 0; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { transition: none !important; animation: none !important; } + button:active { transform: none; } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index d75d8b1..de496d1 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -8,6 +8,6 @@

MediaGarrd Server

API is available under /api/v1.

-

Configure services and backup location

+

The setup page lets you configure services and the backup location, but it is only available until setup is finished: /config

diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js index 7b8cd87..36c8fa5 100644 --- a/src/main/resources/static/js/api.js +++ b/src/main/resources/static/js/api.js @@ -6,7 +6,10 @@ async function request(method, url, body) { }); if (!response.ok) { const data = await response.json().catch(() => ({})); - throw new Error(data.error || `${method} ${url} failed (${response.status})`); + const failure = new Error(data.error || `${method} ${url} failed (${response.status})`); + failure.status = response.status; + failure.retryAfter = Number(response.headers.get('Retry-After')) || 0; + throw failure; } return response.status === 204 ? null : response.json(); } @@ -17,6 +20,9 @@ export const api = { getConfig: () => request('GET', '/api/v1/config'), updateConfig: (settings) => request('PUT', '/api/v1/config', settings), updateSchedule: (backupInterval) => request('PUT', '/api/v1/schedule', { backupInterval }), + getWebhook: () => request('GET', '/api/v1/notifications/webhook'), + updateWebhook: (url) => request('PUT', '/api/v1/notifications/webhook', { url }), + testWebhook: () => request('POST', '/api/v1/notifications/webhook/test'), listServices: () => request('GET', '/api/v1/services'), addService: (service) => request('POST', '/api/v1/services', service), updateService: (name, service) => request('PUT', servicePath(name), service), diff --git a/src/main/resources/static/js/config.js b/src/main/resources/static/js/config.js index 5824f97..3619ada 100644 --- a/src/main/resources/static/js/config.js +++ b/src/main/resources/static/js/config.js @@ -1,5 +1,6 @@ import { initServices } from './services.js'; import { initSettings } from './settings.js'; +import { initWebhook } from './webhook.js'; import { initFinish, unlock } from './setup.js'; const workspace = document.querySelector('.workspace'); @@ -18,13 +19,18 @@ const notify = { function start() { workspace.hidden = false; initSettings(document.getElementById('settingsForm'), notify); + initWebhook(document.getElementById('webhookForm'), notify); initServices(document.getElementById('services'), notify); - initFinish(document.getElementById('finish'), notify, () => { + initFinish(document.getElementById('finish'), document.getElementById('pairingResult'), notify, () => { workspace.querySelectorAll('[data-setup]').forEach((element) => element.remove()); }); } +const fatal = document.getElementById('fatal'); +fatal.querySelector('[data-reload]').addEventListener('click', () => location.reload()); + unlock(document.getElementById('pinDialog')).then(start).catch((error) => { - workspace.hidden = false; - notify.error(error); + workspace.hidden = true; + fatal.querySelector('[data-message]').textContent = `Setup could not be unlocked: ${error.message || error}`; + fatal.hidden = false; }); diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js index c397d73..070f84d 100644 --- a/src/main/resources/static/js/settings.js +++ b/src/main/resources/static/js/settings.js @@ -7,6 +7,9 @@ function toHours(duration) { return Number(hours) + Number(minutes) / 60 + Number(seconds) / 3600; } +const MIN_HOURS = 0.25; +const MAX_HOURS = 8760; + const toDuration = (hours) => `PT${Math.round(hours * 60)}M`; export function initSettings(form, notify) { @@ -22,13 +25,23 @@ export function initSettings(form, notify) { form.addEventListener('submit', async (event) => { event.preventDefault(); + let saved = false; + const hours = Number(intervalHours.value); + if (!(hours >= MIN_HOURS && hours <= MAX_HOURS)) { + notify.error(new Error('Backup interval must be between 15 minutes and 365 days')); + return; + } try { const config = await api.updateConfig({ backupLocation: backupLocation.value, retentionCount: Number(retentionCount.value) }); - const { backupInterval } = await api.updateSchedule(toDuration(Number(intervalHours.value))); + saved = true; + const { backupInterval } = await api.updateSchedule(toDuration(hours)); show({ ...config, backupInterval }); notify.ok('Backup settings saved'); } catch (error) { - notify.error(error); + notify.error(saved ? new Error(`Location and backups to keep were saved, but the interval was not: ${error.message}`) : error); + if (saved) { + await api.getConfig().then(show).catch(() => {}); + } } }); } diff --git a/src/main/resources/static/js/setup.js b/src/main/resources/static/js/setup.js index 94dedad..521ec31 100644 --- a/src/main/resources/static/js/setup.js +++ b/src/main/resources/static/js/setup.js @@ -1,14 +1,36 @@ import { api } from './api.js'; +function formatWait(seconds) { + const minutes = Math.floor(seconds / 60); + return `${minutes}:${String(seconds % 60).padStart(2, '0')}`; +} + export async function unlock(dialog) { const status = await api.setupStatus(); if (status.authorized) return; const form = dialog.querySelector('form'); const error = dialog.querySelector('[data-error]'); + const unlockButton = dialog.querySelector('[data-unlock]'); dialog.addEventListener('cancel', (event) => event.preventDefault()); dialog.showModal(); + function lockFor(seconds) { + let left = seconds; + unlockButton.disabled = true; + const tick = setInterval(() => { + left -= 1; + if (left <= 0) { + clearInterval(tick); + unlockButton.disabled = false; + unlockButton.textContent = 'Unlock'; + return; + } + unlockButton.textContent = `Locked ${formatWait(left)}`; + }, 1000); + unlockButton.textContent = `Locked ${formatWait(left)}`; + } + await new Promise((resolve) => { form.addEventListener('submit', async (event) => { event.preventDefault(); @@ -19,19 +41,48 @@ export async function unlock(dialog) { } catch (e) { error.textContent = e.message; form.reset(); + form.elements.pin.focus(); + if (e.retryAfter) lockFor(e.retryAfter); } }); }); } -export function initFinish(root, notify, onComplete) { - root.querySelector('button').addEventListener('click', async () => { +function showPairing(panel, pairingPin, notify) { + const withPin = panel.querySelector('[data-with-pin]'); + const withoutPin = panel.querySelector('[data-without-pin]'); + withPin.hidden = !pairingPin; + withoutPin.hidden = Boolean(pairingPin); + if (pairingPin) { + const code = panel.querySelector('[data-pin]'); + const button = panel.querySelector('[data-copy-pin]'); + code.textContent = pairingPin; + button.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(pairingPin); + button.textContent = 'Copied'; + } catch { + window.getSelection().selectAllChildren(code); + notify.ok('Copying is not available on this connection. The PIN is selected, press Ctrl+C or Cmd+C to copy it.'); + } + }); + } + panel.hidden = false; +} + +export function initFinish(root, pairingPanel, notify, onComplete) { + const button = root.querySelector('[data-finish]'); + button.addEventListener('click', async () => { + if (button.disabled) return; if (!confirm('Finish setup? This page will be disabled and further changes must go through the API or the MediaGarrd Client.')) return; + button.disabled = true; try { - await api.completeSetup(); + const result = await api.completeSetup(); onComplete(); - notify.ok('Setup complete. This page is now disabled, further changes go through the API or the MediaGarrd Client.'); + notify.ok('Setup complete. This page is now disabled, further changes go through the Client.'); + showPairing(pairingPanel, result && result.pairingPin, notify); } catch (error) { + button.disabled = false; notify.error(error); } }); diff --git a/src/main/resources/static/js/webhook.js b/src/main/resources/static/js/webhook.js new file mode 100644 index 0000000..4c9d041 --- /dev/null +++ b/src/main/resources/static/js/webhook.js @@ -0,0 +1,63 @@ +import { api } from './api.js'; + +function describe(status) { + return status.configured ? `Configured: ${status.target}` : 'Not configured'; +} + +export function initWebhook(form, notify) { + const { url } = form.elements; + const label = form.querySelector('[data-webhook-status]'); + const buttons = form.querySelectorAll('button'); + + function show(status) { + label.textContent = describe(status); + url.value = ''; + } + + async function busy(task) { + buttons.forEach((button) => { button.disabled = true; }); + try { + await task(); + } catch (error) { + notify.error(error); + } finally { + buttons.forEach((button) => { button.disabled = false; }); + } + } + + async function save() { + const value = url.value.trim(); + if (value) { + show(await api.updateWebhook(value)); + } + return value; + } + + api.getWebhook().then((status) => { label.textContent = describe(status); }).catch(notify.error); + + form.addEventListener('submit', (event) => { + event.preventDefault(); + busy(async () => { + if (await save()) { + notify.ok('Webhook saved'); + } else { + notify.error(new Error('Enter a webhook URL, or use Clear to turn notifications off')); + } + }); + }); + + form.querySelector('[data-webhook-clear]').addEventListener('click', () => busy(async () => { + show(await api.updateWebhook('')); + notify.ok('Webhook cleared'); + })); + + form.querySelector('[data-webhook-test]').addEventListener('click', () => busy(async () => { + await save(); + const result = await api.testWebhook(); + if (result.delivered) { + notify.ok('Test message delivered'); + } else { + notify.error(new Error(`Test message was not delivered: ${result.error}`)); + } + })); +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java new file mode 100644 index 0000000..a1fd3a3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java @@ -0,0 +1,226 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiAuthSetupPhaseFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final List SETUP_ENDPOINTS = List.of( + "/api/v1/services", "/api/v1/config", "/api/v1/services;x", "/api/v1;x/services", "/api/v1/config;x"); + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @Autowired + MockMvc mockMvc; + + @Autowired + ServiceRepository services; + + @Autowired + SetupService setup; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping handlerMapping; + + @Test + @Order(0) + void everyResponseForbidsFraming() throws Exception { + for (String path : List.of("/config", "/config.html", "/api/v1/health", "/api/v1/services", "/no-such-page.html")) { + mockMvc.perform(get(path)) + .andExpect(header().string("X-Frame-Options", "DENY")) + .andExpect(header().string("Content-Security-Policy", SecurityHeadersFilter.CONTENT_SECURITY_POLICY)) + .andExpect(header().string("X-Content-Type-Options", "nosniff")) + .andExpect(header().string("Referrer-Policy", "no-referrer")); + } + } + + @Test + @Order(1) + void setupEndpointsNeedASetupSessionAndEverythingElseNeedsAToken() throws Exception { + for (String path : SETUP_ENDPOINTS) { + mockMvc.perform(get(path)).andExpect(status().isUnauthorized()); + } + mockMvc.perform(get("/api/v1/backups")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/events")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/clients")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/config")).andExpect(status().isOk()); + + Cookie session = startSession(); + + for (String path : List.of("/api/v1/services", "/api/v1/config", "/api/v1/services;x")) { + mockMvc.perform(get(path).cookie(session)).andExpect(status().isOk()); + } + mockMvc.perform(get("/api/v1/backups").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/events").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/clients").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/pairing-codes").cookie(session)).andExpect(status().isUnauthorized()); + } + + @Test + @Order(2) + void everyCallTheSetupPageMakesWorksWithTheSetupSession() throws Exception { + Cookie session = startSession(); + String json = MediaType.APPLICATION_JSON_VALUE; + + mockMvc.perform(get("/api/v1/setup").cookie(session)).andExpect(status().isOk()) + .andExpect(jsonPath("$.authorized").value(true)); + mockMvc.perform(get("/api/v1/config").cookie(session)).andExpect(status().isOk()); + mockMvc.perform(put("/api/v1/config").cookie(session).contentType(json).content("{\"retentionCount\": 5}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.retentionCount").value(5)); + mockMvc.perform(put("/api/v1/schedule").cookie(session).contentType(json).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/v1/services").cookie(session)).andExpect(status().isOk()); + mockMvc.perform(post("/api/v1/services").cookie(session).contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\"]}")) + .andExpect(status().isCreated()); + mockMvc.perform(put("/api/v1/services/lidarr").cookie(session).contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\", \"/srv/lidarr2\"]}")) + .andExpect(status().isOk()); + mockMvc.perform(delete("/api/v1/services/lidarr").cookie(session)).andExpect(status().isNoContent()); + + mockMvc.perform(put("/api/v1/schedule").contentType(json).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(put("/api/v1/config").contentType(json).content("{\"retentionCount\": 5}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/services").contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\"]}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(delete("/api/v1/services/radarr")).andExpect(status().isUnauthorized()); + } + + @Test + @Order(6) + void theSetupSessionRoutesAreExactlyTheOnesTheSetupPageCalls() throws Exception { + Set pageCalls = new TreeSet<>(); + Matcher matcher = Pattern.compile("request\\('(\\w+)', (?:'([^']+)'|servicePath\\(name\\))") + .matcher(Files.readString(Path.of("src/main/resources/static/js/api.js"))); + while (matcher.find()) { + pageCalls.add(matcher.group(1) + " " + (matcher.group(2) != null ? matcher.group(2) : "/api/v1/services/{name}")); + } + assertTrue(pageCalls.size() >= 10, "Parsed only " + pageCalls); + + Set setupRoutes = new TreeSet<>(); + Set publicRoutes = new TreeSet<>(); + for (var entry : handlerMapping.getHandlerMethods().entrySet()) { + for (String pattern : entry.getKey().getPathPatternsCondition().getPatternValues()) { + for (var method : entry.getKey().getMethodsCondition().getMethods()) { + String key = method.name() + " " + pattern; + if (entry.getValue().hasMethodAnnotation(SetupSessionAllowed.class)) { + setupRoutes.add(key); + } + if (entry.getValue().hasMethodAnnotation(PublicEndpoint.class)) { + publicRoutes.add(key); + } + } + } + } + + Set tokenOrSession = new TreeSet<>(pageCalls); + tokenOrSession.removeAll(publicRoutes); + assertEquals(tokenOrSession, setupRoutes); + } + + @Test + @Order(3) + void pairingIsRefusedBeforeSetupCompletes() throws Exception { + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + FullContextSupport.currentPin(setup) + "\"}")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + } + + @Test + @Order(4) + void completingSetupOpensPairingAndRetiresTheSetupPageAndSession() throws Exception { + services.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); + Cookie session = startSession(); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/setup/complete").cookie(session)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.pairingPin").value(FullContextSupport.currentPin(setup))) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")) + .andExpect(cookie().maxAge(SetupInterceptor.SESSION_COOKIE, 0)); + + assertTrue(setup.isCompleted()); + assertTrue(setup.isPairingOpen()); + mockMvc.perform(get("/api/v1/services").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services;x").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"123456\"}")) + .andExpect(status().isGone()); + } + + @Test + @Order(5) + void wrongPinsLockPairingOverHttp() throws Exception { + String current = FullContextSupport.currentPin(setup); + String wrong = current.substring(0, 5) + (current.charAt(5) == '0' ? '1' : '0'); + for (int i = 0; i < 5; i++) { + mockMvc.perform(pair(wrong)).andExpect(status().isUnauthorized()); + } + + mockMvc.perform(pair(FullContextSupport.currentPin(setup))) + .andExpect(status().isTooManyRequests()) + .andExpect(header().exists(HttpHeaders.RETRY_AFTER)) + .andExpect(jsonPath("$.error").exists()); + } + + private Cookie startSession() throws Exception { + String value = mockMvc.perform(post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + FullContextSupport.currentPin(setup) + "\"}")) + .andExpect(status().isNoContent()) + .andReturn().getResponse().getCookie(SetupInterceptor.SESSION_COOKIE).getValue(); + return new Cookie(SetupInterceptor.SESSION_COOKIE, value); + } + + private static org.springframework.test.web.servlet.RequestBuilder pair(String pin) { + return post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java new file mode 100644 index 0000000..b994ce3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java @@ -0,0 +1,288 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +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.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiAuthTokenFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final String TOKEN = "full-context-token-0123456789-abcdefghijklmnop"; + private static final Set OPEN_ENDPOINTS = Set.of( + "GET /api/v1/health", "GET /api/v1/version", "GET /api/v1/setup", "POST /api/v1/setup/session", "POST /api/v1/pair"); + private static final List PROTECTED_VARIANTS = List.of( + "/api/v1/services;x", + "/api/v1/services;jsessionid=1", + "/api/v1;x/services", + "/api/v1/%73ervices", + "/api/v1/services/", + "/api/v1/services/%2e", + "/api/v1/%2e/services", + "//api/v1/services", + "///api/v1/services", + "/api/v1//services", + "/API/v1/services", + "/api/v1/backups;x/latest/download", + "/api/v1/backups/latest/download/", + "/api/v1/events;x", + "/api/v1/clients;x"); + + @BeforeAll + static void seedCompletedSetup() { + FullContextSupport.openDatabase(DATA_DIR).settings.saveSetting("setup_completed", "2026-11-19 10:00:00"); + } + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @Autowired + MockMvc mockMvc; + + @Autowired + PairedClientRepository pairedClients; + + @Autowired + SetupService setup; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping handlerMapping; + + @AfterEach + void forgetTestClient() { + pairedClients.removePairedClient("test"); + } + + @Test + @Order(1) + void pairingWithThePinIssuesAWorkingTokenOnce() throws Exception { + assertTrue(setup.isCompleted()); + assertTrue(setup.isPairingOpen()); + String pin = FullContextSupport.currentPin(setup); + + MvcResult paired = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + pin + "\", \"name\": \"Test laptop\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").isNotEmpty()) + .andReturn(); + Map body = JsonMapper.builder().build().readValue(paired.getResponse().getContentAsString(), Map.class); + String token = (String) body.get("token"); + String id = (String) body.get("id"); + + MvcResult again = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + pin + "\"}")) + .andExpect(status().isOk()) + .andReturn(); + String unusedToken = (String) JsonMapper.builder().build().readValue(again.getResponse().getContentAsString(), Map.class).get("token"); + assertTrue(pairedClients.fetchPairedClients().isEmpty()); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupRetentionCount").exists()); + mockMvc.perform(get("/api/v1/clients").header(HttpHeaders.AUTHORIZATION, "bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].current").value(true)); + assertTrue(pairedClients.fetchPairedClientByTokenHash(PairingService.hashToken(token)).isPresent()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + unusedToken)) + .andExpect(status().isUnauthorized()); + + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}")) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error").exists()); + + mockMvc.perform(delete("/api/v1/clients/" + id).header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isNoContent()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(2) + void aCodeFromAPairedClientPairsAnotherOne() throws Exception { + String token = addClient(); + + MvcResult created = mockMvc.perform(post("/api/v1/pairing-codes").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").isNotEmpty()) + .andReturn(); + String code = (String) JsonMapper.builder().build().readValue(created.getResponse().getContentAsString(), Map.class).get("code"); + + MvcResult paired = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").isNotEmpty()) + .andReturn(); + String pending = (String) JsonMapper.builder().build().readValue(paired.getResponse().getContentAsString(), Map.class).get("token"); + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isOk()); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + pending)) + .andExpect(status().isOk()); + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(3) + void missingWrongAndRevokedTokensAreRejected() throws Exception { + String token = addClient(); + + mockMvc.perform(get("/api/v1/services")).andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer nope")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Basic " + token)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, token)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer nope")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + + pairedClients.removePairedClient("test"); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(4) + void healthWithoutATokenRevealsOnlyWhatDiscoveryNeeds() throws Exception { + mockMvc.perform(get("/api/v1/health")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupInterval").exists()) + .andExpect(jsonPath("$.running").doesNotExist()) + .andExpect(jsonPath("$.backupRetentionCount").doesNotExist()); + } + + @Test + @Order(5) + void pathVariantsNeverReachAProtectedHandlerWithoutAToken() throws Exception { + for (String variant : PROTECTED_VARIANTS) { + for (HttpMethod method : List.of(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE)) { + int status = mockMvc.perform(MockMvcRequestBuilders.request(method, variant) + .contentType(MediaType.APPLICATION_JSON).content("{}")) + .andReturn().getResponse().getStatus(); + assertTrue(status == 401 || status == 404 || status == 405, + method + " " + variant + " answered " + status + " without a token"); + } + } + for (String variant : List.of("/api/v1/services;x", "/api/v1;x/services", "/api/v1/%73ervices", "/api/v1/services/")) { + mockMvc.perform(get(variant)).andExpect(status().isUnauthorized()); + } + } + + @Test + @Order(6) + void aMatrixParameterVariantReachesTheHandlerOnlyWithAValidToken() throws Exception { + String token = addClient(); + + mockMvc.perform(get("/api/v1/services;x").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + } + + @Test + @Order(7) + void everyRegisteredApiRouteOutsideTheAllowlistRequiresAToken() throws Exception { + Set reachableWithoutToken = new TreeSet<>(); + Set annotatedPublic = new TreeSet<>(); + int routes = 0; + for (Map.Entry entry : handlerMapping.getHandlerMethods().entrySet()) { + RequestMappingInfo info = entry.getKey(); + Set patterns = info.getPathPatternsCondition().getPatternValues(); + for (String pattern : patterns) { + if (pattern.equals("/error")) { + continue; + } + assertTrue(pattern.startsWith("/api/v1"), "Route outside /api/v1 bypasses the auth interceptor: " + pattern); + Set methods = info.getMethodsCondition().getMethods(); + assertFalse(methods.isEmpty(), "Route without an explicit method: " + pattern); + for (var method : methods) { + routes++; + String key = method.name() + " " + pattern; + if (entry.getValue().hasMethodAnnotation(PublicEndpoint.class)) { + annotatedPublic.add(key); + } + String path = pattern.replaceAll("\\{[^/]+}", "x"); + int status = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.valueOf(method.name()), path)) + .andReturn().getResponse().getStatus(); + if (status != 401) { + reachableWithoutToken.add(key); + } + } + } + } + + assertTrue(routes >= 20, "Only " + routes + " routes were enumerated"); + assertEquals(OPEN_ENDPOINTS, reachableWithoutToken); + assertEquals(OPEN_ENDPOINTS, annotatedPublic); + } + + @Test + @Order(8) + void theSetupPageIsGoneAndASetupCookieIsUselessAfterCompletion() throws Exception { + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config.html")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config;x")).andExpect(status().isNotFound()); + mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); + mockMvc.perform(get("/api/v1/services").cookie(new jakarta.servlet.http.Cookie(SetupInterceptor.SESSION_COOKIE, "anything"))) + .andExpect(status().isUnauthorized()); + } + + private String addClient() { + pairedClients.addPairedClient("test", "Test client", PairingService.hashToken(TOKEN), Instant.now()); + return TOKEN; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java new file mode 100644 index 0000000..c441eb3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java @@ -0,0 +1,61 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.EOFException; +import java.io.IOException; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +class ApiExceptionHandlerTest { + private final ApiExceptionHandler handler = new ApiExceptionHandler(); + private final Logger logger = (Logger) LoggerFactory.getLogger(ApiExceptionHandler.class); + private final ListAppender events = new ListAppender<>(); + private Level previous; + + @BeforeEach + void capture() { + previous = logger.getLevel(); + logger.setLevel(Level.DEBUG); + events.start(); + logger.addAppender(events); + } + + @AfterEach + void release() { + logger.detachAppender(events); + logger.setLevel(previous); + } + + private List levelsAfterCommit(Exception e) throws IOException { + MockHttpServletResponse response = new MockHttpServletResponse(); + response.getWriter().flush(); + response.flushBuffer(); + assertNull(handler.unexpected(e, response)); + return events.list.stream().map(ILoggingEvent::getLevel).toList(); + } + + @Test + void aFailureAfterTheResponseStartedIsLoggedAsAWarning() throws IOException { + assertEquals(List.of(Level.WARN), levelsAfterCommit(new IOException("disk read failed"))); + } + + @Test + void aClientThatWentAwayIsOnlyLoggedAtDebug() throws IOException { + assertEquals(List.of(Level.DEBUG), levelsAfterCommit(new IOException("Broken pipe", new EOFException()))); + events.list.clear(); + assertEquals(List.of(Level.DEBUG), levelsAfterCommit(new AsyncRequestNotUsableException("gone"))); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java new file mode 100644 index 0000000..2709fab --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java @@ -0,0 +1,46 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; + +import org.springframework.http.HttpHeaders; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.PairingService; + +final class ApiTestAuth { + + static final String TOKEN = "test-token"; + static final PairedClient CLIENT = new PairedClient("c1", "Test client", Instant.parse("2026-11-19T10:00:00Z"), null); + + private ApiTestAuth() {} + + static void accept(PairingService pairing) { + when(pairing.authenticate(TOKEN)).thenReturn(Optional.of(CLIENT)); + when(pairing.isPaired(CLIENT.id())).thenReturn(true); + } + + static MockHttpServletRequestBuilder get(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.get(url, vars)); + } + + static MockHttpServletRequestBuilder post(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.post(url, vars)); + } + + static MockHttpServletRequestBuilder put(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.put(url, vars)); + } + + static MockHttpServletRequestBuilder delete(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.delete(url, vars)); + } + + private static MockHttpServletRequestBuilder withToken(MockHttpServletRequestBuilder builder) { + return builder.header(HttpHeaders.AUTHORIZATION, "Bearer " + TOKEN); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index 29f5e25..ba71e2c 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -1,9 +1,12 @@ package wellatleastitried.mediagarrdServer.api; import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -12,17 +15,25 @@ import java.time.Instant; import java.util.List; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupFailedException; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunRejectedException; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.PairingService; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(BackupController.class) @@ -30,18 +41,26 @@ class BackupControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean BackupArchiveService archiveService; - @MockBean + @MockitoBean BackupOrchestratorService orchestratorService; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + @Test void healthReturnsServerStatus() throws Exception { when(orchestratorService.isRunning()).thenReturn(false); @@ -55,12 +74,35 @@ void healthReturnsServerStatus() throws Exception { } @Test - void clientEndpointsNeverRequireSetupSession() throws Exception { - when(archiveService.listArchives()).thenReturn(List.of()); + void healthWithoutATokenIsMinimal() throws Exception { when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); - mockMvc.perform(get("/api/v1/health")).andExpect(status().isOk()); - mockMvc.perform(get("/api/v1/backups")).andExpect(status().isOk()); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/health")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupInterval").exists()) + .andExpect(jsonPath("$.running").doesNotExist()) + .andExpect(jsonPath("$.backupRetentionCount").doesNotExist()); + } + + @Test + void healthWithAnInvalidTokenIsUnauthorized() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer revoked")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void everythingElseNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups/latest/download")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/backups/run")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/schedule") + .contentType(MediaType.APPLICATION_JSON).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isUnauthorized()); + + verifyNoInteractions(orchestratorService, archiveService); } @Test @@ -87,16 +129,64 @@ void runAndListBackups() throws Exception { mockMvc.perform(post("/api/v1/backups/run")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.archive.id").isNotEmpty()); + .andExpect(jsonPath("$.runId").value("run-1")) + .andExpect(jsonPath("$.startTime").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$.endTime").value("2026-01-01T00:01:00Z")) + .andExpect(jsonPath("$.servicesRan", hasSize(0))) + .andExpect(jsonPath("$.archive.id").value("backup-1")) + .andExpect(jsonPath("$.archive.fileName").value("backup-1.zip")) + .andExpect(jsonPath("$.archive.sizeBytes").value(12)) + .andExpect(jsonPath("$.archive.createdAt").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$.archive.path").doesNotExist()); mockMvc.perform(get("/api/v1/backups")) .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(1))); + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].id").value("backup-1")) + .andExpect(jsonPath("$[0].fileName").value("backup-1.zip")) + .andExpect(jsonPath("$[0].sizeBytes").value(12)) + .andExpect(jsonPath("$[0].createdAt").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$[0].path").doesNotExist()); + } + + @Test + void latestAndByIdReturnTheBackupWithoutItsPath() throws Exception { + BackupArchive archive = new BackupArchive("backup-2", "backup-2.zip", Path.of("/srv/backups/backup-2.zip"), 34, Instant.parse("2026-02-01T00:00:00Z")); + when(archiveService.latest()).thenReturn(java.util.Optional.of(archive)); + when(archiveService.byId("backup-2")).thenReturn(java.util.Optional.of(archive)); + + for (String url : List.of("/api/v1/backups/latest", "/api/v1/backups/backup-2")) { + mockMvc.perform(get(url)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value("backup-2")) + .andExpect(jsonPath("$.fileName").value("backup-2.zip")) + .andExpect(jsonPath("$.sizeBytes").value(34)) + .andExpect(jsonPath("$.createdAt").value("2026-02-01T00:00:00Z")) + .andExpect(jsonPath("$.path").doesNotExist()); + } + } + + @Test + void theLatestDownloadStreamsTheNewestArchiveAsAnAttachment(@TempDir Path tempDir) throws Exception { + Path file = tempDir.resolve("latest.zip"); + java.nio.file.Files.writeString(file, "newest-bytes"); + BackupArchive archive = new BackupArchive("20261121-media-backup", "20261121-media-backup.zip", file, 12, Instant.EPOCH); + when(archiveService.latest()).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/latest/download")) + .andExpect(status().isOk()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"20261121-media-backup.zip\"")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_LENGTH, "12")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().string("newest-bytes")); } @Test void rejectedRunReturnsConflictWithReason() throws Exception { - when(orchestratorService.runBackup()).thenThrow(new BackupOrchestratorService.RunRejectedException("A backup run is already in progress")); + when(orchestratorService.runBackup()).thenThrow(new RunRejectedException("A backup run is already in progress")); mockMvc.perform(post("/api/v1/backups/run")) .andExpect(status().isConflict()) @@ -105,18 +195,27 @@ void rejectedRunReturnsConflictWithReason() throws Exception { @Test void failedRunReturnsServerErrorWithReason() throws Exception { - when(orchestratorService.runBackup()).thenThrow(new IllegalStateException("Every service failed, no archive created: radarr: boom")); + when(orchestratorService.runBackup()).thenThrow(new BackupFailedException("Every service failed, no archive created: radarr: boom")); mockMvc.perform(post("/api/v1/backups/run")) .andExpect(status().isInternalServerError()) .andExpect(jsonPath("$.error").value("Every service failed, no archive created: radarr: boom")); } + @Test + void unexpectedFailureHidesItsDetails() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new IllegalStateException("Failed to create run directory /data/server/backups/run-1")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Internal error")); + } + @Test void deletingABackupPublishesBackupsChanged() throws Exception { when(archiveService.deleteById("backup-1")).thenReturn(true); - mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")) + mockMvc.perform(delete("/api/v1/backups/backup-1")) .andExpect(status().isNoContent()); org.mockito.Mockito.verify(broadcaster).publishBackupsChanged(); @@ -126,7 +225,7 @@ void deletingABackupPublishesBackupsChanged() throws Exception { void deletingAMissingBackupPublishesNothing() throws Exception { when(archiveService.deleteById("nope")).thenReturn(false); - mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/nope")) + mockMvc.perform(delete("/api/v1/backups/nope")) .andExpect(status().isNotFound()); org.mockito.Mockito.verify(broadcaster, org.mockito.Mockito.never()).publishBackupsChanged(); @@ -136,11 +235,93 @@ void deletingAMissingBackupPublishesNothing() throws Exception { void updatingTheSchedulePublishesConfigChanged() throws Exception { when(orchestratorService.updateInterval(Duration.ofHours(2))).thenReturn(Duration.ofHours(2)); - mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put("/api/v1/schedule") + mockMvc.perform(put("/api/v1/schedule") .contentType(org.springframework.http.MediaType.APPLICATION_JSON) .content("{\"backupInterval\": \"PT2H\"}")) .andExpect(status().isOk()); org.mockito.Mockito.verify(broadcaster).publishConfigChanged(); } + + @Test + void notFoundAnswersWithTheErrorShape() throws Exception { + when(archiveService.byId("nope")).thenReturn(java.util.Optional.empty()); + when(archiveService.latest()).thenReturn(java.util.Optional.empty()); + when(archiveService.deleteById("nope")).thenReturn(false); + + mockMvc.perform(get("/api/v1/backups/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + mockMvc.perform(get("/api/v1/backups/latest")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("No backup archives found")); + mockMvc.perform(get("/api/v1/backups/latest/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("No backup archives found")); + mockMvc.perform(get("/api/v1/backups/nope/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + mockMvc.perform(delete("/api/v1/backups/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + } + + @Test + void aMissingArchiveFileIsNotFoundWithTheErrorShape() throws Exception { + BackupArchive archive = new BackupArchive("gone", "gone.zip", Path.of("/nonexistent/gone.zip"), 1, Instant.EPOCH); + when(archiveService.byId("gone")).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/gone/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup file missing on disk")); + } + + @Test + void downloadsCarryAnAttachmentHeaderAndAreNotBrokenByNoStore() throws Exception { + Path file = java.nio.file.Files.createTempFile("download", ".zip"); + java.nio.file.Files.writeString(file, "zip-bytes"); + BackupArchive archive = new BackupArchive("20261120-media-backup", "20261120-media-backup.zip", file, 9, Instant.EPOCH); + when(archiveService.byId("20261120-media-backup")).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/20261120-media-backup/download")) + .andExpect(status().isOk()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"20261120-media-backup.zip\"")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().string("zip-bytes")); + } + + @Test + void anUnauthenticatedCallBeforeSetupSaysSetupIsUnfinished() throws Exception { + when(setup.isCompleted()).thenReturn(false); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.containsString("Setup is not finished"))); + } + + @Test + void anUnauthenticatedCallAfterSetupAsksForAToken() throws Exception { + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.containsString("Authorization required"))); + } + + @Test + void springRejectionsUseTheErrorShapeToo() throws Exception { + mockMvc.perform(post("/api/v1/backups/nope")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().exists("Allow")) + .andExpect(jsonPath("$.error").value("Method Not Allowed")); + } + + @Test + void anOverlongBodyIsRefusedBeforeItReachesTheController() throws Exception { + mockMvc.perform(put("/api/v1/schedule") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"backupInterval\": \"" + "P".repeat(RequestBodyLimitFilter.MAX_BODY_BYTES) + "\"}")) + .andExpect(status().isContentTooLarge()) + .andExpect(jsonPath("$.error").value(RequestBodyLimitFilter.MESSAGE)); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java index 9fee6ce..7c3db04 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -9,10 +9,11 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -25,21 +26,30 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import jakarta.servlet.http.Cookie; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupInProgressException; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; -import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.service.BackupRunLifecycle; import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.PairingService; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.ServiceConfigService; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(ConfigController.class) +@Import(ServiceConfigService.class) class ConfigControllerTest { private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); @@ -50,35 +60,41 @@ class ConfigControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean BackupArchiveService archiveService; - @MockBean - DatabaseService db; + @MockitoBean + ServiceRepository services; - @MockBean + @MockitoBean DockerService docker; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; - @MockBean + @MockitoBean + PairingService pairing; + + @MockitoBean BackupOrchestratorService orchestrator; + @MockitoBean + BackupRunLifecycle lifecycle; + @BeforeEach void setUp() { - when(setup.canConfigure(any())).thenReturn(true); - when(orchestrator.whileIdle(any())).thenAnswer(invocation -> invocation.>getArgument(0).get()); + ApiTestAuth.accept(pairing); + when(lifecycle.whileIdle(any())).thenAnswer(invocation -> invocation.>getArgument(0).get()); when(orchestrator.getInterval()).thenReturn(Duration.ofHours(6)); when(archiveService.retentionCount()).thenReturn(4); } @Test void rejectsConfigChangesWhileBackupIsRunning() throws Exception { - doThrow(new BackupOrchestratorService.BackupInProgressException("busy")).when(orchestrator).whileIdle(any()); + doThrow(new BackupInProgressException("busy")).when(lifecycle).whileIdle(any()); mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) .andExpect(status().isConflict()) @@ -87,8 +103,8 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)).andExpect(status().isConflict()); mockMvc.perform(json(put("/api/v1/config"), "{\"retentionCount\": 3}")).andExpect(status().isConflict()); - verify(db, never()).addService(any()); - verify(db, never()).removeService(anyString()); + verify(services, never()).addService(any()); + verify(services, never()).removeService(anyString()); verify(archiveService, never()).updateSettings(any(), any()); verify(broadcaster, never()).publishConfigChanged(); verify(broadcaster, never()).publishBackupsChanged(); @@ -96,21 +112,45 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { @Test void requiresSetupSessionUntilSetupIsComplete() throws Exception { - when(setup.canConfigure(any())).thenReturn(false); - - mockMvc.perform(get("/api/v1/services")) + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services")) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.error").exists()); - mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + mockMvc.perform(json(MockMvcRequestBuilders.post("/api/v1/services"), RADARR_JSON)) .andExpect(status().isUnauthorized()); - mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) + mockMvc.perform(json(MockMvcRequestBuilders.put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) .andExpect(status().isUnauthorized()); - verify(db, never()).fetchServices(); - verify(db, never()).addService(any()); + verify(services, never()).fetchServices(); + verify(services, never()).addService(any()); verify(archiveService, never()).updateSettings(any(), any()); } + @Test + void aSetupSessionIsEnoughBeforeSetupCompletes() throws Exception { + when(setup.canConfigure("session")).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isOk()); + } + + @Test + void aSetupSessionIsIgnoredAfterSetupCompletes() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(setup.canConfigure("session")).thenReturn(true); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()) + .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Bearer")); + } + + @Test + void aWrongTokenIsRejectedEvenBeforeSetupCompletes() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer wrong")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value("Invalid or revoked token, pair this client again")); + } + @Test void returnsBackupLocation() throws Exception { when(archiveService.rootDirectory()).thenReturn(Path.of("/backups")); @@ -159,7 +199,7 @@ void rejectsInvalidBackupLocation() throws Exception { @Test void listsServices() throws Exception { - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); mockMvc.perform(get("/api/v1/services")) .andExpect(status().isOk()) @@ -170,27 +210,27 @@ void listsServices() throws Exception { @Test void addsNormalizedService() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + when(services.fetchService("radarr")).thenReturn(Optional.empty()); mockMvc.perform(json(post("/api/v1/services"), "{\"name\": \" radarr \", \"paths\": [\"/srv/radarr/\", \"\"]}")) .andExpect(status().isCreated()) .andExpect(jsonPath("$.name").value("radarr")) .andExpect(jsonPath("$.paths", hasSize(1))); - verify(db).addService(RADARR); + verify(services).addService(RADARR); verify(orchestrator).servicesChanged(); verify(broadcaster).publishConfigChanged(); } @Test void rejectsDuplicateService() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) .andExpect(status().isConflict()) .andExpect(jsonPath("$.error").exists()); - verify(db, never()).addService(any()); + verify(services, never()).addService(any()); verify(orchestrator, never()).servicesChanged(); verify(broadcaster, never()).publishConfigChanged(); } @@ -201,18 +241,18 @@ void rejectsInvalidService() throws Exception { .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error").value("Path must be absolute: relative")); - verify(db, never()).addService(any()); + verify(services, never()).addService(any()); } @Test void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"radarr\", \"paths\": [\"/srv/other\"]}")) .andExpect(status().isOk()) .andExpect(jsonPath("$.paths[0]").value("/srv/other")); - verify(db).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(services).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); verify(orchestrator).servicesChanged(); verify(docker, never()).removeContainers(anyString()); verify(broadcaster).publishConfigChanged(); @@ -220,32 +260,32 @@ void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { @Test void renamingServiceRemovesOldContainers() throws Exception { - when(db.fetchService("RADARR")).thenReturn(Optional.of(RADARR)); - when(db.fetchService("movies")).thenReturn(Optional.empty()); + when(services.fetchService("RADARR")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("movies")).thenReturn(Optional.empty()); mockMvc.perform(json(put("/api/v1/services/RADARR"), "{\"name\": \"movies\", \"paths\": [\"/srv/radarr\"]}")) .andExpect(status().isOk()); - verify(db).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); + verify(services).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); verify(docker).removeContainers("radarr"); } @Test void renamingOntoExistingServiceConflicts() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); - when(db.fetchService("sonarr")).thenReturn(Optional.of(new ServiceDefinition("sonarr", List.of("/srv/sonarr")))); + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("sonarr")).thenReturn(Optional.of(new ServiceDefinition("sonarr", List.of("/srv/sonarr")))); mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"sonarr\", \"paths\": [\"/srv/radarr\"]}")) .andExpect(status().isConflict()); - verify(db, never()).updateService(anyString(), any()); + verify(services, never()).updateService(anyString(), any()); verify(orchestrator, never()).servicesChanged(); verify(broadcaster, never()).publishConfigChanged(); } @Test void updatingMissingServiceReturnsNotFound() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + when(services.fetchService("radarr")).thenReturn(Optional.empty()); mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) .andExpect(status().isNotFound()); @@ -255,19 +295,19 @@ void updatingMissingServiceReturnsNotFound() throws Exception { @Test void removesServiceAndItsContainers() throws Exception { - when(db.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); mockMvc.perform(delete("/api/v1/services/Radarr")) .andExpect(status().isNoContent()); - verify(db).removeService("radarr"); + verify(services).removeService("radarr"); verify(docker).removeContainers("radarr"); verify(broadcaster).publishConfigChanged(); } @Test void removingMissingServiceReturnsNotFound() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + when(services.fetchService("radarr")).thenReturn(Optional.empty()); mockMvc.perform(delete("/api/v1/services/radarr")) .andExpect(status().isNotFound()); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java new file mode 100644 index 0000000..f28a446 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java @@ -0,0 +1,296 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.PairRequest; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairedClientDto; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.dto.PublicHealthDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerConfigDto; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.dto.SetupCompleteDto; +import wellatleastitried.mediagarrdServer.dto.SetupSessionRequest; +import wellatleastitried.mediagarrdServer.dto.SetupStatusDto; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(DtoWireFormatTest.WireController.class) +@Import(DtoWireFormatTest.WireController.class) +class DtoWireFormatTest { + + private static final Instant MILLIS = Instant.parse("2026-11-11T18:00:00.123Z"); + private static final Instant WHOLE = Instant.parse("2026-11-11T18:00:00Z"); + private static final Instant NANOS = Instant.parse("2026-11-11T18:00:00.123456789Z"); + + @RestController + static class WireController { + + @GetMapping("/wire/backup") + BackupDto backup() { + return new BackupDto("id-1", "backup-1.zip", 1234567890123L, MILLIS); + } + + @GetMapping("/wire/backup-nanos") + BackupDto backupNanos() { + return new BackupDto("id-1", "backup-1.zip", 1L, NANOS); + } + + @GetMapping("/wire/backup-whole") + BackupDto backupWhole() { + return new BackupDto("id-1", "backup-1.zip", 1L, WHOLE); + } + + @GetMapping("/wire/backup-run") + BackupRunDto backupRun() { + return new BackupRunDto("run-1", "2026-11-11T18:00:00Z", "2026-11-11T18:05:00Z", List.of("a", "b"), + new BackupDto("id-1", "backup-1.zip", 10L, WHOLE)); + } + + @GetMapping("/wire/backup-run-empty") + BackupRunDto backupRunEmpty() { + return new BackupRunDto("run-1", "s", "e", List.of(), null); + } + + @GetMapping("/wire/paired-client") + PairedClientDto pairedClient() { + return new PairedClientDto("c-1", "Living room", WHOLE, null, true); + } + + @GetMapping("/wire/paired-client-used") + PairedClientDto pairedClientUsed() { + return new PairedClientDto("c-1", "Living room", WHOLE, MILLIS, false); + } + + @GetMapping("/wire/pairing-code") + PairingCodeDto pairingCode() { + return new PairingCodeDto("ABCD-EFGH", WHOLE); + } + + @GetMapping("/wire/pair-response") + PairResponse pairResponse() { + return new PairResponse("tok", "c-1", "Living room"); + } + + @GetMapping("/wire/public-health") + PublicHealthDto publicHealth() { + return new PublicHealthDto(true, Duration.ofHours(12)); + } + + @GetMapping("/wire/server-config") + ServerConfigDto serverConfig() { + return new ServerConfigDto("/var/lib/mediagarrd/backups", 10, Duration.ofMinutes(90)); + } + + @GetMapping("/wire/server-status") + ServerStatusDto serverStatus() { + return new ServerStatusDto(true, false, 10, Duration.ofSeconds(3661)); + } + + @GetMapping("/wire/setup-status") + SetupStatusDto setupStatus() { + return new SetupStatusDto(false, true); + } + + @GetMapping("/wire/setup-complete") + SetupCompleteDto setupComplete() { + return new SetupCompleteDto("123456"); + } + + @GetMapping("/wire/setup-complete-no-pin") + SetupCompleteDto setupCompleteNoPin() { + return new SetupCompleteDto(null); + } + + @GetMapping("/wire/version-status") + VersionStatusDto versionStatus() { + return new VersionStatusDto("0.1.0", "0.2.0", "https://example.invalid/r", true, CheckState.OK, MILLIS, null); + } + + @GetMapping("/wire/version-status-error") + VersionStatusDto versionStatusError() { + return new VersionStatusDto("0.1.0", null, null, false, CheckState.NO_RELEASES, WHOLE, "none"); + } + + @GetMapping("/wire/paired-client-model") + PairedClient pairedClientModel() { + return new PairedClient("c-1", "Living room", WHOLE, MILLIS); + } + + @GetMapping("/wire/service-definition") + ServiceDefinition serviceDefinition() { + return new ServiceDefinition("plex", List.of("/a", "/b")); + } + + @PostMapping("/wire/echo/config-update") + ConfigUpdateRequest echoConfigUpdate(@RequestBody ConfigUpdateRequest r) { + return r; + } + + @PostMapping("/wire/echo/pair-request") + PairRequest echoPairRequest(@RequestBody PairRequest r) { + return r; + } + + @PostMapping("/wire/echo/schedule-update") + ScheduleUpdateRequest echoScheduleUpdate(@RequestBody ScheduleUpdateRequest r) { + return r; + } + + @PostMapping("/wire/echo/setup-session") + SetupSessionRequest echoSetupSession(@RequestBody SetupSessionRequest r) { + return r; + } + + @PostMapping("/wire/echo/service-definition") + ServiceDefinition echoServiceDefinition(@RequestBody ServiceDefinition r) { + return r; + } + } + + @Autowired + MockMvc mockMvc; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + private void assertWire(String path, String expected) throws Exception { + mockMvc.perform(get(path)) + .andExpect(status().isOk()) + .andExpect(content().string(expected)); + } + + private void assertEcho(String path, String request, String expected) throws Exception { + mockMvc.perform(post(path).contentType(MediaType.APPLICATION_JSON).content(request)) + .andExpect(status().isOk()) + .andExpect(content().string(expected)); + } + + @Test + void backupDtoWritesInstantsAsIsoStrings() throws Exception { + assertWire("/wire/backup", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1234567890123,\"createdAt\":\"2026-11-11T18:00:00.123Z\"}"); + assertWire("/wire/backup-whole", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1,\"createdAt\":\"2026-11-11T18:00:00Z\"}"); + assertWire("/wire/backup-nanos", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1,\"createdAt\":\"2026-11-11T18:00:00.123456789Z\"}"); + } + + @Test + void backupRunDtoKeepsNullsAndNestedArchive() throws Exception { + assertWire("/wire/backup-run", + "{\"runId\":\"run-1\",\"startTime\":\"2026-11-11T18:00:00Z\",\"endTime\":\"2026-11-11T18:05:00Z\"," + + "\"servicesRan\":[\"a\",\"b\"],\"archive\":{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\"," + + "\"sizeBytes\":10,\"createdAt\":\"2026-11-11T18:00:00Z\"}}"); + assertWire("/wire/backup-run-empty", + "{\"runId\":\"run-1\",\"startTime\":\"s\",\"endTime\":\"e\",\"servicesRan\":[],\"archive\":null}"); + } + + @Test + void pairedClientDtoWritesNullLastUsedExplicitly() throws Exception { + assertWire("/wire/paired-client", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\",\"lastUsedAt\":null,\"current\":true}"); + assertWire("/wire/paired-client-used", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\"," + + "\"lastUsedAt\":\"2026-11-11T18:00:00.123Z\",\"current\":false}"); + assertWire("/wire/paired-client-model", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\",\"lastUsedAt\":\"2026-11-11T18:00:00.123Z\"}"); + } + + @Test + void pairingDtosKeepTheirShape() throws Exception { + assertWire("/wire/pairing-code", "{\"code\":\"ABCD-EFGH\",\"expiresAt\":\"2026-11-11T18:00:00Z\"}"); + assertWire("/wire/pair-response", "{\"token\":\"tok\",\"id\":\"c-1\",\"name\":\"Living room\"}"); + } + + @Test + void durationsAreWrittenAsIso8601Strings() throws Exception { + assertWire("/wire/public-health", "{\"healthy\":true,\"backupInterval\":\"PT12H\"}"); + assertWire("/wire/server-config", + "{\"backupLocation\":\"/var/lib/mediagarrd/backups\",\"retentionCount\":10,\"backupInterval\":\"PT1H30M\"}"); + assertWire("/wire/server-status", + "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":10,\"backupInterval\":\"PT1H1M1S\"}"); + } + + @Test + void statusDtosKeepTheirShape() throws Exception { + assertWire("/wire/setup-status", "{\"completed\":false,\"authorized\":true}"); + assertWire("/wire/setup-complete", "{\"pairingPin\":\"123456\"}"); + assertWire("/wire/setup-complete-no-pin", "{\"pairingPin\":null}"); + assertWire("/wire/version-status", + "{\"currentVersion\":\"0.1.0\",\"latestVersion\":\"0.2.0\",\"releaseUrl\":\"https://example.invalid/r\"," + + "\"updateAvailable\":true,\"checkState\":\"OK\",\"checkedAt\":\"2026-11-11T18:00:00.123Z\",\"message\":null}"); + assertWire("/wire/version-status-error", + "{\"currentVersion\":\"0.1.0\",\"latestVersion\":null,\"releaseUrl\":null,\"updateAvailable\":false," + + "\"checkState\":\"NO_RELEASES\",\"checkedAt\":\"2026-11-11T18:00:00Z\",\"message\":\"none\"}"); + } + + @Test + void serviceDefinitionKeepsNameAndPaths() throws Exception { + assertWire("/wire/service-definition", "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}"); + assertEcho("/wire/echo/service-definition", "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}", + "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}"); + } + + @Test + void requestDtosReadTheDocumentedBodies() throws Exception { + assertEcho("/wire/echo/config-update", "{\"backupLocation\":\"/data\",\"retentionCount\":3}", + "{\"backupLocation\":\"/data\",\"retentionCount\":3}"); + assertEcho("/wire/echo/config-update", "{}", "{\"backupLocation\":null,\"retentionCount\":null}"); + assertEcho("/wire/echo/pair-request", "{\"pin\":\"123456\",\"name\":\"TV\"}", "{\"pin\":\"123456\",\"name\":\"TV\"}"); + assertEcho("/wire/echo/pair-request", "{\"pin\":\"123456\"}", "{\"pin\":\"123456\",\"name\":null}"); + assertEcho("/wire/echo/setup-session", "{\"pin\":\"123456\"}", "{\"pin\":\"123456\"}"); + } + + @Test + void durationRequestsAcceptIsoStrings() throws Exception { + assertEcho("/wire/echo/schedule-update", "{\"backupInterval\":\"PT6H\"}", "{\"backupInterval\":\"PT6H\"}"); + assertEcho("/wire/echo/schedule-update", "{\"backupInterval\":\"PT90M\"}", "{\"backupInterval\":\"PT1H30M\"}"); + } + + @Test + void unknownPropertiesInRequestsAreIgnored() throws Exception { + assertEcho("/wire/echo/pair-request", "{\"pin\":\"1\",\"name\":\"TV\",\"extra\":true}", "{\"pin\":\"1\",\"name\":\"TV\"}"); + assertEcho("/wire/echo/config-update", "{\"retentionCount\":2,\"unknown\":[1,2]}", + "{\"backupLocation\":null,\"retentionCount\":2}"); + } + + @Test + void malformedBodiesAreRejectedAsBadRequests() throws Exception { + mockMvc.perform(post("/wire/echo/pair-request").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":")) + .andExpect(status().isBadRequest()); + mockMvc.perform(post("/wire/echo/schedule-update").contentType(MediaType.APPLICATION_JSON) + .content("{\"backupInterval\":\"not-a-duration\"}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java b/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java new file mode 100644 index 0000000..34d6548 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java @@ -0,0 +1,42 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.util.ReflectionTestUtils; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.service.SetupService; + +final class FullContextSupport { + + private FullContextSupport() {} + + static Path newDataDir() { + try { + return Files.createTempDirectory("mediagarrd-full-context"); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + static TestDatabase openDatabase(Path dataDir) { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(dataDir.resolve("mediagarrd.db").toString()); + return new TestDatabase(properties); + } + + static void register(DynamicPropertyRegistry registry, Path dataDir) { + registry.add("mediagarrd.database-path", () -> dataDir.resolve("mediagarrd.db").toString()); + registry.add("mediagarrd.backup-root", () -> dataDir.resolve("backups").toString()); + registry.add("mediagarrd.helper-image", () -> "alpine:3"); + registry.add("mediagarrd.github-api-base-url", () -> "http://127.0.0.1:1"); + } + + static String currentPin(SetupService setup) { + return ReflectionTestUtils.invokeMethod(setup, "currentPin"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java new file mode 100644 index 0000000..7a83c8e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java @@ -0,0 +1,142 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingException; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(PairingController.class) +class PairingControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + PairingService pairing; + + @MockitoBean + SetupService setup; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + + @Test + void pairReturnsTheTokenWithoutAnyAuthorization() throws Exception { + when(pairing.pair("123456", "Laptop")).thenReturn(new PairResponse("the-token", "abc", "Laptop")); + + mockMvc.perform(pair("{\"pin\": \"123456\", \"name\": \"Laptop\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").value("the-token")) + .andExpect(jsonPath("$.id").value("abc")) + .andExpect(jsonPath("$.name").value("Laptop")); + } + + @Test + void pairMapsRejectionsToStatusesWithErrorBodies() throws Exception { + when(pairing.pair("1", null)).thenThrow(new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code")); + when(pairing.pair("2", null)).thenThrow(new PairingException(PairingException.Reason.CLOSED, "Pairing is closed")); + when(pairing.pair("3", null)).thenThrow(new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + when(pairing.pair("4", null)).thenThrow(new LockedOutException(Duration.ofSeconds(90))); + when(pairing.pair("5", null)).thenThrow(new IllegalArgumentException("Name must be 1 to 64 characters")); + + mockMvc.perform(pair("{\"pin\": \"1\"}")).andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value("Invalid PIN or pairing code")); + mockMvc.perform(pair("{\"pin\": \"2\"}")).andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error").value("Pairing is closed")); + mockMvc.perform(pair("{\"pin\": \"3\"}")).andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + mockMvc.perform(pair("{\"pin\": \"4\"}")).andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "90")) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(pair("{\"pin\": \"5\"}")).andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void pairWithAMalformedBodyIsABadRequestInTheErrorShape() throws Exception { + mockMvc.perform(pair("not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void creatingACodeNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/pairing-codes")).andExpect(status().isUnauthorized()); + when(pairing.createCode()).thenReturn(new PairingCodeDto("ABCDE-FGHJK", Instant.parse("2026-11-19T10:10:00Z"))); + + mockMvc.perform(post("/api/v1/pairing-codes")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value("ABCDE-FGHJK")) + .andExpect(jsonPath("$.expiresAt").exists()); + } + + @Test + void listingMarksTheCallersOwnRecord() throws Exception { + Instant created = Instant.parse("2026-11-19T10:00:00Z"); + when(pairing.list()).thenReturn(List.of(ApiTestAuth.CLIENT, new PairedClient("c2", "Phone", created, created))); + + mockMvc.perform(get("/api/v1/clients")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].id").value("c1")) + .andExpect(jsonPath("$[0].current").value(true)) + .andExpect(jsonPath("$[1].current").value(false)) + .andExpect(jsonPath("$[0].token").doesNotExist()) + .andExpect(jsonPath("$[0].tokenHash").doesNotExist()); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/clients")).andExpect(status().isUnauthorized()); + } + + @Test + void revokingARecordAnswers204AndAMissingOneAnswers404() throws Exception { + when(pairing.revoke("c2")).thenReturn(true); + when(pairing.revoke("nope")).thenReturn(false); + + mockMvc.perform(delete("/api/v1/clients/c2")).andExpect(status().isNoContent()); + mockMvc.perform(delete("/api/v1/clients/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Client not found")); + } + + @Test + void revokingNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/clients/c1")).andExpect(status().isUnauthorized()); + + verify(pairing, never()).revoke(any()); + } + + private static org.springframework.test.web.servlet.RequestBuilder pair(String body) { + return MockMvcRequestBuilders.post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java new file mode 100644 index 0000000..6a69c09 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java @@ -0,0 +1,171 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Map; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import tools.jackson.databind.json.JsonMapper; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +class RealServletFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @BeforeAll + static void seedCompletedSetup() { + FullContextSupport.openDatabase(DATA_DIR).settings.saveSetting("setup_completed", "2026-11-20 10:00:00"); + } + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @LocalServerPort + int port; + + @Autowired + SetupService setup; + + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + + private URI uri(String path) { + return URI.create("http://localhost:" + port + path); + } + + private HttpResponse send(HttpRequest.Builder request) throws Exception { + return client.send(request.timeout(Duration.ofSeconds(10)).build(), BodyHandlers.ofString()); + } + + private static String pairedToken; + + private synchronized String pair() throws Exception { + if (pairedToken != null) { + return pairedToken; + } + String body = "{\"pin\":\"" + FullContextSupport.currentPin(setup) + "\",\"name\":\"Real servlet\"}"; + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json").POST(BodyPublishers.ofString(body))); + assertEquals(200, response.statusCode(), response.body()); + pairedToken = (String) JSON.readValue(response.body(), Map.class).get("token"); + return pairedToken; + } + + @Test + void aPairedClientCanOpenTheEventStreamAndGetsItsFirstEvent() throws Exception { + String token = pair(); + + HttpResponse response = client.send(HttpRequest.newBuilder(uri("/api/v1/events")) + .header("Authorization", "Bearer " + token).header("Accept", "text/event-stream").GET().build(), BodyHandlers.ofInputStream()); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body(), StandardCharsets.UTF_8))) { + assertEquals(200, response.statusCode()); + assertTrue(response.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream")); + assertEquals("no-store", response.headers().firstValue("Cache-Control").orElse(null)); + String line = reader.readLine(); + while (line != null && !line.startsWith("event:")) { + line = reader.readLine(); + } + assertEquals("event:state", line); + } + } + + @Test + void theEventStreamRefusesARequestWithoutATokenWithTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/events")).GET()); + + assertEquals(401, response.statusCode()); + assertNotNull(JSON.readValue(response.body(), Map.class).get("error")); + } + + @Test + void unknownPathsAndWrongMethodsUseTheErrorShape() throws Exception { + String token = pair(); + + HttpResponse missing = send(HttpRequest.newBuilder(uri("/api/v1/does-not-exist")) + .header("Authorization", "Bearer " + token).GET()); + HttpResponse wrongMethod = send(HttpRequest.newBuilder(uri("/api/v1/backups")) + .header("Authorization", "Bearer " + token).POST(BodyPublishers.noBody())); + HttpResponse staticMissing = send(HttpRequest.newBuilder(uri("/no-such-page.html")).GET()); + + assertEquals(404, missing.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(missing.body(), Map.class)); + assertEquals(405, wrongMethod.statusCode()); + assertEquals(Map.of("error", "Method Not Allowed"), JSON.readValue(wrongMethod.body(), Map.class)); + assertTrue(wrongMethod.headers().firstValue("Allow").isPresent()); + assertEquals(404, staticMissing.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(staticMissing.body(), Map.class)); + } + + @Test + void theErrorDispatchOfTheDisabledSetupPageUsesTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/config")).GET()); + + assertEquals(404, response.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(response.body(), Map.class)); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null)); + } + + @Test + void realResponsesCarryTheSecurityHeaders() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/health")).GET()); + + assertEquals(200, response.statusCode()); + assertEquals("DENY", response.headers().firstValue("X-Frame-Options").orElse(null)); + assertEquals(SecurityHeadersFilter.CONTENT_SECURITY_POLICY, response.headers().firstValue("Content-Security-Policy").orElse(null)); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null)); + assertEquals("no-referrer", response.headers().firstValue("Referrer-Policy").orElse(null)); + assertEquals("no-store", response.headers().firstValue("Cache-Control").orElse(null)); + } + + @Test + void aChunkedBodyOverTheCapIsRefusedAndASmallOneIsNot() throws Exception { + byte[] big = ("{\"pin\":\"" + "1".repeat(RequestBodyLimitFilter.MAX_BODY_BYTES + 10) + "\"}").getBytes(StandardCharsets.UTF_8); + + HttpResponse refused = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json") + .POST(BodyPublishers.fromPublisher(BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(big))))); + HttpResponse accepted = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json") + .POST(BodyPublishers.fromPublisher(BodyPublishers.ofInputStream( + () -> new ByteArrayInputStream("{\"pin\":\"000000\"}".getBytes(StandardCharsets.UTF_8)))))); + + assertEquals(413, refused.statusCode()); + assertEquals(Map.of("error", RequestBodyLimitFilter.MESSAGE), JSON.readValue(refused.body(), Map.class)); + assertTrue(accepted.statusCode() != 413, accepted.body()); + } + + @Test + void anUnknownCharsetInTheContentTypeIsRefusedWith415AndTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json; charset=nope-8") + .POST(BodyPublishers.ofString("{\"pin\":\"000000\"}"))); + + assertEquals(415, response.statusCode(), response.body()); + assertTrue(JSON.readValue(response.body(), Map.class).containsKey("error"), response.body()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java new file mode 100644 index 0000000..9749e59 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java @@ -0,0 +1,65 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import jakarta.servlet.http.HttpServletRequest; +import tools.jackson.databind.json.JsonMapper; + +class RequestBodyLimitFilterTest { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final RequestBodyLimitFilter filter = new RequestBodyLimitFilter(); + + private MockHttpServletRequest post(String characterEncoding) { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/v1/pair"); + request.setContentType("application/json"); + request.setCharacterEncoding(characterEncoding); + request.setContent("{\"pin\":\"000000\"}".getBytes(StandardCharsets.UTF_8)); + return request; + } + + @Test + void anUnknownCharsetAnswers400WithTheErrorShapeAndNeverReachesTheController() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + + filter.doFilter(post("nope-8"), response, chain); + + assertEquals(400, response.getStatus()); + assertEquals(Map.of("error", RequestBodyLimitFilter.UNSUPPORTED_CHARSET_MESSAGE), JSON.readValue(response.getContentAsString(), Map.class)); + assertNull(chain.getRequest()); + } + + @Test + void anIllegalCharsetNameAnswers400() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + + filter.doFilter(post("bad name!"), response, new MockFilterChain()); + + assertEquals(400, response.getStatus()); + } + + @Test + void aKnownCharsetIsReadWithThatCharset() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + AtomicReference body = new AtomicReference<>(); + + filter.doFilter(post("ISO-8859-1"), response, (request, servletResponse) -> { + body.set(((HttpServletRequest) request).getReader().readLine()); + }); + + assertEquals(200, response.getStatus()); + assertEquals("{\"pin\":\"000000\"}", body.get()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java index e4c64e9..9ce661f 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java @@ -1,21 +1,27 @@ package wellatleastitried.mediagarrdServer.api; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.service.PairingService; import wellatleastitried.mediagarrdServer.service.SetupService; @Timeout(30) @@ -25,35 +31,60 @@ class RunEventsControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + @Test - void streamsEventsWithoutASetupSession() throws Exception { - when(setup.isCompleted()).thenReturn(false); - when(setup.canConfigure(null)).thenReturn(false); - when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + void streamsEventsWithATokenWhetherOrNotSetupIsComplete() throws Exception { + when(broadcaster.subscribe("c1")).thenReturn(new SseEmitter(60_000L)); - mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) - .andExpect(request().asyncStarted()) - .andExpect(status().isOk()); + for (boolean completed : new boolean[] {false, true}) { + when(setup.isCompleted()).thenReturn(completed); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()); + } } @Test - void streamsEventsAfterSetupToo() throws Exception { - when(setup.isCompleted()).thenReturn(true); - when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + void refusesEventsWithoutATokenOrWithASetupSession() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isUnauthorized()); + + when(setup.canConfigure("session")).thenReturn(true); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM) + .cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()); + + verifyNoInteractions(broadcaster); + } + + @Test + void aClientRevokedWhileSubscribingIsClosedAndRefused() throws Exception { + when(broadcaster.subscribe("c1")).thenReturn(new SseEmitter(60_000L)); + when(pairing.isPaired("c1")).thenReturn(false); mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) - .andExpect(request().asyncStarted()); + .andExpect(status().isUnauthorized()); + + verify(broadcaster).closeClient("c1"); } @Test void answers503WhenTooManySubscribers() throws Exception { - when(broadcaster.subscribe()).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); + when(broadcaster.subscribe("c1")).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(status().isServiceUnavailable()); @@ -61,7 +92,7 @@ void answers503WhenTooManySubscribers() throws Exception { @Test void aTimedOutStreamEndsQuietlyWithoutAnErrorPage() throws Exception { - when(broadcaster.subscribe()).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); + when(broadcaster.subscribe("c1")).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); var result = mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(status().isOk()) diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java new file mode 100644 index 0000000..5a862af --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java @@ -0,0 +1,117 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.BackupScheduleService; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(BackupController.class) +class ScheduleIntervalApiTest { + + private static final String MESSAGE = "Backup interval must be between 15 minutes and 365 days"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + BackupArchiveService archiveService; + + @MockitoBean + BackupOrchestratorService orchestratorService; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @TempDir + Path tempDir; + + private TestDatabase db; + private BackupScheduleService schedule; + + @BeforeEach + void setUp() { + ApiTestAuth.accept(pairing); + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new TestDatabase(properties); + schedule = new BackupScheduleService(properties, db.settings, db.backups, setup); + when(orchestratorService.updateInterval(any())).thenAnswer(invocation -> schedule.updateInterval(invocation.getArgument(0))); + when(orchestratorService.getInterval()).thenAnswer(invocation -> schedule.getInterval()); + } + + private org.springframework.test.web.servlet.ResultActions putSchedule(String body) throws Exception { + return mockMvc.perform(put("/api/v1/schedule").contentType(MediaType.APPLICATION_JSON).content(body)); + } + + @Test + void rejectedIntervalsAnswer400AndSaveNothing() throws Exception { + putSchedule("{\"backupInterval\": \"PT2H\"}").andExpect(status().isOk()); + Duration before = schedule.getInterval(); + + List bodies = List.of( + "{}", + "{\"backupInterval\": null}", + "{\"backupInterval\": \"PT0S\"}", + "{\"backupInterval\": \"-PT5M\"}", + "{\"backupInterval\": \"PT14M59S\"}", + "{\"backupInterval\": \"PT1S\"}", + "{\"backupInterval\": \"P365DT1S\"}", + "{\"backupInterval\": \"PT600000000000000M\"}", + "{\"backupInterval\": 0}", + "{\"backupInterval\": -60}", + "{\"backupInterval\": 899}", + "{\"backupInterval\": 31536001}", + "{\"backupInterval\": 36000000000000}"); + for (String body : bodies) { + putSchedule(body) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value(MESSAGE)); + } + + assertEquals(before, schedule.getInterval()); + assertEquals(before.toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void boundaryIntervalsAreAccepted() throws Exception { + putSchedule("{\"backupInterval\": \"PT15M\"}").andExpect(status().isOk()); + assertEquals(Duration.ofMinutes(15), schedule.getInterval()); + putSchedule("{\"backupInterval\": \"P365D\"}").andExpect(status().isOk()); + assertEquals(Duration.ofDays(365), schedule.getInterval()); + putSchedule("{\"backupInterval\": 900}").andExpect(status().isOk()); + assertEquals(Duration.ofMinutes(15), schedule.getInterval()); + putSchedule("{\"backupInterval\": 31536000}").andExpect(status().isOk()); + assertEquals(Duration.ofDays(365), schedule.getInterval()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java index 049aa09..3ea26bf 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java @@ -5,27 +5,34 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.time.Duration; import java.util.List; import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import jakarta.servlet.http.Cookie; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; -import wellatleastitried.mediagarrdServer.service.DatabaseService; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupAlreadyCompleteException; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(SetupController.class) @@ -34,11 +41,19 @@ class SetupControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean SetupService setup; - @MockBean - DatabaseService db; + @MockitoBean + PairingService pairing; + + @MockitoBean + ServiceRepository services; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } @Test void reportsStatusForTheCallersSession() throws Exception { @@ -83,9 +98,19 @@ void pinIsGoneAfterSetupCompletes() throws Exception { verify(setup, never()).startSession(any()); } + @Test + void lockedPinAnswers429WithRetryAfter() throws Exception { + when(setup.startSession("000000")).thenThrow(new LockedOutException(Duration.ofMinutes(7))); + + mockMvc.perform(pin("000000")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "420")) + .andExpect(jsonPath("$.error").exists()); + } + @Test void completeRequiresSession() throws Exception { - mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); verify(setup, never()).complete(); } @@ -93,7 +118,7 @@ void completeRequiresSession() throws Exception { @Test void completeRequiresAtLeastOneService() throws Exception { when(setup.canConfigure(any())).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); mockMvc.perform(post("/api/v1/setup/complete")) .andExpect(status().isConflict()) @@ -105,15 +130,49 @@ void completeRequiresAtLeastOneService() throws Exception { @Test void completeFinishesSetupAndClearsCookie() throws Exception { when(setup.canConfigure(any())).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenReturn("123456"); mockMvc.perform(post("/api/v1/setup/complete")) - .andExpect(status().isNoContent()) - .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Max-Age=0"))); + .andExpect(status().isOk()) + .andExpect(jsonPath("$.pairingPin").value("123456")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Max-Age=0"))) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")); verify(setup).complete(); } + @Test + void completeAnswersAnExplicitNullPinWhenNoPinApplies() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenReturn(null); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"pairingPin\":null}", true)); + } + + @Test + void completeIsGoneWhenARacingRequestCompletedFirst() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenThrow(new SetupAlreadyCompleteException()); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isGone()); + } + + @Test + void completeIsAGenericServerErrorWhenSavingFails() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenThrow(new IllegalStateException("Failed to save setting")); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Internal error")); + } + @Test void completeIsGoneWhenAlreadyCompleted() throws Exception { when(setup.isCompleted()).thenReturn(true); @@ -135,7 +194,19 @@ void setupPageIsServedOnlyUntilSetupCompletes() throws Exception { mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); } - private static RequestBuilder pin(String pin) { + private static org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder pin(String pin) { return post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}"); } + + @Test + void theSessionCookieIsSecureOnlyOverHttps() throws Exception { + when(setup.startSession("123456")).thenReturn(Optional.of("token")); + + mockMvc.perform(pin("123456")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, org.hamcrest.Matchers.not(containsString("Secure")))); + mockMvc.perform(pin("123456").header("X-Forwarded-Proto", "https")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Secure"))); + mockMvc.perform(pin("123456").secure(true)) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Secure"))); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java new file mode 100644 index 0000000..506f644 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java @@ -0,0 +1,166 @@ +package wellatleastitried.mediagarrdServer.api; + +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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; + +class SetupPageAssetsTest { + + private static final Path STATIC = Path.of("src/main/resources/static"); + + private static String read(String name) throws IOException { + return Files.readString(STATIC.resolve(name)); + } + + @Test + void thePagesNeedNoInlineScriptOrStyleSoTheCspHolds() throws IOException { + for (String page : new String[] {"config.html", "index.html"}) { + String html = read(page); + assertFalse(Pattern.compile("]*\\bsrc=)").matcher(html).find(), page + " has an inline script"); + assertFalse(html.contains(" scripts = Files.walk(STATIC.resolve("js"))) { + for (Path script : scripts.filter(path -> path.toString().endsWith(".js")).toList()) { + String code = Files.readString(script); + for (String forbidden : new String[] {"innerHTML", "insertAdjacentHTML", "eval(", "cssText", "setAttribute('style'"}) { + assertFalse(code.contains(forbidden), script + " uses " + forbidden); + } + } + } + } + + @Test + void aFailedUnlockKeepsTheWorkspaceHiddenAndShowsTheError() throws IOException { + String config = read("js/config.js"); + + assertTrue(config.contains("workspace.hidden = true;")); + assertTrue(read("config.html").contains("id=\"fatal\" role=\"alert\"")); + } + + @Test + void thePinFormIsAccessibleAndRefocusedAfterAMistake() throws IOException { + String html = read("config.html"); + String setup = read("js/setup.js"); + + assertTrue(html.contains("aria-describedby=\"pinError\"")); + assertTrue(html.contains("id=\"pinError\" data-error role=\"alert\" aria-live=\"polite\"")); + assertTrue(setup.contains("form.elements.pin.focus()")); + } + + @Test + void theFinishButtonIsFoundByItsOwnAttribute() throws IOException { + assertTrue(read("config.html").contains("data-finish")); + assertTrue(read("js/setup.js").contains("querySelector('[data-finish]')")); + } + + @Test + void theFinishReplyShowsThePairingPinWithACopyButtonAndNeverStoresIt() throws IOException { + String html = read("config.html"); + String setup = read("js/setup.js"); + String config = read("js/config.js"); + + assertTrue(html.contains("id=\"pairingResult\" hidden")); + assertTrue(html.contains("data-copy-pin")); + assertTrue(html.contains("data-without-pin")); + assertTrue(html.indexOf("id=\"pairingResult\"") < html.indexOf("
")); + assertTrue(setup.contains("code.textContent = pairingPin;")); + assertTrue(setup.contains("result.pairingPin")); + assertFalse(setup.contains("localStorage") || setup.contains("sessionStorage") || setup.contains("location.")); + assertTrue(config.contains("document.getElementById('pairingResult')")); + assertTrue(read("css/mediagarrd.css").contains(".pin-row { display: flex; flex-wrap: wrap;")); + } + + @Test + void aRateLimitedUnlockShowsTheWaitFromRetryAfter() throws IOException { + assertTrue(read("js/api.js").contains("Retry-After")); + assertTrue(read("js/setup.js").contains("e.retryAfter")); + } + + @Test + void aPartiallySavedSettingsFormIsRefreshedAndExplained() throws IOException { + String settings = read("js/settings.js"); + + assertTrue(settings.contains("were saved, but the interval was not")); + assertTrue(settings.contains("api.getConfig().then(show)")); + } + + @Test + void theServiceFormAndTableAreLabelled() throws IOException { + String html = read("config.html"); + + assertTrue(html.contains("Host paths to back up")); + assertTrue(html.contains("aria-label=\"Host path\"")); + assertTrue(html.contains("aria-label=\"Remove path\"")); + assertTrue(html.contains("")); + assertEquals(3, html.split("]*>[^<]*

\\s*
* { min-width: 0; }")); + assertTrue(css.contains(".button-row { display: flex; flex-wrap: wrap;")); + assertTrue(css.contains(".input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto;")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java index 6027d77..2e2d718 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java @@ -9,12 +9,13 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import wellatleastitried.mediagarrdServer.dto.CheckState; import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.PairingService; import wellatleastitried.mediagarrdServer.service.SetupService; import wellatleastitried.mediagarrdServer.service.UpdateCheckService; @@ -24,16 +25,18 @@ class VersionControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean UpdateCheckService updateCheckService; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + @Test - void reportsTheVersionStatusWithoutASetupSession() throws Exception { + void reportsTheVersionStatusWithoutATokenOrSetupSession() throws Exception { when(setup.isCompleted()).thenReturn(false); - when(setup.canConfigure(null)).thenReturn(false); when(updateCheckService.status()).thenReturn(new VersionStatusDto( "0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, CheckState.OK, Instant.parse("2026-11-11T18:00:00Z"), null)); @@ -48,16 +51,4 @@ void reportsTheVersionStatusWithoutASetupSession() throws Exception { .andExpect(jsonPath("$.checkedAt").value("2026-11-11T18:00:00Z")) .andExpect(jsonPath("$.message").doesNotExist()); } - - @Test - void reportsAFailedCheckAsAState() throws Exception { - when(updateCheckService.status()).thenReturn(new VersionStatusDto( - "0.1.0", null, null, false, CheckState.ERROR, Instant.parse("2026-11-11T18:00:00Z"), "GitHub is unreachable")); - - mockMvc.perform(get("/api/v1/version")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.checkState").value("ERROR")) - .andExpect(jsonPath("$.updateAvailable").value(false)) - .andExpect(jsonPath("$.message").value("GitHub is unreachable")); - } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java new file mode 100644 index 0000000..99f5bde --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java @@ -0,0 +1,217 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.FAILURE_WEBHOOK_SETTING; + +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; +import wellatleastitried.mediagarrdServer.service.WebhookService; + +@WebMvcTest(WebhookController.class) +@Import(WebhookService.class) +class WebhookControllerTest { + + private static final String SECRET_URL = "https://discord.com/api/webhooks/123456/SECRETTOKEN123"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + SettingsRepository settings; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + private final ListAppender logs = new ListAppender<>(); + private final Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + + @BeforeEach + void setUp() { + ApiTestAuth.accept(pairing); + logs.start(); + rootLogger.addAppender(logs); + } + + @AfterEach + void tearDown() { + rootLogger.detachAppender(logs); + } + + @Test + void reportsNotConfiguredByDefault() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/v1/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":false,\"target\":null}", true)); + } + + @Test + void theGetMasksTheUrlDownToSchemeAndHost() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of(SECRET_URL)); + + MvcResult result = mockMvc.perform(get("/api/v1/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":true,\"target\":\"https://discord.com\"}", true)) + .andReturn(); + + String body = result.getResponse().getContentAsString(); + assertFalse(body.contains("SECRETTOKEN123") || body.contains("webhooks")); + } + + @Test + void thePutSavesTheUrlAndAnswersWithTheMaskedStatus() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of(SECRET_URL)); + + MvcResult result = mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"" + SECRET_URL + "\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":true,\"target\":\"https://discord.com\"}", true)) + .andReturn(); + + verify(settings).saveSetting(FAILURE_WEBHOOK_SETTING, SECRET_URL); + verify(broadcaster).publishConfigChanged(); + assertFalse(result.getResponse().getContentAsString().contains("SECRETTOKEN123")); + assertFalse(logText().contains("SECRETTOKEN123")); + } + + @Test + void thePutClearsWithAnEmptyStringOrNull() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of("")); + + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":false,\"target\":null}", true)); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": null}")) + .andExpect(status().isOk()); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{}")) + .andExpect(status().isOk()); + + verify(settings, org.mockito.Mockito.times(3)).saveSetting(FAILURE_WEBHOOK_SETTING, ""); + } + + @Test + void aBadUrlIsA400WithAFixedMessageThatNeverEchoesTheInput() throws Exception { + String body = "{\"url\": \"https://discord.com/api/webhooks/123/SECRETTOKEN123|\"}"; + + MvcResult result = mockMvc.perform(json(put("/api/v1/notifications/webhook"), body)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL is not a valid URL")) + .andReturn(); + + verify(settings, never()).saveSetting(anyString(), anyString()); + verify(broadcaster, never()).publishConfigChanged(); + assertFalse(result.getResponse().getContentAsString().contains("SECRETTOKEN123")); + assertFalse(logText().contains("SECRETTOKEN123")); + } + + @Test + void userInfoAndWrongSchemesAreRejected() throws Exception { + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"https://user:pw@example.com/x\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must not contain user info")); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"file:///etc/passwd\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must use http or https")); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": 5}")) + .andExpect(status().isBadRequest()); + } + + @Test + void aTestWithoutAWebhookIsA400() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.empty()); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No webhook is configured")); + } + + @Test + void aTestAnswersWithTheDeliveryResultAndThenThe429Cooldown() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of("http://127.0.0.1:1/hook")); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"delivered\":false,\"status\":null,\"error\":\"Could not connect\"}", true)); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().exists(HttpHeaders.RETRY_AFTER)) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.startsWith("Wait "))); + } + + @Test + void theEndpointsNeedATokenOrASetupSession() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/notifications/webhook/test")).andExpect(status().isUnauthorized()); + + verify(settings, never()).saveSetting(anyString(), anyString()); + } + + @Test + void aSetupSessionIsEnoughBeforeSetupCompletesAndIgnoredAfter() throws Exception { + when(setup.canConfigure("session")).thenReturn(true); + when(settings.fetchSetting(eq(FAILURE_WEBHOOK_SETTING))).thenReturn(Optional.empty()); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isOk()); + + when(setup.isCompleted()).thenReturn(true); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()); + } + + private String logText() { + StringBuilder text = new StringBuilder(); + for (ILoggingEvent event : logs.list) { + text.append(event.getFormattedMessage()).append('\n'); + } + return text.toString(); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java index 80fa721..ca67ba3 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java @@ -54,4 +54,14 @@ void rejectsInvalidPaths(String path) { void requiresAtLeastOnePath() { assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("radarr", List.of(" ")).validate()); } + + @Test + void limitsThePathCountAndPathLength() { + java.util.List many = java.util.stream.IntStream.range(0, ServiceDefinition.MAX_PATHS + 1).mapToObj(i -> "/p" + i).toList(); + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("svc", many).validate()); + String longPath = "/" + "a".repeat(ServiceDefinition.MAX_PATH_LENGTH); + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, + () -> new ServiceDefinition("svc", java.util.List.of(longPath)).validate()); + new ServiceDefinition("svc", java.util.stream.IntStream.range(0, ServiceDefinition.MAX_PATHS).mapToObj(i -> "/p" + i).toList()).validate(); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java new file mode 100644 index 0000000..455c603 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java @@ -0,0 +1,96 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +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; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +class BackupRecordRepositoryTest extends DatabaseTestBase { + + @Test + void storesBackupRecordWithEveryServiceResult() { + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", + serviceResult("jellyfin", COMPLETED, null), + serviceResult("sonarr", PARTIAL, "one path failed"), + serviceResult("qbittorrent", FAILED, "no paths copied"))); + + FetchedBackupRecord record = db.backups.fetchBackupById("run-1").orElseThrow(); + + assertEquals("run-1", record.archiveId()); + assertEquals("2026-01-01 00:00:00", record.startTime()); + assertEquals(COMPLETED, record.status()); + assertEquals(Path.of("run-1.zip").toString(), record.filePath()); + assertEquals( + Set.of( + new FetchedBackupServiceRecord("jellyfin", COMPLETED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", null), + new FetchedBackupServiceRecord("sonarr", PARTIAL, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "one path failed"), + new FetchedBackupServiceRecord("qbittorrent", FAILED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "no paths copied")), + Set.copyOf(record.fetchedServices())); + } + + @Test + void storesFailedRunWithoutArchive() { + db.backups.addNewBackupRecord(new BackupRunResult("failed-1", "2026-01-01 00:00:00", "2026-01-01 00:00:01", FAILED, + List.of(serviceResult("radarr", FAILED, "boom")), null, "radarr: boom")); + + FetchedBackupRecord record = db.backups.fetchBackupById("failed-1").orElseThrow(); + + assertEquals(FAILED, record.status()); + assertNull(record.filePath()); + assertEquals("radarr: boom", record.errorMessage()); + assertEquals(1, record.fetchedServices().size()); + } + + @Test + void fetchesLatestBackupRecordByStartTime() { + db.backups.addNewBackupRecord(backupRun("older", "2026-01-01 00:00:00")); + db.backups.addNewBackupRecord(backupRun("newer", "2026-02-01 00:00:00")); + + assertEquals("newer", db.backups.fetchLatestBackupRecord().orElseThrow().archiveId()); + } + + @Test + void returnsEmptyForMissingBackupRecords() { + assertTrue(db.backups.fetchBackupById("missing").isEmpty()); + assertTrue(db.backups.fetchLatestBackupRecord().isEmpty()); + } + + @Test + void deletingBackupRecordCascadesToServiceRows() throws Exception { + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + assertEquals(1, count("backup_services")); + + db.backups.deleteBackupRecordById("run-1"); + + assertEquals(0, count("backup_services")); + assertTrue(db.backups.fetchBackupById("run-1").isEmpty()); + } + + @Test + void lastSuccessfulStartTimeIgnoresFailedRunsAndCountsPartialOnes() { + assertTrue(db.backups.fetchLastSuccessfulStartTime().isEmpty()); + + db.backups.addNewBackupRecord(backupRun("good", "2026-01-01 00:00:00")); + db.backups.addNewBackupRecord(new BackupRunResult("failed-1", "2026-03-01 00:00:00", "2026-03-01 00:00:01", FAILED, + List.of(), null, "boom")); + assertEquals(java.time.LocalDateTime.of(2026, 1, 1, 0, 0).atZone(java.time.ZoneId.systemDefault()).toInstant(), + db.backups.fetchLastSuccessfulStartTime().orElseThrow()); + + db.backups.addNewBackupRecord(new BackupRunResult("partial-1", "2026-02-01 00:00:00", "2026-02-01 00:00:01", PARTIAL, + List.of(), null, null)); + assertEquals(java.time.LocalDateTime.of(2026, 2, 1, 0, 0).atZone(java.time.ZoneId.systemDefault()).toInstant(), + db.backups.fetchLastSuccessfulStartTime().orElseThrow()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java new file mode 100644 index 0000000..e43157a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java @@ -0,0 +1,75 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; + +abstract class DatabaseTestBase { + + @TempDir + Path tempDir; + + MediaGarrdProperties properties; + TestDatabase db; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("nested/mediagarrd.db").toString()); + db = new TestDatabase(properties); + } + + Path databaseFile() { + return Path.of(properties.getDatabasePath()); + } + + List quarantinedContents() throws IOException { + try (var files = Files.list(databaseFile().getParent())) { + return files + .filter(file -> file.getFileName().toString().startsWith("mediagarrd.db.corrupt-")) + .map(file -> { + try { + return Files.readString(file); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) + .toList(); + } + } + + Connection rawConnection() throws SQLException { + return DriverManager.getConnection("jdbc:sqlite:" + properties.getDatabasePath()); + } + + int count(String table) throws SQLException { + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM " + table)) { + return rs.getInt(1); + } + } + + static BackupRunResult backupRun(String id, String startTime, BackupServiceResult... services) { + BackupArchive archive = new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, Instant.parse("2026-01-01T00:00:00Z")); + return new BackupRunResult(id, startTime, startTime, COMPLETED, List.of(services), archive, null); + } + + static BackupServiceResult serviceResult(String name, String status, String error) { + return new BackupServiceResult(null, status, "2026-01-01 00:00:00", "2026-01-01 00:00:01", name, error); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java new file mode 100644 index 0000000..a1f5d58 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java @@ -0,0 +1,58 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; + +class PairedClientRepositoryTest extends DatabaseTestBase { + + @Test + void pairedClientsTableIsAddedToAnExistingDatabase() throws Exception { + db = null; + Files.delete(Path.of(properties.getDatabasePath())); + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + statement.execute("PRAGMA user_version = 2"); + } + + TestDatabase upgraded = new TestDatabase(properties); + + assertEquals(0, upgraded.pairedClients.countPairedClients()); + upgraded.pairedClients.addPairedClient("c1", "Laptop", "hash-1", Instant.parse("2026-11-19T10:00:00Z")); + assertEquals("Laptop", upgraded.pairedClients.fetchPairedClientByTokenHash("hash-1").orElseThrow().name()); + assertTrue(upgraded.pairedClients.fetchPairedClientByTokenHash("other").isEmpty()); + } + + @Test + void pairedClientsCanBeTouchedListedAndRemoved() { + Instant created = Instant.parse("2026-11-19T10:00:00Z"); + db.pairedClients.addPairedClient("c1", "Laptop", "hash-1", created); + db.pairedClients.addPairedClient("c2", "Phone", "hash-2", created.plusSeconds(5)); + + db.pairedClients.touchPairedClient("c2", created.plusSeconds(60)); + + var clients = db.pairedClients.fetchPairedClients(); + assertEquals(List.of("c1", "c2"), clients.stream().map(c -> c.id()).toList()); + assertNull(clients.get(0).lastUsedAt()); + assertEquals(created.plusSeconds(60), clients.get(1).lastUsedAt()); + assertTrue(db.pairedClients.removePairedClient("c1")); + assertFalse(db.pairedClients.removePairedClient("c1")); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void tokenHashesAreUnique() { + db.pairedClients.addPairedClient("c1", "Laptop", "hash-1", Instant.now()); + + assertThrows(IllegalStateException.class, () -> db.pairedClients.addPairedClient("c2", "Phone", "hash-1", Instant.now())); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java new file mode 100644 index 0000000..740cba4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java @@ -0,0 +1,66 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class ServiceRepositoryTest extends DatabaseTestBase { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @Test + void storesAndFetchesServicesWithPathOrderPreserved() { + assertEquals(List.of(), db.services.fetchServices()); + + db.services.addService(RADARR); + + assertEquals(Optional.of(RADARR), db.services.fetchService("radarr")); + assertEquals(Optional.of(RADARR), db.services.fetchService("RADARR")); + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void listsServicesSortedByNameIgnoringCase() { + db.services.addService(new ServiceDefinition("sonarr", List.of("/a"))); + db.services.addService(new ServiceDefinition("Jellyfin", List.of("/b"))); + db.services.addService(new ServiceDefinition("radarr", List.of("/c"))); + + assertEquals(List.of("Jellyfin", "radarr", "sonarr"), db.services.fetchServices().stream().map(ServiceDefinition::name).toList()); + } + + @Test + void rejectsDuplicateServiceNamesIgnoringCase() { + db.services.addService(RADARR); + + assertThrows(IllegalStateException.class, () -> db.services.addService(new ServiceDefinition("Radarr", List.of("/other")))); + } + + @Test + void updatesServiceNameAndPaths() { + db.services.addService(RADARR); + ServiceDefinition renamed = new ServiceDefinition("radarr-4k", List.of("/srv/radarr-4k")); + + assertTrue(db.services.updateService("radarr", renamed)); + + assertTrue(db.services.fetchService("radarr").isEmpty()); + assertEquals(Optional.of(renamed), db.services.fetchService("radarr-4k")); + assertFalse(db.services.updateService("missing", renamed)); + } + + @Test + void removesService() { + db.services.addService(RADARR); + + assertTrue(db.services.removeService("radarr")); + assertFalse(db.services.removeService("radarr")); + assertEquals(List.of(), db.services.fetchServices()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java new file mode 100644 index 0000000..625240d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java @@ -0,0 +1,21 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +class SettingsRepositoryTest extends DatabaseTestBase { + + @Test + void savesAndOverwritesSettings() { + assertTrue(db.settings.fetchSetting("backup_root").isEmpty()); + + db.settings.saveSetting("backup_root", "/first"); + db.settings.saveSetting("backup_root", "/second"); + + assertEquals(Optional.of("/second"), db.settings.fetchSetting("backup_root")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java new file mode 100644 index 0000000..bc2323a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java @@ -0,0 +1,371 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +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.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class SqliteDatabaseTest extends DatabaseTestBase { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @Test + void createsDatabaseFileAndParentDirectories() { + assertTrue(Files.isRegularFile(tempDir.resolve("nested/mediagarrd.db"))); + assertTrue(db.database.verifyDatabaseIntegrity()); + } + + @Test + void migrationRemovesOrphanedServiceRows() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + new TestDatabase(properties); + + assertEquals(0, count("backup_services")); + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("PRAGMA user_version")) { + assertEquals(2, rs.getInt(1)); + } + } + + @Test + void persistsDataAcrossInstances() { + db.services.addService(RADARR); + db.settings.saveSetting("backup_root", "/backups"); + + TestDatabase reopened = new TestDatabase(properties); + + assertEquals(List.of(RADARR), reopened.services.fetchServices()); + assertEquals(Optional.of("/backups"), reopened.settings.fetchSetting("backup_root")); + } + + @Test + void failsLoudlyWhenDatabaseIsUnusable() { + properties.setDatabasePath(tempDir.toString()); + TestDatabase broken = new TestDatabase(properties); + + assertFalse(broken.database.verifyDatabaseIntegrity()); + assertThrows(IllegalStateException.class, broken.services::fetchServices); + assertThrows(IllegalStateException.class, () -> broken.services.addService(RADARR)); + assertThrows(IllegalStateException.class, () -> broken.settings.fetchSetting("backup_root")); + } + + @Test + void verifiesOnlyOnceWhileTheSchemaIsUnchanged() { + AtomicInteger verifications = new AtomicInteger(); + TestDatabase counted = new TestDatabase(new SqliteDatabase(properties) { + @Override + protected synchronized boolean verifyDatabaseIntegrity() { + verifications.incrementAndGet(); + return super.verifyDatabaseIntegrity(); + } + }); + + counted.services.addService(RADARR); + counted.services.fetchServices(); + counted.settings.fetchSetting("backup_root"); + + assertEquals(1, verifications.get()); + } + + @Test + void rebuildsWhenTheDatabaseFileIsDeleted() throws Exception { + db.services.addService(RADARR); + + Files.delete(databaseFile()); + + assertEquals(List.of(), db.services.fetchServices()); + db.services.addService(RADARR); + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void rebuildsWhenTheDatabaseDirectoryIsDeleted() throws Exception { + Files.delete(databaseFile()); + Files.delete(databaseFile().getParent()); + + db.settings.saveSetting("backup_root", "/backups"); + + assertEquals(Optional.of("/backups"), db.settings.fetchSetting("backup_root")); + } + + @Test + void rebuildsWhenATableIsDropped() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("DROP TABLE services"); + } + + db.services.addService(RADARR); + + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void migratesWhenAnOlderDatabaseIsSwappedIn() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + db.services.fetchServices(); + + assertEquals(0, count("backup_services")); + } + + @Test + void movesACorruptDatabaseAsideOnStartup() throws Exception { + Files.writeString(databaseFile(), "x".repeat(4096)); + + TestDatabase recovered = new TestDatabase(properties); + + recovered.services.addService(RADARR); + assertEquals(List.of(RADARR), recovered.services.fetchServices()); + assertEquals(List.of("x".repeat(4096)), quarantinedContents()); + } + + @Test + void movesACorruptDatabaseAsideWhileRunning() throws Exception { + db.services.addService(RADARR); + Files.writeString(databaseFile(), "x".repeat(4096)); + + assertEquals(List.of(), db.services.fetchServices()); + assertEquals(1, quarantinedContents().size()); + } + + @Test + void notifiesListenersOnceAfterARuntimeRebuildFromAnotherThread() throws Exception { + List threads = new java.util.concurrent.CopyOnWriteArrayList<>(); + CountDownLatch notified = new CountDownLatch(1); + db.database.addRebuildListener(() -> { + threads.add(Thread.currentThread().getName()); + notified.countDown(); + }); + Files.writeString(databaseFile(), "x".repeat(4096)); + + db.services.fetchServices(); + db.services.fetchServices(); + + assertTrue(notified.await(10, TimeUnit.SECONDS)); + assertEquals(1, threads.size()); + assertFalse(threads.contains(Thread.currentThread().getName())); + } + + @Test + void doesNotNotifyListenersForAMigrationOnly() throws Exception { + CountDownLatch notified = new CountDownLatch(1); + db.database.addRebuildListener(notified::countDown); + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("DROP TABLE services"); + } + + db.services.fetchServices(); + + assertFalse(notified.await(300, TimeUnit.MILLISECONDS)); + } + + @Test + void snapshotIsAValidCopyWithTheSameRowsAndVersion() throws Exception { + db.services.addService(RADARR); + db.settings.saveSetting("backup_root", "/backups"); + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + Path snapshot = tempDir.resolve("snapshot.db"); + + db.database.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.services.fetchServices()); + } + + @Test + void snapshotHandlesQuotesInTheTargetPath() throws Exception { + Path snapshot = Files.createDirectories(tempDir.resolve("it's here")).resolve("snapshot.db"); + + db.database.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.database.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.database.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.database.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); + TestDatabase paused = new TestDatabase(new SqliteDatabase(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.settings.saveSetting("backup_root", "/before"); + + CompletableFuture snapshot = CompletableFuture.runAsync(() -> { + try { + paused.database.snapshotTo(tempDir.resolve("snapshot.db")); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + assertTrue(snapshotting.await(5, TimeUnit.SECONDS)); + + CompletableFuture write = CompletableFuture.runAsync(() -> paused.settings.saveSetting("backup_root", "/during")); + CompletableFuture delete = CompletableFuture.runAsync(() -> paused.backups.deleteBackupRecordById("none")); + CompletableFuture insert = CompletableFuture.runAsync(() -> + paused.backups.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.settings.fetchSetting("backup_root")); + assertTrue(paused.backups.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.database.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.settings.saveSetting("backup_root", "/" + n); + db.services.fetchServices(); + db.database.verifyDatabaseIntegrity(); + } + })); + } + CompletableFuture.allOf(work.toArray(CompletableFuture[]::new)).get(); + }); + } + + @Test + void theDatabaseFileIsOwnerOnlyAndItsNewDirectoryIsPrivate() throws IOException { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(databaseFile()))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(databaseFile().getParent()))); + } + + @Test + void anExistingDatabaseFileIsTightenedButItsDirectoryIsLeftAlone() throws IOException { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + Path directory = Files.createDirectories(tempDir.resolve("existing")); + Files.setPosixFilePermissions(directory, java.nio.file.attribute.PosixFilePermissions.fromString("rwxr-xr-x")); + MediaGarrdPropertiesHolder.open(directory.resolve("old.db")); + Files.setPosixFilePermissions(directory.resolve("old.db"), java.nio.file.attribute.PosixFilePermissions.fromString("rw-r--r--")); + + MediaGarrdPropertiesHolder.open(directory.resolve("old.db")); + + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(directory.resolve("old.db")))); + assertEquals("rwxr-xr-x", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(directory))); + } + + @Test + void aFailedTransactionIsRolledBackAndRethrown() throws Exception { + try (var connection = rawConnection()) { + connection.setAutoCommit(false); + assertThrows(SQLException.class, () -> db.database.inTransaction(connection, c -> { + c.createStatement().executeUpdate("INSERT INTO settings (key, value) VALUES ('k', 'v')"); + c.createStatement().executeUpdate("INSERT INTO no_such_table VALUES (1)"); + return null; + })); + } + assertEquals(0, count("settings")); + } + + private static final class MediaGarrdPropertiesHolder { + static void open(Path file) { + var properties = new wellatleastitried.mediagarrdServer.MediaGarrdProperties(); + properties.setDatabasePath(file.toString()); + new TestDatabase(properties); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java new file mode 100644 index 0000000..7eae601 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.repository; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +public final class TestDatabase { + + public final SqliteDatabase database; + public final BackupRecordRepository backups; + public final ServiceRepository services; + public final SettingsRepository settings; + public final PairedClientRepository pairedClients; + + public TestDatabase(MediaGarrdProperties properties) { + this(new SqliteDatabase(properties)); + } + + public TestDatabase(SqliteDatabase database) { + this.database = database; + this.backups = new BackupRecordRepository(database); + this.services = new ServiceRepository(database); + this.settings = new SettingsRepository(database); + this.pairedClients = new PairedClientRepository(database); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java index c4fac32..c88ed6f 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java @@ -49,8 +49,10 @@ private Path archive() throws Exception { Item symlink = link("data/latest", TarConstants.LF_SYMLINK, "id_rsa"); symlink.entry().setModTime(new Date(MTIME)); Item hardLink = link("data/id_rsa.bak", TarConstants.LF_LINK, "data/id_rsa"); + Item movie = file("data/movie.mkv", "stored ".repeat(1000)); + movie.entry().setModTime(new Date(MTIME)); Path part = dir.resolve("0.part"); - ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink), "/srv/data", part, new ZipCompression(1)); + ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink, movie), "/srv/data", part, new ZipCompression(1)); return ArchiveTestSupport.merge(dir, part); } @@ -97,6 +99,6 @@ void listingsShowNumericOwnersFromTheLocalHeaders() throws Exception { @Test void everyReaderAcceptsTheArchive() throws Exception { - ZipPartWriterTest.verifyWithTools(archive(), 6); + ZipPartWriterTest.verifyWithTools(archive(), 7); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 1fc30cc..0fc098b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -17,6 +17,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.sql.DriverManager; +import java.time.Instant; import java.util.List; import java.util.Map; @@ -34,6 +35,7 @@ import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; class BackupArchiveServiceTest { @@ -42,7 +44,7 @@ class BackupArchiveServiceTest { Path tempDir; private MediaGarrdProperties properties; - private DatabaseService db; + private TestDatabase db; private BackupArchiveService service; @BeforeEach @@ -51,8 +53,8 @@ void setUp() { properties.setBackupRoot(tempDir.resolve("backups").toString()); properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); properties.setRetentionCount(2); - db = new DatabaseService(properties); - service = new BackupArchiveService(properties, db); + db = new TestDatabase(properties); + service = new BackupArchiveService(properties, db.settings, db.backups); } @Test @@ -111,23 +113,23 @@ void aDuplicateNameAcrossPartsFailsTheMergeAndLeavesNoArchive() throws Exception assertThrows(IllegalStateException.class, () -> service.createArchive(run)); try (var files = Files.list(service.rootDirectory())) { - assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); } assertFalse(Files.exists(run.resolve("merge-names.idx"))); } @Test void partsAreWrittenInSortedPathOrderWithTheSnapshotFirst() throws Exception { - db.saveSetting("backup_root", "/marker"); + db.settings.saveSetting("backup_root", "/marker"); DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); Path run = service.createRunDirectory(); Item restricted = dir("a/"); restricted.entry().setMode(040700); part(run, "second", 0, "/srv/b", tar(dir("b/"), file("b/x", "1"))); part(run, "first", 1, "/srv/a", tar(restricted, dir("a/c/"), file("a/c/x", "1"), file("a/y", "2"))); part(run, "first", 0, "/srv/a0", tar(file("a0", "0"))); - assertEquals(COMPLETED, new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run).status()); + assertEquals(COMPLETED, new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run).status()); BackupArchive archive = service.createArchive(run); @@ -155,7 +157,7 @@ void failedMergeLeavesNoArchiveBehind() throws Exception { assertThrows(IllegalStateException.class, () -> service.createArchive(run)); try (var files = Files.list(service.rootDirectory())) { - assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); } } @@ -164,10 +166,8 @@ void retentionKeepsNewestArchivesAndIgnoresUnrelatedZips() throws Exception { Path unrelated = Files.createDirectories(service.rootDirectory()).resolve("keep-me.zip"); Files.writeString(unrelated, "not a backup"); - for (int i = 0; i < 3; i++) { - createArchive(); - Thread.sleep(10); - } + seedArchives(2); + createArchive(); assertEquals(2, service.listArchives().size()); assertTrue(Files.exists(unrelated)); @@ -181,19 +181,16 @@ void deletesArchiveAndItsRecordById() throws Exception { assertFalse(service.deleteById(archive.id())); assertTrue(service.listArchives().isEmpty()); - assertTrue(db.fetchBackupById(archive.id()).isEmpty()); + assertTrue(db.backups.fetchBackupById(archive.id()).isEmpty()); } @Test void retentionDeletesRecordsOfRemovedArchives() throws Exception { - BackupArchive oldest = createArchive(); - Thread.sleep(10); - createArchive(); - Thread.sleep(10); + BackupArchive oldest = seedArchives(2).get(0); BackupArchive newest = createArchive(); - assertTrue(db.fetchBackupById(oldest.id()).isEmpty()); - assertTrue(db.fetchBackupById(newest.id()).isPresent()); + assertTrue(db.backups.fetchBackupById(oldest.id()).isEmpty()); + assertTrue(db.backups.fetchBackupById(newest.id()).isPresent()); } @Test @@ -204,7 +201,7 @@ void updatesAndPersistsRootDirectory() { assertEquals(newRoot, service.rootDirectory()); assertTrue(Files.isDirectory(newRoot)); - assertEquals(newRoot, new BackupArchiveService(properties, db).rootDirectory()); + assertEquals(newRoot, new BackupArchiveService(properties, db.settings, db.backups).rootDirectory()); } @Test @@ -231,10 +228,7 @@ void rejectsInvalidRootDirectories() throws Exception { @Test void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { - for (int i = 0; i < 2; i++) { - createArchive(); - Thread.sleep(10); - } + seedArchives(2); service.updateSettings(null, 1); @@ -242,7 +236,7 @@ void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { assertEquals(2, service.listArchives().size()); createArchive(); assertEquals(1, service.listArchives().size()); - assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test @@ -250,16 +244,16 @@ void usesPropertyRetentionUntilOneIsSaved() { assertEquals(2, service.retentionCount()); properties.setRetentionCount(0); - assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test void ignoresCorruptStoredRetention() { - db.saveSetting(RETENTION_COUNT_SETTING, "lots"); - assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + db.settings.saveSetting(RETENTION_COUNT_SETTING, "lots"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); - db.saveSetting(RETENTION_COUNT_SETTING, "0"); - assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + db.settings.saveSetting(RETENTION_COUNT_SETTING, "0"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test @@ -268,7 +262,7 @@ void updatesLocationAndRetentionTogether() { service.updateSettings(newRoot.toString(), 5); - BackupArchiveService restarted = new BackupArchiveService(properties, db); + BackupArchiveService restarted = new BackupArchiveService(properties, db.settings, db.backups); assertEquals(newRoot, restarted.rootDirectory()); assertEquals(5, restarted.retentionCount()); } @@ -282,14 +276,14 @@ void rejectsInvalidSettingsWithoutPartialWrites() { assertFalse(Files.exists(tempDir.resolve("never"))); assertEquals(tempDir.resolve("backups"), service.rootDirectory()); assertEquals(2, service.retentionCount()); - assertTrue(db.fetchSetting(RETENTION_COUNT_SETTING).isEmpty()); + assertTrue(db.settings.fetchSetting(RETENTION_COUNT_SETTING).isEmpty()); } @Test void startupCleanupRemovesStaleArtifacts() throws Exception { Path run = service.createRunDirectory(); Files.writeString(run.resolve("partial.txt"), "x"); - Path tempZip = Files.writeString(service.rootDirectory().resolve("old" + BackupArchiveService.ARCHIVE_SUFFIX + ".tmp"), "x"); + Path tempZip = Files.writeString(service.rootDirectory().resolve("old" + BackupArchiveService.TEMP_SUFFIX), "x"); service.cleanupStaleArtifactsOnStartup(); @@ -297,12 +291,45 @@ void startupCleanupRemovesStaleArtifacts() throws Exception { assertFalse(Files.exists(tempZip)); } + @Test + void startupCleanupLeavesTheUsersOwnFilesAndFoldersAlone() throws Exception { + Path root = service.rootDirectory(); + Path ownRuns = Files.createDirectories(root.resolve("runs").resolve("mine")); + Path ownFile = Files.writeString(ownRuns.resolve("keep.txt"), "x"); + Path unrelatedTemp = Files.writeString(root.resolve("notes.zip.tmp"), "x"); + Path nonMediaGarrdTemp = Files.writeString(root.resolve("photos.zip.tmp"), "x"); + + service.cleanupStaleArtifactsOnStartup(); + + assertTrue(Files.exists(ownFile)); + assertTrue(Files.exists(unrelatedTemp)); + assertTrue(Files.exists(nonMediaGarrdTemp)); + } + + @Test + void runDirectoriesLiveInAMediaGarrdSpecificFolder() { + Path run = service.createRunDirectory(); + + assertEquals(service.rootDirectory().resolve(BackupArchiveService.RUNS_DIRECTORY), run.getParent()); + } + + @Test + void syncingAFileSucceedsAndSyncingAMissingDirectoryIsIgnored() throws Exception { + Path file = Files.writeString(tempDir.resolve("sync.bin"), "x"); + + BackupArchiveService.syncFile(file); + BackupArchiveService.syncDirectory(tempDir); + BackupArchiveService.syncDirectory(tempDir.resolve("missing")); + + assertTrue(Files.exists(file)); + } + @Test void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throws Exception { - db.saveSetting("backup_root", "/marker"); + db.settings.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)); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/" + entry)); Path run = service.createRunDirectory(); var excluded = DatabaseSnapshotService.reservedNames(Path.of("/" + entry)); Path directory = Files.createDirectories(run.resolve("Mediagarrd")); @@ -314,7 +341,7 @@ void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throw file("db/mediagarrd.db-shm", "shm"), file("db/notes.txt", "keep")), "/srv/mediagarrd/db", directory.resolve("0.part"), new ZipCompression(1), excluded, java.util.Set.of()); - var snapshot = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); + var snapshot = new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run); BackupArchive archive = service.createArchive(run); assertEquals(COMPLETED, snapshot.status()); @@ -336,15 +363,15 @@ void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throw @Test void aLiveDatabaseCopyThatSlippedPastTheExclusionFailsTheMerge() throws Exception { DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); Path run = service.createRunDirectory(); part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar(dir("db/"), file("db/mediagarrd.db-wal", "wal"))); - new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)).snapshot(run); + new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run); assertThrows(IllegalStateException.class, () -> service.createArchive(run)); try (var files = Files.list(service.rootDirectory())) { - assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); } } @@ -411,16 +438,6 @@ void mergesPartsWithMixedStoredAndDeflatedEntries() throws Exception { assertEquals(contents(archive.path()), streamed); } - @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 partWith(Path run, String service, int index, String hostPath, java.io.InputStream tar, int level) throws Exception { Path directory = Files.createDirectories(run.resolve(service)); ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(level)); @@ -431,12 +448,126 @@ private static void part(Path run, String service, int index, String hostPath, j ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(1)); } + private List seedArchives(int count) throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + List seeded = new java.util.ArrayList<>(); + for (int i = 1; i <= count; i++) { + String fileName = String.format("202101%02d", i) + "-000000-000-media-backup.zip"; + Path path = Files.writeString(root.resolve(fileName), "seeded " + i); + Files.setLastModifiedTime(path, java.nio.file.attribute.FileTime.fromMillis(10_000L * i)); + BackupArchive archive = new BackupArchive(fileName.replace(".zip", ""), fileName, path, Files.size(path), Instant.ofEpochMilli(10_000L * i)); + db.backups.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + seeded.add(archive); + } + return seeded; + } + private BackupArchive createArchive() throws Exception { Path run = service.createRunDirectory(); part(run, "marker", 0, "/srv/marker", tar(file("marker", "ok"))); BackupArchive archive = service.createArchive(run); service.removeRunDirectory(run); - db.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + db.backups.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); return archive; } + + @Test + void retentionKeepsOldArchivesThatHaveNoRecord() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path unrecorded = root.resolve("20200101-000000-000-media-backup.zip"); + Files.writeString(unrecorded, "left by an earlier install"); + Files.setLastModifiedTime(unrecorded, java.nio.file.attribute.FileTime.fromMillis(1_000)); + + seedArchives(3); + createArchive(); + + assertTrue(Files.exists(unrecorded)); + assertTrue(service.listArchives().stream().anyMatch(archive -> archive.path().equals(unrecorded))); + assertEquals(3, service.listArchives().size()); + } + + @Test + void ordersAndReportsArchivesByTheTimestampInTheirNameNotTheirModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path newest = archiveFile(root, "20260105-120000-123-media-backup.zip", 1_000); + Path middle = archiveFile(root, "20260103-000000-000-media-backup.zip", 3_000_000_000L); + Path oldest = archiveFile(root, "20260101-000000-000-media-backup.zip", 2_000_000_000L); + + List archives = service.listArchives(); + + assertEquals(List.of(newest, middle, oldest), archives.stream().map(BackupArchive::path).toList()); + assertEquals(Instant.parse("2026-01-05T12:00:00.123Z"), archives.get(0).createdAt()); + assertEquals(newest, service.latest().orElseThrow().path()); + } + + @Test + void retentionPrunesByTheTimestampInTheNameNotTheModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path first = archiveFile(root, "20210101-000000-000-media-backup.zip", 9_000_000_000L); + Path second = archiveFile(root, "20210102-000000-000-media-backup.zip", 8_000_000_000L); + Path third = archiveFile(root, "20210103-000000-000-media-backup.zip", 7_000_000_000L); + for (Path path : List.of(first, second, third)) { + String id = path.getFileName().toString().replace(".zip", ""); + BackupArchive archive = new BackupArchive(id, path.getFileName().toString(), path, 1, Instant.EPOCH); + db.backups.addNewBackupRecord(new BackupRunResult(id, "start", "end", COMPLETED, List.of(), archive, null)); + } + + BackupArchive created = createArchive(); + + assertFalse(Files.exists(first)); + assertFalse(Files.exists(second)); + assertTrue(Files.exists(third)); + assertTrue(Files.exists(created.path())); + } + + @Test + void anArchiveWhoseNameHasNoTimestampFallsBackToItsModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path odd = archiveFile(root, "manual-media-backup.zip", 1_700_000_000_000L); + Path named = archiveFile(root, "20200101-000000-000-media-backup.zip", 5); + + List archives = service.listArchives(); + + assertEquals(List.of(odd, named), archives.stream().map(BackupArchive::path).toList()); + assertEquals(Instant.ofEpochMilli(1_700_000_000_000L), archives.get(0).createdAt()); + } + + private static Path archiveFile(Path root, String name, long modifiedMillis) throws Exception { + Path path = Files.writeString(root.resolve(name), "x"); + Files.setLastModifiedTime(path, java.nio.file.attribute.FileTime.fromMillis(modifiedMillis)); + return path; + } + + @Test + void archiveIdsDropOnlyTheTrailingZipExtension() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Files.writeString(root.resolve("a.zip-media-backup.zip"), "x"); + + assertEquals("a.zip-media-backup", service.listArchives().get(0).id()); + } + + @Test + void newDirectoriesAndArchivesAreOwnerOnlyButExistingOnesAreLeftAlone() throws Exception { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + Path existing = Files.createDirectories(tempDir.resolve("existing")); + Files.setPosixFilePermissions(existing, java.nio.file.attribute.PosixFilePermissions.fromString("rwxr-xr-x")); + service.updateRootDirectory(existing.toString()); + + BackupArchive archive = createArchive(); + + assertEquals("rwxr-xr-x", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(existing))); + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(archive.path()))); + Path created = tempDir.resolve("fresh/backups"); + service.updateRootDirectory(created.toString()); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(created))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(service.createRunDirectory()))); + } + + @Test + void rejectsOverlongAndControlCharacterLocations() { + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/" + "a".repeat(BackupArchiveService.MAX_LOCATION_LENGTH))); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/tmp/x\ninjected")); + IllegalArgumentException nul = assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/tmp/x\0y")); + assertEquals("Backup location must not contain control characters", nul.getMessage()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java index 41fa227..b92dd93 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java @@ -42,6 +42,8 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; @Timeout(60) @@ -56,10 +58,10 @@ class BackupCopyRoundsTest { private final DockerService docker = mock(DockerService.class); private final BackupArchiveService archives = mock(BackupArchiveService.class); private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); - private final DatabaseService db = mock(DatabaseService.class); + private final ServiceRepository serviceRepository = mock(ServiceRepository.class); private final Map> sources = new HashMap<>(); private final BackupOrchestratorService orchestrator = new BackupOrchestratorService( - new ServiceBackupRunner(docker, new ZipCompression(1)), archives, mock(BackupScheduleService.class), snapshots, db, mock(RunStatusBroadcaster.class)); + new ServiceBackupRunner(docker, new ZipCompression(1)), archives, mock(BackupScheduleService.class), snapshots, serviceRepository, mock(BackupRecordRepository.class), new BackupRunLifecycle(mock(RunStatusBroadcaster.class)), mock(WebhookService.class)); @BeforeEach void setUp() throws Exception { @@ -100,7 +102,7 @@ private void serve(String path, Item... items) { } private BackupRunResult runBackup(ServiceDefinition... services) { - when(db.fetchServices()).thenReturn(List.of(services)); + when(serviceRepository.fetchServices()).thenReturn(List.of(services)); return orchestrator.runBackup(); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index 145ad75..3d3b7fb 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -38,6 +38,9 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; @Timeout(30) class BackupOrchestratorServiceTest { @@ -51,10 +54,13 @@ class BackupOrchestratorServiceTest { private final ServiceBackupRunner runner = mock(ServiceBackupRunner.class); private final BackupArchiveService archives = mock(BackupArchiveService.class); private final BackupScheduleService schedule = mock(BackupScheduleService.class); - private final DatabaseService db = mock(DatabaseService.class); + private final ServiceRepository services = mock(ServiceRepository.class); + private final BackupRecordRepository backups = mock(BackupRecordRepository.class); private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); - private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db, broadcaster); + private final BackupRunLifecycle lifecycle = new BackupRunLifecycle(broadcaster); + private final WebhookService webhook = mock(WebhookService.class); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, services, backups, lifecycle, webhook); @BeforeEach void setUp() { @@ -70,26 +76,28 @@ void tearDown() { @Test void refusesToRunWithoutServices() { - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + assertThrows(RunRejectedException.class, orchestrator::runBackup); verify(archives, never()).createRunDirectory(); assertFalse(orchestrator.isRunning()); verify(broadcaster, never()).publishStarted(any()); verify(broadcaster, never()).publishFinished(any(), any(), any()); verify(schedule, never()).deferNextRun(); + verify(webhook, never()).notifyRun(any()); + verify(webhook, never()).notifyFailure(any()); } @Test void aRejectedManualRunLeavesTheRealScheduleUntouched() { MediaGarrdProperties properties = new MediaGarrdProperties(); - BackupScheduleService realSchedule = new BackupScheduleService(properties, db); - BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, db, broadcaster); - when(db.fetchServices()).thenReturn(List.of()); + BackupScheduleService realSchedule = new BackupScheduleService(properties, mock(SettingsRepository.class), mock(BackupRecordRepository.class), mock(SetupService.class)); + BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, services, backups, new BackupRunLifecycle(broadcaster), webhook); + when(services.fetchServices()).thenReturn(List.of()); Instant before = realSchedule.getNextRun(); - assertThrows(BackupOrchestratorService.RunRejectedException.class, manual::runBackup); + assertThrows(RunRejectedException.class, manual::runBackup); assertEquals(before, realSchedule.getNextRun()); manual.shutdownRunnerExecutor(); @@ -98,7 +106,7 @@ void aRejectedManualRunLeavesTheRealScheduleUntouched() { @Test void aScheduledRunWithoutServicesDefersTheNextCheck() { when(schedule.dueNow()).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); orchestrator.scheduledRun(); @@ -110,7 +118,7 @@ void aScheduledRunWithoutServicesDefersTheNextCheck() { void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -120,13 +128,179 @@ void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.RunRejectedException.class, () -> orchestrator.runBackup(true)); + assertThrows(RunRejectedException.class, () -> orchestrator.runBackup(true)); verify(schedule, never()).deferNextRun(); release.countDown(); manual.get(5, TimeUnit.SECONDS); } + @Test + void aDueScheduledRunWithServicesRunsABackup() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + + orchestrator.scheduledRun(); + + verify(schedule).markRunStarted(); + verify(archives).createArchive(RUN_DIR); + verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + } + + @Test + void aScheduledCheckThatIsNotDueDoesNothing() { + when(schedule.dueNow()).thenReturn(false); + + orchestrator.scheduledRun(); + + verify(services, never()).fetchServices(); + verify(broadcaster, never()).publishStarted(any()); + verify(schedule, never()).markRunStarted(); + verify(schedule, never()).deferNextRun(); + } + + @Test + void aScheduledCheckDuringARunSkipsWithoutLookingAtTheSchedule() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + orchestrator.scheduledRun(); + + verify(schedule, never()).dueNow(); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + } + + @Test + void aRunRejectedBecauseOneIsInProgressSendsNoWebhook() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertThrows(RunRejectedException.class, orchestrator::runBackup); + + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + verify(webhook, never()).notifyFailure(any()); + verify(webhook, org.mockito.Mockito.times(1)).notifyRun(any()); + } + + @Test + void aFailureBeforeTheRunStartsSendsNoWebhook() { + when(services.fetchServices()).thenThrow(new IllegalStateException("database locked")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(webhook, never()).notifyFailure(any()); + verify(webhook, never()).notifyRun(any()); + } + + @Test + void aFailureAfterTheRunStartsSendsAFailedWebhookAndRethrows() { + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertEquals("disk full", e.getMessage()); + verify(webhook).notifyFailure("disk full"); + verify(webhook, never()).notifyRun(any()); + } + + @Test + void aScheduledRunThatEndsPartialSendsAWebhook() { + when(schedule.dueNow()).thenReturn(true); + givenResults(COMPLETED, FAILED); + + orchestrator.scheduledRun(); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(PARTIAL, sent.getValue().status()); + } + + @Test + void aCompletedRunStillHandsTheResultToTheWebhookService() { + givenResults(COMPLETED, COMPLETED); + + BackupRunResult result = orchestrator.runBackup(); + + verify(webhook).notifyRun(result); + verify(webhook, never()).notifyFailure(any()); + } + + @Test + void aRunWhereEveryServiceFailsSendsOneFailedWebhook() { + givenResults(FAILED, FAILED); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(FAILED, sent.getValue().status()); + assertNull(sent.getValue().archive()); + verify(webhook, never()).notifyFailure(any()); + } + + @Test + void aFailedRecordWithAnArchiveSendsAFailedWebhook() { + givenResults(PARTIAL, FAILED); + + orchestrator.runBackup(); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(FAILED, sent.getValue().status()); + assertEquals(ARCHIVE, sent.getValue().archive()); + } + + @Test + void aScheduledRunThatFailsDoesNotStopTheScheduler() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + + verify(broadcaster, org.mockito.Mockito.times(2)).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aScheduledRunWhoseArchivingFailsDoesNotStopTheScheduler() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + + verify(archives, org.mockito.Mockito.times(2)).createArchive(RUN_DIR); + verify(broadcaster, org.mockito.Mockito.times(2)).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + @Test void changingServicesReleasesTheDeferral() { orchestrator.servicesChanged(); @@ -145,7 +319,7 @@ void completedWhenEveryServiceSucceeds() { assertEquals(List.of("radarr", "sonarr", SNAPSHOT), result.serviceNames()); result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); verify(schedule).markRunStarted(); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); verify(archives).removeRunDirectory(RUN_DIR); } @@ -157,6 +331,7 @@ void partialWhenSomeServicesFail() { assertEquals(PARTIAL, result.status()); assertEquals("sonarr: boom", result.errorMessage()); + verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); } @Test @@ -170,7 +345,7 @@ void partialWhenOnlyTheDatabaseSnapshotFails() { assertEquals(SNAPSHOT + ": boom", result.errorMessage()); assertEquals(ARCHIVE, result.archive()); result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); } @Test @@ -194,7 +369,7 @@ void aThrowingSnapshotStillProducesAPartialArchive() { assertEquals(PARTIAL, result.status()); assertEquals(SNAPSHOT + ": docker down", result.errorMessage()); assertEquals(ARCHIVE, result.archive()); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); } @Test @@ -228,17 +403,18 @@ void skipsArchiveWhenEveryServiceFails() { assertFalse(orchestrator.isRunning()); ArgumentCaptor recorded = ArgumentCaptor.forClass(BackupRunResult.class); - verify(db).addNewBackupRecord(recorded.capture()); + verify(backups).addNewBackupRecord(recorded.capture()); BackupRunResult run = recorded.getValue(); assertEquals(FAILED, run.status()); assertNull(run.archive()); assertEquals("radarr: boom\nsonarr: boom", run.errorMessage()); run.serviceResults().forEach(r -> assertEquals(run.runId(), r.runId())); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); } @Test void runnerExceptionsBecomeFailedResults() { - when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR, SONARR)); when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, COMPLETED)); @@ -256,15 +432,16 @@ void cleansUpWhenArchivingFails() { assertThrows(IllegalStateException.class, orchestrator::runBackup); verify(archives).removeRunDirectory(RUN_DIR); - verify(db, never()).addNewBackupRecord(any()); + verify(backups, never()).addNewBackupRecord(any()); assertFalse(orchestrator.isRunning()); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); } @Test void rejectsConcurrentRuns() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -275,23 +452,18 @@ void rejectsConcurrentRuns() throws Exception { assertTrue(started.await(5, TimeUnit.SECONDS)); assertTrue(orchestrator.isRunning()); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + assertThrows(RunRejectedException.class, orchestrator::runBackup); release.countDown(); assertEquals(COMPLETED, first.get(5, TimeUnit.SECONDS).status()); assertFalse(orchestrator.isRunning()); } - @Test - void configChangesRunWhileIdle() { - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); - } - @Test void configChangesAreRejectedDuringABackupRun() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -301,11 +473,11 @@ void configChangesAreRejectedDuringABackupRun() throws Exception { CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.BackupInProgressException.class, () -> orchestrator.whileIdle(() -> "changed")); + assertThrows(BackupInProgressException.class, () -> lifecycle.whileIdle(() -> "changed")); release.countDown(); run.get(5, TimeUnit.SECONDS); - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); } @Test @@ -314,7 +486,7 @@ void backupWaitsForInFlightConfigChange() throws Exception { CountDownLatch finishChange = new CountDownLatch(1); givenResults(COMPLETED, COMPLETED); - CompletableFuture change = CompletableFuture.supplyAsync(() -> orchestrator.whileIdle(() -> { + CompletableFuture change = CompletableFuture.supplyAsync(() -> lifecycle.whileIdle(() -> { changing.countDown(); try { finishChange.await(); @@ -328,7 +500,7 @@ void backupWaitsForInFlightConfigChange() throws Exception { CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); Thread.sleep(100); assertFalse(run.isDone()); - verify(db, never()).fetchServices(); + verify(services, never()).fetchServices(); finishChange.countDown(); assertEquals("changed", change.get(5, TimeUnit.SECONDS)); @@ -341,8 +513,8 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { orchestrator.runBackup(); - var order = inOrder(broadcaster, runner, db); - order.verify(db).fetchServices(); + var order = inOrder(broadcaster, runner, services); + order.verify(services).fetchServices(); order.verify(broadcaster).publishStarted(any()); order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), any(), any(), any()); order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); @@ -350,37 +522,9 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); } - @Test - void publishesPartialWhenSomeServicesFail() { - givenResults(COMPLETED, FAILED); - - orchestrator.runBackup(); - - verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); - } - - @Test - void publishesFailedWhenEveryServiceFails() { - givenResults(FAILED, FAILED); - - assertThrows(IllegalStateException.class, orchestrator::runBackup); - - verify(broadcaster).publishFinished(eq(FAILED), any(), any()); - } - - @Test - void publishesFailedWhenArchivingThrows() { - givenResults(COMPLETED, COMPLETED); - when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); - - assertThrows(IllegalStateException.class, orchestrator::runBackup); - - verify(broadcaster).publishFinished(eq(FAILED), any(), any()); - } - @Test void publishesFailedWhenTheRunDirectoryCannotBeCreated() { - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(archives.createRunDirectory()).thenThrow(new IllegalStateException("no space")); assertThrows(IllegalStateException.class, orchestrator::runBackup); @@ -393,7 +537,7 @@ void publishesFailedWhenTheRunDirectoryCannotBeCreated() { @Test void publishesFailedWhenRecordingTheRunThrows() { givenResults(COMPLETED, COMPLETED); - doThrow(new IllegalStateException("db locked")).when(db).addNewBackupRecord(any()); + doThrow(new IllegalStateException("db locked")).when(backups).addNewBackupRecord(any()); assertThrows(IllegalStateException.class, orchestrator::runBackup); @@ -425,7 +569,7 @@ void aFailingCleanupDoesNotStickTheRunningFlag() { assertEquals(COMPLETED, result.status()); assertFalse(orchestrator.isRunning()); verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); assertEquals(COMPLETED, orchestrator.runBackup().status()); } @@ -455,7 +599,7 @@ void aFailingPublishNeverBreaksTheRun() { void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -464,7 +608,7 @@ void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + assertThrows(RunRejectedException.class, orchestrator::runBackup); verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); verify(broadcaster, never()).publishFinished(any(), any(), any()); @@ -503,7 +647,7 @@ void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { } private void givenResults(String radarrStatus, String sonarrStatus) { - when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR, SONARR)); when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, radarrStatus)); when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, sonarrStatus)); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java new file mode 100644 index 0000000..6563931 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java @@ -0,0 +1,128 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import 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.times; +import static org.mockito.Mockito.verify; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; + +class BackupRunLifecycleTest { + + private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); + private final BackupRunLifecycle lifecycle = new BackupRunLifecycle(broadcaster); + private final Instant start = Instant.parse("2026-11-20T10:00:00Z"); + + private static BackupRunResult result(String status) { + return new BackupRunResult("run", "s", "e", status, List.of(), null, null); + } + + @Test + void aStartedRunPublishesStartedThenFinishedWithItsStatus() { + lifecycle.run(start, run -> { + run.markStarted(); + assertTrue(lifecycle.isRunning()); + return result(COMPLETED); + }); + + InOrder order = inOrder(broadcaster); + order.verify(broadcaster).publishStarted(start); + order.verify(broadcaster).publishFinished(eq(COMPLETED), eq(start), any()); + assertFalse(lifecycle.isRunning()); + } + + @Test + void aBodyThatThrowsFinishesAsFailedAndReleasesTheRun() { + assertThrows(IllegalStateException.class, () -> lifecycle.run(start, run -> { + run.markStarted(); + throw new IllegalStateException("boom"); + })); + + verify(broadcaster).publishFinished(eq(FAILED), eq(start), any()); + assertFalse(lifecycle.isRunning()); + assertEquals(COMPLETED, lifecycle.run(start, run -> result(COMPLETED)).status()); + } + + @Test + void aRunThatNeverStartedPublishesNothing() { + assertThrows(RunRejectedException.class, () -> lifecycle.run(start, run -> { + throw new RunRejectedException("No services are configured for backup"); + })); + + verify(broadcaster, never()).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + assertFalse(lifecycle.isRunning()); + } + + @Test + void markingStartedTwicePublishesOneStartedEvent() { + lifecycle.run(start, run -> { + run.markStarted(); + run.markStarted(); + return result(COMPLETED); + }); + + verify(broadcaster, times(1)).publishStarted(start); + } + + @Test + void aSecondRunIsRejectedWhileOneIsRunning() throws Exception { + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture first = CompletableFuture.supplyAsync(() -> lifecycle.run(start, run -> { + inside.countDown(); + await(release); + return result(COMPLETED); + })); + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + assertThrows(RunRejectedException.class, () -> lifecycle.run(start, run -> result(COMPLETED))); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + } + + @Test + void whileIdleIsRefusedWhileARunHoldsTheConfigLockAndWorksAfterwards() throws Exception { + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture running = CompletableFuture.supplyAsync(() -> lifecycle.run(start, run -> { + inside.countDown(); + await(release); + return result(COMPLETED); + })); + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + assertThrows(BackupInProgressException.class, () -> lifecycle.whileIdle(() -> "changed")); + + release.countDown(); + running.get(5, TimeUnit.SECONDS); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); + } + + private static void await(CountDownLatch latch) { + try { + latch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index ba05b43..b364699 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -2,11 +2,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SETUP_COMPLETED_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; import java.nio.file.Path; import java.time.Duration; +import java.time.Instant; +import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -14,6 +23,11 @@ import org.junit.jupiter.api.io.TempDir; import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils; class BackupScheduleServiceTest { @@ -21,87 +35,358 @@ class BackupScheduleServiceTest { Path tempDir; private MediaGarrdProperties properties; - private DatabaseService db; + private TestDatabase db; + private MutableClock clock; + private SetupService setup; @BeforeEach void setUp() { properties = new MediaGarrdProperties(); properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); - db = new DatabaseService(properties); + db = new TestDatabase(properties); + clock = new MutableClock(); + setup = newSetup(); + } + + private BackupScheduleService service() { + return new BackupScheduleService(properties, db.settings, db.backups, setup, clock); + } + + private void recordBackup(String id, String status, Instant startedAt) { + String start = MediaGarrdUtils.formatTime(startedAt); + BackupArchive archive = "failed".equals(status) ? null + : new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, startedAt); + db.backups.addNewBackupRecord(new BackupRunResult(id, start, start, status, List.of(), archive, null)); + } + + private void completeSetup() { + db.settings.saveSetting(SETUP_COMPLETED_SETTING, "2026-11-19 09:00:00"); + setup = newSetup(); + } + + private SetupService newSetup() { + return new SetupService(db.settings, db.pairedClients, false, clock); } @Test - void updatesAndEvaluatesDueState() throws Exception { - BackupScheduleService service = new BackupScheduleService(properties, db); - service.updateInterval(Duration.ofMillis(1)); + void updatesAndEvaluatesDueState() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); - assertEquals(Duration.ofMillis(1), service.getInterval()); + assertEquals(Duration.ofMinutes(15), service.getInterval()); + assertFalse(service.dueNow()); - Thread.sleep(5); + clock.advance(Duration.ofMinutes(15)); assertTrue(service.dueNow()); } @Test void notDueUntilIntervalElapses() { - BackupScheduleService service = new BackupScheduleService(properties, db); + properties.setBackupInterval(Duration.ofHours(1)); + BackupScheduleService service = service(); + + assertFalse(service.dueNow()); + clock.advance(Duration.ofMinutes(59)); assertFalse(service.dueNow()); + + clock.advance(Duration.ofMinutes(1)); + assertTrue(service.dueNow()); } @Test - void usesPropertyIntervalUntilOneIsSaved() { + void persistsUpdatedIntervalAcrossRestarts() { properties.setBackupInterval(Duration.ofHours(3)); + BackupScheduleService first = service(); + assertEquals(Duration.ofHours(3), first.getInterval()); + + first.updateInterval(Duration.ofMinutes(45)); - assertEquals(Duration.ofHours(3), new BackupScheduleService(properties, db).getInterval()); + assertEquals(Optional.of("PT45M"), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING)); + assertEquals(Duration.ofMinutes(45), service().getInterval()); } @Test - void persistsUpdatedIntervalAcrossRestarts() { - properties.setBackupInterval(Duration.ofHours(3)); - new BackupScheduleService(properties, db).updateInterval(Duration.ofMinutes(45)); + void aRestartRunsAnOverdueBackupRightAway() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + + BackupScheduleService restarted = service(); + + assertTrue(restarted.dueNow()); + assertEquals(clock.instant(), restarted.getNextRun()); + } + + @Test + void aRestartKeepsTheOriginalDueTimeWhenNotYetDue() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant last = clock.instant().minus(Duration.ofHours(5)); + recordBackup("run-1", PARTIAL, last); + + BackupScheduleService restarted = service(); + + assertFalse(restarted.dueNow()); + assertEquals(last.plus(Duration.ofHours(12)), restarted.getNextRun()); + clock.advance(Duration.ofHours(7)); + assertTrue(restarted.dueNow()); + } + + @Test + void aSuccessfulBackupAnchorsEvenWhenSetupIsNotCompleted() { + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + + assertTrue(service().dueNow()); + } + + @Test + void noBackupEverIsDueNowOnceSetupIsCompleted() { + completeSetup(); + + assertTrue(service().dueNow()); + } + + @Test + void failedBackupsDoNotCount() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("failed-1", FAILED, clock.instant().minus(Duration.ofHours(1))); + + assertTrue(service().dueNow()); + } + + @Test + void aFailedBackupAfterASuccessfulOneIsIgnored() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant good = clock.instant().minus(Duration.ofHours(2)); + recordBackup("run-1", COMPLETED, good); + recordBackup("failed-1", FAILED, clock.instant().minus(Duration.ofHours(1))); + + assertEquals(good.plus(Duration.ofHours(12)), service().getNextRun()); + } + + @Test + void noBackupEverWaitsAnIntervalWhileSetupIsNotCompleted() { + properties.setBackupInterval(Duration.ofHours(12)); + + BackupScheduleService service = service(); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(12)), service.getNextRun()); + } + + @Test + void completingSetupMakesTheFirstBackupDue() { + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + assertFalse(service.dueNow()); + + setup.complete(); + + assertTrue(service.dueNow()); + } + + @Test + void aBackupDateInTheFutureIsDueNow() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().plus(Duration.ofDays(3))); + + BackupScheduleService restarted = service(); - assertEquals(Optional.of("PT45M"), db.fetchSetting(BACKUP_INTERVAL_SETTING)); - assertEquals(Duration.ofMinutes(45), new BackupScheduleService(properties, db).getInterval()); + assertTrue(restarted.dueNow()); + assertEquals(clock.instant(), restarted.getNextRun()); } @Test - void invalidIntervalsFallBackToTwelveHours() { - BackupScheduleService service = new BackupScheduleService(properties, db); + void changingTheIntervalRecomputesFromTheLastBackup() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant last = clock.instant().minus(Duration.ofHours(5)); + recordBackup("run-1", COMPLETED, last); + BackupScheduleService service = service(); - assertEquals(Duration.ofHours(12), service.updateInterval(null)); - assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ZERO)); - assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ofMinutes(-5))); + service.updateInterval(Duration.ofHours(24)); + assertEquals(last.plus(Duration.ofHours(24)), service.getNextRun()); + assertFalse(service.dueNow()); + + service.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant(), service.getNextRun()); + assertTrue(service.dueNow()); + } + + @Test + void changingTheIntervalWithoutABackupFollowsSetupState() { + BackupScheduleService beforeSetup = service(); + beforeSetup.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant().plus(Duration.ofHours(2)), beforeSetup.getNextRun()); + + completeSetup(); + BackupScheduleService afterSetup = service(); + afterSetup.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant(), afterSetup.getNextRun()); + } + + @Test + void changingTheIntervalDuringARunDoesNotMakeAnotherRunDue() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + BackupScheduleService service = service(); + assertTrue(service.dueNow()); + service.markRunStarted(); + + service.updateInterval(Duration.ofHours(6)); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(6)), service.getNextRun()); + } + + @Test + void changingTheIntervalAfterAFailedRunWaitsAFullInterval() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + service.markRunStarted(); + clock.advance(Duration.ofMinutes(10)); + + service.updateInterval(Duration.ofHours(1)); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofMinutes(50)), service.getNextRun()); + } + + @Test + void aNewerRecordedBackupWinsOverAnEarlierRunStart() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + service.markRunStarted(); + clock.advance(Duration.ofHours(1)); + Instant recorded = clock.instant(); + recordBackup("run-1", COMPLETED, recorded); + + service.updateInterval(Duration.ofHours(3)); + + assertEquals(recorded.plus(Duration.ofHours(3)), service.getNextRun()); + } + + @Test + void anUnreadableBackupHistoryFallsBackToAFullInterval() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupRecordRepository broken = mock(BackupRecordRepository.class); + when(broken.fetchLastSuccessfulStartTime()).thenThrow(new IllegalStateException("database unavailable")); + + BackupScheduleService service = new BackupScheduleService(properties, db.settings, broken, setup, clock); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(12)), service.getNextRun()); + } + + @Test + void outOfRangeIntervalsAreRejectedAndChangeNothing() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofHours(3)); + Instant nextRun = service.getNextRun(); + String message = "Backup interval must be between 15 minutes and 365 days"; + + for (Duration bad : new Duration[] {null, Duration.ZERO, Duration.ofMinutes(-5), Duration.ofMinutes(15).minusSeconds(1), + Duration.ofSeconds(1), Duration.ofDays(365).plusSeconds(1), Duration.ofMinutes(600000000000000L), Duration.ofSeconds(Long.MAX_VALUE)}) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> service.updateInterval(bad)); + assertEquals(message, e.getMessage()); + } + + assertEquals(Duration.ofHours(3), service.getInterval()); + assertEquals(nextRun, service.getNextRun()); + assertEquals(Duration.ofHours(3).toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void boundaryIntervalsAreAccepted() { + BackupScheduleService service = service(); + + assertEquals(Duration.ofMinutes(15), service.updateInterval(Duration.ofMinutes(15))); + assertEquals(Duration.ofDays(365), service.updateInterval(Duration.ofDays(365))); + service.markRunStarted(); + service.deferNextRun(); + assertEquals(clock.instant().plus(Duration.ofDays(365)), service.getNextRun()); + assertEquals(Duration.ofDays(365).toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void ignoresOutOfRangeStoredIntervalAndStartsWithARecordedBackup() { + properties.setBackupInterval(Duration.ofHours(2)); + recordBackup("last", COMPLETED, clock.instant().minus(Duration.ofHours(1))); + + for (String stored : new String[] {"PT600000000000000M", "PT14M", "P366D", "PT1S"}) { + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, stored); + BackupScheduleService service = service(); + assertEquals(Duration.ofHours(2), service.getInterval()); + assertEquals(clock.instant().plus(Duration.ofHours(1)), service.getNextRun()); + } + } + + @Test + void outOfRangeEnvironmentDefaultFallsBackToTwelveHours() { + recordBackup("last", COMPLETED, clock.instant().minus(Duration.ofHours(1))); + + for (Duration bad : new Duration[] {Duration.ofMinutes(5), Duration.ofDays(400), Duration.ofMinutes(600000000000000L), Duration.ZERO, null}) { + properties.setBackupInterval(bad); + BackupScheduleService service = service(); + assertEquals(Duration.ofHours(12), service.getInterval()); + assertEquals(clock.instant().plus(Duration.ofHours(11)), service.getNextRun()); + } + } + + @Test + void acceptsBoundaryValuesFromStorageAndEnvironment() { + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "PT15M"); + assertEquals(Duration.ofMinutes(15), service().getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "P365D"); + assertEquals(Duration.ofDays(365), service().getInterval()); + + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "junk"); + properties.setBackupInterval(Duration.ofDays(365)); + assertEquals(Duration.ofDays(365), service().getInterval()); } @Test void ignoresCorruptStoredInterval() { properties.setBackupInterval(Duration.ofHours(2)); - db.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); - assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); + assertEquals(Duration.ofHours(2), service().getInterval()); - db.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); - assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); + assertEquals(Duration.ofHours(2), service().getInterval()); } @Test - void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() throws Exception { - BackupScheduleService service = new BackupScheduleService(properties, db); - service.updateInterval(Duration.ofMillis(1)); - Thread.sleep(5); + void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); + clock.advance(Duration.ofMinutes(15)); assertTrue(service.dueNow()); service.updateInterval(Duration.ofHours(1)); - Thread.sleep(5); + clock.advance(Duration.ofMinutes(10)); service.deferNextRun(); assertFalse(service.dueNow()); - assertTrue(service.getNextRun().isAfter(java.time.Instant.now().plus(Duration.ofMinutes(59)))); + Instant expected = clock.instant().plus(Duration.ofHours(1)); + assertEquals(expected, service.getNextRun()); + + clock.advance(Duration.ofHours(1)); + assertTrue(service.dueNow()); } @Test void addingAServiceAfterADeferralMakesTheScheduleDueNow() { - BackupScheduleService service = new BackupScheduleService(properties, db); + BackupScheduleService service = service(); service.deferNextRun(); assertFalse(service.dueNow()); @@ -112,8 +397,8 @@ void addingAServiceAfterADeferralMakesTheScheduleDueNow() { @Test void releasingWithoutADeferralChangesNothing() { - BackupScheduleService service = new BackupScheduleService(properties, db); - java.time.Instant before = service.getNextRun(); + BackupScheduleService service = service(); + Instant before = service.getNextRun(); service.releaseDeferral(); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java index 71c77c3..47a680b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java @@ -29,14 +29,6 @@ void findsTheContainerIdFromTheHostnameMountEvenWhenHostnameIsWrong() throws Exc 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"; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java index 559a0c5..c8a74b2 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java @@ -58,13 +58,6 @@ void mapsThroughABindMount() throws Exception { 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( diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java new file mode 100644 index 0000000..9a8c1a8 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java @@ -0,0 +1,178 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.function.BooleanSupplier; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; + +class DatabaseRebuildHandlerTest { + + @TempDir + Path tempDir; + + private final MutableClock clock = new MutableClock(); + private Path databaseFile; + private TestDatabase db; + private SetupService setup; + private RunStatusBroadcaster broadcaster; + private PairingService pairing; + private BackupArchiveService archives; + private BackupScheduleService schedule; + private Path defaultRoot; + + @BeforeEach + void setUp() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + databaseFile = tempDir.resolve("mediagarrd.db"); + properties.setDatabasePath(databaseFile.toString()); + defaultRoot = tempDir.resolve("default-backups"); + properties.setBackupRoot(defaultRoot.toString()); + db = new TestDatabase(properties); + broadcaster = new RunStatusBroadcaster(); + setup = new SetupService(db.settings, db.pairedClients, false, clock); + pairing = new PairingService(setup, db.pairedClients, broadcaster, clock); + archives = new BackupArchiveService(properties, db.settings, db.backups); + schedule = new BackupScheduleService(properties, db.settings, db.backups, setup, clock); + new DatabaseRebuildHandler(db.database, pairing, broadcaster, archives, schedule); + } + + private void corruptWhileRunning() throws Exception { + Files.writeString(databaseFile, "x".repeat(4096)); + db.settings.fetchSetting("anything"); + } + + private static void await(BooleanSupplier condition) throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + throw new AssertionError("Condition not met in time"); + } + Thread.sleep(10); + } + } + + private PairResponse pairConfirmed(String name) { + PairResponse response = pairing.pair(setup.currentPin(), name); + assertTrue(pairing.authenticate(response.token()).isPresent()); + return response; + } + + @Test + void aRuntimeRebuildReopensSetupLikeARestartOnAFreshDatabase() throws Exception { + setup.complete(); + PairResponse client = pairConfirmed("Laptop"); + pairing.createCode(); + assertEquals(1, db.pairedClients.countPairedClients()); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + + assertEquals(0, db.pairedClients.countPairedClients()); + assertFalse(setup.isPairingOpen()); + String pin = setup.currentPin(); + assertNotNull(pin); + assertTrue(pairing.authenticate(client.token()).isEmpty()); + String session = setup.startSession(pin).orElseThrow(); + assertTrue(setup.canConfigure(session)); + } + + @Test + void theBackupLocationRetentionAndScheduleAreReloadedFromTheNewDatabase() throws Exception { + setup.complete(); + archives.updateSettings(tempDir.resolve("custom-backups").toString(), 7); + schedule.updateInterval(Duration.ofHours(3)); + assertEquals(7, archives.retentionCount()); + assertEquals(Duration.ofHours(3), schedule.getInterval()); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + await(() -> archives.rootDirectory().equals(defaultRoot.toAbsolutePath().normalize())); + await(() -> !Duration.ofHours(3).equals(schedule.getInterval())); + + assertEquals(new MediaGarrdProperties().getRetentionCount(), archives.retentionCount()); + assertEquals(new MediaGarrdProperties().getBackupInterval(), schedule.getInterval()); + } + + @Test + void aPendingPairingFromBeforeTheRebuildCannotConfirmAfterwards() throws Exception { + setup.complete(); + PairResponse pending = pairing.pair(setup.currentPin(), "Phone"); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + setup.complete(); + + assertTrue(pairing.authenticate(pending.token()).isEmpty()); + assertEquals(0, db.pairedClients.countPairedClients()); + } + + @Test + void aLockoutFromBeforeTheRebuildIsCleared() throws Exception { + setup.complete(); + for (int i = 0; i < SetupService.MAX_FAILED_ATTEMPTS; i++) { + assertThrows(PairingException.class, () -> pairing.pair("000000", null)); + } + assertThrows(LockedOutException.class, () -> pairing.pair("000000", null)); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + + assertTrue(setup.startSession(setup.currentPin()).isPresent()); + } + + @Test + void openEventStreamsAreClosedButNewOnesStillWork() throws Exception { + broadcaster.subscribe(new SseEmitter(60_000L)); + assertEquals(1, broadcaster.subscriberCount()); + + corruptWhileRunning(); + await(() -> broadcaster.subscriberCount() == 0); + + broadcaster.subscribe(new SseEmitter(60_000L)); + assertEquals(1, broadcaster.subscriberCount()); + broadcaster.shutdown(); + } + + @Test + void theRebuildDoesNotWaitForTheSetupServiceMonitorOrAQueuedSnapshot() throws Exception { + setup.complete(); + Path snapshot = tempDir.resolve("snapshot.db"); + Files.writeString(databaseFile, "x".repeat(4096)); + + CompletableFuture rebuild; + CompletableFuture snapshotting; + synchronized (setup) { + rebuild = CompletableFuture.runAsync(() -> db.settings.fetchSetting("anything")); + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> rebuild.get()); + snapshotting = CompletableFuture.runAsync(() -> { + try { + db.database.snapshotTo(snapshot); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> snapshotting.get()); + assertTrue(setup.isCompleted()); + } + + await(() -> !setup.isCompleted()); + assertTrue(Files.isRegularFile(snapshot)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java deleted file mode 100644 index 1f3ee24..0000000 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ /dev/null @@ -1,488 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.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; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -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; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -import wellatleastitried.mediagarrdServer.model.BackupArchive; -import wellatleastitried.mediagarrdServer.model.BackupRunResult; -import wellatleastitried.mediagarrdServer.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; -import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import wellatleastitried.mediagarrdServer.model.ServiceDefinition; - -class DatabaseServiceTest { - - private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); - - @TempDir - Path tempDir; - - private MediaGarrdProperties properties; - private DatabaseService db; - - @BeforeEach - void setUp() { - properties = new MediaGarrdProperties(); - properties.setDatabasePath(tempDir.resolve("nested/mediagarrd.db").toString()); - db = new DatabaseService(properties); - } - - @Test - void createsDatabaseFileAndParentDirectories() { - assertTrue(Files.isRegularFile(tempDir.resolve("nested/mediagarrd.db"))); - assertTrue(db.verifyDatabaseIntegrity()); - assertTrue(db.verifyDatabaseIntegrity()); - } - - @Test - void storesBackupRecordWithEveryServiceResult() { - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", - serviceResult("jellyfin", COMPLETED, null), - serviceResult("sonarr", PARTIAL, "one path failed"), - serviceResult("qbittorrent", FAILED, "no paths copied"))); - - FetchedBackupRecord record = db.fetchBackupById("run-1").orElseThrow(); - - assertEquals("run-1", record.archiveId()); - assertEquals("2026-01-01 00:00:00", record.startTime()); - assertEquals(COMPLETED, record.status()); - assertEquals(Path.of("run-1.zip").toString(), record.filePath()); - assertEquals( - Set.of( - new FetchedBackupServiceRecord("jellyfin", COMPLETED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", null), - new FetchedBackupServiceRecord("sonarr", PARTIAL, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "one path failed"), - new FetchedBackupServiceRecord("qbittorrent", FAILED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "no paths copied")), - Set.copyOf(record.fetchedServices())); - } - - @Test - void storesFailedRunWithoutArchive() { - db.addNewBackupRecord(new BackupRunResult("failed-1", "2026-01-01 00:00:00", "2026-01-01 00:00:01", FAILED, - List.of(serviceResult("radarr", FAILED, "boom")), null, "radarr: boom")); - - FetchedBackupRecord record = db.fetchBackupById("failed-1").orElseThrow(); - - assertEquals(FAILED, record.status()); - assertNull(record.filePath()); - assertEquals("radarr: boom", record.errorMessage()); - assertEquals(1, record.fetchedServices().size()); - } - - @Test - void fetchesLatestBackupRecordByStartTime() { - db.addNewBackupRecord(backupRun("older", "2026-01-01 00:00:00")); - db.addNewBackupRecord(backupRun("newer", "2026-02-01 00:00:00")); - - assertEquals("newer", db.fetchLatestBackupRecord().orElseThrow().archiveId()); - } - - @Test - void returnsEmptyForMissingBackupRecords() { - assertTrue(db.fetchBackupById("missing").isEmpty()); - assertTrue(db.fetchLatestBackupRecord().isEmpty()); - } - - @Test - void deletesBackupRecord() { - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00")); - - db.deleteBackupRecordById("run-1"); - - assertTrue(db.fetchBackupById("run-1").isEmpty()); - } - - @Test - void deletingBackupRecordCascadesToServiceRows() throws Exception { - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); - assertEquals(1, count("backup_services")); - - db.deleteBackupRecordById("run-1"); - - assertEquals(0, count("backup_services")); - } - - @Test - void migrationRemovesOrphanedServiceRows() throws Exception { - try (var connection = rawConnection(); var statement = connection.createStatement()) { - statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); - statement.execute("PRAGMA user_version = 1"); - } - - new DatabaseService(properties); - - assertEquals(0, count("backup_services")); - try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("PRAGMA user_version")) { - assertEquals(2, rs.getInt(1)); - } - } - - @Test - void storesAndFetchesServicesWithPathOrderPreserved() { - assertEquals(List.of(), db.fetchServices()); - - db.addService(RADARR); - - assertEquals(Optional.of(RADARR), db.fetchService("radarr")); - assertEquals(Optional.of(RADARR), db.fetchService("RADARR")); - assertEquals(List.of(RADARR), db.fetchServices()); - } - - @Test - void listsServicesSortedByNameIgnoringCase() { - db.addService(new ServiceDefinition("sonarr", List.of("/a"))); - db.addService(new ServiceDefinition("Jellyfin", List.of("/b"))); - db.addService(new ServiceDefinition("radarr", List.of("/c"))); - - assertEquals(List.of("Jellyfin", "radarr", "sonarr"), db.fetchServices().stream().map(ServiceDefinition::name).toList()); - } - - @Test - void rejectsDuplicateServiceNamesIgnoringCase() { - db.addService(RADARR); - - assertThrows(IllegalStateException.class, () -> db.addService(new ServiceDefinition("Radarr", List.of("/other")))); - } - - @Test - void updatesServiceNameAndPaths() { - db.addService(RADARR); - ServiceDefinition renamed = new ServiceDefinition("radarr-4k", List.of("/srv/radarr-4k")); - - assertTrue(db.updateService("radarr", renamed)); - - assertTrue(db.fetchService("radarr").isEmpty()); - assertEquals(Optional.of(renamed), db.fetchService("radarr-4k")); - assertFalse(db.updateService("missing", renamed)); - } - - @Test - void removesService() { - db.addService(RADARR); - - assertTrue(db.removeService("radarr")); - assertFalse(db.removeService("radarr")); - assertEquals(List.of(), db.fetchServices()); - } - - @Test - void savesAndOverwritesSettings() { - assertTrue(db.fetchSetting("backup_root").isEmpty()); - - db.saveSetting("backup_root", "/first"); - db.saveSetting("backup_root", "/second"); - - assertEquals(Optional.of("/second"), db.fetchSetting("backup_root")); - } - - @Test - void persistsDataAcrossInstances() { - db.addService(RADARR); - db.saveSetting("backup_root", "/backups"); - - DatabaseService reopened = new DatabaseService(properties); - - assertEquals(List.of(RADARR), reopened.fetchServices()); - assertEquals(Optional.of("/backups"), reopened.fetchSetting("backup_root")); - } - - @Test - void failsLoudlyWhenDatabaseIsUnusable() { - properties.setDatabasePath(tempDir.toString()); - DatabaseService broken = new DatabaseService(properties); - - assertFalse(broken.verifyDatabaseIntegrity()); - assertThrows(IllegalStateException.class, broken::fetchServices); - assertThrows(IllegalStateException.class, () -> broken.addService(RADARR)); - assertThrows(IllegalStateException.class, () -> broken.fetchSetting("backup_root")); - } - - @Test - void verifiesOnlyOnceWhileTheSchemaIsUnchanged() { - AtomicInteger verifications = new AtomicInteger(); - DatabaseService counted = new DatabaseService(properties) { - @Override - protected synchronized boolean verifyDatabaseIntegrity() { - verifications.incrementAndGet(); - return super.verifyDatabaseIntegrity(); - } - }; - - counted.addService(RADARR); - counted.fetchServices(); - counted.fetchSetting("backup_root"); - - assertEquals(1, verifications.get()); - } - - @Test - void rebuildsWhenTheDatabaseFileIsDeleted() throws Exception { - db.addService(RADARR); - - Files.delete(databaseFile()); - - assertEquals(List.of(), db.fetchServices()); - db.addService(RADARR); - assertEquals(List.of(RADARR), db.fetchServices()); - } - - @Test - void rebuildsWhenTheDatabaseDirectoryIsDeleted() throws Exception { - Files.delete(databaseFile()); - Files.delete(databaseFile().getParent()); - - db.saveSetting("backup_root", "/backups"); - - assertEquals(Optional.of("/backups"), db.fetchSetting("backup_root")); - } - - @Test - void rebuildsWhenATableIsDropped() throws Exception { - try (var connection = rawConnection(); var statement = connection.createStatement()) { - statement.execute("DROP TABLE services"); - } - - db.addService(RADARR); - - assertEquals(List.of(RADARR), db.fetchServices()); - } - - @Test - void migratesWhenAnOlderDatabaseIsSwappedIn() throws Exception { - try (var connection = rawConnection(); var statement = connection.createStatement()) { - statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); - statement.execute("PRAGMA user_version = 1"); - } - - db.fetchServices(); - - assertEquals(0, count("backup_services")); - } - - @Test - void movesACorruptDatabaseAsideOnStartup() throws Exception { - Files.writeString(databaseFile(), "x".repeat(4096)); - - DatabaseService recovered = new DatabaseService(properties); - - recovered.addService(RADARR); - assertEquals(List.of(RADARR), recovered.fetchServices()); - assertEquals(List.of("x".repeat(4096)), quarantinedContents()); - } - - @Test - void movesACorruptDatabaseAsideWhileRunning() throws Exception { - db.addService(RADARR); - Files.writeString(databaseFile(), "x".repeat(4096)); - - assertEquals(List.of(), db.fetchServices()); - 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()); - } - - private List quarantinedContents() throws IOException { - try (var files = Files.list(databaseFile().getParent())) { - return files - .filter(file -> file.getFileName().toString().startsWith("mediagarrd.db.corrupt-")) - .map(file -> { - try { - return Files.readString(file); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) - .toList(); - } - } - - private Connection rawConnection() throws SQLException { - return DriverManager.getConnection("jdbc:sqlite:" + properties.getDatabasePath()); - } - - private int count(String table) throws SQLException { - try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM " + table)) { - return rs.getInt(1); - } - } - - private static BackupRunResult backupRun(String id, String startTime, BackupServiceResult... services) { - BackupArchive archive = new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, Instant.parse("2026-01-01T00:00:00Z")); - return new BackupRunResult(id, startTime, startTime, COMPLETED, List.of(services), archive, null); - } - - private static BackupServiceResult serviceResult(String name, String status, String error) { - return new BackupServiceResult(null, status, "2026-01-01 00:00:00", "2026-01-01 00:00:01", name, error); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java index fba6743..02a00bb 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -26,6 +26,7 @@ import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; class DatabaseSnapshotServiceTest { @@ -34,7 +35,7 @@ class DatabaseSnapshotServiceTest { @TempDir Path tempDir; - private DatabaseService db; + private TestDatabase db; private DatabaseHostPathResolver hostPaths; private DatabaseSnapshotService snapshots; private Path run; @@ -43,19 +44,19 @@ class DatabaseSnapshotServiceTest { void setUp() throws Exception { MediaGarrdProperties properties = new MediaGarrdProperties(); properties.setDatabasePath(tempDir.resolve("db/mediagarrd.db").toString()); - db = new DatabaseService(properties); + db = new TestDatabase(properties); hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(HOST_DATABASE); - snapshots = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(HOST_DATABASE); + snapshots = new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)); 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"); + db.services.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); + Files.setPosixFilePermissions(db.database.databaseFile(), PosixFilePermissions.fromString("rw-r-----")); + Integer uid = (Integer) Files.getAttribute(db.database.databaseFile(), "unix:uid"); + Integer gid = (Integer) Files.getAttribute(db.database.databaseFile(), "unix:gid"); BackupServiceResult result = snapshots.snapshot(run); @@ -83,7 +84,7 @@ void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { @Test void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { - when(hostPaths.resolve(db.databaseFile())).thenThrow(new IOException("no mount covers the database")); + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IOException("no mount covers the database")); BackupServiceResult result = snapshots.snapshot(run); @@ -94,30 +95,30 @@ void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { @Test void failsWithoutAPartWhenTheDatabaseIsMissing() throws Exception { - Files.delete(db.databaseFile()); + Files.delete(db.database.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())); + assertEquals("Database file " + db.database.databaseFile() + " does not exist", result.errorMessage()); + assertFalse(Files.exists(db.database.databaseFile())); assertNoPart(); } @Test void failsWithoutAPartWhenTheDatabaseIsCorrupt() throws Exception { - Files.writeString(db.databaseFile(), "x".repeat(4096)); + Files.writeString(db.database.databaseFile(), "x".repeat(4096)); BackupServiceResult result = snapshots.snapshot(run); assertEquals(FAILED, result.status()); - assertEquals("x".repeat(4096), Files.readString(db.databaseFile())); + assertEquals("x".repeat(4096), Files.readString(db.database.databaseFile())); assertNoPart(); } @Test void resolverFailuresOfAnyKindBecomeAFailedResult() throws Exception { - when(hostPaths.resolve(db.databaseFile())).thenThrow(new IllegalStateException("docker down")); + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IllegalStateException("docker down")); assertEquals("docker down", snapshots.snapshot(run).errorMessage()); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java index d9fca86..2205276 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyMap; @@ -22,6 +23,7 @@ import org.mockito.ArgumentCaptor; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectImageCmd; @@ -158,8 +160,13 @@ void configHashDependsOnPathsNotTheirOrder() { } @Test - void mapsHostPathsUnderMountRoot() { - assertEquals("/mnt/srv/radarr/config", DockerService.containerPath("/srv/radarr/config")); + void copyFromStreamsTheTarFromTheHelperContainerUnderTheMountRoot() { + CopyArchiveFromContainerCmd copyCmd = mock(CopyArchiveFromContainerCmd.class); + java.io.InputStream tar = new java.io.ByteArrayInputStream(new byte[] {1, 2, 3}); + when(client.copyArchiveFromContainerCmd("cid", "/mnt/srv/radarr/config")).thenReturn(copyCmd); + when(copyCmd.exec()).thenReturn(tar); + + assertSame(tar, docker.copyFrom("cid", "/srv/radarr/config")); } private static Container container(String id, String hash) { @@ -176,4 +183,19 @@ private static String bind(String hostPath) { private static String describe(Mount mount) { return mount.getType() + " " + mount.getSource() + " -> " + mount.getTarget() + " ro=" + mount.getReadOnly(); } + + @Test + void removesEveryStaleContainerEvenWhenAMatchingOneComesFirst() { + Container match = container("match", docker.configHash(RADARR)); + Container staleAfter = container("stale-after", "old-hash"); + Container staleBefore = container("stale-before", "older-hash"); + when(listCmd.exec()).thenReturn(List.of(staleBefore, match, staleAfter)); + + assertEquals("match", docker.containerFor(RADARR)); + + verify(client).removeContainerCmd("stale-before"); + verify(client).removeContainerCmd("stale-after"); + verify(client, never()).removeContainerCmd("match"); + verify(client, never()).createContainerCmd(anyString()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java b/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java new file mode 100644 index 0000000..8e7eab5 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java @@ -0,0 +1,31 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +final class MutableClock extends Clock { + + private Instant now = Instant.parse("2026-11-19T10:00:00Z"); + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java new file mode 100644 index 0000000..f96de2a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java @@ -0,0 +1,663 @@ +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +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.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; + +class PairingServiceTest { + + private static final Pattern TOKEN = Pattern.compile("[A-Za-z0-9_-]{43}"); + + @TempDir + Path tempDir; + + private final MutableClock clock = new MutableClock(); + private MediaGarrdProperties properties; + private TestDatabase db; + private SetupService setup; + private RunStatusBroadcaster broadcaster; + private PairingService pairing; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new TestDatabase(properties); + broadcaster = mock(RunStatusBroadcaster.class); + setup = new SetupService(db.settings, db.pairedClients, false, clock); + pairing = new PairingService(setup, db.pairedClients, broadcaster, clock); + } + + @Test + void pairingIsRefusedBeforeSetupCompletes() { + PairingException e = assertThrows(PairingException.class, () -> pairing.pair(setup.currentPin(), null)); + + assertEquals(PairingException.Reason.SETUP_INCOMPLETE, e.reason()); + assertEquals("This server has not finished setup yet. Finish it on the server's /config page, then pair.", e.getMessage()); + assertEquals(0, db.pairedClients.countPairedClients()); + } + + @Test + void theCorrectPinReturnsATokenAndStoresOnlyItsHash() { + setup.complete(); + + PairResponse response = pairing.pair(" " + setup.currentPin() + " ", "Laptop"); + + assertTrue(TOKEN.matcher(response.token()).matches(), response.token()); + assertEquals("Laptop", response.name()); + assertEquals(0, db.pairedClients.countPairedClients()); + + confirm(response); + + assertTrue(db.pairedClients.fetchPairedClientByTokenHash(PairingService.hashToken(response.token())).isPresent()); + assertTrue(db.pairedClients.fetchPairedClientByTokenHash(response.token()).isEmpty()); + assertEquals(1, db.pairedClients.countPairedClients()); + assertFalse(db.pairedClients.fetchPairedClients().toString().contains(response.token())); + } + + @Test + void tokensAreDistinctPerPairing() { + setup.complete(); + PairResponse first = pairing.pair(setup.currentPin(), "A"); + confirm(first); + String code = pairing.createCode().code(); + PairResponse second = pairing.pair(code, "B"); + confirm(second); + + assertNotEquals(first.token(), second.token()); + assertNotEquals(first.id(), second.id()); + assertEquals(2, db.pairedClients.countPairedClients()); + } + + @Test + void aConfirmedPairingClosesPairing() { + setup.complete(); + String pin = setup.currentPin(); + PairResponse response = pairing.pair(pin, null); + assertTrue(setup.isPairingOpen()); + assertEquals(pin, setup.currentPin()); + + confirm(response); + + assertFalse(setup.isPairingOpen()); + assertNull(setup.currentPin()); + PairingException e = assertThrows(PairingException.class, () -> pairing.pair(pin, null)); + + assertEquals(PairingException.Reason.CLOSED, e.reason()); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void aWrongPinIsInvalidAndCreatesNothing() { + setup.complete(); + + PairingException e = assertThrows(PairingException.class, () -> pairing.pair("not-it", null)); + + assertEquals(PairingException.Reason.INVALID, e.reason()); + assertEquals(0, db.pairedClients.countPairedClients()); + assertTrue(setup.isPairingOpen()); + } + + @Test + void wrongPinsLockPairingEvenForTheCorrectPin() { + setup.complete(); + for (int i = 0; i < SetupService.MAX_FAILED_ATTEMPTS; i++) { + assertThrows(PairingException.class, () -> pairing.pair("000000", null)); + } + + assertThrows(LockedOutException.class, () -> pairing.pair(setup.currentPin(), null)); + + clock.advance(SetupService.LOCK_DURATION.plusSeconds(1)); + confirm(pairing.pair(setup.currentPin(), null)); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void anExistingInstallWithoutClientsGetsAPinOnStart() { + setup.complete(); + SetupService restarted = new SetupService(db.settings, db.pairedClients, false, clock); + PairingService restartedPairing = new PairingService(restarted, db.pairedClients, broadcaster, clock); + + PairResponse response = restartedPairing.pair(restarted.currentPin(), null); + + assertTrue(TOKEN.matcher(response.token()).matches()); + assertTrue(restartedPairing.authenticate(response.token()).isPresent()); + } + + @Test + void openPairingFlagLetsAnotherClientPairWithANewPin() { + setup.complete(); + confirm(pairing.pair(setup.currentPin(), "First")); + SetupService restarted = new SetupService(db.settings, db.pairedClients, true, clock); + PairingService restartedPairing = new PairingService(restarted, db.pairedClients, broadcaster, clock); + + PairResponse second = restartedPairing.pair(restarted.currentPin(), "Second"); + assertTrue(restartedPairing.authenticate(second.token()).isPresent()); + + assertEquals(2, db.pairedClients.countPairedClients()); + } + + @Test + void namesAreValidatedAndGeneratedWhenMissing() { + setup.complete(); + + assertThrows(IllegalArgumentException.class, () -> pairing.pair(setup.currentPin(), "x".repeat(65))); + assertThrows(IllegalArgumentException.class, () -> pairing.pair(setup.currentPin(), "