Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/workerd/server/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ wd_cc_library(
],
visibility = ["//visibility:public"],
deps = [
"//src/workerd/util:strong-bool",
"@capnp-cpp//src/kj",
],
)
Expand Down
9 changes: 7 additions & 2 deletions src/workerd/server/cluster/capture-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
69 changes: 48 additions & 21 deletions src/workerd/server/cluster/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -491,21 +509,25 @@ 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?;
self.take_lease().await
}

/// 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<()> {
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/workerd/server/cluster/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 9 additions & 4 deletions src/workerd/server/cluster/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand All @@ -786,15 +791,15 @@ 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)?;
}
replay.finish()
})
.await;
let _ = std::fs::remove_dir_all(&downloads);
let _ = blocking_sharing(share, move || Ok(std::fs::remove_dir_all(&downloads)?)).await;
restored
}

Expand Down
22 changes: 15 additions & 7 deletions src/workerd/server/cluster/log_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Sequence> {
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)?;
Expand Down Expand Up @@ -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<crate::owner::Removal> {
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(())
}))
}
}

Expand All @@ -779,7 +787,7 @@ fn remove(path: &Path) {
/// Every lane the log restores, with its rows.
fn restored_lanes(store: &Bucket, name: &str) -> BTreeMap<String, (i64, i64, i64)> {
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()
Expand Down
14 changes: 14 additions & 0 deletions src/workerd/server/cluster/logic/lease-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
11 changes: 11 additions & 0 deletions src/workerd/server/cluster/logic/lease.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)]
Expand Down
11 changes: 7 additions & 4 deletions src/workerd/server/cluster/owner-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,14 @@ impl Layout for Files {
Ok(path.clone())
}

fn clear(&self) -> crate::Result<()> {
fn clear(&self) -> crate::Result<crate::owner::Removal> {
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(())
}))
}
}

Expand Down
Loading
Loading