//! THE LEDGER OVER THIS MAC'S REAL DISK: the executors a pass is handed //! (`super::ledger::Machine`) as a Mac answers them, shared by the old Mac //! app's schedule (`cotton-ffi` `shell::ledger`) and the repo's //! `cotton-ledger` binary that the claims sweep runs under //! launchd. //! //! **A FOLDER SOMETHING LIVES IN IS NEVER REMOVED.** Before each pass the //! caller reads what is alive on the Mac ([`liveness`]): every registered git //! worktree, and the working folder of every live process and tmux pane. A //! pass that cannot read it removes nothing. Every removal is written to //! `~/.cottondb/ledger.log` by the ledger itself and said by the caller //! ([`said`]). use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use super::ledger::{self, Claim, ClaimKind, Liveness, Machine, Reason, Roots, SessionFate, Spool}; /// How many claims one pass measures: a first pass over a full Mac walks /// hundreds of gigabytes, so it is spread over the next passes. pub const MEASURE_PER_PASS: usize = 25; /// Where the adopt scan looks on this Mac. #[must_use] pub fn roots_at(home: &Path) -> Roots { Roots { home: home.to_path_buf(), tmp: PathBuf::from("/private/tmp"), // `$TMPDIR` is `/var/folders/…`, through the `/var` link: canonical, so the refusal knows it as a temporary folder. user_tmp: std::env::temp_dir().canonicalize().unwrap_or_else(|_| std::env::temp_dir()), checkouts: vec![home.join("Code/cottondb")], } } /// The ledger over this Mac's real disk. #[allow(clippy::too_many_arguments)] pub fn run( spool: &Spool, roots: &Roots, protected: &[PathBuf], reserve_gb: f64, working: &[PathBuf], live: &Liveness, drops: &BTreeSet, session: &dyn Fn(&str) -> SessionFate, ) -> ledger::PassReport { let home = roots.home.clone(); let mut free_gb = || cotton_session_host::machine::free_disk_gb(&home); let mut remove = |claim: &Claim| remove(claim); let mut measure = |path: &Path| ledger::measure(path); let mut machine = Machine { roots, protected, now: std::time::SystemTime::now(), reserve_gb, alive: &cotton_session_host::pty::alive, working, live, session, free_gb: &mut free_gb, remove: &mut remove, measure: &mut measure, }; ledger::pass(spool, &mut machine, drops, MEASURE_PER_PASS) } /// What a pass says in its caller's log: one line per removal — path, claim, /// rule and reason — then the pass's one sentence. #[must_use] pub fn said(report: &ledger::PassReport) -> Vec { let mut lines: Vec = report.released.iter().map(|(claim, reason)| removal_line(claim, reason)).collect(); lines.extend(report.sentence()); lines } fn removal_line(claim: &Claim, reason: &Reason) -> String { format!( "ledger: removed {} claim={} lane={} rule={} reason=\"{}\"", claim.path.display(), claim.id(), claim.lane, claim.rule, reason.words() ) } /// The processes of the build lock holder's tree: the job building now. #[must_use] pub fn build_lock_pids() -> BTreeSet { use cotton_session_host::{machine, processes}; machine::build_lock_pid(Path::new(machine::BUILD_LOCK_DIR)) .map(|holder| processes::tree(&processes::snapshot(), holder)) .unwrap_or_default() } /// Where the jobs `pids` work: each one's working folder, as `lsof` says. #[must_use] pub fn working_of(pids: &BTreeSet) -> Vec { if pids.is_empty() { return Vec::new(); } let list = pids.iter().map(u32::to_string).collect::>().join(","); std::process::Command::new("lsof") .args(["-a", "-d", "cwd", "-F", "n", "-p", &list]) .output() .map(|out| working_dirs(&String::from_utf8_lossy(&out.stdout))) .unwrap_or_default() } /// The working folders in `lsof -F n` output: each `n` line names one. #[must_use] pub fn working_dirs(lsof: &str) -> Vec { let mut dirs: Vec = lsof.lines().filter_map(|line| line.strip_prefix('n')).map(PathBuf::from).collect(); dirs.sort(); dirs.dedup(); dirs } /// What is alive on this Mac now ([`Liveness`]): the worktrees each checkout's /// git has registered, and the working folder of every live process (a coding /// agent, a shell) and tmux pane. Read fresh for every pass. `git` is the git /// this Mac runs, `None` when it has none. #[must_use] pub fn liveness(roots: &Roots, git: Option<&Path>) -> Liveness { let lsof = std::process::Command::new("lsof") .args(["-d", "cwd", "-F", "n"]) .output() .ok() .map(|out| String::from_utf8_lossy(&out.stdout).into_owned()); // No git on this Mac, or no checkout: no worktree is registered. A git // that is there and does not answer for a checkout is not read. let lists: Vec> = roots .checkouts .iter() .filter(|checkout| checkout.join(".git").exists()) .filter_map(|checkout| git.map(|git| (git, checkout))) .map(|(git, checkout)| { std::process::Command::new(git) .arg("-C") .arg(checkout) .args(["worktree", "list", "--porcelain"]) .output() .ok() .filter(|out| out.status.success()) .map(|out| String::from_utf8_lossy(&out.stdout).into_owned()) }) .collect(); liveness_of(lsof.as_deref(), &lists, &tmux_panes()) } /// [`Liveness`] from what the Mac answered: `lsof -d cwd -F n` (`None`: it /// did not run), each checkout's `git worktree list --porcelain` (`None`: git /// refused) and tmux's pane folders, one a line. A process list that did not /// answer or names no folder, or a checkout git would not list, is `unread`. #[must_use] pub fn liveness_of(lsof: Option<&str>, worktree_lists: &[Option], panes: &str) -> Liveness { let mut sessions = lsof.map(working_dirs).unwrap_or_default(); let unread = sessions.is_empty() || worktree_lists.iter().any(Option::is_none); sessions.extend(panes.lines().filter(|line| line.starts_with('/')).map(PathBuf::from)); sessions.sort(); sessions.dedup(); let worktrees = worktree_lists.iter().flatten().flat_map(|list| ledger::registered_worktrees(list)).collect(); Liveness { worktrees, sessions, unread } } /// The working folder of every tmux pane, one a line, or nothing when no /// tmux answers: a pane's shell is a live process the process list already /// names, so this adds the panes it could not see, and its absence hides none. fn tmux_panes() -> String { ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux", "/usr/bin/tmux"] .iter() .filter(|tmux| Path::new(tmux).exists()) .find_map(|tmux| { std::process::Command::new(tmux) .args(["list-panes", "-a", "-F", "#{pane_current_path}"]) .output() .ok() .filter(|out| out.status.success()) }) .map(|out| String::from_utf8_lossy(&out.stdout).into_owned()) .unwrap_or_default() } /// Remove a released claim's path: a simulator through `simctl`, so its /// device set forgets it too; a folder whole; a file (one left loose in home) /// as itself — a symlink is removed as the link, never followed. pub fn remove(claim: &Claim) -> Result<(), String> { if claim.kind == ClaimKind::Simulator { let udid = claim.path.file_name().and_then(|name| name.to_str()).ok_or("a simulator folder with no name")?; let status = std::process::Command::new("xcrun") .args(["simctl", "delete", udid]) .status() .map_err(|error| error.to_string())?; return if status.success() { Ok(()) } else { Err(format!("simctl delete {udid} refused")) }; } let folder = std::fs::symlink_metadata(&claim.path).map_err(|error| error.to_string())?.is_dir(); if folder { std::fs::remove_dir_all(&claim.path).map_err(|error| error.to_string()) } else { std::fs::remove_file(&claim.path).map_err(|error| error.to_string()) } } #[cfg(test)] #[path = "ledger_mac_tests.rs"] mod tests;