//! `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, ssh: 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(); // Beside the host, not in it: the keys file's folder is backed up whole, and a backup // folder inside it would copy every earlier snapshot into each new one. let backups = scratch(&format!("{name}-backups")); fs::remove_dir(&backups).unwrap(); // Stand-ins for /etc/ssh: host keys, and configuration that isn't backed up. let ssh = scratch(&format!("{name}-ssh")); fs::write(ssh.join("ssh_host_ed25519_key"), "private\n").unwrap(); fs::write(ssh.join("ssh_host_ed25519_key.pub"), "public\n").unwrap(); fs::write(ssh.join("sshd_config"), "Port 22\n").unwrap(); Setup { host, backups, web, ssh } } 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_SSH_DIR", &self.ssh) .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_eq!(fs::read_to_string(first.join("ssh-host-keys/ssh_host_ed25519_key")).unwrap(), "private\n"); assert!(first.join("ssh-host-keys/ssh_host_ed25519_key.pub").is_file()); assert!(!first.join("ssh-host-keys/sshd_config").exists(), "only the host keys are kept"); let manifest = fs::read_to_string(first.join("MANIFEST")).unwrap(); assert!(manifest.contains("repositories: 2")); assert!(!manifest.contains("stale") && !manifest.contains("missing"), "a clean snapshot reports no problems"); // 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"); // A bad name is refused before anything is copied: the target is never even created. let elsewhere = setup.host.dir.join("not-restored"); for name in ["../../etc", "2026-01-01T000000Z", ""] { let out = setup.run(RESTORE, &[name, elsewhere.to_str().unwrap()]); assert!(!out.status.success(), "{name:?} was restored"); assert!(!elsewhere.exists(), "{name:?} copied something"); } 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_push_in_progress_keeps_its_last_copy_without_holding_up_the_rest() { let setup = Setup::new("backup-lock"); let work = work("backup-lock-work"); setup.push(&work, "busy"); setup.push(&work, "other"); // Hold the lock as a push does; the backup gives up on it after its (one second) wait. let repo = gitv_core::RepoDir::at(&setup.host.repo("ada", "busy")).unwrap(); let held = repo.lock(false).unwrap(); // Never backed up before: there is no copy to keep, but the other repository is backed up. let out = setup.backup(); assert!(!out.status.success(), "an incomplete backup must fail"); assert!(stderr(&out).contains("ada/busy.git for over 1s, and no earlier snapshot"), "{}", stderr(&out)); let first = setup.latest(); assert!(first.join("repos/ada/other.git/HEAD").is_file(), "the other repository was backed up"); assert!(!first.join("repos/ada/busy.git").exists()); assert!(fs::read_to_string(first.join("MANIFEST")).unwrap().contains("never backed up): ada/busy.git")); drop(held); // Backed up once, then held again while it moves on: the snapshot keeps the earlier copy. let out = setup.backup(); assert!(out.status.success(), "{}", stderr(&out)); let good = setup.latest(); commit(&work, "Second"); setup.push(&work, "busy"); setup.push(&work, "other"); let held = repo.lock(false).unwrap(); let out = setup.backup(); assert!(!out.status.success()); assert!(stderr(&out).contains("kept its copy from"), "{}", stderr(&out)); let latest = setup.latest(); assert_ne!(latest, good, "everything else still moves on"); let tip = |root: &Path, name: &str| git(&root.join(format!("repos/ada/{name}.git")), &["log", "-1", "--format=%s"]); assert_eq!(tip(&latest, "busy"), "First", "the held repository is its last good copy"); assert_eq!(tip(&latest, "other"), "Second"); let head = |root: &Path| fs::metadata(root.join("repos/ada/busy.git/HEAD")).unwrap().ino(); assert_eq!(head(&latest), head(&good), "the kept copy is hard links, not a second copy"); drop(held); let out = setup.backup(); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(tip(&setup.latest(), "busy"), "Second"); } #[test] fn latest_is_replaced_in_one_step() { let setup = Setup::new("backup-latest"); let work = work("backup-latest-work"); setup.push(&work, "project"); // A leftover from a run that crashed between making the new link and renaming it. fs::create_dir_all(setup.backups.join("gitv")).unwrap(); std::os::unix::fs::symlink("snapshots/gone", setup.backups.join("gitv/.latest.new")).unwrap(); assert!(setup.backup().status.success()); assert!(setup.latest().join("MANIFEST").is_file()); assert!(fs::symlink_metadata(setup.backups.join("gitv/.latest.new")).is_err(), "nothing is left beside it"); } #[test] fn a_restore_check_without_snapshots_copies_nothing() { let setup = Setup::new("backup-none"); fs::create_dir_all(setup.backups.join("gitv/snapshots")).unwrap(); let out = setup.run(RESTORE, &["check"]); assert!(!out.status.success()); assert!(stderr(&out).contains("no such snapshot"), "{}", stderr(&out)); assert!(!setup.backups.join("gitv/restore-check").exists(), "nothing was copied"); } #[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"); } #[test] fn one_repository_comes_back_from_a_snapshot_after_its_trash_is_purged() { let setup = Setup::new("backup-one"); let host = &setup.host; let work = work("backup-one-work"); git(&work, &["branch", "release"]); git(&work, &["tag", "-a", "v1", "-m", "One"]); git(&work, &["tag", "light"]); let out = host.git(&work, &["push", "-q", "ada@x:ada/tools.git", "main", "release", "v1", "light"]); assert!(out.status.success(), "{}", stderr(&out)); for args in [ &["visibility", "ada", "tools", "public"][..], &["default-branch", "ada", "tools", "release"], &["description", "ada", "tools", "Tools for ada"], ] { let out = host.admin(args); assert!(out.status.success(), "{args:?}: {}", stderr(&out)); } let refs = |repo: &Path| git(repo, &["for-each-ref", "--format=%(objectname) %(refname)"]); let before = refs(&host.repo("ada", "tools")); assert_eq!(before.lines().count(), 4, "{before}"); let out = setup.backup(); assert!(out.status.success(), "{}", stderr(&out)); let snapshot = setup.latest().file_name().unwrap().to_str().unwrap().to_string(); // Deleted, purged from the trash, and the name since taken by a new repository. assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); let out = host.admin(&["purge", "--older-than-days", "0"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(fs::read_dir(host.repos.join("ada/.trash")).unwrap().count(), 0, "the trash was purged"); assert!(host.admin(&["create", "ada", "tools"]).status.success()); let out = setup.run(RESTORE, &["find", "ada/tools"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), snapshot); assert!(!setup.run(RESTORE, &["find", "ada/missing"]).status.success()); let target = scratch("backup-one-restored"); let out = setup.run(RESTORE, &["latest", target.to_str().unwrap(), "ada/tools"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(stderr(&out).contains("gitv import ada tools"), "{}", stderr(&out)); let restored = target.join("tools.git"); assert_eq!(fs::read_dir(&target).unwrap().count(), 1, "only that repository was copied"); // The new repository at the name is never replaced. let out = host.admin(&["import", "ada", "tools", restored.to_str().unwrap()]); assert!(!out.status.success()); assert!(stderr(&out).contains("already exists"), "{}", stderr(&out)); assert_eq!(refs(&host.repo("ada", "tools")), "", "the new repository is untouched"); let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")) .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .filter(|n| n.starts_with(".create")) .collect(); assert!(leftovers.is_empty(), "{leftovers:?}"); // Under another name it comes back whole: refs, default branch, visibility, description. let out = host.admin(&["import", "ada", "tools-restored", restored.to_str().unwrap()]); assert!(out.status.success(), "{}", stderr(&out)); let back = host.repo("ada", "tools-restored"); assert_eq!(refs(&back), before); assert_eq!(git(&back, &["symbolic-ref", "HEAD"]), "refs/heads/release"); assert!(back.join("gitv-public").is_file(), "still public"); assert_eq!(fs::read_to_string(back.join("description")).unwrap(), "Tools for ada\n"); let out = host.ssh("ada", "list"); assert!(String::from_utf8_lossy(&out.stdout).contains("ada/tools-restored.git")); let clone = scratch("backup-one-clone"); let out = host.git(&clone, &["clone", "-q", "ada@x:ada/tools-restored.git", "copy"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "release"); // Names that aren't OWNER/NAME, and repositories a snapshot doesn't hold, copy nothing. let elsewhere = host.dir.join("not-restored"); for repo in ["ada/../etc", "ada", "ada/tools/x", "Ada/tools", "ada/missing"] { let out = setup.run(RESTORE, &["latest", elsewhere.to_str().unwrap(), repo]); assert!(!out.status.success(), "{repo} was restored"); assert!(!elsewhere.exists(), "{repo} copied something"); } // Only a bare repository is imported. let out = host.admin(&["import", "ada", "other", work.to_str().unwrap()]); assert!(!out.status.success(), "a working copy was imported"); assert!(!host.repo("ada", "other").exists()); }