From 6f174f3f87d2bf542f141bbabe1f69046541d9b2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 16:31:58 -0700 Subject: [PATCH] fix(store): git is told to end before it is killed, and nothing in the owner's backup folder is ever deleted A stopped git was killed outright and the program then removed lock files: in the archive every lock found, in a folder target any lock new since the push whose mtime held still for 1.5 s. Git does not touch a lock it is holding, so an unchanged mtime does not prove a lock stale: another git (the owner's, another machine's on a shared disk, a sync client's) stalled in a hook or an fsync loses its lock to that rule, and two ref updates race. The removal also re-resolved the repository and refs paths, so a folder swapped for a link redirected it. Now: SIGTERM goes to the git's process group first (git removes its own locks on SIGTERM, a push's receiving end its quarantine), TERM_GRACE (3 s) is waited for the group to end, and only then SIGKILL. A folder target is never written to or deleted from except by git: a lock our kill left there is left, noted with its whole path, and the push fails with LockLeft, which tells the owner which file to remove and that it is only safe once nothing else uses the folder. The archive keeps only two removals: the locks our own stopped git made (not there when the command began), and at open and at the start of a backup a lock older than ten minutes. Removals go through a directory handle opened once, never follow links, and take only regular files named as git names its locks (git_locks.rs). Tests use real git: SIGTERM mid-commit, mid-add and mid-push leaves no lock and no cleanup; a frozen group (SIGSTOP, so SIGTERM stays pending) is killed after the grace and the archive's locks go while the target's stay and are named; a git that traps SIGTERM is killed after the grace; fsck --strict on both repositories right after a stop during a 48 MiB pack's receipt; the archive's age rule; a swapped refs folder or archive path touches nothing outside. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-store/src/backup.rs | 1184 +++++++++++++++++++------- crates/ledger-store/src/git_locks.rs | 561 ++++++++++++ crates/ledger-store/src/lib.rs | 1 + 3 files changed, 1427 insertions(+), 319 deletions(-) create mode 100644 crates/ledger-store/src/git_locks.rs diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs index 6fafa93b..62ac531e 100644 --- a/crates/ledger-store/src/backup.rs +++ b/crates/ledger-store/src/backup.rs @@ -51,51 +51,61 @@ //! root.rs). None of ours starts another git to go on after it ends //! (`gc.auto=0`, `maintenance.auto=false`): when a git of ours has //! ended, nothing it began is still working. -//! 5. A git killed (cancelled, or silent for GIT_TIMEOUT) can leave lock -//! files, and none that is stale is left for a person to remove. Once -//! the killed command is reaped AND every process it started is gone -//! (a killed process can still take a lock in its last instructions, -//! so the process group is waited for, GROUP_GONE_WAIT, and nothing -//! is removed while it isn't), the locks in the repositories that -//! command could write are dealt with, each noted ([`LockNote`], for -//! the caller's record): -//! (A killed `init` of the archive, or of a folder target's new +//! 5. A git that is stopped (cancelled, or silent for GIT_TIMEOUT) is +//! stopped gently: SIGTERM to its whole process group first (git +//! removes the lock files it holds when it is sent one, and a push's +//! receiving end the objects it had not yet kept), up to TERM_GRACE +//! (3 s: git's handler takes milliseconds, so the grace is only for a +//! machine too loaded to schedule it) for the group to end, and only +//! then SIGKILL. So a lock left behind is the rare case, and there is +//! nothing to clean up in the usual one. (Windows has no signal to +//! send a group: the nearest thing the code has, `taskkill /T /F`, +//! ends the tree at once, and the rules below cover what is left.) +//! Once the stopped command is reaped AND every process it started is +//! gone (a killed process can still take a lock in its last +//! instructions, so the process group is waited for, GROUP_GONE_WAIT, +//! and nothing is looked at as left over while it isn't), the locks in +//! the repositories that command could write are dealt with, each +//! noted ([`LockNote`], for the caller's record). Each repository is +//! looked at as the command begins (its folder opened once, the locks +//! already there listed); "ours" is a lock that wasn't there then. +//! (A stopped `init` of the archive, or of a folder target's new //! repository, is such a command too: its HEAD lock is dealt with //! the same way.) -//! a. The book's own archive: every lock in it is removed at once. -//! This process holds the book's store lock (the caller's duty: -//! it is the only holder of the lock that lets a git run on the -//! archive, and runs one git at a time on it), so no other -//! wanderbooks process can be running git on it, and the one of -//! ours that could have made a lock is the one just killed. The -//! same holds when the book opens (`clear_archive_locks`, called -//! with the store open): a lock found then is a dead git's (the -//! server killed, a power cut). +//! a. The book's own archive (`archive.git` in the book's folder, +//! private to this program): the locks of ours are removed once +//! the group is gone, each noted. Nothing else is removed from +//! it in a stop. At open (`clear_archive_locks`), and when a +//! backup begins, only a lock older than ARCHIVE_STALE (10 +//! minutes) is removed, each removal noted; a younger one is +//! left (the next backup tries again, and removes it once it is +//! old). Running git by hand inside the archive is unsupported: +//! only the store lock keeps another wanderbooks process out, and +//! what protects the archive from one that doesn't is that this +//! code never removes a lock younger than ARCHIVE_STALE except +//! one that its own stopped git made (a lock a person's git +//! holds that long is the person's to deal with). //! b. A target on this computer (a folder, or a repository named by //! a path): its git is our `receive-pack`, a child of the one -//! killed. What may write the folder is, by what this code and -//! D-30 allow, this book's backups (one push at a time, one -//! process per book by the store lock) and nothing else; but the -//! folder is the owner's (an external disk, a synced folder such -//! as Syncthing's) and the code cannot enforce that no other -//! computer, no other data root backing up a book of the same -//! id, and no hand of the owner's pushes to it too (the only -//! guard is INVARIANT 2: a push that finds it moved reports it -//! and forces nothing). So a lock there is removed only if ALL -//! hold: our command was killed and everything it started is -//! gone; the lock was NOT there when the push began (one that was -//! belongs to someone else, or to an earlier crash we can't tell -//! from it: it is left, and noted as left); and it has stood -//! unchanged for LOCK_SETTLE after the kill (a live writer holds -//! a ref lock for the milliseconds of a ref update, so a lock -//! still there, unchanged, that long is a dead writer's). What -//! this cannot see: a second writer that took the same lock -//! during our push and then stalled, holding it, past LOCK_SETTLE -//! (a hung disk or sync). That writer is outside what the -//! product supports, and the lock is the one a push of theirs -//! would also fail on. A repository far away (ssh, https) is -//! never touched: its receiving end cleans up when the -//! connection ends. +//! stopped. This program NEVER writes to, or deletes from, a +//! folder that is the owner's (an external disk, a synced folder +//! such as Syncthing's, shared with other computers and other +//! gits): only git itself does. A lock git left there when it +//! had to be killed, that wasn't there when the push began, is +//! left in place and reported with its whole path: a note +//! (`lock_left`), and [`BackupError::LockLeft`], which marks the +//! target's backup failed and names the files and what the owner +//! may do (remove them, only when nothing else is using the +//! backup folder). A lock that was there when the push began is +//! another's: untouched, and not named. A later backup that finds +//! the lock gone goes on normally. A repository far away (ssh, +//! https) is never looked at: its receiving end cleans up when +//! the connection ends. +//! c. No removal follows a path. A removal goes through the folder +//! handle opened and verified once, when the command began (it is +//! the archive in the book's folder, not a link; git_locks), never +//! follows a link, and removes only a regular file named as git +//! names its locks, in the places git puts them. //! 6. A step that has to end when the books are let go (the caller's //! cancel flag, [`Git::with_cancel`]) ends promptly, wherever it is, //! and leaves nothing half-made: it looks for the flag between every @@ -106,8 +116,8 @@ //! running is killed. A stopped drill or proof removes its scratch //! clone (the one removal that is not itself stopped: it is as long //! as the clone is big). The longest between two looks is one git -//! command's kill (a signal, GROUP_GONE_WAIT, and up to 10 s for its -//! pipes), one journal line, one file, or one 64 KiB chunk. +//! command's stop (SIGTERM and up to TERM_GRACE, then a kill, GROUP_GONE_WAIT, +//! and up to 10 s for its pipes), one journal line, one file, or one 64 KiB chunk. //! ``` use std::path::{Path, PathBuf}; @@ -124,8 +134,17 @@ pub const BACKED_UP: [&str; 5] = [ crate::root::KEYS_DIR, crate::access::ACCESS_FILE, ]; -/// The longest a git command may take before it is stopped. +/// The longest a git command may say nothing before it is stopped. pub const GIT_TIMEOUT: Duration = Duration::from_secs(300); +/// How long a git that is to be stopped is given, after SIGTERM, to end +/// (and so remove its own lock files) before its whole process group is +/// killed (INVARIANT 5). Git's handler takes milliseconds; this is for a +/// machine so loaded that the handler is slow to be scheduled. +pub const TERM_GRACE: Duration = Duration::from_secs(3); +/// How old a lock in the book's own archive must be, at open and when a +/// backup begins, before it is taken for a dead git's (INVARIANT 5a): a +/// younger one is left, and the next backup tries again. +pub const ARCHIVE_STALE: Duration = Duration::from_secs(600); /// Why a backup couldn't be made, pushed or trusted. Never names a path of /// the data root (INVARIANT 4). @@ -145,6 +164,14 @@ pub enum BackupError { /// ([`Git::with_cancel`]). #[error("git {0} was stopped: the books are closing")] Cancelled(String), + /// A git of ours was stopped while it was writing a backup folder (or a + /// repository on this computer), and left lock files there (every one + /// named, whole paths, separated by `, `), which this program never + /// removes from a place that is the owner's (INVARIANT 5b). + #[error( + "git was stopped while it was writing the backup, and left lock files in your backup folder: {0}. This program doesn't remove files from your backup folder. Remove those files (only those), and only when nothing else is using the backup folder (another computer, a sync program, git run by hand); the next backup then goes on" + )] + LockLeft(String), /// A folder target that isn't there (an external disk not mounted). #[error("the backup folder isn't there (is its disk connected?)")] NoFolder, @@ -182,11 +209,13 @@ pub struct LockNote { /// The lock, as a path in the repository (`index.lock`, /// `refs/heads/main.lock`). pub lock: String, - /// Removed (stale by construction), or left (it could be a live - /// writer's). + /// Removed (the archive's, made by the git just stopped), or left. pub removed: bool, /// Why: what ended the git that made it, or why it was left. pub why: &'static str, + /// For a lock left in a folder that is the owner's: its whole path, the + /// file the owner is told to remove (INVARIANT 5b). + pub path: Option, } /// A watcher of a verification's phases ([`Git::with_phase_watch`]). @@ -217,6 +246,9 @@ pub struct Git { /// Set by whoever serves the books when they are let go: a git /// command running is stopped, with what it started, and none starts. cancel: Option>, + /// How long a git that is to be stopped has to end after SIGTERM + /// before it is killed (TERM_GRACE). + term_grace: Duration, watch: Watch, } @@ -250,11 +282,20 @@ impl Git { exe, quiet: GIT_TIMEOUT, cancel: None, + term_grace: TERM_GRACE, watch: Watch::default(), }) .ok_or(BackupError::NoGit) } + /// This git, given `grace` (not TERM_GRACE) to end after SIGTERM before + /// it is killed (a seam for tests). + #[must_use] + pub fn with_term_grace(mut self, grace: Duration) -> Self { + self.term_grace = grace; + self + } + /// This git, stopped (every command running, and any that would /// start) once `cancel` is set: how the server's close ends a backup /// that is still going, instead of leaving it to run against books it @@ -416,18 +457,29 @@ impl Git { } /// [`Self::run`] where every repository the command may write (its - /// `guards`) has its stale locks dealt with once the command was - /// killed and all it started is gone (INVARIANT 5). + /// `guards`) is looked at as the command begins, and has the locks it + /// left dealt with if the command was stopped, once all it started is + /// gone (INVARIANT 5). A stop that left a lock in the owner's folder is + /// said so: [`BackupError::LockLeft`]. fn run_in( &self, what: &str, args: &[&std::ffi::OsStr], guards: &[&Watched], ) -> Result { + let snaps: Vec = guards.iter().map(|g| g.snapshot()).collect(); let (result, killed) = self.run_killed(what, args); if killed != Killed::No { - for guard in guards { - guard.after_kill(self, killed == Killed::Gone); + let mut left = Vec::new(); + for (guard, snap) in guards.iter().zip(&snaps) { + left.extend(guard.after_kill(self, snap, killed == Killed::Gone)); + } + if matches!( + result, + Err(BackupError::Cancelled(_) | BackupError::TimedOut(_)) + ) && !left.is_empty() + { + return Err(BackupError::LockLeft(left.join(", "))); } } result @@ -495,29 +547,18 @@ impl Git { // says of itself, in part. let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _), usize::MAX); let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _), OUTPUT_MAX); - // Git and every process it started (its own group, above). + // Once git has ended normally, what it started is stopped (Unix: + // its group; Windows has no group to signal, and nothing is looked + // for: a process spawned per git call would cost more than the + // leftovers it could find). #[cfg(unix)] - // SAFETY: kill has no preconditions; the group is git's own - // (process_group(0) above), so this stops it and what it started. - let kill_group = |pid: u32| unsafe { - libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + let kill_leftovers = |pid: u32| { + // SAFETY: kill has no preconditions; the group is git's own + // (process_group(0) above). + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + } }; - // Windows has no process group to signal: a git that has gone quiet - // is stopped with the tree of processes it started (`taskkill /T`). - // Once git has ended normally nothing is looked for (a process - // spawned per git call would cost more than the leftovers it could - // find). - #[cfg(windows)] - let kill_group = |pid: u32| { - let _ = std::process::Command::new("taskkill") - .args(["/T", "/F", "/PID", &pid.to_string()]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); - }; - #[cfg(unix)] - let kill_leftovers = kill_group; #[cfg(windows)] let kill_leftovers = |_: u32| {}; let status = loop { @@ -528,17 +569,11 @@ impl Git { .elapsed() .saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed))); if self.cancelled() { - kill_group(child.id()); - let _ = child.kill(); - let _ = child.wait(); - killed.set(group_gone(child.id())); + killed.set(self.stop(&mut child)); return Err(BackupError::Cancelled(what.to_string())); } if quiet_for > self.quiet { - kill_group(child.id()); - let _ = child.kill(); - let _ = child.wait(); - killed.set(group_gone(child.id())); + killed.set(self.stop(&mut child)); return Err(BackupError::TimedOut(what.to_string())); } std::thread::sleep(Duration::from_millis(20)); @@ -557,6 +592,61 @@ impl Git { } } +impl Git { + /// Stop a git that is running, and everything it started (INVARIANT 5): + /// SIGTERM to its process group first (git removes the lock files it + /// holds when it is sent one, and a push's receiving end the objects it + /// had not yet kept), then up to `term_grace` for the group to end, and + /// only then SIGKILL. The leader is reaped as the group is waited for + /// (a zombie is still in its group). What became of the group. + /// + /// Windows has no signal to send a group: the nearest thing the code has + /// is `taskkill /T /F`, which ends the tree at once, so there is no + /// grace there, and no reliance on git's own clean-up: the lock rules + /// (INVARIANT 5) cover what is left. + fn stop(&self, child: &mut std::process::Child) -> Killed { + #[cfg(unix)] + { + let pid = child.id(); + // SAFETY: kill has no preconditions; the group is git's own + // (process_group(0) when it was started). + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGTERM); + } + let by = Instant::now() + self.term_grace; + loop { + let _ = child.try_wait(); + if group_empty(pid) { + return Killed::Gone; + } + if Instant::now() >= by { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + // SAFETY: as above. + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + } + let _ = child.kill(); + let _ = child.wait(); + group_gone(pid) + } + #[cfg(windows)] + { + let _ = std::process::Command::new("taskkill") + .args(["/T", "/F", "/PID", &child.id().to_string()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + let _ = child.kill(); + let _ = child.wait(); + Killed::Gone + } + } +} + /// The most kept of what a git says of itself. const OUTPUT_MAX: usize = 1 << 20; @@ -576,6 +666,14 @@ enum Killed { /// be gone. pub const GROUP_GONE_WAIT: Duration = Duration::from_secs(2); +/// Whether the process group `pid` led has no process left. +#[cfg(unix)] +fn group_empty(pid: u32) -> bool { + // SAFETY: signal 0 only asks whether a process is in the group. + let found = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; + found != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) +} + /// Wait until the process group `pid` led has no process left, for /// GROUP_GONE_WAIT at most: a killed process can run a few more /// instructions before the kernel takes it, and could take a lock in them. @@ -584,9 +682,7 @@ fn group_gone(pid: u32) -> Killed { { let by = Instant::now() + GROUP_GONE_WAIT; loop { - // SAFETY: signal 0 only asks whether a process is in the group. - let found = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; - if found != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { + if group_empty(pid) { return Killed::Gone; } if Instant::now() >= by { @@ -603,48 +699,6 @@ fn group_gone(pid: u32) -> Killed { } } -/// Where the lock files of a repository are (every lock git makes in a -/// bare repository: its own folder, its refs, the pack and info folders of -/// its objects), as paths in it. -fn locks_in(repo: &Path) -> Vec { - fn here(dir: &Path, rel: &str, deep: bool, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for e in entries.flatten() { - let name = e.file_name().to_string_lossy().into_owned(); - let Ok(kind) = e.file_type() else { continue }; - if kind.is_file() && name.ends_with(".lock") { - out.push(format!("{rel}{name}")); - } else if deep && kind.is_dir() { - here(&e.path(), &format!("{rel}{name}/"), true, out); - } - } - } - let mut out = Vec::new(); - here(repo, "", false, &mut out); - here(&repo.join("refs"), "refs/", true, &mut out); - here( - &repo.join("objects").join("info"), - "objects/info/", - false, - &mut out, - ); - here( - &repo.join("objects").join("pack"), - "objects/pack/", - false, - &mut out, - ); - out.sort(); - out -} - -/// How long a lock found in a target after our git was killed must stay -/// there, unchanged, before it is taken for a dead writer's (INVARIANT 5): -/// a live git holds one for the milliseconds of a ref update. -pub const LOCK_SETTLE: Duration = Duration::from_millis(1500); - /// A shared place for the lock files dealt with (see /// [`Git::with_lock_notes`]). #[derive(Clone, Default)] @@ -657,118 +711,183 @@ impl LockNotes { } } -/// A repository a git command may leave locks in when it is killed. +/// A repository a git command may leave locks in when it is stopped. pub struct Watched { dir: PathBuf, /// `archive`, `folder` or `repository`. kind: &'static str, - /// For a target: the locks there when the command began, which are - /// never ours to remove. None for the book's own archive, where every - /// lock is ours (INVARIANT 5). - before: Option>, +} + +/// A repository as it was when a command began: its folder opened once +/// (never again by its path: INVARIANT 5), and the locks already in it. +struct Snapshot { + handle: Option, + before: std::collections::BTreeSet, } impl Watched { - /// The book's own archive: this process holds the book's store lock, so - /// no other process runs git on it, and one killed of ours is the only - /// one that could have left a lock. + /// The book's own archive, `dir` (`/archive.git`): private to + /// this program, one git of ours at a time. fn archive(dir: &Path) -> Self { Self { dir: dir.to_path_buf(), kind: "archive", - before: None, } } - /// A target repository on this computer, looked at before the command - /// that may write it begins. + /// A target repository on this computer, the owner's. fn target(dir: &Path, kind: &'static str) -> Self { Self { dir: dir.to_path_buf(), kind, - before: Some(locks_in(dir).into_iter().collect()), } } - /// The command was killed. Once all it started is `gone`, deal with - /// the locks (INVARIANT 5). - fn after_kill(&self, git: &Git, gone: bool) { - let note = |lock: &str, removed: bool, why: &'static str| { - git.note(LockNote { - repo: self.kind, - lock: lock.to_string(), - removed, - why, - }); - }; - let now = locks_in(&self.dir); - if !gone { - for lock in &now { - note(lock, false, "what git started was still running"); + fn is_archive(&self) -> bool { + self.kind == "archive" + } + + fn open(&self) -> std::io::Result { + if self.is_archive() { + match (self.dir.parent(), self.dir.file_name().and_then(|n| n.to_str())) { + (Some(book), Some(name)) => crate::git_locks::RepoDir::open_in(book, name), + _ => Err(std::io::ErrorKind::InvalidInput.into()), } - return; + } else { + crate::git_locks::RepoDir::open(&self.dir) } - let stamp = |lock: &str| { - std::fs::metadata(self.dir.join(lock)) - .and_then(|m| m.modified()) - .ok() - }; - let Some(before) = &self.before else { - for lock in &now { - if std::fs::remove_file(self.dir.join(lock)).is_ok() { - note(lock, true, "git was stopped"); + } + + /// Looked at as a command begins. + fn snapshot(&self) -> Snapshot { + let handle = self.open().ok(); + let before = handle + .as_ref() + .map(|h| h.locks().into_iter().map(|f| f.lock).collect()) + .unwrap_or_default(); + Snapshot { handle, before } + } + + /// The command was stopped. Once all it started is `gone`, deal with + /// the locks it left (INVARIANT 5): in the archive, remove those that + /// were not there when the command began; in the owner's folder remove + /// nothing, and say so. The whole paths of the locks left there. + fn after_kill(&self, git: &Git, snap: &Snapshot, gone: bool) -> Vec { + // A repository that didn't exist when the command began (a new + // target's, made by an `init` that was stopped) is looked at, never + // changed. The archive is only ever touched through the handle + // opened before the command. + let fresh; + let handle = match (&snap.handle, self.is_archive()) { + (Some(h), _) => h, + (None, true) => return Vec::new(), + (None, false) => match self.open() { + Ok(h) => { + fresh = h; + &fresh } - } - return; + Err(_) => return Vec::new(), + }, }; - // A target: never a lock that was there before our command began. - let mut ours: Vec<(String, Option)> = Vec::new(); - for lock in &now { - if before.contains(lock) { - note(lock, false, "it was there before the push began"); + let mut left = Vec::new(); + for found in handle.locks() { + if snap.before.contains(&found.lock) { + continue; + } + let lock = found.lock; + if self.is_archive() { + if !gone { + git.note(LockNote { + repo: self.kind, + lock, + removed: false, + why: "what git started was still running", + path: None, + }); + } else if handle.remove(&lock).unwrap_or(false) { + git.note(LockNote { + repo: self.kind, + lock, + removed: true, + why: "git was stopped", + path: None, + }); + } } else { - ours.push((lock.clone(), stamp(lock))); + let path = handle.path().join(&lock).display().to_string(); + git.note(LockNote { + repo: self.kind, + lock, + removed: false, + why: if gone { + "git was stopped while it held it: the owner's folder is never changed by this program" + } else { + "what git started was still running" + }, + path: Some(path.clone()), + }); + left.push(path); } } - if ours.is_empty() { - return; - } - // One that a live writer took meanwhile is gone within the - // milliseconds of its ref update; one still there, unchanged, after - // LOCK_SETTLE is a dead writer's, and the only one ours could be. - std::thread::sleep(LOCK_SETTLE); - for (lock, was) in ours { - match stamp(&lock) { - Some(is) if Some(is) == was => { - if std::fs::remove_file(self.dir.join(&lock)).is_ok() { - note(&lock, true, "git was stopped"); - } - } - Some(_) => note(&lock, false, "it changed after git was stopped"), - None => {} + left + } +} + +/// The locks of the book's archive in `book_dir` that are older than +/// ARCHIVE_STALE, removed, each noted in `notes`; and, when `say_young`, +/// each younger one noted as left. The archive is opened once and only +/// regular files named as git names its locks are touched (INVARIANT 5a). +fn clear_stale_archive_locks( + book_dir: &Path, + removed_why: &'static str, + young: Option<&'static str>, + notes: &mut Vec, +) { + let Ok(handle) = crate::git_locks::RepoDir::open_in(book_dir, ARCHIVE_DIR) else { + return; + }; + let now = std::time::SystemTime::now(); + for found in handle.locks() { + let old = found + .modified + .and_then(|t| now.duration_since(t).ok()) + .is_some_and(|age| age >= ARCHIVE_STALE); + if old { + if handle.remove(&found.lock).unwrap_or(false) { + notes.push(LockNote { + repo: "archive", + lock: found.lock, + removed: true, + why: removed_why, + path: None, + }); } + } else if let Some(why) = young { + notes.push(LockNote { + repo: "archive", + lock: found.lock, + removed: false, + why, + path: None, + }); } } } /// The locks a git of ours left in the book's archive at an earlier time /// (killed with the server, a power cut), for the caller to say it removed -/// them. Call it only while this process holds the book's store lock: no -/// other wanderbooks process can then be running git on the archive, and no -/// git of this process's is, so every lock in it is stale (INVARIANT 5). +/// them: those older than ARCHIVE_STALE are removed, younger ones are left +/// and noted as left (the next backup tries again, and removes them once +/// they are old). Call it while this process holds the book's store lock: +/// no other wanderbooks process runs git on the archive (INVARIANT 5a). pub fn clear_archive_locks(book_dir: &Path) -> Vec { - let archive = book_dir.join(ARCHIVE_DIR); let mut notes = Vec::new(); - for lock in locks_in(&archive) { - if std::fs::remove_file(archive.join(&lock)).is_ok() { - notes.push(LockNote { - repo: "archive", - lock, - removed: true, - why: "found when the books opened", - }); - } - } + clear_stale_archive_locks( + book_dir, + "found when the books opened, older than ten minutes", + Some("younger than ten minutes when the books opened: left, the next backup tries again"), + &mut notes, + ); notes } @@ -850,7 +969,7 @@ pub fn commit( head: (u64, String), ) -> Result, BackupError> { let archive = archive(git, book_dir)?; - clear_old_locks(&archive); + clear_old_locks(git, book_dir); let guard = Watched::archive(&archive); let git_dir = format!("--git-dir={}", archive.display()); let work_tree = format!("--work-tree={}", book_dir.display()); @@ -978,7 +1097,7 @@ pub fn stage_blobs(git: &Git, book_dir: &Path) -> Result<(), BackupError> { return Ok(()); } let archive = archive(git, book_dir)?; - clear_old_locks(&archive); + clear_old_locks(git, book_dir); let guard = Watched::archive(&archive); let git_dir = format!("--git-dir={}", archive.display()); let work_tree = format!("--work-tree={}", book_dir.display()); @@ -998,18 +1117,19 @@ pub fn stage_blobs(git: &Git, book_dir: &Path) -> Result<(), BackupError> { Ok(()) } -/// The locks a git left behind (stopped, the server killed) would refuse -/// every later backup: cleared once older than any git may run quiet, -/// so never one a git still at work holds. -fn clear_old_locks(archive: &Path) { - for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { - let path = archive.join(lock); - let old = std::fs::metadata(&path) - .and_then(|m| m.modified()) - .is_ok_and(|t| t.elapsed().is_ok_and(|e| e > GIT_TIMEOUT)); - if old { - let _ = std::fs::remove_file(path); - } +/// The locks a git left behind (the server killed, a power cut) would +/// refuse every later backup: those older than ARCHIVE_STALE are removed, +/// each noted, so none a git still at work holds is touched (INVARIANT 5a). +fn clear_old_locks(git: &Git, book_dir: &Path) { + let mut notes = Vec::new(); + clear_stale_archive_locks( + book_dir, + "older than ten minutes when a backup began", + None, + &mut notes, + ); + for note in notes { + git.note(note); } } @@ -1962,7 +2082,7 @@ mod tests { s.add_account("6000", "Supplies", AccountType::Expense, None, false) .unwrap(); assert!(commit(&git, &b, "acme", s.head()).is_err()); - let then = std::time::SystemTime::now() - GIT_TIMEOUT - Duration::from_secs(1); + let then = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(1); for lock in locks { std::fs::File::options() .write(true) @@ -2382,6 +2502,7 @@ mod tests { exe: wrapper, quiet: GIT_TIMEOUT, cancel: None, + term_grace: TERM_GRACE, watch: Watch::default(), } } @@ -2446,6 +2567,15 @@ mod tests { ) .unwrap(); std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + // The receiving end's `pre-receive`: waits while `slow-pack` exists, + // after the pack has been received into the quarantine. + let pre = hooks.join("pre-receive"); + std::fs::write( + &pre, + "#!/bin/sh\ncat >/dev/null\nd=\"$(dirname \"$0\")\"\nif [ -e \"$d/slow-pack\" ]; then\n echo $$ >> \"$d/hooked-pack\"\n while [ -e \"$d/slow-pack\" ]; do sleep 0.05; done\nfi\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&pre, std::fs::Permissions::from_mode(0o755)).unwrap(); let wrapper = dir.join("slow-git"); std::fs::write( &wrapper, @@ -2462,6 +2592,7 @@ mod tests { exe: wrapper, quiet: GIT_TIMEOUT, cancel: None, + term_grace: TERM_GRACE, watch: Watch::default(), }, hooks, @@ -2489,17 +2620,59 @@ mod tests { .unwrap_or_else(|e| panic!("the repository isn't whole: {e}")); } - /// INVARIANT 5, the archive: a real git killed inside a commit (holding - /// the index and ref locks) leaves them, and once it is reaped they are - /// removed at once, each noted; the next backup needs no hand, and the - /// repository passes git's own check. + /// The locks in `repo`, as paths in it. + fn locks_in(repo: &Path) -> Vec { + crate::git_locks::RepoDir::open(repo) + .unwrap() + .locks() + .into_iter() + .map(|f| f.lock) + .collect() + } + + /// Hold every process of the group `pid` leads still (SIGSTOP): a + /// SIGTERM sent to it then stays pending, git can't run its handler, + /// and only the kill after the grace ends it. This is how a git that + /// can't end on SIGTERM, with the locks it holds, is made on purpose. + fn freeze_group_of(pid: u32) { + let out = std::process::Command::new("ps") + .args(["-o", "pgid=", "-p", &pid.to_string()]) + .output() + .unwrap(); + let group: i32 = String::from_utf8_lossy(&out.stdout) + .trim() + .parse() + .expect("ps names the group"); + // SAFETY: stopping the group this test's own git started. + assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0); + } + + /// The pid of the first hook of `slow_git` that waited, in `file`. + fn hooked_pid(hooks: &Path, file: &str) -> u32 { + std::fs::read_to_string(hooks.join(file)) + .unwrap() + .lines() + .next() + .unwrap() + .trim() + .parse() + .unwrap() + } + + /// INVARIANT 5, the archive, told to stop: a real git in the middle of a + /// commit, holding the ref locks, ends on SIGTERM and removes them + /// itself. Nothing is left, and nothing was cleaned up here (no note): + /// the grace is long, so a git that needed the kill would show. #[test] - fn a_git_killed_mid_commit_leaves_no_lock_and_the_next_backup_succeeds() { + fn a_git_stopped_by_sigterm_mid_commit_leaves_no_lock_and_needs_no_cleanup() { let real = Git::find().expect("git is installed"); let dir = tempfile::tempdir().unwrap(); let (slow, hooks) = slow_git(dir.path(), &real); let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let cancelled = slow.clone().with_cancel(flag.clone()); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); let b = dir.path().join("book"); let mut s = book(&b); commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); @@ -2512,8 +2685,7 @@ mod tests { std::thread::spawn(move || commit(&git, &b, "acme", head)) }; wait_hooked(&hooks); - // Inside the commit's ref update it holds the ref locks (its index - // lock is given up before): that is what a kill leaves. + // Inside the commit's ref update it holds the ref locks. let held = locks_in(&archive); assert!(held.contains(&"HEAD.lock".to_string()), "{held:?}"); assert!( @@ -2526,16 +2698,11 @@ mod tests { BackupError::Cancelled("commit".into()) ); assert_eq!(locks_in(&archive), Vec::::new()); - let notes = cancelled.take_lock_notes(); - for lock in &held { - assert!( - notes.iter().any(|n| n.repo == "archive" - && &n.lock == lock - && n.removed - && n.why == "git was stopped"), - "{lock} wasn't noted: {notes:?}" - ); - } + assert_eq!( + cancelled.take_lock_notes(), + Vec::new(), + "git removed its own locks: there was nothing for this program to clean up" + ); // The next backup, with no one to remove anything by hand. std::fs::remove_file(hooks.join("slow")).unwrap(); let made = commit(&slow, &b, "acme", s.head()) @@ -2545,15 +2712,78 @@ mod tests { fsck(&real, &archive); } - /// INVARIANT 5, the index lock: a real git killed inside `add` (here - /// hashing a very large, empty, stored file) holds the index lock, which - /// a kill leaves; it goes at once, and the next backup needs no hand. + /// INVARIANT 5, the archive, a git that can't end on SIGTERM: killed + /// only after the grace; once its group is gone the locks it left, none + /// of which was there when the command began, are removed through the + /// archive's own handle, each noted; the next backup needs no hand. #[test] - fn a_git_killed_mid_add_leaves_no_index_lock() { + fn a_git_that_cannot_end_on_sigterm_is_killed_after_the_grace_and_its_archive_locks_go() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks) = slow_git(dir.path(), &real); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(400); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(grace); + let b = dir.path().join("book"); + let mut s = book(&b); + commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + let archive = b.join(ARCHIVE_DIR); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, head) = (cancelled.clone(), b.clone(), s.head()); + std::thread::spawn(move || commit(&git, &b, "acme", head)) + }; + wait_hooked(&hooks); + let held = locks_in(&archive); + assert!(!held.is_empty(), "git held no lock inside its ref update"); + freeze_group_of(hooked_pid(&hooks, "hooked")); + let stopped = Instant::now(); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("commit".into()) + ); + assert!( + stopped.elapsed() >= grace, + "killed before the grace had run out" + ); + assert_eq!(locks_in(&archive), Vec::::new()); + let notes = cancelled.take_lock_notes(); + for lock in &held { + assert!( + notes.iter().any(|n| n.repo == "archive" + && &n.lock == lock + && n.removed + && n.why == "git was stopped" + && n.path.is_none()), + "{lock} wasn't noted: {notes:?}" + ); + } + std::fs::remove_file(hooks.join("slow")).unwrap(); + let made = commit(&slow, &b, "acme", s.head()) + .unwrap() + .expect("the next backup is made"); + assert_eq!(made.head, s.head()); + fsck(&real, &archive); + } + + /// INVARIANT 5, the index lock: a real git stopped inside `add` (here + /// hashing a very large, empty, stored file) holds the index lock, and + /// removes it itself on SIGTERM; the next backup needs no hand. + #[test] + fn a_git_stopped_mid_add_leaves_no_index_lock() { let real = Git::find().expect("git is installed"); let dir = tempfile::tempdir().unwrap(); let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let git = real.clone().with_cancel(flag.clone()); + let git = real + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); let b = dir.path().join("book"); let s = book(&b); commit(&real, &b, "acme", s.head()).unwrap().unwrap(); @@ -2567,58 +2797,75 @@ mod tests { let (git, b) = (git.clone(), b.clone()); std::thread::spawn(move || stage_blobs(&git, &b)) }; - let by = Instant::now() + Duration::from_secs(30); + // The lock is taken as `add` begins and held until it ends, which + // for a file this size is minutes: seeing it is being inside. + let by = Instant::now() + Duration::from_secs(60); while !archive.join("index.lock").exists() { assert!(Instant::now() < by, "git never took the index lock"); std::thread::sleep(Duration::from_millis(5)); } - // Hashing, with the lock held. - std::thread::sleep(Duration::from_millis(300)); - assert!(archive.join("index.lock").exists()); flag.store(true, std::sync::atomic::Ordering::SeqCst); assert_eq!( running.join().unwrap().unwrap_err(), BackupError::Cancelled("add".into()) ); assert_eq!(locks_in(&archive), Vec::::new()); - let notes = git.take_lock_notes(); - assert!( - notes - .iter() - .any(|n| n.lock == "index.lock" && n.removed && n.repo == "archive"), - "{notes:?}" - ); + assert_eq!(git.take_lock_notes(), Vec::new()); std::fs::remove_file(&big).unwrap(); stage_blobs(&real, &b).unwrap(); fsck(&real, &archive); } - /// INVARIANT 5, a folder target: a real git killed inside a push (its - /// receive-pack holding the target's ref lock) leaves the lock there; - /// once the push is reaped and the lock has stood unchanged for - /// LOCK_SETTLE it is removed and noted, the next push succeeds, and - /// both repositories pass git's check. A lock that was there before the - /// push began is another's, and stays. - #[test] - fn a_git_killed_mid_push_leaves_no_lock_in_the_target_but_never_removes_another() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks) = slow_git(dir.path(), &real); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let cancelled = slow.clone().with_cancel(flag.clone()); - let b = dir.path().join("book"); + /// A book backed up once to a folder target, then changed and + /// committed again, ready for a push: (git, hooks, book folder, target + /// repository, the target, the store). + fn ready_to_push( + dir: &Path, + real: &Git, + ) -> (Git, PathBuf, PathBuf, PathBuf, Target, crate::Store) { + let (slow, hooks) = slow_git(dir, real); + let b = dir.join("book"); let mut s = book(&b); commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); - let folder = dir.path().join("disk"); + let folder = dir.join("disk"); std::fs::create_dir(&folder).unwrap(); let target = Target::Folder(folder.clone()); push(&slow, &b, "acme", &target, true).unwrap(); - let repo = folder.join("acme.git"); - // Another writer's lock, held before our push begins. - std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); s.add_account("6000", "Supplies", AccountType::Expense, None, false) .unwrap(); commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + (slow, hooks, b, folder.join("acme.git"), target, s) + } + + fn main_of(real: &Git, repo: &Path) -> String { + real.run( + "rev-parse", + &[ + os(&format!("--git-dir={}", repo.display())), + os("rev-parse"), + os("refs/heads/main"), + ], + ) + .unwrap() + } + + /// INVARIANT 5b, told to stop: a real git in the middle of a push (its + /// receive-pack holding the target's ref lock) ends on SIGTERM and its + /// receiving end removes the lock itself. Nothing was removed here, a + /// lock that was there before the push is untouched, the next push + /// succeeds, and both repositories pass git's check. + #[test] + fn a_push_stopped_by_sigterm_leaves_no_lock_in_the_target_and_removes_nothing_there() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); + // Another writer's lock, held before our push begins. + std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); std::fs::write(hooks.join("slow"), b"").unwrap(); let running = { let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); @@ -2626,83 +2873,329 @@ mod tests { }; wait_hooked(&hooks); assert!(repo.join("refs/heads/main.lock").exists()); - let stopped = Instant::now(); flag.store(true, std::sync::atomic::Ordering::SeqCst); assert_eq!( running.join().unwrap().unwrap_err(), BackupError::Cancelled("push".into()) ); - assert!( - stopped.elapsed() >= LOCK_SETTLE, - "removed before the lock had stood for the settling time" - ); assert!(!repo.join("refs/heads/main.lock").exists()); assert!( repo.join("refs/heads/another.lock").exists(), "a lock that was there before the push was removed" ); - let notes = cancelled.take_lock_notes(); - assert!( - notes.iter().any(|n| n.repo == "folder" - && n.lock == "refs/heads/main.lock" - && n.removed - && n.why == "git was stopped"), - "{notes:?}" - ); - assert!( - notes - .iter() - .any(|n| n.lock == "refs/heads/another.lock" && !n.removed), - "{notes:?}" - ); + assert_eq!(cancelled.take_lock_notes(), Vec::new()); // The next push, nobody's hand in it. std::fs::remove_file(hooks.join("slow")).unwrap(); std::fs::remove_file(hooks.join("hooked")).unwrap(); let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); - let said = real - .run( - "rev-parse", - &[ - os(&format!("--git-dir={}", repo.display())), - os("rev-parse"), - os("refs/heads/main"), - ], - ) - .unwrap(); - assert_eq!(said, commit_id); + assert_eq!(main_of(&real, &repo), commit_id); fsck(&real, &repo); fsck(&real, &b.join(ARCHIVE_DIR)); } - /// INVARIANT 5, at open: every lock found in the book's archive is - /// removed (this process holds the books' lock, so no other git can be - /// there) and each is noted. + /// INVARIANT 5b, a git that can't end on SIGTERM: killed after the + /// grace, it leaves the target's ref lock, and nothing in the owner's + /// folder is deleted by us, whatever the lock's age. The push is + /// reported as failed, naming the file and what the owner may do. A + /// lock that was there before the push began is not named, and is + /// untouched. Once the owner (here, the test) removes the file the next + /// push succeeds, and both repositories pass git's check. #[test] - fn locks_found_in_the_archive_when_the_books_open_are_removed_and_noted() { + fn a_lock_left_in_a_folder_target_by_a_kill_is_never_removed_but_reported() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); + std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(400); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(grace); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); + std::thread::spawn(move || push(&git, &b, "acme", &target, true)) + }; + wait_hooked(&hooks); + let lock = repo.join("refs/heads/main.lock"); + assert!(lock.exists()); + freeze_group_of(hooked_pid(&hooks, "hooked")); + let stopped = Instant::now(); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + let said = running.join().unwrap().unwrap_err(); + assert!(stopped.elapsed() >= grace); + let BackupError::LockLeft(named) = &said else { + panic!("{said:?}"); + }; + assert!( + named.split(", ").any(|p| p == lock.display().to_string()), + "{said}" + ); + // Every lock it left is named, by its whole path, and each is there. + for path in named.split(", ") { + assert!(Path::new(path).exists(), "{path}"); + } + let words = said.to_string(); + assert!(words.contains("nothing else is using the backup folder"), "{words}"); + assert!(!words.contains("another.lock"), "{words}"); + // Left where it was, and the one before our push untouched. + assert!(lock.exists(), "a file in the owner's folder was deleted"); + assert!(repo.join("refs/heads/another.lock").exists()); + let notes = cancelled.take_lock_notes(); + assert!( + notes.iter().all(|n| n.repo == "folder" + && !n.removed + && n.path.as_deref() + == Some(repo.join(&n.lock).display().to_string().as_str())), + "{notes:?}" + ); + assert!( + notes.iter().any(|n| n.lock == "refs/heads/main.lock"), + "{notes:?}" + ); + assert!(!notes.iter().any(|n| n.lock.contains("another")), "{notes:?}"); + // Still there, a later push fails by git's own words, and the file + // stays. + std::fs::remove_file(hooks.join("slow")).unwrap(); + assert!(push(&slow, &b, "acme", &target, true).is_err()); + assert!(lock.exists(), "a later push removed it"); + // The owner removes it; the next backup goes on. + std::fs::remove_file(&lock).unwrap(); + let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); + assert_eq!(main_of(&real, &repo), commit_id); + fsck(&real, &repo); + fsck(&real, &b.join(ARCHIVE_DIR)); + } + + /// A book whose next push carries a large object (about 48 MiB that + /// doesn't compress), with a `pre-receive` hook on the receiving side + /// that waits while `slow-pack` exists: the pack has been received into + /// the target's quarantine by then, and the push is held inside the + /// transfer's receiving end. + fn large_push_ready(dir: &Path, real: &Git) -> (Git, PathBuf, PathBuf, PathBuf, Target) { + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir, real); + let mut bytes = vec![0u8; 48 << 20]; + let mut x: u64 = 0x9E37_79B9_7F4A_7C15; + for chunk in bytes.chunks_mut(8) { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + chunk.copy_from_slice(&x.to_le_bytes()[..chunk.len()]); + } + std::fs::write(b.join("blobs").join("large-and-random"), &bytes).unwrap(); + commit(&slow, &b, "acme", (1, "x".into())) + .map(|_| ()) + .unwrap(); + (slow, hooks, b, repo, target) + } + + /// INVARIANT 5, 6: a push stopped while its pack is being received (a + /// large object, the receiving end held up by a hook) leaves both + /// repositories whole, however it was ended: git's own check is run on + /// both at once, with nothing cleaned up between. + #[test] + fn a_push_stopped_during_the_pack_transfer_leaves_both_repositories_whole() { + let real = Git::find().expect("git is installed"); + for (name, frozen) in [("by SIGTERM", false), ("by the kill after the grace", true)] { + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target) = large_push_ready(dir.path(), &real); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_millis(if frozen { 400 } else { 120_000 })); + std::fs::write(hooks.join("slow-pack"), b"").unwrap(); + let running = { + let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); + std::thread::spawn(move || push(&git, &b, "acme", &target, true)) + }; + let by = Instant::now() + Duration::from_secs(300); + while !hooks.join("hooked-pack").exists() { + assert!( + Instant::now() < by, + "{name}: the push never reached the receiving end's hook" + ); + std::thread::sleep(Duration::from_millis(10)); + } + // The pack is in the target's quarantine: a stop is in the + // transfer's receiving end. + let incoming = std::fs::read_dir(repo.join("objects")) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().contains("incoming-")) + .count(); + assert!(incoming > 0, "{name}: nothing was being received"); + if frozen { + freeze_group_of(hooked_pid(&hooks, "hooked-pack")); + } + flag.store(true, std::sync::atomic::Ordering::SeqCst); + let said = running.join().unwrap().unwrap_err(); + assert!( + matches!(said, BackupError::Cancelled(_) | BackupError::LockLeft(_)), + "{name}: {said:?}" + ); + // At once: nothing cleaned up, nothing waited for. + fsck(&real, &repo); + fsck(&real, &b.join(ARCHIVE_DIR)); + // And the target still takes the next push, after the owner's + // own removal of a lock a kill left (none, when SIGTERM ended + // git). + std::fs::remove_file(hooks.join("slow-pack")).unwrap(); + std::fs::remove_file(hooks.join("hooked-pack")).unwrap(); + if let BackupError::LockLeft(path) = said { + assert!(frozen, "{name}: SIGTERM left a lock"); + std::fs::remove_file(path).unwrap(); + } + let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); + assert_eq!(main_of(&real, &repo), commit_id, "{name}"); + fsck(&real, &repo); + } + } + + /// INVARIANT 5a: at open, a lock in the archive is removed only if it + /// is older than ARCHIVE_STALE, each removal noted; a younger one is + /// left (and said so), nothing that isn't a lock's name is touched, and + /// the next backup removes a lock once it has grown old. + #[test] + fn the_archives_age_rule_at_open() { let git = Git::find().expect("git is installed"); let dir = tempfile::tempdir().unwrap(); let b = dir.path().join("book"); + let mut s = book(&b); + commit(&git, &b, "acme", s.head()).unwrap().unwrap(); + let archive = b.join(ARCHIVE_DIR); + let old_enough = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(5); + let age = |path: &Path, to: std::time::SystemTime| { + std::fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(to) + .unwrap(); + }; + let old = ["index.lock", "refs/heads/main.lock"]; + let young = ["HEAD.lock", "packed-refs.lock"]; + for lock in old.iter().chain(&young) { + std::fs::write(archive.join(lock), b"").unwrap(); + } + for lock in old { + age(&archive.join(lock), old_enough); + } + // Not locks, however old: a file of git's own, a folder named like + // one, and a link. + std::fs::write(archive.join("description.lock-not"), b"").unwrap(); + age(&archive.join("description.lock-not"), old_enough); + std::fs::create_dir(archive.join("shallow.lock")).unwrap(); + let notes = clear_archive_locks(&b); + let removed: Vec<&str> = notes + .iter() + .filter(|n| n.removed) + .map(|n| n.lock.as_str()) + .collect(); + let mut removed_sorted = removed.clone(); + removed_sorted.sort(); + assert_eq!(removed_sorted, ["index.lock", "refs/heads/main.lock"]); + let mut left: Vec<&str> = notes + .iter() + .filter(|n| !n.removed) + .map(|n| n.lock.as_str()) + .collect(); + left.sort(); + assert_eq!(left, ["HEAD.lock", "packed-refs.lock"]); + assert!(notes.iter().all(|n| n.repo == "archive")); + assert_eq!(locks_in(&archive), ["HEAD.lock", "packed-refs.lock"]); + assert!(archive.join("description.lock-not").exists()); + assert!(archive.join("shallow.lock").is_dir()); + // The next backup meets a young lock: it fails by git's words, and + // the lock stays. Once old it is removed, noted, and the backup goes. + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + assert!(commit(&git, &b, "acme", s.head()).is_err()); + assert!(archive.join("HEAD.lock").exists()); + for lock in young { + age(&archive.join(lock), old_enough); + } + let git = git.with_lock_notes(LockNotes::default()); + let made = commit(&git, &b, "acme", s.head()) + .unwrap() + .expect("backed up"); + assert_eq!(made.head, s.head()); + let notes = git.take_lock_notes(); + let mut removed: Vec<&str> = notes.iter().map(|n| n.lock.as_str()).collect(); + removed.sort(); + assert_eq!(removed, ["HEAD.lock", "packed-refs.lock"]); + assert!(notes.iter().all(|n| n.removed && n.repo == "archive")); + assert_eq!(locks_in(&archive), Vec::::new()); + } + + /// INVARIANT 5a and git_locks INVARIANT 1: what is removed after a stop + /// is removed through the archive's folder as it was opened when the + /// command began. A `refs` folder swapped for a link, or the archive's + /// own path swapped for one, in the meantime, touches nothing outside. + #[test] + fn removal_after_a_stop_goes_through_the_handle_opened_before_the_command() { + let git = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + std::fs::write(outside.join(lock), b"theirs").unwrap(); + } + let untouched = |what: &str| { + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + assert_eq!( + std::fs::read(outside.join(lock)).unwrap(), + b"theirs", + "{what}: {lock} outside was touched" + ); + } + }; + // 1. `refs` swapped for a link. + let b = dir.path().join("book"); let s = book(&b); commit(&git, &b, "acme", s.head()).unwrap().unwrap(); let archive = b.join(ARCHIVE_DIR); - let planted = [ - "index.lock", - "HEAD.lock", - "packed-refs.lock", - "refs/heads/main.lock", - ]; - for lock in planted { - std::fs::write(archive.join(lock), b"").unwrap(); - } - let notes = clear_archive_locks(&b); - let mut named: Vec<_> = notes.iter().map(|n| n.lock.clone()).collect(); - named.sort(); - let mut want: Vec<_> = planted.iter().map(|l| l.to_string()).collect(); - want.sort(); - assert_eq!(named, want); - assert!(notes.iter().all(|n| n.removed && n.repo == "archive")); - assert_eq!(locks_in(&archive), Vec::::new()); - assert_eq!(clear_archive_locks(&b), Vec::new()); + let watched = Watched::archive(&archive); + let snap = watched.snapshot(); + std::fs::write(archive.join("index.lock"), b"ours").unwrap(); + std::fs::write(archive.join("refs/heads/main.lock"), b"ours").unwrap(); + std::fs::rename(archive.join("refs"), dir.path().join("refs-moved")).unwrap(); + std::os::unix::fs::symlink(outside.join("refs"), archive.join("refs")).unwrap(); + let left = watched.after_kill(&git, &snap, true); + assert!(left.is_empty()); + assert!(!archive.join("index.lock").exists(), "its own lock stays"); + assert!( + dir.path().join("refs-moved/heads/main.lock").exists(), + "the folder moved aside was reached through the link" + ); + untouched("refs swapped"); + let notes = git.take_lock_notes(); + assert_eq!( + notes.iter().map(|n| n.lock.as_str()).collect::>(), + ["index.lock"] + ); + // 2. The archive's own path swapped for a link. + std::fs::remove_file(archive.join("refs")).unwrap(); + std::fs::rename(dir.path().join("refs-moved"), archive.join("refs")).unwrap(); + std::fs::remove_file(archive.join("refs/heads/main.lock")).unwrap(); + let snap = watched.snapshot(); + std::fs::write(archive.join("index.lock"), b"ours").unwrap(); + let moved = b.join("archive-moved.git"); + std::fs::rename(&archive, &moved).unwrap(); + std::os::unix::fs::symlink(&outside, &archive).unwrap(); + let left = watched.after_kill(&git, &snap, true); + assert!(left.is_empty()); + assert!(!moved.join("index.lock").exists()); + untouched("archive path swapped"); + // 3. A command that began when the archive path was already a link + // has no handle, and nothing is removed anywhere. + std::fs::write(outside.join("new.lock"), b"theirs").unwrap(); + let snap = watched.snapshot(); + assert!(snap.handle.is_none()); + std::fs::write(outside.join("index.lock"), b"theirs").unwrap(); + assert!(watched.after_kill(&git, &snap, true).is_empty()); + untouched("path a link from the start"); } /// INVARIANT 6: a drill stops inside whichever phase it is told to stop @@ -2783,6 +3276,7 @@ mod tests { exe, quiet, cancel: None, + term_grace: TERM_GRACE, watch: Watch::default(), } } @@ -2823,7 +3317,8 @@ mod tests { .trim() .parse() .unwrap(); - std::thread::sleep(Duration::from_millis(200)); + // `run` returned: the group was waited for, so what it started is + // gone now, not at some later moment. // SAFETY: signal 0 only asks whether the process is there. assert_ne!(unsafe { libc::kill(child, 0) }, 0, "what it started ran on"); // And none starts now. @@ -2835,6 +3330,56 @@ mod tests { assert!(!pid.exists(), "a cancelled git started anyway"); } + /// INVARIANT 5: a git is told to end (SIGTERM, to its whole group) + /// before it is killed, and killed only once the grace has run out: one + /// that ignores the signal (a trap, as a hook may set) is waited for the + /// whole grace, then killed with all it started. + #[test] + fn a_git_that_ignores_sigterm_is_killed_after_the_grace_with_all_it_started() { + let dir = tempfile::tempdir().unwrap(); + let (started, termed) = (dir.path().join("started"), dir.path().join("termed")); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(500); + let stubborn = fake_git( + dir.path(), + &format!( + "trap 'echo term >> \"{}\"' TERM\necho $$ > '{}'\nwhile :; do sleep 0.05; done", + termed.display(), + started.display() + ), + Duration::from_secs(60), + ) + .with_cancel(cancel.clone()) + .with_term_grace(grace); + let running = { + let stubborn = stubborn.clone(); + std::thread::spawn(move || stubborn.run("stubborn", &[])) + }; + let by = Instant::now() + Duration::from_secs(30); + while !started.exists() { + assert!(Instant::now() < by, "the fake git never started"); + std::thread::sleep(Duration::from_millis(10)); + } + let stopped = Instant::now(); + cancel.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("stubborn".into()) + ); + assert!( + stopped.elapsed() >= grace, + "killed before the grace had run out" + ); + assert!(termed.exists(), "it was never sent SIGTERM first"); + let shell: i32 = std::fs::read_to_string(&started) + .unwrap() + .trim() + .parse() + .unwrap(); + // SAFETY: signal 0 only asks whether the process is there. + assert_ne!(unsafe { libc::kill(shell, 0) }, 0, "it ran on"); + } + #[test] fn a_git_is_stopped_only_once_it_falls_quiet_and_with_all_it_started() { let dir = tempfile::tempdir().unwrap(); @@ -2910,6 +3455,7 @@ mod tests { exe: quoted.join("git"), quiet: GIT_TIMEOUT, cancel: None, + term_grace: TERM_GRACE, watch: Watch::default(), }; let b = dir.path().join("book"); diff --git a/crates/ledger-store/src/git_locks.rs b/crates/ledger-store/src/git_locks.rs new file mode 100644 index 00000000..d11a28ed --- /dev/null +++ b/crates/ledger-store/src/git_locks.rs @@ -0,0 +1,561 @@ +//! The lock files a git leaves in a repository, found and (only where it +//! is ours to) removed through a directory handle (ledger-store `backup` +//! INVARIANT 5). +//! +//! ```text +//! GOAL: a lock file a stopped git left can be seen, and removed from the +//! one repository this program owns, without ever touching anything +//! a swapped folder or link points to. +//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10, 13: +//! a close is answered with no git of ours still working, and +//! leaves nothing a person must clean up); git's own lock files +//! (git-config, gitrepository-layout: `HEAD.lock`, `index.lock`, +//! `.lock`, `packed-refs.lock`, `shallow.lock`, +//! `config.lock`). +//! INVARIANTS: +//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a +//! directory that is not a link, the folder it was found in kept as +//! the book's own. Every look and every removal after that goes +//! through that handle: the folders below it (`refs/`, and those +//! under it) are each opened from the one above with links refused, +//! so a folder swapped for a link, or the repository's own path swapped +//! for one, after the handle was opened, sends nothing anywhere: the +//! handle still names the folder that was opened. +//! 2. Only a regular file is ever removed (never a link, never a folder, +//! never a file whose type changed), and only one named as git names +//! its locks, in the places git puts them (`is_lock`). A name that +//! isn't one is refused. +//! 3. Where there is no directory handle to be had (not Unix) each step +//! looks at the path itself and refuses a link: the same rules, +//! without the guarantee against a swap in between. Nothing else +//! about the platform's behaviour is designed here. +//! ``` + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +/// Locks git makes in a repository's own folder. +const TOP: [&str; 5] = [ + "HEAD.lock", + "index.lock", + "config.lock", + "packed-refs.lock", + "shallow.lock", +]; +/// Locks git makes below it, outside `refs/`. +const BELOW: [&str; 2] = [ + "objects/info/commit-graph.lock", + "objects/pack/multi-pack-index.lock", +]; +/// How deep under `refs/` a lock is looked for. +const REFS_DEPTH: usize = 12; + +/// Whether `rel` (a path in a repository, with `/` between its parts) is +/// named as git names a lock, in a place git puts one (INVARIANT 2). +pub fn is_lock(rel: &str) -> bool { + if TOP.contains(&rel) || BELOW.contains(&rel) { + return true; + } + let Some(under) = rel.strip_prefix("refs/") else { + return false; + }; + let parts: Vec<&str> = under.split('/').collect(); + parts.len() <= REFS_DEPTH + && parts + .iter() + .all(|p| !p.is_empty() && *p != "." && *p != "..") + && parts + .last() + .is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock")) +} + +/// A lock found: its path in the repository, and when it was last written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Found { + /// `index.lock`, `refs/heads/main.lock`. + pub lock: String, + /// Its modification time, when the system said. + pub modified: Option, +} + +/// A repository's folder, opened once (INVARIANT 1). +#[derive(Debug)] +pub struct RepoDir { + path: PathBuf, + inner: imp::Dir, +} + +impl RepoDir { + /// The folder at `path`, which must not itself be a link. + pub fn open(path: &Path) -> io::Result { + Ok(RepoDir { + path: path.to_path_buf(), + inner: imp::open(path)?, + }) + } + + /// The folder `name` inside the folder `parent` (the book's own folder + /// holding its archive): `name` must not be a link. + pub fn open_in(parent: &Path, name: &str) -> io::Result { + Ok(RepoDir { + path: parent.join(name), + inner: imp::open_in(parent, name)?, + }) + } + + /// The path it was opened by (for words, never for an operation). + pub fn path(&self) -> &Path { + &self.path + } + + /// The locks in it, sorted: regular files named as git names its locks. + pub fn locks(&self) -> Vec { + let mut out = Vec::new(); + for rel in TOP.iter().chain(BELOW.iter()) { + if let Some(modified) = self.inner.regular(rel) { + out.push(Found { + lock: (*rel).to_string(), + modified, + }); + } + } + self.inner.refs(&mut out, REFS_DEPTH); + out.sort_by(|a, b| a.lock.cmp(&b.lock)); + out + } + + /// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file + /// of that name was removed, Ok(false) if there was none (or it was + /// not a regular file: nothing was done), Err if the name isn't a + /// lock's or the system refused. + pub fn remove(&self, rel: &str) -> io::Result { + if !is_lock(rel) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a name git gives a lock", + )); + } + self.inner.remove(rel) + } +} + +#[cfg(unix)] +mod imp { + use super::{Found, SystemTime}; + use std::ffi::{CStr, CString, OsStr}; + use std::io; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; + use std::os::unix::ffi::OsStrExt; + use std::path::Path; + + #[derive(Debug)] + pub struct Dir(OwnedFd); + + const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC; + + fn c(text: &OsStr) -> io::Result { + CString::new(text.as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL")) + } + + fn owned(fd: libc::c_int) -> io::Result { + if fd < 0 { + Err(io::Error::last_os_error()) + } else { + // SAFETY: a file descriptor just returned by the system, owned + // by no one else. + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + } + } + + pub fn open(path: &Path) -> io::Result { + let path = c(path.as_os_str())?; + // SAFETY: a NUL-ended path; the flags refuse a link at its end. + owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir) + } + + pub fn open_in(parent: &Path, name: &str) -> io::Result { + let parent = c(parent.as_os_str())?; + // SAFETY: as in `open`; the parent may be reached through links (it + // is the book's own folder), only `name` may not be one. + let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?; + sub(parent.as_raw_fd(), name).map(Dir) + } + + /// The folder `name` of `dir`, a link refused. + fn sub(dir: RawFd, name: &str) -> io::Result { + let name = c(OsStr::new(name))?; + // SAFETY: `dir` is open for the call; the name is NUL-ended. + owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) }) + } + + /// `name` in `dir` as it is (a link is not followed): its stat. + fn stat(dir: RawFd, name: &str) -> io::Result { + let name = c(OsStr::new(name))?; + // SAFETY: zeroed stat is a valid out-parameter; `dir` is open. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + let found = + unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) }; + if found == 0 { + Ok(st) + } else { + Err(io::Error::last_os_error()) + } + } + + fn is_regular(st: &libc::stat) -> bool { + (st.st_mode & libc::S_IFMT) == libc::S_IFREG + } + + fn is_dir(st: &libc::stat) -> bool { + (st.st_mode & libc::S_IFMT) == libc::S_IFDIR + } + + fn modified(st: &libc::stat) -> Option { + let secs = u64::try_from(st.st_mtime).ok()?; + let nanos = u32::try_from(st.st_mtime_nsec).ok()?; + Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos)) + } + + /// The names in the folder `dir` (a fresh look each time). + fn names(dir: RawFd) -> Vec { + // SAFETY: a duplicate of an open descriptor, handed to fdopendir, + // which owns it from then on (closedir closes it). + let copy = unsafe { libc::dup(dir) }; + if copy < 0 { + return Vec::new(); + } + let stream = unsafe { libc::fdopendir(copy) }; + if stream.is_null() { + // SAFETY: fdopendir didn't take it. + unsafe { libc::close(copy) }; + return Vec::new(); + } + let mut out = Vec::new(); + // SAFETY: `stream` is a live directory stream until closedir; each + // entry's name is a NUL-ended string valid until the next readdir. + unsafe { + libc::rewinddir(stream); + loop { + let entry = libc::readdir(stream); + if entry.is_null() { + break; + } + let name = CStr::from_ptr((*entry).d_name.as_ptr()); + if let Ok(name) = name.to_str() + && name != "." + && name != ".." + { + out.push(name.to_string()); + } + } + libc::closedir(stream); + } + out + } + + impl Dir { + /// The folder holding `rel`, opened step by step from this one + /// with a link refused at each, and `rel`'s last part. + fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> { + let mut parts: Vec<&str> = rel.split('/').collect(); + let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; + // SAFETY: a duplicate of the open descriptor, owned here. + let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?; + for part in parts { + here = sub(here.as_raw_fd(), part)?; + } + Ok((here, last)) + } + + /// A regular file at `rel`: its modification time (when known). + pub fn regular(&self, rel: &str) -> Option> { + let (parent, name) = self.parent_of(rel).ok()?; + let st = stat(parent.as_raw_fd(), name).ok()?; + is_regular(&st).then(|| modified(&st)) + } + + /// The locks under `refs/`, in `out`. + pub fn refs(&self, out: &mut Vec, depth: usize) { + let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else { + return; + }; + fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec) { + for name in names(dir) { + let Ok(st) = stat(dir, &name) else { continue }; + let rel = format!("{prefix}{name}"); + if is_regular(&st) { + if super::is_lock(&rel) { + out.push(Found { + lock: rel, + modified: modified(&st), + }); + } + } else if is_dir(&st) + && depth > 0 + && let Ok(inner) = sub(dir, &name) + { + walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out); + } + } + } + walk(refs.as_raw_fd(), "refs/", depth, out); + } + + pub fn remove(&self, rel: &str) -> io::Result { + let (parent, name) = match self.parent_of(rel) { + Ok(found) => found, + // A folder that isn't there (or is a link): nothing to remove. + Err(_) => return Ok(false), + }; + match stat(parent.as_raw_fd(), name) { + Ok(st) if is_regular(&st) => {} + _ => return Ok(false), + } + let name = c(OsStr::new(name))?; + // SAFETY: the parent is open; the name is NUL-ended and relative + // to it, and names a regular file just looked at. + let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) }; + if removed == 0 { + Ok(true) + } else { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::NotFound { + Ok(false) + } else { + Err(e) + } + } + } + } +} + +#[cfg(not(unix))] +mod imp { + use super::{Found, SystemTime}; + use std::io; + use std::path::{Path, PathBuf}; + + #[derive(Debug)] + pub struct Dir(PathBuf); + + fn plain(path: &Path) -> io::Result<()> { + let meta = std::fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a plain folder", + )); + } + Ok(()) + } + + pub fn open(path: &Path) -> io::Result { + plain(path)?; + Ok(Dir(path.to_path_buf())) + } + + pub fn open_in(parent: &Path, name: &str) -> io::Result { + open(&parent.join(name)) + } + + impl Dir { + fn at(&self, rel: &str) -> io::Result { + let mut path = self.0.clone(); + let mut parts: Vec<&str> = rel.split('/').collect(); + let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; + for part in parts { + path.push(part); + plain(&path)?; + } + path.push(last); + Ok(path) + } + + pub fn regular(&self, rel: &str) -> Option> { + let path = self.at(rel).ok()?; + let meta = std::fs::symlink_metadata(path).ok()?; + meta.file_type() + .is_file() + .then(|| meta.modified().ok()) + } + + pub fn refs(&self, out: &mut Vec, depth: usize) { + fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let Ok(meta) = std::fs::symlink_metadata(e.path()) else { + continue; + }; + let rel = format!("{prefix}{}", e.file_name().to_string_lossy()); + if meta.file_type().is_file() { + if super::is_lock(&rel) { + out.push(Found { + lock: rel, + modified: meta.modified().ok(), + }); + } + } else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 { + walk(&e.path(), &format!("{rel}/"), depth - 1, out); + } + } + } + let refs = self.0.join("refs"); + if plain(&refs).is_ok() { + walk(&refs, "refs/", depth, out); + } + } + + pub fn remove(&self, rel: &str) -> io::Result { + let Ok(path) = self.at(rel) else { + return Ok(false); + }; + match std::fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() => { + std::fs::remove_file(path).map(|()| true) + } + _ => Ok(false), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(dir: &Path) -> PathBuf { + let repo = dir.join("repo.git"); + std::fs::create_dir_all(repo.join("refs/heads")).unwrap(); + std::fs::create_dir_all(repo.join("objects/pack")).unwrap(); + std::fs::create_dir_all(repo.join("objects/info")).unwrap(); + repo + } + + #[test] + fn only_the_names_git_gives_its_locks_are_locks() { + for yes in [ + "HEAD.lock", + "index.lock", + "config.lock", + "packed-refs.lock", + "shallow.lock", + "refs/heads/main.lock", + "refs/heads/feature/x.lock", + "refs/tags/v1.lock", + "objects/info/commit-graph.lock", + "objects/pack/multi-pack-index.lock", + ] { + assert!(is_lock(yes), "{yes}"); + } + for no in [ + "", + ".lock", + "refs/.lock", + "refs/heads/", + "refs/heads/main", + "refs/heads/../../x.lock", + "refs//x.lock", + "refs/heads/./x.lock", + "other.lock", + "objects/pack/pack-1.pack", + "objects/other.lock", + "../index.lock", + "/etc/x.lock", + "hooks/pre-commit.lock", + "refs", + ] { + assert!(!is_lock(no), "{no:?}"); + } + } + + #[test] + fn locks_are_found_and_only_regular_files_are_removed() { + let dir = tempfile::tempdir().unwrap(); + let repo = repo(dir.path()); + std::fs::write(repo.join("index.lock"), b"").unwrap(); + std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap(); + // Named like locks, but not files: neither is listed nor removed. + std::fs::create_dir(repo.join("HEAD.lock")).unwrap(); + std::fs::write(dir.path().join("elsewhere"), b"").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap(); + // Not a lock's name. + std::fs::write(repo.join("refs/heads/main"), b"").unwrap(); + let handle = RepoDir::open(&repo).unwrap(); + let found: Vec = handle.locks().into_iter().map(|f| f.lock).collect(); + assert_eq!(found, ["index.lock", "refs/heads/main.lock"]); + assert!(handle.locks().iter().all(|f| f.modified.is_some())); + assert!(handle.remove("index.lock").unwrap()); + assert!(!handle.remove("index.lock").unwrap(), "already gone"); + assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays"); + assert!(repo.join("HEAD.lock").is_dir()); + #[cfg(unix)] + { + assert!(!handle.remove("config.lock").unwrap(), "a link stays"); + assert!(repo.join("config.lock").is_symlink()); + assert!(dir.path().join("elsewhere").exists()); + } + assert!(handle.remove("refs/heads/main").is_err(), "not a lock"); + assert!(repo.join("refs/heads/main").exists()); + assert!(handle.remove("../elsewhere.lock").is_err()); + } + + /// INVARIANT 1: a folder (or the repository's own path) swapped for a + /// link after the handle was opened sends nothing anywhere. + #[cfg(unix)] + #[test] + fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() { + let dir = tempfile::tempdir().unwrap(); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + std::fs::write(outside.join(lock), b"theirs").unwrap(); + } + // `refs` swapped for a link to a folder holding a lock of that name. + let repo_path = repo(dir.path()); + std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap(); + let handle = RepoDir::open(&repo_path).unwrap(); + std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap(); + std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap(); + assert!(!handle.remove("refs/heads/main.lock").unwrap()); + assert!(handle.locks().is_empty(), "a link is not looked through"); + assert_eq!( + std::fs::read(outside.join("refs/heads/main.lock")).unwrap(), + b"theirs" + ); + assert_eq!( + std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(), + b"ours", + "nor was the folder it moved to touched through the link" + ); + // The repository's own path swapped for a link: the handle still + // names the folder it opened (moved aside), and the link's target + // is never touched. + let second = dir.path().join("second.git"); + std::fs::create_dir_all(second.join("refs")).unwrap(); + std::fs::write(second.join("index.lock"), b"ours").unwrap(); + let handle = RepoDir::open(&second).unwrap(); + std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap(); + std::os::unix::fs::symlink(&outside, &second).unwrap(); + assert!(handle.remove("index.lock").unwrap()); + assert!(!dir.path().join("second-moved.git/index.lock").exists()); + assert_eq!( + std::fs::read(outside.join("index.lock")).unwrap(), + b"theirs", + "the link's target was touched" + ); + assert_eq!( + std::fs::read(outside.join("HEAD.lock")).unwrap(), + b"theirs" + ); + // And a repository that is a link when the handle is opened is + // refused, with the archive's own `open_in` too. + assert!(RepoDir::open(&second).is_err()); + assert!(RepoDir::open_in(dir.path(), "second.git").is_err()); + assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok()); + } +} diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index 2151e98b..eb3477cb 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -29,6 +29,7 @@ pub mod error; pub mod exports; pub mod form1099; pub mod format; +pub mod git_locks; pub mod journal; pub mod lock; pub mod meta;