pidfile-rs-0.1.0/.cargo_vcs_info.json0000644000000001121374777224400131410ustar { "git": { "sha1": "1a2462ff71b8b5cb000408be8330dff067913313" } } pidfile-rs-0.1.0/.gitignore010066400017500001750000000000231374752336000137260ustar 00000000000000/target Cargo.lock pidfile-rs-0.1.0/Cargo.toml0000644000000020311374777224400111410ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "pidfile-rs" version = "0.1.0" authors = ["Andrej Shadura "] description = "Rust wrapper for pidfile_* functions from libbsd/libutil" license = "MIT" repository = "https://github.com/andrewshadura/bsd-pidfile-rs" [dependencies.libc] version = "0.2" [dependencies.log] version = "0.4" [dependencies.thiserror] version = "1.0" [dev-dependencies.nix] version = "0.19" [dev-dependencies.tempfile] version = "3" [build-dependencies.pkg-config] version = "0.3" pidfile-rs-0.1.0/Cargo.toml.orig010066400017500001750000000006531374776375600146550ustar 00000000000000[package] name = "pidfile-rs" version = "0.1.0" authors = ["Andrej Shadura "] edition = "2018" description = "Rust wrapper for pidfile_* functions from libbsd/libutil" license = "MIT" repository = "https://github.com/andrewshadura/bsd-pidfile-rs" [dependencies] libc = "0.2" thiserror = "1.0" log = "0.4" [build-dependencies] pkg-config = "0.3" [dev-dependencies] tempfile = "3" nix = "0.19" pidfile-rs-0.1.0/LICENSE-MIT010066400017500001750000000017771374777164700134300ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pidfile-rs-0.1.0/README.md010066400017500001750000000024761374777165000132420ustar 00000000000000BSD pidfile for Rust ==================== This crate provides a wrapper for a family of [`pidfile_*` functions][pidfile] provided in the BSD systems by [libutil][], and elsewhere by [libbsd][]. Known alternatives in pure Rust: * [pidfile](https://crates.io/crates/pidfile) by Carl Lerche, very advanced, but last updated in 2014 and now longer compiles with modern Rust. * [pidlock](https://crates.io/crates/pidlock) by Paul Hummer provides a lock-like API, but doesn’t actually use filesystem locks. * [qpidfile](https://crates.io/crates/qpidfile) by Jan Danielsson, well-maintained, but very basic. The BSD pidfile functions employ very clever locking mechanism, detect concurrently running daemons and allow deferring writes to the PID file, so potential errors can be handled before a fork. The ultimate goal is to rewrite these functions in Rust, but until a rewrite is done, it’s best to use the BSD functions using the FFI. [libutil]: https://man.netbsd.org/libutil.3 [libbsd]: https://libbsd.freedesktop.org/ [pidfile]: https://linux.die.net/man/3/pidfile License ------- [MIT license](LICENSE-MIT), also known as the Expat license. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be licensed as above, without any additional terms or conditions. pidfile-rs-0.1.0/build.rs010066400017500001750000000002551372566433500134160ustar 00000000000000fn main() { if pkg_config::Config::new().probe("libbsd").is_ok() { println!("cargo:rustc-cfg=pidfile"); } println!("cargo:rerun-if-changed=build.rs"); } pidfile-rs-0.1.0/src/lib.rs010066400017500001750000000241431374777164700136670ustar 00000000000000// Copyright (C) 2020 Andrej Shadura // SPDX-License-Identifier: MIT use std::ffi::{CString, NulError}; use std::fs::Permissions; use std::io; use std::os::unix::{ffi::OsStringExt, fs::PermissionsExt}; use std::path::PathBuf; use libc::{c_char, c_int, mode_t, pid_t}; use log::warn; use thiserror::Error; #[allow(non_camel_case_types)] enum pidfn {} extern { #[link_name = "pidfile_open"] fn bsd_pidfile_open(path: *const c_char, mode: mode_t, pidptr: *mut pid_t) -> *mut pidfn; #[link_name = "pidfile_write"] fn bsd_pidfile_write(pfh: *mut pidfn) -> c_int; #[link_name = "pidfile_close"] fn bsd_pidfile_close(pfh: *mut pidfn) -> c_int; #[link_name = "pidfile_remove"] fn bsd_pidfile_remove(pfh: *mut pidfn) -> c_int; #[allow(dead_code)] #[link_name = "pidfile_fileno"] fn bsd_pidfile_fileno(pfh: *mut pidfn) -> c_int; } /// A PID file protected with a lock. /// /// An instance of `Pidfile` can be used to manage a PID file: create it, /// lock it, detect already running daemons. It is backed by [`pidfile`][] /// functions of `libbsd`/`libutil` which use `flopen` to lock the PID /// file. /// /// When a PID file is created, the process ID of the current process is /// *not* written there, making it possible to lock the PID file before /// forking and only write the ID of the forked process when it is ready. /// /// The PID file is deleted automatically when the `Pidfile` comes out of /// the scope. To close the PID file without deleting it, for example, in /// the parent process of a forked daemon, call `close()`. /// /// # Example /// /// When the parent process exits without calling destructors, e.g. by /// using [`exit`][] or when forking with [`daemon`(3)], `Pidfile` can /// be used in the following way: /// ```rust /// # use std::error::Error; /// # use std::fs::Permissions; /// # use std::os::unix::fs::PermissionsExt; /// # use tempfile::tempdir; /// // This example uses daemon(3) wrapped by nix to daemonise: /// use nix::unistd::daemon; /// use pidfile_rs::Pidfile; /// /// // ... /// /// # let dir = tempdir()?; /// # let mut pidfile_path = dir.path().to_owned(); /// # pidfile_path.push("file.pid"); /// # println!("pidfile_path = {:?}", pidfile_path); /// let pidfile = Some(Pidfile::new( /// &pidfile_path, /// Permissions::from_mode(0o600) /// )?); /// /// // do some pre-fork preparations /// // ... /// /// // in the parent process, the PID file is closed without deleting it /// daemon(false, true)?; /// /// pidfile.unwrap().write(); /// /// // do some work /// println!("The daemon’s work is done, now it’s time to go home."); /// /// // the PID file will be deleted when this function returns /// /// # Ok::<(), Box>(()) /// ``` /// /// [`exit`]: https://doc.rust-lang.org/std/process/fn.exit.html /// [`pidfile`]: https://linux.die.net/man/3/pidfile /// [`daemon`(3)]: https://linux.die.net/man/3/daemon #[derive(Debug)] pub struct Pidfile { pidfn: *mut pidfn } #[derive(Error, Debug)] pub enum PidfileError { /// The file cannot be locked. The `pid` field contains the PID of the /// already running process or `None` in case it did not write /// its PID yet. #[error("daemon already running with {}", match .pid { Some(pid) => format!("PID {}", pid), None => "unknown PID".into() })] AlreadyRunning { pid: Option }, /// An I/O error has occurred. #[error(transparent)] Io(#[from] io::Error), /// An interior NUL byte was found in the path. #[error(transparent)] NulError(#[from] NulError), } impl Pidfile { /// Creates a new PID file and locks it. /// /// If the PID file cannot be locked, returns `PidfileError::AlreadyRunning` with /// a PID of the already running process, or `None` if no PID has been written to /// the PID file yet. pub fn new(path: &PathBuf, permissions: Permissions) -> Result { match CString::new(path.clone().into_os_string().into_vec()) { Ok(c_path) => { let mut old_pid: pid_t = -1; let pidfn = unsafe { bsd_pidfile_open(c_path.as_ptr(), permissions.mode(), &mut old_pid) }; if !pidfn.is_null() { return Ok(Pidfile { pidfn: pidfn }); } else { let err = io::Error::last_os_error(); if err.kind() == io::ErrorKind::AlreadyExists { return Err(PidfileError::AlreadyRunning { pid: if old_pid != -1 { Some(old_pid) } else { None } }); } else { Err(PidfileError::Io(err)) } } }, Err(err) => { Err(PidfileError::NulError(err)) } } } /// Writes the current process ID to the PID file. /// /// The file is truncated before writing. pub fn write(&self) -> Result<(), PidfileError> { if unsafe { bsd_pidfile_write(self.pidfn) == 0 } { Ok(()) } else { Err(PidfileError::Io(io::Error::last_os_error())) } } /// Closes the PID file without removing it. /// /// This function consumes the object, making it impossible /// to manipulated with the PID file after this function has /// been called. pub fn close(self) { if unsafe { bsd_pidfile_close(self.pidfn) != 0 } { let err = io::Error::last_os_error(); warn!("Failed to close the PID file: {}", err); } } } impl Drop for Pidfile { /// Closes the PID file and removes it. fn drop(&mut self) { if unsafe { bsd_pidfile_remove(self.pidfn) != 0 } { let err = io::Error::last_os_error(); warn!("Failed to remove the PID file: {}", err); } } } #[cfg(test)] mod tests { use crate::*; use std::fs::{Permissions, read_to_string}; use std::io; use std::os::unix::fs::PermissionsExt; use std::process; use tempfile::tempdir; #[test] fn create_file() { let dir = tempdir().unwrap(); let mut pidfile_path = dir.path().to_owned(); pidfile_path.push("file.pid"); let my_pid = process::id().to_string(); { let pidfile = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect("Failed to create PID file"); println!("pidfile_path = {:?}", pidfile_path); assert_eq!(pidfile_path.is_file(), true); pidfile.write().expect("Failed to write PID file"); let contents = read_to_string(pidfile_path.as_path()).expect("Can’t read PID file"); assert_eq!(my_pid, contents); } assert_eq!( pidfile_path.is_file(), false, "PID file should have disappeared" ); } #[test] fn close_file() { let dir = tempdir().unwrap(); let mut pidfile_path = dir.path().to_owned(); pidfile_path.push("file.pid"); let my_pid = process::id().to_string(); { let pidfile = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect("Failed to create PID file"); println!("pidfile_path = {:?}", pidfile_path); assert_eq!(pidfile_path.is_file(), true); pidfile.write().expect("Failed to write PID file"); let contents = read_to_string(pidfile_path.as_path()).expect("Can’t read PID file"); assert_eq!(my_pid, contents); pidfile.close(); } assert_eq!( pidfile_path.is_file(), true, "PID file should have not disappeared" ); } #[test] fn invalid_path() { let dir = tempdir().unwrap(); let mut pidfile_path = dir.path().to_owned(); pidfile_path.push("<>"); pidfile_path.push("file.pid"); let error = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect_err("PID file shouldn’t exist, but it does"); println!("pidfile_path = {:?}", pidfile_path); assert_eq!(pidfile_path.is_file(), false); if let PidfileError::Io(error) = error { assert_eq!(error.kind(), io::ErrorKind::NotFound); } else { panic!("unexpected error: {:?}", error) } pidfile_path.push("\0"); let error = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect_err("NULs should not have been accepted, but they were"); if let PidfileError::NulError(error) = error { println!("expected error: {}", error); } else { panic!("unexpected error: {:?}", error) } } #[test] fn concurrent() { let dir = tempdir().unwrap(); let mut pidfile_path = dir.path().to_owned(); pidfile_path.push("file.pid"); let my_pid = process::id().to_string(); let pidfile = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect("Failed to create PID file"); println!("pidfile_path = {:?}", pidfile_path); assert_eq!(pidfile_path.is_file(), true, "PID file not created?"); pidfile.write().expect("Failed to write PID file"); let contents = read_to_string(pidfile_path.as_path()).expect("Can’t read PID file"); assert_eq!(my_pid, contents); let error = Pidfile::new(&pidfile_path, Permissions::from_mode(0o600)) .expect_err("Expected error, but got"); assert_eq!( error.to_string(), format!("daemon already running with PID {}", my_pid) ); if let PidfileError::AlreadyRunning { pid } = error { assert_eq!( my_pid, pid.expect("No PID written?").to_string(), "PID different?!" ); } else { panic!("unexpected error: {:?}", error) } } }