agentmux_srv_core/registry/
shared_guard.rs1use std::path::{Path, PathBuf};
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::time::{Duration, Instant};
29
30use serde::{Deserialize, Serialize};
31
32use crate::backend::storage::error::StoreError;
33
34const WAIT: Duration = Duration::from_secs(20);
37const POLL: Duration = Duration::from_millis(500);
38
39static DEFERRED: AtomicBool = AtomicBool::new(false);
41
42static TOLD_TOO_NEW: AtomicBool = AtomicBool::new(false);
44
45pub(crate) fn deferred() -> bool {
47 DEFERRED.load(Ordering::Relaxed)
48}
49
50pub fn shared_dir() -> Option<PathBuf> {
53 if deferred() {
54 return None;
55 }
56 agentmux_common::DataPaths::from_env().map(|p| p.shared_dir)
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub(super) struct Writer {
62 pub pid: u32,
63 pub started_s: u64,
65 pub version: String,
66 pub channel: String,
67}
68
69impl Writer {
70 fn this(sys: &sysinfo::System, version: &str) -> Writer {
71 let pid = std::process::id();
72 Writer {
73 pid,
74 started_s: crate::backend::transcript::framer::start_time(sys, pid).unwrap_or(0),
75 version: version.to_string(),
76 channel: std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default(),
77 }
78 }
79
80 fn label(&self) -> String {
81 if self.channel.is_empty() {
82 format!("AgentMux {}", self.version)
83 } else {
84 format!("AgentMux {} ({})", self.version, self.channel)
85 }
86 }
87}
88
89#[derive(Debug, PartialEq, Eq)]
91pub(super) enum Claim {
92 Owner,
94 Deferred(Writer),
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub(super) struct Entry {
101 pub seq: u64,
102 pub writer: Writer,
103}
104
105fn writers_dir(shared_root: &Path) -> PathBuf {
106 shared_root.join("locks").join("srv-writers")
107}
108
109fn seq_of(path: &Path) -> Option<u64> {
110 if path.extension()? != "json" {
111 return None;
112 }
113 path.file_stem()?.to_str()?.parse().ok()
114}
115
116fn live_others(dir: &Path, me: u32, alive: &dyn Fn(&Writer) -> bool) -> Vec<Entry> {
119 let mut out = Vec::new();
120 let Ok(entries) = std::fs::read_dir(dir) else { return out };
121 for entry in entries.flatten() {
122 let path = entry.path();
123 let Some(seq) = seq_of(&path) else { continue };
124 let Some(writer) = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::<Writer>(&b).ok()) else { continue };
125 if writer.pid == me {
126 continue;
127 }
128 if alive(&writer) {
129 out.push(Entry { seq, writer });
130 } else {
131 let _ = std::fs::remove_file(&path);
132 }
133 }
134 out
135}
136
137fn highest(dir: &Path) -> std::io::Result<u64> {
139 Ok(std::fs::read_dir(dir)?.flatten().filter_map(|e| seq_of(&e.path())).max().unwrap_or(0))
140}
141
142fn link_from(dir: &Path, aside: &Path, start: u64) -> std::io::Result<u64> {
145 let mut seq = start;
146 loop {
147 match std::fs::hard_link(aside, dir.join(format!("{seq}.json"))) {
148 Ok(()) => return Ok(seq),
149 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => seq += 1,
150 Err(e) => return Err(e),
151 }
152 }
153}
154
155fn register(dir: &Path, me: &Writer) -> std::io::Result<u64> {
160 std::fs::create_dir_all(dir)?;
161 let aside = dir.join(format!("{}.tmp", me.pid));
162 std::fs::write(&aside, serde_json::to_vec(me).unwrap_or_default())?;
163 let placed = settle(dir, &aside, highest(dir)? + 1);
164 let _ = std::fs::remove_file(&aside);
165 placed
166}
167
168fn settle(dir: &Path, aside: &Path, start: u64) -> std::io::Result<u64> {
170 let mut seq = link_from(dir, aside, start)?;
171 for _ in 0..8 {
172 if highest(dir)? <= seq {
173 break;
174 }
175 let _ = std::fs::remove_file(dir.join(format!("{seq}.json")));
176 seq = link_from(dir, aside, highest(dir)? + 1)?;
177 }
178 Ok(seq)
179}
180
181fn blocker(my_seq: u64, me: &Writer, others: &[Entry]) -> Option<Writer> {
184 others.iter().filter(|o| o.writer.version != me.version && o.seq < my_seq).min_by_key(|o| o.seq).map(|o| o.writer.clone())
185}
186
187pub(crate) fn claim_in(dir: &Path, me: &Writer, alive: &dyn Fn(&Writer) -> bool, wait: Duration, poll: Duration) -> Claim {
190 let seq = match register(dir, me) {
191 Ok(seq) => seq,
192 Err(e) => {
193 tracing::warn!(error = %e, dir = %dir.display(), "shared guard: couldn't register this srv; the shared folder is used unguarded");
194 return Claim::Owner;
195 }
196 };
197 let started = Instant::now();
198 loop {
199 match blocker(seq, me, &live_others(dir, me.pid, alive)) {
200 None => return Claim::Owner,
201 Some(b) if started.elapsed() >= wait => {
202 let _ = std::fs::remove_file(dir.join(format!("{seq}.json")));
203 return Claim::Deferred(b);
204 }
205 Some(_) => std::thread::sleep(poll),
206 }
207 }
208}
209
210pub(crate) fn deferred_incident(me: &Writer, owner: &Writer) -> agentmux_common::incidents::Incident {
212 let mut i = agentmux_common::incidents::Incident::new(
213 "shared_stores_in_use",
214 format!(
215 "{} is using your shared agents, accounts and history, so {} started without them. Close {} and restart this one to use them.",
216 owner.label(),
217 me.label(),
218 owner.label()
219 ),
220 "srv",
221 );
222 i.cause = Some("Two AgentMux installs of different versions must not write the same files at the same time.".to_string());
223 i.did = vec!["This AgentMux left your shared files alone.".to_string()];
224 i.lost = vec!["Until it is restarted alone, it shows only its own channel's agents and history.".to_string()];
225 i
226}
227
228pub(crate) fn too_new_incident(db: &str, found: i64, expected: i64, me: &Writer) -> agentmux_common::incidents::Incident {
230 let mut i = agentmux_common::incidents::Incident::new(
231 "shared_store_newer",
232 format!("{} is older than your data ({db} is at version {found}; this one reads up to {expected}). Update AgentMux to use it.", me.label()),
233 "srv",
234 );
235 i.cause = Some("A newer AgentMux changed your shared files.".to_string());
236 i.did = vec![format!("This AgentMux did not open {db}, so it did not change it.")];
237 i.lost = vec!["Until it is updated, it shows only its own channel's agents, accounts and history.".to_string()];
238 i
239}
240
241fn record(incident: &agentmux_common::incidents::Incident) {
242 tracing::warn!(target: "incidents", kind = %incident.kind, what = %incident.what, "incident recorded");
243 let Some(paths) = agentmux_common::DataPaths::from_env() else { return };
244 let path = paths.data_dir.join(agentmux_common::incidents::FILE_NAME);
245 if let Err(e) = agentmux_common::incidents::append(&path, incident) {
246 tracing::warn!(error = %e, "shared guard: couldn't write the incident");
247 }
248}
249
250pub fn note_open_failure(e: &StoreError) {
252 if let StoreError::SchemaTooNew { db, found, expected } = e {
253 if TOLD_TOO_NEW.swap(true, Ordering::Relaxed) {
255 return;
256 }
257 let sys = crate::backend::transcript::framer::scan_processes();
258 record(&too_new_incident(db, *found, *expected, &Writer::this(&sys, env!("CARGO_PKG_VERSION"))));
259 }
260}
261
262pub fn claim_at_boot(version: &str) {
265 let Some((me, claim)) = claim_this_process(version) else { return };
266 match claim {
267 Claim::Owner => tracing::info!(version, "shared guard: this srv uses the shared folder"),
268 Claim::Deferred(owner) => {
269 record(&deferred_incident(&me, &owner));
270 if let Some(reason) = agentmux_common::DataPaths::from_env().and_then(|p| crate::migrations::data_needs_preparing(&p.data_dir, version)) {
273 tracing::error!(%reason, "shared guard: this srv's data needs preparing and the shared folder is held by another version; not starting");
274 std::process::exit(refuse_beside(&owner, &reason));
275 }
276 DEFERRED.store(true, Ordering::Relaxed);
277 tracing::warn!(owner_pid = owner.pid, owner_version = %owner.version, "shared guard: another version holds the shared folder; running without it");
278 }
279 }
280}
281
282fn claim_this_process(version: &str) -> Option<(Writer, Claim)> {
284 let root = crate::registry::resolve_global_shared_root()?;
285 let sys = crate::backend::transcript::framer::scan_processes();
286 let me = Writer::this(&sys, version);
287 let alive = |w: &Writer| {
288 let sys = crate::backend::transcript::framer::scan_processes();
289 sys.process(sysinfo::Pid::from_u32(w.pid))
290 .is_some_and(|p| crate::backend::transcript::framer::is_srv(&p.name().to_string_lossy()) && p.start_time().abs_diff(w.started_s) <= 1)
291 };
292 let claim = claim_in(&writers_dir(&root), &me, &alive, WAIT, POLL);
293 Some((me, claim))
294}
295
296pub(crate) fn claim_for_migrate(data_dir: &Path) -> Option<i32> {
300 let version = env!("CARGO_PKG_VERSION");
301 let (_, Claim::Deferred(owner)) = claim_this_process(version)? else { return None };
302 Some(migrate_exit_code(&owner, crate::migrations::data_needs_preparing(data_dir, version)))
303}
304
305fn migrate_exit_code(owner: &Writer, needs_preparing: Option<String>) -> i32 {
308 let Some(reason) = needs_preparing else { return 0 };
309 refuse_beside(owner, &reason)
310}
311
312fn refuse_beside(owner: &Writer, reason: &str) -> i32 {
315 eprintln!("agentmux-srv: {} is using the shared folder and this data needs preparing ({reason}). Close it and start this one again.", owner.label());
316 eprintln!("{}", agentmux_common::srv_stderr::shared_folder_held_line(&owner.label(), reason));
317 agentmux_common::srv_stderr::SHARED_FOLDER_HELD_EXIT
318}
319
320#[cfg(test)]
321#[path = "shared_guard_tests.rs"]
322mod tests;