Debian Codegraph @

lib/src/lock/windows.rs

raw
1 // Copyright 2020 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Windows file locking implementation using std's `File::lock()` which maps
16 //! to `LockFileEx`.
17
18 use std::fs::File;
19 use std::fs::OpenOptions;
20 use std::fs::TryLockError;
21 use std::io;
22 use std::os::windows::fs::OpenOptionsExt as _;
23 use std::path::Path;
24 use std::path::PathBuf;
25 use std::thread;
26
27 use tracing::instrument;
28
29 use super::FileLockError;
30 use super::backoff::BackoffIterator;
31
32 const FILE_SHARE_READ: u32 = 1;
33 const FILE_SHARE_WRITE: u32 = 2;
34 const ERROR_SHARING_VIOLATION: u32 = 32;
35
36 pub struct FileLock {
37 path: PathBuf,
38 /// `Option` so `Drop` can close the handle before deleting.
39 file: Option<File>,
40 }
41
42 impl FileLock {
43 /// Acquire an exclusive lock on `path`, blocking until it's available.
44 pub fn lock(path: PathBuf) -> Result<Self, FileLockError> {
45 // In blocking mode, `lock_inner` never returns `Ok(None)`.
46 Ok(Self::lock_inner(path, true)?.expect("blocking lock should return a lock"))
47 }
48
49 /// Try to acquire an exclusive lock on `path` without blocking. Returns
50 /// `Ok(None)` if the lock is currently held by another process.
51 pub fn try_lock(path: PathBuf) -> Result<Option<Self>, FileLockError> {
52 Self::lock_inner(path, false)
53 }
54
55 fn lock_inner(path: PathBuf, blocking: bool) -> Result<Option<Self>, FileLockError> {
56 tracing::info!("Attempting to lock {path:?}");
57
58 let file = try_create_file(&path).map_err(|err| FileLockError {
59 message: "Failed to open lock file",
60 path: path.clone(),
61 err,
62 })?;
63
64 if blocking {
65 // Acquire exclusive lock (blocks until available)
66 file.lock().map_err(|err| FileLockError {
67 message: "Failed to lock lock file",
68 path: path.clone(),
69 err,
70 })?;
71 } else {
72 // Acquire the lock, or report that another process holds it.
73 match file.try_lock() {
74 Ok(()) => {}
75 Err(TryLockError::WouldBlock) => return Ok(None),
76 Err(TryLockError::Error(err)) => {
77 return Err(FileLockError {
78 message: "Failed to lock lock file",
79 path,
80 err,
81 });
82 }
83 }
84 }
85
86 tracing::info!("Locked {path:?}");
87 Ok(Some(Self {
88 path,
89 file: Some(file),
90 }))
91 }
92 }
93
94 impl Drop for FileLock {
95 #[instrument(skip_all)]
96 fn drop(&mut self) {
97 if let Some(file) = self.file.take() {
98 file.unlock()
99 .inspect_err(|err| tracing::warn!(?err, ?self.path, "Failed to unlock lock file"))
100 .ok();
101 // file is dropped here, closing the handle so the delete below
102 // can succeed. Another process holding the file open prevents
103 // deletion (they open without FILE_SHARE_DELETE), avoiding races.
104 }
105 std::fs::remove_file(&self.path).ok();
106 }
107 }
108
109 fn try_create_file(path: &Path) -> io::Result<File> {
110 let mut backoff_iterator = BackoffIterator::new();
111 let mut options = OpenOptions::new();
112 options
113 .create(true)
114 .write(true)
115 // Don't share delete access. This ensures that std::fs::remove_file
116 // (which uses DeleteFileW) will fail if any other process has the file
117 // open — so deletion in Drop only succeeds when we're the last handle
118 // holder.
119 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
120 loop {
121 match options.open(path) {
122 Ok(file) => return Ok(file),
123 // The file may be open for deletion in Drop.
124 Err(err)
125 if err.kind() == io::ErrorKind::PermissionDenied
126 || err.raw_os_error() == Some(ERROR_SHARING_VIOLATION as _) =>
127 {
128 let Some(duration) = backoff_iterator.next() else {
129 return Err(err);
130 };
131 // Ensure that a file can be created in the target directory.
132 tempfile::tempfile_in(path.parent().expect("file path should have parent"))?;
133 thread::sleep(duration);
134 }
135 Err(err) => return Err(err),
136 }
137 }
138 }