diff --git a/rust/src/daemon.rs b/rust/src/daemon.rs index f01221a78..5db7def18 100644 --- a/rust/src/daemon.rs +++ b/rust/src/daemon.rs @@ -222,6 +222,9 @@ fn destroy_instance() { if let Some(ws) = WORK_STATE.lock().unwrap_or_else(PoisonError::into_inner).take() { crate::ffi::uninstall_workstate(&ws); } + // Every queued state save runs now; one still failing (a full queue disk) makes the + // stop unclean: logged here, and the process exits with status 1. + crate::statesaver::stop_report(); if let Some(opts) = OPTIONS.lock().unwrap_or_else(PoisonError::into_inner).take() { crate::options::release_options(opts); } diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 1ca1bc4d2..ddedf3007 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2111,15 +2111,20 @@ fn queue_file_path(qdir: &[u8], sep: u8, name: &[u8]) -> Vec { crate::artwritercore::article_writer_format_dest_file_path(qdir, sep, name) } -/// Deletes a queue-dir file, in order with the saves queued for it (statesaver). +/// Deletes a queue-dir file and its `.new` (a load would restore a `.new` found alone), +/// in order with the saves queued for it (statesaver). fn remove_queue_file(qdir: &[u8], sep: u8, name: &[u8]) { let p = queue_file_path(qdir, sep, name); let job = crate::statesaver::Job { seq: 0, - temp: p.clone(), + temp: diskstate_format_new_path(&p), path: p, sep, - kind: crate::statesaver::JobKind::Delete { temp_too: false }, + kind: crate::statesaver::JobKind::Delete { + temp_too: true, + after: None, + }, + retry: Default::default(), }; crate::statesaver::submit(job, &mut active_disk_log_cb); } @@ -4560,6 +4565,30 @@ pub(crate) fn test_state_sync_delay() { } } +/// A failed sync that may have lost the written data (`EIO`, a full disk or quota): +/// the save fails. Others (a file system that cannot sync) only warn, as before. +fn sync_lost_data(errno: i32) -> bool { + errno == libc::EIO || errno == libc::ENOSPC || errno == libc::EDQUOT +} + +/// Unit-test hook: a write of a state file whose path ends with a name in +/// `FAIL_WRITES` fails as on a full disk. +#[cfg(test)] +pub(crate) static FAIL_WRITES: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + +fn test_state_write_fails(_path: &[u8]) -> Option { + #[cfg(test)] + if FAIL_WRITES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .any(|n| _path.ends_with(n)) + { + return Some(std::io::Error::from_raw_os_error(libc::ENOSPC)); + } + None +} + /// Writes or deletes one state file as `RsStateFile` always has: a transactional write /// goes to `.new`, is synced (FlushQueue), renamed over the file, and the /// directory synced. Runs inline or on the `queue-saver` thread (statesaver). @@ -4570,7 +4599,7 @@ pub(crate) fn run_state_job( let dest_c = bytes_to_cstring_trunc(&job.path); let temp_c = bytes_to_cstring_trunc(&job.temp); let (bytes, transactional, sync) = match &job.kind { - crate::statesaver::JobKind::Delete { temp_too } => { + crate::statesaver::JobKind::Delete { temp_too, .. } => { crate::fsops::delete_file(&dest_c); if *temp_too { crate::fsops::delete_file(&temp_c); @@ -4599,7 +4628,27 @@ pub(crate) fn run_state_job( return false; } let mut file: std::fs::File = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fd) }; - let _ = file.write_all(bytes); + // A write cut short (6790: the queue disk full) is never renamed over the last good + // file: the temporary file goes and the save fails (statesaver retries it). + let written = test_state_write_fails(&job.path) + .map_or_else(|| file.write_all(bytes), Err); + if let Err(e) = written { + log( + DiskLogLevel::Error, + &[ + b"Error saving diskstate: Could not write file ", + &job.temp[..], + b": ", + e.to_string().as_bytes(), + ] + .concat(), + ); + drop(file); + if transactional { + crate::fsops::delete_file(&temp_c); + } + return false; + } if !transactional { return true; } @@ -4617,6 +4666,23 @@ pub(crate) fn run_state_job( let fd = std::os::unix::io::AsRawFd::as_raw_fd(&file); test_state_sync_delay(); if !crate::fsops::flush_file_buffers(fd, &mut errmsg) { + let errno = crate::fsops::last_errno(); + if sync_lost_data(errno) { + // The data may not be on disk: keep the last good file. + log( + DiskLogLevel::Error, + &[ + b"Error saving diskstate: Could not flush file ", + &job.temp[..], + b" into disk: ", + &errmsg, + ] + .concat(), + ); + drop(file); + crate::fsops::delete_file(&temp_c); + return false; + } log( DiskLogLevel::Warning, &[ @@ -4632,7 +4698,7 @@ pub(crate) fn run_state_job( drop(file); - crate::fsops::delete_file(&dest_c); + // rename(2) replaces the last good file in one step: no moment without it. if !crate::fsops::move_file(&temp_c, &dest_c) { let err = crate::fsops::error_message(crate::fsops::last_errno()); log( @@ -4714,6 +4780,15 @@ impl RsStateFile { } fn discard(&self) { + self.discard_job(None); + } + + /// Deletes the file once the save of `after` queued before has reached the disk. + fn discard_after(&self, after: &[u8]) { + self.discard_job(Some(after.to_vec())); + } + + fn discard_job(&self, after: Option>) { let job = crate::statesaver::Job { seq: 0, path: self.dest.clone(), @@ -4721,7 +4796,9 @@ impl RsStateFile { sep: self.sep, kind: crate::statesaver::JobKind::Delete { temp_too: self.transactional, + after, }, + retry: Default::default(), }; crate::statesaver::submit(job, &mut active_disk_log_cb); } @@ -4762,6 +4839,7 @@ impl RsStateFile { transactional: self.transactional, sync: self.flush && flush_queue, }, + retry: Default::default(), }; crate::statesaver::submit(job, &mut |level, msg| emit_log(env, level, msg)) } @@ -5673,7 +5751,7 @@ unsafe fn save_single_file_or_state( qdir: &[u8], sep: u8, part: FilePart, - replace: bool, + _replace: bool, // every save is transactional and unsynced now (see below) ) -> bool { let export_mode = match part { FilePart::Info => FileExport::InfoWithArticles, @@ -5699,15 +5777,22 @@ unsafe fn save_single_file_or_state( } else { diskstate_format_file_state_name(file_id, part == FilePart::CompletedState) }; + // Always written to `.new` and renamed: a partial state (`s`) written in + // place was cut short when the queue disk filled (6790), and the load then threw away + // every article it recorded (57 GB downloaded again). A write error now keeps the + // last good file. Not synced, as before: the partial states of every downloading + // file are saved each second, and a sync each (with the directory's) queued the + // saves behind one another (queuesyncslow: a thread waiting for its save waited + // seconds); rename over an existing file is ordered after its data on ext4. let mut sf = RsStateFile::new( qdir, sep, &fname, DISKSTATE_FILE_VERSION, - replace, + true, DISKSTATE_FILE_VERSION, ); - sf.flush = !replace; + sf.flush = false; let Some(mut w) = (unsafe { sf.begin_write(env) }) else { return false; }; @@ -5741,7 +5826,9 @@ unsafe fn load_single_file_or_state( sep, &fname, DISKSTATE_FILE_VERSION, - false, + // Transactional: a `.new` left by a crash is dropped next to the file, or + // restored when it is all there is. + true, DISKSTATE_FILE_LEGACY_VERSION, ); let Some(mut r) = (unsafe { sf.begin_read(env) }) else { @@ -5871,6 +5958,10 @@ unsafe fn load_all_file_states_op( let cache_was_active = cache_was_active(qdir, sep); for filename in crate::fsops::list_dir_entries(qdir) { + // `s.new` is a state's temporary file: read through its `s` (begin_read). + if filename.contains(&b'.') { + continue; + } if let Some((id, suffix)) = diskstate_parse_queue_file_id_and_suffix(&filename) { if suffix == b'c' || (env.continue_partial != 0 && !cache_was_active) { let found = call_ctrl(env, DiskCtrl::SelectFileWithCounters { file_id: id }) != 0; @@ -6768,7 +6859,9 @@ pub unsafe fn diskstate_exec(op: DiskOp, env: &NzbgetRsDiskStateEnv) -> c_int { true, DISKSTATE_QUEUE_VERSION, ); - p_sf.discard(); + // Obsolete once this queue save is on disk: deleted after it, never while it + // fails (statesaver retries it; the progress since the last good queue stays). + p_sf.discard_after(&q_sf.dest); let last_nzb = call_ctrl(env, DiskCtrl::LastNzbId); let last_file = call_ctrl(env, DiskCtrl::LastFileId); diff --git a/rust/src/entrypoint.rs b/rust/src/entrypoint.rs index 734649356..a265ad11d 100644 --- a/rust/src/entrypoint.rs +++ b/rust/src/entrypoint.rs @@ -149,7 +149,13 @@ pub unsafe extern "C" fn nzbget_rs_main( } // 3. Lifecycle coordinator loop (4-Phase Lifecycle) - LifecycleManager::global().run_daemon_loop(argc, argv, argp) + let rc = LifecycleManager::global().run_daemon_loop(argc, argv, argp); + // A stop that left state files unsaved is not a clean exit (statesaver). + if rc == 0 && crate::statesaver::stopped_unclean() { + 1 + } else { + rc + } } #[cfg(test)] diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs index fca7289be..754b42156 100644 --- a/rust/src/statesaver.rs +++ b/rust/src/statesaver.rs @@ -21,14 +21,50 @@ //! ([`settled`]), so it sees the latest content without waiting for a sync. //! //! Across files there is no crash-time ordering beyond that: after a crash the disk -//! can hold a newer `progress` next to an older `queue`, and a queue save whose write -//! fails on this thread has already queued the delete of `progress` behind it. The -//! loader never relied on more (a partial state could already be newer than `queue`, -//! `files` is checked against the queued file count, `ids` is a floor written inline). +//! can hold a newer `progress` next to an older `queue`. The loader never relied on +//! more (a partial state could already be newer than `queue`, `files` is checked +//! against the queued file count, `ids` is a floor written inline). A delete that +//! must follow a write of another file (`progress` after `queue`) waits for it +//! ([`JobKind::Delete`] `after`) and is dropped if that write never succeeds. +//! +//! A failed save (6790: the queue disk full, ENOSPC) keeps the last good file (the +//! writer never renames a write that failed) and is retried with backoff +//! ([`Retry`]): it stays queued, a newer save of the file takes its place and its +//! backoff, and nobody waits for it meanwhile (a full disk must not stall the API or +//! the coordinator). At shutdown [`finish`] tries each failing save once more and +//! names the ones that still fail: the stop is then not clean. use crate::diskstate_format::DiskLogLevel; use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +/// The first retry of a failed save comes after this; each further one doubles it, up +/// to [`RETRY_MAX`]. +const RETRY_BASE: Duration = Duration::from_secs(1); +const RETRY_MAX: Duration = Duration::from_secs(30); + +/// How often a save of this file failed in a row, and when it is tried again. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Retry { + pub attempts: u32, + pub not_before: Option, +} + +impl Retry { + /// The state after one more failed attempt at `now`. + fn failed(&self, now: Instant) -> Self { + let attempts = self.attempts.saturating_add(1); + let shift = (attempts - 1).min(16); + let wait = RETRY_BASE + .checked_mul(1u32 << shift) + .map_or(RETRY_MAX, |d| d.min(RETRY_MAX)); + Self { + attempts, + not_before: Some(now + wait), + } + } +} /// What a job does to its file. #[derive(Debug, Clone, PartialEq, Eq)] @@ -40,8 +76,13 @@ pub(crate) enum JobKind { transactional: bool, sync: bool, }, - /// Delete the file, and `temp` too when `temp_too`. - Delete { temp_too: bool }, + /// Delete the file, and `temp` too when `temp_too`. With `after`, only once no + /// job for that file is queued or running: `progress` is deleted after the `queue` + /// save that makes it obsolete has reached the disk, never while it fails. + Delete { + temp_too: bool, + after: Option>, + }, } /// One state file to write or delete. `path` identifies it. @@ -54,6 +95,8 @@ pub(crate) struct Job { pub temp: Vec, pub sep: u8, pub kind: JobKind, + /// Failed attempts so far; set by the saver. + pub retry: Retry, } pub(crate) type Log<'a> = &'a mut dyn FnMut(DiskLogLevel, &[u8]); @@ -68,6 +111,34 @@ struct State { next_seq: u64, /// Saves are queued (the coordinator runs), else run inline. queue_saves: bool, + /// Files whose save was given up ([`Saver::drain`] after its last attempt failed). + unsaved: Vec>, + /// Files whose failed save [`Saver::drain`] tries a last time now: out of the queue + /// and maybe not yet marked running, so a delete waiting for them checks here too. + last_attempt: Vec>, +} + +impl State { + /// A queued job nobody waits for: it failed before (it is retried later), or it + /// is a delete waiting for a write of another file. + fn deferred(&self, job: &Job) -> bool { + job.retry.attempts > 0 || self.blocked(job) + } + + /// A delete whose `after` file still has a job queued or running. + fn blocked(&self, job: &Job) -> bool { + match &job.kind { + JobKind::Delete { + after: Some(after), .. + } => { + self.queue.iter().any(|j| j.path == *after) + || self.in_flight.iter().any(|(p, _)| p == after) + || self.unsaved.contains(after) + || self.last_attempt.contains(after) + } + _ => false, + } + } } pub(crate) struct Saver { @@ -88,11 +159,11 @@ thread_local! { /// While alive (the coordinator's loop), saves are queued for the saver thread; on drop, /// saves run inline again and the queued ones are drained. -pub(crate) struct AsyncSaves(&'static Saver); +pub(crate) struct AsyncSaves(&'static Arc); impl AsyncSaves { pub(crate) fn enter() -> Self { - let saver: &'static Saver = global(); + let saver: &'static Arc = global(); saver.lock().queue_saves = true; COORDINATOR.with(|c| c.set(true)); Self(saver) @@ -132,6 +203,15 @@ fn active_log(level: DiskLogLevel, msg: &[u8]) { crate::log::log_active_bytes(level.kind() as i32, msg); } +fn saved_again_message(job: &Job) -> Vec { + [ + &b"Saved diskstate file "[..], + &job.path, + format!(" after {} failed attempts", job.retry.attempts).as_bytes(), + ] + .concat() +} + impl Saver { pub(crate) fn new(exec: Box) -> Arc { Arc::new(Self { @@ -156,10 +236,11 @@ impl Saver { let mut st = self.lock(); let coordinator = COORDINATOR.with(|c| c.get()); let under_lock = QUEUE_LOCK_DEPTH.with(|d| d.get() > 0); - if st.queue_saves && (coordinator || under_lock) { + // A delete that waits for another file's write is queued behind it. + if (st.queue_saves && (coordinator || under_lock)) || st.blocked(&job) { let path = job.path.clone(); let seq = self.enqueue_locked(st, job); - if !coordinator { + if !coordinator && under_lock { TICKETS.with(|t| t.borrow_mut().push((path, seq))); } true @@ -169,9 +250,11 @@ impl Saver { st.next_seq += 1; job.seq = st.next_seq; // This newer content (or delete) replaces a queued one, and whoever waits - // for that one waits for this. + // for that one waits for this; a failing one's count goes on. if let Some(i) = st.queue.iter().position(|j| j.path == job.path) { - job.seq = st.queue.remove(i).expect("position is in range").seq; + let old = st.queue.remove(i).expect("position is in range"); + job.seq = old.seq; + job.retry.attempts = old.retry.attempts; } self.run_marked(st, job, log) } @@ -193,7 +276,9 @@ impl Saver { if matches!(st.queue[i].kind, JobKind::Write { .. }) && matches!(job.kind, JobKind::Write { .. }) => { + // Latest content, first position, and a failing save's backoff. job.seq = st.queue[i].seq; + job.retry = st.queue[i].retry.clone(); st.queue[i] = job; st.queue[i].seq } @@ -207,6 +292,12 @@ impl Saver { st.next_seq } }; + self.start_worker(st); + seq + } + + /// Starts the saver thread if it is not running yet, and wakes it. + fn start_worker(self: &Arc, mut st: MutexGuard<'_, State>) { if !st.thread_started { let me = Arc::clone(self); if std::thread::Builder::new() @@ -219,19 +310,53 @@ impl Saver { // No thread: run the queue here, as before. drop(st); self.run_queue_inline(); - return seq; + return; } } self.cv.notify_all(); - seq } - /// Waits until none of `tickets` (file, seq) is queued or running. - fn wait_for(&self, tickets: &[(Vec, u64)]) { + /// Runs `job`, marked running by the caller. A failed save is queued again for a + /// retry with backoff (the saver thread runs it), unless a newer save of the file + /// is queued already: that one takes over the backoff. + fn exec_job(self: &Arc, job: Job, log: Log<'_>) -> bool { + let ok = (self.exec)(&job, log); + if ok { + if job.retry.attempts > 0 { + log(DiskLogLevel::Info, &saved_again_message(&job)); + } + let mut st = self.lock(); + st.unsaved.retain(|p| *p != job.path); + return true; + } + let retry = job.retry.failed(Instant::now()); + let mut st = self.lock(); + if let Some(newer) = st.queue.iter_mut().find(|j| j.path == job.path) { + if newer.retry.attempts < retry.attempts { + newer.retry = retry; + } + } else { + st.queue.push_back(Job { retry, ..job }); + } + self.start_worker(st); + false + } + + /// Waits until none of `tickets` (file, seq) is queued or running, but for a save + /// that failed (retried later) or a delete waiting for another file's write. + fn wait_for(self: &Arc, tickets: &[(Vec, u64)]) { let mut st = self.lock(); + if !st.thread_started { + // No saver thread: nobody else would run them. + drop(st); + self.run_queue_inline(); + st = self.lock(); + } loop { let busy = tickets.iter().any(|(p, s)| { - st.queue.iter().any(|j| j.path == *p && j.seq <= *s) + st.queue + .iter() + .any(|j| j.path == *p && j.seq <= *s && !st.deferred(j)) || st.in_flight.iter().any(|(fp, fs)| fp == p && fs <= s) }); if !busy { @@ -252,9 +377,10 @@ impl Saver { } /// Waits for a job running for the same file, then runs `job` in this thread. - fn run_marked(&self, st: MutexGuard<'_, State>, job: Job, log: Log<'_>) -> bool { - let _mark = self.mark(st, &job.path, job.seq); - (self.exec)(&job, log) + fn run_marked(self: &Arc, st: MutexGuard<'_, State>, job: Job, log: Log<'_>) -> bool { + let path = job.path.clone(); + let _mark = self.mark(st, &path, job.seq); + self.exec_job(job, log) } /// Waits until no job runs for `path`, then marks it running (as save `seq`; a @@ -267,22 +393,43 @@ impl Saver { Mark { saver: self, path } } - fn next_job(&self, st: &mut State) -> Option { - let i = st - .queue - .iter() - .position(|j| !st.in_flight.iter().any(|(p, _)| *p == j.path))?; + /// The first queued job that may run now: its file is not running, its retry is + /// due, and a delete's `after` write is done. + fn next_job(&self, st: &mut State, now: Instant) -> Option { + let i = st.queue.iter().position(|j| { + !st.in_flight.iter().any(|(p, _)| *p == j.path) + && j.retry.not_before.is_none_or(|t| t <= now) + && !st.blocked(j) + })?; st.queue.remove(i) } - fn worker(&self) { + fn worker(self: Arc) { loop { let mut st = self.lock(); let job = loop { - if let Some(job) = self.next_job(&mut st) { + if let Some(job) = self.next_job(&mut st, Instant::now()) { break job; } - st = self.wait(st); + // Asleep until a job comes, or the next retry is due. + // (Only jobs that could run then: one whose file another thread holds + // wakes it when that thread is done.) + let due = st + .queue + .iter() + .filter(|j| !st.in_flight.iter().any(|(p, _)| *p == j.path) && !st.blocked(j)) + .filter_map(|j| j.retry.not_before) + .min(); + st = match due { + Some(due) => { + let wait = due.saturating_duration_since(Instant::now()); + self.cv + .wait_timeout(st, wait.max(Duration::from_millis(1))) + .unwrap_or_else(|e| e.into_inner()) + .0 + } + None => self.wait(st), + }; }; // A panicking job must not kill the thread: later jobs and `drain` wait for it. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { @@ -297,43 +444,61 @@ impl Saver { } } - fn run_queue_inline(&self) { + /// Runs the queued jobs due now in this thread (no saver thread could start). A + /// failed one stays queued for the next call. + fn run_queue_inline(self: &Arc) { loop { let mut st = self.lock(); - let Some(job) = self.next_job(&mut st) else { + let Some(job) = self.next_job(&mut st, Instant::now()) else { return; }; - self.run_marked(st, job, &mut active_log); + let path = job.path.clone(); + let _mark = self.mark(st, &path, job.seq); + if !(self.exec)(&job, &mut active_log) { + // Kept for a later call (its backoff not yet due), merged into a newer + // queued save of the file as `exec_job` does; the others go on. + let retry = job.retry.failed(Instant::now()); + let mut st = self.lock(); + if let Some(newer) = st.queue.iter_mut().find(|j| j.path == job.path) { + if newer.retry.attempts < retry.attempts { + newer.retry = retry; + } + } else { + st.queue.push_back(Job { retry, ..job }); + } + } } } /// Makes the latest content of `path` reach the disk before a caller reads, /// stats or deletes it: runs its queued job now, in this thread, or waits for /// the one running. - pub(crate) fn settle(&self, path: &[u8]) { + pub(crate) fn settle(self: &Arc, path: &[u8]) { self.settled(path, || ()); } /// [`Saver::settle`], then runs `f` while no job can touch `path`: a reader that - /// checks the file and its `.new` never sees the moment of a rename. - pub(crate) fn settled(&self, path: &[u8], f: impl FnOnce() -> R) -> R { + /// checks the file and its `.new` never sees the moment of a rename. A delete that + /// still waits for another file's write stays queued (the file stays meanwhile). + pub(crate) fn settled(self: &Arc, path: &[u8], f: impl FnOnce() -> R) -> R { let mut st = self.idle(self.lock(), path); let pending = st .queue .iter() - .position(|j| j.path == path) + .position(|j| j.path == path && !st.blocked(j)) .and_then(|i| st.queue.remove(i)); let seq = pending.as_ref().map_or(u64::MAX, |j| j.seq); let _mark = self.mark(st, path, seq); if let Some(job) = pending { - (self.exec)(&job, &mut active_log); + self.exec_job(job, &mut active_log); } f() } /// The content of a queued write of `path`, for a reader: the file on disk is older. - /// A queued delete runs now (no sync), so the reader finds the file gone. - pub(crate) fn pending_content(&self, path: &[u8]) -> Option> { + /// A queued delete runs now (no sync), so the reader finds the file gone, unless it + /// waits for another file's write. + pub(crate) fn pending_content(self: &Arc, path: &[u8]) -> Option> { let mut st = self.lock(); let i = st.queue.iter().position(|j| j.path == path)?; if let JobKind::Write { bytes, .. } = &st.queue[i].kind { @@ -344,19 +509,74 @@ impl Saver { if let JobKind::Write { bytes, .. } = &st.queue[i].kind { return Some(bytes.clone()); } + if st.blocked(&st.queue[i]) { + return None; + } let job = st.queue.remove(i).expect("position is in range"); self.run_marked(st, job, &mut active_log); None } - /// Waits until every queued job has run (the coordinator's exit). - pub(crate) fn drain(&self) { + /// Waits until every queued job has run (the coordinator's exit, the stop). A save + /// that failed and waits for its retry gets a last attempt now; one that fails + /// again is given up, the last good file staying ([`Saver::unsaved`] names it), and + /// a delete waiting for its write is dropped. Returns how many files are unsaved. + pub(crate) fn drain(self: &Arc) -> usize { let mut st = self.lock(); - while !st.queue.is_empty() || !st.in_flight.is_empty() { - st = self.wait(st); + loop { + if !st.thread_started { + drop(st); + self.run_queue_inline(); + st = self.lock(); + } + while !st.in_flight.is_empty() + || st + .queue + .iter() + .any(|j| j.retry.attempts == 0 && !st.blocked(j)) + { + st = self.wait(st); + } + // One failed save at a time, out of the queue and into `last_attempt` in one + // hold, so a delete waiting for it never sees it gone before it is decided. + let Some(i) = st.queue.iter().position(|j| j.retry.attempts > 0) else { + // Left: deletes waiting for a write that was given up. + st.queue.clear(); + self.cv.notify_all(); + return st.unsaved.len(); + }; + let job = st.queue.remove(i).expect("position is in range"); + st.last_attempt.push(job.path.clone()); + let ok = { + let _mark = self.mark(st, &job.path, job.seq); + (self.exec)(&job, &mut active_log) + }; + st = self.lock(); + st.last_attempt.retain(|p| *p != job.path); + if ok { + active_log(DiskLogLevel::Info, &saved_again_message(&job)); + st.unsaved.retain(|p| *p != job.path); + } else if !st.unsaved.contains(&job.path) { + active_log( + DiskLogLevel::Error, + &[ + &b"Error saving diskstate: giving up on "[..], + &job.path, + b"; the last good copy on disk is kept", + ] + .concat(), + ); + st.unsaved.push(job.path); + } + self.cv.notify_all(); } } + /// The files whose save [`Saver::drain`] gave up and no later save wrote. + pub(crate) fn unsaved(&self) -> Vec> { + self.lock().unsaved.clone() + } + #[cfg(test)] fn queued_paths(&self) -> Vec> { self.lock().queue.iter().map(|j| j.path.clone()).collect() @@ -406,10 +626,49 @@ pub(crate) fn pending_content(path: &[u8]) -> Option> { } /// [`Saver::drain`] on the daemon's saver. -pub(crate) fn drain() { +pub(crate) fn drain() -> usize { global().drain() } +/// The daemon stops: every queued save runs (a failing one gets its last attempt), and +/// the files whose latest state could not be saved are returned. Not empty, the stop +/// is not clean: their last good copies on disk are older than the queue in memory. +pub(crate) fn finish() -> Vec> { + let saver = global(); + saver.drain(); + saver.unsaved() +} + +/// Set once a stop (or reload) left state files unsaved; the process exit status says so. +static STOPPED_UNCLEAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// At the instance's teardown: [`finish`], and an error naming the unsaved files, if any. +pub(crate) fn stop_report() { + let unsaved = finish(); + STOPPED_UNCLEAN.store(false, std::sync::atomic::Ordering::SeqCst); + if unsaved.is_empty() { + return; + } + // (Each teardown decides anew: a reload's unsaved files are saved by a later one.) + STOPPED_UNCLEAN.store(true, std::sync::atomic::Ordering::SeqCst); + let mut msg = format!( + "Stopping is not clean: {} state file(s) could not be saved, their last good copies \ + are older than the queue in memory:", + unsaved.len() + ) + .into_bytes(); + for p in unsaved.iter().take(10) { + msg.push(b' '); + msg.extend_from_slice(crate::nserv::base_file_name(p)); + } + active_log(DiskLogLevel::Error, &msg); +} + +/// True once a teardown left state files unsaved ([`stop_report`]). +pub(crate) fn stopped_unclean() -> bool { + STOPPED_UNCLEAN.load(std::sync::atomic::Ordering::SeqCst) +} + #[cfg(test)] mod tests { use super::*; @@ -442,12 +701,16 @@ mod tests { transactional: true, sync: true, }, + retry: Retry::default(), } } fn delete(path: &str) -> Job { Job { - kind: JobKind::Delete { temp_too: true }, + kind: JobKind::Delete { + temp_too: true, + after: None, + }, ..write(path, "") } } @@ -610,6 +873,192 @@ mod tests { releaser.join().unwrap(); } + /// A saver whose writes fail while `full` is set (a full disk); it records the + /// jobs that succeeded and counts every attempt. + fn disk_full() -> ( + Arc, + Arc>>, + Arc, + Arc, + ) { + let done = Arc::new(Mutex::new(Vec::new())); + let full = Arc::new(AtomicBool::new(true)); + let tries = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (d, f, n) = (Arc::clone(&done), Arc::clone(&full), Arc::clone(&tries)); + let saver = Saver::new(Box::new(move |job: &Job, _log: Log<'_>| { + n.fetch_add(1, Ordering::SeqCst); + if matches!(job.kind, JobKind::Write { .. }) && f.load(Ordering::SeqCst) { + return false; + } + d.lock().unwrap().push(job.clone()); + true + })); + (saver, done, full, tries) + } + + fn wait_until(what: impl Fn() -> bool) { + let deadline = Instant::now() + Duration::from_secs(20); + while !what() { + assert!(Instant::now() < deadline, "timed out"); + std::thread::sleep(Duration::from_millis(5)); + } + } + + #[test] + fn a_failed_save_is_kept_and_retried_with_backoff_until_it_succeeds() { + let (saver, done, full, tries) = disk_full(); + assert!(!saver.submit(write("9s", "a"), &mut |_, _| {})); + // Kept, with its backoff; nobody waits for it. + let st = saver.lock(); + assert_eq!(st.queue.len(), 1); + assert_eq!(st.queue[0].retry.attempts, 1); + assert!(st.queue[0].retry.not_before.is_some()); + let seq = st.queue[0].seq; + drop(st); + saver.wait_for(&[(b"9s".to_vec(), seq)]); + // The first retry comes after about a second, not at once. + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(tries.load(Ordering::SeqCst), 1); + wait_until(|| tries.load(Ordering::SeqCst) >= 2); + assert_eq!(saver.lock().queue[0].retry.attempts, 2); + full.store(false, Ordering::SeqCst); + wait_until(|| !done.lock().unwrap().is_empty()); + assert_eq!(summary(&done), ["9s=a"]); + assert_eq!(saver.drain(), 0); + } + + #[test] + fn a_newer_save_of_a_failing_file_takes_its_place_and_backoff() { + let (saver, done, full, _tries) = disk_full(); + assert!(!saver.submit(write("8s", "old"), &mut |_, _| {})); + saver.lock().queue_saves = true; + COORDINATOR.with(|c| c.set(true)); + assert!(saver.submit(write("8s", "new"), &mut |_, _| {})); + COORDINATOR.with(|c| c.set(false)); + { + let st = saver.lock(); + assert_eq!(st.queue.len(), 1); + assert_eq!(st.queue[0].retry.attempts, 1, "the backoff goes on"); + } + assert_eq!(saver.pending_content(b"8s"), Some(b"new".to_vec())); + full.store(false, Ordering::SeqCst); + wait_until(|| !done.lock().unwrap().is_empty()); + assert_eq!(summary(&done), ["8s=new"]); + saver.lock().queue_saves = false; + saver.drain(); + } + + #[test] + fn a_delete_after_a_failing_write_waits_for_it_and_is_dropped_if_it_is_given_up() { + let (saver, done, full, _tries) = disk_full(); + let after_queue = |path: &str| Job { + kind: JobKind::Delete { + temp_too: true, + after: Some(b"queue".to_vec()), + }, + ..write(path, "") + }; + // The queue save fails: progress stays. + assert!(!saver.submit(write("queue", "q1"), &mut |_, _| {})); + assert!(saver.submit(after_queue("progress"), &mut |_, _| {})); + assert_eq!( + saver.queued_paths(), + [b"queue".to_vec(), b"progress".to_vec()] + ); + assert_eq!( + saver.pending_content(b"progress"), + None, + "a reader finds the file still there" + ); + assert_eq!(saver.queued_paths().len(), 2); + // Given up at the stop: the delete is dropped, progress kept. + assert_eq!(saver.drain(), 1); + assert_eq!(saver.unsaved(), [b"queue".to_vec()]); + assert!(saver.queued_paths().is_empty()); + assert!(summary(&done).is_empty()); + // The next queue save succeeds: then progress goes, after it. + full.store(false, Ordering::SeqCst); + assert!(saver.submit(write("queue", "q2"), &mut |_, _| {})); + assert!(saver.unsaved().is_empty()); + assert!(saver.submit(after_queue("progress"), &mut |_, _| {})); + assert_eq!(summary(&done), ["queue=q2", "-progress"]); + } + + #[test] + fn drain_gives_a_failing_save_a_last_attempt_and_names_it_when_that_fails() { + let (saver, done, full, tries) = disk_full(); + assert!(!saver.submit(write("5s", "x"), &mut |_, _| {})); + assert!(!saver.submit(write("6s", "y"), &mut |_, _| {})); + assert_eq!(saver.drain(), 2); + assert!(tries.load(Ordering::SeqCst) >= 4); + assert!(saver.queued_paths().is_empty()); + let mut unsaved = saver.unsaved(); + unsaved.sort(); + assert_eq!(unsaved, [b"5s".to_vec(), b"6s".to_vec()]); + // Space again: the last attempt succeeds. + assert!(!saver.submit(write("7s", "z"), &mut |_, _| {})); + full.store(false, Ordering::SeqCst); + assert_eq!(saver.drain(), 2); + assert_eq!(summary(&done), ["7s=z"]); + } + + /// The real writer on a full disk: the last good file stays whole, no `.new` is left. + #[test] + fn a_failed_write_never_replaces_the_last_good_file() { + use std::os::unix::ffi::OsStrExt; + let dir = std::env::temp_dir().join(format!( + "rg-statesaver-full-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("4242s"); + let temp = dir.join("4242s.new"); + std::fs::write(&path, b"last good").unwrap(); + let job = Job { + seq: 0, + path: path.as_os_str().as_bytes().to_vec(), + temp: temp.as_os_str().as_bytes().to_vec(), + sep: b'/', + kind: JobKind::Write { + bytes: b"newer".to_vec(), + transactional: true, + sync: true, + }, + retry: Retry::default(), + }; + crate::diskstate_format::FAIL_WRITES + .lock() + .unwrap() + .push(b"/4242s".to_vec()); + let mut errors = Vec::new(); + let ok = crate::diskstate_format::run_state_job(&job, &mut |level, msg| { + if level == DiskLogLevel::Error { + errors.push(String::from_utf8_lossy(msg).into_owned()); + } + }); + crate::diskstate_format::FAIL_WRITES + .lock() + .unwrap() + .retain(|n| n != b"/4242s"); + assert!(!ok); + assert_eq!(std::fs::read(&path).unwrap(), b"last good"); + assert!(!temp.exists()); + assert!( + errors + .iter() + .any(|e| e.contains("Could not write file") && e.contains("4242s.new")), + "{errors:?}" + ); + // Space again: the save replaces it. + assert!(crate::diskstate_format::run_state_job(&job, &mut |_, _| {})); + assert_eq!(std::fs::read(&path).unwrap(), b"newer"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The real job writer: a queued save is on disk, readable, after `settle`, /// and its temporary file is gone. #[test] @@ -636,6 +1085,7 @@ mod tests { transactional: true, sync: true, }, + retry: Retry::default(), }; saver.enqueue(job("first")); saver.enqueue(job("second")); diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index 3495070c8..0a6289836 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -1859,6 +1859,159 @@ def scenario_queuesyncslow(daemon, t): return ('queuesyncslow', ok, 'status=%s elapsed=%.1fs bound=30s' % (h['Status'], elapsed)) +def _small_fs_mount(t, mnt, size_mb): + """Mounts a small file system of its own at ``mnt`` (Linux: an ext4 image through + sudo, which frees a truncated file's blocks only at the next journal commit, as the + NVMe on 6790 did; macOS: an HFS+ disk image). Returns the unmount command, or None + with the reason when this machine cannot.""" + os.makedirs(mnt, exist_ok=True) + img = t.path('smallfs.img') + if sys.platform.startswith('linux'): + if shutil.which('mkfs.ext4') is None: + return None, 'mkfs.ext4 not installed' + if subprocess.run(['sudo', '-n', 'true'], capture_output=True).returncode != 0: + return None, 'no passwordless sudo to mount' + with open(img, 'wb') as f: + f.truncate(size_mb * 1024 * 1024) + if subprocess.run(['mkfs.ext4', '-q', '-F', '-m', '0', img], capture_output=True).returncode != 0: + return None, 'mkfs.ext4 failed' + if subprocess.run(['sudo', '-n', 'mount', '-o', 'loop', img, mnt], capture_output=True).returncode != 0: + return None, 'loop mount failed' + subprocess.run(['sudo', '-n', 'chown', '%d:%d' % (os.getuid(), os.getgid()), mnt], check=True) + return ['sudo', '-n', 'umount', mnt], None + if sys.platform == 'darwin': + dmg = img + '.dmg' + made = subprocess.run(['hdiutil', 'create', '-quiet', '-size', '%dm' % size_mb, '-fs', 'HFS+', + '-volname', 'rgfull', dmg], capture_output=True) + if made.returncode != 0: + return None, 'hdiutil create failed' + if subprocess.run(['hdiutil', 'attach', '-quiet', '-nobrowse', '-mountpoint', mnt, dmg], + capture_output=True).returncode != 0: + return None, 'hdiutil attach failed' + return ['hdiutil', 'detach', '-quiet', '-force', mnt], None + return None, 'no small file system on %s' % sys.platform + + +class _DiskFiller: + """Fills the file system of ``path`` and keeps it full: a thread writes whatever + space comes free (a deleted temporary file, a journal commit) into the filler file + until ``release``.""" + + def __init__(self, path): + self.path = path + self.stop = threading.Event() + self.f = open(path, 'wb', buffering=0) + self._fill() + self.thread = threading.Thread(target=self._keep_full, daemon=True) + self.thread.start() + + def _fill(self): + for chunk in (1 << 20, 1 << 16, 1 << 12, 512): + while True: + try: + self.f.write(b'\0' * chunk) + except OSError: + break + + def _keep_full(self): + while not self.stop.wait(0.02): + self._fill() + + def release(self): + self.stop.set() + self.thread.join(timeout=10) + try: + self.f.close() + except OSError: + pass + os.remove(self.path) + + +def scenario_diskfullrestart(daemon, t): + """6790, 2026-11-27: the disk holding QueueDir and InterDir filled up during a + download. The partial state of the downloading file (``s``, then written in + place) was cut short by the failed write, the deploy restart found it damaged and + threw away every article it recorded: 57 GB downloaded again. Here QueueDir and + InterDir sit on a small file system of their own; it is filled at 40 %, the daemon + is stopped (its last saves fail), space is freed and the daemon started again. No + article that came before the fill (less the last 4 s, which a save may not have + recorded yet) may be fetched again, the output must be byte-exact, and the stop + with failing saves must not exit 0 (not a clean stop).""" + seg, size = 100_000, 40_000_000 + data = _payload(size, 6790) + pp = _place_copy(t, 'dfA', data, 'f.bin') + api = daemon.wait_ready() + try: + api.shutdown() + except Exception: + pass + t.procs[-1].wait(timeout=60) + mnt = t.path('main', 'small') + umount, why = _small_fs_mount(t, mnt, 64) + if umount is None: + return ('diskfullrestart', None, 'SKIP: %s' % why) + filler = None + try: + os.makedirs(os.path.join(mnt, 'queue')) + os.makedirs(os.path.join(mnt, 'inter')) + conf = t.path(daemon.conf_rel) + with open(conf, 'ab') as f: + f.write(('QueueDir=%s\nInterDir=%s\n' % (os.path.join(mnt, 'queue'), + os.path.join(mnt, 'inter'))).encode()) + daemon.start() + api = daemon.wait_ready() + daemon.append(api, 'RelDF', build_nzb(pp, 'df.bin', size, seg, set()), False, 'df-key', 100) + total = size // seg + history = [] # (time, requests so far) + deadline = time.time() + 120 + while time.time() < deadline: + history.append((time.time(), len(_failcont_requests(t)))) + if history[-1][1] >= total * 4 // 10: + break + time.sleep(0.1) + filler = _DiskFiller(os.path.join(mnt, 'filler')) + fill_time = time.time() + recorded = max([n for when, n in history if when <= fill_time - 4.0] or [0]) + before = _failcont_requests(t)[:recorded] + time.sleep(4) # saves and article writes fail on the full disk + try: + api.shutdown() + except Exception: + pass + stop_rc = t.procs[-1].wait(timeout=120) + save_errors = _grep_log(t, 'Error saving diskstate') + unclean = _grep_log(t, 'Stopping is not clean') + filler.release() + filler = None + restart_at = len(_failcont_requests(t)) + daemon.start() + api = daemon.wait_ready() + h = daemon.wait_history(api, 'RelDF', timeout=240) + after = _failcont_requests(t)[restart_at:] + again = sorted(set(before) & set(after)) + integ = _verify_output(t, data) + discarded = _grep_log(t, 'Discarding damaged download state') + ok = (h['Status'].startswith('SUCCESS') and integ and recorded > 0 and not again + and save_errors > 0 and stop_rc == 1 and unclean > 0) + return ('diskfullrestart', ok, + 'status=%s integrity=%s recorded_before_fill=%d fetched_again=%d of them ' + 'fetched_after_restart=%d save_errors=%d stop_rc=%s unclean_logs=%d discarded_states=%d' + % (h['Status'], integ, recorded, len(again), len(after), save_errors, stop_rc, + unclean, discarded)) + finally: + if filler: + filler.release() + for p in t.procs: + if p.poll() is None: + p.kill() + p.wait(timeout=30) + if subprocess.run(umount, capture_output=True).returncode != 0: + # Busy: detach it lazily, so the work dir cleanup never reaches into it. + lazy = umount[:-1] + ['-l', umount[-1]] if umount[0] == 'sudo' else umount + rc = subprocess.run(lazy, capture_output=True).returncode + print(' diskfullrestart: unmount of %s failed, lazy unmount rc=%d' % (mnt, rc)) + + def scenario_streamtimeout(daemon, t): """DupeStreamTimeout: the only duplicate is stalled (every request for its articles waits 8 s, longer than the timeout), so the repair of the @@ -15518,6 +15671,7 @@ def scenario_dupausedunpack(daemon, t): 'stream': scenario_stream, 'truncatedstate': scenario_truncatedstate, 'queuesyncslow': scenario_queuesyncslow, + 'diskfullrestart': scenario_diskfullrestart, 'queuebatchstart': scenario_queuebatchstart, 'streamrestartcredit': scenario_streamrestartcredit, 'streamtimeout': scenario_streamtimeout, @@ -16016,6 +16170,7 @@ def scenario_dupausedunpack(daemon, t): 'stream': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'truncatedstate': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=1'], 'queuesyncslow': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=6'], + 'diskfullrestart': ['ContinuePartial=yes', 'FlushQueue=yes', 'DiskSpace=0', 'Server1.Connections=4'], 'queuebatchstart': ['Server1.Connections=30'], 'streamrestartcredit': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'streamdeaddonor': ['DupeArticleFallback=stream', 'ParCheck=auto'], @@ -16439,10 +16594,10 @@ def _promote_fallback(options, mode): # finished job is rightly not redone FALLBACK_MODE_BOUND = {'livegate', 'streamrestartcredit', 'wholefilerestart', 'wholefilestale'} # scenarios that read nserv's request log (nserv.log) -CAPTURE_REQUESTS = {'repost', 'altfetchonce', 'wholefileproofcost', 'dropnzbdir', 'fleetstaysqueued', 'fleetprimaryfirst'} | { +CAPTURE_REQUESTS = {'repost', 'diskfullrestart', 'altfetchonce', 'wholefileproofcost', 'dropnzbdir', 'fleetstaysqueued', 'fleetprimaryfirst'} | { 'failcont_twin25', 'failcont_twin50', 'failcont_twin90', 'failcont_alt25', 'failcont_alt50', 'failcont_altlive', 'failcont_alt90', 'failcont_aes25', 'failcont_aes50', 'failcont_aes90', 'failcont_compressed', 'failcont_othervideo', 'failcont_twinlabel', 'failcont_fleettwin', 'failcont_fleetalt', 'failcont_fleetaes', 'failcont_aestwin', 'failcont_aesalt', 'failcont_rar5m3', 'failcont_rar5m3aes', 'failcont_rar5m3other', 'failcont_lzma2', 'failcont_norestart', 'weakswitchalt', 'weakswitchtwin', 'weakswitchaes', 'weakswitchm3', 'failcont_aescontainer', 'failcont_alt25busy'} # extra nserv arguments per scenario (-w: response latency in ms) -SCENARIO_NSERV_ARGS = {'streamtimeoutwrites': ['-w', '800'], 'fleetslowprobe': ['-x', '2000'], 'fleetprobespeed': ['-w', '300'], 'fleetprobebusy': ['-w', '300'], 'fleetprobehealthfail': ['-w', '800'], 'finaldeletemidway': ['-w', '300'], 'finaldeleterestart': ['-w', '300'], 'restartmidway': ['-w', '300'], 'xpacklatency': ['-w', '1000'], 'deadpickprobe': ['-w', '500'], 'deadpickafterreload': ['-w', '500'], +SCENARIO_NSERV_ARGS = {'diskfullrestart': ['-w', '300'], 'streamtimeoutwrites': ['-w', '800'], 'fleetslowprobe': ['-x', '2000'], 'fleetprobespeed': ['-w', '300'], 'fleetprobebusy': ['-w', '300'], 'fleetprobehealthfail': ['-w', '800'], 'finaldeletemidway': ['-w', '300'], 'finaldeleterestart': ['-w', '300'], 'restartmidway': ['-w', '300'], 'xpacklatency': ['-w', '1000'], 'deadpickprobe': ['-w', '500'], 'deadpickafterreload': ['-w', '500'], 'deadpickpartial': ['-w', '100'], 'deadpickstray': ['-w', '500'], 'forcefailover': ['-w', '500'], 'copybackup': ['-w', '500'], 'copyoffailed': ['-w', '500'], 'deaddownloadstray2': ['-w', '300'], 'deaddownloadrestart': ['-w', '300'], 'deadbackupsonly': ['-w', '500'], 'backuporder': ['-w', '500'], 'deaddownloadlate': ['-w', '300'], 'deadpickservers': ['-w', '200'], 'deadpickfewservers': ['-w', '200'], # a missing article answers late, so the dead volumes fail one after another and later