1use std::fs::{self, OpenOptions};
48use std::io::Write;
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::thread::JoinHandle;
53use std::time::{Duration, SystemTime, UNIX_EPOCH};
54
55use anyhow::{Context, Result, anyhow};
56use serde::{Deserialize, Serialize};
57
58use super::atomic::atomic_write_bytes;
59
60pub const LOCK_FILENAME: &str = ".rgstore.lock";
62
63pub const STALE_LOCK_PREFIX: &str = ".rgstore.lock.stale.";
65
66pub const BREAK_FILENAME: &str = ".rgstore.lock.break";
68
69const BREAK_STALE_AFTER: Duration = Duration::from_secs(60);
72
73const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
75
76const HEARTBEAT_TICK: Duration = Duration::from_millis(100);
79
80const DEFAULT_TIMEOUT_SECS: u64 = 30 * 60;
81const DEFAULT_STALE_AFTER_SECS: u64 = 120;
82
83const BACKOFF_START: Duration = Duration::from_millis(50);
84const BACKOFF_MAX: Duration = Duration::from_secs(5);
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct LockInfo {
89 pub pid: u32,
90 pub hostname: String,
91 pub started_at: String,
93 pub heartbeat_at: String,
95 pub heartbeat_epoch: u64,
98 pub operation: String,
100 pub gtars_version: String,
101}
102
103impl LockInfo {
104 fn new(operation: &str) -> Self {
105 let now = chrono::Utc::now().to_rfc3339();
106 LockInfo {
107 pid: std::process::id(),
108 hostname: hostname(),
109 started_at: now.clone(),
110 heartbeat_at: now,
111 heartbeat_epoch: epoch_secs(),
112 operation: operation.to_string(),
113 gtars_version: env!("CARGO_PKG_VERSION").to_string(),
114 }
115 }
116
117 pub fn describe(&self) -> String {
119 format!(
120 "pid {} on {} (operation={}, gtars {}, since {})",
121 self.pid, self.hostname, self.operation, self.gtars_version, self.started_at
122 )
123 }
124}
125
126#[derive(Debug, Clone)]
132pub struct LockOptions {
133 pub timeout: Option<Duration>,
135 pub stale_after: Duration,
137 pub force: bool,
140}
141
142impl Default for LockOptions {
143 fn default() -> Self {
144 LockOptions {
145 timeout: env_secs("GTARS_STORE_LOCK_TIMEOUT")
146 .unwrap_or(Some(Duration::from_secs(DEFAULT_TIMEOUT_SECS))),
147 stale_after: env_secs("GTARS_STORE_LOCK_STALE_AFTER")
148 .flatten()
149 .unwrap_or(Duration::from_secs(DEFAULT_STALE_AFTER_SECS)),
150 force: false,
151 }
152 }
153}
154
155impl LockOptions {
156 pub fn non_blocking() -> Self {
158 LockOptions {
159 timeout: Some(Duration::ZERO),
160 ..Default::default()
161 }
162 }
163
164 #[must_use]
165 pub fn timeout_secs(mut self, secs: u64) -> Self {
166 self.timeout = if secs == 0 {
167 None
168 } else {
169 Some(Duration::from_secs(secs))
170 };
171 self
172 }
173
174 #[must_use]
175 pub fn force(mut self, force: bool) -> Self {
176 self.force = force;
177 self
178 }
179}
180
181pub struct StoreLock {
183 path: PathBuf,
184 info: LockInfo,
185 stop: Arc<AtomicBool>,
186 heartbeat: Option<JoinHandle<()>>,
187}
188
189impl std::fmt::Debug for StoreLock {
190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191 f.debug_struct("StoreLock")
192 .field("path", &self.path)
193 .field("pid", &self.info.pid)
194 .field("operation", &self.info.operation)
195 .finish()
196 }
197}
198
199impl StoreLock {
200 pub fn lock_path(store_dir: &Path) -> PathBuf {
202 store_dir.join(LOCK_FILENAME)
203 }
204
205 pub fn acquire(store_dir: &Path, operation: &str, opts: LockOptions) -> Result<Self> {
208 let path = Self::lock_path(store_dir);
209 fs::create_dir_all(store_dir)
210 .with_context(|| format!("creating store directory {:?} for locking", store_dir))?;
211
212 if opts.force {
213 steal(&path)?;
214 }
215
216 let deadline = opts.timeout.map(|t| SystemTime::now() + t);
217 let mut backoff = BACKOFF_START;
218
219 loop {
220 match try_create(&path, operation) {
221 Ok(Some(info)) => {
222 let stop = Arc::new(AtomicBool::new(false));
223 let heartbeat = spawn_heartbeat(path.clone(), info.clone(), stop.clone());
224 return Ok(StoreLock {
225 path,
226 info,
227 stop,
228 heartbeat: Some(heartbeat),
229 });
230 }
231 Ok(None) => {} Err(e) => return Err(e),
233 }
234
235 match read_info(&path) {
237 Ok(Some(holder)) => {
238 if let Some(reason) = staleness(&path, &holder, opts.stale_after) {
239 eprintln!(
240 "warning: breaking stale RefgetStore lock {:?}: {} ({})",
241 path,
242 holder.describe(),
243 reason
244 );
245 let _ = break_stale(&path, &holder);
248 continue;
249 }
250 if deadline.is_some_and(|d| SystemTime::now() >= d) {
251 return Err(anyhow!(
252 "timed out waiting for the RefgetStore write lock at {:?}, \
253 held by {}. If that writer is gone, clear it with \
254 `gtars refget lock-status <store> --force-unlock`, or raise \
255 GTARS_STORE_LOCK_TIMEOUT.",
256 path,
257 holder.describe()
258 ));
259 }
260 }
261 Ok(None) | Err(_) => {
265 if mtime_age(&path).is_none_or(|age| age > opts.stale_after) {
266 eprintln!(
267 "warning: breaking unreadable RefgetStore lock {:?} (no valid payload)",
268 path
269 );
270 let _ = break_unreadable(&path, opts.stale_after);
271 continue;
272 }
273 if deadline.is_some_and(|d| SystemTime::now() >= d) {
274 return Err(anyhow!(
275 "timed out waiting for the RefgetStore write lock at {:?} \
276 (lockfile payload unreadable)",
277 path
278 ));
279 }
280 }
281 }
282
283 std::thread::sleep(backoff);
284 backoff = std::cmp::min(backoff * 2, BACKOFF_MAX);
285 }
286 }
287
288 pub fn try_acquire(store_dir: &Path, operation: &str) -> Result<Option<Self>> {
290 match Self::acquire(store_dir, operation, LockOptions::non_blocking()) {
291 Ok(lock) => Ok(Some(lock)),
292 Err(_) => Ok(None),
293 }
294 }
295
296 pub fn info(&self) -> &LockInfo {
298 &self.info
299 }
300}
301
302impl Drop for StoreLock {
303 fn drop(&mut self) {
304 self.stop.store(true, Ordering::Relaxed);
305 if let Some(handle) = self.heartbeat.take() {
306 let _ = handle.join();
307 }
308 if let Ok(Some(current)) = read_info(&self.path) {
312 if current.pid != self.info.pid || current.hostname != self.info.hostname {
313 return;
314 }
315 }
316 let _ = fs::remove_file(&self.path);
317 }
318}
319
320pub fn lock_status(store_dir: &Path) -> Result<Option<LockInfo>> {
326 read_info(&StoreLock::lock_path(store_dir))
327}
328
329pub fn force_unlock(store_dir: &Path) -> Result<bool> {
332 let path = StoreLock::lock_path(store_dir);
333 let existed = path.exists();
334 if existed {
335 steal(&path)?;
336 }
337 if let Ok(entries) = fs::read_dir(store_dir) {
339 for entry in entries.filter_map(|e| e.ok()) {
340 if entry
341 .file_name()
342 .to_str()
343 .is_some_and(|n| n.starts_with(STALE_LOCK_PREFIX) || n == BREAK_FILENAME)
344 {
345 let _ = fs::remove_file(entry.path());
346 }
347 }
348 }
349 Ok(existed)
350}
351
352fn try_create(path: &Path, operation: &str) -> Result<Option<LockInfo>> {
358 match OpenOptions::new().write(true).create_new(true).open(path) {
359 Ok(mut file) => {
360 let info = LockInfo::new(operation);
361 let json = serde_json::to_vec_pretty(&info)?;
362 file.write_all(&json)?;
366 file.sync_all()?;
367 Ok(Some(info))
368 }
369 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
370 Err(e) => Err(e).with_context(|| format!("creating lockfile {:?}", path)),
371 }
372}
373
374fn read_info(path: &Path) -> Result<Option<LockInfo>> {
375 match fs::read_to_string(path) {
376 Ok(s) => Ok(serde_json::from_str(&s).ok()),
377 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
378 Err(e) => Err(e).with_context(|| format!("reading lockfile {:?}", path)),
379 }
380}
381
382fn steal(path: &Path) -> Result<()> {
391 let dir = path.parent().unwrap_or_else(|| Path::new("."));
392 let stolen = dir.join(format!(
393 "{}{}.{}",
394 STALE_LOCK_PREFIX,
395 std::process::id(),
396 nanos()
397 ));
398 match fs::rename(path, &stolen) {
399 Ok(()) => {
400 let _ = fs::remove_file(&stolen);
401 Ok(())
402 }
403 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
406 Err(e) => Err(e).with_context(|| format!("stealing stale lockfile {:?}", path)),
407 }
408}
409
410struct BreakClaim(PathBuf);
412
413impl Drop for BreakClaim {
414 fn drop(&mut self) {
415 let _ = fs::remove_file(&self.0);
416 }
417}
418
419fn claim_break(path: &Path) -> Result<Option<BreakClaim>> {
425 let dir = path.parent().unwrap_or_else(|| Path::new("."));
426 let marker = dir.join(BREAK_FILENAME);
427 match OpenOptions::new().write(true).create_new(true).open(&marker) {
428 Ok(mut f) => {
429 let _ = write!(f, "{} {}", std::process::id(), hostname());
430 Ok(Some(BreakClaim(marker)))
431 }
432 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
433 if mtime_age(&marker).is_some_and(|age| age > BREAK_STALE_AFTER) {
434 let dead = dir.join(format!("{}break.{}.{}", STALE_LOCK_PREFIX, std::process::id(), nanos()));
435 if fs::rename(&marker, &dead).is_ok() {
436 let _ = fs::remove_file(&dead);
437 }
438 }
439 Ok(None)
440 }
441 Err(e) => Err(e).with_context(|| format!("creating break marker {:?}", marker)),
442 }
443}
444
445fn break_stale(path: &Path, judged: &LockInfo) -> Result<()> {
450 let Some(_claim) = claim_break(path)? else {
451 return Ok(());
452 };
453 match read_info(path)? {
454 Some(current)
455 if current.pid == judged.pid
456 && current.hostname == judged.hostname
457 && current.started_at == judged.started_at =>
458 {
459 steal(path)
460 }
461 _ => Ok(()),
463 }
464}
465
466fn break_unreadable(path: &Path, stale_after: Duration) -> Result<()> {
469 let Some(_claim) = claim_break(path)? else {
470 return Ok(());
471 };
472 match read_info(path)? {
473 Some(_) => Ok(()), None => {
475 if mtime_age(path).is_none_or(|age| age > stale_after) {
476 steal(path)
477 } else {
478 Ok(())
479 }
480 }
481 }
482}
483
484fn staleness(path: &Path, holder: &LockInfo, stale_after: Duration) -> Option<String> {
486 if holder.hostname == hostname() && !pid_alive(holder.pid) {
488 return Some(format!("pid {} is not running on this host", holder.pid));
489 }
490
491 let now = epoch_secs();
494 let heartbeat_age = Duration::from_secs(now.saturating_sub(holder.heartbeat_epoch));
495 let file_age = mtime_age(path)?;
496 if heartbeat_age > stale_after && file_age > stale_after {
497 return Some(format!(
498 "no heartbeat for {}s (threshold {}s)",
499 heartbeat_age.as_secs(),
500 stale_after.as_secs()
501 ));
502 }
503 None
504}
505
506fn mtime_age(path: &Path) -> Option<Duration> {
508 let modified = fs::metadata(path).ok()?.modified().ok()?;
509 SystemTime::now().duration_since(modified).ok()
510}
511
512#[cfg(target_os = "linux")]
513fn pid_alive(pid: u32) -> bool {
514 Path::new(&format!("/proc/{}", pid)).exists()
515}
516
517#[cfg(not(target_os = "linux"))]
520fn pid_alive(_pid: u32) -> bool {
521 true
522}
523
524fn hostname() -> String {
525 for path in ["/proc/sys/kernel/hostname", "/etc/hostname"] {
526 if let Ok(s) = fs::read_to_string(path) {
527 let s = s.trim();
528 if !s.is_empty() {
529 return s.to_string();
530 }
531 }
532 }
533 for var in ["HOSTNAME", "COMPUTERNAME"] {
534 if let Ok(s) = std::env::var(var) {
535 if !s.is_empty() {
536 return s;
537 }
538 }
539 }
540 "unknown-host".to_string()
541}
542
543fn epoch_secs() -> u64 {
544 SystemTime::now()
545 .duration_since(UNIX_EPOCH)
546 .map(|d| d.as_secs())
547 .unwrap_or(0)
548}
549
550fn nanos() -> u128 {
551 SystemTime::now()
552 .duration_since(UNIX_EPOCH)
553 .map(|d| d.as_nanos())
554 .unwrap_or(0)
555}
556
557fn env_secs(var: &str) -> Option<Option<Duration>> {
560 let raw = std::env::var(var).ok()?;
561 let secs: u64 = raw.trim().parse().ok()?;
562 Some(if secs == 0 {
563 None
564 } else {
565 Some(Duration::from_secs(secs))
566 })
567}
568
569fn spawn_heartbeat(path: PathBuf, info: LockInfo, stop: Arc<AtomicBool>) -> JoinHandle<()> {
574 std::thread::spawn(move || {
575 let mut elapsed = Duration::ZERO;
576 while !stop.load(Ordering::Relaxed) {
577 std::thread::sleep(HEARTBEAT_TICK);
578 elapsed += HEARTBEAT_TICK;
579 if elapsed < HEARTBEAT_INTERVAL {
580 continue;
581 }
582 elapsed = Duration::ZERO;
583
584 match read_info(&path) {
585 Ok(Some(current))
586 if current.pid == info.pid && current.hostname == info.hostname => {}
587 _ => return,
589 }
590
591 let mut refreshed = info.clone();
592 refreshed.heartbeat_at = chrono::Utc::now().to_rfc3339();
593 refreshed.heartbeat_epoch = epoch_secs();
594 if let Ok(json) = serde_json::to_vec_pretty(&refreshed) {
595 let _ = atomic_write_bytes(&path, &json);
596 }
597 }
598 })
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn acquire_and_release() {
607 let dir = tempfile::tempdir().unwrap();
608 let path = StoreLock::lock_path(dir.path());
609 {
610 let lock = StoreLock::acquire(dir.path(), "test", LockOptions::default()).unwrap();
611 assert!(path.exists());
612 assert_eq!(lock.info().operation, "test");
613 assert!(lock_status(dir.path()).unwrap().is_some());
614 }
615 assert!(!path.exists());
616 assert!(lock_status(dir.path()).unwrap().is_none());
617 }
618
619 #[test]
620 fn second_acquire_times_out_while_first_is_held() {
621 let dir = tempfile::tempdir().unwrap();
622 let _held = StoreLock::acquire(dir.path(), "first", LockOptions::default()).unwrap();
623
624 let err = StoreLock::acquire(
625 dir.path(),
626 "second",
627 LockOptions::default().timeout_secs(1),
628 );
629 assert!(err.is_err());
630 let msg = err.unwrap_err().to_string();
631 assert!(msg.contains("timed out"), "unexpected error: {}", msg);
632 assert!(msg.contains("first"), "error should name the holder: {}", msg);
633 }
634
635 #[test]
636 fn stale_lock_from_dead_pid_on_this_host_is_broken() {
637 let dir = tempfile::tempdir().unwrap();
638 let path = StoreLock::lock_path(dir.path());
639
640 let dead_pid = 4_194_305u32;
642 let mut info = LockInfo::new("abandoned");
643 info.pid = dead_pid;
644 info.hostname = hostname();
645 fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
646
647 let lock = StoreLock::acquire(dir.path(), "recovering", LockOptions::default()).unwrap();
649 assert_eq!(lock.info().pid, std::process::id());
650 }
651
652 #[test]
653 fn old_heartbeat_from_another_host_is_presumed_stale() {
654 let dir = tempfile::tempdir().unwrap();
655 let path = StoreLock::lock_path(dir.path());
656
657 let mut info = LockInfo::new("remote");
658 info.hostname = "some-other-node".to_string();
659 info.heartbeat_epoch = epoch_secs().saturating_sub(10_000);
660 fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
661 let backdated = SystemTime::now() - Duration::from_secs(10_000);
663 let f = fs::File::open(&path).unwrap();
664 f.set_modified(backdated).unwrap();
665 drop(f);
666
667 let opts = LockOptions {
668 stale_after: Duration::from_secs(120),
669 ..LockOptions::default()
670 };
671 let lock = StoreLock::acquire(dir.path(), "taking-over", opts).unwrap();
672 assert_eq!(lock.info().hostname, hostname());
673 }
674
675 #[test]
676 fn live_remote_holder_is_not_broken() {
677 let dir = tempfile::tempdir().unwrap();
678 let path = StoreLock::lock_path(dir.path());
679
680 let mut info = LockInfo::new("remote");
681 info.hostname = "some-other-node".to_string();
682 fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
683
684 let result = StoreLock::acquire(
685 dir.path(),
686 "contender",
687 LockOptions::default().timeout_secs(1),
688 );
689 assert!(result.is_err(), "a live remote holder must not be broken");
690 }
691
692 #[test]
693 fn force_unlock_clears_a_held_lock() {
694 let dir = tempfile::tempdir().unwrap();
695 let mut info = LockInfo::new("remote");
696 info.hostname = "some-other-node".to_string();
697 fs::write(
698 StoreLock::lock_path(dir.path()),
699 serde_json::to_vec_pretty(&info).unwrap(),
700 )
701 .unwrap();
702
703 assert!(force_unlock(dir.path()).unwrap());
704 assert!(lock_status(dir.path()).unwrap().is_none());
705 assert!(!force_unlock(dir.path()).unwrap());
707 }
708
709 #[test]
710 fn drop_does_not_remove_a_lock_another_writer_took_over() {
711 let dir = tempfile::tempdir().unwrap();
712 let path = StoreLock::lock_path(dir.path());
713 let lock = StoreLock::acquire(dir.path(), "original", LockOptions::default()).unwrap();
714
715 let mut other = LockInfo::new("takeover");
717 other.pid = lock.info().pid + 1;
718 fs::write(&path, serde_json::to_vec_pretty(&other).unwrap()).unwrap();
719
720 drop(lock);
721 let remaining = lock_status(dir.path()).unwrap().expect("lock was clobbered");
722 assert_eq!(remaining.operation, "takeover");
723 }
724}