Compare commits
No commits in common. "f747aab65dbe6b217886e191a36ca140ac5bda3b" and "9aa395814c7edfa0f5389e342422757667e6226a" have entirely different histories.
f747aab65d
...
9aa395814c
4 changed files with 0 additions and 391 deletions
209
BACKUPS.md
209
BACKUPS.md
|
|
@ -1,209 +0,0 @@
|
|||
# Backups
|
||||
|
||||
Nightly [restic](https://restic.net) backups of the VPS to a Scaleway Object
|
||||
Storage bucket, configured in [`backups.nix`](backups.nix).
|
||||
|
||||
## What is backed up
|
||||
|
||||
One encrypted, deduplicated restic repository holds two kinds of snapshots:
|
||||
|
||||
| Tag | When (Europe/Amsterdam) | Paths | Notes |
|
||||
|----------|------------------------|-------|-------|
|
||||
| `panel` | daily 03:30 | `/var/lib/containers` (stacks, volumes, routes, panel state), `~reudy/.local/share/containers/storage/volumes` | The panel's running containers are **stopped for the duration** (usually under a minute) and started again afterwards, so databases inside them are copied consistently. |
|
||||
| `system` | daily 04:00 | `/etc`, `/home`, `/root`, `/var/lib`, `/var/backup` | Forgejo, Nextcloud, Authelia, the panel's database, SSH host keys, `/var/lib/nixos` (uid/gid map), the `hello` container, and so on. |
|
||||
|
||||
Before the system snapshot, the SQLite databases (Forgejo, Nextcloud, Authelia,
|
||||
panel) are dumped to `/var/backup/sqlite/<name>.sql`. These dumps are
|
||||
consistent even though the services keep running. The raw `.db` files are
|
||||
backed up as well, but a copy taken mid-write can be torn, so restore from the
|
||||
dumps if a raw file looks broken.
|
||||
|
||||
**Not backed up** (it can all be rebuilt): `/nix/store` (rebuilt from this
|
||||
flake), container images (pulled or built again on deploy), `~/.cache`,
|
||||
Nextcloud previews, core dumps.
|
||||
|
||||
**Retention**, applied every Sunday at 05:30 by `restic-backups-maintenance`:
|
||||
7 daily, 4 weekly and 6 monthly snapshots, per tag. The same run prunes
|
||||
unreferenced data and checks the repository, reading a random 2 GB of it.
|
||||
|
||||
## Cost notes
|
||||
|
||||
Scaleway doesn't charge for API requests. It charges for stored GB-hours,
|
||||
egress above 75 GB a month, and Glacier restores. So:
|
||||
|
||||
- objects are uploaded as **One Zone** (`ONEZONE_IA`), half the price of
|
||||
Multi-AZ. The class is set per object at upload time (`extraOptions` in
|
||||
`backups.nix`), so changing it only affects new uploads;
|
||||
- the backup itself downloads almost nothing. All jobs share one local cache
|
||||
in `/var/cache/restic`, so metadata is fetched once;
|
||||
- pruning (which may download and re-pack partly-used data) runs weekly, not
|
||||
after every backup;
|
||||
- `check` reads a fixed 2 GB sample instead of the whole repository;
|
||||
- Glacier isn't used. It stores more cheaply, but every restore and every
|
||||
pruning repack would first need a paid, hours-long thaw.
|
||||
|
||||
`sudo restic-system stats --mode raw-data` shows how much is actually stored.
|
||||
|
||||
## One-time setup
|
||||
|
||||
The two secrets are agenix files. Create them **on a machine that holds one of
|
||||
the user keys in [`secrets.nix`](secrets.nix)**, from a checkout of this repo:
|
||||
|
||||
```bash
|
||||
# 1. The repository password. Generate a long random one (e.g. in your password
|
||||
# manager) and keep it there: without it the backups cannot be read.
|
||||
agenix -e secrets/restic-password.age
|
||||
|
||||
# 2. Where the repository is and how to reach it. Four lines, no quotes:
|
||||
agenix -e secrets/restic-env.age
|
||||
```
|
||||
|
||||
```ini
|
||||
RESTIC_REPOSITORY=s3:https://s3.<region>.scw.cloud/<bucket>/vps
|
||||
AWS_ACCESS_KEY_ID=SCW...
|
||||
AWS_SECRET_ACCESS_KEY=...
|
||||
AWS_DEFAULT_REGION=<region>
|
||||
```
|
||||
|
||||
`<region>` is the bucket's region: `fr-par`, `nl-ams` or `pl-waw`. Use an API
|
||||
key from a dedicated Scaleway IAM application whose policy only grants Object
|
||||
Storage in the bucket's project, not your personal key.
|
||||
|
||||
Store the password, the access key pair, the bucket name and the region in your
|
||||
password manager too. The `.age` files can be decrypted with your SSH keys, but
|
||||
the canonical copy of this repo lives on the server you'd be recovering.
|
||||
|
||||
Then commit the two `.age` files, deploy, and run the first backups by hand:
|
||||
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake .#vps
|
||||
|
||||
# Optional: seed the panel data without stopping anything. The real run below
|
||||
# then uploads only what changed, so the apps are down for seconds, not for
|
||||
# the whole first upload.
|
||||
sudo restic-panel init # only if the repository doesn't exist yet
|
||||
sudo restic-panel backup --tag seed /var/lib/containers
|
||||
|
||||
sudo systemctl start restic-backups-panel
|
||||
sudo restic-panel forget --tag seed # its data stays, shared with the real snapshot
|
||||
|
||||
sudo systemctl start restic-backups-system # the first upload can take a while
|
||||
journalctl -u restic-backups-system -f
|
||||
```
|
||||
|
||||
## Day to day
|
||||
|
||||
```bash
|
||||
systemctl list-timers 'restic-*' # next / last runs
|
||||
systemctl status restic-backups-{panel,system,maintenance}
|
||||
journalctl -u restic-backups-system -n 100
|
||||
|
||||
sudo restic-system snapshots # restic-<job> wrappers work
|
||||
sudo restic-system snapshots --tag panel # all point at the same repo
|
||||
```
|
||||
|
||||
A failed run leaves the unit in `failed` state. There is no alerting yet, so
|
||||
`systemctl --failed` is the place to look.
|
||||
|
||||
## Restoring files
|
||||
|
||||
```bash
|
||||
sudo restic-system snapshots --tag system
|
||||
sudo restic-system ls latest --tag system /var/lib/forgejo
|
||||
sudo restic-system restore latest --tag system \
|
||||
--include /var/lib/forgejo/data/forgejo.db --target /root/restore
|
||||
```
|
||||
|
||||
Restores keep owners and permissions. Stop the affected service before copying
|
||||
files back into place.
|
||||
|
||||
### A panel app
|
||||
|
||||
```bash
|
||||
panelctl stop <app>
|
||||
sudo restic-panel restore latest --tag panel \
|
||||
--include /var/lib/containers/volumes/<app> --target /
|
||||
panelctl deploy <app>
|
||||
```
|
||||
|
||||
### A SQLite database from its dump
|
||||
|
||||
```bash
|
||||
sudo systemctl stop forgejo
|
||||
sudo -u forgejo mv /var/lib/forgejo/data/forgejo.db{,.broken}
|
||||
sudo -u forgejo sqlite3 /var/lib/forgejo/data/forgejo.db < /root/restore/var/backup/sqlite/forgejo.sql
|
||||
sudo systemctl start forgejo
|
||||
```
|
||||
|
||||
## Disaster recovery: rebuilding the server
|
||||
|
||||
On NixOS, "the whole server" is this flake plus the state in the backup.
|
||||
|
||||
1. **Get a fresh NixOS VPS** (vpsAdminOS NixOS template) and SSH in as root.
|
||||
If the IP address changed, update the DNS records for `*.reudy.net`.
|
||||
|
||||
2. **Get restic and the credentials** into the shell. Don't paste them on the
|
||||
command line:
|
||||
|
||||
```bash
|
||||
nix --extra-experimental-features 'nix-command flakes' shell nixpkgs#restic nixpkgs#git nixpkgs#rsync
|
||||
read -rs -p 'Scaleway access key: ' AWS_ACCESS_KEY_ID; echo
|
||||
read -rs -p 'Scaleway secret key: ' AWS_SECRET_ACCESS_KEY; echo
|
||||
read -rs -p 'Restic password: ' RESTIC_PASSWORD; echo
|
||||
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY RESTIC_PASSWORD
|
||||
export AWS_DEFAULT_REGION=<region>
|
||||
export RESTIC_REPOSITORY=s3:https://s3.<region>.scw.cloud/<bucket>/vps
|
||||
restic snapshots
|
||||
```
|
||||
|
||||
3. **Restore both latest snapshots to a staging directory**:
|
||||
|
||||
```bash
|
||||
restic restore latest --tag system --target /restore
|
||||
restic restore latest --tag panel --target /restore
|
||||
```
|
||||
|
||||
4. **Put identity back first**: the SSH host keys (agenix decrypts the secrets
|
||||
with them) and the uid/gid map (so restored files keep the right owners):
|
||||
|
||||
```bash
|
||||
cp -a /restore/etc/ssh/ssh_host_* /etc/ssh/
|
||||
cp -a /restore/var/lib/nixos/. /var/lib/nixos/
|
||||
```
|
||||
|
||||
5. **Get the flake.** Forgejo isn't running yet, so clone it from the restored
|
||||
repository, and point the `panel` input at the restored panel repository:
|
||||
|
||||
```bash
|
||||
git clone /restore/var/lib/forgejo/repositories/reudy-net/nixos.git /root/nixos
|
||||
cd /root/nixos
|
||||
nixos-rebuild boot --flake .#vps \
|
||||
--override-input panel 'git+file:///restore/var/lib/forgejo/repositories/reudy-net/panel.git?ref=main'
|
||||
```
|
||||
|
||||
6. **Copy the state into place and boot into the new system:**
|
||||
|
||||
```bash
|
||||
rsync -aHAX /restore/var/lib/ /var/lib/
|
||||
rsync -aHAX /restore/home/ /home/
|
||||
rsync -aHAX /restore/root/ /root/
|
||||
reboot
|
||||
```
|
||||
|
||||
Caddy fetches new certificates by itself. If a service won't start because
|
||||
its database is damaged, load the dump from `/var/backup/sqlite` (above).
|
||||
Then run `passwd reudy` if sudo doesn't accept the old password.
|
||||
|
||||
7. **Bring the panel apps back**: their compose files, volumes and settings are
|
||||
restored, but the images are not:
|
||||
|
||||
```bash
|
||||
panelctl list
|
||||
panelctl deploy <app> # for each app
|
||||
```
|
||||
|
||||
8. Once Forgejo is up, rebuild once more without `--override-input`, check
|
||||
`systemctl --failed`, then delete `/restore`.
|
||||
|
||||
Practise this once on a throwaway VPS. Until a restore has worked, the backup
|
||||
hasn't been tested.
|
||||
176
backups.nix
176
backups.nix
|
|
@ -1,176 +0,0 @@
|
|||
{ config, lib, pkgs, ... }:
|
||||
|
||||
# Nightly restic backups to Scaleway Object Storage. BACKUPS.md covers what is
|
||||
# kept, how to check on it and how to restore (including a full rebuild).
|
||||
#
|
||||
# Everything goes into one repository, as three jobs:
|
||||
# system - host state: /etc, /home, /root, /var/lib (minus the panel)
|
||||
# panel - panel apps: /var/lib/containers plus rootless named volumes,
|
||||
# with the app containers stopped for a consistent copy
|
||||
# maintenance - weekly forget/prune and a small check, no backup
|
||||
#
|
||||
# Scaleway doesn't charge for requests, only for stored GB-hours, egress over
|
||||
# 75 GB a month and Glacier restores. So the settings below keep the stored size
|
||||
# small and avoid downloads: no /nix/store (rebuilt from the flake), one shared
|
||||
# local cache so metadata is fetched once, pruning only weekly, and checks that
|
||||
# read a fixed 2 GB sample instead of the whole repository.
|
||||
let
|
||||
panel = config.services.reudy-panel;
|
||||
# Rootless Podman keeps named volumes (and images) in the user's home.
|
||||
panelPodmanStorage = "${config.users.users.${panel.user}.home}/.local/share/containers/storage";
|
||||
|
||||
# Consistent SQLite copies land here and are picked up by the system job.
|
||||
sqliteDumpDir = "/var/backup/sqlite";
|
||||
|
||||
common = {
|
||||
passwordFile = config.age.secrets."restic-password".path;
|
||||
# RESTIC_REPOSITORY, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and
|
||||
# AWS_DEFAULT_REGION; see BACKUPS.md for the format.
|
||||
environmentFile = config.age.secrets."restic-env".path;
|
||||
initialize = true;
|
||||
extraOptions = [
|
||||
# One Zone costs half as much as Multi-AZ and is enough for a copy that
|
||||
# already lives away from the server. It only applies to newly uploaded
|
||||
# objects, so changing it later doesn't move what's already stored.
|
||||
"s3.storage-class=ONEZONE_IA"
|
||||
];
|
||||
};
|
||||
|
||||
# Copies each SQLite database with `.dump`, which reads inside a single
|
||||
# transaction, so the copy is consistent even while the service writes. It
|
||||
# runs as the database's owner so it can't leave root-owned -wal/-shm files
|
||||
# behind that would lock the service out. A failed dump only warns: the live
|
||||
# files are still backed up, and one bad database shouldn't stop the rest.
|
||||
dumpSqlite = name: db: ''
|
||||
if [ -f ${lib.escapeShellArg db} ]; then
|
||||
owner=$(stat -c %U ${lib.escapeShellArg db})
|
||||
if runuser -u "$owner" -- sqlite3 ${lib.escapeShellArg db} .dump > ${sqliteDumpDir}/${name}.sql.tmp; then
|
||||
mv ${sqliteDumpDir}/${name}.sql.tmp ${sqliteDumpDir}/${name}.sql
|
||||
else
|
||||
echo "WARNING: dumping ${name} failed, keeping the previous dump" >&2
|
||||
rm -f ${sqliteDumpDir}/${name}.sql.tmp
|
||||
fi
|
||||
else
|
||||
echo "skipping ${name}: ${db} does not exist"
|
||||
fi
|
||||
'';
|
||||
|
||||
# Podman as the panel's user, the same way the panel itself runs it. The
|
||||
# user has no fixed uid in this config, so look it up.
|
||||
podmanAsPanelUser = ''
|
||||
podman_panel() {
|
||||
runuser -u ${panel.user} -- env XDG_RUNTIME_DIR="/run/user/$(id -u ${panel.user})" podman "$@"
|
||||
}
|
||||
'';
|
||||
stoppedContainers = "/run/restic-backups-panel/stopped-containers";
|
||||
in
|
||||
{
|
||||
age.secrets."restic-password".file = ./secrets/restic-password.age;
|
||||
age.secrets."restic-env".file = ./secrets/restic-env.age;
|
||||
|
||||
systemd.tmpfiles.rules = [ "d ${sqliteDumpDir} 0700 root root -" ];
|
||||
|
||||
services.restic.backups = {
|
||||
system = common // {
|
||||
paths = [ "/etc" "/home" "/root" "/var/lib" "/var/backup" ];
|
||||
exclude = [
|
||||
# Backed up by the panel job, with the containers stopped.
|
||||
"/var/lib/containers"
|
||||
"${config.users.users.${panel.user}.home}/.local/share/containers"
|
||||
# Regenerated on demand.
|
||||
"/home/*/.cache"
|
||||
"/root/.cache"
|
||||
"/var/lib/systemd/coredump"
|
||||
"${config.services.nextcloud.datadir}/data/appdata_*/preview"
|
||||
];
|
||||
extraBackupArgs = [ "--tag system" ];
|
||||
backupPrepareCommand = ''
|
||||
set -eu
|
||||
${dumpSqlite "forgejo" config.services.forgejo.database.path}
|
||||
${dumpSqlite "nextcloud" "${config.services.nextcloud.datadir}/data/${config.services.nextcloud.config.dbname}.db"}
|
||||
${dumpSqlite "authelia" config.services.authelia.instances.main.settings.storage.local.path}
|
||||
${dumpSqlite "panel" "${panel.baseDir}/state/panel/panel.db"}
|
||||
'';
|
||||
timerConfig = {
|
||||
OnCalendar = "04:00";
|
||||
RandomizedDelaySec = "10m";
|
||||
Persistent = true;
|
||||
};
|
||||
};
|
||||
|
||||
panel = common // {
|
||||
paths = [
|
||||
panel.baseDir
|
||||
"${panelPodmanStorage}/volumes"
|
||||
];
|
||||
exclude = [
|
||||
# Rootful Podman's image store, if it is ever used. Images are pulled
|
||||
# or rebuilt again on deploy, so they're not worth paying to store.
|
||||
"${panel.baseDir}/storage"
|
||||
"${panel.baseDir}/cache"
|
||||
];
|
||||
extraBackupArgs = [ "--tag panel" ];
|
||||
# Stop the running app containers so databases inside them are copied
|
||||
# in a consistent state. The cleanup command starts exactly these again,
|
||||
# and runs even when the backup fails.
|
||||
backupPrepareCommand = ''
|
||||
set -eu
|
||||
${podmanAsPanelUser}
|
||||
podman_panel ps --quiet > ${stoppedContainers}
|
||||
if [ -s ${stoppedContainers} ]; then
|
||||
echo "stopping $(wc -l < ${stoppedContainers}) container(s)"
|
||||
podman_panel stop --time 30 $(cat ${stoppedContainers})
|
||||
fi
|
||||
'';
|
||||
backupCleanupCommand = ''
|
||||
set -eu
|
||||
${podmanAsPanelUser}
|
||||
if [ -s ${stoppedContainers} ]; then
|
||||
echo "starting $(wc -l < ${stoppedContainers}) container(s)"
|
||||
podman_panel start $(cat ${stoppedContainers})
|
||||
fi
|
||||
'';
|
||||
timerConfig = {
|
||||
OnCalendar = "03:30";
|
||||
RandomizedDelaySec = "10m";
|
||||
Persistent = true;
|
||||
};
|
||||
};
|
||||
|
||||
# No paths, so this unit only forgets, prunes and checks.
|
||||
maintenance = common // {
|
||||
initialize = false;
|
||||
pruneOpts = [
|
||||
"--keep-daily 7"
|
||||
"--keep-weekly 4"
|
||||
"--keep-monthly 6"
|
||||
];
|
||||
# Without --with-cache, check re-downloads all metadata into a temp dir.
|
||||
# The 2 GB sample spreads a real read of the data over the weeks while
|
||||
# staying well inside the free egress.
|
||||
checkOpts = [
|
||||
"--with-cache"
|
||||
"--read-data-subset=2G"
|
||||
];
|
||||
timerConfig = {
|
||||
OnCalendar = "Sun 05:30";
|
||||
Persistent = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services = lib.genAttrs
|
||||
[ "restic-backups-system" "restic-backups-panel" "restic-backups-maintenance" ]
|
||||
(_: {
|
||||
# One cache for all jobs, so metadata is downloaded once instead of once
|
||||
# per job. The restic-<job> wrappers pick this up from the unit too.
|
||||
environment.RESTIC_CACHE_DIR = lib.mkForce "/var/cache/restic";
|
||||
serviceConfig.CacheDirectory = lib.mkForce "restic";
|
||||
path = [
|
||||
"/run/wrappers" # newuidmap & co. for rootless Podman
|
||||
config.virtualisation.podman.package
|
||||
pkgs.sqlite
|
||||
pkgs.util-linux
|
||||
];
|
||||
});
|
||||
}
|
||||
|
|
@ -44,7 +44,6 @@
|
|||
./authelia.nix
|
||||
./nextcloud.nix
|
||||
./forgejo.nix
|
||||
./backups.nix
|
||||
./containers/hello.nix
|
||||
agenix.nixosModules.default
|
||||
|
||||
|
|
|
|||
|
|
@ -20,9 +20,4 @@ in
|
|||
|
||||
# Nextcloud admin password (plaintext, read by the nextcloud service)
|
||||
"secrets/nextcloud-admin-pass.age".publicKeys = users ++ systems;
|
||||
|
||||
# Restic backups (backups.nix): the repository password, and an env file with
|
||||
# the repository URL and Scaleway S3 keys. See BACKUPS.md.
|
||||
"secrets/restic-password.age".publicKeys = users ++ systems;
|
||||
"secrets/restic-env.age".publicKeys = users ++ systems;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue