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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::cell::{RefCell, RefMut};
use std::fs::{File, OpenOptions};
use std::io::{self, Result};
use std::mem;
use std::path::{Path, PathBuf};
use fs2::FileExt;
#[cfg(windows)]
use std::os::windows::fs::OpenOptionsExt;
pub struct SdFlock(PathBuf, RefCell<Option<File>>);
type LockFn = fn(&File) -> Result<()>;
impl SdFlock {
pub fn new<P>(p: P) -> SdFlock
where P: AsRef<Path>
{
SdFlock(p.as_ref().to_owned(), RefCell::new(None))
}
pub fn lock_shared(&self) -> Result<()> {
self.lock_finish(self.lock_start(File::lock_shared, false)?)
}
pub fn lock_exclusive(&self) -> Result<()> {
self.lock_finish(self.lock_start(File::lock_exclusive, true)?)
}
pub fn try_lock_shared(&self) -> Result<()> {
self.lock_finish(self.lock_start(File::try_lock_shared, false)?)
}
pub fn try_lock_exclusive(&self) -> Result<()> {
self.lock_finish(self.lock_start(File::try_lock_exclusive, true)?)
}
pub fn unlock(&self) -> Result<()> {
self.1.borrow().as_ref().expect("unlocking unlocked file").unlock()?;
*self.1.borrow_mut() = None;
Ok(())
}
pub fn file(&mut self) -> &mut File {
self.1.get_mut().as_mut().expect("borrowing locked file")
}
pub (crate) fn borrow_file_mut(&self) -> RefMut<Option<File>> {
self.1.borrow_mut()
}
pub fn path(&self) -> &Path {
&self.0
}
fn has_lock(&self) -> bool {
assert!(self.1.try_borrow_mut().is_ok());
self.1.borrow_mut().is_some()
}
#[cfg(test)]
fn try_lock_shared_start(&self) -> Result<(File, LockFn, bool)> {
self.lock_start(File::try_lock_shared, false)
}
#[cfg(test)]
fn try_lock_shared_finish(&self, st: (File, LockFn, bool)) -> Result<()> {
self.lock_finish(st)
}
fn lock_start(&self, lf: LockFn, write: bool) -> Result<(File, LockFn, bool)> {
assert!(!self.has_lock());
let f = open(&self.0, write, false)?;
Ok((f, lf, write))
}
fn lock_finish(&self, st: (File, LockFn, bool)) -> Result<()> {
assert!(self.1.borrow_mut().is_none());
let mut file = Some(st.0);
let lock = st.1;
let write = st.2;
loop {
lock(file.as_ref().expect(""))?;
let file2 = open(&self.0, false, false);
let file2 = if cfg!(windows) {
if let Err(e) = file2 {
if e.kind() == io::ErrorKind::PermissionDenied {
let oldfile = mem::replace(&mut file, None);
drop(oldfile);
let file3 = open(&self.0, write, false);
match file3 {
Ok(file3) => {
debug!("windows lock / drop conflict");
let _ = mem::replace(&mut file, Some(file3));
continue;
}
Err(e) => {
debug!("failed windows lock / drop conflict");
return Err(e);
}
}
} else {
return Err(e);
}
} else {
file2
}
} else {
file2
};
let file2 = file2.expect("");
if same_file(&file.as_ref().expect(""), &file2)? {
drop(file2);
*self.1.borrow_mut() = file;
return Ok(());
} else {
debug!("lock / drop conflict");
drop(file2);
let newfile = Some(open(&self.0, write, false)?);
let oldfile = mem::replace(&mut file, newfile);
drop(oldfile);
}
}
}
}
impl Drop for SdFlock {
fn drop(&mut self) {
assert!(!self.has_lock(), "dropping locked SdFlock");
if self.try_lock_exclusive().is_err() {
return;
}
#[cfg(unix)]
{
use std::fs;
let r = fs::remove_file(&self.0);
if let Err(e) = r {
error!("unable to remove lock file during drop: {}", e);
}
}
#[cfg(windows)]
{
let f = open(&self.0, false, true);
if let Err(e) = f {
error!("unable to open lock file during drop: {}", e);
} else {
drop(f);
}
}
}
}
fn open(p: &Path, write: bool, delete: bool) -> Result<File> {
let mut opts = OpenOptions::new();
opts.read(true).write(write).create(true);
if !write { opts.append(true); }
if delete {
#[cfg(windows)]
const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x04000000;
#[cfg(windows)]
opts.custom_flags(FILE_FLAG_DELETE_ON_CLOSE);
}
opts.open(p)
}
#[cfg(windows)]
#[allow(bad_style)]
fn same_file(file1: &File, file2: &File) -> Result<bool> {
extern "system" {
fn GetFileInformationByHandle(
hFile: HANDLE,
lpFileInformation: LPBY_HANDLE_FILE_INFORMATION,
) -> BOOL;
}
type DWORD = u32;
type BOOL = i32;
type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION;
#[repr(C)]
struct FILETIME {
dwLowDateTime: DWORD,
dwHighDateTime: DWORD,
}
#[repr(C)]
struct BY_HANDLE_FILE_INFORMATION {
dwFileAttributes: DWORD,
ftCreationTime: FILETIME,
ftLastAccessTime: FILETIME,
ftLastWriteTime: FILETIME,
dwVolumeSerialNumber: DWORD,
nFileSizeHigh: DWORD,
nFileSizeLow: DWORD,
nNumberOfLinks: DWORD,
nFileIndexHigh: DWORD,
nFileIndexLow: DWORD,
}
use std::mem;
use std::os::windows::io::AsRawHandle;
use std::os::windows::raw::HANDLE;
let handle1 = file1.as_raw_handle();
let handle2 = file2.as_raw_handle();
unsafe {
let mut info1: BY_HANDLE_FILE_INFORMATION = mem::zeroed();
let mut info2: BY_HANDLE_FILE_INFORMATION = mem::zeroed();
let r1 = GetFileInformationByHandle(handle1, &mut info1);
let r2 = GetFileInformationByHandle(handle2, &mut info2);
if r1 == 0 || r2 == 0 {
return Err(io::ErrorKind::Other.into());
}
Ok(info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
&& info1.nFileIndexHigh == info2.nFileIndexHigh
&& info1.nFileIndexLow == info2.nFileIndexLow)
}
}
#[cfg(unix)]
fn same_file(file1: &File, file2: &File) -> Result<bool> {
use std::os::unix::fs::MetadataExt;
let inode1 = file1.metadata()?.ino();
let inode2 = file2.metadata()?.ino();
Ok(inode1 == inode2)
}
#[cfg(test)]
mod test {
use tempdir::TempDir;
use super::SdFlock;
use rand::{thread_rng, Rng};
use std::thread;
#[test]
fn shared() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let flock1 = SdFlock::new(&path);
let flock2 = SdFlock::new(&path);
assert!(flock1.try_lock_shared().is_ok());
assert!(flock2.try_lock_shared().is_ok());
assert!(flock1.unlock().is_ok());
assert!(flock2.unlock().is_ok());
}
#[test]
fn exclusive() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let flock1 = SdFlock::new(&path);
let flock2 = SdFlock::new(&path);
assert!(flock1.try_lock_shared().is_ok());
assert!(flock2.try_lock_exclusive().is_err());
assert!(flock1.unlock().is_ok());
assert!(flock2.try_lock_exclusive().is_ok());
assert!(flock2.unlock().is_ok());
}
#[test]
fn delete_on_drop() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let flock = SdFlock::new(&path);
assert!(flock.try_lock_shared().is_ok());
assert!(flock.unlock().is_ok());
assert!(path.exists());
drop(flock);
assert!(!path.exists());
}
#[test]
fn no_delete_on_locked_drop() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let flock1 = SdFlock::new(&path);
let flock2 = SdFlock::new(&path);
assert!(flock1.try_lock_shared().is_ok());
assert!(path.exists());
drop(flock2);
assert!(path.exists());
assert!(flock1.unlock().is_ok());
assert!(path.exists());
drop(flock1);
assert!(!path.exists());
}
#[test]
fn reacquire() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let flock1 = SdFlock::new(&path);
let flock2 = SdFlock::new(&path);
let flock3 = SdFlock::new(&path);
let state = flock1.try_lock_shared_start().unwrap();
assert!(path.exists());
drop(flock2);
assert!(!path.exists());
assert!(flock1.try_lock_shared_finish(state).is_ok());
assert!(path.exists());
assert!(flock3.try_lock_exclusive().is_err());
assert!(flock1.unlock().is_ok());
}
#[test]
fn stress_exclusive() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let joins = (0..100).map(|_| {
let path = path.clone();
thread::spawn(move || {
let flock = SdFlock::new(&path);
for _ in 0..100 {
assert!(flock.lock_exclusive().is_ok());
assert!(flock.unlock().is_ok());
}
})
});
for join in joins {
assert!(join.join().is_ok());
}
}
#[test]
fn stress_drop() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let joins = (0..100).map(|_| {
let path = path.clone();
thread::spawn(move || {
for _ in 0..100 {
drop(SdFlock::new(&path));
}
})
});
for join in joins {
assert!(join.join().is_ok());
}
}
#[test]
fn stress_random() {
let dir = TempDir::new("sdflock").unwrap();
let path = dir.path().join("flock");
let joins = (0..100).map(|_| {
let path = path.clone();
thread::spawn(move || {
let flock = SdFlock::new(&path);
let mut rng = thread_rng();
for _ in 0..100 {
let rnd = rng.gen_range(0, 3);
if rnd == 0 {
assert!(flock.lock_shared().is_ok());
assert!(flock.unlock().is_ok());
} else if rnd == 1 {
assert!(flock.lock_exclusive().is_ok());
assert!(flock.unlock().is_ok());
} else if rnd == 2 {
drop(SdFlock::new(&path));
} else {
panic!()
}
}
})
});
for join in joins {
assert!(join.join().is_ok());
}
}
}