-
Notifications
You must be signed in to change notification settings - Fork 11
watt: implement single-instance lock mechanism for watt daemon #47
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,7 @@ | ||
| use std::path::PathBuf; | ||
| use std::{ | ||
| env, | ||
| path::PathBuf, | ||
| }; | ||
|
|
||
| use anyhow::Context as _; | ||
| use clap::Parser as _; | ||
|
|
@@ -11,6 +14,8 @@ pub mod fs; | |
|
|
||
| pub mod config; | ||
|
|
||
| pub mod lock; | ||
|
|
||
| #[derive(clap::Parser, Debug)] | ||
| #[command(version, about)] | ||
| pub struct Cli { | ||
|
|
@@ -20,6 +25,11 @@ pub struct Cli { | |
| /// The daemon config path. | ||
| #[arg(long, env = "WATT_CONFIG")] | ||
| config: Option<PathBuf>, | ||
|
|
||
| /// Force running even if another instance is already running. Potentially | ||
| /// destructive. | ||
| #[arg(long)] | ||
| force: bool, | ||
| } | ||
|
|
||
| pub fn main() -> anyhow::Result<()> { | ||
|
|
@@ -38,5 +48,13 @@ pub fn main() -> anyhow::Result<()> { | |
|
|
||
| log::info!("starting watt daemon"); | ||
|
|
||
| let lock_path = env::var("XDG_RUNTIME_DIR") | ||
| .map(|dir| PathBuf::from(dir).join("watt.pid")) | ||
| .unwrap_or_else(|_| PathBuf::from("/run/watt.pid")); | ||
|
|
||
| let _lock = lock::LockFile::acquire(&lock_path, cli.force).context( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. with_context, otherwise you're allocating each time even on no error |
||
| format!("failed to acquire pid lock at {}", lock_path.display()), | ||
| )?; | ||
|
|
||
| system::run_daemon(config) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| use std::{ | ||
| error::Error, | ||
| fmt, | ||
| fs::{ | ||
| self, | ||
| File, | ||
| OpenOptions, | ||
| }, | ||
| io::Write, | ||
| ops, | ||
| path::{ | ||
| Path, | ||
| PathBuf, | ||
| }, | ||
| process, | ||
| }; | ||
|
|
||
| #[cfg(unix)] use nix::fcntl::{ | ||
| Flock, | ||
| FlockArg, | ||
| }; | ||
|
|
||
| #[cfg(not(unix))] | ||
| compile_error!("watt is only supported on Unix-like systems"); | ||
|
|
||
| pub struct LockFile { | ||
| lock: Flock<File>, | ||
| path: PathBuf, | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| pub struct LockFileError { | ||
| pub path: PathBuf, | ||
| pid: u32, | ||
| } | ||
|
|
||
| impl fmt::Display for LockFileError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| if self.pid == 0 { | ||
| write!(f, "failed to acquire lock at {}", self.path.display()) | ||
| } else { | ||
| write!(f, "another watt daemon is running (PID: {})", self.pid) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Error for LockFileError {} | ||
|
|
||
| impl ops::Deref for LockFile { | ||
| type Target = File; | ||
|
|
||
| fn deref(&self) -> &Self::Target { | ||
| &self.lock | ||
| } | ||
| } | ||
|
|
||
| impl ops::DerefMut for LockFile { | ||
| fn deref_mut(&mut self) -> &mut Self::Target { | ||
| &mut self.lock | ||
| } | ||
| } | ||
|
|
||
| impl LockFile { | ||
| pub fn path(&self) -> &Path { | ||
| &self.path | ||
| } | ||
|
|
||
| pub fn acquire( | ||
| lock_path: &Path, | ||
| force: bool, | ||
| ) -> Result<Option<Self>, LockFileError> { | ||
| let pid = process::id(); | ||
|
|
||
| #[allow(clippy::suspicious_open_options)] | ||
| let file = OpenOptions::new() | ||
| .create(true) | ||
| .read(true) | ||
| .write(true) | ||
| .open(lock_path) | ||
| .map_err(|error| { | ||
| log::error!( | ||
| "failed to open lock file at {}: {}", | ||
| lock_path.display(), | ||
| error | ||
| ); | ||
| LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| } | ||
| })?; | ||
|
|
||
| let mut lock = match Flock::lock(file, FlockArg::LockExclusiveNonblock) { | ||
| Ok(lock) => lock, | ||
| Err((_, nix::errno::Errno::EWOULDBLOCK)) => { | ||
| let Some(existing_pid) = Self::read_pid(lock_path) else { | ||
| if force { | ||
| log::warn!( | ||
| "could not determine PID of existing watt instance, starting \ | ||
| anyway", | ||
| ); | ||
| return Ok(None); | ||
| } | ||
|
|
||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| }); | ||
| }; | ||
|
|
||
| if force { | ||
| log::warn!( | ||
| "another watt instance is running (PID: {existing_pid}), starting \ | ||
| anyway", | ||
| ); | ||
| return Ok(None); | ||
| } | ||
|
|
||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: existing_pid, | ||
| }); | ||
| }, | ||
|
|
||
| Err((_, error)) => { | ||
| log::error!("failed to acquire lock: {}", error); | ||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| }); | ||
| }, | ||
| }; | ||
|
|
||
| if let Err(e) = lock.set_len(0) { | ||
| log::error!("failed to truncate lock file: {}", e); | ||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| }); | ||
| } | ||
|
|
||
| if let Err(e) = lock.write_all(format!("{pid}\n").as_bytes()) { | ||
| log::error!("failed to write PID to lock file: {}", e); | ||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| }); | ||
| } | ||
|
|
||
| if let Err(e) = lock.sync_all() { | ||
| log::error!("failed to sync lock file: {}", e); | ||
| return Err(LockFileError { | ||
| path: lock_path.to_owned(), | ||
| pid: 0, | ||
| }); | ||
| } | ||
|
|
||
| Ok(Some(LockFile { | ||
| lock, | ||
| path: lock_path.to_owned(), | ||
| })) | ||
| } | ||
|
|
||
| fn read_pid(lock_path: &Path) -> Option<u32> { | ||
| match fs::read_to_string(lock_path) { | ||
| Ok(content) => content.trim().parse().ok(), | ||
| Err(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn release(&mut self) { | ||
| let _ = fs::remove_file(&self.path); | ||
| } | ||
| } | ||
|
|
||
| impl Drop for LockFile { | ||
| fn drop(&mut self) { | ||
| self.release(); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not .join("watt.pid") at the end?