cargo/util/flock.rs
1use std::fs::{self, File, OpenOptions};
2use std::io;
3use std::io::{Read, Seek, SeekFrom, Write};
4use std::path::{Display, Path, PathBuf};
5
6use fs2::{lock_contended_error, FileExt};
7#[allow(unused_imports)]
8use libc;
9use termcolor::Color::Cyan;
10
11use crate::util::errors::{CargoResult, CargoResultExt};
12use crate::util::paths;
13use crate::util::Config;
14
15pub struct FileLock {
16 f: Option<File>,
17 path: PathBuf,
18 state: State,
19}
20
21#[derive(PartialEq, Debug)]
22enum State {
23 Unlocked,
24 Shared,
25 Exclusive,
26}
27
28impl FileLock {
29 /// Returns the underlying file handle of this lock.
30 pub fn file(&self) -> &File {
31 self.f.as_ref().unwrap()
32 }
33
34 /// Returns the underlying path that this lock points to.
35 ///
36 /// Note that special care must be taken to ensure that the path is not
37 /// referenced outside the lifetime of this lock.
38 pub fn path(&self) -> &Path {
39 assert_ne!(self.state, State::Unlocked);
40 &self.path
41 }
42
43 /// Returns the parent path containing this file
44 pub fn parent(&self) -> &Path {
45 assert_ne!(self.state, State::Unlocked);
46 self.path.parent().unwrap()
47 }
48
49 /// Removes all sibling files to this locked file.
50 ///
51 /// This can be useful if a directory is locked with a sentinel file but it
52 /// needs to be cleared out as it may be corrupt.
53 pub fn remove_siblings(&self) -> CargoResult<()> {
54 let path = self.path();
55 for entry in path.parent().unwrap().read_dir()? {
56 let entry = entry?;
57 if Some(&entry.file_name()[..]) == path.file_name() {
58 continue;
59 }
60 let kind = entry.file_type()?;
61 if kind.is_dir() {
62 paths::remove_dir_all(entry.path())?;
63 } else {
64 paths::remove_file(entry.path())?;
65 }
66 }
67 Ok(())
68 }
69}
70
71impl Read for FileLock {
72 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
73 self.file().read(buf)
74 }
75}
76
77impl Seek for FileLock {
78 fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
79 self.file().seek(to)
80 }
81}
82
83impl Write for FileLock {
84 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
85 self.file().write(buf)
86 }
87
88 fn flush(&mut self) -> io::Result<()> {
89 self.file().flush()
90 }
91}
92
93impl Drop for FileLock {
94 fn drop(&mut self) {
95 if self.state != State::Unlocked {
96 if let Some(f) = self.f.take() {
97 let _ = f.unlock();
98 }
99 }
100 }
101}
102
103/// A "filesystem" is intended to be a globally shared, hence locked, resource
104/// in Cargo.
105///
106/// The `Path` of a filesystem cannot be learned unless it's done in a locked
107/// fashion, and otherwise functions on this structure are prepared to handle
108/// concurrent invocations across multiple instances of Cargo.
109#[derive(Clone, Debug)]
110pub struct Filesystem {
111 root: PathBuf,
112}
113
114impl Filesystem {
115 /// Creates a new filesystem to be rooted at the given path.
116 pub fn new(path: PathBuf) -> Filesystem {
117 Filesystem { root: path }
118 }
119
120 /// Like `Path::join`, creates a new filesystem rooted at this filesystem
121 /// joined with the given path.
122 pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
123 Filesystem::new(self.root.join(other))
124 }
125
126 /// Like `Path::push`, pushes a new path component onto this filesystem.
127 pub fn push<T: AsRef<Path>>(&mut self, other: T) {
128 self.root.push(other);
129 }
130
131 /// Consumes this filesystem and returns the underlying `PathBuf`.
132 ///
133 /// Note that this is a relatively dangerous operation and should be used
134 /// with great caution!.
135 pub fn into_path_unlocked(self) -> PathBuf {
136 self.root
137 }
138
139 /// Creates the directory pointed to by this filesystem.
140 ///
141 /// Handles errors where other Cargo processes are also attempting to
142 /// concurrently create this directory.
143 pub fn create_dir(&self) -> io::Result<()> {
144 fs::create_dir_all(&self.root)
145 }
146
147 /// Returns an adaptor that can be used to print the path of this
148 /// filesystem.
149 pub fn display(&self) -> Display<'_> {
150 self.root.display()
151 }
152
153 /// Opens exclusive access to a file, returning the locked version of a
154 /// file.
155 ///
156 /// This function will create a file at `path` if it doesn't already exist
157 /// (including intermediate directories), and then it will acquire an
158 /// exclusive lock on `path`. If the process must block waiting for the
159 /// lock, the `msg` is printed to `config`.
160 ///
161 /// The returned file can be accessed to look at the path and also has
162 /// read/write access to the underlying file.
163 pub fn open_rw<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
164 where
165 P: AsRef<Path>,
166 {
167 self.open(
168 path.as_ref(),
169 OpenOptions::new().read(true).write(true).create(true),
170 State::Exclusive,
171 config,
172 msg,
173 )
174 }
175
176 /// Opens shared access to a file, returning the locked version of a file.
177 ///
178 /// This function will fail if `path` doesn't already exist, but if it does
179 /// then it will acquire a shared lock on `path`. If the process must block
180 /// waiting for the lock, the `msg` is printed to `config`.
181 ///
182 /// The returned file can be accessed to look at the path and also has read
183 /// access to the underlying file. Any writes to the file will return an
184 /// error.
185 pub fn open_ro<P>(&self, path: P, config: &Config, msg: &str) -> CargoResult<FileLock>
186 where
187 P: AsRef<Path>,
188 {
189 self.open(
190 path.as_ref(),
191 OpenOptions::new().read(true),
192 State::Shared,
193 config,
194 msg,
195 )
196 }
197
198 fn open(
199 &self,
200 path: &Path,
201 opts: &OpenOptions,
202 state: State,
203 config: &Config,
204 msg: &str,
205 ) -> CargoResult<FileLock> {
206 let path = self.root.join(path);
207
208 // If we want an exclusive lock then if we fail because of NotFound it's
209 // likely because an intermediate directory didn't exist, so try to
210 // create the directory and then continue.
211 let f = opts
212 .open(&path)
213 .or_else(|e| {
214 if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
215 fs::create_dir_all(path.parent().unwrap())?;
216 opts.open(&path)
217 } else {
218 Err(e)
219 }
220 })
221 .chain_err(|| format!("failed to open: {}", path.display()))?;
222 match state {
223 State::Exclusive => {
224 acquire(config, msg, &path, &|| f.try_lock_exclusive(), &|| {
225 f.lock_exclusive()
226 })?;
227 }
228 State::Shared => {
229 acquire(config, msg, &path, &|| f.try_lock_shared(), &|| {
230 f.lock_shared()
231 })?;
232 }
233 State::Unlocked => {}
234 }
235 Ok(FileLock {
236 f: Some(f),
237 path,
238 state,
239 })
240 }
241}
242
243impl PartialEq<Path> for Filesystem {
244 fn eq(&self, other: &Path) -> bool {
245 self.root == other
246 }
247}
248
249impl PartialEq<Filesystem> for Path {
250 fn eq(&self, other: &Filesystem) -> bool {
251 self == other.root
252 }
253}
254
255/// Acquires a lock on a file in a "nice" manner.
256///
257/// Almost all long-running blocking actions in Cargo have a status message
258/// associated with them as we're not sure how long they'll take. Whenever a
259/// conflicted file lock happens, this is the case (we're not sure when the lock
260/// will be released).
261///
262/// This function will acquire the lock on a `path`, printing out a nice message
263/// to the console if we have to wait for it. It will first attempt to use `try`
264/// to acquire a lock on the crate, and in the case of contention it will emit a
265/// status message based on `msg` to `config`'s shell, and then use `block` to
266/// block waiting to acquire a lock.
267///
268/// Returns an error if the lock could not be acquired or if any error other
269/// than a contention error happens.
270fn acquire(
271 config: &Config,
272 msg: &str,
273 path: &Path,
274 r#try: &dyn Fn() -> io::Result<()>,
275 block: &dyn Fn() -> io::Result<()>,
276) -> CargoResult<()> {
277 // File locking on Unix is currently implemented via `flock`, which is known
278 // to be broken on NFS. We could in theory just ignore errors that happen on
279 // NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
280 // forever**, even if the nonblocking flag is passed!
281 //
282 // As a result, we just skip all file locks entirely on NFS mounts. That
283 // should avoid calling any `flock` functions at all, and it wouldn't work
284 // there anyway.
285 //
286 // [1]: https://github.com/rust-lang/cargo/issues/2615
287 if is_on_nfs_mount(path) {
288 return Ok(());
289 }
290
291 match r#try() {
292 Ok(()) => return Ok(()),
293
294 // In addition to ignoring NFS which is commonly not working we also
295 // just ignore locking on filesystems that look like they don't
296 // implement file locking. We detect that here via the return value of
297 // locking (e.g. inspecting errno).
298 #[cfg(unix)]
299 Err(ref e) if e.raw_os_error() == Some(libc::ENOTSUP) => return Ok(()),
300
301 #[cfg(target_os = "linux")]
302 Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => return Ok(()),
303
304 Err(e) => {
305 if e.raw_os_error() != lock_contended_error().raw_os_error() {
306 let e = failure::Error::from(e);
307 let cx = format!("failed to lock file: {}", path.display());
308 return Err(e.context(cx).into());
309 }
310 }
311 }
312 let msg = format!("waiting for file lock on {}", msg);
313 config.shell().status_with_color("Blocking", &msg, Cyan)?;
314
315 block().chain_err(|| format!("failed to lock file: {}", path.display()))?;
316 return Ok(());
317
318 #[cfg(all(target_os = "linux", not(target_env = "musl")))]
319 fn is_on_nfs_mount(path: &Path) -> bool {
320 use std::ffi::CString;
321 use std::mem;
322 use std::os::unix::prelude::*;
323
324 let path = match CString::new(path.as_os_str().as_bytes()) {
325 Ok(path) => path,
326 Err(_) => return false,
327 };
328
329 unsafe {
330 let mut buf: libc::statfs = mem::zeroed();
331 let r = libc::statfs(path.as_ptr(), &mut buf);
332
333 r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
334 }
335 }
336
337 #[cfg(any(not(target_os = "linux"), target_env = "musl"))]
338 fn is_on_nfs_mount(_path: &Path) -> bool {
339 false
340 }
341}