Debian Codegraph @

rust/hg-core/src/lock.rs

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