Skip to main content

isothrum_runner/run/
endpoints.rs

1//! A deployment's published service endpoints, as this computer reaches them: where the
2//! deployment says each one is, or, when its network is internal to a jump host (the run's
3//! `ssh_jump` value, `user@host`), a local forward through that host to it.
4//!
5//! A forward is the console tunnels' ([`crate::graphical::tunnel`]): `ssh -N -L
6//! 127.0.0.1:<free port>:<host>:<port>` through the jump host, signed in with the run's key (its
7//! `ssh_private_key_file`, else the runner's), the jump host's keys checked against the run's
8//! `ssh_jump_known_hosts_file` value when it has one, else pinned the first time the run meets
9//! it, recorded in the run's tool ledger. This process keeps it while the run publishes the
10//! endpoint, so a caller asks again and again and gets the same address: one whose `ssh` ended is
11//! opened again at the next ask; one the run no longer publishes is ended. A `down` ends them from
12//! any process, through the ledger, and so does this process's exit (`kill_on_drop`).
13
14use std::collections::BTreeMap;
15use std::sync::{LazyLock, Mutex, PoisonError};
16
17use super::Running;
18use crate::Result;
19use crate::events::Emitter;
20use crate::formats::{Published, ToolCx};
21use crate::graphical::Tunnel;
22use crate::graphical::tunnel::{self, Purpose, To};
23use crate::options::RunOptions;
24use crate::ssh::Login;
25
26/// The run's value naming the jump host its network is reached through.
27const JUMP_VAR: &str = "ssh_jump";
28
29/// The run's value naming the private key that signs in there.
30const KEY_VAR: &str = "ssh_private_key_file";
31
32/// The run's value naming a `known_hosts` file of the jump host's keys.
33const KNOWN_HOSTS_VAR: &str = "ssh_jump_known_hosts_file";
34
35/// The forwards this process keeps, by run (its runner's home and its name), each by the
36/// `host:port` it goes to.
37type Forwards = BTreeMap<(std::path::PathBuf, String), BTreeMap<String, Tunnel>>;
38
39/// The forwards this process keeps.
40static FORWARDS: LazyLock<Mutex<Forwards>> = LazyLock::new(Mutex::default);
41
42/// A service endpoint the deployment publishes, as this computer reaches it.
43#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
44#[non_exhaustive]
45pub struct ServiceEndpoint {
46    /// Its name, as the deployment gives it (`<machine>/<service>`, by the `published` output's convention).
47    pub name: String,
48    /// Where this computer reaches it, `host:port`: the deployment's address, or a forward's on
49    /// this computer's loopback. None when it can't be reached now ([`ServiceEndpoint::why`]).
50    pub address: Option<String>,
51    /// Whether `address` is a local forward through the run's jump host.
52    pub forwarded: bool,
53    /// Why it can't be reached now: its forward didn't open.
54    pub why: Option<String>,
55}
56
57impl Running<'_> {
58    /// The service endpoints the deployment publishes (a Terraform module's `published` output:
59    /// `{ "web/site" = "192.0.2.10:8080" }`), each where this computer reaches it: as the
60    /// deployment gives it, or, when the run has a jump host (its `ssh_jump` value, `user@host`:
61    /// the deployment's network is internal to it), at a local forward through that host, kept
62    /// open by this process (the module docs say how long). One whose forward doesn't open says
63    /// why, the others are given all the same. `opts` gives what the tools get. Emits nothing and
64    /// never locks the run.
65    ///
66    /// # Errors
67    ///
68    /// As the deployment's outputs can't be read; `input_invalid` when the run's `ssh_jump` isn't
69    /// `user@host`.
70    pub async fn service_endpoints(&self, opts: &RunOptions) -> Result<Vec<ServiceEndpoint>> {
71        let emitter = Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref());
72        let (published, jump, key, known_hosts) = self
73            .with_cx(opts, &emitter, self.runner.config.processes.as_ref(), async |cx: &ToolCx<'_>| {
74                Ok((self.driver.published(cx).await?, cx.var(JUMP_VAR), cx.var(KEY_VAR), cx.var(KNOWN_HOSTS_VAR)))
75            })
76            .await?;
77        let Some(jump) = jump else {
78            return Ok(published
79                .into_iter()
80                .map(|p| reached(&p, Ok(format!("{}:{}", p.host, p.port)), false))
81                .collect());
82        };
83        let via = jump
84            .split_once('@')
85            .and_then(|(user, host)| Login::new(user, host))
86            .ok_or_else(|| crate::Error::Input {
87                name: JUMP_VAR.to_owned(),
88                reason: format!("`{}` isn't `user@host`", jump.escape_debug()),
89            })?;
90        let run = (self.runner.config.home.clone(), self.name.to_string());
91        let wanted: Vec<String> = published.iter().map(|p| format!("{}:{}", p.host, p.port)).collect();
92        let mut kept = locked().remove(&run).unwrap_or_default();
93        kept.retain(|to, _| wanted.contains(to));
94        let mut out = Vec::with_capacity(published.len());
95        for (p, to) in published.iter().zip(wanted) {
96            if !kept.get_mut(&to).is_some_and(Tunnel::runs) {
97                kept.remove(&to);
98                let target = To {
99                    via: via.clone(),
100                    host: p.host.clone(),
101                    port: p.port,
102                    key: key.clone().map(Into::into),
103                    known_hosts: known_hosts.clone().map(Into::into),
104                };
105                match tunnel::open(self.runner, &self.name, &self.state_dir(), Purpose::Endpoint(&p.name), &target).await {
106                    Ok(forward) => {
107                        kept.insert(to.clone(), forward);
108                    }
109                    Err(e) => {
110                        out.push(reached(p, Err(e.to_string()), true));
111                        continue;
112                    }
113                }
114            }
115            let at = kept.get(&to).map(|t| t.local().to_string());
116            out.push(reached(p, at.ok_or_else(String::new), true));
117        }
118        locked().insert(run, kept);
119        Ok(out)
120    }
121}
122
123/// `p` reached at `at` (or why not), `forwarded` or not.
124fn reached(p: &Published, at: std::result::Result<String, String>, forwarded: bool) -> ServiceEndpoint {
125    let (address, why) = match at {
126        Ok(at) => (Some(at), None),
127        Err(why) => (None, Some(why)),
128    };
129    ServiceEndpoint {
130        name: p.name.clone(),
131        address,
132        forwarded,
133        why,
134    }
135}
136
137/// The forwards this process keeps, locked.
138fn locked() -> std::sync::MutexGuard<'static, Forwards> {
139    FORWARDS.lock().unwrap_or_else(PoisonError::into_inner)
140}