use crate::storage::Store;
use fs4::FileExt;
use serde::{Deserialize, Serialize};
use std::{
io,
path::PathBuf,
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
#[derive(Clone, Serialize, Deserialize)]
struct LeaseRecord {
format: String,
owner: String,
host: String,
pid: u32,
process_start: String,
expires: i64,
keys: Vec<String>,
}
fn now() -> i64 {
time::OffsetDateTime::now_utc().unix_timestamp()
}
fn process_start(pid: u32) -> Option<String> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
stat.rsplit_once(") ")?
.1
.split_whitespace()
.nth(19)
.map(str::to_owned)
}
fn record(keys: Vec<String>, format: &str) -> LeaseRecord {
LeaseRecord {
format: format.into(),
owner: crate::storage::run_id(),
host: crate::workspace::host_id(),
pid: std::process::id(),
process_start: process_start(std::process::id()).unwrap_or_default(),
expires: now() + 300,
keys,
}
}
fn scratch() -> PathBuf {
std::env::temp_dir().join(format!("workflow-metadata-{}", unsafe { libc::geteuid() }))
}
pub(crate) struct ConsumerLease {
state: Arc<ConsumerState>,
}
struct ConsumerState {
alive: AtomicBool,
lost: AtomicBool,
wake: Condvar,
wait: Mutex<()>,
}
impl ConsumerLease {
pub(crate) fn acquire(
store: &Store,
run: &str,
keys: Vec<String>,
owner: Option<&str>,
) -> io::Result<Option<Arc<Self>>> {
if keys.is_empty() {
return Ok(None);
}
reject_maintenance(store, run, owner)?;
let mut lease = record(keys, "scientific-workflow-consumer.v1");
let key = format!("{run}/records/readers/{}.json", lease.owner);
store.put_json(&key, &lease, &scratch(), true)?;
if let Err(error) = reject_maintenance(store, run, owner) {
let _ = store.backend.remove(&key);
return Err(error);
}
let state = Arc::new(ConsumerState {
alive: AtomicBool::new(true),
lost: AtomicBool::new(false),
wake: Condvar::new(),
wait: Mutex::new(()),
});
let thread_state = state.clone();
let store = store.clone();
std::thread::spawn(move || {
while thread_state.alive.load(Ordering::Acquire) {
let lock = thread_state.wait.lock().unwrap();
let _ = thread_state
.wake
.wait_timeout(lock, Duration::from_secs(20));
if !thread_state.alive.load(Ordering::Acquire) {
break;
}
lease.expires = now() + 300;
if store.put_json(&key, &lease, &scratch(), false).is_err() {
thread_state.lost.store(true, Ordering::Release);
break;
}
}
let _ = store.backend.remove(&key);
});
Ok(Some(Arc::new(Self { state })))
}
pub(crate) fn check(&self) -> io::Result<()> {
if self.state.lost.load(Ordering::Acquire) {
Err(io::Error::other(
"artifact reader lost its retention lease; retry verified access",
))
} else {
Ok(())
}
}
}
impl Drop for ConsumerLease {
fn drop(&mut self) {
self.state.alive.store(false, Ordering::Release);
self.state.wake.notify_all();
}
}
fn reject_maintenance(store: &Store, run: &str, owner: Option<&str>) -> io::Result<()> {
match store.json::<LeaseRecord>(&format!("{run}/records/seal-lock.json")) {
Ok(record) if owner == Some(record.owner.as_str()) => Ok(()),
Ok(_) => Err(io::Error::new(
io::ErrorKind::WouldBlock,
"run maintenance currently excludes new raw-data readers",
)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
pub(crate) struct MaintenanceLease {
store: Store,
key: String,
owner: String,
_local: std::fs::File,
}
impl MaintenanceLease {
pub(crate) fn owner(&self) -> &str {
&self.owner
}
pub(crate) fn acquire(store: &Store, run: &str) -> io::Result<Self> {
Self::acquire_scope(store, run, false)
}
pub(crate) fn acquire_gc(store: &Store) -> io::Result<Self> {
Self::acquire_scope(store, "root-gc", true)
}
fn acquire_scope(store: &Store, run: &str, gc: bool) -> io::Result<Self> {
let identity = match &store.location {
super::StorageLocation::Filesystem { root } => {
format!("fs:{}", root.canonicalize()?.display())
}
super::StorageLocation::Https { endpoint, .. } => {
format!("https:{}", endpoint.trim_end_matches('/'))
}
super::StorageLocation::Gdrive { folder_id, .. } => format!("drive:{folder_id}"),
};
let local_root = scratch().join("maintenance");
std::fs::create_dir_all(&local_root)?;
let path = local_root.join(crate::artifact::digest_bytes(
format!("{identity}/{run}").as_bytes(),
));
let local = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)?;
FileExt::try_lock(&local).map_err(io::Error::from)?;
let key = if gc {
"gc-lock.json".into()
} else {
format!("{run}/records/seal-lock.json")
};
match store.json::<LeaseRecord>(&key) {
Ok(previous) => {
let same_host = previous.host == crate::workspace::host_id();
let alive =
process_start(previous.pid).as_deref() == Some(previous.process_start.as_str());
if !same_host || alive {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
"run maintenance is owned by another process; foreign-host recovery requires resolving that owner's lease",
));
}
store.backend.remove(&key)?;
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let lease = record(Vec::new(), "scientific-workflow-maintenance.v1");
store.put_json(&key, &lease, &scratch(), true)?;
let guard = Self {
store: store.clone(),
key,
owner: lease.owner,
_local: local,
};
if !gc {
guard.check_consumers(run)?;
}
Ok(guard)
}
pub(crate) fn check_consumers(&self, run: &str) -> io::Result<()> {
for key in self
.store
.backend
.list(&format!("{run}/records/readers/"))?
{
let lease: LeaseRecord = self.store.json(&key)?;
let dead_here = lease.host == crate::workspace::host_id()
&& process_start(lease.pid).as_deref() != Some(lease.process_start.as_str());
if lease.expires > now() && !dead_here {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
"raw artifacts have an active reader or materialization lease; close it before sealing",
));
}
}
Ok(())
}
}
impl Drop for MaintenanceLease {
fn drop(&mut self) {
if self
.store
.json::<LeaseRecord>(&self.key)
.is_ok_and(|record| record.owner == self.owner)
{
let _ = self.store.backend.remove(&self.key);
}
}
}
pub(crate) struct LeasedReader {
pub(crate) input: Box<dyn std::io::Read + Send>,
pub(crate) lease: Option<Arc<ConsumerLease>>,
}
impl std::io::Read for LeasedReader {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if let Some(lease) = &self.lease {
lease.check()?;
}
self.input.read(buffer)
}
}