Add verified backups to a block storage volume, and a recovery runbook
Browse filesdeploy/gitv-backup writes a daily hard-linked snapshot of the repositories, the SSH keys and the web sign-in to a mounted volume. Each repository is copied under an exclusive lock that pushes now hold shared (with post-push gc kept inside the push), every copy is checked with git fsck, and only a passing snapshot becomes latest. It refuses to run unless the volume is mounted. deploy/gitv-restore restores a snapshot into an empty directory and runs a full fsck; a weekly timer does this as a drill. The README covers setting up the volume, what it protects against, and rebuilding the server from a snapshot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 15:51
- Commit
- ca9f4860186f
- Parent
- 08ea36c
10 files changed +509−1
+57−0
| @@ -91,3 +91,60 @@ Fedora's distribution-provided systemd defaults. OpenSSH uses | ||
| `deploy/gitv-purge.service` and `deploy/gitv-purge.timer` in `/etc/systemd/system`, enabled with | ||
| `systemctl enable --now gitv-purge.timer`. | ||
| ## Backups | ||
| `deploy/gitv-backup` snapshots everything the server can't rebuild: the repositories (with their trash, reflogs, push logs and visibility markers), `/etc/gitv` (the SSH keys) and `/var/lib/gitv-web` (the web sign-in). Each snapshot is a plain copy in `/mnt/gitv-backup/gitv/snapshots/<UTC time>/`. Files unchanged since the previous snapshot are hard links to it, so a day's snapshot costs only what changed. Each repository is copied under a lock that pushes also take, so no copy catches a push half way. Every copy is then checked with `git fsck`, and only a snapshot that passes becomes `latest`. Snapshots are kept for 30 days. | ||
| The backup holds the authenticator secret and the password hash, so it is private to root (mode 0700). | ||
| **The volume.** Create a DigitalOcean block storage volume in the droplet's region (ext4), attach it, and mount it at `/mnt/gitv-backup`: | ||
| ```sh | ||
| # /etc/fstab (use the volume's own /dev/disk/by-id name) | ||
| /dev/disk/by-id/scsi-0DO_Volume_gitv-backup /mnt/gitv-backup ext4 defaults,nofail,discard,noatime 0 2 | ||
| ``` | ||
| The script refuses to run unless that directory is a mounted volume, so a missing mount can't fill the droplet's own disk. | ||
| A volume survives the droplet being destroyed or its disk failing, and the snapshots cover mistakes for 30 days. It doesn't survive a regional outage or the loss of the DigitalOcean account. Take an occasional DigitalOcean snapshot of the volume, and add an off-site copy when that matters. | ||
| **Install.** | ||
| ```sh | ||
| install -m 0755 deploy/gitv-backup deploy/gitv-restore /usr/local/sbin/ | ||
| cp deploy/gitv-backup.{service,timer} deploy/gitv-restore-check.{service,timer} /etc/systemd/system/ | ||
| systemctl daemon-reload | ||
| systemctl enable --now gitv-backup.timer gitv-restore-check.timer | ||
| systemctl start gitv-backup # a first snapshot now | ||
| ``` | ||
| The backup runs daily at about 02:30. Every Sunday, `gitv-restore check` copies the latest snapshot out, runs a full `git fsck` on every repository, and deletes the copy, proving the backups restore. A failure of either shows in `systemctl --failed` and `journalctl -u gitv-backup`. | ||
| ## Disaster recovery | ||
| **One repository or file.** Snapshots are plain folders, so copy what you need straight out of `/mnt/gitv-backup/gitv/snapshots/<time>/repos/<owner>/<name>.git`. For history overwritten in the last 30 days, the reflog and push log (see Storage) are quicker. | ||
| **The whole server.** On a fresh Fedora droplet: | ||
| 1. Detach the volume from the old droplet (if it still exists), attach it to the new one, and mount it at `/mnt/gitv-backup` as above. | ||
| 2. Install git and Caddy. Create the `git` account with an ordinary shell such as `/bin/bash`. sshd runs each key's forced command through it, so `git-shell` would refuse `gitv serve`, and keys can't run anything else. Also create the `gitv-web` system account in the `git` group. Build and install `gitv` and `gitv-web` to `/usr/local/bin`, and the deployment files as described under Production configuration and Backups. | ||
| 3. Restore the latest snapshot to a staging folder. This also verifies every repository: | ||
| ```sh | ||
| gitv-restore list | ||
| gitv-restore latest /srv/gitv-restore | ||
| ``` | ||
| 4. Move it into place. rsync run as root keeps owners by name, so the new accounts take over their files: | ||
| ```sh | ||
| mkdir -p /srv/gitv /etc/gitv /var/lib/gitv-web | ||
| rsync -a /srv/gitv-restore/repos/ /srv/gitv/repos/ | ||
| rsync -a /srv/gitv-restore/etc-gitv/ /etc/gitv/ | ||
| rsync -a /srv/gitv-restore/gitv-web/ /var/lib/gitv-web/ | ||
| rm -rf /srv/gitv-restore | ||
| ``` | ||
| 5. Start `sshd`, `gitv-web` and `caddy`, and enable the timers. Point DNS at the new droplet. Check a clone over SSH and over HTTPS, and sign in to the web browser. | ||
| Pushes made after the last snapshot are lost from the server, but every clone still has them: pushing again restores them. | ||
deploy/gitv-backupAdded
+126−0
| @@ -0,0 +1,126 @@ | ||
| #!/bin/bash | ||
| # Snapshot everything GITv needs to come back after losing the server: the repositories (with | ||
| # their trash, reflogs, push logs and visibility markers), the SSH keys file and the web sign-in. | ||
| # | ||
| # Each run writes <backup dir>/gitv/snapshots/<UTC time>/, a plain copy that restores with | ||
| # rsync or cp. Files unchanged since the previous snapshot are hard links to it, so a snapshot | ||
| # costs only what changed. Each repository is copied under its exclusive lock (pushes hold it | ||
| # shared), then checked with git fsck; only a snapshot that passes becomes `latest`. | ||
| # | ||
| # Settings (environment; the systemd unit sets the backup directory): | ||
| # GITV_BACKUP_DIR where the volume is mounted (/mnt/gitv-backup) | ||
| # GITV_BACKUP_KEEP_DAYS delete snapshots older than this (30) | ||
| # GITV_BACKUP_REQUIRE_MOUNT refuse unless the dir is a mount (1) | ||
| # GITV_BACKUP_LOCK_WAIT seconds to wait for a push (900) | ||
| # GITV_REPOS, GITV_KEYS, GITV_WEB_AUTH as for gitv and gitv-web. | ||
| set -euo pipefail | ||
| umask 077 | ||
| dest=${GITV_BACKUP_DIR:-/mnt/gitv-backup} | ||
| keep_days=${GITV_BACKUP_KEEP_DAYS:-30} | ||
| lock_wait=${GITV_BACKUP_LOCK_WAIT:-900} | ||
| repos=${GITV_REPOS:-/srv/gitv/repos} | ||
| keys_dir=$(dirname "${GITV_KEYS:-/etc/gitv/authorized_keys}") | ||
| web_dir=$(dirname "${GITV_WEB_AUTH:-/var/lib/gitv-web/login}") | ||
| say() { echo "gitv-backup: $*" >&2; } | ||
| die() { say "$*"; exit 1; } | ||
| # An unmounted volume would silently fill the server's own disk instead. | ||
| if [[ ${GITV_BACKUP_REQUIRE_MOUNT:-1} == 1 ]] && ! mountpoint -q "$dest"; then | ||
| die "$dest is not a mounted volume; mount the backup volume there first" | ||
| fi | ||
| [[ -d $repos && ! -L $repos ]] || die "$repos is not a directory" | ||
| base=$dest/gitv | ||
| snapshots=$base/snapshots | ||
| mkdir -p "$snapshots" | ||
| chmod 700 "$base" | ||
| # One backup at a time. | ||
| exec 9>"$base/.lock" | ||
| flock -n 9 || die "another backup is running" | ||
| # Leftovers from a run that crashed part way. | ||
| find "$snapshots" -mindepth 1 -maxdepth 1 -name '*.partial' -exec rm -rf {} + | ||
| stamp=$(date -u +%Y-%m-%dT%H%M%SZ) | ||
| [[ -e $snapshots/$stamp ]] && die "snapshot $stamp already exists" | ||
| snap=$snapshots/$stamp.partial | ||
| previous=$(readlink -f "$base/latest" 2>/dev/null || true) | ||
| [[ -d $previous ]] || previous= | ||
| # copy FROM TO PART [rsync options...]: copy FROM to TO, hard-linking files unchanged since | ||
| # the previous snapshot's PART. | ||
| copy() { | ||
| local from=$1 to=$2 part=$3 | ||
| shift 3 | ||
| local link=() | ||
| if [[ -n $previous && -d $previous/$part ]]; then link=(--link-dest="$previous/$part"); fi | ||
| rsync -a --delete "${link[@]}" "$@" "$from" "$to" | ||
| } | ||
| # Everything but the repositories themselves: owner folders, the trash, anything unexpected. | ||
| mkdir -p "$snap/repos" | ||
| copy "$repos/" "$snap/repos/" repos --exclude='/*/*.git/' || die "copying $repos failed" | ||
| # Each repository under its lock, so no push is caught half way. | ||
| count=0 | ||
| while IFS= read -r -d '' repo; do | ||
| rel=${repo#"$repos"/} | ||
| mkdir -p "$snap/repos/$rel" | ||
| link=() | ||
| if [[ -n $previous && -d $previous/repos/$rel ]]; then link=(--link-dest="$previous/repos/$rel"); fi | ||
| if ! flock -x -w "$lock_wait" "$repo" rsync -a --delete "${link[@]}" "$repo/" "$snap/repos/$rel/"; then | ||
| if [[ ! -e $repo ]]; then | ||
| say "$rel was deleted during the backup; skipped" | ||
| rm -rf "${snap:?}/repos/$rel" | ||
| continue | ||
| fi | ||
| die "copying $rel failed (or a push held it for over ${lock_wait}s)" | ||
| fi | ||
| count=$((count + 1)) | ||
| done < <(find "$repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0 | sort -z) | ||
| # The SSH keys and the web sign-in (whose authenticator secret makes this backup sensitive). | ||
| for pair in "$keys_dir:etc-gitv" "$web_dir:gitv-web"; do | ||
| from=${pair%:*} to=${pair##*:} | ||
| if [[ -d $from ]]; then | ||
| copy "$from/" "$snap/$to/" "$to" || die "copying $from failed" | ||
| else | ||
| say "warning: $from doesn't exist; not backed up" | ||
| fi | ||
| done | ||
| # Prove the copies are whole: every ref and reflog entry must reach complete history. | ||
| failed=0 | ||
| while IFS= read -r -d '' copy_dir; do | ||
| if ! env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$copy_dir" fsck --no-progress --connectivity-only >/dev/null 2>"$base/fsck.err"; then | ||
| say "fsck failed for ${copy_dir#"$snap"/repos/}: $(head -c 2000 "$base/fsck.err")" | ||
| failed=$((failed + 1)) | ||
| fi | ||
| done < <(find "$snap/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0) | ||
| rm -f "$base/fsck.err" | ||
| { | ||
| echo "snapshot: $stamp" | ||
| echo "host: $(hostname)" | ||
| echo "repositories: $count" | ||
| echo "previous: ${previous:+$(basename "$previous")}" | ||
| echo "$(git --version)" | ||
| } >"$snap/MANIFEST" | ||
| if ((failed)); then | ||
| mv "$snap" "$snapshots/$stamp.failed" | ||
| die "$failed repositories failed verification; kept as $stamp.failed, latest is unchanged" | ||
| fi | ||
| mv "$snap" "$snapshots/$stamp" | ||
| ln -sfn "snapshots/$stamp" "$base/latest" | ||
| say "snapshot $stamp: $count repositories" | ||
| # Retention: snapshots older than keep_days, never the newest. | ||
| find "$snapshots" -mindepth 1 -maxdepth 1 -type d -mtime +"$keep_days" ! -name "$stamp" -print0 | | ||
| while IFS= read -r -d '' old; do | ||
| rm -rf "$old" && say "removed old snapshot $(basename "$old")" | ||
| done | ||
+23−0
| @@ -0,0 +1,23 @@ | ||
| [Unit] | ||
| Description=Snapshot GITv repositories, keys and web sign-in to the backup volume | ||
| RequiresMountsFor=/mnt/gitv-backup | ||
| [Service] | ||
| Type=oneshot | ||
| Environment=GITV_BACKUP_DIR=/mnt/gitv-backup | ||
| ExecStart=/usr/local/sbin/gitv-backup | ||
| Nice=10 | ||
| IOSchedulingClass=idle | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ReadWritePaths=/mnt/gitv-backup | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| PrivateNetwork=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| # Read every repository and private folder, and keep owners and modes in the copies. | ||
| CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH CAP_CHOWN CAP_FOWNER | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| [Unit] | ||
| Description=Daily GITv backup | ||
| [Timer] | ||
| OnCalendar=*-*-* 02:30 | ||
| RandomizedDelaySec=30m | ||
| Persistent=true | ||
| [Install] | ||
| WantedBy=timers.target | ||
deploy/gitv-restoreAdded
+62−0
| @@ -0,0 +1,62 @@ | ||
| #!/bin/bash | ||
| # Restore a gitv-backup snapshot into an empty directory and verify it there. It never writes | ||
| # into the live tree: move what you need into place afterwards (see the README's recovery steps). | ||
| # | ||
| # gitv-restore list the snapshots, newest last | ||
| # gitv-restore <snapshot|latest> DIR copy it to DIR (which must be empty or absent) and check it | ||
| # gitv-restore check restore latest to a scratch folder on the volume, check | ||
| # it, and remove it: a drill proving backups restore | ||
| # | ||
| # GITV_BACKUP_DIR as for gitv-backup. | ||
| set -euo pipefail | ||
| umask 077 | ||
| base=${GITV_BACKUP_DIR:-/mnt/gitv-backup}/gitv | ||
| say() { echo "gitv-restore: $*" >&2; } | ||
| die() { say "$*"; exit 1; } | ||
| snapshot_dir() { | ||
| local name=$1 | ||
| [[ $name == latest ]] && name=$(basename "$(readlink -f "$base/latest" 2>/dev/null || true)") | ||
| [[ $name =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{6}Z$ ]] || die "no such snapshot: $1 (see: gitv-restore list)" | ||
| [[ -d $base/snapshots/$name ]] || die "no such snapshot: $name" | ||
| echo "$base/snapshots/$name" | ||
| } | ||
| # Copy a snapshot to an empty target with owners and modes kept, then fsck every repository. | ||
| restore() { | ||
| local from=$1 to=$2 | ||
| if [[ -e $to ]] && [[ -n $(ls -A "$to") ]]; then die "$to isn't empty"; fi | ||
| mkdir -p "$to" | ||
| rsync -a "$from/" "$to/" | ||
| local count=0 failed=0 repo | ||
| while IFS= read -r -d '' repo; do | ||
| count=$((count + 1)) | ||
| if ! env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$repo" fsck --no-progress --full >/dev/null; then | ||
| say "fsck failed for ${repo#"$to"/repos/}" | ||
| failed=$((failed + 1)) | ||
| fi | ||
| done < <(find "$to/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0) | ||
| ((failed == 0)) || die "$failed of $count repositories failed fsck" | ||
| say "restored $(basename "$from") to $to: $count repositories verified" | ||
| } | ||
| case ${1:-} in | ||
| list) | ||
| ls -1 "$base/snapshots" | ||
| ;; | ||
| check) | ||
| scratch=$base/restore-check | ||
| rm -rf "$scratch" | ||
| trap 'rm -rf "$scratch"' EXIT | ||
| restore "$(snapshot_dir latest)" "$scratch" | ||
| ;; | ||
| "" | -h | --help) | ||
| sed -n '2,10p' "$0" | ||
| ;; | ||
| *) | ||
| [[ $# == 2 ]] || die "usage: gitv-restore <snapshot|latest> DIR" | ||
| restore "$(snapshot_dir "$1")" "$2" | ||
| ;; | ||
| esac | ||
+22−0
| @@ -0,0 +1,22 @@ | ||
| [Unit] | ||
| Description=Prove the latest GITv backup restores: copy it out and fsck every repository | ||
| RequiresMountsFor=/mnt/gitv-backup | ||
| [Service] | ||
| Type=oneshot | ||
| Environment=GITV_BACKUP_DIR=/mnt/gitv-backup | ||
| ExecStart=/usr/local/sbin/gitv-restore check | ||
| Nice=10 | ||
| IOSchedulingClass=idle | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ReadWritePaths=/mnt/gitv-backup | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| PrivateNetwork=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH CAP_CHOWN CAP_FOWNER | ||
+9−0
| @@ -0,0 +1,9 @@ | ||
| [Unit] | ||
| Description=Weekly GITv restore drill | ||
| [Timer] | ||
| OnCalendar=Sun *-*-* 04:00 | ||
| Persistent=true | ||
| [Install] | ||
| WantedBy=timers.target | ||
+14−1
| @@ -614,6 +614,16 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> { | ||
| command.env("GIT_PROTOCOL", protocol); | ||
| } | ||
| let pushing = program == "git-receive-pack"; | ||
| // A push holds the repository's lock shared from its first look at the refs until HEAD is | ||
| // settled, so a backup (which holds it exclusive) copies before the push or after it. | ||
| let _lock = if pushing { | ||
| Some(repo.lock(false).map_err(|e| { | ||
| log_operator(&format!("{owner}/{name}.git: couldn't lock for a push: {e}")); | ||
| "repository unavailable".to_string() | ||
| })?) | ||
| } else { | ||
| None | ||
| }; | ||
| let before = if pushing { | ||
| // Every ref update gets a reflog entry (bare repositories keep none by default), and | ||
| // objects nothing refers to any more stay as long as those entries do. Given through | ||
| @@ -643,10 +653,13 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> { | ||
| /// Configuration every push runs with, so overwritten or deleted history can be recovered for | ||
| /// [`TRASH_DAYS`]: reflogs on every ref, and unreachable objects kept as long as their entries. | ||
| const RECOVERY_CONFIG: [(&str, &str); 3] = [ | ||
| /// The gc a push may trigger runs within the push rather than detached, so it finishes under | ||
| /// the push's lock too. | ||
| const RECOVERY_CONFIG: [(&str, &str); 4] = [ | ||
| ("core.logAllRefUpdates", "always"), | ||
| ("gc.reflogExpireUnreachable", "30.days.ago"), | ||
| ("gc.pruneExpire", "30.days.ago"), | ||
| ("gc.autoDetach", "false"), | ||
| ]; | ||
| /// Where each repository records its pushes' ref changes. Git drops a branch's reflog when the | ||
+9−0
| @@ -128,6 +128,15 @@ impl RepoDir { | ||
| pub fn handle(&self) -> BorrowedFd<'_> { | ||
| self.fd.as_fd() | ||
| } | ||
| /// Lock the repository directory itself, waiting for any conflicting holder. Pushes hold it | ||
| /// shared; a backup holds it exclusive (`flock -x <repo>`) so it never copies a push half | ||
| /// written. Released when the returned lock is dropped. | ||
| pub fn lock(&self, exclusive: bool) -> nix::Result<nix::fcntl::Flock<OwnedFd>> { | ||
| let fd = self.fd.try_clone().map_err(|e| nix::errno::Errno::from_raw(e.raw_os_error().unwrap_or(0)))?; | ||
| let kind = if exclusive { nix::fcntl::FlockArg::LockExclusive } else { nix::fcntl::FlockArg::LockShared }; | ||
| nix::fcntl::Flock::lock(fd, kind).map_err(|(_, e)| e) | ||
| } | ||
| } | ||
| /// A command that starts inside the open directory `dir`. The command owns its own duplicate | ||
tests/backup.rsAdded
+177−0
| @@ -0,0 +1,177 @@ | ||
| //! `deploy/gitv-backup` and `deploy/gitv-restore`, run against a scratch installation. | ||
| mod common; | ||
| use std::fs; | ||
| use std::os::unix::fs::MetadataExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, Output}; | ||
| use std::time::Duration; | ||
| use common::{Host, git, scratch, stderr}; | ||
| const BACKUP: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/deploy/gitv-backup"); | ||
| const RESTORE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/deploy/gitv-restore"); | ||
| /// A host with a web sign-in folder, and somewhere for its backups. | ||
| struct Setup { | ||
| host: Host, | ||
| backups: PathBuf, | ||
| web: PathBuf, | ||
| } | ||
| impl Setup { | ||
| fn new(name: &str) -> Setup { | ||
| let host = Host::new(name); | ||
| let web = host.dir.join("web"); | ||
| fs::create_dir_all(&web).unwrap(); | ||
| fs::write(web.join("login"), "user=Um9i\n").unwrap(); | ||
| fs::write(&host.keys, "restrict,command=\"gitv serve ada\" ssh-ed25519 AAAA\n").unwrap(); | ||
| let backups = host.dir.join("backups"); | ||
| Setup { host, backups, web } | ||
| } | ||
| fn run(&self, script: &str, args: &[&str]) -> Output { | ||
| Command::new(script) | ||
| .args(args) | ||
| .env("GITV_REPOS", &self.host.repos) | ||
| .env("GITV_KEYS", &self.host.keys) | ||
| .env("GITV_WEB_AUTH", self.web.join("login")) | ||
| .env("GITV_BACKUP_DIR", &self.backups) | ||
| .env("GITV_BACKUP_REQUIRE_MOUNT", "0") | ||
| .env("GITV_BACKUP_LOCK_WAIT", "1") | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| fn backup(&self) -> Output { | ||
| // Snapshots are named by the second. | ||
| std::thread::sleep(Duration::from_millis(1100)); | ||
| self.run(BACKUP, &[]) | ||
| } | ||
| fn latest(&self) -> PathBuf { | ||
| fs::canonicalize(self.backups.join("gitv/latest")).unwrap() | ||
| } | ||
| fn push(&self, work: &Path, name: &str) { | ||
| let out = self.host.git(work, &["push", "-q", &format!("ada@x:ada/{name}.git"), "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| } | ||
| fn work(name: &str) -> PathBuf { | ||
| let dir = scratch(name); | ||
| git(&dir, &["init", "-q", "-b", "main"]); | ||
| fs::write(dir.join("a.txt"), "one\n").unwrap(); | ||
| git(&dir, &["add", "."]); | ||
| git(&dir, &["commit", "-qm", "First"]); | ||
| dir | ||
| } | ||
| fn commit(dir: &Path, message: &str) { | ||
| fs::write(dir.join("a.txt"), format!("{message}\n")).unwrap(); | ||
| git(dir, &["commit", "-qam", message]); | ||
| } | ||
| #[test] | ||
| fn snapshots_hold_everything_and_restore_whole() { | ||
| let setup = Setup::new("backup-whole"); | ||
| let work = work("backup-whole-work"); | ||
| setup.push(&work, "project"); | ||
| setup.push(&work, "old"); | ||
| assert!(setup.host.admin(&["visibility", "ada", "project", "public"]).status.success()); | ||
| assert!(setup.host.admin(&["delete", "ada", "old", "--yes"]).status.success()); | ||
| assert!(setup.host.admin(&["create", "ada", "empty"]).status.success()); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let first = setup.latest(); | ||
| let repo = first.join("repos/ada/project.git"); | ||
| assert!(repo.join("gitv-public").is_file(), "visibility is kept"); | ||
| assert!(repo.join("gitv-push.log").is_file(), "the push log is kept"); | ||
| assert!(first.join("repos/ada/empty.git/HEAD").is_file(), "empty repositories are kept"); | ||
| assert_eq!(fs::read_dir(first.join("repos/ada/.trash")).unwrap().count(), 1, "the trash is kept"); | ||
| assert!(fs::read_to_string(first.join("etc-gitv/authorized_keys")).unwrap().contains("ssh-ed25519")); | ||
| assert_eq!(fs::read_to_string(first.join("gitv-web/login")).unwrap(), "user=Um9i\n"); | ||
| assert!(fs::read_to_string(first.join("MANIFEST")).unwrap().contains("repositories: 2")); | ||
| // The next snapshot shares unchanged files with this one. | ||
| commit(&work, "Second"); | ||
| setup.push(&work, "project"); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let second = setup.latest(); | ||
| assert_ne!(first, second); | ||
| let objects = |root: &Path| root.join("repos/ada/project.git/objects"); | ||
| let first_commit = git(&work, &["rev-parse", "HEAD~1"]); | ||
| let loose = format!("{}/{}", &first_commit[..2], &first_commit[2..]); | ||
| assert_eq!( | ||
| fs::metadata(objects(&first).join(&loose)).unwrap().ino(), | ||
| fs::metadata(objects(&second).join(&loose)).unwrap().ino(), | ||
| "an unchanged object is a hard link, not a second copy" | ||
| ); | ||
| // Restoring gives a working repository at the newest state, and refuses to overwrite. | ||
| let target = scratch("backup-whole-restored"); | ||
| let out = setup.run(RESTORE, &["latest", target.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("2 repositories verified"), "{}", stderr(&out)); | ||
| assert_eq!(git(&target.join("repos/ada/project.git"), &["log", "--format=%s", "main"]), "Second\nFirst"); | ||
| assert!(!setup.run(RESTORE, &["latest", target.to_str().unwrap()]).status.success(), "a full target is refused"); | ||
| assert!(!setup.run(RESTORE, &["../../etc", "/tmp/x"]).status.success(), "snapshot names are validated"); | ||
| let out = setup.run(RESTORE, &["check"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv/restore-check").exists(), "the drill cleans up"); | ||
| } | ||
| #[test] | ||
| fn a_corrupt_repository_fails_the_backup_and_keeps_latest() { | ||
| let setup = Setup::new("backup-corrupt"); | ||
| let work = work("backup-corrupt-work"); | ||
| setup.push(&work, "project"); | ||
| assert!(setup.backup().status.success()); | ||
| let good = setup.latest(); | ||
| // Lose an object the branch needs. | ||
| let tree = git(&work, &["rev-parse", "HEAD^{tree}"]); | ||
| fs::remove_file(setup.host.repo("ada", "project").join(format!("objects/{}/{}", &tree[..2], &tree[2..]))).unwrap(); | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("fsck failed for ada/project.git"), "{}", stderr(&out)); | ||
| assert_eq!(setup.latest(), good, "latest still names the last good snapshot"); | ||
| let failed = fs::read_dir(setup.backups.join("gitv/snapshots")) | ||
| .unwrap() | ||
| .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".failed")) | ||
| .count(); | ||
| assert_eq!(failed, 1); | ||
| } | ||
| #[test] | ||
| fn a_backup_waits_for_a_push_in_progress() { | ||
| let setup = Setup::new("backup-lock"); | ||
| let work = work("backup-lock-work"); | ||
| setup.push(&work, "project"); | ||
| // Hold the lock as a push does; the backup gives up after its (one second) wait. | ||
| let repo = gitv::RepoDir::at(&setup.host.repo("ada", "project")).unwrap(); | ||
| let held = repo.lock(false).unwrap(); | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("held it for over 1s"), "{}", stderr(&out)); | ||
| drop(held); | ||
| assert!(setup.backup().status.success()); | ||
| } | ||
| #[test] | ||
| fn an_unmounted_backup_directory_is_refused() { | ||
| let setup = Setup::new("backup-unmounted"); | ||
| let out = Command::new(BACKUP) | ||
| .env("GITV_REPOS", &setup.host.repos) | ||
| .env("GITV_BACKUP_DIR", &setup.backups) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("not a mounted volume"), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv").exists(), "nothing was written"); | ||
| } | ||