1use std::collections::HashMap;
36use std::path::{Path, PathBuf};
37use std::time::{Duration, SystemTime};
38
39use serde::Serialize;
40
41pub const KEY_CLEAN: &str = "oldversions:clean";
43pub const KEY_KEEP_PREVIOUS: &str = "oldversions:keep_previous";
44pub const KEY_IDLE_HOURS: &str = "oldversions:idle_hours";
45pub const KEY_PORTABLES: &str = "oldversions:portables";
46
47#[derive(Debug, Clone, PartialEq)]
49pub struct Policy {
50 pub clean: bool,
52 pub keep_previous: usize,
54 pub idle: Duration,
56 pub portables: bool,
58}
59
60impl Default for Policy {
61 fn default() -> Self {
62 Self { clean: true, keep_previous: 1, idle: Duration::from_secs(24 * 3600), portables: false }
66 }
67}
68
69impl Policy {
70 pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
72 Self::from_extra_for(extra, false)
73 }
74
75 pub fn from_extra_for(extra: &HashMap<String, serde_json::Value>, _hosted: bool) -> Self {
79 let d = Self::default();
80 let num = |key: &str| extra.get(key).and_then(|v| v.as_f64()).filter(|n| n.is_finite() && *n >= 0.0);
81 Self {
82 clean: extra.get(KEY_CLEAN).and_then(|v| v.as_bool()).unwrap_or(d.clean),
83 keep_previous: num(KEY_KEEP_PREVIOUS).map_or(d.keep_previous, |n| (n as usize).max(1)),
84 idle: num(KEY_IDLE_HOURS).and_then(|h| Duration::try_from_secs_f64(h * 3600.0).ok()).unwrap_or(d.idle),
85 portables: extra.get(KEY_PORTABLES).and_then(|v| v.as_bool()).unwrap_or(d.portables),
86 }
87 }
88}
89
90#[derive(Debug, Clone)]
92pub struct Layout {
93 pub versions_root: PathBuf,
95 pub running: String,
97 pub channel: String,
99 pub portable_parents: Vec<PathBuf>,
101}
102
103pub fn layout_from_env() -> Option<Layout> {
106 let paths = agentmux_common::DataPaths::from_env()?;
107 let version_dir = paths.data_dir.parent()?;
108 let versions_root = version_dir.parent()?;
109 if versions_root.file_name()? != "versions" || versions_root.parent()? != paths.instance_dir {
110 return None;
111 }
112 let mut portable_parents = Vec::new();
113 match crate::backend::update::install::detect() {
114 crate::backend::update::install::InstallKind::WindowsPortable { root } | crate::backend::update::install::InstallKind::LinuxPortable { root } => {
115 portable_parents.extend(root.parent().map(Path::to_path_buf));
116 }
117 _ => {}
118 }
119 if let Ok(entries) = std::fs::read_dir(paths.instance_dir.join("updates")) {
120 portable_parents.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
121 }
122 Some(Layout {
123 versions_root: versions_root.to_path_buf(),
124 running: version_dir.file_name()?.to_string_lossy().into_owned(),
125 channel: paths.channel,
126 portable_parents,
127 })
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
131#[serde(rename_all = "snake_case")]
132pub enum Kind {
133 VersionData,
135 Portable,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
140#[serde(rename_all = "snake_case")]
141pub enum Keep {
142 Running,
144 NotOlder,
146 Rollback,
148 InUse,
150 ScanFailed,
152 RecentlyActive,
154 NotOurs,
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
160pub struct Candidate {
161 pub dir: PathBuf,
162 pub version: String,
163 pub kind: Kind,
164 pub bytes: u64,
165}
166
167#[derive(Debug, Clone, Default, Serialize)]
168pub struct Plan {
169 pub removable: Vec<Candidate>,
170 pub kept: Vec<(PathBuf, Keep)>,
172}
173
174impl Plan {
175 pub fn reclaimable_bytes(&self) -> u64 {
176 self.removable.iter().map(|c| c.bytes).sum()
177 }
178}
179
180#[derive(Debug, Clone, Default)]
182pub struct ProcView {
183 pub pid: u32,
184 pub name: String,
186 pub strings: Vec<String>,
188}
189
190#[derive(Debug, Clone, Default)]
192pub struct InUse {
193 pub procs: Option<Vec<ProcView>>,
195}
196
197fn normal(s: &str) -> String {
198 let s = s.replace('\\', "/").to_ascii_lowercase();
199 s.strip_prefix("//?/").map_or_else(|| s.clone(), str::to_string)
201}
202
203impl InUse {
204 pub fn scan() -> Self {
206 let mut sys = sysinfo::System::new();
207 sys.refresh_processes_specifics(
208 sysinfo::ProcessesToUpdate::All,
209 true,
210 sysinfo::ProcessRefreshKind::nothing()
211 .with_cwd(sysinfo::UpdateKind::Always)
212 .with_exe(sysinfo::UpdateKind::Always)
213 .with_cmd(sysinfo::UpdateKind::Always)
214 .with_environ(sysinfo::UpdateKind::Always),
215 );
216 let procs: Vec<ProcView> = sys
217 .processes()
218 .iter()
219 .map(|(pid, p)| {
220 let mut strings: Vec<String> = Vec::new();
221 strings.extend(p.exe().map(|e| e.to_string_lossy().into_owned()));
222 strings.extend(p.cwd().map(|c| c.to_string_lossy().into_owned()));
223 strings.extend(p.cmd().iter().map(|a| a.to_string_lossy().into_owned()));
224 strings.extend(p.environ().iter().map(|e| e.to_string_lossy().into_owned()));
225 ProcView { pid: pid.as_u32(), name: p.name().to_string_lossy().into_owned(), strings }
226 })
227 .collect();
228 Self { procs: (!procs.is_empty()).then_some(procs) }
230 }
231
232 pub fn mentions(&self, dir: &Path) -> bool {
235 let needle = normal(&dir.to_string_lossy());
236 let needle = needle.trim_end_matches('/');
237 if needle.is_empty() {
238 return false;
239 }
240 self.procs.iter().flatten().flat_map(|p| p.strings.iter()).any(|s| {
241 let hay = normal(s);
242 hay.match_indices(needle).any(|(i, _)| {
243 hay[i + needle.len()..].chars().next().is_none_or(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+')))
244 })
245 })
246 }
247
248 fn agentmux_alive(&self, pid: u32) -> bool {
250 self.procs.iter().flatten().any(|p| p.pid == pid && p.name.to_ascii_lowercase().contains("agentmux"))
251 }
252}
253
254fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
256 let mut it = s.split('.');
257 let mut next = || it.next().filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())).and_then(|p| p.parse::<u64>().ok());
258 let v = (next()?, next()?, next()?);
259 it.next().is_none().then_some(v)
260}
261
262fn portable_version(name: &str) -> Option<&str> {
264 if cfg!(windows) {
265 name.strip_prefix("agentmux-")?.strip_suffix("-x64-portable")
266 } else {
267 name.strip_prefix("AgentMux-")
268 }
269}
270
271fn leftover_stem(name: &str) -> Option<&str> {
273 let (stem, pid) = name.rsplit_once(".removing-")?;
274 (!pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())).then_some(stem)
275}
276
277fn stem_is_ours(kind: Kind, stem: &str) -> bool {
279 match kind {
280 Kind::Portable => portable_version(stem).and_then(parse_version).is_some(),
281 Kind::VersionData => parse_version(stem).is_some(),
282 }
283}
284
285fn dir_size(dir: &Path) -> u64 {
287 let mut total = 0;
288 let mut stack = vec![dir.to_path_buf()];
289 while let Some(d) = stack.pop() {
290 let Ok(rd) = std::fs::read_dir(&d) else { continue };
291 for entry in rd.flatten() {
292 let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
293 if meta.is_dir() {
294 stack.push(entry.path());
295 } else {
296 total += meta.len();
297 }
298 }
299 }
300 total
301}
302
303fn last_activity(dir: &Path) -> Option<SystemTime> {
307 let mut newest: Option<SystemTime> = None;
308 let mut stack = vec![dir.to_path_buf()];
309 while let Some(d) = stack.pop() {
310 if let Ok(t) = std::fs::symlink_metadata(&d).and_then(|m| m.modified()) {
311 newest = Some(newest.map_or(t, |n| n.max(t)));
312 }
313 let Ok(rd) = std::fs::read_dir(&d) else { continue };
314 for e in rd.flatten() {
315 let Ok(meta) = e.metadata() else { continue };
316 if meta.is_dir() && !meta.file_type().is_symlink() {
317 stack.push(e.path());
318 } else if let Ok(t) = meta.modified() {
319 newest = Some(newest.map_or(t, |n| n.max(t)));
320 }
321 }
322 }
323 newest
324}
325
326fn recorded_srv_pid(dir: &Path) -> Option<u32> {
328 std::fs::read_to_string(dir.join("data").join(crate::backend::base::SRV_DATA_LOCK_FILE)).ok()?.trim().parse().ok()
329}
330
331fn in_use_reason(dir: &Path, policy: &Policy, now: SystemTime, in_use: &InUse) -> Option<Keep> {
333 if in_use.procs.is_none() {
334 return Some(Keep::ScanFailed);
335 }
336 if in_use.mentions(dir) || recorded_srv_pid(dir).is_some_and(|p| in_use.agentmux_alive(p)) {
337 return Some(Keep::InUse);
338 }
339 let idle = last_activity(dir).and_then(|t| now.duration_since(t).ok()).unwrap_or(Duration::ZERO); (idle < policy.idle).then_some(Keep::RecentlyActive)
341}
342
343struct Entry {
344 dir: PathBuf,
345 version: String,
346 key: (u64, u64, u64),
347}
348
349fn scan_dir(parent: &Path, kind: Kind, layout: &Layout, kept: &mut Vec<(PathBuf, Keep)>, leftovers: &mut Vec<(PathBuf, Kind)>) -> Vec<Entry> {
351 let Ok(rd) = std::fs::read_dir(parent) else { return Vec::new() };
352 let mut out = Vec::new();
353 for e in rd.flatten() {
354 let path = e.path();
355 let name = e.file_name().to_string_lossy().into_owned();
356 let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
357 if meta.file_type().is_symlink() {
358 kept.push((path, Keep::NotOurs));
359 continue;
360 }
361 if !meta.is_dir() {
362 continue;
363 }
364 if name.contains(".removing-") {
365 if leftover_stem(&name).is_some_and(|stem| stem_is_ours(kind, stem)) {
368 leftovers.push((path, kind));
369 }
370 continue;
371 }
372 let version = match kind {
373 Kind::Portable => portable_version(&name).map(str::to_owned),
374 _ => Some(name.clone()),
375 };
376 let Some(key) = version.as_deref().and_then(parse_version) else {
377 if kind != Kind::Portable || name.to_ascii_lowercase().starts_with("agentmux") {
380 kept.push((path, Keep::NotOurs));
381 }
382 continue;
383 };
384 let version = version.unwrap_or_default();
385 if kind == Kind::Portable
386 && !(crate::backend::update::download::is_staged_portable(&path, &version)
387 && agentmux_common::runtime_mode::recorded_channel_in(&path).as_deref() == Some(layout.channel.as_str()))
388 {
389 kept.push((path, Keep::NotOurs));
390 continue;
391 }
392 out.push(Entry { dir: path, version, key });
393 }
394 out
395}
396
397fn judge(plan: &mut Plan, kind: Kind, mut entries: Vec<Entry>, running: (u64, u64, u64), policy: &Policy, now: SystemTime, in_use: &InUse) {
398 entries.sort_by(|a, b| b.key.cmp(&a.key));
399 let mut older = 0;
400 for e in entries {
401 let keep = if e.key == running {
402 Some(Keep::Running)
403 } else if e.key > running {
404 Some(Keep::NotOlder)
405 } else {
406 older += 1;
407 if older <= policy.keep_previous {
408 Some(Keep::Rollback)
409 } else {
410 in_use_reason(&e.dir, policy, now, in_use)
411 }
412 };
413 match keep {
414 Some(k) => plan.kept.push((e.dir, k)),
415 None => plan.removable.push(Candidate { bytes: dir_size(&e.dir), dir: e.dir, version: e.version, kind }),
416 }
417 }
418}
419
420pub fn plan(layout: &Layout, policy: &Policy, now: SystemTime, in_use: &InUse) -> Plan {
422 let mut plan = Plan::default();
423 let Some(running) = parse_version(&layout.running) else {
424 return plan;
426 };
427 let mut leftovers = Vec::new();
428 let entries = scan_dir(&layout.versions_root, Kind::VersionData, layout, &mut plan.kept, &mut leftovers);
429 judge(&mut plan, Kind::VersionData, entries, running, policy, now, in_use);
430 let mut portables = Vec::new();
431 for parent in &layout.portable_parents {
432 portables.extend(scan_dir(parent, Kind::Portable, layout, &mut plan.kept, &mut leftovers));
433 }
434 judge(&mut plan, Kind::Portable, portables, running, policy, now, in_use);
435 for (dir, kind) in leftovers {
436 match in_use_reason(&dir, policy, now, in_use) {
437 Some(k) => plan.kept.push((dir, k)),
438 None => plan.removable.push(Candidate { bytes: dir_size(&dir), version: String::new(), dir, kind }),
439 }
440 }
441 plan
442}
443
444#[derive(Debug, Default, Serialize)]
445pub struct Report {
446 pub removed: Vec<(PathBuf, u64)>,
447 pub skipped: Vec<(PathBuf, String)>,
449}
450
451pub fn remove(plan: &Plan, layout: &Layout, policy: &Policy, now: SystemTime, in_use: &dyn Fn() -> InUse) -> Report {
454 let mut report = Report::default();
455 let current_data = layout.versions_root.join(&layout.running).join("data");
456 for c in &plan.removable {
457 if c.kind == Kind::Portable && !policy.portables {
459 report.skipped.push((c.dir.clone(), "portable cleanup is off (oldversions:portables)".into()));
460 continue;
461 }
462 if std::fs::symlink_metadata(&c.dir).map_or(true, |m| m.file_type().is_symlink() || !m.is_dir()) {
463 report.skipped.push((c.dir.clone(), "no longer a plain folder".into()));
464 continue;
465 }
466 if let Some(why) = in_use_reason(&c.dir, policy, now, &in_use()) {
467 report.skipped.push((c.dir.clone(), format!("{why:?}: in use now")));
468 continue;
469 }
470 if c.kind == Kind::VersionData {
473 if let Err(e) = carry_attachments(&c.dir, ¤t_data) {
474 report.skipped.push((c.dir.clone(), format!("could not carry its attachments forward: {e}")));
475 continue;
476 }
477 }
478 let target = if c.dir.file_name().is_some_and(|n| n.to_string_lossy().contains(".removing-")) {
479 c.dir.clone()
480 } else {
481 let name = c.dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
482 let renamed = c.dir.with_file_name(format!("{name}.removing-{}", std::process::id()));
483 if let Err(e) = std::fs::rename(&c.dir, &renamed) {
485 report.skipped.push((c.dir.clone(), format!("could not be renamed, so something has it open: {e}")));
486 continue;
487 }
488 renamed
489 };
490 match std::fs::remove_dir_all(&target) {
491 Ok(()) => report.removed.push((c.dir.clone(), c.bytes)),
492 Err(e) => report.skipped.push((target, format!("removal started, finishing on the next pass: {e}"))),
493 }
494 }
495 report
496}
497
498fn carry_attachments(from_version: &Path, current_data: &Path) -> Result<u64, String> {
502 fn copy(src: &Path, dst: &Path) -> Result<u64, String> {
503 std::fs::create_dir_all(dst).map_err(|e| format!("create {}: {e}", dst.display()))?;
504 let mut bytes = 0;
505 for entry in std::fs::read_dir(src).map_err(|e| format!("read {}: {e}", src.display()))? {
506 let entry = entry.map_err(|e| format!("entry of {}: {e}", src.display()))?;
507 let file_type = entry.file_type().map_err(|e| format!("type of {}: {e}", entry.path().display()))?;
508 if file_type.is_symlink() {
509 return Err(format!("{} is a symlink, so it is not carried", entry.path().display()));
512 }
513 let to = dst.join(entry.file_name());
514 if file_type.is_dir() {
515 bytes += copy(&entry.path(), &to)?;
516 continue;
517 }
518 if to.exists() {
521 continue;
522 }
523 let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
524 let tmp = dst.join(format!(".{}.copying-{}", entry.file_name().to_string_lossy(), std::process::id()));
527 if let Err(e) = std::fs::copy(entry.path(), &tmp) {
528 let _ = std::fs::remove_file(&tmp);
529 return Err(format!("copy to {}: {e}", to.display()));
530 }
531 match publish(&tmp, &to) {
532 Ok(true) => bytes += size,
533 Ok(false) => {}
536 Err(e) => return Err(format!("publish to {}: {e}", to.display())),
537 }
538 }
539 Ok(bytes)
540 }
541 let src = from_version.join("data").join("attachments");
542 if !src.is_dir() {
543 return Ok(0);
544 }
545 copy(&src, ¤t_data.join("attachments"))
546}
547
548fn publish(tmp: &Path, to: &Path) -> std::io::Result<bool> {
561 match std::fs::hard_link(tmp, to) {
562 Ok(()) => {
563 let _ = std::fs::remove_file(tmp);
564 Ok(true)
565 }
566 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists || to.exists() => {
567 let _ = std::fs::remove_file(tmp);
568 Ok(false)
569 }
570 Err(e) => {
571 let _ = std::fs::remove_file(tmp);
572 Err(e)
573 }
574 }
575}
576
577#[derive(Debug, Serialize)]
579pub struct Run {
580 pub plan: Plan,
581 pub report: Option<Report>,
583 pub scan_ok: bool,
585}
586
587pub fn run(layout: &Layout, policy: &Policy, dry_run: bool, only: Option<&[String]>, now: SystemTime) -> Run {
590 let in_use = InUse::scan();
591 let scan_ok = in_use.procs.is_some();
592 let mut plan = plan(layout, policy, now, &in_use);
593 if let Some(only) = only {
594 plan.removable.retain(|c| only.iter().any(|d| Path::new(d) == c.dir));
595 }
596 let report = (!dry_run).then(|| remove(&plan, layout, policy, now, &InUse::scan));
597 Run { plan, report, scan_ok }
598}
599
600#[cfg(test)]
601#[path = "old_versions_tests.rs"]
602mod tests;