#
cargo/util/
flock.rs

    1//! File-locking support.
    2//!
    3//! This module defines the [`Filesystem`] type which is an abstraction over a
    4//! filesystem, ensuring that access to the filesystem is only done through
    5//! coordinated locks.
    6//!
    7//! The [`FileLock`] type represents a locked file, and provides access to the
    8//! file.
    9
    10use std::fs::TryLockError;
    11use std::fs::{File, OpenOptions};
    12use std::io;
    13use std::io::{Read, Seek, SeekFrom, Write};
    14use std::path::{Display, Path, PathBuf};
    15
    16use crate::util::GlobalContext;
    17use crate::util::errors::CargoResult;
    18use crate::util::style;
    19use anyhow::Context as _;
    20use cargo_util::paths;
    21
    22/// A locked file.
    23///
    24/// This provides access to file while holding a lock on the file. This type
    25/// implements the [`Read`], [`Write`], and [`Seek`] traits to provide access
    26/// to the underlying file.
    27///
    28/// Locks are either shared (multiple processes can access the file) or
    29/// exclusive (only one process can access the file).
    30///
    31/// This type is created via methods on the [`Filesystem`] type.
    32///
    33/// When this value is dropped, the lock will be released.
    34#[derive(Debug)]
    35pub struct FileLock {
    36    f: Option<File>,
    37    path: PathBuf,
    38}
    39
    40impl FileLock {
    41    /// Returns the underlying file handle of this lock.
    42    pub fn file(&self) -> &File {
    43        self.f.as_ref().unwrap()
    44    }
    45
    46    /// Returns the underlying path that this lock points to.
    47    ///
    48    /// Note that special care must be taken to ensure that the path is not
    49    /// referenced outside the lifetime of this lock.
    50    pub fn path(&self) -> &Path {
    51        &self.path
    52    }
    53
    54    /// Returns the parent path containing this file
    55    pub fn parent(&self) -> &Path {
    56        self.path.parent().unwrap()
    57    }
    58
    59    /// Removes all sibling files to this locked file.
    60    ///
    61    /// This can be useful if a directory is locked with a sentinel file but it
    62    /// needs to be cleared out as it may be corrupt.
    63    pub fn remove_siblings(&self) -> CargoResult<()> {
    64        let path = self.path();
    65        for entry in path.parent().unwrap().read_dir()? {
    66            let entry = entry?;
    67            if Some(&entry.file_name()[..]) == path.file_name() {
    68                continue;
    69            }
    70            let kind = entry.file_type()?;
    71            if kind.is_dir() {
    72                paths::remove_dir_all(entry.path())?;
    73            } else {
    74                paths::remove_file(entry.path())?;
    75            }
    76        }
    77        Ok(())
    78    }
    79}
    80
    81impl Read for FileLock {
    82    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
    83        self.file().read(buf)
    84    }
    85}
    86
    87impl Seek for FileLock {
    88    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
    89        self.file().seek(to)
    90    }
    91}
    92
    93impl Write for FileLock {
    94    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    95        self.file().write(buf)
    96    }
    97
    98    fn flush(&mut self) -> io::Result<()> {
    99        self.file().flush()
    100    }
    101}
    102
    103impl Drop for FileLock {
    104    fn drop(&mut self) {
    105        if let Some(f) = self.f.take() {
    106            if let Err(e) = f.unlock() {
    107                tracing::warn!("failed to release lock: {e:?}");
    108            }
    109        }
    110    }
    111}
    112
    113/// A "filesystem" is intended to be a globally shared, hence locked, resource
    114/// in Cargo.
    115///
    116/// The `Path` of a filesystem cannot be learned unless it's done in a locked
    117/// fashion, and otherwise functions on this structure are prepared to handle
    118/// concurrent invocations across multiple instances of Cargo.
    119///
    120/// The methods on `Filesystem` that open files return a [`FileLock`] which
    121/// holds the lock, and that type provides methods for accessing the
    122/// underlying file.
    123///
    124/// If the blocking methods (like [`Filesystem::open_ro_shared`]) detect that
    125/// they will block, then they will display a message to the user letting them
    126/// know it is blocked. There are non-blocking variants starting with the
    127/// `try_` prefix like [`Filesystem::try_open_ro_shared_create`].
    128///
    129/// The behavior of locks acquired by the `Filesystem` depend on the operating
    130/// system. On unix-like system, they are advisory using [`flock`], and thus
    131/// not enforced against processes which do not try to acquire the lock. On
    132/// Windows, they are mandatory using [`LockFileEx`], enforced against all
    133/// processes.
    134///
    135/// This **does not** guarantee that a lock is acquired. In some cases, for
    136/// example on filesystems that don't support locking, it will return a
    137/// [`FileLock`] even though the filesystem lock was not acquired. This is
    138/// intended to provide a graceful fallback instead of refusing to work.
    139/// Usually there aren't multiple processes accessing the same resource. In
    140/// that case, it is the user's responsibility to not run concurrent
    141/// processes.
    142///
    143/// [`flock`]: https://linux.die.net/man/2/flock
    144/// [`LockFileEx`]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex
    145#[derive(Clone, Debug, PartialEq, Eq)]
    146pub struct Filesystem {
    147    root: PathBuf,
    148}
    149
    150impl Filesystem {
    151    /// Creates a new filesystem to be rooted at the given path.
    152    pub fn new(path: PathBuf) -> Filesystem {
    153        Filesystem { root: path }
    154    }
    155
    156    /// Like `Path::join`, creates a new filesystem rooted at this filesystem
    157    /// joined with the given path.
    158    pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
    159        Filesystem::new(self.root.join(other))
    160    }
    161
    162    /// Like `Path::push`, pushes a new path component onto this filesystem.
    163    pub fn push<T: AsRef<Path>>(&mut self, other: T) {
    164        self.root.push(other);
    165    }
    166
    167    /// Consumes this filesystem and returns the underlying `PathBuf`.
    168    ///
    169    /// Note that this is a relatively dangerous operation and should be used
    170    /// with great caution!.
    171    pub fn into_path_unlocked(self) -> PathBuf {
    172        self.root
    173    }
    174
    175    /// Returns the underlying `Path`.
    176    ///
    177    /// Note that this is a relatively dangerous operation and should be used
    178    /// with great caution!.
    179    pub fn as_path_unlocked(&self) -> &Path {
    180        &self.root
    181    }
    182
    183    /// Creates the directory pointed to by this filesystem.
    184    ///
    185    /// Handles errors where other Cargo processes are also attempting to
    186    /// concurrently create this directory.
    187    pub fn create_dir(&self) -> CargoResult<()> {
    188        paths::create_dir_all(&self.root)
    189    }
    190
    191    /// Returns an adaptor that can be used to print the path of this
    192    /// filesystem.
    193    pub fn display(&self) -> Display<'_> {
    194        self.root.display()
    195    }
    196
    197    /// Opens read-write exclusive access to a file, returning the locked
    198    /// version of a file.
    199    ///
    200    /// This function will create a file at `path` if it doesn't already exist
    201    /// (including intermediate directories), and then it will acquire an
    202    /// exclusive lock on `path`. If the process must block waiting for the
    203    /// lock, the `msg` is printed to [`GlobalContext`].
    204    ///
    205    /// The returned file can be accessed to look at the path and also has
    206    /// read/write access to the underlying file.
    207    pub fn open_rw_exclusive_create<P>(
    208        &self,
    209        path: P,
    210        gctx: &GlobalContext,
    211        msg: &str,
    212    ) -> CargoResult<FileLock>
    213    where
    214        P: AsRef<Path>,
    215    {
    216        let mut opts = OpenOptions::new();
    217        opts.read(true).write(true).create(true);
    218        let (path, f) = self.open(path.as_ref(), &opts, true)?;
    219        acquire(gctx, msg, &path, &|| f.try_lock(), &|| f.lock())?;
    220        Ok(FileLock { f: Some(f), path })
    221    }
    222
    223    /// A non-blocking version of [`Filesystem::open_rw_exclusive_create`].
    224    ///
    225    /// Returns `None` if the operation would block due to another process
    226    /// holding the lock.
    227    pub fn try_open_rw_exclusive_create<P: AsRef<Path>>(
    228        &self,
    229        path: P,
    230    ) -> CargoResult<Option<FileLock>> {
    231        let mut opts = OpenOptions::new();
    232        opts.read(true).write(true).create(true);
    233        let (path, f) = self.open(path.as_ref(), &opts, true)?;
    234        if try_acquire(&path, &|| f.try_lock())? {
    235            Ok(Some(FileLock { f: Some(f), path }))
    236        } else {
    237            Ok(None)
    238        }
    239    }
    240
    241    /// Opens read-only shared access to a file, returning the locked version of a file.
    242    ///
    243    /// This function will fail if `path` doesn't already exist, but if it does
    244    /// then it will acquire a shared lock on `path`. If the process must block
    245    /// waiting for the lock, the `msg` is printed to [`GlobalContext`].
    246    ///
    247    /// The returned file can be accessed to look at the path and also has read
    248    /// access to the underlying file. Any writes to the file will return an
    249    /// error.
    250    pub fn open_ro_shared<P>(
    251        &self,
    252        path: P,
    253        gctx: &GlobalContext,
    254        msg: &str,
    255    ) -> CargoResult<FileLock>
    256    where
    257        P: AsRef<Path>,
    258    {
    259        let (path, f) = self.open(path.as_ref(), &OpenOptions::new().read(true), false)?;
    260        acquire(gctx, msg, &path, &|| f.try_lock_shared(), &|| {
    261            f.lock_shared()
    262        })?;
    263        Ok(FileLock { f: Some(f), path })
    264    }
    265
    266    /// Opens read-only shared access to a file, returning the locked version of a file.
    267    ///
    268    /// Compared to [`Filesystem::open_ro_shared`], this will create the file
    269    /// (and any directories in the parent) if the file does not already
    270    /// exist.
    271    pub fn open_ro_shared_create<P: AsRef<Path>>(
    272        &self,
    273        path: P,
    274        gctx: &GlobalContext,
    275        msg: &str,
    276    ) -> CargoResult<FileLock> {
    277        let mut opts = OpenOptions::new();
    278        opts.read(true).write(true).create(true);
    279        let (path, f) = self.open(path.as_ref(), &opts, true)?;
    280        acquire(gctx, msg, &path, &|| f.try_lock_shared(), &|| {
    281            f.lock_shared()
    282        })?;
    283        Ok(FileLock { f: Some(f), path })
    284    }
    285
    286    /// A non-blocking version of [`Filesystem::open_ro_shared_create`].
    287    ///
    288    /// Returns `None` if the operation would block due to another process
    289    /// holding the lock.
    290    pub fn try_open_ro_shared_create<P: AsRef<Path>>(
    291        &self,
    292        path: P,
    293    ) -> CargoResult<Option<FileLock>> {
    294        let mut opts = OpenOptions::new();
    295        opts.read(true).write(true).create(true);
    296        let (path, f) = self.open(path.as_ref(), &opts, true)?;
    297        if try_acquire(&path, &|| f.try_lock_shared())? {
    298            Ok(Some(FileLock { f: Some(f), path }))
    299        } else {
    300            Ok(None)
    301        }
    302    }
    303
    304    fn open(&self, path: &Path, opts: &OpenOptions, create: bool) -> CargoResult<(PathBuf, File)> {
    305        let path = self.root.join(path);
    306        let f = opts
    307            .open(&path)
    308            .or_else(|e| {
    309                // If we were requested to create this file, and there was a
    310                // NotFound error, then that was likely due to missing
    311                // intermediate directories. Try creating them and try again.
    312                if e.kind() == io::ErrorKind::NotFound && create {
    313                    paths::create_dir_all(path.parent().unwrap())?;
    314                    Ok(opts.open(&path)?)
    315                } else {
    316                    Err(anyhow::Error::from(e))
    317                }
    318            })
    319            .with_context(|| format!("failed to open: {}", path.display()))?;
    320        Ok((path, f))
    321    }
    322}
    323
    324impl PartialEq<Path> for Filesystem {
    325    fn eq(&self, other: &Path) -> bool {
    326        self.root == other
    327    }
    328}
    329
    330impl PartialEq<Filesystem> for Path {
    331    fn eq(&self, other: &Filesystem) -> bool {
    332        self == other.root
    333    }
    334}
    335
    336fn try_acquire(path: &Path, lock_try: &dyn Fn() -> Result<(), TryLockError>) -> CargoResult<bool> {
    337    // File locking on Unix is currently implemented via `flock`, which is known
    338    // to be broken on NFS. We could in theory just ignore errors that happen on
    339    // NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
    340    // forever**, even if the "non-blocking" flag is passed!
    341    //
    342    // As a result, we just skip all file locks entirely on NFS mounts. That
    343    // should avoid calling any `flock` functions at all, and it wouldn't work
    344    // there anyway.
    345    //
    346    // [1]: https://github.com/rust-lang/cargo/issues/2615
    347    if is_on_nfs_mount(path) {
    348        tracing::debug!("{path:?} appears to be an NFS mount, not trying to lock");
    349        return Ok(true);
    350    }
    351
    352    match lock_try() {
    353        Ok(()) => Ok(true),
    354
    355        // In addition to ignoring NFS which is commonly not working we also
    356        // just ignore locking on filesystems that look like they don't
    357        // implement file locking.
    358        Err(TryLockError::Error(e)) if error_unsupported(&e) => Ok(true),
    359
    360        Err(TryLockError::Error(e)) => {
    361            let e = anyhow::Error::from(e);
    362            let cx = format!("failed to lock file: {}", path.display());
    363            Err(e.context(cx))
    364        }
    365
    366        Err(TryLockError::WouldBlock) => Ok(false),
    367    }
    368}
    369
    370/// Acquires a lock on a file in a "nice" manner.
    371///
    372/// Almost all long-running blocking actions in Cargo have a status message
    373/// associated with them as we're not sure how long they'll take. Whenever a
    374/// conflicted file lock happens, this is the case (we're not sure when the lock
    375/// will be released).
    376///
    377/// This function will acquire the lock on a `path`, printing out a nice message
    378/// to the console if we have to wait for it. It will first attempt to use `try`
    379/// to acquire a lock on the crate, and in the case of contention it will emit a
    380/// status message based on `msg` to [`GlobalContext`]'s shell, and then use `block` to
    381/// block waiting to acquire a lock.
    382///
    383/// Returns an error if the lock could not be acquired or if any error other
    384/// than a contention error happens.
    385fn acquire(
    386    gctx: &GlobalContext,
    387    msg: &str,
    388    path: &Path,
    389    lock_try: &dyn Fn() -> Result<(), TryLockError>,
    390    lock_block: &dyn Fn() -> io::Result<()>,
    391) -> CargoResult<()> {
    392    if cfg!(debug_assertions) {
    393        // Force borrow to catch invalid borrows outside of contention situations
    394        gctx.shell().verbosity();
    395    }
    396    if try_acquire(path, lock_try)? {
    397        return Ok(());
    398    }
    399    let msg = format!("waiting for file lock on {}", msg);
    400    gctx.shell()
    401        .status_with_color("Blocking", &msg, &style::NOTE)?;
    402
    403    lock_block().with_context(|| format!("failed to lock file: {}", path.display()))?;
    404    Ok(())
    405}
    406
    407#[cfg(all(target_os = "linux", not(target_env = "musl")))]
    408fn is_on_nfs_mount(path: &Path) -> bool {
    409    use std::ffi::CString;
    410    use std::mem;
    411    use std::os::unix::prelude::*;
    412
    413    let Ok(path) = CString::new(path.as_os_str().as_bytes()) else {
    414        return false;
    415    };
    416
    417    unsafe {
    418        let mut buf: libc::statfs = mem::zeroed();
    419        let r = libc::statfs(path.as_ptr(), &mut buf);
    420
    421        r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
    422    }
    423}
    424
    425#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
    426fn is_on_nfs_mount(_path: &Path) -> bool {
    427    false
    428}
    429
    430#[cfg(unix)]
    431fn error_unsupported(err: &std::io::Error) -> bool {
    432    match err.raw_os_error() {
    433        // Unfortunately, depending on the target, these may or may not be the same.
    434        // For targets in which they are the same, the duplicate pattern causes a warning.
    435        #[allow(unreachable_patterns)]
    436        Some(libc::ENOTSUP | libc::EOPNOTSUPP) => true,
    437        Some(libc::ENOSYS) => true,
    438        _ => err.kind() == std::io::ErrorKind::Unsupported,
    439    }
    440}
    441
    442#[cfg(windows)]
    443fn error_unsupported(err: &std::io::Error) -> bool {
    444    use windows_sys::Win32::Foundation::ERROR_INVALID_FUNCTION;
    445    match err.raw_os_error() {
    446        Some(code) if code == ERROR_INVALID_FUNCTION as i32 => true,
    447        _ => err.kind() == std::io::ErrorKind::Unsupported,
    448    }
    449}