summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 68bf4356823696bf00a38bf6436bcac0104cb530 (plain)
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
extern crate libc;

use std::fs;
use std::io::Write;

#[derive(Debug, PartialEq)]
pub enum PidlockError {
    LockExists,
    InvalidState,
}

type PidlockResult = Result<(), PidlockError>;

#[derive(Debug, PartialEq)]
enum PidlockState {
    New,
    Acquired,
    Released,
}

fn getpid() -> u32 {
    unsafe { libc::getpid() as u32 }
}

pub struct Pidlock {
    pid: u32,
    path: String,
    state: PidlockState,
}

impl Pidlock {
    pub fn new(path: &str) -> Self {
        Pidlock {
            pid: getpid(),
            path: path.to_string(),
            state: PidlockState::New,
        }
    }

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

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

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

    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(())
    }
}

#[cfg(test)]
mod tests {
    use super::{Pidlock, PidlockError};
    use super::{getpid, PidlockState};

    const TEST_PID: &str = "/tmp/test.pid";

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

        assert_eq!(pidfile.pid, getpid());
        assert_eq!(pidfile.path, "/tmp/test.pid".to_string());
        assert_eq!(pidfile.state, PidlockState::New);
    }

    #[test]
    fn test_acquire_and_release() {
        let mut pidfile = Pidlock::new(TEST_PID);
        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(TEST_PID);
        orig_pidfile.acquire().unwrap();

        let mut pidfile = Pidlock::new(TEST_PID);
        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(TEST_PID);
        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(TEST_PID);
        match pidfile.release() {
            Err(err) => {
                assert_eq!(err, PidlockError::InvalidState);
            }
            _ => {
                panic!("Test failed");
            }
        }
    }
}