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