Show More
@@ -0,0 +1,187 b'' | |||||
|
1 | //! Filesystem-based locks for local repositories | |||
|
2 | ||||
|
3 | use crate::errors::HgError; | |||
|
4 | use crate::errors::HgResultExt; | |||
|
5 | use crate::utils::StrExt; | |||
|
6 | use crate::vfs::Vfs; | |||
|
7 | use std::io; | |||
|
8 | use std::io::ErrorKind; | |||
|
9 | ||||
|
10 | #[derive(derive_more::From)] | |||
|
11 | pub enum LockError { | |||
|
12 | AlreadyHeld, | |||
|
13 | #[from] | |||
|
14 | Other(HgError), | |||
|
15 | } | |||
|
16 | ||||
|
17 | /// Try to call `f` with the lock acquired, without waiting. | |||
|
18 | /// | |||
|
19 | /// If the lock is aready held, `f` is not called and `LockError::AlreadyHeld` | |||
|
20 | /// is returned. `LockError::Io` is returned for any unexpected I/O error | |||
|
21 | /// accessing the lock file, including for removing it after `f` was called. | |||
|
22 | /// The return value of `f` is dropped in that case. If all is successful, the | |||
|
23 | /// return value of `f` is forwarded. | |||
|
24 | pub fn try_with_lock_no_wait<R>( | |||
|
25 | hg_vfs: Vfs, | |||
|
26 | lock_filename: &str, | |||
|
27 | f: impl FnOnce() -> R, | |||
|
28 | ) -> Result<R, LockError> { | |||
|
29 | let our_lock_data = &*OUR_LOCK_DATA; | |||
|
30 | for _retry in 0..5 { | |||
|
31 | match make_lock(hg_vfs, lock_filename, our_lock_data) { | |||
|
32 | Ok(()) => { | |||
|
33 | let result = f(); | |||
|
34 | unlock(hg_vfs, lock_filename)?; | |||
|
35 | return Ok(result); | |||
|
36 | } | |||
|
37 | Err(HgError::IoError { error, .. }) | |||
|
38 | if error.kind() == ErrorKind::AlreadyExists => | |||
|
39 | { | |||
|
40 | let lock_data = read_lock(hg_vfs, lock_filename)?; | |||
|
41 | if lock_data.is_none() { | |||
|
42 | // Lock was apparently just released, retry acquiring it | |||
|
43 | continue; | |||
|
44 | } | |||
|
45 | if !lock_should_be_broken(&lock_data) { | |||
|
46 | return Err(LockError::AlreadyHeld); | |||
|
47 | } | |||
|
48 | // The lock file is left over from a process not running | |||
|
49 | // anymore. Break it, but with another lock to | |||
|
50 | // avoid a race. | |||
|
51 | break_lock(hg_vfs, lock_filename)?; | |||
|
52 | ||||
|
53 | // Retry acquiring | |||
|
54 | } | |||
|
55 | Err(error) => Err(error)?, | |||
|
56 | } | |||
|
57 | } | |||
|
58 | Err(LockError::AlreadyHeld) | |||
|
59 | } | |||
|
60 | ||||
|
61 | fn break_lock(hg_vfs: Vfs, lock_filename: &str) -> Result<(), LockError> { | |||
|
62 | try_with_lock_no_wait(hg_vfs, &format!("{}.break", lock_filename), || { | |||
|
63 | // Check again in case some other process broke and | |||
|
64 | // acquired the lock in the meantime | |||
|
65 | let lock_data = read_lock(hg_vfs, lock_filename)?; | |||
|
66 | if !lock_should_be_broken(&lock_data) { | |||
|
67 | return Err(LockError::AlreadyHeld); | |||
|
68 | } | |||
|
69 | Ok(hg_vfs.remove_file(lock_filename)?) | |||
|
70 | })? | |||
|
71 | } | |||
|
72 | ||||
|
73 | #[cfg(unix)] | |||
|
74 | fn make_lock( | |||
|
75 | hg_vfs: Vfs, | |||
|
76 | lock_filename: &str, | |||
|
77 | data: &str, | |||
|
78 | ) -> Result<(), HgError> { | |||
|
79 | // Use a symbolic link because creating it is atomic. | |||
|
80 | // The link’s "target" contains data not representing any path. | |||
|
81 | let fake_symlink_target = data; | |||
|
82 | hg_vfs.create_symlink(lock_filename, fake_symlink_target) | |||
|
83 | } | |||
|
84 | ||||
|
85 | fn read_lock( | |||
|
86 | hg_vfs: Vfs, | |||
|
87 | lock_filename: &str, | |||
|
88 | ) -> Result<Option<String>, HgError> { | |||
|
89 | let link_target = | |||
|
90 | hg_vfs.read_link(lock_filename).io_not_found_as_none()?; | |||
|
91 | if let Some(target) = link_target { | |||
|
92 | let data = target | |||
|
93 | .into_os_string() | |||
|
94 | .into_string() | |||
|
95 | .map_err(|_| HgError::corrupted("non-UTF-8 lock data"))?; | |||
|
96 | Ok(Some(data)) | |||
|
97 | } else { | |||
|
98 | Ok(None) | |||
|
99 | } | |||
|
100 | } | |||
|
101 | ||||
|
102 | fn unlock(hg_vfs: Vfs, lock_filename: &str) -> Result<(), HgError> { | |||
|
103 | hg_vfs.remove_file(lock_filename) | |||
|
104 | } | |||
|
105 | ||||
|
106 | /// Return whether the process that is/was holding the lock is known not to be | |||
|
107 | /// running anymore. | |||
|
108 | fn lock_should_be_broken(data: &Option<String>) -> bool { | |||
|
109 | (|| -> Option<bool> { | |||
|
110 | let (prefix, pid) = data.as_ref()?.split_2(':')?; | |||
|
111 | if prefix != &*LOCK_PREFIX { | |||
|
112 | return Some(false); | |||
|
113 | } | |||
|
114 | let process_is_running; | |||
|
115 | ||||
|
116 | #[cfg(unix)] | |||
|
117 | { | |||
|
118 | let pid: libc::pid_t = pid.parse().ok()?; | |||
|
119 | unsafe { | |||
|
120 | let signal = 0; // Test if we could send a signal, without sending | |||
|
121 | let result = libc::kill(pid, signal); | |||
|
122 | if result == 0 { | |||
|
123 | process_is_running = true | |||
|
124 | } else { | |||
|
125 | let errno = | |||
|
126 | io::Error::last_os_error().raw_os_error().unwrap(); | |||
|
127 | process_is_running = errno != libc::ESRCH | |||
|
128 | } | |||
|
129 | } | |||
|
130 | } | |||
|
131 | ||||
|
132 | Some(!process_is_running) | |||
|
133 | })() | |||
|
134 | .unwrap_or(false) | |||
|
135 | } | |||
|
136 | ||||
|
137 | lazy_static::lazy_static! { | |||
|
138 | /// A string which is used to differentiate pid namespaces | |||
|
139 | /// | |||
|
140 | /// It's useful to detect "dead" processes and remove stale locks with | |||
|
141 | /// confidence. Typically it's just hostname. On modern linux, we include an | |||
|
142 | /// extra Linux-specific pid namespace identifier. | |||
|
143 | static ref LOCK_PREFIX: String = { | |||
|
144 | // Note: this must match the behavior of `_getlockprefix` in `mercurial/lock.py` | |||
|
145 | ||||
|
146 | /// Same as https://github.com/python/cpython/blob/v3.10.0/Modules/socketmodule.c#L5414 | |||
|
147 | const BUFFER_SIZE: usize = 1024; | |||
|
148 | let mut buffer = [0_i8; BUFFER_SIZE]; | |||
|
149 | let hostname_bytes = unsafe { | |||
|
150 | let result = libc::gethostname(buffer.as_mut_ptr(), BUFFER_SIZE); | |||
|
151 | if result != 0 { | |||
|
152 | panic!("gethostname: {}", io::Error::last_os_error()) | |||
|
153 | } | |||
|
154 | std::ffi::CStr::from_ptr(buffer.as_mut_ptr()).to_bytes() | |||
|
155 | }; | |||
|
156 | let hostname = | |||
|
157 | std::str::from_utf8(hostname_bytes).expect("non-UTF-8 hostname"); | |||
|
158 | ||||
|
159 | #[cfg(target_os = "linux")] | |||
|
160 | { | |||
|
161 | use std::os::linux::fs::MetadataExt; | |||
|
162 | match std::fs::metadata("/proc/self/ns/pid") { | |||
|
163 | Ok(meta) => { | |||
|
164 | return format!("{}/{:x}", hostname, meta.st_ino()) | |||
|
165 | } | |||
|
166 | Err(error) => { | |||
|
167 | // TODO: match on `error.kind()` when `NotADirectory` | |||
|
168 | // is available on all supported Rust versions: | |||
|
169 | // https://github.com/rust-lang/rust/issues/86442 | |||
|
170 | use libc::{ | |||
|
171 | ENOENT, // ErrorKind::NotFound | |||
|
172 | ENOTDIR, // ErrorKind::NotADirectory | |||
|
173 | EACCES, // ErrorKind::PermissionDenied | |||
|
174 | }; | |||
|
175 | match error.raw_os_error() { | |||
|
176 | Some(ENOENT) | Some(ENOTDIR) | Some(EACCES) => {} | |||
|
177 | _ => panic!("stat /proc/self/ns/pid: {}", error), | |||
|
178 | } | |||
|
179 | } | |||
|
180 | } | |||
|
181 | } | |||
|
182 | ||||
|
183 | hostname.to_owned() | |||
|
184 | }; | |||
|
185 | ||||
|
186 | static ref OUR_LOCK_DATA: String = format!("{}:{}", &*LOCK_PREFIX, std::process::id()); | |||
|
187 | } |
@@ -29,6 +29,7 b' pub mod repo;' | |||||
29 | pub mod revlog; |
|
29 | pub mod revlog; | |
30 | pub use revlog::*; |
|
30 | pub use revlog::*; | |
31 | pub mod config; |
|
31 | pub mod config; | |
|
32 | pub mod lock; | |||
32 | pub mod logging; |
|
33 | pub mod logging; | |
33 | pub mod operations; |
|
34 | pub mod operations; | |
34 | pub mod revset; |
|
35 | pub mod revset; |
@@ -6,6 +6,7 b' use crate::dirstate_tree::owning::Owning' | |||||
6 | use crate::errors::HgError; |
|
6 | use crate::errors::HgError; | |
7 | use crate::errors::HgResultExt; |
|
7 | use crate::errors::HgResultExt; | |
8 | use crate::exit_codes; |
|
8 | use crate::exit_codes; | |
|
9 | use crate::lock::{try_with_lock_no_wait, LockError}; | |||
9 | use crate::manifest::{Manifest, Manifestlog}; |
|
10 | use crate::manifest::{Manifest, Manifestlog}; | |
10 | use crate::revlog::filelog::Filelog; |
|
11 | use crate::revlog::filelog::Filelog; | |
11 | use crate::revlog::revlog::RevlogError; |
|
12 | use crate::revlog::revlog::RevlogError; | |
@@ -243,6 +244,13 b' impl Repo {' | |||||
243 | } |
|
244 | } | |
244 | } |
|
245 | } | |
245 |
|
246 | |||
|
247 | pub fn try_with_wlock_no_wait<R>( | |||
|
248 | &self, | |||
|
249 | f: impl FnOnce() -> R, | |||
|
250 | ) -> Result<R, LockError> { | |||
|
251 | try_with_lock_no_wait(self.hg_vfs(), "wlock", f) | |||
|
252 | } | |||
|
253 | ||||
246 | pub fn has_dirstate_v2(&self) -> bool { |
|
254 | pub fn has_dirstate_v2(&self) -> bool { | |
247 | self.requirements |
|
255 | self.requirements | |
248 | .contains(requirements::DIRSTATE_V2_REQUIREMENT) |
|
256 | .contains(requirements::DIRSTATE_V2_REQUIREMENT) |
@@ -145,6 +145,21 b' impl SliceExt for [u8] {' | |||||
145 | } |
|
145 | } | |
146 | } |
|
146 | } | |
147 |
|
147 | |||
|
148 | pub trait StrExt { | |||
|
149 | // TODO: Use https://doc.rust-lang.org/nightly/std/primitive.str.html#method.split_once | |||
|
150 | // once we require Rust 1.52+ | |||
|
151 | fn split_2(&self, separator: char) -> Option<(&str, &str)>; | |||
|
152 | } | |||
|
153 | ||||
|
154 | impl StrExt for str { | |||
|
155 | fn split_2(&self, separator: char) -> Option<(&str, &str)> { | |||
|
156 | let mut iter = self.splitn(2, separator); | |||
|
157 | let a = iter.next()?; | |||
|
158 | let b = iter.next()?; | |||
|
159 | Some((a, b)) | |||
|
160 | } | |||
|
161 | } | |||
|
162 | ||||
148 | pub trait Escaped { |
|
163 | pub trait Escaped { | |
149 | /// Return bytes escaped for display to the user |
|
164 | /// Return bytes escaped for display to the user | |
150 | fn escaped_bytes(&self) -> Vec<u8>; |
|
165 | fn escaped_bytes(&self) -> Vec<u8>; |
@@ -87,6 +87,26 b" impl Vfs<'_> {" | |||||
87 | std::fs::rename(&from, &to) |
|
87 | std::fs::rename(&from, &to) | |
88 | .with_context(|| IoErrorContext::RenamingFile { from, to }) |
|
88 | .with_context(|| IoErrorContext::RenamingFile { from, to }) | |
89 | } |
|
89 | } | |
|
90 | ||||
|
91 | pub fn remove_file( | |||
|
92 | &self, | |||
|
93 | relative_path: impl AsRef<Path>, | |||
|
94 | ) -> Result<(), HgError> { | |||
|
95 | let path = self.join(relative_path); | |||
|
96 | std::fs::remove_file(&path) | |||
|
97 | .with_context(|| IoErrorContext::RemovingFile(path)) | |||
|
98 | } | |||
|
99 | ||||
|
100 | #[cfg(unix)] | |||
|
101 | pub fn create_symlink( | |||
|
102 | &self, | |||
|
103 | relative_link_path: impl AsRef<Path>, | |||
|
104 | target_path: impl AsRef<Path>, | |||
|
105 | ) -> Result<(), HgError> { | |||
|
106 | let link_path = self.join(relative_link_path); | |||
|
107 | std::os::unix::fs::symlink(target_path, &link_path) | |||
|
108 | .with_context(|| IoErrorContext::WritingFile(link_path)) | |||
|
109 | } | |||
90 | } |
|
110 | } | |
91 |
|
111 | |||
92 | fn fs_metadata( |
|
112 | fn fs_metadata( |
General Comments 0
You need to be logged in to leave comments.
Login now