blyte_agent/
folder_lock.rs1use std::path::Path;
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Holder {
9 pub pid: u32,
10 pub kind: String,
11 pub id: String,
12}
13
14#[derive(Debug)]
15pub struct FolderLock {
16 #[cfg(unix)]
17 _file: std::fs::File,
18}
19
20#[cfg(unix)]
21fn read_holder(file: &mut std::fs::File) -> Result<Holder, String> {
22 use std::io::{Read, Seek, SeekFrom};
23
24 file.seek(SeekFrom::Start(0))
25 .map_err(|e| format!("cannot seek lock file: {e}"))?;
26 let mut text = String::new();
27 file.read_to_string(&mut text)
28 .map_err(|e| format!("cannot read lock file: {e}"))?;
29 let first_line = text.lines().next().unwrap_or("");
30 serde_json::from_str(first_line).map_err(|e| format!("cannot parse lock holder: {e}"))
31}
32
33#[cfg(unix)]
34pub fn acquire(lock_path: &Path, holder: &Holder) -> Result<FolderLock, String> {
35 use std::io::{Seek, SeekFrom, Write};
36 use std::os::unix::io::AsRawFd;
37
38 if let Some(parent) = lock_path.parent() {
39 if !parent.as_os_str().is_empty() {
40 std::fs::create_dir_all(parent)
41 .map_err(|e| format!("cannot create lock directory {}: {e}", parent.display()))?;
42 }
43 }
44 let mut file = std::fs::OpenOptions::new()
45 .read(true)
46 .write(true)
47 .create(true)
48 .truncate(false)
49 .open(lock_path)
50 .map_err(|e| format!("cannot open lock file {}: {e}", lock_path.display()))?;
51 let ret = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
52 if ret == 0 {
53 let line = serde_json::to_string(holder)
54 .map_err(|e| format!("cannot serialize lock holder: {e}"))?;
55 file.set_len(0)
56 .map_err(|e| format!("cannot truncate lock file {}: {e}", lock_path.display()))?;
57 file.seek(SeekFrom::Start(0))
58 .map_err(|e| format!("cannot seek lock file {}: {e}", lock_path.display()))?;
59 writeln!(file, "{line}")
60 .map_err(|e| format!("cannot write lock file {}: {e}", lock_path.display()))?;
61 file.flush()
62 .map_err(|e| format!("cannot flush lock file {}: {e}", lock_path.display()))?;
63 return Ok(FolderLock { _file: file });
64 }
65 let err = std::io::Error::last_os_error();
66 if err.raw_os_error() == Some(libc::EWOULDBLOCK) || err.raw_os_error() == Some(libc::EAGAIN) {
67 return match read_holder(&mut file) {
68 Ok(h) => Err(format!(
69 "{} {} (pid {}) is already working in this folder",
70 h.kind, h.id, h.pid
71 )),
72 Err(_) => Err(format!(
73 "this folder is already locked ({})",
74 lock_path.display()
75 )),
76 };
77 }
78 Err(format!("cannot lock {}: {err}", lock_path.display()))
79}
80
81#[cfg(unix)]
82pub fn holder(lock_path: &Path) -> Result<Option<Holder>, String> {
83 use std::io::ErrorKind;
84 use std::os::unix::io::AsRawFd;
85
86 let mut file = match std::fs::OpenOptions::new().read(true).open(lock_path) {
87 Ok(f) => f,
88 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
89 Err(e) => {
90 return Err(format!(
91 "cannot open lock file {}: {e}",
92 lock_path.display()
93 ))
94 }
95 };
96 let ret = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
97 if ret == 0 {
98 return Ok(None);
99 }
100 let err = std::io::Error::last_os_error();
101 if err.raw_os_error() == Some(libc::EWOULDBLOCK) || err.raw_os_error() == Some(libc::EAGAIN) {
102 return read_holder(&mut file).map(Some).map_err(|e| {
103 format!(
104 "folder is locked ({}), but holder could not be read: {e}",
105 lock_path.display()
106 )
107 });
108 }
109 Err(format!(
110 "cannot inspect lock file {}: {err}",
111 lock_path.display()
112 ))
113}
114
115#[cfg(not(unix))]
116pub fn acquire(lock_path: &Path, _holder: &Holder) -> Result<FolderLock, String> {
117 Err(format!(
118 "folder locking is not supported on this platform ({})",
119 lock_path.display()
120 ))
121}
122
123#[cfg(not(unix))]
124pub fn holder(lock_path: &Path) -> Result<Option<Holder>, String> {
125 Err(format!(
126 "folder locking is not supported on this platform ({})",
127 lock_path.display()
128 ))
129}