1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use std::convert::TryInto;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::{fs, process};

use log::warn;

/// Errors that may occur during the `Pidlock` lifetime.
#[derive(Debug, PartialEq)]
pub enum PidlockError {
    #[doc = "A lock already exists"]
    LockExists,
    #[doc = "An operation was attempted in the wrong state, e.g. releasing before acquiring."]
    InvalidState,
}

/// A result from a Pidlock operation
type PidlockResult = Result<(), PidlockError>;

/// States a Pidlock can be in during its lifetime.
#[derive(Debug, PartialEq)]
enum PidlockState {
    #[doc = "A new pidlock, unacquired"]
    New,
    #[doc = "A lock is acquired"]
    Acquired,
    #[doc = "A lock is released"]
    Released,
}

/// Check whether a process exists, used to determine whether a pid file is stale.
///
/// # Safety
///
/// This function uses unsafe methods to determine process existence. The function
/// itself is private, and the input is validated prior to call.
fn process_exists(pid: i32) -> bool {
    #[cfg(target_os = "windows")]
    unsafe {
        // If GetExitCodeProcess returns STILL_ACTIVE, then the process
        // doesn't have an exit code (...or exited with code 259)
        use windows_sys::Win32::{
            Foundation::{CloseHandle, STILL_ACTIVE},
            System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_INFORMATION},
        };
        let handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid as u32);
        let mut code = 0;
        GetExitCodeProcess(handle, &mut code);
        CloseHandle(handle);
        code == STILL_ACTIVE as u32
    }

    #[cfg(not(target_os = "windows"))]
    unsafe {
        // From the POSIX standard: If sig is 0 (the null signal), error checking
        // is performed but no signal is actually sent. The null signal can be
        // used to check the validity of pid.
        let result = libc::kill(pid, 0);
        result == 0
    }
}

/// A pid-centered lock. A lock is considered "acquired" when a file exists on disk
/// at the path specified, containing the process id of the locking process.
pub struct Pidlock {
    #[doc = "The current process id"]
    pid: u32,
    #[doc = "A path to the lock file"]
    path: PathBuf,
    #[doc = "Current state of the Pidlock"]
    state: PidlockState,
}

impl Pidlock {
    /// Create a new Pidlock at the provided path.
    pub fn new(path: &str) -> Self {
        Pidlock {
            pid: process::id(),
            path: PathBuf::from(path),
            state: PidlockState::New,
        }
    }

    /// Check whether a lock file already exists, and if it does, whether the
    /// specified pid is still a valid process id on the system.
    fn check_stale(&self) {
        self.get_owner();
    }

    /// Acquire a lock.
    pub fn acquire(&mut self) -> PidlockResult {
        match self.state {
            PidlockState::New => {}
            _ => {
                return Err(PidlockError::InvalidState);
            }
        }
        self.check_stale();

        let mut file = match fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(self.path.clone())
        {
            Ok(file) => file,
            Err(_) => {
                return Err(PidlockError::LockExists);
            }
        };
        file.write_all(&format!("{}", self.pid).into_bytes()[..])
            .unwrap();

        self.state = PidlockState::Acquired;
        Ok(())
    }

    /// Returns true when the lock is in an acquired state.
    pub fn locked(&self) -> bool {
        self.state == PidlockState::Acquired
    }

    /// Release the lock.
    pub fn release(&mut self) -> PidlockResult {
        match self.state {
            PidlockState::Acquired => {}
            _ => {
                return Err(PidlockError::InvalidState);
            }
        }

        fs::remove_file(self.path.clone()).unwrap();

        self.state = PidlockState::Released;
        Ok(())
    }

