Skip to main content

bark_cli/
connection.rs

1//! The barkd single-instance guarantee: `barkd.lock`, exclusively locked
2//! for the process lifetime. The wallet's `LOCK` can't serve here, since
3//! it is only taken once a wallet is open.
4
5use std::fs::{self, File, TryLockError};
6use std::io::Read;
7use std::path::Path;
8
9use anyhow::{bail, Context};
10
11use bark::lock_manager::PidLockError;
12use bark::lock_manager::pid_flock::FlockPidLockManager;
13
14use crate::wallet::AUTH_TOKEN_FILE;
15
16/// File in the datadir exclusively locked for the lifetime of a barkd process.
17pub const BARKD_LOCK_FILE: &str = "barkd.lock";
18
19/// File in the datadir carrying the base URL the barkd holding the lock
20/// listens on. Only meaningful while the lock is held.
21pub const BARKD_URL_FILE: &str = "barkd.url";
22
23/// Record the base URL this barkd listens on, so that clients on the same
24/// datadir connect to it instead of the default listen address.
25pub fn store_barkd_url(datadir: &Path, url: &str) -> anyhow::Result<()> {
26	let path = datadir.join(BARKD_URL_FILE);
27	fs::write(&path, url).with_context(|| format!("failed to write {}", path.display()))
28}
29
30/// The base URL recorded by the barkd on this datadir, if any.
31pub fn barkd_url(datadir: &Path) -> anyhow::Result<Option<String>> {
32	let path = datadir.join(BARKD_URL_FILE);
33	match fs::read_to_string(&path) {
34		Ok(url) => {
35			let url = url.trim();
36			Ok(if url.is_empty() { None } else { Some(url.to_string()) })
37		},
38		Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
39		Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
40	}
41}
42
43/// Remove everything in the datadir except the running barkd's own files,
44/// so the held lock, auth token and listen URL survive a wallet wipe.
45pub fn wipe_datadir_except_barkd_files(datadir: &Path) -> anyhow::Result<()> {
46	let barkd_files = [BARKD_LOCK_FILE, AUTH_TOKEN_FILE, BARKD_URL_FILE];
47	for entry in fs::read_dir(datadir).context("failed to list datadir")? {
48		let entry = entry?;
49		if barkd_files.iter().any(|k| entry.file_name() == *k) {
50			continue;
51		}
52		let path = entry.path();
53		if entry.file_type()?.is_dir() {
54			fs::remove_dir_all(&path)
55		} else {
56			fs::remove_file(&path)
57		}.with_context(|| format!("failed to remove {}", path.display()))?;
58	}
59	Ok(())
60}
61
62/// The pid of the barkd holding the datadir lock, or `None` when no barkd
63/// is running there. The flock, not the file's existence, is the liveness
64/// signal: the OS releases it the instant the holder dies.
65pub fn barkd_pid(datadir: &Path) -> anyhow::Result<Option<u32>> {
66	let path = datadir.join(BARKD_LOCK_FILE);
67	let mut file = match File::open(&path) {
68		Ok(f) => f,
69		Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
70		Err(e) => return Err(e).with_context(|| {
71			format!("failed to open lock file {}", path.display())
72		}),
73	};
74
75	match file.try_lock() {
76		// We got the lock, so no barkd holds it; ours releases with `file`.
77		Ok(()) => Ok(None),
78		Err(TryLockError::WouldBlock) => {
79			let mut holder = String::new();
80			file.read_to_string(&mut holder).context("failed to read barkd lock")?;
81			let pid = holder.trim().parse::<u32>()
82				.context("barkd is running but its lock file carries no pid")?;
83			Ok(Some(pid))
84		},
85		Err(TryLockError::Error(e)) => {
86			Err(anyhow::Error::from(e)).with_context(|| {
87				format!("failed to probe barkd lock at {}", path.display())
88			})
89		},
90	}
91}
92
93/// Take the exclusive barkd lock on the datadir, or fail fast when another
94/// barkd already runs there. The OS releases the lock when the returned value
95/// is dropped or the process exits, even on SIGKILL or a crash.
96pub fn acquire_barkd_lock(datadir: &Path) -> anyhow::Result<FlockPidLockManager> {
97	match FlockPidLockManager::new_with_lock_file(datadir, BARKD_LOCK_FILE) {
98		Ok(lock) => Ok(lock),
99		Err(PidLockError::AlreadyHeld { datadir, pid }) => match pid {
100			Some(pid) => bail!(
101				"another barkd is already running on datadir {} (pid {})",
102				datadir.display(), pid,
103			),
104			None => bail!(
105				"another barkd is already running on datadir {}",
106				datadir.display(),
107			),
108		},
109		Err(e) => Err(e).context("failed to acquire barkd lock"),
110	}
111}
112
113#[cfg(test)]
114mod test {
115	use super::*;
116
117	fn tmp_dir() -> std::path::PathBuf {
118		let dir = std::env::temp_dir()
119			.join(format!("bark-connection-{}", std::process::id()))
120			.join(format!("{}", std::time::SystemTime::now()
121				.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
122		fs::create_dir_all(&dir).unwrap();
123		dir
124	}
125
126	#[test]
127	fn wipe_keeps_barkd_files() {
128		let dir = tmp_dir();
129		let _lock = acquire_barkd_lock(&dir).unwrap();
130		fs::write(dir.join(AUTH_TOKEN_FILE), "tok").unwrap();
131		store_barkd_url(&dir, "http://127.0.0.1:3001").unwrap();
132		fs::write(dir.join("db.sqlite"), "x").unwrap();
133		fs::create_dir(dir.join("sub")).unwrap();
134		fs::write(dir.join("sub").join("f"), "y").unwrap();
135
136		wipe_datadir_except_barkd_files(&dir).unwrap();
137
138		assert!(dir.join(BARKD_LOCK_FILE).exists());
139		assert!(dir.join(AUTH_TOKEN_FILE).exists());
140		assert!(dir.join(BARKD_URL_FILE).exists());
141		assert!(!dir.join("db.sqlite").exists());
142		assert!(!dir.join("sub").exists());
143
144		let _ = fs::remove_dir_all(&dir);
145	}
146
147	#[test]
148	fn barkd_url_roundtrip() {
149		let dir = tmp_dir();
150		assert_eq!(barkd_url(&dir).unwrap(), None, "no url file yet");
151
152		store_barkd_url(&dir, "http://127.0.0.1:3001").unwrap();
153		assert_eq!(barkd_url(&dir).unwrap().as_deref(), Some("http://127.0.0.1:3001"));
154
155		let _ = fs::remove_dir_all(&dir);
156	}
157
158	#[test]
159	fn barkd_pid_reflects_lock_state() {
160		let dir = tmp_dir();
161		assert_eq!(barkd_pid(&dir).unwrap(), None, "no lock file yet");
162
163		let held = acquire_barkd_lock(&dir).unwrap();
164		assert_eq!(barkd_pid(&dir).unwrap(), Some(std::process::id()));
165
166		// The file outlives the holder; only the flock signals liveness.
167		drop(held);
168		assert_eq!(barkd_pid(&dir).unwrap(), None);
169
170		let _ = fs::remove_dir_all(&dir);
171	}
172
173	#[test]
174	fn barkd_lock_refuses_second_holder() {
175		let dir = tmp_dir();
176		let held = acquire_barkd_lock(&dir).unwrap();
177
178		// flock is per open file description, so a second open in the same
179		// process conflicts just like another process would.
180		let err = acquire_barkd_lock(&dir).unwrap_err();
181		assert!(
182			err.to_string().contains("another barkd is already running"),
183			"unexpected error: {}", err,
184		);
185		assert!(err.to_string().contains(&std::process::id().to_string()));
186
187		drop(held);
188		let _reacquired = acquire_barkd_lock(&dir).unwrap();
189
190		let _ = fs::remove_dir_all(&dir);
191	}
192}