1use std::fs::{File, OpenOptions};
7use std::os::fd::AsRawFd;
8use std::os::unix::fs::OpenOptionsExt;
9use std::path::Path;
10use std::{fmt, io};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Sharing {
15 Serve,
19 Alone,
21 Beside,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Work {
28 Serve,
29 TenantCreate,
30 TenantList,
31 TenantSetRetention,
32 TenantRemove,
33 TenantSetMetadata,
34 TenantSetRoleCap,
35 TenantRoleCap,
36 ExportParquet,
37 KeyCreate,
38 KeyList,
39 KeyRevoke,
40 UserAdd,
41 UserList,
42 UserDeactivate,
43 MembershipGrant,
44 MembershipRevoke,
45 RekeyTenant,
46 RekeyMaster,
47 AuditExport,
48 Check,
49 Backup,
50 StorageMoveObjects,
51}
52
53impl Work {
54 pub fn sharing(self) -> Sharing {
56 match self {
57 Work::Serve => Sharing::Serve,
58 Work::TenantCreate
59 | Work::TenantRemove
60 | Work::RekeyTenant
61 | Work::RekeyMaster
62 | Work::Check
63 | Work::StorageMoveObjects => Sharing::Alone,
64 Work::TenantList
65 | Work::TenantSetRetention
66 | Work::KeyCreate
67 | Work::KeyList
68 | Work::KeyRevoke
69 | Work::UserAdd
70 | Work::UserList
71 | Work::UserDeactivate
72 | Work::MembershipGrant
73 | Work::MembershipRevoke
74 | Work::AuditExport
75 | Work::Backup
76 | Work::TenantSetMetadata
77 | Work::TenantSetRoleCap
78 | Work::TenantRoleCap
79 | Work::ExportParquet => Sharing::Beside,
80 }
81 }
82}
83
84#[derive(Debug)]
87pub struct DataDirLock {
88 _held: Vec<File>,
89}
90
91#[derive(Debug)]
93pub enum LockError {
94 InUse(Sharing),
96 Io(io::Error),
98}
99
100impl fmt::Display for LockError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 match self {
103 LockError::InUse(Sharing::Serve) => f.write_str(
104 "the data directory is in use by another vcon-server or a command that runs alone",
105 ),
106 LockError::InUse(Sharing::Alone) => f.write_str(
107 "the data directory is in use; stop the server and any other command first",
108 ),
109 LockError::InUse(Sharing::Beside) => {
110 f.write_str("the data directory is in use by a command that runs alone")
111 }
112 LockError::Io(e) => write!(f, "the data directory cannot be locked: {e}"),
113 }
114 }
115}
116
117pub fn lock(dir: &Path, sharing: Sharing) -> Result<DataDirLock, LockError> {
124 let take = |name: &str, how| {
125 flock(&dir.join(name), how).map_err(|e| match e.kind() {
126 io::ErrorKind::WouldBlock => LockError::InUse(sharing),
127 _ => LockError::Io(e),
128 })
129 };
130 let held = match sharing {
131 Sharing::Serve => vec![take(SERVERS, libc::LOCK_EX)?],
132 Sharing::Alone => vec![
133 take(SERVERS, libc::LOCK_EX)?,
134 take(COMMANDS, libc::LOCK_EX)?,
135 ],
136 Sharing::Beside => vec![take(COMMANDS, libc::LOCK_SH)?],
137 };
138 Ok(DataDirLock { _held: held })
139}
140
141const SERVERS: &str = "lock";
142const COMMANDS: &str = "lock.commands";
143
144fn flock(path: &Path, how: libc::c_int) -> io::Result<File> {
146 let file = OpenOptions::new()
147 .create(true)
148 .truncate(false)
149 .write(true)
150 .mode(crate::fs::FILE_MODE)
151 .open(path)?;
152 if unsafe { libc::flock(file.as_raw_fd(), how | libc::LOCK_NB) } != 0 {
155 return Err(io::Error::last_os_error());
156 }
157 Ok(file)
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
170 fn every_kind_of_work_shares_the_directory_as_documented() {
171 let documented = |work: Work| match work {
172 Work::Serve => Sharing::Serve,
173 Work::TenantCreate => Sharing::Alone,
174 Work::TenantList => Sharing::Beside,
175 Work::TenantSetRetention => Sharing::Beside,
176 Work::TenantRemove => Sharing::Alone,
177 Work::KeyCreate => Sharing::Beside,
178 Work::KeyList => Sharing::Beside,
179 Work::KeyRevoke => Sharing::Beside,
180 Work::UserAdd => Sharing::Beside,
181 Work::UserList => Sharing::Beside,
182 Work::UserDeactivate => Sharing::Beside,
183 Work::MembershipGrant => Sharing::Beside,
184 Work::MembershipRevoke => Sharing::Beside,
185 Work::RekeyTenant => Sharing::Alone,
186 Work::RekeyMaster => Sharing::Alone,
187 Work::AuditExport => Sharing::Beside,
188 Work::Check => Sharing::Alone,
189 Work::Backup => Sharing::Beside,
190 Work::TenantSetMetadata => Sharing::Beside,
191 Work::TenantSetRoleCap => Sharing::Beside,
192 Work::TenantRoleCap => Sharing::Beside,
193 Work::ExportParquet => Sharing::Beside,
194 Work::StorageMoveObjects => Sharing::Alone,
195 };
196 for work in [
197 Work::Serve,
198 Work::TenantCreate,
199 Work::TenantList,
200 Work::TenantSetRetention,
201 Work::TenantRemove,
202 Work::KeyCreate,
203 Work::KeyList,
204 Work::KeyRevoke,
205 Work::UserAdd,
206 Work::UserList,
207 Work::UserDeactivate,
208 Work::MembershipGrant,
209 Work::MembershipRevoke,
210 Work::RekeyTenant,
211 Work::RekeyMaster,
212 Work::AuditExport,
213 Work::Check,
214 Work::Backup,
215 Work::TenantSetMetadata,
216 Work::TenantSetRoleCap,
217 Work::TenantRoleCap,
218 Work::ExportParquet,
219 Work::StorageMoveObjects,
220 ] {
221 assert_eq!(work.sharing(), documented(work), "{work:?}");
222 }
223 }
224
225 #[test]
228 fn who_may_run_beside_whom() {
229 use Sharing::{Alone, Beside, Serve};
230 for (first, second, allowed) in [
231 (Serve, Serve, false),
232 (Serve, Alone, false),
233 (Serve, Beside, true),
234 (Alone, Serve, false),
235 (Alone, Alone, false),
236 (Alone, Beside, false),
237 (Beside, Serve, true),
238 (Beside, Alone, false),
239 (Beside, Beside, true),
240 ] {
241 let dir = tempfile::tempdir().expect("temp dir");
242 let held = lock(dir.path(), first).expect("the first lock");
243 match lock(dir.path(), second) {
244 Ok(_) => assert!(allowed, "{second:?} beside {first:?}"),
245 Err(LockError::InUse(asked)) => {
246 assert!(!allowed, "{second:?} refused beside {first:?}");
247 assert_eq!(asked, second);
248 }
249 Err(e) => panic!("{first:?} then {second:?}: {e}"),
250 }
251 drop(held);
252 assert!(lock(dir.path(), second).is_ok(), "{second:?} once free");
253 }
254 }
255
256 #[test]
259 fn a_refused_lock_holds_nothing() {
260 let dir = tempfile::tempdir().expect("temp dir");
261 let beside = lock(dir.path(), Sharing::Beside).expect("beside");
262 assert!(lock(dir.path(), Sharing::Alone).is_err());
263 let server = lock(dir.path(), Sharing::Serve).expect("serve beside");
264 drop((beside, server));
265 assert!(lock(dir.path(), Sharing::Alone).is_ok());
266 }
267
268 #[test]
269 fn each_refusal_says_what_holds_the_directory() {
270 for (sharing, words) in [
271 (Sharing::Serve, "another vcon-server or a command"),
272 (Sharing::Alone, "stop the server"),
273 (Sharing::Beside, "runs alone"),
274 ] {
275 let text = LockError::InUse(sharing).to_string();
276 assert!(text.contains(words), "{sharing:?}: {text}");
277 }
278 }
279
280 #[test]
281 fn a_data_directory_that_cannot_hold_a_lock_file_is_an_error() {
282 let missing = Path::new("/nonexistent/vcon-server-data");
283 for sharing in [Sharing::Serve, Sharing::Alone, Sharing::Beside] {
284 assert!(matches!(lock(missing, sharing), Err(LockError::Io(_))));
285 }
286 }
287}