Skip to main content

rigtop_core/
remote.rs

1//! A [`DataSource`] for a remote host, reached by running `rigtop --agent`
2//! through the system's `ssh` (OpenSSH; `ssh.exe` on Windows).
3//!
4//! Using the system client means `~/.ssh/config`, keys, agents and
5//! `ProxyJump` all work as on the command line. Authentication must not
6//! need a prompt (`BatchMode`), since there is no terminal to ask on.
7
8use 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::{
17    AgentMessage, ClientMessage, FEATURE_WATCH_PROCESSES, PROTOCOL_VERSION, write_message,
18};
19use crate::snapshot::Snapshot;
20use crate::source::{DataSource, ProcessSignal, SourceError};
21
22/// Command run on the remote host by default.
23pub const DEFAULT_REMOTE_COMMAND: &str = "rigtop --agent";
24/// Tried in order when the default command is not found: the install
25/// script puts rigtop in `~/.local/bin` and `cargo install` in
26/// `~/.cargo/bin`, which non-interactive SSH sessions often lack on their
27/// `PATH`. Release binaries come first: they update without building.
28pub const FALLBACK_REMOTE_COMMANDS: [&str; 2] =
29    ["~/.local/bin/rigtop --agent", "~/.cargo/bin/rigtop --agent"];
30/// Exit status of POSIX shells for "command not found".
31const NOT_FOUND_STATUS: i32 = 127;
32
33/// Minimum time between connection attempts after a failure.
34const RECONNECT_DELAY: Duration = Duration::from_secs(5);
35/// How long to wait for the first snapshot of a new connection (SSH
36/// handshake plus the agent's warm-up sample).
37const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
38/// How long to wait for the agent to answer a signal request.
39const SIGNAL_TIMEOUT: Duration = Duration::from_secs(10);
40/// stderr lines kept to explain failures.
41const STDERR_LINES: usize = 20;
42
43/// How to start the agent: a program and its arguments.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct RemoteTarget {
46    /// Short name for messages (e.g. the SSH destination).
47    pub name: String,
48    /// Program to run (normally `ssh`).
49    pub program: String,
50    /// Its arguments.
51    pub args: Vec<String>,
52    /// Arguments to try in order when the remote command is not found
53    /// (for the default command: [`FALLBACK_REMOTE_COMMANDS`]).
54    pub fallback_args: Vec<Vec<String>>,
55}
56
57impl RemoteTarget {
58    /// Runs `remote_command` on `destination` (anything `ssh` accepts:
59    /// a `~/.ssh/config` host, `user@host`, ...).
60    pub fn ssh(destination: &str, remote_command: &str) -> Self {
61        let options = [
62            // No password or host key prompts: fail instead of hanging.
63            "BatchMode=yes",
64            "ConnectTimeout=10",
65            // Notice dead connections within ~45 s.
66            "ServerAliveInterval=15",
67            "ServerAliveCountMax=3",
68        ];
69        let mut args = vec!["-T".to_owned()];
70        for option in options {
71            args.push("-o".to_owned());
72            args.push(option.to_owned());
73        }
74        // `--` keeps a destination starting with "-" from being an option.
75        args.push("--".to_owned());
76        args.push(destination.to_owned());
77        args.push(remote_command.to_owned());
78        // Only the default command falls back; one set by the user is
79        // taken as it is.
80        let fallback_args = if remote_command == DEFAULT_REMOTE_COMMAND {
81            FALLBACK_REMOTE_COMMANDS
82                .iter()
83                .map(|command| {
84                    let mut fallback = args.clone();
85                    *fallback.last_mut().expect("command pushed above") = (*command).to_owned();
86                    fallback
87                })
88                .collect()
89        } else {
90            Vec::new()
91        };
92        Self {
93            name: destination.to_owned(),
94            program: "ssh".to_owned(),
95            args,
96            fallback_args,
97        }
98    }
99}
100
101/// What the reader thread passes on.
102enum Incoming {
103    Message(AgentMessage),
104    /// stdout closed: the agent or ssh exited.
105    Closed,
106}
107
108/// One running agent process.
109struct Connection {
110    child: Child,
111    stdin: ChildStdin,
112    incoming: Receiver<Incoming>,
113    /// Last lines of the process's stderr (ssh errors, "command not found").
114    stderr: Arc<Mutex<VecDeque<String>>>,
115    /// Whether a snapshot has arrived on this connection yet.
116    established: bool,
117}
118
119impl Connection {
120    fn spawn(target: &RemoteTarget, args: &[String]) -> Result<Self, SourceError> {
121        let mut command = Command::new(&target.program);
122        command
123            .args(args)
124            .stdin(Stdio::piped())
125            .stdout(Stdio::piped())
126            .stderr(Stdio::piped());
127        #[cfg(windows)]
128        {
129            use std::os::windows::process::CommandExt;
130            // CREATE_NO_WINDOW: a GUI must not flash a console for ssh.exe.
131            command.creation_flags(0x0800_0000);
132        }
133        let mut child = command.spawn().map_err(|err| {
134            SourceError::Disconnected(format!("cannot start {}: {err}", target.program))
135        })?;
136        let stdin = child.stdin.take().expect("piped stdin");
137        let stdout = child.stdout.take().expect("piped stdout");
138        let stderr_pipe = child.stderr.take().expect("piped stderr");
139
140        let (tx, incoming) = mpsc::channel();
141        thread::Builder::new()
142            .name("rigtop-remote-reader".to_owned())
143            .spawn(move || {
144                for line in BufReader::new(stdout).lines() {
145                    let Ok(line) = line else { break };
146                    // Lines that are not protocol messages (e.g. a login
147                    // banner printed by a shell profile) are skipped.
148                    if let Ok(message) = serde_json::from_str::<AgentMessage>(&line)
149                        && tx.send(Incoming::Message(message)).is_err()
150                    {
151                        return;
152                    }
153                }
154                let _ = tx.send(Incoming::Closed);
155            })
156            .map_err(SourceError::Io)?;
157
158        let stderr = Arc::new(Mutex::new(VecDeque::new()));
159        let lines = Arc::clone(&stderr);
160        thread::Builder::new()
161            .name("rigtop-remote-stderr".to_owned())
162            .spawn(move || {
163                for line in BufReader::new(stderr_pipe).lines() {
164                    let Ok(line) = line else { break };
165                    let mut lines = lines.lock().unwrap_or_else(|e| e.into_inner());
166                    if lines.len() == STDERR_LINES {
167                        lines.pop_front();
168                    }
169                    lines.push_back(line);
170                }
171            })
172            .map_err(SourceError::Io)?;
173
174        Ok(Self {
175            child,
176            stdin,
177            incoming,
178            stderr,
179            established: false,
180        })
181    }
182
183    fn send(&mut self, message: &ClientMessage) -> Result<(), SourceError> {
184        write_message(&mut self.stdin, message).map_err(SourceError::Io)
185    }
186
187    /// Explanation for a lost connection, from the process's stderr, and
188    /// whether the remote command was not found.
189    fn failure(&mut self) -> (String, bool) {
190        // Give the stderr thread a moment to collect the final lines.
191        thread::sleep(Duration::from_millis(100));
192        let status = self.child.try_wait().ok().flatten();
193        let lines = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
194        let detail = lines
195            .iter()
196            .rev()
197            .find(|l| !l.trim().is_empty())
198            .cloned()
199            .unwrap_or_default();
200        // ssh passes the remote exit status on; cmd.exe says "not recognized".
201        let not_found = status.and_then(|s| s.code()) == Some(NOT_FOUND_STATUS)
202            || detail.contains("command not found")
203            || detail.contains("not recognized");
204        let reason = match (detail.is_empty(), status) {
205            (false, _) => detail,
206            (true, Some(status)) => format!("connection closed ({status})"),
207            (true, None) => "connection closed".to_owned(),
208        };
209        (reason, not_found)
210    }
211}
212
213impl Drop for Connection {
214    fn drop(&mut self) {
215        // Closing stdin makes the agent exit; killing ssh ends the session
216        // right away instead of waiting for it.
217        let _ = self.child.kill();
218        let _ = self.child.wait();
219    }
220}
221
222/// Snapshots from `rigtop --agent` on another machine.
223pub struct RemoteSource {
224    target: RemoteTarget,
225    connection: Option<Connection>,
226    last_attempt: Option<Instant>,
227    interval: Duration,
228    process_limit: Option<usize>,
229    /// See [`DataSource::watch_processes`].
230    watched_pids: Vec<u32>,
231    /// The connected agent understands [`ClientMessage::WatchProcesses`].
232    agent_watches: bool,
233    /// Snapshots received while waiting for something else (signal results).
234    pending: VecDeque<Snapshot>,
235    /// rigtop version from the agent's greeting.
236    agent_version: String,
237    /// Why the last connection failed, repeated while waiting to retry.
238    last_error: Option<String>,
239    /// Which command starts the agent: 0 for the configured one, then the
240    /// fallbacks in order.
241    attempt: usize,
242    /// The command was not found and the next one should be tried at once.
243    retry_now: bool,
244}
245
246impl RemoteSource {
247    /// Creates a source; the connection is made on the first poll.
248    pub fn new(target: RemoteTarget) -> Self {
249        Self {
250            target,
251            connection: None,
252            last_attempt: None,
253            interval: Duration::from_secs(1),
254            process_limit: None,
255            watched_pids: Vec::new(),
256            agent_watches: false,
257            pending: VecDeque::new(),
258            agent_version: String::new(),
259            last_error: None,
260            attempt: 0,
261            retry_now: false,
262        }
263    }
264
265    /// The target this source connects to.
266    pub fn target(&self) -> &RemoteTarget {
267        &self.target
268    }
269
270    /// Returns the connection, (re)connecting if needed and allowed.
271    fn connection(&mut self) -> Result<&mut Connection, SourceError> {
272        if self.connection.is_none() {
273            if let Some(at) = self.last_attempt {
274                let wait = RECONNECT_DELAY.saturating_sub(at.elapsed());
275                if !wait.is_zero() {
276                    let reason = self.last_error.as_deref().unwrap_or("not connected");
277                    return Err(SourceError::Disconnected(format!(
278                        "{}: {reason} (retrying in {}s)",
279                        self.target.name,
280                        wait.as_secs() + 1
281                    )));
282                }
283            }
284            self.last_attempt = Some(Instant::now());
285            let args = match self.attempt {
286                0 => &self.target.args,
287                n => self
288                    .target
289                    .fallback_args
290                    .get(n - 1)
291                    .unwrap_or(&self.target.args),
292            };
293            let mut connection = match Connection::spawn(&self.target, args) {
294                Ok(connection) => connection,
295                Err(err) => {
296                    self.last_error = Some(match &err {
297                        SourceError::Disconnected(reason) => reason.clone(),
298                        other => other.to_string(),
299                    });
300                    return Err(err);
301                }
302            };
303            // Known from the greeting of this agent.
304            self.agent_watches = false;
305            // Agents start with their own default; send our settings.
306            let sent = connection
307                .send(&ClientMessage::SetInterval {
308                    ms: self.interval.as_millis() as u64,
309                })
310                .and_then(|()| {
311                    connection.send(&ClientMessage::SetProcessLimit {
312                        limit: self.process_limit,
313                    })
314                });
315            self.connection = Some(connection);
316            if sent.is_err() {
317                // ssh already exited (bad host, auth failure): its stderr
318                // says why, which beats "broken pipe".
319                return Err(self.disconnect(None));
320            }
321        }
322        Ok(self.connection.as_mut().expect("connected above"))
323    }
324
325    /// Drops the connection and returns an error explaining why.
326    fn disconnect(&mut self, reason: Option<String>) -> SourceError {
327        let (mut reason, not_found) = match (reason, self.connection.as_mut()) {
328            (Some(reason), _) => (reason, false),
329            (None, Some(connection)) => connection.failure(),
330            (None, None) => ("connection closed".to_owned(), false),
331        };
332        self.connection = None;
333        if not_found && !self.target.fallback_args.is_empty() {
334            if self.attempt < self.target.fallback_args.len() {
335                self.attempt += 1;
336                self.retry_now = true;
337                self.last_attempt = None;
338            } else {
339                // None worked; start over with the PATH next time, in case
340                // rigtop gets installed there.
341                self.attempt = 0;
342                reason = format!(
343                    "rigtop is not on the PATH, in ~/.local/bin or in ~/.cargo/bin ({reason})"
344                );
345            }
346        }
347        let error = SourceError::Disconnected(format!("{}: {reason}", self.target.name));
348        self.last_error = Some(reason);
349        error
350    }
351
352    /// Waits up to `timeout` for the next message.
353    fn next_message(&mut self, timeout: Duration) -> Result<Option<AgentMessage>, SourceError> {
354        let connection = self.connection()?;
355        match connection.incoming.recv_timeout(timeout) {
356            Ok(Incoming::Message(message)) => Ok(Some(message)),
357            Ok(Incoming::Closed) | Err(RecvTimeoutError::Disconnected) => {
358                Err(self.disconnect(None))
359            }
360            Err(RecvTimeoutError::Timeout) => Ok(None),
361        }
362    }
363
364    /// Handles messages that are not what the caller waits for. Returns an
365    /// error for fatal ones (protocol mismatch).
366    /// Sends the watched processes to the connected agent.
367    fn send_watched(&mut self) {
368        if let Some(connection) = self.connection.as_mut() {
369            let _ = connection.send(&ClientMessage::WatchProcesses {
370                pids: self.watched_pids.clone(),
371            });
372        }
373    }
374
375    fn absorb(&mut self, message: AgentMessage) -> Result<(), SourceError> {
376        match message {
377            AgentMessage::Hello {
378                protocol, version, ..
379            } if protocol != PROTOCOL_VERSION => {
380                let reason = format!(
381                    "agent speaks protocol {protocol} (rigtop {version}), this client speaks {PROTOCOL_VERSION}; \
382                     install the same rigtop version on both sides"
383                );
384                // Do not retry quickly against an incompatible agent.
385                self.last_attempt = Some(Instant::now());
386                Err(self.disconnect(Some(reason)))
387            }
388            AgentMessage::Hello {
389                version, features, ..
390            } => {
391                self.agent_version = version;
392                self.agent_watches = features.iter().any(|f| f == FEATURE_WATCH_PROCESSES);
393                if self.agent_watches && !self.watched_pids.is_empty() {
394                    self.send_watched();
395                }
396                Ok(())
397            }
398            AgentMessage::SignalResult { .. } => Ok(()),
399            AgentMessage::Snapshot { mut snapshot } => {
400                // Agents before 0.9.1 do not put their version in snapshots.
401                if snapshot.host.rigtop_version.is_empty() {
402                    snapshot.host.rigtop_version = self.agent_version.clone();
403                }
404                if let Some(connection) = self.connection.as_mut() {
405                    connection.established = true;
406                }
407                self.last_error = None;
408                self.pending.push_back(*snapshot);
409                Ok(())
410            }
411            AgentMessage::Error { message } => Err(SourceError::Remote(message)),
412        }
413    }
414}
415
416impl RemoteSource {
417    /// One attempt at [`DataSource::poll`].
418    fn poll_once(&mut self) -> Result<Snapshot, SourceError> {
419        // A new connection needs time for SSH and the agent's warm-up.
420        let established = self.connection.as_ref().is_some_and(|c| c.established);
421        let timeout = if established {
422            self.interval * 3 + Duration::from_secs(5)
423        } else {
424            CONNECT_TIMEOUT
425        };
426        let deadline = Instant::now() + timeout;
427        loop {
428            // Drain everything already received; keep only the newest snapshot.
429            while let Some(message) = self.next_message(Duration::ZERO)? {
430                self.absorb(message)?;
431            }
432            if let Some(newest) = self.pending.pop_back() {
433                self.pending.clear();
434                return Ok(newest);
435            }
436            let remaining = deadline.saturating_duration_since(Instant::now());
437            if remaining.is_zero() {
438                return Err(self.disconnect(Some("no data from the agent (timed out)".to_owned())));
439            }
440            if let Some(message) = self.next_message(remaining)? {
441                self.absorb(message)?;
442            }
443        }
444    }
445}
446
447impl DataSource for RemoteSource {
448    /// Returns the newest snapshot from the agent, waiting for one if none
449    /// arrived since the previous poll.
450    fn poll(&mut self) -> Result<Snapshot, SourceError> {
451        loop {
452            match self.poll_once() {
453                // Not found: try the next place (~/.local/bin, then
454                // ~/.cargo/bin) right away.
455                Err(_) if std::mem::take(&mut self.retry_now) => continue,
456                result => return result,
457            }
458        }
459    }
460
461    fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
462        if self
463            .connection()?
464            .send(&ClientMessage::Signal { pid, signal })
465            .is_err()
466        {
467            return Err(self.disconnect(None));
468        }
469        let deadline = Instant::now() + SIGNAL_TIMEOUT;
470        loop {
471            let remaining = deadline.saturating_duration_since(Instant::now());
472            if remaining.is_zero() {
473                return Err(SourceError::Remote(format!(
474                    "no answer to the signal for {pid}"
475                )));
476            }
477            match self.next_message(remaining)? {
478                Some(AgentMessage::SignalResult {
479                    pid: answered,
480                    error,
481                    ..
482                }) if answered == pid => {
483                    return match error {
484                        None => Ok(()),
485                        Some(error) => Err(SourceError::Remote(error)),
486                    };
487                }
488                Some(other) => self.absorb(other)?,
489                None => {}
490            }
491        }
492    }
493
494    fn set_interval(&mut self, interval: Duration) {
495        self.interval = interval;
496        if let Some(connection) = self.connection.as_mut() {
497            let _ = connection.send(&ClientMessage::SetInterval {
498                ms: interval.as_millis() as u64,
499            });
500        }
501    }
502
503    fn set_process_limit(&mut self, limit: Option<usize>) {
504        self.process_limit = limit;
505        if let Some(connection) = self.connection.as_mut() {
506            let _ = connection.send(&ClientMessage::SetProcessLimit { limit });
507        }
508    }
509
510    fn watch_processes(&mut self, pids: Vec<u32>) {
511        self.watched_pids = pids;
512        // Older agents would answer with an error; their snapshots leave
513        // `watched_pids` empty, so the client knows it cannot tell.
514        if self.agent_watches {
515            self.send_watched();
516        }
517    }
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    #[test]
525    fn ssh_target_uses_batch_mode_and_keeps_the_destination_safe() {
526        let target = RemoteTarget::ssh("zefat", DEFAULT_REMOTE_COMMAND);
527        assert_eq!(target.program, "ssh");
528        assert_eq!(target.name, "zefat");
529        assert!(target.args.windows(2).any(|w| w == ["-o", "BatchMode=yes"]));
530        let n = target.args.len();
531        assert_eq!(&target.args[n - 3..], ["--", "zefat", "rigtop --agent"]);
532        // The default command falls back to ~/.local/bin, then ~/.cargo/bin ...
533        let fallbacks: Vec<&str> = target
534            .fallback_args
535            .iter()
536            .map(|args| args[n - 1].as_str())
537            .collect();
538        assert_eq!(fallbacks, FALLBACK_REMOTE_COMMANDS);
539        assert_eq!(&target.fallback_args[0][n - 3..n - 1], ["--", "zefat"]);
540        // ... a command the user chose does not.
541        let custom = RemoteTarget::ssh("zefat", "/opt/rigtop/bin/rigtop --agent");
542        assert!(custom.fallback_args.is_empty());
543    }
544
545    /// `sh -c <script>` standing in for ssh.
546    #[cfg(unix)]
547    fn sh_target(script: &str, fallbacks: &[&str]) -> RemoteTarget {
548        let args = |script: &str| vec!["-c".to_owned(), script.to_owned()];
549        RemoteTarget {
550            name: "fake".to_owned(),
551            program: "sh".to_owned(),
552            args: args(script),
553            fallback_args: fallbacks.iter().map(|script| args(script)).collect(),
554        }
555    }
556
557    #[cfg(unix)]
558    #[test]
559    fn command_not_found_tries_the_fallback_at_once() {
560        // Found nowhere: every attempt in one poll, and a clear message.
561        let missing = "echo 'zsh:1: command not found: rigtop' >&2; exit 127";
562        let mut source = RemoteSource::new(sh_target(missing, &[missing, missing]));
563        let err = source.poll().unwrap_err().to_string();
564        assert!(
565            err.contains("not on the PATH, in ~/.local/bin or in ~/.cargo/bin"),
566            "{err}"
567        );
568        assert_eq!(source.attempt, 0, "the PATH comes first again next time");
569
570        // Other failures do not switch to the fallbacks.
571        let mut source = RemoteSource::new(sh_target(
572            "echo 'Permission denied (publickey)' >&2; exit 255",
573            &[missing],
574        ));
575        let err = source.poll().unwrap_err().to_string();
576        assert!(err.contains("Permission denied"), "{err}");
577        assert_eq!(source.attempt, 0);
578    }
579
580    #[test]
581    fn missing_program_is_reported_and_retried_later() {
582        let mut source = RemoteSource::new(RemoteTarget {
583            name: "nowhere".to_owned(),
584            program: "/nonexistent/ssh".to_owned(),
585            args: Vec::new(),
586            fallback_args: Vec::new(),
587        });
588        let err = source.poll().unwrap_err().to_string();
589        assert!(err.contains("cannot start"), "{err}");
590        // The next attempt waits for the reconnect delay, repeating the cause.
591        let err = source.poll().unwrap_err().to_string();
592        assert!(
593            err.contains("retrying") && err.contains("cannot start"),
594            "{err}"
595        );
596    }
597
598    #[cfg(unix)]
599    #[test]
600    fn stderr_explains_an_agent_that_exits() {
601        // Stands in for ssh failing, e.g. "rigtop: command not found".
602        let mut source = RemoteSource::new(RemoteTarget {
603            name: "fake".to_owned(),
604            program: "sh".to_owned(),
605            args: vec![
606                "-c".to_owned(),
607                "echo 'rigtop: command not found' >&2; exit 127".to_owned(),
608            ],
609            fallback_args: Vec::new(),
610        });
611        let err = source.poll().unwrap_err().to_string();
612        assert!(err.contains("fake: rigtop: command not found"), "{err}");
613    }
614
615    #[cfg(unix)]
616    #[test]
617    fn incompatible_protocol_is_rejected() {
618        let mut source = RemoteSource::new(RemoteTarget {
619            name: "old".to_owned(),
620            program: "sh".to_owned(),
621            args: vec![
622                "-c".to_owned(),
623                r#"echo '{"type":"hello","protocol":999,"version":"9.9.9"}'; sleep 5"#.to_owned(),
624            ],
625            fallback_args: Vec::new(),
626        });
627        let err = source.poll().unwrap_err().to_string();
628        assert!(err.contains("protocol 999"), "{err}");
629    }
630
631    #[cfg(unix)]
632    #[test]
633    fn old_agents_get_their_version_from_the_greeting() {
634        // An agent before 0.9.1: no version in its snapshots.
635        let mut source = RemoteSource::new(RemoteTarget {
636            name: "old".to_owned(),
637            program: "sh".to_owned(),
638            args: vec![
639                "-c".to_owned(),
640                r#"echo '{"type":"hello","protocol":1,"version":"0.8.2"}'
641                   echo '{"type":"snapshot","snapshot":{"host":{"hostname":"nas"}}}'
642                   sleep 5"#
643                    .to_owned(),
644            ],
645            fallback_args: Vec::new(),
646        });
647        let snapshot = source.poll().unwrap();
648        assert_eq!(snapshot.host.hostname, "nas");
649        assert_eq!(snapshot.host.rigtop_version, "0.8.2");
650        assert_eq!(
651            crate::view::version_note(&snapshot).as_deref(),
652            Some("agent 0.8.2")
653        );
654    }
655}