1use std::collections::VecDeque;
9use std::io::{BufRead, BufReader};
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
12use std::sync::{Arc, Mutex};
13use std::thread;
14use std::time::{Duration, Instant};
15
16use crate::agent::{AgentMessage, ClientMessage, PROTOCOL_VERSION, write_message};
17use crate::snapshot::Snapshot;
18use crate::source::{DataSource, ProcessSignal, SourceError};
19
20pub const DEFAULT_REMOTE_COMMAND: &str = "rigtop --agent";
22pub const FALLBACK_REMOTE_COMMAND: &str = "~/.cargo/bin/rigtop --agent";
26const NOT_FOUND_STATUS: i32 = 127;
28
29const RECONNECT_DELAY: Duration = Duration::from_secs(5);
31const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
34const SIGNAL_TIMEOUT: Duration = Duration::from_secs(10);
36const STDERR_LINES: usize = 20;
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct RemoteTarget {
42 pub name: String,
44 pub program: String,
46 pub args: Vec<String>,
48 pub fallback_args: Option<Vec<String>>,
51}
52
53impl RemoteTarget {
54 pub fn ssh(destination: &str, remote_command: &str) -> Self {
57 let options = [
58 "BatchMode=yes",
60 "ConnectTimeout=10",
61 "ServerAliveInterval=15",
63 "ServerAliveCountMax=3",
64 ];
65 let mut args = vec!["-T".to_owned()];
66 for option in options {
67 args.push("-o".to_owned());
68 args.push(option.to_owned());
69 }
70 args.push("--".to_owned());
72 args.push(destination.to_owned());
73 args.push(remote_command.to_owned());
74 let fallback_args = (remote_command == DEFAULT_REMOTE_COMMAND).then(|| {
77 let mut fallback = args.clone();
78 *fallback.last_mut().expect("command pushed above") =
79 FALLBACK_REMOTE_COMMAND.to_owned();
80 fallback
81 });
82 Self {
83 name: destination.to_owned(),
84 program: "ssh".to_owned(),
85 args,
86 fallback_args,
87 }
88 }
89}
90
91enum Incoming {
93 Message(AgentMessage),
94 Closed,
96}
97
98struct Connection {
100 child: Child,
101 stdin: ChildStdin,
102 incoming: Receiver<Incoming>,
103 stderr: Arc<Mutex<VecDeque<String>>>,
105 established: bool,
107}
108
109impl Connection {
110 fn spawn(target: &RemoteTarget, args: &[String]) -> Result<Self, SourceError> {
111 let mut command = Command::new(&target.program);
112 command
113 .args(args)
114 .stdin(Stdio::piped())
115 .stdout(Stdio::piped())
116 .stderr(Stdio::piped());
117 #[cfg(windows)]
118 {
119 use std::os::windows::process::CommandExt;
120 command.creation_flags(0x0800_0000);
122 }
123 let mut child = command.spawn().map_err(|err| {
124 SourceError::Disconnected(format!("cannot start {}: {err}", target.program))
125 })?;
126 let stdin = child.stdin.take().expect("piped stdin");
127 let stdout = child.stdout.take().expect("piped stdout");
128 let stderr_pipe = child.stderr.take().expect("piped stderr");
129
130 let (tx, incoming) = mpsc::channel();
131 thread::Builder::new()
132 .name("rigtop-remote-reader".to_owned())
133 .spawn(move || {
134 for line in BufReader::new(stdout).lines() {
135 let Ok(line) = line else { break };
136 if let Ok(message) = serde_json::from_str::<AgentMessage>(&line)
139 && tx.send(Incoming::Message(message)).is_err()
140 {
141 return;
142 }
143 }
144 let _ = tx.send(Incoming::Closed);
145 })
146 .map_err(SourceError::Io)?;
147
148 let stderr = Arc::new(Mutex::new(VecDeque::new()));
149 let lines = Arc::clone(&stderr);
150 thread::Builder::new()
151 .name("rigtop-remote-stderr".to_owned())
152 .spawn(move || {
153 for line in BufReader::new(stderr_pipe).lines() {
154 let Ok(line) = line else { break };
155 let mut lines = lines.lock().unwrap_or_else(|e| e.into_inner());
156 if lines.len() == STDERR_LINES {
157 lines.pop_front();
158 }
159 lines.push_back(line);
160 }
161 })
162 .map_err(SourceError::Io)?;
163
164 Ok(Self {
165 child,
166 stdin,
167 incoming,
168 stderr,
169 established: false,
170 })
171 }
172
173 fn send(&mut self, message: &ClientMessage) -> Result<(), SourceError> {
174 write_message(&mut self.stdin, message).map_err(SourceError::Io)
175 }
176
177 fn failure(&mut self) -> (String, bool) {
180 thread::sleep(Duration::from_millis(100));
182 let status = self.child.try_wait().ok().flatten();
183 let lines = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
184 let detail = lines
185 .iter()
186 .rev()
187 .find(|l| !l.trim().is_empty())
188 .cloned()
189 .unwrap_or_default();
190 let not_found = status.and_then(|s| s.code()) == Some(NOT_FOUND_STATUS)
192 || detail.contains("command not found")
193 || detail.contains("not recognized");
194 let reason = match (detail.is_empty(), status) {
195 (false, _) => detail,
196 (true, Some(status)) => format!("connection closed ({status})"),
197 (true, None) => "connection closed".to_owned(),
198 };
199 (reason, not_found)
200 }
201}
202
203impl Drop for Connection {
204 fn drop(&mut self) {
205 let _ = self.child.kill();
208 let _ = self.child.wait();
209 }
210}
211
212pub struct RemoteSource {
214 target: RemoteTarget,
215 connection: Option<Connection>,
216 last_attempt: Option<Instant>,
217 interval: Duration,
218 process_limit: Option<usize>,
219 pending: VecDeque<Snapshot>,
221 last_error: Option<String>,
223 use_fallback: bool,
225 retry_now: bool,
227}
228
229impl RemoteSource {
230 pub fn new(target: RemoteTarget) -> Self {
232 Self {
233 target,
234 connection: None,
235 last_attempt: None,
236 interval: Duration::from_secs(1),
237 process_limit: None,
238 pending: VecDeque::new(),
239 last_error: None,
240 use_fallback: false,
241 retry_now: false,
242 }
243 }
244
245 pub fn target(&self) -> &RemoteTarget {
247 &self.target
248 }
249
250 fn connection(&mut self) -> Result<&mut Connection, SourceError> {
252 if self.connection.is_none() {
253 if let Some(at) = self.last_attempt {
254 let wait = RECONNECT_DELAY.saturating_sub(at.elapsed());
255 if !wait.is_zero() {
256 let reason = self.last_error.as_deref().unwrap_or("not connected");
257 return Err(SourceError::Disconnected(format!(
258 "{}: {reason} (retrying in {}s)",
259 self.target.name,
260 wait.as_secs() + 1
261 )));
262 }
263 }
264 self.last_attempt = Some(Instant::now());
265 let args = match (&self.target.fallback_args, self.use_fallback) {
266 (Some(fallback), true) => fallback,
267 _ => &self.target.args,
268 };
269 let mut connection = match Connection::spawn(&self.target, args) {
270 Ok(connection) => connection,
271 Err(err) => {
272 self.last_error = Some(match &err {
273 SourceError::Disconnected(reason) => reason.clone(),
274 other => other.to_string(),
275 });
276 return Err(err);
277 }
278 };
279 let sent = connection
281 .send(&ClientMessage::SetInterval {
282 ms: self.interval.as_millis() as u64,
283 })
284 .and_then(|()| {
285 connection.send(&ClientMessage::SetProcessLimit {
286 limit: self.process_limit,
287 })
288 });
289 self.connection = Some(connection);
290 if sent.is_err() {
291 return Err(self.disconnect(None));
294 }
295 }
296 Ok(self.connection.as_mut().expect("connected above"))
297 }
298
299 fn disconnect(&mut self, reason: Option<String>) -> SourceError {
301 let (mut reason, not_found) = match (reason, self.connection.as_mut()) {
302 (Some(reason), _) => (reason, false),
303 (None, Some(connection)) => connection.failure(),
304 (None, None) => ("connection closed".to_owned(), false),
305 };
306 self.connection = None;
307 if not_found && self.target.fallback_args.is_some() {
308 if self.use_fallback {
309 self.use_fallback = false;
312 reason = format!("rigtop is neither on the PATH nor in ~/.cargo/bin ({reason})");
313 } else {
314 self.use_fallback = true;
315 self.retry_now = true;
316 self.last_attempt = None;
317 }
318 }
319 let error = SourceError::Disconnected(format!("{}: {reason}", self.target.name));
320 self.last_error = Some(reason);
321 error
322 }
323
324 fn next_message(&mut self, timeout: Duration) -> Result<Option<AgentMessage>, SourceError> {
326 let connection = self.connection()?;
327 match connection.incoming.recv_timeout(timeout) {
328 Ok(Incoming::Message(message)) => Ok(Some(message)),
329 Ok(Incoming::Closed) | Err(RecvTimeoutError::Disconnected) => {
330 Err(self.disconnect(None))
331 }
332 Err(RecvTimeoutError::Timeout) => Ok(None),
333 }
334 }
335
336 fn absorb(&mut self, message: AgentMessage) -> Result<(), SourceError> {
339 match message {
340 AgentMessage::Hello { protocol, version } if protocol != PROTOCOL_VERSION => {
341 let reason = format!(
342 "agent speaks protocol {protocol} (rigtop {version}), this client speaks {PROTOCOL_VERSION}; \
343 install the same rigtop version on both sides"
344 );
345 self.last_attempt = Some(Instant::now());
347 Err(self.disconnect(Some(reason)))
348 }
349 AgentMessage::Hello { .. } | AgentMessage::SignalResult { .. } => Ok(()),
350 AgentMessage::Snapshot { snapshot } => {
351 if let Some(connection) = self.connection.as_mut() {
352 connection.established = true;
353 }
354 self.last_error = None;
355 self.pending.push_back(*snapshot);
356 Ok(())
357 }
358 AgentMessage::Error { message } => Err(SourceError::Remote(message)),
359 }
360 }
361}
362
363impl RemoteSource {
364 fn poll_once(&mut self) -> Result<Snapshot, SourceError> {
366 let established = self.connection.as_ref().is_some_and(|c| c.established);
368 let timeout = if established {
369 self.interval * 3 + Duration::from_secs(5)
370 } else {
371 CONNECT_TIMEOUT
372 };
373 let deadline = Instant::now() + timeout;
374 loop {
375 while let Some(message) = self.next_message(Duration::ZERO)? {
377 self.absorb(message)?;
378 }
379 if let Some(newest) = self.pending.pop_back() {
380 self.pending.clear();
381 return Ok(newest);
382 }
383 let remaining = deadline.saturating_duration_since(Instant::now());
384 if remaining.is_zero() {
385 return Err(self.disconnect(Some("no data from the agent (timed out)".to_owned())));
386 }
387 if let Some(message) = self.next_message(remaining)? {
388 self.absorb(message)?;
389 }
390 }
391 }
392}
393
394impl DataSource for RemoteSource {
395 fn poll(&mut self) -> Result<Snapshot, SourceError> {
398 match self.poll_once() {
399 Err(_) if std::mem::take(&mut self.retry_now) => self.poll_once(),
401 result => result,
402 }
403 }
404
405 fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
406 if self
407 .connection()?
408 .send(&ClientMessage::Signal { pid, signal })
409 .is_err()
410 {
411 return Err(self.disconnect(None));
412 }
413 let deadline = Instant::now() + SIGNAL_TIMEOUT;
414 loop {
415 let remaining = deadline.saturating_duration_since(Instant::now());
416 if remaining.is_zero() {
417 return Err(SourceError::Remote(format!(
418 "no answer to the signal for {pid}"
419 )));
420 }
421 match self.next_message(remaining)? {
422 Some(AgentMessage::SignalResult {
423 pid: answered,
424 error,
425 ..
426 }) if answered == pid => {
427 return match error {
428 None => Ok(()),
429 Some(error) => Err(SourceError::Remote(error)),
430 };
431 }
432 Some(other) => self.absorb(other)?,
433 None => {}
434 }
435 }
436 }
437
438 fn set_interval(&mut self, interval: Duration) {
439 self.interval = interval;
440 if let Some(connection) = self.connection.as_mut() {
441 let _ = connection.send(&ClientMessage::SetInterval {
442 ms: interval.as_millis() as u64,
443 });
444 }
445 }
446
447 fn set_process_limit(&mut self, limit: Option<usize>) {
448 self.process_limit = limit;
449 if let Some(connection) = self.connection.as_mut() {
450 let _ = connection.send(&ClientMessage::SetProcessLimit { limit });
451 }
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 #[test]
460 fn ssh_target_uses_batch_mode_and_keeps_the_destination_safe() {
461 let target = RemoteTarget::ssh("zefat", DEFAULT_REMOTE_COMMAND);
462 assert_eq!(target.program, "ssh");
463 assert_eq!(target.name, "zefat");
464 assert!(target.args.windows(2).any(|w| w == ["-o", "BatchMode=yes"]));
465 let n = target.args.len();
466 assert_eq!(&target.args[n - 3..], ["--", "zefat", "rigtop --agent"]);
467 let fallback = target.fallback_args.as_ref().unwrap();
469 assert_eq!(&fallback[n - 3..], ["--", "zefat", FALLBACK_REMOTE_COMMAND]);
470 let custom = RemoteTarget::ssh("zefat", "/opt/rigtop/bin/rigtop --agent");
472 assert_eq!(custom.fallback_args, None);
473 }
474
475 #[cfg(unix)]
477 fn sh_target(script: &str, fallback: Option<&str>) -> RemoteTarget {
478 let args = |script: &str| vec!["-c".to_owned(), script.to_owned()];
479 RemoteTarget {
480 name: "fake".to_owned(),
481 program: "sh".to_owned(),
482 args: args(script),
483 fallback_args: fallback.map(args),
484 }
485 }
486
487 #[cfg(unix)]
488 #[test]
489 fn command_not_found_tries_the_fallback_at_once() {
490 let missing = "echo 'zsh:1: command not found: rigtop' >&2; exit 127";
492 let mut source = RemoteSource::new(sh_target(missing, Some(missing)));
493 let err = source.poll().unwrap_err().to_string();
494 assert!(
495 err.contains("neither on the PATH nor in ~/.cargo/bin"),
496 "{err}"
497 );
498 assert!(!source.use_fallback, "the PATH comes first again next time");
499
500 let mut source = RemoteSource::new(sh_target(
502 "echo 'Permission denied (publickey)' >&2; exit 255",
503 Some(missing),
504 ));
505 let err = source.poll().unwrap_err().to_string();
506 assert!(err.contains("Permission denied"), "{err}");
507 assert!(!source.use_fallback);
508 }
509
510 #[test]
511 fn missing_program_is_reported_and_retried_later() {
512 let mut source = RemoteSource::new(RemoteTarget {
513 name: "nowhere".to_owned(),
514 program: "/nonexistent/ssh".to_owned(),
515 args: Vec::new(),
516 fallback_args: None,
517 });
518 let err = source.poll().unwrap_err().to_string();
519 assert!(err.contains("cannot start"), "{err}");
520 let err = source.poll().unwrap_err().to_string();
522 assert!(
523 err.contains("retrying") && err.contains("cannot start"),
524 "{err}"
525 );
526 }
527
528 #[cfg(unix)]
529 #[test]
530 fn stderr_explains_an_agent_that_exits() {
531 let mut source = RemoteSource::new(RemoteTarget {
533 name: "fake".to_owned(),
534 program: "sh".to_owned(),
535 args: vec![
536 "-c".to_owned(),
537 "echo 'rigtop: command not found' >&2; exit 127".to_owned(),
538 ],
539 fallback_args: None,
540 });
541 let err = source.poll().unwrap_err().to_string();
542 assert!(err.contains("fake: rigtop: command not found"), "{err}");
543 }
544
545 #[cfg(unix)]
546 #[test]
547 fn incompatible_protocol_is_rejected() {
548 let mut source = RemoteSource::new(RemoteTarget {
549 name: "old".to_owned(),
550 program: "sh".to_owned(),
551 args: vec![
552 "-c".to_owned(),
553 r#"echo '{"type":"hello","protocol":999,"version":"9.9.9"}'; sleep 5"#.to_owned(),
554 ],
555 fallback_args: None,
556 });
557 let err = source.poll().unwrap_err().to_string();
558 assert!(err.contains("protocol 999"), "{err}");
559 }
560}