diff --git a/src/workerd/server/BUILD.bazel b/src/workerd/server/BUILD.bazel index 5bd5332c6db..71603814030 100644 --- a/src/workerd/server/BUILD.bazel +++ b/src/workerd/server/BUILD.bazel @@ -377,6 +377,7 @@ wd_cc_library( ], visibility = ["//visibility:public"], deps = [ + "//src/workerd/util:strong-bool", "@capnp-cpp//src/kj", ], ) diff --git a/src/workerd/server/cluster/capture-test.rs b/src/workerd/server/cluster/capture-test.rs index 6ce6e319bd6..d6d33688f5a 100644 --- a/src/workerd/server/cluster/capture-test.rs +++ b/src/workerd/server/cluster/capture-test.rs @@ -408,8 +408,13 @@ impl Sim { return Err(format!("{} is live but not captured", d.lane)); } let spool = self.dir.join(format!("restore-{}", self.session)); - let (end, lanes) = block(crate::log::restore(&self.log, self.session, &spool)) - .map_err(|e| format!("restore: {e}"))?; + let (end, lanes) = block(crate::log::restore( + &self.log, + self.session, + &spool, + &(std::sync::Arc::new(()) as crate::owner::Share), + )) + .map_err(|e| format!("restore: {e}"))?; let got: BTreeMap<_, _> = lanes .iter() .map(|(lane, path)| (lane.clone(), std::fs::read(path).unwrap())) diff --git a/src/workerd/server/cluster/cluster.rs b/src/workerd/server/cluster/cluster.rs index 0ef2584ec6c..09c653008b7 100644 --- a/src/workerd/server/cluster/cluster.rs +++ b/src/workerd/server/cluster/cluster.rs @@ -159,8 +159,15 @@ impl Cluster { // Named open here, but not open here. Evicted here with the bucket // holding the epoch: resume it (`take_over`); a stale owner that // writes on cannot acknowledge, since every acknowledgement rereads - // own.json. Otherwise, dropped after a failure or evicted before its - // upload completed: recover it at the next epoch. + // own.json. Otherwise, dropped after a failure, evicted before its + // upload completed or its files failed to sync: recover it at the + // next epoch. An eviction of the epoch still running decides which. + if let Claim::Owned(owned) = &claim + && owned.recover.is_none() + && !self.owners.holds(ns, actor) + { + self.owners.evicted(ns, actor, owned.epoch).await; + } if let Claim::Owned(owned) = &claim && owned.recover.is_none() && !self.owners.holds(ns, actor) @@ -317,6 +324,12 @@ impl Cluster { self.owners.tier().await; } + /// Counts an eviction of an object as running, for the claims here to + /// wait for, until the guard is dropped (`Owners::evicting`). + pub fn evicting(&self, ns: &str, actor: &str, epoch: u64) -> crate::Evicting { + self.owners.evicting(ns, actor, epoch) + } + /// Keep an object workerd evicted, uploading what the bucket lacks. pub async fn evict_actor(&self, ns: &str, actor: &str, epoch: u64) { self.owners.evict(ns, actor, epoch).await; @@ -414,22 +427,27 @@ impl Cluster { } step = self.lease.borrow_mut().renewed(now_ms(), result); } - let delay = match step { + let wait = match step { Step::Fence(reason) => return reason, Step::Retry(reason) => { tracing::warn!("renewing the cluster lease failed; retrying: {reason}"); - timing.retry_ms + tokio::time::sleep(ms(timing.retry_ms)).await; + continue; } - Step::Renew => timing.interval_ms, + Step::Renew => tokio::time::sleep(ms(timing.interval_ms)), }; // A stale listing only delays routing to a new peer: its - // failure is logged, never fatal. - match timeout(ms(timing.list_timeout_ms), self.list_round(&timing)).await { - Ok(Ok(_)) => {} - Ok(Err(e)) => tracing::warn!("listing the cluster failed: {e}"), - Err(_) => tracing::warn!("listing the cluster timed out"), - } - tokio::time::sleep(ms(delay)).await; + // failure is logged, never fatal. It runs during the wait for + // the next renewal, which a slow one delays only past that wait, + // and not after a failed renewal, whose retry it would delay. + let list = async { + match timeout(ms(timing.list_timeout_ms), self.list_round(&timing)).await { + Ok(Ok(_)) => {} + Ok(Err(e)) => tracing::warn!("listing the cluster failed: {e}"), + Err(_) => tracing::warn!("listing the cluster timed out"), + } + }; + futures::join!(list, wait); } } @@ -491,8 +509,8 @@ impl Cluster { !self.ownership.may_claim.get() } - /// The first renewal, before the node links its services: their - /// storage opens only under a lease. + /// The first renewal, before the node links its services, after a + /// check that the bucket keeps conditional writes. pub async fn join(&self) -> Result<()> { let probe = format!("nodes/{}.probe", self.node()); check_conditional_writes(&self.bucket, &probe).await?; @@ -500,12 +518,16 @@ impl Cluster { } /// Renews the lease once more as the node starts serving, so that its - /// first maintenance round finds the lease held. Linking, after `join`, - /// opens every namespace's storage, which on a slow disk takes most of - /// a lease. A lease that lapsed meanwhile is renewed, not fenced on: - /// the node has run no actor and claimed nothing a peer could take over. + /// first maintenance round finds the lease held; from then on its actors + /// run only while the lease holds (`actors_may_run`). Linking, after + /// `join`, opens every namespace's storage, which on a slow disk or a + /// loaded machine outlasts a lease. A lease that lapsed meanwhile is + /// renewed, not fenced on: the node has run no actor and claimed nothing + /// a peer could take over. pub async fn renew_to_serve(&self) -> Result<()> { - self.take_lease().await + self.take_lease().await?; + self.lease.borrow_mut().requires_live_lease = true; + Ok(()) } async fn take_lease(&self) -> Result<()> { @@ -514,11 +536,16 @@ impl Cluster { Ok(()) } - /// Whether this node's lease holds now: an actor database opens only - /// while it does. + /// Whether this node's lease holds now. pub fn lease_holds(&self) -> bool { self.lease.borrow().holds(now_ms()) } + + /// Whether this node's actors may run and open their databases now: + /// before it serves, always; then while its lease holds. + pub fn actors_may_run(&self) -> bool { + self.lease.borrow().allows_actors(now_ms()) + } } /// How often owned objects' logs are checked for compaction. diff --git a/src/workerd/server/cluster/lib.rs b/src/workerd/server/cluster/lib.rs index 168297c7fad..297c1902e56 100644 --- a/src/workerd/server/cluster/lib.rs +++ b/src/workerd/server/cluster/lib.rs @@ -74,8 +74,10 @@ pub use cluster::open_bucket; pub use log::DB; pub use log::facet_path; pub use log::facet_prefix; +pub use owner::Evicting; pub use owner::Layout; pub use owner::Owners; +pub use owner::Removal; pub use ownership::Claim; pub use ownership::Ownership; pub use registry::NodeRecord; diff --git a/src/workerd/server/cluster/log.rs b/src/workerd/server/cluster/log.rs index 86aa72c1f02..30f4cc7f83e 100644 --- a/src/workerd/server/cluster/log.rs +++ b/src/workerd/server/cluster/log.rs @@ -45,6 +45,8 @@ use crate::Bucket; use crate::Error; use crate::Result; use crate::Sequence; +use crate::owner::Share; +use crate::owner::blocking_sharing; /// A database's lane, after its facet's prefix. pub const DB: &str = "db"; @@ -765,18 +767,21 @@ impl Log { /// Restores `session` of the log into `spool`, created empty: the plan's /// files downloaded, then replayed on the blocking pool. The frame the log /// continues from, 0 for an empty log, and each live lane's name and -/// database, under `spool`. +/// database, under `spool`. Each task it starts on the blocking pool keeps +/// a clone of `share` until it ends, but for the downloads' writers. pub async fn restore( log: &Log, session: u32, spool: &Path, + share: &Share, ) -> Result<(Sequence, Vec<(String, PathBuf)>)> { let plan = plan(&log.files(session).await?); if plan.is_empty() { return Ok((0, Vec::new())); } let downloads = spool.join("files"); - std::fs::create_dir_all(&downloads)?; + let created = downloads.clone(); + blocking_sharing(share, move || Ok(std::fs::create_dir_all(&created)?)).await?; let files: Vec<_> = (0..plan.len()) .map(|i| (plan[i], downloads.join(i.to_string()))) .collect(); @@ -786,7 +791,7 @@ pub async fn restore( .try_collect::<()>() .await?; let lanes = spool.join("lanes"); - let restored = crate::owner::blocking(move || { + let restored = blocking_sharing(share, move || { let mut replay = Replay::new(&lanes)?; for (f, path) in &files { replay.apply(f, path)?; @@ -794,7 +799,7 @@ pub async fn restore( replay.finish() }) .await; - let _ = std::fs::remove_dir_all(&downloads); + let _ = blocking_sharing(share, move || Ok(std::fs::remove_dir_all(&downloads)?)).await; restored } diff --git a/src/workerd/server/cluster/log_tests.rs b/src/workerd/server/cluster/log_tests.rs index 4aaa2839080..8d2638ca520 100644 --- a/src/workerd/server/cluster/log_tests.rs +++ b/src/workerd/server/cluster/log_tests.rs @@ -334,10 +334,15 @@ fn upload_snapshot(store: &Bucket, to: Sequence) { .unwrap(); } +/// A share of no hold. +fn share() -> crate::owner::Share { + std::sync::Arc::new(()) +} + /// Restores the log's lanes into a spool, moving the root's to `out`. fn restore_db(store: &Bucket, out: &Path) -> crate::Result { let spool = crate::log::with_suffix(out, ".spool"); - let (end, lanes) = runtime().block_on(restore(&log(store), 0, &spool))?; + let (end, lanes) = runtime().block_on(restore(&log(store), 0, &spool, &share()))?; for (lane, path) in lanes { if lane == DB { std::fs::rename(path, out)?; @@ -751,11 +756,14 @@ impl Layout for Root { Ok(self.0.clone()) } - fn clear(&self) -> crate::Result<()> { - for suffix in ["", "-wal", "-shm"] { - let _ = std::fs::remove_file(crate::log::with_suffix(&self.0, suffix)); - } - Ok(()) + fn clear(&self) -> crate::Result { + let path = self.0.clone(); + Ok(Box::new(move || { + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(crate::log::with_suffix(&path, suffix)); + } + Ok(()) + })) } } @@ -779,7 +787,7 @@ fn remove(path: &Path) { /// Every lane the log restores, with its rows. fn restored_lanes(store: &Bucket, name: &str) -> BTreeMap { let (_, lanes) = runtime() - .block_on(restore(&log(store), 0, &scratch(name))) + .block_on(restore(&log(store), 0, &scratch(name), &share())) .unwrap(); let open = |path: PathBuf| rows(&Connection::open(path.to_str().unwrap())); lanes.into_iter().map(|(l, path)| (l, open(path))).collect() diff --git a/src/workerd/server/cluster/logic/lease-test.rs b/src/workerd/server/cluster/logic/lease-test.rs index d8507312f03..7f7402f25dd 100644 --- a/src/workerd/server/cluster/logic/lease-test.rs +++ b/src/workerd/server/cluster/logic/lease-test.rs @@ -59,6 +59,20 @@ fn renews_and_holds_until_the_safety_margin() { } } +#[test] +fn actors_need_the_lease_only_once_the_instance_serves() { + for t in timings() { + let mut lease = Lease::new(t); + assert_eq!(lease.renewed(0, Ok(t.lease_ms)), Step::Renew); + // Startup outlasted the lease: storage still opens. + assert!(!lease.holds(t.lease_ms) && lease.allows_actors(t.lease_ms)); + lease.requires_live_lease = true; + assert!(!lease.allows_actors(t.lease_ms)); + assert_eq!(lease.renewed(t.lease_ms, Ok(2 * t.lease_ms)), Step::Renew); + assert!(lease.allows_actors(t.lease_ms)); + } +} + #[test] fn a_failed_renewal_retries_until_the_lease_nearly_lapses() { for t in timings() { diff --git a/src/workerd/server/cluster/logic/lease.rs b/src/workerd/server/cluster/logic/lease.rs index bad980c015a..406c0382b44 100644 --- a/src/workerd/server/cluster/logic/lease.rs +++ b/src/workerd/server/cluster/logic/lease.rs @@ -150,6 +150,11 @@ pub struct Lease { until_ms: u64, /// The instance left the cluster: it renews no more. pub left: bool, + /// Set as the instance starts serving: from then on its actors run + /// only while the lease holds. Until then none has run and a peer can + /// take nothing over, so its storage opens whether or not the lease + /// holds. + pub requires_live_lease: bool, } impl Lease { @@ -193,6 +198,12 @@ impl Lease { pub fn holds(&self, now_ms: u64) -> bool { now_ms + self.timing.safety_ms() < self.until_ms } + + /// Whether the instance's actors may run and open their databases at + /// `now_ms`: before it serves, always; then while the lease holds. + pub fn allows_actors(&self, now_ms: u64) -> bool { + !self.requires_live_lease || self.holds(now_ms) + } } #[cfg(test)] diff --git a/src/workerd/server/cluster/owner-test.rs b/src/workerd/server/cluster/owner-test.rs index 7c955fcbc17..26793385a82 100644 --- a/src/workerd/server/cluster/owner-test.rs +++ b/src/workerd/server/cluster/owner-test.rs @@ -158,11 +158,14 @@ impl Layout for Files { Ok(path.clone()) } - fn clear(&self) -> crate::Result<()> { + fn clear(&self) -> crate::Result { self.placed.borrow_mut().clear(); - std::fs::remove_dir_all(&self.dir)?; - std::fs::create_dir_all(&self.dir)?; - Ok(()) + let dir = self.dir.clone(); + Ok(Box::new(move || { + std::fs::remove_dir_all(&dir)?; + std::fs::create_dir_all(&dir)?; + Ok(()) + })) } } diff --git a/src/workerd/server/cluster/owner.rs b/src/workerd/server/cluster/owner.rs index 9a4b3b50129..fe36097752d 100644 --- a/src/workerd/server/cluster/owner.rs +++ b/src/workerd/server/cluster/owner.rs @@ -17,6 +17,7 @@ use std::collections::HashSet; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; +use std::sync::Arc; use futures::StreamExt; use futures::stream; @@ -47,10 +48,14 @@ pub trait Layout { /// The database file of lane `lane`, its facet numbered if new. fn place(&self, lane: &str) -> Result; /// Removes every local file of the object: databases, WALs, and - /// whatever numbers its facets. - fn clear(&self) -> Result<()>; + /// whatever numbers its facets. Answers the removal, which runs on the + /// blocking pool; what must happen on this thread happens first. + fn clear(&self) -> Result; } +/// File system work that runs off the event loop. +pub type Removal = Box Result<()> + Send>; + /// An owned object, its capture, and how far its commits are acknowledged. struct Slot { object: tokio::sync::Mutex, @@ -129,6 +134,9 @@ pub struct Owners { opened: RefCell>, /// Objects workerd closed, until their eviction. retiring: RefCell>>, + /// Evictions running, by object: the epoch, and a receiver whose sender + /// the eviction drops once it has settled whether the object is dormant. + evicting: Evictions, /// Evictions in flight. Objects written together go idle together, and /// a node's lease renewals must not wait behind all their uploads. evictions: tokio::sync::Semaphore, @@ -137,6 +145,116 @@ pub struct Owners { dormant: RefCell>, /// Objects whose compaction is in flight. compacting: RefCell>, + /// Per object, the lock of `Hold`. + holds: Arc, + /// The restores begun, each with a spool of its own (`open_spool`). + restores: Cell, +} + +/// Each object's `Hold` lock, while anything holds or awaits it. +type Holds = std::sync::Mutex>>; + +type HoldLock = tokio::sync::Mutex; + +/// What a `Hold` lock guards: its entry in `Holds`, which goes with the +/// lock's last reference, on whichever thread drops it, a blocking task's +/// included. +struct HoldEntry { + holds: Arc, + key: String, +} + +impl Drop for HoldEntry { + fn drop(&mut self) { + let mut holds = self + .holds + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + // Unless a holder made the object a new lock since. + if holds.get(&self.key).is_some_and(|w| w.strong_count() == 0) { + holds.remove(&self.key); + } + } +} + +/// A hold on an object's local files, for a takeover or the sync of an +/// eviction. Each task the holder starts on the blocking pool shares it, so +/// that a holder dropped meanwhile, a takeover cancelled, holds the object +/// until the last such task has finished: the next holder waits, and never +/// removes, moves or reads the files beside a task of the last. The files' +/// paths are the object's whatever the epoch, so an epoch cannot tell them +/// apart. +struct Hold(Arc>); + +impl Hold { + async fn new(owners: &Owners, key: &str) -> Self { + let lock = { + let mut holds = owners + .holds + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let held = holds.get(key).and_then(std::sync::Weak::upgrade); + held.unwrap_or_else(|| { + let lock = Arc::new(HoldLock::new(HoldEntry { + holds: Arc::clone(&owners.holds), + key: key.to_owned(), + })); + holds.insert(key.to_owned(), Arc::downgrade(&lock)); + lock + }) + }; + Self(Arc::new(lock.lock_owned().await)) + } + + /// A share of the hold, for a task the holder starts. + fn share(&self) -> Share { + Arc::clone(&self.0) as Share + } + + async fn blocking( + &self, + f: impl FnOnce() -> Result + Send + 'static, + ) -> Result { + blocking_sharing(&self.share(), f).await + } +} + +/// Evictions running, by object (`Owners::evicting`). +type Evictions = Rc)>>>; + +/// An object's eviction in flight, until this is dropped (`Owners::evicted`). +pub struct Evicting { + running: Evictions, + key: String, + settling: tokio::sync::watch::Receiver<()>, + _settled: tokio::sync::watch::Sender<()>, +} + +impl Evicting { + fn new(owners: &Owners, key: String, epoch: Epoch) -> Self { + let (settled, settling) = tokio::sync::watch::channel(()); + let entry = (epoch, settling.clone()); + owners.evicting.borrow_mut().insert(key.clone(), entry); + Self { + running: Rc::clone(&owners.evicting), + key, + settling, + _settled: settled, + } + } +} + +impl Drop for Evicting { + fn drop(&mut self) { + let mut evicting = self.running.borrow_mut(); + // Unless a later eviction of the object replaced it. + if evicting + .get(&self.key) + .is_some_and(|(_, settling)| settling.same_channel(&self.settling)) + { + evicting.remove(&self.key); + } + } } /// An object's compaction in flight, until this is dropped. @@ -162,9 +280,12 @@ impl Owners { objects: RefCell::new(HashMap::new()), opened: RefCell::new(HashMap::new()), retiring: RefCell::new(HashMap::new()), + evicting: Rc::default(), evictions: tokio::sync::Semaphore::new(EVICT_CONCURRENCY), dormant: RefCell::new(HashMap::new()), compacting: RefCell::new(HashSet::new()), + holds: Arc::default(), + restores: Cell::new(0), } } @@ -186,6 +307,20 @@ impl Owners { actor: &str, owned: &Owned, layout: &dyn Layout, + ) -> Result<()> { + let hold = Hold::new(self, &object_key(ns, actor)).await; + self.take_over_held(ownership, ns, actor, owned, layout, &hold) + .await + } + + async fn take_over_held( + &self, + ownership: &Ownership, + ns: &str, + actor: &str, + owned: &Owned, + layout: &dyn Layout, + hold: &Hold, ) -> Result<()> { let key = object_key(ns, actor); let path = &layout.place(DB)?; @@ -228,18 +363,35 @@ impl Owners { // longer describes dormant. self.retiring.borrow_mut().remove(&key); self.dormant.borrow_mut().remove(&key); - layout.clear()?; - remove_dir(&cache_root(path))?; + hold.blocking(layout.clear()?).await?; if let Some(recover) = recover { // Nothing in the bucket: an object that committed nothing. let log = self.client(ns, actor); - let spool = crate::log::with_suffix(path, ".restore"); - let restored = crate::log::restore(&log, recover as u32, &spool).await; - let placed = restored.and_then(|(end, lanes)| { - databases = place(layout, lanes)?; - Ok(end) - }); - remove_dir(&spool)?; + let spools = crate::log::with_suffix(path, ".restore"); + let spool = { + let restore = self.restores.get(); + self.restores.set(restore + 1); + let spools = spools.clone(); + hold.blocking(move || Ok(open_spool(&spools, restore)?)) + .await? + }; + let restored = + crate::log::restore(&log, recover as u32, &spool, &hold.share()).await; + let placed = match restored { + Ok((end, lanes)) => place(layout, lanes, hold).await.map(|placed| { + databases = placed; + end + }), + Err(e) => Err(e), + }; + // As `open_spool` would: the restore may have left downloads + // behind if it failed. + hold.blocking(move || { + let _ = std::fs::remove_dir_all(&spool); + let _ = std::fs::remove_dir(&spools); + Ok(()) + }) + .await?; let end = placed?; tracing::info!( "cluster: {ns}/{actor} epoch {} recovers {recover}: bucket up to {end}, \ @@ -252,13 +404,18 @@ impl Owners { // The state the epoch inherits is its session's snapshot at frame // 0, written from the files on the blocking pool; a new object has // none. - let cache = open_cache(path, owned.epoch)?; + let cache = { + let (root, epoch) = (cache_root(path), owned.epoch); + hold.blocking(move || Ok(open_epoch_dir(&root, epoch)?)) + .await? + }; let session = owned.epoch as u32; let (snapshot, lanes) = if self.opened.borrow().contains_key(&key) { (None, Vec::new()) } else { let (databases, cache) = (databases.clone(), cache.clone()); - blocking(move || crate::log::snapshot_file(&databases, &cache, session)).await? + hold.blocking(move || crate::log::snapshot_file(&databases, &cache, session)) + .await? }; let cursor = Cursor { session, @@ -569,19 +726,36 @@ impl Owners { /// lacks, and remember that this node's file holds the epoch. The record /// still names this node, so other nodes route here, and the next /// request wakes it without a restore. + /// + /// Its files are synced first. Workerd writes a clustered object's files + /// without syncing them, the bucket holding each commit, so a write the + /// OS failed to write back would surface nowhere: the wake would read + /// what the OS kept in its stead. The sync reports it, and the object + /// is not kept; the next request restores it from the bucket. pub async fn evict(&self, ns: &str, actor: &str, epoch: Epoch) { - let _permit = self.evictions.acquire().await; let key = object_key(ns, actor); + let _evicting = Evicting::new(self, key.clone(), epoch); + let _permit = self.evictions.acquire().await; let Some(slot) = self.retiring.borrow().get(&key).cloned() else { return; }; + // Not held: an upload can take long, and a takeover here, at the next + // epoch, need not wait for it (`open_epoch_dir`). self.tier_one(&slot).await; + let databases = slot.capture.borrow().databases(); + let synced = Hold::new(self, &key) + .await + .blocking(move || sync_object(&databases)) + .await; // Still retiring: no takeover here cleared its files meanwhile. let current = self.retiring.borrow().get(&key).cloned(); if !current.is_some_and(|r| Rc::ptr_eq(&r, &slot)) { return; } self.retiring.borrow_mut().remove(&key); + if let Err(e) = synced { + return tracing::warn!("cluster: {key} is not kept, its files failed to sync: {e}"); + } let mut guard = slot.object.lock().await; let last = slot.capture.borrow().last(); guard.cursor = slot.capture.borrow().cursor(); @@ -596,6 +770,28 @@ impl Owners { } } + /// Counts an eviction of an object at `epoch` as running until the + /// guard is dropped, from before the eviction itself starts (`evict` + /// counts it from its own start). + pub fn evicting(&self, ns: &str, actor: &str, epoch: Epoch) -> Evicting { + Evicting::new(self, object_key(ns, actor), epoch) + } + + /// Waits for an eviction here of an object at `epoch`, if one is + /// running, to settle whether the object is `dormant` at the epoch. Its + /// sync can outlast the object's idle time: a request in the meantime + /// would otherwise find the object neither open nor dormant, and recover + /// it at the next epoch. An eviction awaits nothing a claim holds. + pub async fn evicted(&self, ns: &str, actor: &str, epoch: Epoch) { + let evicting = self.evicting.borrow().get(&object_key(ns, actor)).cloned(); + if let Some((evicted, mut settling)) = evicting + && evicted == epoch + { + // Fails once the eviction drops the sender. + let _ = settling.changed().await; + } + } + /// The epoch this node evicted an object at, with the bucket holding it. pub fn dormant(&self, ns: &str, actor: &str) -> Option { let dormant = self.dormant.borrow(); @@ -710,6 +906,22 @@ fn tmp_path(path: &Path) -> PathBuf { tmp.into() } +/// What a task keeps while it runs: a share of a hold on its files. +pub type Share = Arc; + +/// `blocking`, keeping a clone of `share` until `f` returns. +pub async fn blocking_sharing( + share: &Share, + f: impl FnOnce() -> Result + Send + 'static, +) -> Result { + let share = Arc::clone(share); + blocking(move || { + let _share = share; + f() + }) + .await +} + pub async fn blocking( f: impl FnOnce() -> Result + Send + 'static, ) -> Result { @@ -731,14 +943,85 @@ struct Replica { session: u32, } -/// The copies' directory for `epoch` of the database at `path`, created -/// empty. Other epochs' copies are removed. -fn open_cache(path: &Path, epoch: Epoch) -> Result { - let root = cache_root(path); - remove_dir(&root)?; - let cache = root.join(format!("e{epoch}")); - std::fs::create_dir_all(&cache)?; - Ok(cache) +/// `root`'s directory for `epoch`, created empty: a database's copies, +/// `.log/e`. Later epochs' are kept. Earlier epochs' are +/// removed if they can be, and anything else there: what a takeover holds +/// (`Hold`) writes only its own epoch's, but an earlier epoch's eviction may +/// still be uploading from its copies or its compaction writing them, and +/// on Windows a file open there cannot be removed. Nothing reads an earlier +/// epoch's, so what is left is only garbage. This epoch's must go: a +/// compaction trusts a copy it finds there. +fn open_epoch_dir(root: &Path, epoch: Epoch) -> std::io::Result { + let name = format!("e{epoch}"); + let later = |name: &std::ffi::OsStr| { + let n = name.to_str().and_then(|n| n.strip_prefix('e')); + n.and_then(|n| n.parse::().ok()) + .is_some_and(|n| n > epoch) + }; + let entries = match std::fs::read_dir(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + entries => Some(entries?), + }; + for entry in entries.into_iter().flatten() { + let entry = entry?; + if later(&entry.file_name()) { + continue; + } + let removed = if entry.file_type()?.is_dir() { + std::fs::remove_dir_all(entry.path()) + } else { + std::fs::remove_file(entry.path()) + }; + match removed { + Err(e) if entry.file_name() == *name && e.kind() != std::io::ErrorKind::NotFound => { + return Err(e); + } + _ => {} + } + } + let dir = root.join(name); + std::fs::create_dir_all(&dir)?; + Ok(dir) +} + +/// Sync an object's files to disk: each database, its WAL, and the root's +/// facet index, `.facets` beside `.sqlite`. +fn sync_object(databases: &[(String, PathBuf)]) -> Result<()> { + for (lane, path) in databases { + let wal = crate::log::with_suffix(path, "-wal"); + let index = (lane == DB).then(|| path.with_extension("facets")); + for file in [Some(path.clone()), Some(wal), index].into_iter().flatten() { + // Written to, for Windows to flush it. + match std::fs::OpenOptions::new().write(true).open(&file) { + Ok(file) => sync_file(&file)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } + } + } + Ok(()) +} + +/// `file.sync_data()`, but in this crate's tests, whose files are scratch. +/// On macOS and Windows a sync waits for the device to flush, and the owner +/// simulation's hundreds of evictions each sync their files. +fn sync_file(file: &std::fs::File) -> std::io::Result<()> { + if cfg!(test) { Ok(()) } else { file.sync_data() } +} + +/// Restore `restore`'s spool, `.restore/`, created +/// empty. A restore's tasks share its takeover's hold (`Hold::share`), but +/// for its downloads' writers, which the bucket client starts and nothing +/// awaits once a takeover is cancelled; such a writer writes only its own +/// restore's spool. The others are removed if they can be: nothing reads +/// them, and on Windows a file open there cannot be removed. +fn open_spool(spools: &Path, restore: u64) -> std::io::Result { + for entry in std::fs::read_dir(spools).into_iter().flatten().flatten() { + let _ = std::fs::remove_dir_all(entry.path()); + } + let spool = spools.join(restore.to_string()); + std::fs::create_dir_all(&spool)?; + Ok(spool) } fn cache_root(path: &Path) -> PathBuf { @@ -806,18 +1089,32 @@ async fn put(replica: &Replica, to: Sequence, staged: Option>) -> Result upload(replica, file).await.map(Some) } -/// Moves restored `lanes` to where `layout` places them. Returns each -/// lane's name and database. -fn place(layout: &dyn Layout, lanes: Vec<(String, PathBuf)>) -> Result> { +/// Moves restored `lanes` to where `layout` places them, the moves on the +/// blocking pool. Placing stays on this thread: it numbers new facets in +/// the namespace's storage, which lives here, with a write but no sync in a +/// cluster. Returns each lane's name and database. +async fn place( + layout: &dyn Layout, + lanes: Vec<(String, PathBuf)>, + hold: &Hold, +) -> Result> { let mut databases = Vec::new(); + let mut moves = Vec::new(); for (lane, file) in lanes { let path = layout.place(&lane)?; - std::fs::rename(&file, &path)?; + moves.push((file, path.clone())); databases.push((lane, path)); } if !databases.iter().any(|(lane, _)| lane == DB) { databases.push((DB.to_owned(), layout.place(DB)?)); } + hold.blocking(move || { + for (file, path) in &moves { + std::fs::rename(file, path)?; + } + Ok(()) + }) + .await?; Ok(databases) } @@ -838,6 +1135,97 @@ mod tests { } } + #[test] + fn a_hold_is_forgotten_once_its_last_task_is_done() { + let owners = Owners::new(crate::dst::Harness::new(0).bucket); + let hold = futures::executor::block_on(Hold::new(&owners, "ns/a")); + // A takeover cancelled while its blocking task, which shares the + // hold, runs on. + let task = hold.share(); + drop(hold); + assert_eq!(owners.holds.lock().unwrap().len(), 1); + std::thread::spawn(move || drop(task)).join().unwrap(); + assert!(owners.holds.lock().unwrap().is_empty()); + // The next holder makes it anew, and forgets it in turn. + drop(futures::executor::block_on(Hold::new(&owners, "ns/a"))); + assert!(owners.holds.lock().unwrap().is_empty()); + } + + #[test] + fn a_claim_awaits_an_eviction_of_its_epoch_only() { + use futures::FutureExt; + let owners = Owners::new(crate::dst::Harness::new(0).bucket); + let eviction = Evicting::new(&owners, object_key("ns", "a"), 1); + assert!(owners.evicted("ns", "a", 2).now_or_never().is_some()); + assert!(owners.evicted("ns", "b", 1).now_or_never().is_some()); + let mut evicted = std::pin::pin!(owners.evicted("ns", "a", 1)); + assert!(evicted.as_mut().now_or_never().is_none()); + // A later eviction of the object, which the first's end leaves. + let later = Evicting::new(&owners, object_key("ns", "a"), 1); + drop(eviction); + assert!(evicted.now_or_never().is_some()); + assert!(owners.evicted("ns", "a", 1).now_or_never().is_none()); + drop(later); + assert!(owners.evicted("ns", "a", 1).now_or_never().is_some()); + assert!(owners.evicting.borrow().is_empty()); + } + + #[test] + fn a_task_sharing_a_hold_keeps_the_object_held() { + use futures::FutureExt; + let owners = Owners::new(crate::dst::Harness::new(0).bucket); + let hold = futures::executor::block_on(Hold::new(&owners, "ns/a")); + // A restore's replay, still running when its takeover is cancelled. + let replay = hold.share(); + drop(hold); + let mut next = std::pin::pin!(Hold::new(&owners, "ns/a")); + assert!(next.as_mut().now_or_never().is_none()); + drop(replay); + assert!(next.now_or_never().is_some()); + } + + #[test] + fn a_restore_spool_is_its_own() { + let tmp = std::env::var_os("TEST_TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); + let spools = tmp.join(format!("spools-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&spools); + // An earlier restore's, cancelled with its downloads in flight. + std::fs::create_dir_all(spools.join("3/files")).unwrap(); + std::fs::write(spools.join("3/files/0"), "x").unwrap(); + let spool = open_spool(&spools, 4).unwrap(); + assert_eq!(spool, spools.join("4")); + let left: Vec<_> = std::fs::read_dir(&spools) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .collect(); + assert_eq!(left, ["4"]); + assert_eq!(std::fs::read_dir(&spool).unwrap().count(), 0); + std::fs::remove_dir_all(&spools).unwrap(); + } + + #[test] + fn an_epoch_dir_starts_empty_and_keeps_later_epochs() { + let tmp = std::env::var_os("TEST_TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); + let root = tmp.join(format!("epoch-dir-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + for (dir, file) in [("e3", "a"), ("e5", "b"), ("e7", "c")] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + std::fs::write(root.join(dir).join(file), "x").unwrap(); + } + std::fs::write(root.join("junk"), "x").unwrap(); + let dir = open_epoch_dir(&root, 5).unwrap(); + assert_eq!(dir, root.join("e5")); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + let mut left: Vec<_> = std::fs::read_dir(&root) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .collect(); + left.sort(); + assert_eq!(left, ["e5", "e7"]); + assert!(root.join("e7/c").exists()); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn a_snapshot_is_due_when_the_log_reaches_its_size() { let mut files = vec![file(true, 0, 1000), file(false, 3, 960)]; diff --git a/src/workerd/server/facet-tree-index.c++ b/src/workerd/server/facet-tree-index.c++ index ddddf83034e..18b50e9e1cf 100644 --- a/src/workerd/server/facet-tree-index.c++ +++ b/src/workerd/server/facet-tree-index.c++ @@ -8,7 +8,9 @@ namespace workerd::server { using kj::byte; using kj::uint; -FacetTreeIndex::FacetTreeIndex(kj::Own fileParam): file(kj::mv(fileParam)) { +FacetTreeIndex::FacetTreeIndex(kj::Own fileParam, SyncFacetIndex sync) + : file(kj::mv(fileParam)), + sync(sync) { // Read the file to populate the initial index auto fileBytes = file->readAllBytes(); @@ -21,7 +23,7 @@ FacetTreeIndex::FacetTreeIndex(kj::Own fileParam): file(kj::mv(f if (fileBytes.size() <= sizeof(MAGIC_NUMBER)) { // New file, initialize with magic number. file->write(0, kj::asBytes(MAGIC_NUMBER)); - file->datasync(); + if (sync) file->datasync(); offset = sizeof(MAGIC_NUMBER); return; } @@ -113,7 +115,7 @@ uint FacetTreeIndex::getId(uint parent, kj::StringPtr name) { // We don't want to return an entry that might disappear after a power failure, so sync it // now. - file->datasync(); + if (sync) file->datasync(); offset += entrySize; diff --git a/src/workerd/server/facet-tree-index.h b/src/workerd/server/facet-tree-index.h index 02cabc64a52..168f7e9d01b 100644 --- a/src/workerd/server/facet-tree-index.h +++ b/src/workerd/server/facet-tree-index.h @@ -1,10 +1,16 @@ #pragma once +#include + #include #include namespace workerd::server { +// Whether a FacetTreeIndex syncs its file after each write. NO for an index nothing reads after a +// crash of the machine, such as a cluster node's, which a takeover removes. +WD_STRONG_BOOL(SyncFacetIndex); + using kj::uint; // Implements an index, stored on disk, which maps leaves of a tree to small integers in a stable @@ -51,7 +57,7 @@ class FacetTreeIndex { public: // Construct the index, reading the given file to populate the initial index, and then arranging // to append new entries to the file as needed. - FacetTreeIndex(kj::Own file); + FacetTreeIndex(kj::Own file, SyncFacetIndex sync = SyncFacetIndex::YES); // Gets the ID for the given facet, assigning it if needed. uint getId(uint parent, kj::StringPtr name); @@ -68,6 +74,7 @@ class FacetTreeIndex { private: kj::Own file; + SyncFacetIndex sync; // Offset at which to write the next entry. Typically points to the end of the file (except when // a corrupted tail was detected). diff --git a/src/workerd/server/factory/worker-factory-actor.c++ b/src/workerd/server/factory/worker-factory-actor.c++ index 1a94783d355..30f643fa135 100644 --- a/src/workerd/server/factory/worker-factory-actor.c++ +++ b/src/workerd/server/factory/worker-factory-actor.c++ @@ -18,8 +18,9 @@ namespace workerd::server { namespace { // The directory a clustered namespace's SQLite opens its files through. Opening fails once this -// instance's cluster lease has lapsed, and writes to a WAL are reported to the cluster, which cuts -// commits from them. It has no fd, so SQLite uses the KJ VFS, on every platform. +// instance serves and its cluster lease has lapsed, and writes to a WAL are reported to the +// cluster, which cuts commits from them. It has no fd, so SQLite uses the KJ VFS, on every +// platform. class ClusterDirectory final: public kj::Directory { public: ClusterDirectory(kj::Own inner, const ActorNamespaceHandle& actors) @@ -174,7 +175,15 @@ ActorStorage::Impl::Impl(const WorkerFactory& factory, sqliteDirectory(actors->replicated() ? kj::heap(vfsDirectory->clone(), *actors) : vfsDirectory->clone()), - vfs(*sqliteDirectory, {.sync = factory.getImpl().options->syncStorage}), + // A cluster's databases need no syncs: an object's commits are durable once the bucket + // holds them, and a node reuses its files only within the process that wrote them, so no + // crash that a sync guards against leaves a file that is read again. The namespace's + // directory is emptied before this opens it (`clear_directory`, actor.rs), the alarm + // scheduler's database and facet indexes included. A sync is also where a failed writeback + // reports its I/O error: an object kept to resume from is synced as it goes idle + // (`Owners::evict`, cluster/owner.rs). + vfs(*sqliteDirectory, + {.sync = factory.getImpl().options->syncStorage && !actors->replicated()}), uniqueKey(kj::mv(uniqueKey)), alarmScheduler(kj::heap(kj::systemPreciseCalendarClock(), factory.getImpl().timer, @@ -188,10 +197,16 @@ ActorStorage::Impl::Impl(const WorkerFactory& factory, return actors->actor_for_alarm(kj::heap(kj::mv(id))); })) {} +SyncFacetIndex ActorStorage::Impl::syncFacetIndex() const { + return SyncFacetIndex(!actors->replicated()); +} + kj::Maybe> ActorStorage::Impl::getFacetTreeIndexIfNotEmpty( - const kj::Directory& dir, kj::StringPtr rootKey) { + const kj::Directory& dir, kj::StringPtr rootKey, SyncFacetIndex sync) { return dir.tryOpenFile(kj::Path({kj::str(rootKey, ".facets")}), kj::WriteMode::MODIFY) - .map([](kj::Own&& file) { return kj::heap(kj::mv(file)); }); + .map([sync](kj::Own&& file) { + return kj::heap(kj::mv(file), sync); + }); } kj::Path ActorStorage::Impl::getSqlitePath( @@ -213,8 +228,8 @@ void ActorStorage::Impl::deleteFacet( } void ActorStorage::Impl::deleteDescendantStorage( - const kj::Directory& dir, kj::StringPtr rootKey, uint parentId) { - KJ_IF_SOME(index, getFacetTreeIndexIfNotEmpty(dir, rootKey)) { + const kj::Directory& dir, kj::StringPtr rootKey, uint parentId, SyncFacetIndex sync) { + KJ_IF_SOME(index, getFacetTreeIndexIfNotEmpty(dir, rootKey, sync)) { index->forEachChild( parentId, [&](uint childId, kj::StringPtr) { deleteFacet(dir, rootKey, *index, childId); }); } else { @@ -251,8 +266,10 @@ void ActorStorage::Impl::cloneFacet(const kj::Directory& dir, } // A cluster captures a database's commits from its WAL's start, so the copy's WAL is folded // into it, out of the cluster's sight. + // This copy and the checkpoint stay on the event loop: cloning a facet is synchronous for the + // actor that asks. The checkpoint needs no sync, for the reasons the namespace's VFS needs none. if (actors->replicated()) { - SqliteDatabase::Vfs vfs(dir); + SqliteDatabase::Vfs vfs(dir, {.sync = false}); SqliteDatabase(vfs, getSqlitePath(rootKey, dstId), kj::WriteMode::MODIFY) .run("PRAGMA wal_checkpoint(TRUNCATE);"); dir.tryRemove(getSqlitePath(rootKey, dstId, "-wal")); @@ -352,20 +369,32 @@ void actor_storage_delete_facet(const ActorStorage& storage, auto& dir = *KJ_UNWRAP_OR(impl.directory, return); auto key = kj::str(rootKey); // Without an index there can be no facet storage. - KJ_IF_SOME(index, impl.getFacetTreeIndexIfNotEmpty(dir, key)) { - impl.deleteFacet(dir, key, *index, index->getId(parentFacetId.orDefault(0), kj::str(name))); + KJ_IF_SOME(index, impl.getFacetTreeIndexIfNotEmpty(dir, key, impl.syncFacetIndex())) { + ActorStorage::Impl::deleteFacet( + dir, key, *index, index->getId(parentFacetId.orDefault(0), kj::str(name))); + } +} + +void ActorStorage::Impl::clearObject(const kj::Directory& dir, kj::StringPtr rootKey) { + // The index goes too, so syncing it would be wasted. + deleteDescendantStorage(dir, rootKey, 0, SyncFacetIndex::NO); + for (const auto& suffix: {""_kj, "-wal"_kj, "-shm"_kj}) { + dir.tryRemove(getSqlitePath(rootKey, 0, suffix)); } + dir.tryRemove(kj::Path({kj::str(rootKey, ".facets")})); } void actor_storage_clear(const ActorStorage& storage, ::rust::Str rootKey) { auto& impl = storage.getImpl(); auto& dir = *KJ_UNWRAP_OR(impl.directory, return); - auto key = kj::str(rootKey); - impl.deleteDescendantStorage(dir, key, 0); - for (const auto& suffix: {""_kj, "-wal"_kj, "-shm"_kj}) { - dir.tryRemove(impl.getSqlitePath(key, 0, suffix)); - } - dir.tryRemove(kj::Path({kj::str(key, ".facets")})); + ActorStorage::Impl::clearObject(dir, kj::str(rootKey)); +} + +void actor_storage_clear_at(::rust::Str directory, ::rust::Str rootKey) { + auto fs = kj::newDiskFilesystem(); + auto dir = fs->getRoot().openSubdir( + fs->getCurrentPath().evalNative(kj::str(directory)), kj::WriteMode::MODIFY); + ActorStorage::Impl::clearObject(*dir, kj::str(rootKey)); } void actor_storage_clone_facet(const ActorStorage& storage, @@ -377,12 +406,12 @@ void actor_storage_clone_facet(const ActorStorage& storage, auto& dir = *KJ_UNWRAP_OR(impl.directory, return); auto key = kj::str(rootKey); // Without an index there is no storage to delete or copy. - KJ_IF_SOME(index, impl.getFacetTreeIndexIfNotEmpty(dir, key)) { + KJ_IF_SOME(index, impl.getFacetTreeIndexIfNotEmpty(dir, key, impl.syncFacetIndex())) { uint parentId = parentFacetId.orDefault(0); // The destination's storage goes first, as deleting the facet would; then the copy. A source // without a database has no data, which the emptied destination matches. uint dstId = index->getId(parentId, kj::str(dst)); - impl.deleteFacet(dir, key, *index, dstId); + ActorStorage::Impl::deleteFacet(dir, key, *index, dstId); impl.cloneFacet(dir, key, *index, index->getId(parentId, kj::str(src)), dstId); } } @@ -395,7 +424,8 @@ kj::Maybe actor_storage_facet_id(const ActorStorage& storage, // The index is read from disk for this one lookup; the server keeps the number it yields. auto file = dir.openFile( kj::Path({kj::str(rootKey, ".facets")}), kj::WriteMode::CREATE | kj::WriteMode::MODIFY); - return FacetTreeIndex(kj::mv(file)).getId(parentFacetId.orDefault(0), kj::str(name)); + return FacetTreeIndex(kj::mv(file), storage.getImpl().syncFacetIndex()) + .getId(parentFacetId.orDefault(0), kj::str(name)); } // ======================================================================================= @@ -551,17 +581,20 @@ Worker::Actor::MakeActorCacheFunc makeActorCacheFunc(kj::Own sqliteHooks = kj::heap(); } - auto db = kj::heap(storage->vfs, storage->getSqlitePath(rootKey, selfId), - kj::WriteMode::CREATE | kj::WriteMode::MODIFY); + auto db = + kj::heap(storage->vfs, ActorStorage::Impl::getSqlitePath(rootKey, selfId), + kj::WriteMode::CREATE | kj::WriteMode::MODIFY); // The database runs in WAL mode, also after `reset()` (which `deleteAll()` uses, and which // also deletes the child facets' storage; that is not transactional with the reset, as it is // in production). db->run("PRAGMA journal_mode=WAL;"); db->afterReset([storage = kj::addRef(*storage), rootKey = kj::str(rootKey), selfId]( SqliteDatabase& db) mutable { - storage->actors->database_reset(toRust(storage->getSqlitePath(rootKey, selfId).toString())); + storage->actors->database_reset( + toRust(ActorStorage::Impl::getSqlitePath(rootKey, selfId).toString())); db.run("PRAGMA journal_mode=WAL;"); - storage->deleteDescendantStorage(*KJ_ASSERT_NONNULL(storage->directory), rootKey, selfId); + ActorStorage::Impl::deleteDescendantStorage( + *KJ_ASSERT_NONNULL(storage->directory), rootKey, selfId, storage->syncFacetIndex()); }); kj::Function(SpanParent)> commit = [](SpanParent) -> kj::Promise { return kj::READY_NOW; diff --git a/src/workerd/server/factory/worker-factory-impl.h b/src/workerd/server/factory/worker-factory-impl.h index a6fa52bfd6b..8647e20a5b5 100644 --- a/src/workerd/server/factory/worker-factory-impl.h +++ b/src/workerd/server/factory/worker-factory-impl.h @@ -232,15 +232,22 @@ class ActorStorage::Impl final: public kj::Refcounted { kj::String uniqueKey; kj::Own alarmScheduler; + // Whether this namespace's facet indexes sync: not in a cluster, whose takeovers remove them. + SyncFacetIndex syncFacetIndex() const; + // The facet index of the root actor `rootKey`, read from disk for one operation; none when it // does not exist (so no facet can have storage). - kj::Maybe> getFacetTreeIndexIfNotEmpty( - const kj::Directory& dir, kj::StringPtr rootKey); + static kj::Maybe> getFacetTreeIndexIfNotEmpty( + const kj::Directory& dir, kj::StringPtr rootKey, SyncFacetIndex sync); - kj::Path getSqlitePath(kj::StringPtr rootKey, uint facetId, kj::StringPtr suffix = ""_kj); - void deleteFacet( + static kj::Path getSqlitePath(kj::StringPtr rootKey, uint facetId, kj::StringPtr suffix = ""_kj); + static void deleteFacet( const kj::Directory& dir, kj::StringPtr rootKey, FacetTreeIndex& index, uint facetId); - void deleteDescendantStorage(const kj::Directory& dir, kj::StringPtr rootKey, uint parentId); + static void deleteDescendantStorage( + const kj::Directory& dir, kj::StringPtr rootKey, uint parentId, SyncFacetIndex sync); + // Removes the root actor `rootKey`'s databases, its facets', and their index from `dir`. Static, + // so it can run off the event loop on a directory of its own. + static void clearObject(const kj::Directory& dir, kj::StringPtr rootKey); void cloneFacet(const kj::Directory& dir, kj::StringPtr rootKey, FacetTreeIndex& index, diff --git a/src/workerd/server/factory/worker-factory.h b/src/workerd/server/factory/worker-factory.h index 3c9ec30a7c9..6c9f0b5932a 100644 --- a/src/workerd/server/factory/worker-factory.h +++ b/src/workerd/server/factory/worker-factory.h @@ -329,6 +329,7 @@ kj::Maybe actor_storage_facet_id(const ActorStorage& storage, kj::Maybe parentFacetId, ::rust::Str name); void actor_storage_clear(const ActorStorage& storage, ::rust::Str rootKey); +void actor_storage_clear_at(::rust::Str directory, ::rust::Str rootKey); kj::Promise factory_shutdown_containers(const WorkerFactory& factory); kj::Promise factory_stop_container( diff --git a/src/workerd/server/server/actor.rs b/src/workerd/server/server/actor.rs index 06bdf8cdf26..50e90832ffc 100644 --- a/src/workerd/server/server/actor.rs +++ b/src/workerd/server/server/actor.rs @@ -300,13 +300,14 @@ impl ActorNamespace { } } - /// Fails in a cluster once this instance's lease has lapsed. A node stalled past its lease may - /// have been taken over: running its actors, even to read their databases, could act on stale - /// data. + /// Fails in a cluster once this instance serves and its lease has lapsed. A node stalled past + /// its lease may have been taken over: running its actors, even to read their databases, could + /// act on stale data. Before it serves, linking opens the namespace's storage under no lease + /// (`Cluster::actors_may_run`). fn require_lease(&self) -> Result<()> { if self .cluster() - .is_some_and(|node| !node.cluster.lease_holds()) + .is_some_and(|node| !node.cluster.actors_may_run()) { return Err(kj::failed!( "this instance's cluster lease in the bucket has lapsed" @@ -589,6 +590,7 @@ impl ActorNamespace { )); } claim_directory(&directory)?; + clear_directory(&directory)?; } let _ = self.directory.set(directory); } @@ -598,11 +600,6 @@ impl ActorNamespace { unique_key, Box::new(ActorNamespaceHandle(Weak::clone(&self.this))), )?; - if self.cluster().is_some() { - // An earlier process's alarms: its objects may live elsewhere now, and peers adopt - // its alarms from the bucket. - ffi::actor_storage_delete_all(&storage)?; - } // Checked above; nothing else sets it. let _ = self.storage.set(storage); Ok(()) @@ -658,27 +655,88 @@ impl ActorNamespace { } } -/// Marks a namespace's `directory` as the cluster's. The cluster replaces an -/// object's database with the bucket's copy, so a directory holding Durable -/// Objects from before cluster mode is refused rather than deleted. +/// Empties a cluster namespace's `directory` but for its `.cluster` marker, as the process starts. +/// What an earlier process left there goes unread: the bucket holds the objects, a takeover +/// restores each from it, and peers adopt the earlier process's alarms from it. Those files were +/// written with no syncs, so after a crash of the machine any of them may be torn, a facet index +/// or the alarm scheduler's database included, and none can be trusted to clean up the rest. The +/// files this process writes it reads only while the OS has kept them for it. +fn clear_directory(directory: &str) -> Result<()> { + let entries = std::fs::read_dir(directory).map_err(|e| kj::failed!("{directory}: {e}"))?; + for entry in entries { + let entry = entry.map_err(|e| kj::failed!("{directory}: {e}"))?; + if entry.file_name() == ".cluster" { + continue; + } + let path = entry.path(); + let removed = match entry.file_type() { + Ok(kind) if kind.is_dir() => std::fs::remove_dir_all(&path), + Ok(_) => std::fs::remove_file(&path), + Err(e) => Err(e), + }; + match removed { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + return Err(kj::failed!("{}: {e}", path.display())); + } + _ => {} + } + } + Ok(()) +} + +/// Marks a namespace's `directory` as the cluster's, which `clear_directory` then empties at each +/// start. The cluster replaces an object's database with the bucket's copy, so a directory holding +/// Durable Objects from before cluster mode is refused rather than deleted, and so is one holding +/// anything else but the alarm scheduler's database of a namespace with no objects, which is all +/// workerd would have left there: regular files of its names, not directories nor symlinks. fn claim_directory(directory: &str) -> Result<()> { let directory = std::path::Path::new(directory); let marker = directory.join(".cluster"); if marker.exists() { return Ok(()); } - let databases = std::fs::read_dir(directory).into_iter().flatten().flatten(); - let held = databases.map(|e| e.file_name()).any(|name| { - let name = name.to_string_lossy(); - name.ends_with(".sqlite") && name != "metadata.sqlite" - }); - if held { + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries.collect::>>(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(e), + }; + let entries = entries.map_err(|e| kj::failed!("{}: {e}", directory.display()))?; + // Each entry's name, and whether it is a regular file: not a directory, nor a symlink. + let mut names: Vec<(String, bool)> = entries + .iter() + .map(|e| { + let file = e.file_type().is_ok_and(|t| t.is_file()); + (e.file_name().to_string_lossy().into_owned(), file) + }) + .collect(); + names.sort(); + let scheduler = |name: &str| { + ["", "-wal", "-shm", "-journal"] + .iter() + .any(|suffix| name == format!("metadata.sqlite{suffix}")) + }; + if names + .iter() + .any(|(name, _)| name.ends_with(".sqlite") && !scheduler(name)) + { return Err(kj::failed!( "{} holds Durable Objects from before cluster mode, which the cluster would \ replace: move them away", directory.display() )); } + let foreign: Vec<&str> = names + .iter() + .filter(|(name, file)| !(*file && scheduler(name))) + .map(|(name, _)| name.as_str()) + .collect(); + if !foreign.is_empty() { + return Err(kj::failed!( + "{} holds files that are not a cluster's, which it would delete: {}; move them away", + directory.display(), + foreign.join(", ") + )); + } std::fs::create_dir_all(directory) .and_then(|()| std::fs::write(&marker, "")) .map_err(|e| kj::failed!("{}: {e}", marker.display())) @@ -2174,10 +2232,16 @@ impl cluster::Layout for Databases { Ok(path.into()) } - fn clear(&self) -> cluster::Result<()> { - let storage = self.ns.storage().map_err(|e| layout_error(&e))?; - ffi::actor_storage_clear(storage, &self.root_key) - .map_err(|e| layout_error(&crate::Error::from(e))) + fn clear(&self) -> cluster::Result { + // Storage in memory, with no directory, keeps no object's files. + let Some(directory) = self.ns.directory.get().cloned() else { + return Ok(Box::new(|| Ok(()))); + }; + let root_key = self.root_key.clone(); + Ok(Box::new(move || { + ffi::actor_storage_clear_at(&directory, &root_key) + .map_err(|e| layout_error(&crate::Error::from(e))) + })) } } diff --git a/src/workerd/server/server/bridge.rs b/src/workerd/server/server/bridge.rs index 77c12d778f8..02f98b546b9 100644 --- a/src/workerd/server/server/bridge.rs +++ b/src/workerd/server/server/bridge.rs @@ -556,6 +556,9 @@ pub mod ffi { ) -> Result>; /// Removes the root actor `root_key`'s databases, its facets', and their index. fn actor_storage_clear(storage: &ActorStorage, root_key: &str) -> Result<()>; + /// `actor_storage_clear` on the namespace directory at `directory`, which it opens + /// itself: callable from any thread. + fn actor_storage_clear_at(directory: &str, root_key: &str) -> Result<()>; /// Shuts down the Docker client of every actor's container and resolves once Docker has /// removed the containers. No actor can start a container afterwards. @@ -982,8 +985,8 @@ pub mod ffi { ) -> Result>; /// Whether the cluster replicates the namespace's actors. fn replicated(self: &ActorNamespaceHandle) -> bool; - /// Called as SQLite opens one of the namespace's files: fails once this instance's - /// cluster lease has lapsed. + /// Called as SQLite opens one of the namespace's files: fails once this instance serves + /// and its cluster lease has lapsed. fn check_open(self: &ActorNamespaceHandle) -> Result<()>; /// A write SQLite made to one of the namespace's WAL files. fn wal_write(self: &ActorNamespaceHandle, file: &str, offset: u64, data: &[u8]); diff --git a/src/workerd/server/server/cluster.rs b/src/workerd/server/server/cluster.rs index 616b3f42131..ba7c29ca7a7 100644 --- a/src/workerd/server/server/cluster.rs +++ b/src/workerd/server/server/cluster.rs @@ -960,8 +960,11 @@ impl Retire { let cluster = Rc::clone(&self.node.cluster); cluster.close_actor(&self.namespace, &self.actor); let (namespace, actor, epoch) = (self.namespace, self.actor, self.epoch); + // From now, not once the task runs: a request meanwhile waits for the eviction. + let evicting = cluster.evicting(&namespace, &actor, epoch); self.node.factory.spawn_detached(async move { cluster.evict_actor(&namespace, &actor, epoch).await; + drop(evicting); }); } } diff --git a/src/workerd/server/server/config.rs b/src/workerd/server/server/config.rs index 1d2cda8f1bf..8e00de4de56 100644 --- a/src/workerd/server/server/config.rs +++ b/src/workerd/server/server/config.rs @@ -1476,7 +1476,6 @@ impl Server { _ => None, }; if let Some(cluster) = &cluster { - // Actor databases open only under a lease. cluster .cluster .join() diff --git a/src/workerd/server/tests/cluster/cluster-test.mjs b/src/workerd/server/tests/cluster/cluster-test.mjs index 9b33528603e..8a12fab291d 100644 --- a/src/workerd/server/tests/cluster/cluster-test.mjs +++ b/src/workerd/server/tests/cluster/cluster-test.mjs @@ -513,7 +513,8 @@ class FakeS3 { // The nodes run the config constant `configName` of `config`, whose disk // service `disk` is a directory of each node's own, once `before` has prepared // the bucket, of `dialect` ("s3" or "gcs", FakeS3.fresh). `nodeEnv` answers -// what a node adds to its environment. +// what a node adds to its environment, and `prepare` fills a node's directory +// before it starts. async function withCluster( numNodes, fn, @@ -525,6 +526,7 @@ async function withCluster( before = async () => {}, dialect = 's3', nodeEnv = () => ({}), + prepare = async () => {}, } = {} ) { // Each test run gets its own bucket and disks, so state doesn't leak @@ -538,6 +540,7 @@ async function withCluster( for (let i = 0; i < numNodes; i++) { const localPath = join(root, `node${i}`); await mkdir(localPath); + await prepare(localPath); nodes.push( new ClusterNode({ binary: env.WORKERD_BINARY, @@ -1343,6 +1346,58 @@ test('cluster: Durable Objects from before cluster mode are refused', async () = }); }); +test('cluster: a directory holding files of its own is refused, not cleared', async () => { + await withCluster(1, async ({ bucket }) => { + const local = await mkdtemp(join(tmpdir(), 'workerd-cluster-')); + const start = (nodeId) => + new ClusterNode({ + binary: env.WORKERD_BINARY, + config: env.WD_TEST_CONFIG, + configName: 'config', + localPath: local, + s3Port: bucket.port, + nodeId, + }); + const dir = join(local, 'counter-test-namespace'); + await mkdir(dir); + await writeFile(join(dir, 'notes.txt'), 'keep me'); + await writeFile(join(dir, 'metadata.sqlite'), ''); + const refused = start('foreign'); + await assert.rejects(refused.start(), /exited before listening/); + assert.match( + refused.stderr, + /holds files that are not a cluster's.*notes\.txt/ + ); + assert.deepStrictEqual((await readdir(dir)).sort(), [ + 'metadata.sqlite', + 'notes.txt', + ]); + // Nor a directory of the scheduler database's name, which would go with + // what it holds. + await rm(join(dir, 'notes.txt')); + await rm(join(dir, 'metadata.sqlite')); + await mkdir(join(dir, 'metadata.sqlite')); + await writeFile(join(dir, 'metadata.sqlite', 'notes.txt'), 'keep me'); + const nested = start('nested'); + await assert.rejects(nested.start(), /exited before listening/); + assert.match( + nested.stderr, + /holds files that are not a cluster's.*metadata\.sqlite/ + ); + assert.deepStrictEqual(await readdir(join(dir, 'metadata.sqlite')), [ + 'notes.txt', + ]); + // What workerd leaves in a namespace with no objects, it claims. + await rm(join(dir, 'metadata.sqlite'), { recursive: true }); + await writeFile(join(dir, 'metadata.sqlite'), ''); + const claimed = start('claimed'); + await claimed.start(); + await claimed.stop({ signal: 'SIGKILL', timeoutMs: 5000 }); + assert((await readdir(dir)).includes('.cluster')); + await rm(local, { recursive: true }); + }); +}); + test('cluster: each running instance holds a lease record', async () => { await withCluster(2, async ({ nodes, bucket, nodeKeys }) => { const records = await bucket.nodes(); @@ -1418,6 +1473,68 @@ test("cluster: an alarm runs once on its object's owner", async () => { }); }); +test('cluster: a node starts over the torn files of an earlier process', async () => { + // A cluster writes its files with no syncs, so a crash of the machine can + // leave any of them torn: the next process starts without them. First the + // name of the object's files, its id. + let id; + await withCluster(1, async ({ nodes: [node] }) => { + ({ id } = ( + await fetchJson(node.httpPort, '/alarms?name=over-garbage') + ).body); + }); + const garbage = Buffer.concat([ + Buffer.from('SQLite format 3\0'), + Buffer.alloc(8192, 0xa5), + ]); + const prepare = async (localPath) => { + for (const ns of ['counter-test-namespace', 'kv']) { + const dir = join(localPath, ns); + await mkdir(dir); + await writeFile(join(dir, '.cluster'), ''); + await writeFile(join(dir, 'metadata.sqlite'), garbage); + await writeFile(join(dir, 'metadata.sqlite-wal'), 'not a WAL'); + } + // The object's: a facet index a takeover cannot read, a facet's database + // it would not name, and the copies of an epoch. + const dir = join(localPath, 'counter-test-namespace'); + await writeFile(join(dir, `${id}.sqlite`), garbage); + await writeFile(join(dir, `${id}.facets`), Buffer.alloc(100, 0xa5)); + await writeFile(join(dir, `${id}.3.sqlite`), garbage); + await mkdir(join(dir, `${id}.sqlite.log`, 'e7'), { recursive: true }); + await writeFile(join(dir, `${id}.sqlite.log`, 'e7', '1'), garbage); + }; + await withCluster( + 1, + async ({ nodes: [node] }) => { + // Only the marker is left, and the scheduler's new database. + for (const ns of ['counter-test-namespace', 'kv']) { + const entries = await readdir(join(node.localPath, ns)); + const left = entries.filter( + (name) => name !== '.cluster' && !name.startsWith('metadata.sqlite') + ); + assert.deepStrictEqual(left, [], ns); + } + const set = await fetchJson( + node.httpPort, + '/set-alarm?name=over-garbage&ms=200' + ); + assert.strictEqual(set.status, 200, JSON.stringify(set.body)); + assert.strictEqual(set.body.id, id); + assert.strictEqual(await facetAdd(node.httpPort, 'over-garbage', 'a'), 1); + // The scheduler's new database holds the alarm, which runs. + const deadline = Date.now() + 10_000; + let res; + do { + await sleep(100); + res = await fetchJson(node.httpPort, '/alarms?name=over-garbage'); + } while (res.body.fired?.length !== 1 && Date.now() < deadline); + assert.deepStrictEqual(res.body.fired, [node.nodeId]); + }, + { prepare } + ); +}); + test("cluster: a killed owner's alarm runs once on a survivor", async () => { await withCluster(2, async ({ nodes, bucket, nodeKeys }) => { const set = await fetchJson( @@ -2034,6 +2151,27 @@ test( } ); +test('cluster: a node opening many DOs at once keeps its lease', async () => { + await withCluster(1, async ({ nodes: [node] }) => { + // Opening this many at once keeps the node's event loop busy for seconds + // in a slow build: its lease is renewed meanwhile. + const names = Array.from({ length: 64 }, (_, i) => `many-${i}`); + const responses = await Promise.all( + names.map((name) => + fetchJson(node.httpPort, `/increment?name=${name}`, { + timeoutMs: 20_000, + }).catch((e) => ({ status: 0, body: { error: String(e) } })) + ) + ); + for (const response of responses) { + assert.strictEqual(response.status, 200, JSON.stringify(response)); + } + // A renewal round past the burst. + await sleep(1000); + assert.doesNotMatch(node.stderr, /leaving the cluster/); + }); +}); + test( 'cluster: requests to a DO of a stopping node wait for its handoff and follow it', SIGTERM_DRAINS,