|
| 1 | +//! Inter-process locking on the Volta directory |
| 2 | +//! |
| 3 | +//! To avoid issues where multiple separate invocations of Volta modify the |
| 4 | +//! data directory simultaneously, we provide a locking mechanism that only |
| 5 | +//! allows a single process to modify the directory at a time. |
| 6 | +//! |
| 7 | +//! However, within a single process, we may attempt to lock the directory in |
| 8 | +//! different code paths. For example, when installing a package we require a |
| 9 | +//! lock, however we also may need to install Node, which requires a lock as |
| 10 | +//! well. To avoid deadlocks in those situations, we track the state of the |
| 11 | +//! lock globally: |
| 12 | +//! |
| 13 | +//! - If a lock is requested and no locks are active, then we acquire a file |
| 14 | +//! lock on the `volta.lock` file and initialize the state with a count of 1 |
| 15 | +//! - If a lock already exists, then we increment the count of active locks |
| 16 | +//! - When a lock is no longer needed, we decrement the count of active locks |
| 17 | +//! - When the last lock is released, we release the file lock and clear the |
| 18 | +//! global lock state. |
| 19 | +//! |
| 20 | +//! This allows multiple code paths to request a lock and not worry about |
| 21 | +//! potential deadlocks, while still preventing multiple processes from making |
| 22 | +//! concurrent changes. |
| 23 | +
|
1 | 24 | use std::fs::{File, OpenOptions}; |
| 25 | +use std::marker::PhantomData; |
2 | 26 | use std::ops::Drop; |
3 | | -use std::path::Path; |
| 27 | +use std::sync::Mutex; |
4 | 28 |
|
| 29 | +use crate::error::{Context, ErrorKind, Fallible}; |
| 30 | +use crate::layout::volta_home; |
5 | 31 | use crate::style::progress_spinner; |
6 | 32 | use fs2::FileExt; |
| 33 | +use lazy_static::lazy_static; |
7 | 34 | use log::debug; |
8 | 35 |
|
| 36 | +lazy_static! { |
| 37 | + static ref LOCK_STATE: Mutex<Option<LockState>> = Mutex::new(None); |
| 38 | +} |
| 39 | + |
| 40 | +/// The current state of locks for this process. |
| 41 | +/// |
| 42 | +/// Note: To ensure thread safety _within_ this process, we enclose the |
| 43 | +/// state in a Mutex. This Mutex and it's associated locks are separate |
| 44 | +/// from the overall process lock and are only used to ensure the count |
| 45 | +/// is accurately maintained within a given process. |
| 46 | +struct LockState { |
| 47 | + file: File, |
| 48 | + count: usize, |
| 49 | +} |
| 50 | + |
9 | 51 | const LOCK_FILE: &str = "volta.lock"; |
10 | 52 |
|
11 | | -/// An RAII implementation of an exclusive lock on the Volta directory. When this falls out of scope, |
12 | | -/// the lock will be unlocked. |
| 53 | +/// An RAII implementation of a process lock on the Volta directory. A given Volta process can have |
| 54 | +/// multiple active locks, but only one process can have any locks at a time. |
| 55 | +/// |
| 56 | +/// Once all of the `VoltaLock` objects go out of scope, the lock will be released to other |
| 57 | +/// processes. |
13 | 58 | pub struct VoltaLock { |
14 | | - inner: File, |
| 59 | + // Private field ensures that this cannot be created except for with the `acquire()` method |
| 60 | + _private: PhantomData<()>, |
15 | 61 | } |
16 | 62 |
|
17 | 63 | impl VoltaLock { |
18 | | - pub fn acquire(volta_home: &Path) -> std::io::Result<Self> { |
19 | | - let path = volta_home.join(LOCK_FILE); |
20 | | - debug!("Acquiring lock on Volta directory: {}", path.display()); |
21 | | - |
22 | | - let file = OpenOptions::new().write(true).create(true).open(path)?; |
23 | | - // First we try to lock the file without blocking. If that fails, then we show a spinner |
24 | | - // and block until the lock completes. |
25 | | - if file.try_lock_exclusive().is_err() { |
26 | | - let spinner = progress_spinner("Waiting for file lock on Volta directory"); |
27 | | - // Note: Blocks until the file can be locked |
28 | | - let lock_result = file.lock_exclusive(); |
29 | | - spinner.finish_and_clear(); |
30 | | - lock_result?; |
| 64 | + pub fn acquire() -> Fallible<Self> { |
| 65 | + let mut state = LOCK_STATE |
| 66 | + .lock() |
| 67 | + .with_context(|| ErrorKind::LockAcquireError)?; |
| 68 | + |
| 69 | + // Check if there is an active lock for this process. If so, increment |
| 70 | + // the count of active locks. If not, create a file lock and initialize |
| 71 | + // the state with a count of 1 |
| 72 | + match &mut *state { |
| 73 | + Some(inner) => { |
| 74 | + inner.count += 1; |
| 75 | + } |
| 76 | + None => { |
| 77 | + let path = volta_home()?.root().join(LOCK_FILE); |
| 78 | + debug!("Acquiring lock on Volta directory: {}", path.display()); |
| 79 | + |
| 80 | + let file = OpenOptions::new() |
| 81 | + .write(true) |
| 82 | + .create(true) |
| 83 | + .open(path) |
| 84 | + .with_context(|| ErrorKind::LockAcquireError)?; |
| 85 | + // First we try to lock the file without blocking. If that fails, then we show a spinner |
| 86 | + // and block until the lock completes. |
| 87 | + if file.try_lock_exclusive().is_err() { |
| 88 | + let spinner = progress_spinner("Waiting for file lock on Volta directory"); |
| 89 | + // Note: Blocks until the file can be locked |
| 90 | + let lock_result = file |
| 91 | + .lock_exclusive() |
| 92 | + .with_context(|| ErrorKind::LockAcquireError); |
| 93 | + spinner.finish_and_clear(); |
| 94 | + lock_result?; |
| 95 | + } |
| 96 | + |
| 97 | + *state = Some(LockState { file, count: 1 }); |
| 98 | + } |
31 | 99 | } |
32 | 100 |
|
33 | | - Ok(Self { inner: file }) |
| 101 | + Ok(Self { |
| 102 | + _private: PhantomData, |
| 103 | + }) |
34 | 104 | } |
35 | 105 | } |
36 | 106 |
|
37 | 107 | impl Drop for VoltaLock { |
38 | | - #[allow(unused_must_use)] |
39 | 108 | fn drop(&mut self) { |
40 | | - self.inner.unlock(); |
| 109 | + // On drop, decrement the count of active locks. If the count is 1, |
| 110 | + // then this is the last active lock, so instead unlock the file and |
| 111 | + // clear out the lock state. |
| 112 | + if let Ok(mut state) = LOCK_STATE.lock() { |
| 113 | + match &mut *state { |
| 114 | + Some(inner) => { |
| 115 | + if inner.count == 1 { |
| 116 | + debug!("Unlocking Volta Directory"); |
| 117 | + let _ = inner.file.unlock(); |
| 118 | + *state = None; |
| 119 | + } else { |
| 120 | + inner.count -= 1; |
| 121 | + } |
| 122 | + } |
| 123 | + None => { |
| 124 | + debug!("Unexpected unlock of Volta directory when it wasn't locked"); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
41 | 128 | } |
42 | 129 | } |
0 commit comments