public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH proxmox v3 3/3] rest-server: clamp old task log cleanup cutoff to earliest active task
Date: Fri, 27 Nov 2026 17:10:54 +0100	[thread overview]
Message-ID: <20261127161054.401599-4-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261127161054.401599-1-c.ebner@proxmox.com>

Determining the cutoff timestamp for old task log cleanup previously
only inspected the oldest entry in the task archive, which only tracks
finished tasks. Still running tasks are listed exclusively in the
active tasks file without an end time.

If a long-running task started before the calculated archive cutoff
time and has not written any new log lines since then, its log file's
mtime is older than the cutoff time and cleanup_old_tasks() would
remove the log file while the task is still active.

Prevent this by also reading the active task list while holding the
shared task list lock during cutoff time gathering and clamping the
cutoff timestamp to the earliest active task's start time and the
current time.

Additionally, subtract a safety margin of twice the lock timeout from
the cutoff, which protects from two races with task creation:
- File timestamp granularity for mtime, SystemTime not being
  monotonic and only using seconds precision may result in a task
  log's mtime being older than the task's start time.
- A new task's log file is created before the task is inserted into
  the active task list, which can wait up to the lock timeout if the
  cutoff calculation acquired the lock first.

The margin is a heuristic only to avoid extending the lock scope on
task creation. It assumes that a new task is registered within at
least twice the lock timeout after creating its log file.

Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
 proxmox-rest-server/src/worker_task.rs | 40 ++++++++++++++++++++------
 1 file changed, 32 insertions(+), 8 deletions(-)

diff --git a/proxmox-rest-server/src/worker_task.rs b/proxmox-rest-server/src/worker_task.rs
index 1d03a8f4..843ce899 100644
--- a/proxmox-rest-server/src/worker_task.rs
+++ b/proxmox-rest-server/src/worker_task.rs
@@ -28,6 +28,9 @@ use proxmox_worker_task::WorkerTaskContext;
 static LAST_WORKER_LISTENERS: OnceLock<watch::Sender<bool>> = OnceLock::new();
 static WORKER_COUNT: AtomicUsize = AtomicUsize::new(0);
 static INTERNAL_TASK_COUNT: AtomicUsize = AtomicUsize::new(0);
+const LOCK_TIMEOUT: Duration = Duration::from_secs(15);
+// Safety margin in seconds subtracted from the old task log cleanup cutoff time.
+const TASK_LOG_CUTOFF_MARGIN: i64 = 2 * LOCK_TIMEOUT.as_secs() as i64;
 
 fn last_worker_listeners() -> &'static watch::Sender<bool> {
     LAST_WORKER_LISTENERS.get_or_init(|| watch::channel(false).0)
@@ -130,10 +133,12 @@ impl WorkerTaskSetup {
             .file_opts
             .perm(nix::sys::stat::Mode::from_bits_truncate(0o660));
 
-        let timeout = std::time::Duration::new(15, 0);
-
-        let file =
-            proxmox_sys::fs::open_file_locked(&self.task_lock_fn, timeout, exclusive, options)?;
+        let file = proxmox_sys::fs::open_file_locked(
+            &self.task_lock_fn,
+            LOCK_TIMEOUT,
+            exclusive,
+            options,
+        )?;
 
         Ok(TaskListLockGuard(file))
     }
@@ -263,8 +268,9 @@ impl WorkerTaskSetup {
         .map_err(|err: Error| format_err!("unable to create task log dir - {}", err))
     }
 
-    /// Identify the oldest finished task entry's timestamp by iterating the task
-    /// archive and return the calculated cutoff time.
+    /// Identify the oldest finished task entry's timestamp by iterating the task archive, clamp it
+    /// to the earliest active task's start time and the current time, and return the resulting
+    /// cutoff time minus a safety margin of twice the lock timeout.
     ///
     /// Note: acquired a shared lock on [`WorkerTaskSetup::task_lock_fn`].
     fn oldest_task_cutoff_time(&self, compressed: bool) -> Result<Option<SystemTime>, Error> {
@@ -273,11 +279,29 @@ impl WorkerTaskSetup {
         let logrotate = LogRotate::new(&self.task_archive_fn, compressed, None, None)?;
 
         if let Some(last_file) = logrotate.files().last() {
+            let oldest_active = read_task_file_from_path(&self.active_tasks_fn)?
+                .into_iter()
+                .map(|info| info.upid.starttime)
+                .min();
+
             let reader = BufReader::new(last_file);
             for line in reader.lines() {
                 let line = line?;
                 if let Ok((_, _, Some(state))) = parse_worker_status_line(&line) {
-                    let timestamp = state.endtime();
+                    let mut timestamp = state.endtime().min(proxmox_time::epoch_i64());
+
+                    if let Some(oldest_active) = oldest_active {
+                        timestamp = timestamp.min(oldest_active);
+                    }
+
+                    // The margin covers two races with task creation:
+                    // - a task log's mtime can be slightly older than the task's start time, as
+                    //   file timestamps come from the coarse kernel clock and start times are
+                    //   truncated to seconds.
+                    // - a new task's log file is created before the task is inserted into the
+                    //   active task list, which can wait up to the lock timeout if this method
+                    //   acquired the lock first.
+                    let timestamp = timestamp.saturating_sub(TASK_LOG_CUTOFF_MARGIN);
 
                     let cutoff_time = if timestamp > 0 {
                         SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(timestamp as u64))
@@ -385,7 +409,7 @@ pub fn rotate_task_log_archive(
 }
 
 /// removes all task logs that are older than the oldest task entry in the
-/// task archive
+/// task archive and not currently active
 pub fn cleanup_old_tasks(compressed: bool) -> Result<(), Error> {
     let setup = worker_task_setup()?;
 
-- 
2.47.3





      parent reply	other threads:[~2026-11-27 16:11 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-27 16:10 [PATCH proxmox v3 0/3] fix #8341: reduce task list lock contention during old task log cleanup Christian Ebner
2026-11-27 16:10 ` [PATCH proxmox v3 1/3] rest-server: use shared instead of exclusive lock for old task cleanup Christian Ebner
2026-11-27 16:10 ` [PATCH proxmox v3 2/3] fix #8341: rest-server: do not lock task list during old log cleanup Christian Ebner
2026-11-27 16:10 ` Christian Ebner [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261127161054.401599-4-c.ebner@proxmox.com \
    --to=c.ebner@proxmox.com \
    --cc=pbs-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal