isothrum_runner/run/attach.rs
1//! Hot-adding a run's own on-demand access machine into the running run, and hot-removing it: a
2//! manifest machine marked `on_demand`, which the initial `up` left down (a Compose `access`
3//! profile, a Vagrant `autostart: false`). `attach` brings it up on a chosen network with the
4//! image the user picked, `detach` takes it back out. A run that declares no access machine has
5//! nothing to attach: an embedder adds a machine of its own as an ordinary machine of the run
6//! ([`Running::update`], [`Running::retire`], [`Running::console_command`]).
7
8use isoloom_manifest::Machine;
9use serde::Serialize;
10use serde_json::json;
11
12use super::Running;
13use super::operation::Done;
14use crate::Result;
15use crate::driver;
16use crate::error::Error;
17use crate::events::{Emitter, Events};
18use crate::options::RunOptions;
19use crate::state::Op;
20
21/// What a hot-add produced: the access machine brought up, and where to reach it.
22#[derive(Debug, Clone, Serialize)]
23#[non_exhaustive]
24pub struct AttachReport {
25 /// Its name, as status reports it: the access machine's manifest name.
26 pub machine: String,
27 /// Its native name (the Compose service / Vagrant define).
28 pub native: String,
29 /// The run's network it is on (the chosen one, else its first).
30 pub network: Option<String>,
31 /// Its address on that network, where the user reaches it.
32 pub address: Option<String>,
33 /// The image or box it was brought up with, when the user picked one.
34 pub image: Option<String>,
35}
36
37/// Which access machine an attach adds, where, from what: as [`Running::attach`] takes them.
38#[derive(Debug, Clone, Copy, Default)]
39#[non_exhaustive]
40pub struct AccessPick<'a> {
41 /// The on-demand machine, when the run has more than one.
42 pub machine: Option<&'a str>,
43 /// The run's network it joins (default: its first).
44 pub network: Option<&'a str>,
45 /// What it runs from (default: the run's).
46 pub image: Option<&'a str>,
47}
48
49impl<'a> AccessPick<'a> {
50 /// The on-demand machine `name`.
51 #[must_use]
52 pub fn with_machine(mut self, name: &'a str) -> AccessPick<'a> {
53 self.machine = Some(name);
54 self
55 }
56
57 /// Joins the run's network `name`.
58 #[must_use]
59 pub fn with_network(mut self, name: &'a str) -> AccessPick<'a> {
60 self.network = Some(name);
61 self
62 }
63
64 /// Runs from `image` (a container image, or a Vagrant box).
65 #[must_use]
66 pub fn with_image(mut self, image: &'a str) -> AccessPick<'a> {
67 self.image = Some(image);
68 self
69 }
70}
71
72impl Running<'_> {
73 /// Hot-adds the run's on-demand access machine into the running run, with `opts` (the params
74 /// and secrets the run's operations take), brought up with the user-picked `image` (its baked
75 /// default otherwise), on `network` when given. `image` is a container image for a Compose
76 /// access service, the Vagrant box for an access VM. `machine` names which on-demand machine,
77 /// needed only when the run has more than one. `network` is one of the manifest's networks: a
78 /// Compose access service's container also joins it, by the native name the run gives it (as
79 /// status shows it); a VM's networks are its Vagrantfile's, so a Vagrant run refuses one.
80 ///
81 /// # Errors
82 ///
83 /// Fails with `machine_unknown` for a named machine the run doesn't have,
84 /// `machine_ambiguous` when it has several and none is named, `network_unknown` for a
85 /// `network` it doesn't have, `unsupported` when it declares no access machine (or the target
86 /// brings none up later: a server or a cloud) and for a network it can't join (a Vagrant
87 /// run's), `not_running` when the run isn't up, `tool_failed` when the container can't join
88 /// the network (one already on it has), and as the other operations do for a step or the
89 /// state.
90 pub async fn attach(&self, pick: AccessPick<'_>, opts: &RunOptions, events: &dyn Events) -> Result<AttachReport> {
91 let AccessPick { machine, network, image } = pick;
92 self.operate(Op::Attach, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
93 let target = self.access_machine(machine)?;
94 if let Some(n) = network {
95 self.network_named(n)?;
96 }
97 let (_, mut cx) = self.existing(connected, e).await?;
98 let native = network.map(|n| self.native_network(&cx, n)).transpose()?;
99 self.observe_running(&mut cx).await?;
100 self.driver.attach(&cx, target, image, native.as_deref()).await?;
101 let report = report(target, network, image);
102 // The whole report: `isothrum attach --json` says where it is with this event alone.
103 let data = report.data();
104 Ok(Done {
105 value: report,
106 ok: true,
107 data,
108 state: None,
109 })
110 })
111 .await
112 }
113
114 /// Hot-removes the run's access machine from the running run, with `opts`, leaving the rest
115 /// up: the on-demand machine chosen as [`Running::attach`] chooses it, taken out as
116 /// [`Running::retire`] takes a machine out (its Compose service removed through the `access`
117 /// profile, its VM destroyed).
118 ///
119 /// # Errors
120 ///
121 /// Fails as [`Running::attach`] does for the machine choice and the target, and as the other
122 /// operations do for a step or the state.
123 pub async fn detach(&self, machine: Option<&str>, opts: &RunOptions, events: &dyn Events) -> Result<()> {
124 self.operate(Op::Detach, opts, events, async |connected: &RunOptions, e: &Emitter<'_>| {
125 let target = self.access_machine(machine)?;
126 let (_, cx) = self.existing(connected, e).await?;
127 self.take_out(&cx, target).await?;
128 Ok(Done {
129 value: (),
130 ok: true,
131 data: json!({ "machine": target.name.as_str(), "native": driver::native_name(target) }),
132 state: None,
133 })
134 })
135 .await
136 }
137
138 /// The manifest's network `name`, refused with `network_unknown` when the run has none so
139 /// named.
140 fn network_named(&self, name: &str) -> Result<&isoloom_manifest::Network> {
141 self.manifest()
142 .networks
143 .iter()
144 .find(|n| n.name.as_str() == name)
145 .ok_or_else(|| Error::NetworkUnknown {
146 run: self.name().to_string(),
147 network: name.to_owned(),
148 })
149 }
150
151 /// The native name of the run's network `name` (`web-portal_backend`), as status renders it.
152 fn native_network(&self, cx: &crate::executor::Cx<'_>, name: &str) -> Result<String> {
153 self.networks(cx)
154 .into_iter()
155 .find(|n| n.name == name)
156 .and_then(|n| n.native)
157 .ok_or_else(|| Error::Unsupported {
158 what: format!("joining network `{name}`: the run doesn't say its native name"),
159 })
160 }
161
162 /// Which access machine an attach targets: the on-demand machine `machine` names, or the
163 /// only one.
164 fn access_machine(&self, machine: Option<&str>) -> Result<&Machine> {
165 let mut on_demand = self.manifest().machines.iter().filter(|m| m.on_demand);
166 if let Some(name) = machine {
167 return on_demand.find(|m| m.name.as_str() == name).ok_or_else(|| Error::MachineUnknown {
168 run: self.name().to_string(),
169 machine: name.to_owned(),
170 });
171 }
172 match (on_demand.next(), on_demand.next()) {
173 (Some(one), None) => Ok(one),
174 (None, _) => Err(Error::Unsupported {
175 what: "hot-adding an access machine (this run declares no access machine)".to_owned(),
176 }),
177 _ => Err(Error::MachineAmbiguous {
178 run: self.name().to_string(),
179 which: "on-demand machines",
180 machines: self.on_demand_names(),
181 }),
182 }
183 }
184
185 /// The run's on-demand access machines, by name, for the "name one" message.
186 fn on_demand_names(&self) -> String {
187 self.manifest()
188 .machines
189 .iter()
190 .filter(|m| m.on_demand)
191 .map(|m| m.name.as_str())
192 .collect::<Vec<_>>()
193 .join(", ")
194 }
195}
196
197impl AttachReport {
198 /// The report as its `result` event's `data`: each field by its JSON name, built from its
199 /// strings (so it can't fail as writing through a serializer could).
200 fn data(&self) -> serde_json::Value {
201 serde_json::json!({
202 "machine": self.machine,
203 "native": self.native,
204 "network": self.network,
205 "address": self.address,
206 "image": self.image,
207 })
208 }
209}
210
211/// The report of an attach of `m`: its identity and address from the manifest, with the picked
212/// `network` and `image`.
213fn report(m: &Machine, network: Option<&str>, image: Option<&str>) -> AttachReport {
214 let (network, address) = address_on(m, network);
215 AttachReport {
216 machine: m.name.as_str().to_owned(),
217 native: driver::native_name(m).to_owned(),
218 network,
219 address,
220 image: image.map(str::to_owned),
221 }
222}
223
224/// The machine's static address on `network` (its first when none is named), from the manifest.
225fn address_on(m: &Machine, network: Option<&str>) -> (Option<String>, Option<String>) {
226 match network {
227 Some(n) => (
228 Some(n.to_owned()),
229 m.addresses.iter().find(|(k, _)| k.as_str() == n).map(|(_, a)| a.to_string()),
230 ),
231 None => m
232 .addresses
233 .iter()
234 .next()
235 .map_or((None, None), |(k, a)| (Some(k.as_str().to_owned()), Some(a.to_string()))),
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 /// The event's data is the report as its own JSON writes it, field for field: a field added
244 /// to one and not the other fails this.
245 #[test]
246 fn the_events_data_is_the_report() {
247 let report = AttachReport {
248 machine: "user".into(),
249 native: "access".into(),
250 network: Some("lan".into()),
251 address: None,
252 image: Some("debian:12".into()),
253 };
254 assert_eq!(report.data(), serde_json::to_value(&report).unwrap());
255 }
256}