diff --git a/seaweed-volume/src/server/grpc_server.rs b/seaweed-volume/src/server/grpc_server.rs index 2ddbfc25a9..5bce000caa 100644 --- a/seaweed-volume/src/server/grpc_server.rs +++ b/seaweed-volume/src/server/grpc_server.rs @@ -1063,9 +1063,9 @@ fn claim_volume_against_copy( } /// Whether `vid`'s .ecj appends must wait for the decode publishing tail. -/// Only meaningful read under the store write lock: a decode can claim the -/// tail while a caller waits for the decoder's read lock, so membership -/// tested before acquiring the write lock is stale by commit time. +/// Only meaningful read under the volume's journal lock: a decode claims the +/// tail before it takes that lock for its catch-up, so membership tested +/// before acquiring it is stale by commit time. pub(crate) fn ec_decode_tail_contains(state: &VolumeServerState, vid: VolumeId) -> bool { state .ec_decode_tail @@ -3775,33 +3775,44 @@ impl VolumeServer for VolumeGrpcService { if let Some(loc_idx) = loc_idx { if let Some(ev) = store.locations[loc_idx].find_ec_volume_mut(vid) { let journal_path = ev.ecj_file_name(); - ev.rebuild_ecx_from_journal().map_err(|e| { + // Held through the siblings' adoption: a delete through + // another disk's handle must land before the fold reads + // the file or after that handle is repointed. + let path_lock = ev.journal_path_lock(); + let _path = crate::storage::erasure_coding::ec_volume::lock_path(&path_lock); + let fold = ev.rebuild_ecx_from_journal(); + // The fold replaced a journal other disks may share: + // repoint their handles before dropping the path lock, + // or their next delete lands on the detached inode. A + // fold that failed after removing the file (only once + // its tombstones are synced) still owes them that, and + // one sibling's failure must not skip the rest. + let replaced = + fold.is_ok() || !std::path::Path::new(&journal_path).exists(); + let mut result = fold; + if replaced { + let key_for = crate::storage::erasure_coding::ecj_registry::key_for; + let journal_key = key_for(&journal_path); + for (i, loc) in store.locations.iter_mut().enumerate() { + if i == loc_idx { + continue; + } + if let Some(other) = loc.find_ec_volume_mut(vid) { + if key_for(&other.ecj_file_name()) == journal_key { + if let Err(e) = other.adopt_folded_journal() { + result = result.and(Err(e)); + } + } + } + } + } + result.map_err(|e| { status_internal_with_rebuild_ids( format!("RebuildEcxFile: {}", e), &rebuilt, ) })?; folded = true; - // The fold replaced a journal other disks may share: - // repoint their handles before dropping the store lock, - // or their next delete lands on the detached inode. - for (i, loc) in store.locations.iter_mut().enumerate() { - if i == loc_idx { - continue; - } - if let Some(other) = loc.find_ec_volume_mut(vid) { - if std::path::Path::new(&other.ecj_file_name()) - == std::path::Path::new(&journal_path) - { - other.adopt_folded_journal().map_err(|e| { - status_internal_with_rebuild_ids( - format!("RebuildEcxFile: {}", e), - &rebuilt, - ) - })?; - } - } - } } } } @@ -4339,47 +4350,59 @@ impl VolumeServer for VolumeGrpcService { let vid = VolumeId(req.volume_id); let needle_id = NeedleId(req.file_key); - // A delete committed between the last journal catch_up and the - // compaction swap would be absent from the rebuilt .idx, so the - // tail membership must be checked under the store write lock: a - // decode can claim the tail while this delete waits for the - // decoder's read lock, and a check taken before acquiring it would - // be stale by the time the append commits. - let mut store = loop { - let store = self.state.store.write().unwrap(); - if !ec_decode_tail_contains(&self.state, vid) { - break store; - } - drop(store); - wait_ec_decode_tail(&self.state, vid).await; - }; - - // Go's handler locates the needle first: absent fails the RPC so the - // caller moves to the next holder; an existing tombstone is a no-op. - if let Some(ec_vol) = store.find_ec_volume_mut(vid) { - match ec_vol.find_needle_from_ecx(needle_id) { - Ok(Some((_, size))) if size.is_deleted() => { + // The store lock only resolves the volume and its needle: the append + // and its fsync run under the volume's journal lock, so a slow disk + // stalls deletes of this volume, not every store reader. The decode + // tail is checked under that journal lock (see journal_delete_local). + loop { + let appender = { + let store = self.state.store.read().unwrap(); + // Go's handler locates the needle first: absent fails the RPC + // so the caller moves to the next holder; an existing + // tombstone is a no-op. + let Some(ec_vol) = store.find_ec_volume(vid) else { + // If EC volume not mounted, it's a no-op (matching Go behavior) + return Ok(Response::new( + volume_server_pb::VolumeEcBlobDeleteResponse {}, + )); + }; + match ec_vol.find_needle_from_ecx(needle_id) { + Ok(Some((_, size))) if size.is_deleted() => { + return Ok(Response::new( + volume_server_pb::VolumeEcBlobDeleteResponse {}, + )); + } + Ok(None) => { + return Err(Status::not_found(format!( + "needle {} not in ec volume {}", + needle_id, req.volume_id + ))); + } + Ok(Some(_)) => {} + Err(e) => return Err(Status::internal(e.to_string())), + } + ec_vol.journal_appender() + }; + let state = self.state.clone(); + let committed = tokio::task::spawn_blocking(move || { + appender.journal_delete(needle_id, || ec_decode_tail_contains(&state, vid)) + }) + .await + .map_err(|e| Status::internal(e.to_string()))?; + match committed { + Ok(()) => { return Ok(Response::new( volume_server_pb::VolumeEcBlobDeleteResponse {}, )); } - Ok(None) => { - return Err(Status::not_found(format!( - "needle {} not in ec volume {}", - needle_id, req.volume_id - ))); + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + wait_ec_decode_tail(&self.state, vid).await; } - Ok(Some(_)) => {} + // Unmounted or remounted since it was resolved: resolve again. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(Status::internal(e.to_string())), } - ec_vol - .journal_delete(needle_id) - .map_err(|e| Status::internal(e.to_string()))?; } - // If EC volume not mounted, it's a no-op (matching Go behavior) - Ok(Response::new( - volume_server_pb::VolumeEcBlobDeleteResponse {}, - )) } async fn volume_ec_shards_to_volume( @@ -7978,7 +8001,7 @@ impl EcDecodeJob { // VolumeEcShardsCopy into the idx dir, count as deleted throughout. // The first pass runs unlocked — a slow journal must not stall every // store writer — then a second pass runs with appends quiesced by the - // read lock. The rollback epoch proves whether it needs to be a full + // journal locks. The rollback epoch proves whether it needs to be a full // rescan: an unchanged epoch means no append was rolled back inside // the window, so every id folded in was committed and catch_up only // needs to pick up records appended meanwhile. @@ -7987,7 +8010,8 @@ impl EcDecodeJob { let mut deleted = ec_decoder::EcjDeletions::read(&[&ecx_dir, &idx_dir], &collection, vid) .map_err(|e| Status::internal(format!("read ecj: {}", e)))?; { - let _guard = state.store.read().unwrap(); + let store = state.store.read().unwrap(); + let _journals = store.lock_ec_journals(vid); if epoch_before == crate::storage::erasure_coding::ec_volume::ECJ_ROLLBACK_EPOCH .load(std::sync::atomic::Ordering::Acquire) @@ -8099,14 +8123,15 @@ impl EcDecodeJob { .insert(vid); let _tail = EcDecodeTailGuard(state, vid); - // Deletes journaled while the .dat was written. Journal appends hold - // the store write lock through their sync-or-truncate, so a read lock - // held from catch_up through the .idx publish guarantees every record - // read is committed — a rolled-back delete cannot leave a tombstone - // in the index — and no new journal record can be missed by the - // rebuilt .idx. + // Deletes journaled while the .dat was written. Runtime appends hold + // their volume's journal lock and path appends the store write lock + // through their sync-or-truncate, so holding both from catch_up + // through the .idx publish guarantees every record read is committed + // — a rolled-back delete cannot leave a tombstone in the index — and + // no new journal record can be missed by the rebuilt .idx. { - let _guard = state.store.read().unwrap(); + let store = state.store.read().unwrap(); + let _journals = store.lock_ec_journals(vid); deleted .catch_up() .map_err(|e| Status::internal(format!("read ecj: {}", e)))?; @@ -16268,39 +16293,40 @@ mod tests { assert_eq!(err.code(), tonic::Code::Unavailable); } - /// The blob-delete tail check must run under the store write lock: a - /// delete that passed an unlocked check could still be parked behind - /// the decoder's read lock when the decode claims the tail, then commit - /// its journal append after the rebuilt .idx — an acknowledged delete - /// the mount would never see. + /// The blob-delete tail check must run under the journal lock: a delete + /// that passed an earlier check could still be parked behind an append + /// when the decode claims the tail, then commit its journal append after + /// the rebuilt .idx — an acknowledged delete the mount would never see. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_volume_ec_blob_delete_rechecks_tail_under_write_lock() { + async fn test_volume_ec_blob_delete_rechecks_tail_under_journal_lock() { let (service, _tmp, _data, idx, _) = make_split_idx_ec_decode_service(&[], false).await; let state = service.state.clone(); - - // Park the delete on the store write lock, claimed in a thread so a - // std guard is never held across .await; the tail is claimed while - // it waits — the interleaving an unlocked check missed. - let claimed = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let held = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let releaser = { - let claimed = claimed.clone(); - let held = held.clone(); - let state = state.clone(); - std::thread::spawn(move || { - let guard = state.store.write().unwrap(); - held.store(true, Ordering::SeqCst); - while !claimed.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - drop(guard); - }) + let (appender, path_lock) = { + let store = state.store.read().unwrap(); + let ev = store.find_ec_volume(VolumeId(1)).unwrap(); + (ev.journal_appender(), ev.journal_path_lock().unwrap()) }; - // Spawn only once the write lock is held: on a slow runner the delete - // could otherwise acquire it first and commit before the tail exists. - while !held.load(Ordering::SeqCst) { - tokio::time::sleep(std::time::Duration::from_millis(5)).await; - } + // A delete takes the path lock before the journal lock and gives both + // up together, so with the journal lock held here the path lock is + // busy exactly while the delete is parked on it. + let path_busy_becomes = |busy: bool| { + let path_lock = path_lock.clone(); + async move { + let deadline = + std::time::Instant::now() + std::time::Duration::from_secs(5); + while path_lock.try_lock().is_ok() == busy { + assert!( + std::time::Instant::now() < deadline, + "path lock never became busy={busy}" + ); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + } + }; + + // Park the delete on the journal lock; the tail is claimed while it + // waits — the interleaving a check taken before the lock missed. + let held = appender.lock_journal(); let delete = tokio::spawn(async move { service .volume_ec_blob_delete(Request::new(volume_server_pb::VolumeEcBlobDeleteRequest { @@ -16311,21 +16337,27 @@ mod tests { })) .await }); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + path_busy_becomes(true).await; + assert!( + state.store.try_write().is_ok(), + "a delete waiting on its journal must not hold the store lock" + ); state .ec_decode_tail .lock() .unwrap() .insert(VolumeId(1)); - claimed.store(true, Ordering::SeqCst); - releaser.join().unwrap(); + drop(held); - // Under the lock the delete sees the tail and parks on the notify. - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - assert!( - !delete.is_finished(), + // Under the lock the delete sees the tail, gives up both locks + // without appending, and parks on the notify. + path_busy_becomes(false).await; + assert_eq!( + std::fs::metadata(format!("{idx}/1.ecj")).map_or(0, |m| m.len()), + 0, "a delete must not commit while its volume is in the decode tail" ); + assert!(!delete.is_finished()); state .ec_decode_tail diff --git a/seaweed-volume/src/server/store_ec.rs b/seaweed-volume/src/server/store_ec.rs index fa7dd15831..733f28d3be 100644 --- a/seaweed-volume/src/server/store_ec.rs +++ b/seaweed-volume/src/server/store_ec.rs @@ -461,12 +461,12 @@ async fn delete_on_ec_shard_holders( let mut last_err = None; if local_shards.contains(&shard_id) { // A decode in its publishing tail must not miss this delete. The - // tail membership is verified again under the store write lock - // inside journal_delete_local — WouldBlock means the decode claimed - // it in the gap after this wait — so wait and retry. + // tail membership is verified again under the journal lock inside + // journal_delete_local — WouldBlock means the decode claimed it in + // the gap after this wait — so wait and retry. loop { crate::server::grpc_server::wait_ec_decode_tail(state, target.vid).await; - match journal_delete_local(state, target.vid, target.needle_id) { + match journal_delete_local(state, target.vid, target.needle_id).await { Ok(()) => return Ok(true), Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue, // Nothing was committed — the volume unmounted or remounted @@ -533,38 +533,42 @@ async fn delete_on_remote_ec_shard( /// no-op: `journal_delete` would accept it silently, but here it means the /// volume remounted as a different generation mid-delete and the tombstone /// should go to a replica that still has the needle. -fn journal_delete_local( +async fn journal_delete_local( state: &Arc, vid: VolumeId, needle_id: NeedleId, ) -> io::Result<()> { - let mut store = state.store.write().unwrap(); - // Membership is read under the write lock: a decode can claim the - // publishing tail while this call waited for the decoder's read lock, - // so a check taken earlier would be stale by commit time. - if crate::server::grpc_server::ec_decode_tail_contains(state, vid) { - return Err(io::Error::new( - io::ErrorKind::WouldBlock, - format!("ec volume {} is in decode publishing tail", vid.0), - )); - } - let ecv = store.find_ec_volume_mut(vid).ok_or_else(|| { - io::Error::new( - io::ErrorKind::NotFound, - format!("ec volume {} unmounted", vid.0), - ) - })?; - match ecv.find_needle_from_ecx(needle_id)? { - None => { - return Err(io::Error::new( + let appender = { + let store = state.store.read().unwrap(); + let ecv = store.find_ec_volume(vid).ok_or_else(|| { + io::Error::new( io::ErrorKind::NotFound, - format!("needle {} not in local ecx", needle_id), - )); + format!("ec volume {} unmounted", vid.0), + ) + })?; + match ecv.find_needle_from_ecx(needle_id)? { + None => { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("needle {} not in local ecx", needle_id), + )); + } + Some((_, size)) if size.is_deleted() => return Ok(()), + Some(_) => {} } - Some((_, size)) if size.is_deleted() => return Ok(()), - Some(_) => {} - } - ecv.journal_delete(needle_id) + ecv.journal_appender() + }; + // Membership is read under the journal lock: a decode claims the + // publishing tail before it takes that lock for its catch-up, so a check + // taken earlier would be stale by commit time. + let state = state.clone(); + tokio::task::spawn_blocking(move || { + appender.journal_delete(needle_id, || { + crate::server::grpc_server::ec_decode_tail_contains(&state, vid) + }) + }) + .await + .map_err(io::Error::other)? } fn local_shard_ids(ecv: &crate::storage::erasure_coding::EcVolume) -> HashSet { diff --git a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs index e3a8dd6d85..d29b880f65 100644 --- a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs +++ b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs @@ -6,7 +6,7 @@ use std::collections::{HashMap, HashSet}; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufWriter, Write}; -use std::sync::RwLock; +use std::sync::{Arc, Mutex, MutexGuard, RwLock}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use crate::pb::master_pb; @@ -180,6 +180,136 @@ fn read_ecj_ids_with( Ok(()) } +/// A volume's `.ecj` append handle and on-disk size, under the volume's own +/// journal lock (Go's `EcVolume.ecjFileAccessLock`). The size is what +/// mount-time compaction compares against the id set; the runtime delete count +/// comes from `deleted_needles`. +#[derive(Default)] +pub(crate) struct EcJournal { + file: Option, + size: i64, + /// Set once the volume is closed or dropped: an appender that resolved the + /// volume before that must re-resolve rather than write a detached file. + closed: bool, +} + +impl EcJournal { + /// Append whole records and sync them. On any failure the file is + /// truncated back to the pre-append length so the on-disk journal and + /// `deleted_needles` cannot drift. + fn append(&mut self, records: &[u8], volume_id: VolumeId, ecj_path: &str) -> io::Result<()> { + let ecj_file = self + .file + .as_mut() + .ok_or_else(|| io::Error::other("ecj file not open"))?; + // The file's own length, not this handle's cached size: another disk + // holding the same journal may have appended since. + let prev_ecj_size = ecj_file.metadata()?.len() as i64; + let append_result = ecj_file + .write_all(records) + .and_then(|_| ecj_file.sync_all()); + + match append_result { + Ok(()) => { + self.size = prev_ecj_size + records.len() as i64; + Ok(()) + } + Err(e) => { + // write_all may have extended the file on disk before + // sync_all failed; truncate back to the known-good size so + // the on-disk journal never drifts past `deleted_needles`. + // Uses its own write handle: on Windows the append handle + // lacks FILE_WRITE_DATA, so set_len through it fails with + // ERROR_ACCESS_DENIED and the rollback would silently not + // happen. + let rollback = open_volume_file(OpenOptions::new().write(true), ecj_path) + .and_then(|f| f.set_len(prev_ecj_size as u64).and_then(|_| f.sync_all())); + // Bumped on attempt, not success: a failed rollback leaves the + // bytes in place and a decode re-reading for the epoch change + // simply sees them — harmless — while a successful one must + // never go unnoticed by an unlocked journal read. + ECJ_ROLLBACK_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if let Err(trunc_err) = rollback { + tracing::error!( + volume_id = volume_id.0, + truncate_error = %trunc_err, + "failed to truncate ecj after append failure" + ); + } + Err(e) + } + } + } +} + +/// Takes a `.ecj` path's append lock, ahead of any holder's journal lock. +pub(crate) fn lock_path(lock: &Option>>) -> Option> { + lock.as_ref() + .map(|l| l.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// A mounted volume's deletion journal, usable after the store lock that found +/// the volume is released, so the append's fsync stalls only this volume. +pub struct EcJournalAppender { + volume_id: VolumeId, + ecj_path: String, + path_lock: Option>>, + ecj: Arc>, + deleted_needles: Arc>>, +} + +impl EcJournalAppender { + /// Journal a delete of a needle the caller found live in `.ecx`. + /// `must_wait` runs under the journal lock, which a decode takes for its + /// catch-up, so a `true` answer (the decode publishing tail) is current + /// when the append would commit; it gives `WouldBlock`. A volume closed + /// since it was resolved gives `NotFound` with nothing written. + pub fn journal_delete( + &self, + needle_id: NeedleId, + must_wait: impl FnOnce() -> bool, + ) -> io::Result<()> { + let _path = lock_path(&self.path_lock); + let mut journal = self.ecj.lock().unwrap_or_else(|e| e.into_inner()); + if journal.closed { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("ec volume {} closed", self.volume_id.0), + )); + } + if self + .deleted_needles + .read() + .map(|s| s.contains(&needle_id)) + .unwrap_or(false) + { + return Ok(()); + } + if must_wait() { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + format!( + "ec volume {} is in decode publishing tail", + self.volume_id.0 + ), + )); + } + let mut buf = [0u8; NEEDLE_ID_SIZE]; + needle_id.to_bytes(&mut buf); + journal.append(&buf, self.volume_id, &self.ecj_path)?; + if let Ok(mut set) = self.deleted_needles.write() { + set.insert(needle_id); + } + Ok(()) + } + + /// Holds the journal lock, standing in for an append stuck in its fsync. + #[cfg(test)] + pub(crate) fn lock_journal(&self) -> MutexGuard<'_, EcJournal> { + self.ecj.lock().unwrap() + } +} + /// An erasure-coded volume managing its local shards and index. pub struct EcVolume { pub volume_id: VolumeId, @@ -196,22 +326,17 @@ pub struct EcVolume { pub block_size: i64, ecx_file: Option, ecx_file_size: i64, - ecj_file: Option, + ecj: Arc>, /// This volume's registration as a holder of its `.ecj` path. Held for as - /// long as `ecj_file` may be open; see `ecj_registry`. + /// long as the journal handle may be open; see `ecj_registry`. ecj_hold: Option, - /// On-disk size of the .ecj deletion journal: the rollback point for a - /// failed append, and the size mount-time compaction compares against the - /// id set and re-checks on disk before replacing the file. The runtime - /// delete count comes from `deleted_needles.len()`, not from this. - ecj_file_size: i64, /// In-memory set of needle ids that have been deleted since the volume /// was encoded. .ecx is immutable at runtime — it only stores the /// sorted (id, offset, size) index written at encode time — and runtime /// deletes are journaled to .ecj + tracked here. Reads consult this /// set to mask out deleted needles on top of the sealed .ecx lookup. /// Seeded from .ecj in `new()` and updated by `journal_delete`. - deleted_needles: RwLock>, + deleted_needles: Arc>>, pub disk_type: DiskType, /// Directory where .ecx/.ecj were actually found (may differ from dir_idx after fallback). ecx_actual_dir: String, @@ -755,10 +880,9 @@ impl EcVolume { block_size, ecx_file: None, ecx_file_size: 0, - ecj_file: None, + ecj: Arc::default(), ecj_hold: None, - ecj_file_size: 0, - deleted_needles: RwLock::new(HashSet::new()), + deleted_needles: Arc::default(), disk_type: DiskType::default(), ecx_actual_dir: dir_idx.to_string(), shard_locations: RwLock::new(ShardLocationCache::default()), @@ -846,6 +970,10 @@ impl EcVolume { // the tail repair and the handle below see the final inode, and it // stops any compaction from replacing the file under this handle. vol.ecj_hold = Some(EcjHold::acquire(&ecj_path)); + // Another disk's runtime may be appending to this file: repair and + // load only settled records. + let path_lock = vol.journal_path_lock(); + let path_guard = lock_path(&path_lock); // Repair a torn tail BEFORE the append handle exists. // @@ -886,11 +1014,15 @@ impl EcVolume { } let ecj_file = open_ecj_append(&ecj_path)?; - vol.ecj_file_size = ecj_file.metadata()?.len() as i64; - vol.ecj_file = Some(ecj_file); + { + let mut journal = vol.journal(); + journal.size = ecj_file.metadata()?.len() as i64; + journal.file = Some(ecj_file); + } // Seed the in-memory deleted set from the journal. vol.load_deleted_needles_from_ecj(ecj_ops.read_at)?; + drop(path_guard); // Load the generation-0 EC bitrot checksum sidecar. Optional, except // when it contradicts the volume's own geometry — see @@ -1129,11 +1261,12 @@ impl EcVolume { &mut self, read_at: fn(&File, &mut [u8], u64) -> io::Result<()>, ) -> io::Result<()> { - let ecj_file = match self.ecj_file.as_ref() { + let journal = self.journal(); + let ecj_file = match journal.file.as_ref() { Some(f) => f, None => return Ok(()), }; - if self.ecj_file_size < NEEDLE_ID_SIZE as i64 { + if journal.size < NEEDLE_ID_SIZE as i64 { return Ok(()); } @@ -1141,7 +1274,8 @@ impl EcVolume { // held the `deleted_needles` write lock for the whole scan, which on a // bloated journal is the entire (unbounded) startup. let mut loaded: HashSet = HashSet::new(); - read_ecj_ids_with(read_at, ecj_file, 0, self.ecj_file_size as u64, &mut loaded)?; + read_ecj_ids_with(read_at, ecj_file, 0, journal.size as u64, &mut loaded)?; + drop(journal); let mut set = self .deleted_needles @@ -1231,7 +1365,7 @@ impl EcVolume { tracing::warn!( volume_id = self.volume_id.0, collection = %self.collection, - on_disk_bytes = self.ecj_file_size, + on_disk_bytes = self.journal().size, unique_ids = ids.len(), compacted_bytes = ids.len() * NEEDLE_ID_SIZE, "compacting bloated .ecj deletion journal", @@ -1265,8 +1399,11 @@ impl EcVolume { .map_err(|_| io::Error::other("deleted_needles lock poisoned"))? .len(); let compacted_len = (distinct as i64).saturating_mul(NEEDLE_ID_SIZE as i64); - Ok(self.ecj_file_size >= ECJ_COMPACT_MIN_BYTES - && self.ecj_file_size >= compacted_len.saturating_mul(ECJ_COMPACT_RATIO)) + let size = self.journal().size; + Ok( + size >= ECJ_COMPACT_MIN_BYTES + && size >= compacted_len.saturating_mul(ECJ_COMPACT_RATIO), + ) } /// The deleted set, sorted so the rewritten file is deterministic: two @@ -1289,7 +1426,8 @@ impl EcVolume { /// A copy that appended, or replaced the file, after the load fails this, /// and compacting then would drop what it wrote. fn ecj_unchanged_since_load(&self, ecj_path: &str) -> io::Result { - let Some(held) = self.ecj_file.as_ref() else { + let journal = self.journal(); + let Some(held) = journal.file.as_ref() else { return Ok(false); }; let held = held.metadata()?; @@ -1301,7 +1439,7 @@ impl EcVolume { return Ok(false); } } - Ok(held.len() == on_path.len() && on_path.len() as i64 == self.ecj_file_size) + Ok(held.len() == on_path.len() && on_path.len() as i64 == journal.size) } /// Publish a compacted tmp file over the live journal: drop the handle @@ -1323,12 +1461,13 @@ impl EcVolume { // rename over a file that is still open fails outright, which would // make compaction a permanent no-op there; on Unix the handle would // survive as an unlinked inode, which is worse than useless. - self.ecj_file = None; + let mut journal = self.journal(); + journal.file = None; if let Err(rename_err) = (ops.rename)(tmp_path, ecj_path) { let _ = fs::remove_file(tmp_path); return match (ops.reopen)(ecj_path) { Ok(f) => { - self.ecj_file = Some(f); + journal.file = Some(f); Err(EcjPublishError::Abandoned(rename_err)) } Err(reopen_err) => Err(EcjPublishError::HandleLost(io::Error::new( @@ -1355,8 +1494,8 @@ impl EcVolume { // Reopen so later journal_delete appends land in the file just written. let reopened = (ops.reopen)(ecj_path).map_err(|e| lost("reopen it", e))?; let size = reopened.metadata().map_err(|e| lost("stat it", e))?.len(); - self.ecj_file_size = size as i64; - self.ecj_file = Some(reopened); + journal.size = size as i64; + journal.file = Some(reopened); Ok(()) } @@ -1419,8 +1558,12 @@ impl EcVolume { /// Sync the EC volume's journal and index files to disk (matching Go's ecv.Sync()). /// Go flushes both .ecj and .ecx to ensure in-place deletion marks are persisted. pub fn sync_to_disk(&self) -> io::Result<()> { - if let Some(ref ecj_file) = self.ecj_file { - ecj_file.sync_all()?; + // Every append syncs its own record, so one in flight is not waited + // for: callers such as CopyFile hold the store lock here. + if let Ok(journal) = self.ecj.try_lock() { + if let Some(ref ecj_file) = journal.file { + ecj_file.sync_all()?; + } } if let Some(ref ecx_file) = self.ecx_file { ecx_file.sync_all()?; @@ -2083,6 +2226,7 @@ impl EcVolume { /// in place and the error is propagated so tombstones are not lost. pub(crate) fn rebuild_ecx_from_journal(&mut self) -> io::Result<()> { let ecj_path = self.ecj_file_name(); + let mut journal = self.journal(); if !std::path::Path::new(&ecj_path).exists() { return Ok(()); } @@ -2118,9 +2262,9 @@ impl EcVolume { // if the recreate fails, deletes must error rather than keep // appending to the removed inode. fs::remove_file(&ecj_path)?; - self.ecj_file = None; - self.ecj_file = Some(open_ecj_append(&ecj_path)?); - self.ecj_file_size = 0; + journal.file = None; + journal.file = Some(open_ecj_append(&ecj_path)?); + journal.size = 0; if let Ok(mut set) = self.deleted_needles.write() { set.clear(); } @@ -2138,10 +2282,11 @@ impl EcVolume { // The old handle points at the replaced file: drop it before the // reopen so a failure leaves deletes erroring, not appending to a // detached inode. Mirrors Go's ReopenDeletionJournal. - self.ecj_file = None; + let mut journal = self.journal(); + journal.file = None; let reopened = open_ecj_append(&ecj_path)?; - self.ecj_file_size = reopened.metadata()?.len() as i64; - self.ecj_file = Some(reopened); + journal.size = reopened.metadata()?.len() as i64; + journal.file = Some(reopened); if let Ok(mut set) = self.deleted_needles.write() { set.clear(); } @@ -2184,63 +2329,38 @@ impl EcVolume { return Ok(()); } - let mut buf = [0u8; NEEDLE_ID_SIZE]; - needle_id.to_bytes(&mut buf); - self.append_journal(&buf)?; - if let Ok(mut set) = self.deleted_needles.write() { - set.insert(needle_id); - } - Ok(()) + self.journal_appender().journal_delete(needle_id, || false) } - /// Append whole records to `.ecj` and sync them. On any failure the file is - /// truncated back to the pre-append length so the on-disk journal and - /// `deleted_needles` cannot drift. - fn append_journal(&mut self, records: &[u8]) -> io::Result<()> { - let prev_ecj_size = self.ecj_file_size; - let append_result: io::Result<()> = { - let ecj_file = self - .ecj_file - .as_mut() - .ok_or_else(|| io::Error::other("ecj file not open"))?; - ecj_file - .write_all(records) - .and_then(|_| ecj_file.sync_all()) - }; - - match append_result { - Ok(()) => { - self.ecj_file_size += records.len() as i64; - Ok(()) - } - Err(e) => { - // write_all may have extended the file on disk before - // sync_all failed; truncate back to the known-good size so - // the on-disk journal never drifts past `deleted_needles`. - // Uses its own write handle: on Windows the append handle - // lacks FILE_WRITE_DATA, so set_len through it fails with - // ERROR_ACCESS_DENIED and the rollback would silently not - // happen. - let ecj_path = self.ecj_file_name(); - let rollback = open_volume_file(OpenOptions::new().write(true), &ecj_path) - .and_then(|f| f.set_len(prev_ecj_size as u64).and_then(|_| f.sync_all())); - // Bumped on attempt, not success: a failed rollback leaves the - // bytes in place and a decode re-reading for the epoch change - // simply sees them — harmless — while a successful one must - // never go unnoticed by an unlocked journal read. - ECJ_ROLLBACK_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - if let Err(trunc_err) = rollback { - tracing::error!( - volume_id = self.volume_id.0, - truncate_error = %trunc_err, - "failed to truncate ecj after append failure" - ); - } - Err(e) - } + /// This volume's journal, detached from the borrow of the volume. + pub fn journal_appender(&self) -> EcJournalAppender { + EcJournalAppender { + volume_id: self.volume_id, + ecj_path: self.ecj_file_name(), + path_lock: self.journal_path_lock(), + ecj: self.ecj.clone(), + deleted_needles: self.deleted_needles.clone(), } } + /// The append lock of this volume's `.ecj` path, shared with every other + /// disk's runtime journaling into the same file. + pub(crate) fn journal_path_lock(&self) -> Option>> { + self.ecj_hold.as_ref().map(EcjHold::append_lock) + } + + /// Takes this volume's journal lock, waiting out an append in flight. + pub(crate) fn journal(&self) -> MutexGuard<'_, EcJournal> { + self.ecj.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn append_journal(&mut self, records: &[u8]) -> io::Result<()> { + let ecj_path = self.ecj_file_name(); + let path_lock = self.journal_path_lock(); + let _path = lock_path(&path_lock); + self.journal().append(records, self.volume_id, &ecj_path) + } + /// Internal: binary search .ecx without masking by `deleted_needles`. /// Used by `journal_delete` so a repeat delete can still see the raw /// pre-existing .ecx tombstone from a prior rebuild. @@ -2380,9 +2500,9 @@ impl EcVolume { /// Fold a peer's deletion journal into this mounted volume: append only /// the ids not already deleted here, in one write and one fsync, then /// publish them into the in-memory set — the same commit order as - /// `journal_delete`. `&mut self` serializes it with deletes under the store - /// lock, and the live handle is appended to in place, so no delete can land - /// in an orphaned file. Returns how many ids were added. + /// `journal_delete`. The journal lock serializes it with deletes, and the + /// live handle is appended to in place, so no delete can land in an + /// orphaned file. Returns how many ids were added. pub fn merge_journal(&mut self, ids: &HashSet) -> io::Result { let delta = super::ecj_merge::ecj_delta(ids, |id| self.is_needle_deleted(*id)); if delta.is_empty() { @@ -2405,6 +2525,13 @@ impl EcVolume { // ---- Lifecycle ---- + /// Closes the journal handle under its lock, after any append in flight. + fn close_journal(&self) { + let mut journal = self.journal(); + journal.file = None; + journal.closed = true; + } + pub fn close(&mut self) { for shard in &mut self.shards { if let Some(s) = shard { @@ -2417,7 +2544,7 @@ impl EcVolume { let _ = ecx_file.sync_all(); } self.ecx_file = None; - self.ecj_file = None; + self.close_journal(); self.ecj_hold = None; } @@ -2479,11 +2606,17 @@ impl EcVolume { let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base); } self.ecx_file = None; - self.ecj_file = None; + self.close_journal(); self.ecj_hold = None; } } +impl Drop for EcVolume { + fn drop(&mut self) { + self.close_journal(); + } +} + #[cfg(test)] mod tests { use super::*; @@ -3504,6 +3637,44 @@ mod tests { assert!(deleted.contains(&NeedleId(7))); } + /// Disks sharing one `.ecj` share its append lock: a delete through one + /// disk's handle waits while another disk's runtime reads or replaces the + /// file, so a fold or a mount never sees an append half done. + #[test] + fn test_sibling_holders_share_the_append_lock() { + let tmp = TempDir::new().unwrap(); + let a_dir = tmp.path().join("a"); + let b_dir = tmp.path().join("b"); + std::fs::create_dir_all(&a_dir).unwrap(); + std::fs::create_dir_all(&b_dir).unwrap(); + let (a, b) = (a_dir.to_str().unwrap(), b_dir.to_str().unwrap()); + let vid = VolumeId(49); + write_ecx_file( + a, + "", + vid, + &[(NeedleId(7), Offset::from_actual_offset(8), Size(10))], + ); + + let on_a = EcVolume::new(a, a, "", vid).unwrap(); + let on_b = EcVolume::new(b, a, "", vid).unwrap(); + assert_eq!(on_b.ecj_file_name(), on_a.ecj_file_name()); + + let path_lock = on_a.journal_path_lock(); + let held = lock_path(&path_lock); + let appender = on_b.journal_appender(); + let delete = std::thread::spawn(move || appender.journal_delete(NeedleId(7), || false)); + std::thread::sleep(std::time::Duration::from_millis(100)); + assert!( + !delete.is_finished(), + "a sibling's append must wait for the path lock" + ); + drop(held); + delete.join().unwrap().unwrap(); + assert!(on_b.is_needle_deleted(NeedleId(7))); + assert_eq!(on_a.read_deleted_needles().unwrap(), vec![NeedleId(7)]); + } + /// A copy appending to the journal by path must not have its bytes /// dropped by a compaction renaming over the file. #[test] @@ -3655,7 +3826,10 @@ mod tests { write_bloated_ecj(dir, "", VolumeId(43), &ids, 4096); let mut vol = EcVolume::new(dir, dir, "", VolumeId(43)).unwrap(); - assert!(vol.ecj_file.is_some(), "mount must leave a journal handle"); + assert!( + vol.journal().file.is_some(), + "mount must leave a journal handle" + ); let ecj_path = format!( "{}.ecj", diff --git a/seaweed-volume/src/storage/erasure_coding/ecj_registry.rs b/seaweed-volume/src/storage/erasure_coding/ecj_registry.rs index 426623875b..c8696def1d 100644 --- a/seaweed-volume/src/storage/erasure_coding/ecj_registry.rs +++ b/seaweed-volume/src/storage/erasure_coding/ecj_registry.rs @@ -32,7 +32,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Condvar, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; #[derive(Default)] struct PathState { @@ -42,6 +42,10 @@ struct PathState { /// Writers that have started on the path. Lives as long as the entry, /// which a registered holder keeps. write_gen: u64, + /// Serializes appends through every holder's handle with anything that + /// reads or replaces the file under a holder, as one disk's journal lock + /// covers only its own handle. + append_lock: Arc>, } impl PathState { @@ -69,7 +73,7 @@ fn lock() -> MutexGuard<'static, HashMap> { /// Canonical key for `path`: its resolved parent directory joined with the /// file name. The file itself may not exist yet (a copy creates it), so only /// the directory is resolved. -fn key_for(path: &str) -> PathBuf { +pub(crate) fn key_for(path: &str) -> PathBuf { let p = Path::new(path); let (Some(parent), Some(name)) = (p.parent(), p.file_name()) else { return std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); @@ -118,6 +122,7 @@ pub(crate) struct EcjHold { /// so they cover every write the load might have missed. write_gen: u64, writer_at_start: bool, + append_lock: Arc>, } impl EcjHold { @@ -125,17 +130,23 @@ impl EcjHold { /// progress so the handle opened afterwards is on the final inode. pub(crate) fn acquire(ecj_path: &str) -> Self { let key = key_for(ecj_path); - let (write_gen, writer_at_start) = update_when_not_compacting(&key, |s| { + let (write_gen, writer_at_start, append_lock) = update_when_not_compacting(&key, |s| { s.holders += 1; - (s.write_gen, s.writers > 0) + (s.write_gen, s.writers > 0, s.append_lock.clone()) }); EcjHold { key, write_gen, writer_at_start, + append_lock, } } + /// The path's append lock, shared by every holder of the path. + pub(crate) fn append_lock(&self) -> Arc> { + self.append_lock.clone() + } + /// Reserve the path for a compaction, or `None` when another holder or an /// active writer could still reach the current inode, or when a writer /// has run on the path since the hold was taken, so the journal may no diff --git a/seaweed-volume/src/storage/store.rs b/seaweed-volume/src/storage/store.rs index 9976900a4a..0f9d1c648f 100644 --- a/seaweed-volume/src/storage/store.rs +++ b/seaweed-volume/src/storage/store.rs @@ -1363,6 +1363,19 @@ impl Store { None } + /// Takes the journal lock of every runtime of `vid`, in disk order, so no + /// delete append is in flight while the caller reads the journals. + pub(crate) fn lock_ec_journals( + &self, + vid: VolumeId, + ) -> Vec> { + self.locations + .iter() + .filter_map(|loc| loc.find_ec_volume(vid)) + .map(|ecv| ecv.journal()) + .collect() + } + /// Find an EC volume across all locations (mutable). /// Every per-disk `EcVolume` this store maps for `vid`. A vid can mount on /// N disks as N distinct runtimes, and the first-match `find_ec_volume_mut` diff --git a/weed/server/volume_grpc_erasure_coding.go b/weed/server/volume_grpc_erasure_coding.go index a0e4fcbdc1..7edf07635b 100644 --- a/weed/server/volume_grpc_erasure_coding.go +++ b/weed/server/volume_grpc_erasure_coding.go @@ -296,16 +296,19 @@ func (vs *VolumeServer) VolumeEcShardsRebuild(ctx context.Context, req *volume_s // handle is repointed: otherwise RebuildEcxFile's unlink strands later // appends on the detached inode. indexBaseFileName = ev.EcIndexBaseFileName() + folded := false unlockJournal := ev.LockDeletionJournal() err := erasure_coding.RebuildEcxFile(indexBaseFileName) if err == nil { + folded = true err = ev.ReopenDeletionJournal() } unlockJournal() - if err == nil { + if folded { // Mounts on sibling disks can journal into the same .ecj — the // fold unlinked it, so repoint their handles too or their next - // append lands on the detached inode. + // append lands on the detached inode, even when this mount's own + // reopen failed, and past a sibling that fails. for _, location := range vs.store.Locations { if location == rebuildLocation { continue @@ -314,9 +317,8 @@ func (vs *VolumeServer) VolumeEcShardsRebuild(ctx context.Context, req *volume_s unlockSibling := sibling.LockDeletionJournal() serr := sibling.ReopenDeletionJournal() unlockSibling() - if serr != nil { + if serr != nil && err == nil { err = fmt.Errorf("reopen shared ec journal on %s: %v", location.Directory, serr) - break } } }