    /// Gets the owner of this lockfile, returning the pid. If the lock file doesn't exist,
    /// or the specified pid is not a valid process id on the system, it clears it.
    pub fn get_owner(&self) -> Option<u32> {
        let mut file = match fs::OpenOptions::new().read(true).open(self.path.clone()) {
            Ok(file) => file,
            Err(_) => {
                return None;
            }
        };

        let mut contents = String::new();
        if file.read_to_string(&mut contents).is_err() {
            warn!(
                "Removing corrupted/invalid pid file at {}",
                self.path.to_str().unwrap()
            );
            fs::remove_file(&self.path).unwrap();
            return None;
        }

        match contents.trim().parse::<i32>() {
            Ok(pid) if process_exists(pid) => {
                Some(pid.try_into().expect("if a pid exists it is a valid u32"))
            }
            Ok(_) => {
                warn!("Removing stale pid file at {}", self.path.to_str().unwrap());
                fs::remove_file(&self.path).unwrap();
                None
            }
            Err(_) => {
                warn!(
                    "Removing corrupted/invalid pid file at {}",
                    self.path.to_str().unwrap()
                );
                fs::remove_file(&self.path).unwrap();
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::io::Write;
    use std::path::PathBuf;

    use rand::distributions::Alphanumeric;
    use rand::{thread_rng, Rng};

    use super::PidlockState;
    use super::{Pidlock, PidlockError};

    // This was removed from the library itself, but retained here
    // to assert backwards compatibility with std::process::id
    fn getpid() -> u32 {
        unsafe { libc::getpid() as u32 }
    }

    fn make_pid_path() -> String {
        let rand_string: String = thread_rng()
            .sample_iter(&Alphanumeric)
            .take(10)
            .map(char::from)
            .collect();
        format!("/tmp/test.{}.pid", rand_string)
    }

    #[test]
    fn test_new() {
        let pid_path = make_pid_path();
        let pidfile = Pidlock::new(&pid_path);

        assert_eq!(pidfile.pid, getpid());
        assert_eq!(pidfile.path, PathBuf::from(pid_path));
        assert_eq!(pidfile.state, PidlockState::New);
    }

    #[test]
    fn test_acquire_and_release() {
        let mut pidfile = Pidlock::new(&make_pid_path());
        pidfile.acquire().unwrap();

        assert_eq!(pidfile.state, PidlockState::Acquired);

        pidfile.release().unwrap();

        assert_eq!(pidfile.state, PidlockState::Released);
    }

    #[test]
    fn test_acquire_lock_exists() {
        let mut orig_pidfile = Pidlock::new(&make_pid_path());
        orig_pidfile.acquire().unwrap();

        let mut pidfile = Pidlock::new(orig_pidfile.path.to_str().unwrap());
        match pidfile.acquire() {
            Err(err) => {
                orig_pidfile.release().unwrap();
                assert_eq!(err, PidlockError::LockExists);
            }
            _ => {
                orig_pidfile.release().unwrap();
                panic!("Test failed");
            }
        }
    }

    #[test]
    fn test_acquire_already_acquired() {
        let mut pidfile = Pidlock::new(&make_pid_path());
        pidfile.acquire().unwrap();
        match pidfile.acquire() {
            Err(err) => {
                pidfile.release().unwrap();
                assert_eq!(err, PidlockError::InvalidState);
            }
            _ => {
                pidfile.release().unwrap();
                panic!("Test failed");
            }
        }
    }

    #[test]
    fn test_release_bad_state() {
        let mut pidfile = Pidlock::new(&make_pid_path());
        match pidfile.release() {
            Err(err) => {
                assert_eq!(err, PidlockError::InvalidState);
            }
            _ => {
                panic!("Test failed");
            }
        }
    }

    #[test]
    fn test_locked() {
        let mut pidfile = Pidlock::new(&make_pid_path());
        pidfile.acquire().unwrap();
        assert!(pidfile.locked());
    }

    #[test]
    fn test_locked_not_locked() {
        let pidfile = Pidlock::new(&make_pid_path());
        assert!(!pidfile.locked());
    }

    #[test]
    fn test_stale_pid() {
        let path = make_pid_path();
        match fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(path.clone())
        {
            Ok(mut file) => {
                file.write_all(&format!("{}", thread_rng().gen::<i32>()).into_bytes()[..])
                    .unwrap();
            }
            Err(_) => {
                panic!("Could not open file for writing");
            }
        };

        let mut pidfile = Pidlock::new(&path);
        pidfile.acquire().unwrap();
        assert_eq!(pidfile.state, PidlockState::Acquired);
    }

    #[test]
    fn test_stale_pid_invalid_contents() {
        let path = make_pid_path();
        let contents: String = thread_rng()
            .sample_iter(&Alphanumeric)
            .take(20)
            .map(char::from)
            .collect();
        match fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(path.clone())
        {
            Ok(mut file) => {
                file.write_all(&contents.into_bytes()).unwrap();
            }
            Err(_) => {
                panic!("Could not open file for writing");
            }
        };

        let mut pidfile = Pidlock::new(&path);
        pidfile.acquire().unwrap();
        assert_eq!(pidfile.state, PidlockState::Acquired);
    }

    #[test]
    fn test_stale_pid_corrupted_contents() {
        let path = make_pid_path();
        match fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(path.clone())
        {
            Ok(mut file) => {
                file.write_all(&rand::thread_rng().gen::<[u8; 32]>())
                    .unwrap();
            }
            Err(_) => {
                panic!("Could not open file for writing");
            }
        };

        let mut pidfile = Pidlock::new(&path);
        pidfile.acquire().unwrap();
        assert_eq!(pidfile.state, PidlockState::Acquired);
    }
}