|
| 1 | +//! Per-extraction temporary directory owned by the runner. The extractor and |
| 2 | +//! any tools it spawns receive it via `TMPDIR`, `TMP`, and `TEMP`. The runner |
| 3 | +//! removes it when the extractor finishes or is killed (including on timeout or |
| 4 | +//! cancellation). If the runner itself is killed, the next run removes its |
| 5 | +//! leftover directories. |
| 6 | +
|
| 7 | +use std::{ |
| 8 | + collections::BTreeMap, |
| 9 | + fs, |
| 10 | + path::{Path, PathBuf}, |
| 11 | + sync::atomic::{AtomicU64, Ordering}, |
| 12 | +}; |
| 13 | + |
| 14 | +/// Names start with this, then the runner's process ID. |
| 15 | +const PREFIX: &str = "projections-extraction-"; |
| 16 | + |
| 17 | +/// The variables that name the temporary directory, on any platform. |
| 18 | +const VARIABLES: [&str; 3] = ["TMPDIR", "TMP", "TEMP"]; |
| 19 | + |
| 20 | +pub(super) struct Temporary(PathBuf); |
| 21 | + |
| 22 | +impl Temporary { |
| 23 | + /// Creates a new private directory in `parent` after cleaning up |
| 24 | + /// directories left by dead runners. Returns `None` if creation fails, |
| 25 | + /// letting the extractor run without one as before. |
| 26 | + pub(super) fn new(parent: &Path) -> Option<Self> { |
| 27 | + static NEXT: AtomicU64 = AtomicU64::new(0); |
| 28 | + sweep(parent); |
| 29 | + let process = std::process::id(); |
| 30 | + (0..100).find_map(|_| { |
| 31 | + let directory = parent.join(format!("{PREFIX}{process}-{}", NEXT.fetch_add(1, Ordering::SeqCst))); |
| 32 | + private(&directory).ok().map(|()| Self(directory)) |
| 33 | + }) |
| 34 | + } |
| 35 | + |
| 36 | + /// Creates a new directory in `parent` and points `environment`'s |
| 37 | + /// temporary directory variables at it. |
| 38 | + pub(super) fn within(parent: &Path, environment: &mut BTreeMap<String, String>) -> Option<Self> { |
| 39 | + let temporary = Self::new(parent)?; |
| 40 | + temporary.apply(environment); |
| 41 | + Some(temporary) |
| 42 | + } |
| 43 | + |
| 44 | + /// Points the extractor's temporary directory variables at this directory. |
| 45 | + fn apply(&self, environment: &mut BTreeMap<String, String>) { |
| 46 | + for name in VARIABLES { |
| 47 | + environment.insert(name.into(), self.0.to_string_lossy().into_owned()); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Parent directory for an extractor's temporary directory: the one named in |
| 53 | +/// `environment` (if granted by the definition), or the system temp directory. |
| 54 | +pub(super) fn parent(environment: &BTreeMap<String, String>) -> PathBuf { |
| 55 | + VARIABLES |
| 56 | + .iter() |
| 57 | + .find_map(|name| environment.get(*name)) |
| 58 | + .map_or_else(std::env::temp_dir, PathBuf::from) |
| 59 | +} |
| 60 | + |
| 61 | +/// Adds to an out-of-space failure that the disk is full and how much space is |
| 62 | +/// free in `parent`, so a full disk isn't mistaken for a broken extractor. An |
| 63 | +/// extractor's failure keeps it in its own message, which reports show. |
| 64 | +pub(super) fn disk_advice(error: anyhow::Error, parent: &Path) -> anyhow::Error { |
| 65 | + let full = |said: &str| { |
| 66 | + let said = said.to_ascii_lowercase(); |
| 67 | + ["no space left on device", "not enough space on the disk"] |
| 68 | + .iter() |
| 69 | + .any(|words| said.contains(words)) |
| 70 | + }; |
| 71 | + let advice = || { |
| 72 | + let free = crate::workspaces::free_space(parent).map_or_else(|| "an unknown amount".to_owned(), crate::workspaces::gib); |
| 73 | + format!( |
| 74 | + "The disk is full: {free} is free in {}, where the extractor's temporary files go. Free some space and run it again", |
| 75 | + parent.display() |
| 76 | + ) |
| 77 | + }; |
| 78 | + match error.downcast::<super::ProcessFailure>() { |
| 79 | + Ok(mut failure) => { |
| 80 | + if full(&format!("{} {}", failure.message, failure.stderr())) { |
| 81 | + failure.message.push_str(&format!(". {}", advice())); |
| 82 | + } |
| 83 | + failure.into() |
| 84 | + } |
| 85 | + Err(error) if full(&format!("{error:#}")) => error.context(advice()), |
| 86 | + Err(error) => error, |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +impl Drop for Temporary { |
| 91 | + fn drop(&mut self) { |
| 92 | + remove(&self.0); |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +#[cfg(unix)] |
| 97 | +fn private(directory: &Path) -> std::io::Result<()> { |
| 98 | + use std::os::unix::fs::DirBuilderExt; |
| 99 | + fs::DirBuilder::new().mode(0o700).create(directory) |
| 100 | +} |
| 101 | + |
| 102 | +#[cfg(not(unix))] |
| 103 | +fn private(directory: &Path) -> std::io::Result<()> { |
| 104 | + fs::create_dir(directory) |
| 105 | +} |
| 106 | + |
| 107 | +/// Removes `directory`. If that fails, it gives its owner (this process's |
| 108 | +/// user) access to every directory inside, which Go's read-only module cache |
| 109 | +/// takes away, and tries again. Links are never followed. |
| 110 | +fn remove(directory: &Path) { |
| 111 | + if fs::remove_dir_all(directory).is_ok() || fs::symlink_metadata(directory).is_err() { |
| 112 | + return; |
| 113 | + } |
| 114 | + accessible(directory); |
| 115 | + let _ = fs::remove_dir_all(directory); |
| 116 | +} |
| 117 | + |
| 118 | +#[cfg(unix)] |
| 119 | +fn accessible(directory: &Path) { |
| 120 | + use std::os::unix::fs::PermissionsExt; |
| 121 | + let Ok(metadata) = fs::symlink_metadata(directory) else { return }; |
| 122 | + if !metadata.is_dir() { |
| 123 | + return; |
| 124 | + } |
| 125 | + let mode = metadata.permissions().mode(); |
| 126 | + let _ = fs::set_permissions(directory, fs::Permissions::from_mode(mode | 0o700)); |
| 127 | + for entry in fs::read_dir(directory).into_iter().flatten().flatten() { |
| 128 | + accessible(&entry.path()); |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +/// Elsewhere a read-only attribute on files is what stops removal. |
| 133 | +#[cfg(not(unix))] |
| 134 | +fn accessible(path: &Path) { |
| 135 | + let Ok(metadata) = fs::symlink_metadata(path) else { return }; |
| 136 | + if metadata.file_type().is_symlink() { |
| 137 | + return; |
| 138 | + } |
| 139 | + let mut permissions = metadata.permissions(); |
| 140 | + #[allow(clippy::permissions_set_readonly_false)] |
| 141 | + permissions.set_readonly(false); |
| 142 | + let _ = fs::set_permissions(path, permissions); |
| 143 | + if metadata.is_dir() { |
| 144 | + for entry in fs::read_dir(path).into_iter().flatten().flatten() { |
| 145 | + accessible(&entry.path()); |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +/// Removes directories in `parent` left by runner processes that have exited. |
| 151 | +fn sweep(parent: &Path) { |
| 152 | + let own = std::process::id(); |
| 153 | + for entry in fs::read_dir(parent).into_iter().flatten().flatten() { |
| 154 | + let name = entry.file_name(); |
| 155 | + let Some(process) = name |
| 156 | + .to_str() |
| 157 | + .and_then(|name| name.strip_prefix(PREFIX)) |
| 158 | + .and_then(|rest| rest.split_once('-')) |
| 159 | + .and_then(|(process, _)| process.parse::<u32>().ok()) |
| 160 | + else { |
| 161 | + continue; |
| 162 | + }; |
| 163 | + if process != own && mine(&entry.path()) && !running(process, &entry.path()) { |
| 164 | + remove(&entry.path()); |
| 165 | + } |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +/// Whether `path` is a directory, not a link, that this process's user owns: |
| 170 | +/// another user's entry in a shared temporary directory is never touched. |
| 171 | +#[cfg(unix)] |
| 172 | +fn mine(path: &Path) -> bool { |
| 173 | + use std::os::unix::fs::MetadataExt; |
| 174 | + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && metadata.uid() == unsafe { libc::geteuid() }) |
| 175 | +} |
| 176 | + |
| 177 | +#[cfg(not(unix))] |
| 178 | +fn mine(path: &Path) -> bool { |
| 179 | + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir()) |
| 180 | +} |
| 181 | + |
| 182 | +/// Whether the runner with process ID `process` may still be using `directory`. |
| 183 | +#[cfg(unix)] |
| 184 | +fn running(process: u32, _directory: &Path) -> bool { |
| 185 | + let Ok(process) = i32::try_from(process) else { return false }; |
| 186 | + // Signal 0 only checks: EPERM means it runs as another user. |
| 187 | + unsafe { libc::kill(process, 0) == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) } |
| 188 | +} |
| 189 | + |
| 190 | +/// Without a cheap liveness check, treat a directory untouched for a day as abandoned. |
| 191 | +#[cfg(not(unix))] |
| 192 | +fn running(_process: u32, directory: &Path) -> bool { |
| 193 | + fs::metadata(directory) |
| 194 | + .and_then(|metadata| metadata.modified()) |
| 195 | + .ok() |
| 196 | + .and_then(|modified| modified.elapsed().ok()) |
| 197 | + .is_none_or(|age| age < std::time::Duration::from_secs(24 * 60 * 60)) |
| 198 | +} |
| 199 | + |
| 200 | +#[cfg(test)] |
| 201 | +mod tests { |
| 202 | + use super::*; |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn the_directory_is_private_named_in_the_environment_and_removed() { |
| 206 | + let parent = tempfile::tempdir().unwrap(); |
| 207 | + let temporary = Temporary::new(parent.path()).unwrap(); |
| 208 | + let directory = temporary.0.clone(); |
| 209 | + assert!(directory.is_dir()); |
| 210 | + #[cfg(unix)] |
| 211 | + { |
| 212 | + use std::os::unix::fs::PermissionsExt; |
| 213 | + assert_eq!(fs::metadata(&directory).unwrap().permissions().mode() & 0o777, 0o700); |
| 214 | + } |
| 215 | + let mut environment = BTreeMap::new(); |
| 216 | + temporary.apply(&mut environment); |
| 217 | + assert_eq!(environment["TMPDIR"], directory.to_string_lossy()); |
| 218 | + assert_eq!(environment["TEMP"], environment["TMP"]); |
| 219 | + // What a killed tool leaves, read-only parts included. |
| 220 | + let left = directory.join("go-build123/b001"); |
| 221 | + fs::create_dir_all(&left).unwrap(); |
| 222 | + fs::write(left.join("a.out"), "binary").unwrap(); |
| 223 | + let mut permissions = fs::metadata(&left).unwrap().permissions(); |
| 224 | + permissions.set_readonly(true); |
| 225 | + fs::set_permissions(&left, permissions).unwrap(); |
| 226 | + drop(temporary); |
| 227 | + assert!(!directory.exists()); |
| 228 | + } |
| 229 | + |
| 230 | + #[cfg(unix)] |
| 231 | + #[test] |
| 232 | + fn directories_of_runners_no_longer_running_are_removed() { |
| 233 | + let parent = tempfile::tempdir().unwrap(); |
| 234 | + // A process that has exited, so its ID names no running process (for now). |
| 235 | + let mut child = std::process::Command::new("true").spawn().unwrap(); |
| 236 | + let gone = child.id(); |
| 237 | + child.wait().unwrap(); |
| 238 | + let abandoned = parent.path().join(format!("{PREFIX}{gone}-0")); |
| 239 | + let live = parent.path().join(format!("{PREFIX}1-0")); |
| 240 | + let unrelated = parent.path().join("go-build42"); |
| 241 | + for directory in [&abandoned, &live, &unrelated] { |
| 242 | + fs::create_dir(directory).unwrap(); |
| 243 | + } |
| 244 | + // A link with the name is never followed. |
| 245 | + let elsewhere = tempfile::tempdir().unwrap(); |
| 246 | + fs::write(elsewhere.path().join("kept"), "").unwrap(); |
| 247 | + let link = parent.path().join(format!("{PREFIX}{gone}-1")); |
| 248 | + std::os::unix::fs::symlink(elsewhere.path(), &link).unwrap(); |
| 249 | + let temporary = Temporary::new(parent.path()).unwrap(); |
| 250 | + assert!(!abandoned.exists()); |
| 251 | + assert!(live.exists(), "process 1 is always running"); |
| 252 | + assert!(unrelated.exists()); |
| 253 | + assert!(temporary.0.exists()); |
| 254 | + assert!(elsewhere.path().join("kept").exists()); |
| 255 | + } |
| 256 | +} |
0 commit comments