crates/state/cache/src/authority.rs 12.4 KiB 350 lines Raw
1 //! One authority per filesystem.2 //!3 //! A cache manager must be the only process deciding what lives on a4 //! filesystem. Two locks enforce that from different directions:5 //!6 //! - an abstract Unix socket named after `st_dev` blocks any second manager on7 //!   the same filesystem, even one whose tier directory is elsewhere;8 //! - a host-mounted `flock` file keyed by `st_dev` in the runtime directory9 //!   covers a manager in another network namespace that cannot see the10 //!   abstract socket;11 //! - an exclusive `flock` on the tier root blocks a manager that can see the12 //!   same directory but not the device lock.13 //!14 //! The abstract socket needs no mount-root write permission. It disappears when15 //! the process dies, so a crash never leaves a stale lock behind.16 17 use std::fs::{self, File, OpenOptions};18 use std::io;19 use std::os::fd::{AsFd, OwnedFd};20 use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};21 use std::path::{Path, PathBuf};22 23 use rustix::fs::{FlockOperation, OFlags, flock, stat, statvfs};24 use rustix::net::{AddressFamily, SocketAddrUnix, SocketType, bind, socket};25 26 use crate::CacheError;27 28 /// A directory that this cache manager owns.29 pub struct TierGuard {30     /// The file that holds the `flock`.31     pub _lock: Option<File>,32     /// The abstract-socket claim for this filesystem.33     pub _claim: Option<OwnedFd>,34     /// A host-mounted lock keyed by `st_dev`. The abstract socket is scoped to35     /// one network namespace; this file is visible to another namespace that36     /// mounts the same authority directory.37     pub _dev_lock: Option<File>,38     /// The device that the directory lives on.39     pub dev: u64,40     /// Bytes available to an unprivileged writer right now.41     pub free: u64,42     /// Bytes in one filesystem block.43     pub _block: u64,44 }45 46 /// Creates a tier root when absent and refuses a symlink or a permissive root.47 /// This is public inside the crate so `Cache::open` can compare every device48 /// before it opens the first claim.49 pub fn prepare_dir(dir: &Path) -> Result<(), CacheError> {50     match fs::symlink_metadata(dir) {51         Ok(meta) if meta.file_type().is_symlink() => {52             return Err(CacheError::Layout(format!(53                 "{} is a symlink; a cache tier must be a directory",54                 dir.display()55             )));56         }57         Ok(meta) if !meta.is_dir() => {58             return Err(CacheError::Layout(format!(59                 "{} is not a directory",60                 dir.display()61             )));62         }63         Ok(meta) if meta.permissions().mode() & 0o077 != 0 => {64             return Err(CacheError::Layout(format!(65                 "{} is mode {:04o}; a cache tier must be 0700",66                 dir.display(),67                 meta.permissions().mode() & 0o777768             )));69         }70         Ok(_) => {}71         Err(why) if why.kind() == io::ErrorKind::NotFound => {72             fs::create_dir_all(dir).map_err(|why| CacheError::io(dir, why))?;73             fs::set_permissions(dir, fs::Permissions::from_mode(0o700))74                 .map_err(|why| CacheError::io(dir, why))?;75         }76         Err(why) => return Err(CacheError::io(dir, why)),77     }78     Ok(())79 }80 81 /// Opens a tier root and claims its filesystem.82 ///83 /// The directory is created `0700` when absent. An existing directory with a84 /// group or world bit is refused: a cache contains prompts, and a permissive85 /// parent must not silently publish them.86 pub fn open_tier(dir: &Path, authority: bool) -> Result<TierGuard, CacheError> {87     prepare_dir(dir)?;88     let stat = stat(dir).map_err(|why| CacheError::io(dir, why.into()))?;89     let dev = stat.st_dev;90     let vfs = statvfs(dir).map_err(|why| CacheError::io(dir, why.into()))?;91     let free = vfs.f_bavail.saturating_mul(vfs.f_frsize);92     let block = vfs.f_frsize.max(1);93 94     let (claim, dev_lock, lock) = if authority {95         let claim = claim(dev)?;96         let dev_lock = device_lock(dev)?;97         let lock_path = dir.join(".lock");98         let lock = OpenOptions::new()99             .read(true)100             .write(true)101             .create(true)102             .truncate(false)103             .mode(0o600)104             .custom_flags(OFlags::NOFOLLOW.bits() as i32)105             .open(&lock_path)106             .map_err(|why| CacheError::io(&lock_path, why))?;107         flock(lock.as_fd(), FlockOperation::NonBlockingLockExclusive).map_err(|why| {108             CacheError::Busy(format!(109                 "{} is already owned by another cache manager: {why}",110                 dir.display()111             ))112         })?;113         (Some(claim), Some(dev_lock), Some(lock))114     } else {115         (None, None, None)116     };117 118     let tmp = dir.join(".tmp");119     ensure_dir(&tmp)?;120     for entry in fs::read_dir(&tmp).map_err(|why| CacheError::io(&tmp, why))? {121         let entry = entry.map_err(|why| CacheError::io(&tmp, why))?;122         let _ = fs::remove_file(entry.path());123     }124     ensure_dir(&dir.join("entries"))?;125     Ok(TierGuard {126         _lock: lock,127         _claim: claim,128         _dev_lock: dev_lock,129         dev,130         free,131         _block: block,132     })133 }134 135 fn ensure_dir(path: &Path) -> Result<(), CacheError> {136     match fs::create_dir(path) {137         Ok(()) => fs::set_permissions(path, fs::Permissions::from_mode(0o700))138             .map_err(|why| CacheError::io(path, why)),139         Err(why) if why.kind() == io::ErrorKind::AlreadyExists => {140             let meta = fs::symlink_metadata(path).map_err(|why| CacheError::io(path, why))?;141             if meta.file_type().is_symlink()142                 || !meta.is_dir()143                 || meta.permissions().mode() & 0o077 != 0144             {145                 return Err(CacheError::Layout(format!(146                     "{} must be a real 0700 directory",147                     path.display()148                 )));149             }150             Ok(())151         }152         Err(why) => Err(CacheError::io(path, why)),153     }154 }155 156 /// Claims one device with an abstract socket.157 fn claim(dev: u64) -> Result<OwnedFd, CacheError> {158     let name = format!("inf3r-cache-fs-{}:{}", major(dev), minor(dev));159     let fd = socket(AddressFamily::UNIX, SocketType::STREAM, None)160         .map_err(|why| CacheError::Busy(format!("cannot create the cache claim: {why}")))?;161     let address = SocketAddrUnix::new_abstract_name(name.as_bytes())162         .map_err(|why| CacheError::Busy(format!("cannot name the cache claim {name}: {why}")))?;163     bind(&fd, &address).map_err(|why| {164         CacheError::Busy(format!(165             "filesystem {name} already has a cache manager: {why}"166         ))167     })?;168     Ok(fd)169 }170 171 /// One fixed path per user and filesystem, outside every tier.172 ///173 /// `/run/user/<uid>` is the host-mounted runtime directory: a rootless174 /// container that mounts it sees the same lock as the host service. The temp175 /// directory is the fallback for a machine without a runtime directory; an176 /// operator that runs managers in separate mount namespaces must arrange the177 /// same `INF3R_CACHE_AUTHORITY_DIR` for all of them.178 fn authority_dir() -> PathBuf {179     if let Some(dir) = std::env::var_os("INF3R_CACHE_AUTHORITY_DIR") {180         return PathBuf::from(dir);181     }182     let uid = fs::metadata("/proc/self")183         .map(|meta| meta.uid())184         .unwrap_or(0);185     let run = PathBuf::from(format!("/run/user/{uid}"));186     if run.is_dir() {187         run188     } else {189         std::env::temp_dir()190     }191 }192 193 /// Claims the filesystem itself, not only one directory on it.194 fn device_lock(dev: u64) -> Result<File, CacheError> {195     let dir = authority_dir();196     fs::create_dir_all(&dir).map_err(|why| CacheError::io(&dir, why))?;197     let path = dir.join(format!(198         "inf3r-cache-dev-{}-{}.lock",199         major(dev),200         minor(dev)201     ));202     let file = OpenOptions::new()203         .read(true)204         .write(true)205         .create(true)206         .truncate(false)207         .mode(0o600)208         .custom_flags(OFlags::NOFOLLOW.bits() as i32)209         .open(&path)210         .map_err(|why| CacheError::io(&path, why))?;211     flock(file.as_fd(), FlockOperation::NonBlockingLockExclusive).map_err(|why| {212         CacheError::Busy(format!(213             "filesystem {}:{} already has a cache manager: {why}",214             major(dev),215             minor(dev)216         ))217     })?;218     Ok(file)219 }220 221 /// What a read-only preflight found about one tier.222 #[derive(Clone, Copy, Debug)]223 pub struct TierProbe {224     pub dev: u64,225     pub free: u64,226     /// The tier lock or the device claim is already held by a live manager.227     pub held: bool,228 }229 230 /// Checks a tier without creating it or clearing its temp directory.231 ///232 /// `doctor` uses this. A held claim is not a failure: it is the one-authority233 /// invariant working while the service is running.234 pub fn probe_tier(dir: &Path) -> Result<TierProbe, CacheError> {235     let meta = fs::symlink_metadata(dir).map_err(|why| CacheError::io(dir, why))?;236     if meta.file_type().is_symlink() || !meta.is_dir() {237         return Err(CacheError::Layout(format!(238             "{} is not a real directory",239             dir.display()240         )));241     }242     if meta.permissions().mode() & 0o077 != 0 {243         return Err(CacheError::Layout(format!(244             "{} is mode {:04o}; a cache tier must be 0700",245             dir.display(),246             meta.permissions().mode() & 0o7777247         )));248     }249     for child in [".tmp", "entries"] {250         let path = dir.join(child);251         match fs::symlink_metadata(&path) {252             Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => {253                 return Err(CacheError::Layout(format!(254                     "{} must be a real directory",255                     path.display()256                 )));257             }258             Ok(_) => {}259             Err(why) if why.kind() == io::ErrorKind::NotFound => {}260             Err(why) => return Err(CacheError::io(&path, why)),261         }262     }263     let stat = stat(dir).map_err(|why| CacheError::io(dir, why.into()))?;264     let dev = stat.st_dev;265     let vfs = statvfs(dir).map_err(|why| CacheError::io(dir, why.into()))?;266     let free = vfs.f_bavail.saturating_mul(vfs.f_frsize);267     let mut held = false;268     match claim(dev) {269         Ok(claim) => drop(claim),270         Err(CacheError::Busy(_)) => held = true,271         Err(why) => return Err(why),272     }273     let lock_path = dir.join(".lock");274     match OpenOptions::new()275         .read(true)276         .write(true)277         .custom_flags(OFlags::NOFOLLOW.bits() as i32)278         .open(&lock_path)279     {280         Ok(lock) => {281             if flock(lock.as_fd(), FlockOperation::NonBlockingLockExclusive).is_err() {282                 held = true;283             }284         }285         Err(why) if why.kind() == io::ErrorKind::NotFound => {}286         Err(why) => return Err(CacheError::io(&lock_path, why)),287     }288     let dev_lock = authority_dir().join(format!(289         "inf3r-cache-dev-{}-{}.lock",290         major(dev),291         minor(dev)292     ));293     match OpenOptions::new()294         .read(true)295         .write(true)296         .custom_flags(OFlags::NOFOLLOW.bits() as i32)297         .open(&dev_lock)298     {299         Ok(lock) => {300             if flock(lock.as_fd(), FlockOperation::NonBlockingLockExclusive).is_err() {301                 held = true;302             }303         }304         Err(why) if why.kind() == io::ErrorKind::NotFound => {}305         Err(why) => return Err(CacheError::io(&dev_lock, why)),306     }307     Ok(TierProbe { dev, free, held })308 }309 310 /// Bytes free on an already-open tier.311 pub fn free_bytes(_guard: &TierGuard, dir: &Path) -> Result<u64, CacheError> {312     let vfs = statvfs(dir).map_err(|why| CacheError::io(dir, why.into()))?;313     Ok(vfs.f_bavail.saturating_mul(vfs.f_frsize))314 }315 316 /// The Linux `major(3)` encoding of a `dev_t`.317 pub const fn major(dev: u64) -> u64 {318     ((dev >> 8) & 0xfff) | ((dev >> 32) & !0xfff)319 }320 321 /// The Linux `minor(3)` encoding of a `dev_t`.322 pub const fn minor(dev: u64) -> u64 {323     (dev & 0xff) | ((dev >> 12) & !0xff)324 }325 326 /// Creates a temp file with `O_EXCL | O_NOFOLLOW` and mode `0600`.327 pub fn create_temp(path: &Path) -> Result<File, CacheError> {328     OpenOptions::new()329         .read(true)330         .write(true)331         .create_new(true)332         .mode(0o600)333         .custom_flags(OFlags::NOFOLLOW.bits() as i32)334         .open(path)335         .map_err(|why| CacheError::io(path, why))336 }337 338 /// Opens a committed entry with `O_NOFOLLOW`.339 pub fn open_read(path: &Path) -> Result<File, CacheError> {340     OpenOptions::new()341         .read(true)342         .custom_flags(OFlags::NOFOLLOW.bits() as i32)343         .open(path)344         .map_err(|why| CacheError::io(path, why))345 }346 347 /// The path of one shard under a tier.348 pub fn shard_path(tier_dir: &Path, id: &[u8; 32]) -> PathBuf {349     tier_dir.join("entries").join(format!("{:02x}", id[0]))350 }