Skip to main content

cargo/util/
cache_lock.rs

1//! Support for locking the package and index caches.
2//!
3//! This implements locking on the package and index caches (source files,
4//! `.crate` files, and index caches) to coordinate when multiple cargos are
5//! running at the same time.
6//!
7//! ## Usage
8//!
9//! There is a global [`CacheLocker`] held inside cargo's venerable
10//! [`GlobalContext`]. The `CacheLocker` manages creating and tracking the locks
11//! being held. There are methods on [`GlobalContext`] for managing the locks:
12//!
13//! - [`GlobalContext::acquire_package_cache_lock`] --- Acquires a lock. May block if
14//!   another process holds a lock.
15//! - [`GlobalContext::try_acquire_package_cache_lock`] --- Acquires a lock, returning
16//!   immediately if it would block.
17//! - [`GlobalContext::assert_package_cache_locked`] --- This is used to ensure the
18//!   proper lock is being held.
19//!
20//! Lower-level code that accesses the package cache typically just use
21//! `assert_package_cache_locked` to ensure that the correct lock is being
22//! held. Higher-level code is responsible for acquiring the appropriate lock,
23//! and holding it during the duration that it is performing its operation.
24//!
25//! ## Types of locking
26//!
27//! There are three styles of locks:
28//!
29//! * [`CacheLockMode::DownloadExclusive`] -- This is an exclusive lock
30//!   acquired while downloading packages and doing resolution.
31//! * [`CacheLockMode::Shared`] -- This is a shared lock acquired while a
32//!   build is running. In other words, whenever cargo just needs to read from
33//!   the cache, it should hold this lock. This is here to ensure that no
34//!   cargos are trying to read the source caches when cache garbage
35//!   collection runs.
36//! * [`CacheLockMode::MutateExclusive`] -- This is an exclusive lock acquired
37//!   whenever needing to modify existing source files (for example, with
38//!   cache garbage collection). This is acquired to make sure that no other
39//!   cargo is reading from the cache.
40//!
41//! Importantly, a `DownloadExclusive` lock does *not* interfere with a
42//! `Shared` lock. The download process generally does not modify source files
43//! (it only adds new ones), so other cargos should be able to safely proceed
44//! in reading source files[^1].
45//!
46//! See the [`CacheLockMode`] enum docs for more details on when the different
47//! modes should be used.
48//!
49//! ## Locking implementation details
50//!
51//! This is implemented by two separate lock files, the "download" one and the
52//! "mutate" one. The `MutateExclusive` lock acquired both the "mutate" and
53//! "download" locks. The `Shared` lock acquires the "mutate" lock in share
54//! mode.
55//!
56//! An important rule is that `MutateExclusive` acquires the locks in the
57//! order "mutate" first and then the "download". That helps prevent
58//! deadlocks. It is not allowed for a cargo to first acquire a
59//! `DownloadExclusive` lock and then a `Shared` lock because that would open
60//! it up for deadlock.
61//!
62//! Another rule is that there should be only one [`CacheLocker`] per process
63//! to uphold the ordering rules. You could in theory have multiple if you
64//! could ensure that other threads would make progress and drop a lock, but
65//! cargo is not architected that way.
66//!
67//! It is safe to recursively acquire a lock as many times as you want.
68//!
69//! ## Interaction with older cargos
70//!
71//! Before version 1.74, cargo only acquired the `DownloadExclusive` lock when
72//! downloading and doing resolution. Newer cargos that acquire
73//! `MutateExclusive` should still correctly block when an old cargo is
74//! downloading (because it also acquires `DownloadExclusive`), but they do
75//! not properly coordinate when an old cargo is in the build phase (because
76//! it holds no locks). This isn't expected to be much of a problem because
77//! the intended use of mutating the cache is only to delete old contents
78//! which aren't currently being used. It is possible for there to be a
79//! conflict, particularly if the user manually deletes the entire cache, but
80//! it is not expected for this scenario to happen too often, and the only
81//! consequence is that one side or the other encounters an error and needs to
82//! retry.
83//!
84//! [^1]: A minor caveat is that downloads will delete an existing `src`
85//!   directory if it was extracted via an old cargo. See
86//!   [`crate::sources::registry::RegistrySource::unpack_package`]. This
87//!   should probably be fixed, but is unlikely to be a problem if the user is
88//!   only using versions of cargo with the same deletion logic.
89
90use super::FileLock;
91use crate::CargoResult;
92use crate::GlobalContext;
93use anyhow::Context as _;
94use std::io;
95use std::sync::Mutex;
96
97/// The style of lock to acquire.
98#[derive(Copy, Clone, Debug, PartialEq)]
99pub enum CacheLockMode {
100    /// A `DownloadExclusive` lock ensures that only one cargo is doing
101    /// resolution and downloading new packages.
102    ///
103    /// You should use this when downloading new packages or doing resolution.
104    ///
105    /// If another cargo has a `MutateExclusive` lock, then an attempt to get
106    /// a `DownloadExclusive` lock will block.
107    ///
108    /// If another cargo has a `Shared` lock, then both can operate
109    /// concurrently.
110    DownloadExclusive,
111    /// A `Shared` lock allows multiple cargos to read from the source files.
112    ///
113    /// You should use this when cargo is reading source files from the
114    /// package cache. This is typically done during the build phase, since
115    /// cargo only needs to read files during that time. This allows multiple
116    /// cargo processes to build concurrently without interfering with one
117    /// another, while guarding against other cargos using `MutateExclusive`.
118    ///
119    /// If another cargo has a `MutateExclusive` lock, then an attempt to get
120    /// a `Shared` will block.
121    ///
122    /// If another cargo has a `DownloadExclusive` lock, then they both can
123    /// operate concurrently under the assumption that downloading does not
124    /// modify existing source files.
125    Shared,
126    /// A `MutateExclusive` lock ensures no other cargo is reading or writing
127    /// from the package caches.
128    ///
129    /// You should use this when modifying existing files in the package
130    /// cache. For example, things like garbage collection want to avoid
131    /// deleting files while other cargos are trying to read (`Shared`) or
132    /// resolve or download (`DownloadExclusive`).
133    ///
134    /// If another cargo has a `DownloadExclusive` or `Shared` lock, then this
135    /// will block until they all release their locks.
136    MutateExclusive,
137}
138
139/// Whether or not a lock attempt should block.
140#[derive(Copy, Clone)]
141enum BlockingMode {
142    Blocking,
143    NonBlocking,
144}
145
146use BlockingMode::*;
147
148/// Whether or not a lock attempt blocked or succeeded.
149#[derive(PartialEq, Copy, Clone)]
150#[must_use]
151enum LockingResult {
152    LockAcquired,
153    WouldBlock,
154}
155
156use LockingResult::*;
157
158/// A file lock, with a counter to assist with recursive locking.
159#[derive(Debug)]
160struct RecursiveLock {
161    /// The file lock.
162    ///
163    /// An important note is that locks can be `None` even when they are held.
164    /// This can happen on things like old NFS mounts where locking isn't
165    /// supported. We otherwise pretend we have a lock via the lock count. See
166    /// [`FileLock`] for more detail on that.
167    lock: Option<FileLock>,
168    /// Number locks held, to support recursive locking.
169    count: u32,
170    /// If this is `true`, it is an exclusive lock, otherwise it is shared.
171    is_exclusive: bool,
172    /// The filename of the lock.
173    filename: &'static str,
174}
175
176impl RecursiveLock {
177    fn new(filename: &'static str) -> RecursiveLock {
178        RecursiveLock {
179            lock: None,
180            count: 0,
181            is_exclusive: false,
182            filename,
183        }
184    }
185
186    /// Low-level lock count increment routine.
187    fn increment(&mut self) {
188        self.count = self.count.checked_add(1).unwrap();
189    }
190
191    /// Unlocks a previously acquired lock.
192    fn decrement(&mut self) {
193        let new_cnt = self.count.checked_sub(1).unwrap();
194        self.count = new_cnt;
195        if new_cnt == 0 {
196            // This will drop, releasing the lock.
197            self.lock = None;
198        }
199    }
200
201    /// Acquires a shared lock.
202    fn lock_shared(
203        &mut self,
204        gctx: &GlobalContext,
205        description: &'static str,
206        blocking: BlockingMode,
207    ) -> LockingResult {
208        match blocking {
209            Blocking => {
210                self.lock_shared_blocking(gctx, description);
211                LockAcquired
212            }
213            NonBlocking => self.lock_shared_nonblocking(gctx),
214        }
215    }
216
217    /// Acquires a shared lock, blocking if held by another locker.
218    fn lock_shared_blocking(&mut self, gctx: &GlobalContext, description: &'static str) {
219        if self.count == 0 {
220            self.is_exclusive = false;
221            self.lock =
222                match gctx
223                    .cargo_home()
224                    .open_ro_shared_create(self.filename, gctx, description)
225                {
226                    Ok(lock) => Some(lock),
227                    Err(e) => {
228                        // There is no error here because locking is mostly a
229                        // best-effort attempt. If cargo home is read-only, we don't
230                        // want to fail just because we couldn't create the lock file.
231                        tracing::warn!("failed to acquire cache lock {}: {e:?}", self.filename);
232                        None
233                    }
234                };
235        }
236        self.increment();
237    }
238
239    /// Acquires a shared lock, returns [`WouldBlock`] if held by another locker.
240    fn lock_shared_nonblocking(&mut self, gctx: &GlobalContext) -> LockingResult {
241        if self.count == 0 {
242            self.is_exclusive = false;
243            self.lock = match gctx.cargo_home().try_open_ro_shared_create(self.filename) {
244                Ok(Some(lock)) => Some(lock),
245                Ok(None) => {
246                    return WouldBlock;
247                }
248                Err(e) => {
249                    // Pretend that the lock was acquired (see lock_shared_blocking).
250                    tracing::warn!("failed to acquire cache lock {}: {e:?}", self.filename);
251                    None
252                }
253            };
254        }
255        self.increment();
256        LockAcquired
257    }
258
259    /// Acquires an exclusive lock.
260    fn lock_exclusive(
261        &mut self,
262        gctx: &GlobalContext,
263        description: &'static str,
264        blocking: BlockingMode,
265    ) -> CargoResult<LockingResult> {
266        if self.count > 0 && !self.is_exclusive {
267            // Lock upgrades are dicey. It might be possible to support
268            // this but would take a bit of work, and so far it isn't
269            // needed.
270            panic!("lock upgrade from shared to exclusive not supported");
271        }
272        match blocking {
273            Blocking => {
274                self.lock_exclusive_blocking(gctx, description)?;
275                Ok(LockAcquired)
276            }
277            NonBlocking => self.lock_exclusive_nonblocking(gctx),
278        }
279    }
280
281    /// Acquires an exclusive lock, blocking if held by another locker.
282    fn lock_exclusive_blocking(
283        &mut self,
284        gctx: &GlobalContext,
285        description: &'static str,
286    ) -> CargoResult<()> {
287        if self.count == 0 {
288            self.is_exclusive = true;
289            match gctx
290                .cargo_home()
291                .open_rw_exclusive_create(self.filename, gctx, description)
292            {
293                Ok(lock) => self.lock = Some(lock),
294                Err(e) => {
295                    if maybe_readonly(&e) {
296                        // This is a best-effort attempt to at least try to
297                        // acquire some sort of lock. This can help in the
298                        // situation where this cargo only has read-only access,
299                        // but maybe some other cargo has read-write. This will at
300                        // least attempt to coordinate with it.
301                        //
302                        // We don't want to fail on a read-only mount because
303                        // cargo grabs an exclusive lock in situations where it
304                        // may only be reading from the package cache. In that
305                        // case, cargo isn't writing anything, and we don't want
306                        // to fail on that.
307                        self.lock_shared_blocking(gctx, description);
308                        // This has to pretend it is exclusive for recursive locks to work.
309                        self.is_exclusive = true;
310                        return Ok(());
311                    } else {
312                        return Err(e).context("failed to acquire package cache lock");
313                    }
314                }
315            }
316        }
317        self.increment();
318        Ok(())
319    }
320
321    /// Acquires an exclusive lock, returns [`WouldBlock`] if held by another locker.
322    fn lock_exclusive_nonblocking(&mut self, gctx: &GlobalContext) -> CargoResult<LockingResult> {
323        if self.count == 0 {
324            self.is_exclusive = true;
325            match gctx
326                .cargo_home()
327                .try_open_rw_exclusive_create(self.filename)
328            {
329                Ok(Some(lock)) => self.lock = Some(lock),
330                Ok(None) => return Ok(WouldBlock),
331                Err(e) => {
332                    if maybe_readonly(&e) {
333                        let result = self.lock_shared_nonblocking(gctx);
334                        // This has to pretend it is exclusive for recursive locks to work.
335                        self.is_exclusive = true;
336                        return Ok(result);
337                    } else {
338                        return Err(e).context("failed to acquire package cache lock");
339                    }
340                }
341            }
342        }
343        self.increment();
344        Ok(LockAcquired)
345    }
346}
347
348/// The state of the [`CacheLocker`].
349#[derive(Debug)]
350struct CacheState {
351    /// The cache lock guards the package cache used for download and
352    /// resolution (append operations that should not interfere with reading
353    /// from existing src files).
354    cache_lock: RecursiveLock,
355    /// The mutate lock is used to either guard the entire package cache for
356    /// destructive modifications (in exclusive mode), or for reading the
357    /// package cache src files (in shared mode).
358    ///
359    /// Note that [`CacheLockMode::MutateExclusive`] holds both
360    /// [`CacheState::mutate_lock`] and [`CacheState::cache_lock`].
361    mutate_lock: RecursiveLock,
362}
363
364impl CacheState {
365    fn lock(
366        &mut self,
367        gctx: &GlobalContext,
368        mode: CacheLockMode,
369        blocking: BlockingMode,
370    ) -> CargoResult<LockingResult> {
371        use CacheLockMode::*;
372        if mode == Shared && self.cache_lock.count > 0 && self.mutate_lock.count == 0 {
373            // Shared lock, when a DownloadExclusive is held.
374            //
375            // This isn't supported because it could cause a deadlock. If
376            // one cargo is attempting to acquire a MutateExclusive lock,
377            // and acquires the mutate lock, but is blocked on the
378            // download lock, and the cargo that holds the download lock
379            // attempts to get a shared lock, they would end up blocking
380            // each other.
381            panic!("shared lock while holding download lock is not allowed");
382        }
383        match mode {
384            Shared => {
385                if self.mutate_lock.lock_shared(gctx, SHARED_DESCR, blocking) == WouldBlock {
386                    return Ok(WouldBlock);
387                }
388            }
389            DownloadExclusive => {
390                if self
391                    .cache_lock
392                    .lock_exclusive(gctx, DOWNLOAD_EXCLUSIVE_DESCR, blocking)?
393                    == WouldBlock
394                {
395                    return Ok(WouldBlock);
396                }
397            }
398            MutateExclusive => {
399                if self
400                    .mutate_lock
401                    .lock_exclusive(gctx, MUTATE_EXCLUSIVE_DESCR, blocking)?
402                    == WouldBlock
403                {
404                    return Ok(WouldBlock);
405                }
406
407                // Part of the contract of MutateExclusive is that it doesn't
408                // allow any processes to have a lock on the package cache, so
409                // this acquires both locks.
410                match self
411                    .cache_lock
412                    .lock_exclusive(gctx, DOWNLOAD_EXCLUSIVE_DESCR, blocking)
413                {
414                    Ok(LockAcquired) => {}
415                    Ok(WouldBlock) => {
416                        self.mutate_lock.decrement();
417                        return Ok(WouldBlock);
418                    }
419                    Err(e) => {
420                        self.mutate_lock.decrement();
421                        return Err(e);
422                    }
423                }
424            }
425        }
426        Ok(LockAcquired)
427    }
428}
429
430/// A held lock guard.
431///
432/// When this is dropped, the lock will be released.
433#[must_use]
434pub struct CacheLock<'lock> {
435    mode: CacheLockMode,
436    locker: &'lock CacheLocker,
437}
438
439impl Drop for CacheLock<'_> {
440    fn drop(&mut self) {
441        use CacheLockMode::*;
442        let mut state = match self.locker.state.lock() {
443            Ok(result) => result,
444            // we should release the cache even if a thread panicked while holding a lock
445            Err(poison) => poison.into_inner(),
446        };
447        match self.mode {
448            Shared => {
449                state.mutate_lock.decrement();
450            }
451            DownloadExclusive => {
452                state.cache_lock.decrement();
453            }
454            MutateExclusive => {
455                state.cache_lock.decrement();
456                state.mutate_lock.decrement();
457            }
458        }
459    }
460}
461
462/// The filename for the [`CacheLockMode::DownloadExclusive`] lock.
463const CACHE_LOCK_NAME: &str = ".package-cache";
464/// The filename for the [`CacheLockMode::MutateExclusive`] and
465/// [`CacheLockMode::Shared`] lock.
466const MUTATE_NAME: &str = ".package-cache-mutate";
467
468// Descriptions that are displayed in the "Blocking" message shown to the user.
469const SHARED_DESCR: &str = "shared package cache";
470const DOWNLOAD_EXCLUSIVE_DESCR: &str = "package cache";
471const MUTATE_EXCLUSIVE_DESCR: &str = "package cache mutation";
472
473/// A locker that can be used to acquire locks.
474///
475/// See the [`crate::util::cache_lock`] module documentation for an overview
476/// of how cache locking works.
477#[derive(Debug)]
478pub struct CacheLocker {
479    /// The state of the locker.
480    ///
481    /// [`CacheLocker`] uses interior mutability because it is stuffed inside
482    /// [`GlobalContext`], which does not allow mutation.
483    state: Mutex<CacheState>,
484}
485
486impl CacheLocker {
487    /// Creates a new `CacheLocker`.
488    pub fn new() -> CacheLocker {
489        CacheLocker {
490            state: CacheState {
491                cache_lock: RecursiveLock::new(CACHE_LOCK_NAME),
492                mutate_lock: RecursiveLock::new(MUTATE_NAME),
493            }
494            .into(),
495        }
496    }
497
498    /// Acquires a lock with the given mode, possibly blocking if another
499    /// cargo is holding the lock.
500    pub fn lock(&self, gctx: &GlobalContext, mode: CacheLockMode) -> CargoResult<CacheLock<'_>> {
501        let mut state = self.state.lock().unwrap();
502        let _ = state.lock(gctx, mode, Blocking)?;
503        Ok(CacheLock { mode, locker: self })
504    }
505
506    /// Acquires a lock with the given mode, returning `None` if another cargo
507    /// is holding the lock.
508    pub fn try_lock(
509        &self,
510        gctx: &GlobalContext,
511        mode: CacheLockMode,
512    ) -> CargoResult<Option<CacheLock<'_>>> {
513        let mut state = self.state.lock().unwrap();
514        if state.lock(gctx, mode, NonBlocking)? == LockAcquired {
515            Ok(Some(CacheLock { mode, locker: self }))
516        } else {
517            Ok(None)
518        }
519    }
520
521    /// Returns whether or not a lock is held for the given mode in this locker.
522    ///
523    /// This does not tell you whether or not it is locked in some other
524    /// locker (such as in another process).
525    ///
526    /// Note that `Shared` will return true if a `MutateExclusive` lock is
527    /// held, since `MutateExclusive` is just an upgraded `Shared`. Likewise,
528    /// `DownloadExclusive` will return true if a `MutateExclusive` lock is
529    /// held since they overlap.
530    pub fn is_locked(&self, mode: CacheLockMode) -> bool {
531        let state = self.state.lock().unwrap();
532        match (
533            mode,
534            state.cache_lock.count,
535            state.mutate_lock.count,
536            state.mutate_lock.is_exclusive,
537        ) {
538            (CacheLockMode::Shared, _, 1.., _) => true,
539            (CacheLockMode::MutateExclusive, _, 1.., true) => true,
540            (CacheLockMode::DownloadExclusive, 1.., _, _) => true,
541            _ => false,
542        }
543    }
544}
545
546/// Returns whether or not the error appears to be from a read-only filesystem.
547fn maybe_readonly(err: &anyhow::Error) -> bool {
548    err.chain().any(|err| {
549        if let Some(io) = err.downcast_ref::<io::Error>() {
550            if io.kind() == io::ErrorKind::PermissionDenied {
551                return true;
552            }
553
554            #[cfg(unix)]
555            return io.raw_os_error() == Some(libc::EROFS);
556        }
557
558        false
559    })
560}