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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 40 additions & 29 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -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":"<ISO-8601>"}`
- `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 <archive> -C /` restore it in place
- The host path is found by inspecting the server's own container, a run is reported as partial with the error logged if it cannot be found or the snapshot fails, and a corrupt or missing database is never replaced by an empty one
- All database operations now wait while the snapshot is taken, so nothing is written to the database mid-copy
- The database snapshot appears as `_mediagarrd-server` in each run's service results and in the API's service names
- A service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to the snapshot in the archive
- 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 <archive> -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 <archive> -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 <archive> -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
73 changes: 12 additions & 61 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -14,74 +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://<server-ip>: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-<timestamp>` and replaced with an empty one, after which settings and services must be configured again (restart the server to get a new setup PIN).
Open `http://<server-ip>: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 <archive>.zip -C /
```
Extract into an empty directory with `-C <dir>` to inspect a backup first.

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

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

> **Security:** the server needs `/var/run/docker.sock`, which gives it root-equivalent access to the host. During setup the configuration API requires the PIN session, but once setup is finished the API is unauthenticated, so do not expose the server port to untrusted networks.
> **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)
6 changes: 6 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -31,6 +33,10 @@ java {
}
}

springBoot {
buildInfo()
}

tasks.test {
useJUnitPlatform()
}
41 changes: 41 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
@@ -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. |
Loading
Loading