use std::path::{Path, PathBuf};
use std::sync::MutexGuard;
use std::time::Duration;
pub const FILE_LOCK_WAIT: Duration = Duration::from_secs(120);
pub struct AdmissionGuard {
_process: MutexGuard<'static, ()>,
#[cfg(unix)]
_file: Option<std::fs::File>,
}
pub fn default_lock_path() -> Option<PathBuf> {
crate::credentials::dir().map(|d| d.join("sandbox").join("admission.lock"))
}
fn process_lock() -> MutexGuard<'static, ()> {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
LOCK.lock().unwrap_or_else(|p| p.into_inner())
}
fn provision_process_lock() -> MutexGuard<'static, ()> {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
LOCK.lock().unwrap_or_else(|p| p.into_inner())
}
pub fn provision_lock(wait: Duration) -> Result<AdmissionGuard, String> {
let path = crate::credentials::dir().map(|d| d.join("sandbox").join("provision.lock"));
lock_with(provision_process_lock(), path.as_deref(), wait)
}
pub fn lock_at(path: Option<&Path>, wait: Duration) -> Result<AdmissionGuard, String> {
lock_with(process_lock(), path, wait)
}
fn lock_with(
process: MutexGuard<'static, ()>,
path: Option<&Path>,
wait: Duration,
) -> Result<AdmissionGuard, String> {
#[cfg(unix)]
{
let file = match path {
None => None,
Some(p) => Some(flock_exclusive(p, wait)?),
};
Ok(AdmissionGuard {
_process: process,
_file: file,
})
}
#[cfg(not(unix))]
{
let _ = (path, wait);
Ok(AdmissionGuard { _process: process })
}
}
#[cfg(unix)]
fn flock_exclusive(path: &Path, wait: Duration) -> Result<std::fs::File, String> {
use std::os::unix::io::AsRawFd;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("admission lock dir {dir:?}: {e}"))?;
}
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(path)
.map_err(|e| format!("admission lock {path:?}: {e}"))?;
let deadline = std::time::Instant::now() + wait;
loop {
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc == 0 {
return Ok(file);
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() != Some(libc::EWOULDBLOCK) && err.raw_os_error() != Some(libc::EINTR)
{
return Err(format!("admission lock {path:?}: {err}"));
}
if std::time::Instant::now() >= deadline {
return Err(format!(
"admission lock {path:?} is held by another zc process (waited {}s)",
wait.as_secs()
));
}
std::thread::sleep(Duration::from_millis(20));
}
}
pub fn admission_lock() -> AdmissionGuard {
match lock_at(default_lock_path().as_deref(), FILE_LOCK_WAIT) {
Ok(g) => g,
Err(e) => {
eprintln!(" [SANDBOX] {e}; admitting under the in-process lock only");
AdmissionGuard {
_process: process_lock(),
#[cfg(unix)]
_file: None,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("zc-lock-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
#[cfg(unix)]
#[test]
fn the_file_lock_excludes_a_second_holder_until_it_is_dropped() {
let dir = scratch("excl");
let path = dir.join("sandbox").join("admission.lock");
let first = flock_exclusive(&path, Duration::from_millis(50)).unwrap();
let e = flock_exclusive(&path, Duration::from_millis(60)).unwrap_err();
assert!(e.contains("held by another zc process"), "{e}");
drop(first);
assert!(flock_exclusive(&path, Duration::from_millis(50)).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn the_lock_path_is_injectable_and_created() {
let dir = scratch("inject");
let path = dir.join("a").join("b.lock");
let g = lock_at(Some(&path), Duration::from_millis(50)).unwrap();
assert!(path.exists());
drop(g);
assert!(lock_at(None, Duration::from_millis(1)).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unusable_lock_path_is_an_error_not_a_silent_skip() {
let dir = scratch("bad");
std::fs::create_dir_all(&dir).unwrap();
let blocker = dir.join("file");
std::fs::write(&blocker, "x").unwrap();
let e = lock_at(
Some(&blocker.join("admission.lock")),
Duration::from_millis(1),
);
#[cfg(unix)]
assert!(e.is_err());
#[cfg(not(unix))]
assert!(e.is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
}