Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup stale lock files in the .lsp-locks directory #6816

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
67 changes: 65 additions & 2 deletions forc-util/src/fs_locking.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{hash_path, user_forc_directory};
use std::{
fs::{create_dir_all, remove_file, File},
fs::{create_dir_all, read_dir, remove_file, File},
io::{self, Read, Write},
path::{Path, PathBuf},
};
Expand All @@ -19,6 +19,9 @@ impl PidFileLocking {
dir: Y,
extension: &str,
) -> PidFileLocking {
// Try to cleanup stale files, ignore any errors as this is best-effort
let _ = Self::cleanup_stale_files();

let file_name = hash_path(filename);
Self(
user_forc_directory()
Expand Down Expand Up @@ -136,11 +139,43 @@ impl PidFileLocking {
fs.flush()?;
Ok(())
}

/// Cleans up all stale lock files in the .lsp-locks directory
/// Returns a vector of paths that were cleaned up
Comment on lines +143 to +144
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit:

Suggested change
/// Cleans up all stale lock files in the .lsp-locks directory
/// Returns a vector of paths that were cleaned up
/// Cleans up stale lock files in the .lsp-locks directory.
/// A lock file is considered stale if:
/// - It has a .lock extension
/// - Either its contents cannot be parsed as a valid PID
/// - Or the PID it contains is no longer active
///
/// Returns paths of the lock files that were removed.

pub fn cleanup_stale_files() -> io::Result<Vec<PathBuf>> {
let lock_dir = user_forc_directory().join(".lsp-locks");
let entries = read_dir(&lock_dir)?;
let mut cleaned_paths = Vec::new();

for entry in entries {
let entry = entry?;
let path = entry.path();
if let Some(ext) = path.extension().and_then(|ext| ext.to_str()) {
if ext == "lock" {
if let Ok(mut file) = File::open(&path) {
let mut contents = String::new();
if file.read_to_string(&mut contents).is_ok() {
if let Ok(pid) = contents.trim().parse::<usize>() {
if !Self::is_pid_active(pid) {
Copy link
Contributor

@alfiedotwtf alfiedotwtf Jan 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've stopped using PID files because I've been burned by this before - the call to is_pid_active() can still return true on servers with long uptimes that are burning through processes, causing PIDs to wrap. On some systems the PID space is as small as 32768 but on my beast it's:

> cat /proc/sys/kernel/pid_max 
4194304

Instead, I now use advisory locking (the following is code from forc-telemetry), which also has the nice advantage in that it's shorter code as you don't need to read the file:

self.logfile_lock = match Flock::lock(logfile, FlockArg::LockExclusiveNonblock) {
        Ok(logfile_lock) => Some(logfile_lock),
        Err((_, Errno::EWOULDBLOCK)) => {
            // Silently exit as another Collector is already running
            exit(0);
        }
}

remove_file(&path)?;
cleaned_paths.push(path);
}
} else {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the else should do clean up as there's a race condition - the other process could be in the middle of writing it's PID into the lockfile itself 😅

remove_file(&path)?;
cleaned_paths.push(path);
}
}
}
}
}
Comment on lines +153 to +170
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: reduced nesting

Suggested change
if let Some(ext) = path.extension().and_then(|ext| ext.to_str()) {
if ext == "lock" {
if let Ok(mut file) = File::open(&path) {
let mut contents = String::new();
if file.read_to_string(&mut contents).is_ok() {
if let Ok(pid) = contents.trim().parse::<usize>() {
if !Self::is_pid_active(pid) {
remove_file(&path)?;
cleaned_paths.push(path);
}
} else {
remove_file(&path)?;
cleaned_paths.push(path);
}
}
}
}
}
// Skip non-lock files
if path.extension()
.and_then(|ext| ext.to_str())
.map_or(false, |ext| ext == "lock")
{
let contents = match fs::read_to_string(&path) {
Ok(content) => content,
Err(_) => continue,
};
let should_remove = contents.trim()
.parse::<usize>()
.map_or(true, |pid| !Self::is_pid_active(pid));
if should_remove {
remove_file(&path)?;
cleaned_paths.push(path);
}
}

}
Ok(cleaned_paths)
}
}

#[cfg(test)]
mod test {
use super::PidFileLocking;
use super::{user_forc_directory, PidFileLocking};
use std::{
fs::{metadata, File},
io::{ErrorKind, Write},
Expand Down Expand Up @@ -201,4 +236,32 @@ mod test {
let e = metadata(&x.0).unwrap_err().kind();
assert_eq!(e, ErrorKind::NotFound);
}

#[test]
fn test_cleanup_stale_files() {
// First create some test files
let test_lock = PidFileLocking::lsp("test_cleanup");
test_lock.lock().expect("Failed to create test lock file");

// Create a test lock file with invalid PID
let lock_path = user_forc_directory()
.join(".lsp-locks")
.join("test_cleanup.lock");
File::create(&lock_path).expect("Failed to create test lock file");

// Run cleanup and check returned paths
let cleaned_paths =
PidFileLocking::cleanup_stale_files().expect("Failed to cleanup stale files");

// Verify that only the invalid lock file was cleaned up
assert_eq!(cleaned_paths.len(), 1);
assert_eq!(cleaned_paths[0], lock_path);

// Verify file system state
assert!(test_lock.0.exists(), "Active lock file should still exist");
assert!(!lock_path.exists(), "Lock file should be removed");

// Cleanup after test
test_lock.release().expect("Failed to release test lock");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: not a biggie, maybe we should use tempfile to ensure file/dir cleanup (automatically done when var goes out of scope - even if a test fails mid-way)

}
}
Loading