agentmux_srv_core/backend/tower/
remote.rs1use std::collections::HashMap;
21use std::sync::{Arc, Mutex, OnceLock};
22use std::time::{Duration, Instant};
23
24use agentmux_remote::fsproto::ProcFrame;
25
26use crate::backend::remote::files::RemoteFiles;
27use crate::backend::remote::sessions::AskIn;
28use crate::backend::remote::ConnTarget;
29use crate::backend::rpc_types::{TowerHost, TowerProcess, TowerSnapshot};
30
31pub const TOP: u32 = 100;
33
34const REUSE_WITHIN: Duration = Duration::from_millis(900);
36
37const WSL_IDLE_CLOSE: Duration = Duration::from_secs(120);
39
40pub fn is_local(conn: &str) -> bool {
42 matches!(ConnTarget::parse(conn), Ok(ConnTarget::Local)) || conn.trim().is_empty()
43}
44
45pub async fn sample(conn: &str, filter: &str, ask: Option<AskIn<'_>>) -> Result<TowerSnapshot, String> {
48 let slot = slot((conn.to_string(), filter.to_string()));
52 let mut slot = slot.lock().await;
53 if let Some((at, snap)) = slot.as_ref() {
54 if at.elapsed() < REUSE_WITHIN {
55 return Ok(snap.clone());
56 }
57 }
58 let helper = match ConnTarget::parse(conn)? {
59 ConnTarget::Ssh(_) => crate::backend::remote::files::connect(conn, ask).await.map_err(|e| e.message)?,
60 ConnTarget::Wsl(distro) => wsl_helper(&distro).await?,
61 ConnTarget::Local => return Err("tower: this computer is sampled locally".to_string()),
62 };
63 let frame = helper.procs(TOP, filter).await.map_err(|e| e.message)?;
64 let snap = to_snapshot(conn, &helper.os, frame);
65 *slot = Some((Instant::now(), snap.clone()));
66 Ok(snap)
67}
68
69type Slot = Arc<tokio::sync::Mutex<Option<(Instant, TowerSnapshot)>>>;
70
71fn slot(key: (String, String)) -> Slot {
75 static SLOTS: OnceLock<Mutex<HashMap<(String, String), Slot>>> = OnceLock::new();
76 let mut slots = SLOTS.get_or_init(Default::default).lock().unwrap();
77 slots.retain(|k, s| {
78 *k == key
79 || Arc::strong_count(s) > 1
80 || s.try_lock().map_or(true, |g| g.as_ref().is_some_and(|(at, _)| at.elapsed() < STALE_SLOT))
81 });
82 slots.entry(key).or_default().clone()
83}
84
85const STALE_SLOT: Duration = Duration::from_secs(60);
87
88pub fn to_snapshot(conn: &str, os: &str, f: ProcFrame) -> TowerSnapshot {
91 let rows: Vec<TowerProcess> = f
92 .rows
93 .into_iter()
94 .map(|r| TowerProcess {
95 id: format!("{}:{}", r.pid, r.start_key),
96 pid: r.pid,
97 ppid: r.ppid,
98 name: r.name,
99 started_at_ms: r.started_at_ms,
100 cpu: r.cpu_milli.map(|m| m as f64 / 1000.0),
101 mem: r.mem,
102 mem_resident: r.mem_resident,
103 mem_commit: None,
104 role: None,
105 task: None,
106 detail: None,
107 ..Default::default()
108 })
109 .collect();
110 TowerSnapshot {
111 ts_ms: agentmux_common::time::now_ms() as u64,
112 hostname: conn.to_string(),
113 panes: None,
114 memory: None,
115 os: os.to_string(),
116 cpu_count: f.cpu_count,
117 memory_metric: f.memory_metric,
118 interval_ms: crate::backend::tower::sampler::INTERVAL.as_millis() as u32,
119 remote: true,
120 tasks: Vec::new(),
121 machine: None,
123 host: Some(TowerHost {
124 processes: rows,
125 unmeasured: f.unmeasured,
126 cpu: f.cpu_milli.map(|m| m as f64 / 1000.0),
127 mem: f.mem,
128 total: f.total,
129 matched: f.matched,
130 }),
131 }
132}
133
134struct WslHelper {
137 files: Arc<RemoteFiles>,
138 last_used: Mutex<Instant>,
139}
140
141fn wsl_pool() -> &'static tokio::sync::Mutex<HashMap<String, Arc<WslHelper>>> {
142 static POOL: OnceLock<tokio::sync::Mutex<HashMap<String, Arc<WslHelper>>>> = OnceLock::new();
143 POOL.get_or_init(|| {
144 tokio::spawn(async {
146 loop {
147 tokio::time::sleep(Duration::from_secs(30)).await;
148 wsl_pool()
149 .lock()
150 .await
151 .retain(|_, h| h.files.is_open() && h.last_used.lock().unwrap().elapsed() < WSL_IDLE_CLOSE);
152 }
153 });
154 Default::default()
155 })
156}
157
158fn wsl_target() -> &'static str {
160 if cfg!(target_arch = "aarch64") {
161 "aarch64-unknown-linux-musl"
162 } else {
163 "x86_64-unknown-linux-musl"
164 }
165}
166
167pub async fn wsl_helper(distro: &str) -> Result<Arc<RemoteFiles>, String> {
170 let mut pool = wsl_pool().lock().await;
171 if let Some(h) = pool.get(distro).filter(|h| h.files.is_open()) {
172 *h.last_used.lock().unwrap() = Instant::now();
173 return Ok(h.files.clone());
174 }
175 let files = start_wsl(distro).await?;
176 pool.insert(distro.to_string(), Arc::new(WslHelper { files: files.clone(), last_used: Mutex::new(Instant::now()) }));
177 Ok(files)
178}
179
180#[cfg(windows)]
181async fn start_wsl(distro: &str) -> Result<Arc<RemoteFiles>, String> {
182 use agentmux_common::win32::NoWindow;
183 let helper = crate::backend::remote::helper_install::local_path(env!("CARGO_PKG_VERSION"), wsl_target())?;
184 let dir = helper.parent().ok_or("the helper has no folder")?;
185 let file = helper.file_name().ok_or("the helper has no name")?.to_string_lossy().into_owned();
188 let mut cmd = tokio::process::Command::new("wsl.exe");
189 crate::backend::pane_env::sanitize_external_command(&mut cmd);
191 cmd.arg("-d")
192 .arg(distro)
193 .arg("--cd")
194 .arg(dir)
195 .arg("--exec")
196 .arg(format!("./{file}"))
197 .args(["serve", "--stdio"])
198 .stdin(std::process::Stdio::piped())
199 .stdout(std::process::Stdio::piped())
200 .stderr(std::process::Stdio::null())
201 .kill_on_drop(true)
202 .no_window();
203 let mut child = cmd.spawn().map_err(|e| format!("couldn't start WSL ({distro}): {e}"))?;
204 let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
205 return Err("WSL started without its pipes".to_string());
206 };
207 let conn = format!("wsl://{distro}");
208 RemoteFiles::over(&conn, stdout, stdin, Box::new(child)).await.map_err(|e| e.message)
209}
210
211#[cfg(not(windows))]
212async fn start_wsl(distro: &str) -> Result<Arc<RemoteFiles>, String> {
213 let _ = wsl_target();
214 Err(format!("WSL ({distro}) is only on Windows"))
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use agentmux_remote::fsproto::ProcRow;
221
222 #[test]
223 fn a_frame_becomes_a_host_only_snapshot() {
224 let snap = to_snapshot(
225 "build-box",
226 "linux",
227 ProcFrame {
228 cpu_count: 16,
229 memory_metric: "anonymous resident + swap".into(),
230 total: 410,
231 matched: 410,
232 unmeasured: 0,
233 cpu_milli: Some(2500),
234 mem: 8 << 30,
235 rows: vec![ProcRow {
236 pid: 77,
237 ppid: Some(1),
238 start_key: 123,
239 started_at_ms: Some(1),
240 name: "cargo".into(),
241 cpu_milli: Some(1250),
242 mem: Some(1 << 30),
243 mem_resident: None,
244 }],
245 },
246 );
247 assert!(snap.remote && snap.tasks.is_empty());
248 assert_eq!((snap.hostname.as_str(), snap.os.as_str(), snap.cpu_count), ("build-box", "linux", 16));
249 let host = snap.host.unwrap();
250 assert_eq!((host.total, host.processes.len()), (410, 1));
251 assert!((host.cpu.unwrap() - 2.5).abs() < 1e-9);
252 let p = &host.processes[0];
253 assert_eq!(p.id, "77:123");
254 assert_eq!(p.cpu, Some(1.25));
255 }
256
257 #[test]
258 fn this_computer_is_local() {
259 assert!(is_local(""));
260 assert!(is_local("local"));
261 assert!(!is_local("user@build-box"));
262 assert!(!is_local("wsl://Ubuntu"));
263 }
264
265 #[tokio::test]
270 #[cfg(windows)]
271 async fn a_wsl_distribution_is_sampled_through_the_bundled_helper() {
272 let Ok(distro) = std::env::var("AGENTMUX_TEST_WSL_DISTRO") else { return };
273 let conn = format!("wsl://{distro}");
274 let first = sample(&conn, "", None).await.unwrap();
275 let host = first.host.as_ref().unwrap();
276 assert_eq!(first.os, "linux");
277 assert!(host.total > 0 && !host.processes.is_empty(), "{first:?}");
278 assert!(host.processes.iter().any(|p| p.pid == 1), "PID 1 (init) is listed");
279 tokio::time::sleep(Duration::from_millis(1200)).await;
280 let second = sample(&conn, "", None).await.unwrap();
281 assert!(second.host.unwrap().processes.iter().any(|p| p.cpu.is_some()), "rates on the second frame");
282 }
283
284 #[tokio::test]
287 async fn an_ssh_host_is_sampled_through_its_helper() {
288 let home = tempfile::tempdir().unwrap();
289 crate::backend::remote::files::connect_in_process("tower-test-host", home.path().to_path_buf()).await;
290 let me = std::process::id().to_string();
291 let snap = sample("tower-test-host", &me, None).await.unwrap();
292 let host = snap.host.unwrap();
293 assert!(host.processes.iter().any(|p| p.pid == std::process::id()), "{host:?}");
294 assert!(host.total > host.matched || host.total == host.matched);
295 let again = sample("tower-test-host", &me, None).await.unwrap();
297 assert_eq!(again.ts_ms, snap.ts_ms);
298 }
299
300 #[tokio::test]
303 async fn concurrent_asks_share_one_frame() {
304 let home = tempfile::tempdir().unwrap();
305 crate::backend::remote::files::connect_in_process("tower-test-host-2", home.path().to_path_buf()).await;
306 let (a, b) = tokio::join!(sample("tower-test-host-2", "x", None), sample("tower-test-host-2", "x", None));
307 assert_eq!(a.unwrap().ts_ms, b.unwrap().ts_ms);
308 }
309}