Skip to main content

isothrum_client/client/
home.rs

1//! What a client asks of a home besides its operations: a run's record, forgetting it, the runs
2//! past their lifetime, the way into a machine, its screen and its hypervisor's app, where its
3//! services are reached, the runner's key, and what the runs' downloads fetched. The client never
4//! opens the home's files.
5
6use isothrum_runner::{Download, DownloadRemoval, DownloadToAdopt, DownloadsToRemove, MachineUsage, NativeConsole, RunName, ServiceEndpoint, ShellCommand};
7
8use super::console::{self, HeldConsole};
9use super::{Client, Reply, Request, Result, unexpected};
10use crate::proto::{Command, OpOptions, Target};
11use crate::v1::RunRow;
12use crate::wire::write_line;
13
14impl Client {
15    /// `command`'s reply, as `pick` takes it; a reply of another kind is a protocol error.
16    async fn answer<T>(&self, command: Command, pick: impl FnOnce(Reply) -> std::result::Result<T, Box<Reply>>) -> Result<T> {
17        pick(self.request(command).await?).map_err(|other| unexpected(&other))
18    }
19
20    /// Run `run`'s record; none for a run never recorded.
21    ///
22    /// # Errors
23    ///
24    /// The store couldn't be read, or the connection ended.
25    pub async fn record(&self, run: &RunName) -> Result<Option<RunRow>> {
26        self.answer(Command::Record { run: run.clone() }, |reply| match reply {
27            Reply::Run { run: row, .. } => Ok(row.map(|r| *r)),
28            other => Err(Box::new(other)),
29        })
30        .await
31    }
32
33    /// Forgets run `run`'s record (what it created is left as it is).
34    ///
35    /// # Errors
36    ///
37    /// `locked` while an operation of the run is queued or running; the store couldn't be
38    /// written, or the connection ended.
39    pub async fn forget(&self, run: &RunName) -> Result<()> {
40        self.request(Command::Forget { run: run.clone() }).await.map(drop)
41    }
42
43    /// The recorded runs whose lifetime passed and that may still hold something: a reaper's
44    /// `down` each.
45    ///
46    /// # Errors
47    ///
48    /// The store couldn't be read, or the connection ended.
49    pub async fn expired(&self) -> Result<Vec<RunRow>> {
50        self.answer(Command::Expired, |reply| match reply {
51            Reply::Runs { runs, .. } => Ok(runs),
52            other => Err(Box::new(other)),
53        })
54        .await
55    }
56
57    /// The command that opens an interactive console into `machine` of run `run` (`target`:
58    /// where to open it, else as recorded), as `user` when given, for this client to run in its
59    /// own terminal.
60    ///
61    /// # Errors
62    ///
63    /// Where the run's format has no way in; the connection ended.
64    pub async fn console_command(&self, run: &RunName, target: Option<Target>, machine: &str, user: Option<&str>) -> Result<ShellCommand> {
65        let command = Command::ConsoleCommand {
66            run: run.clone(),
67            target,
68            machine: machine.to_owned(),
69            user: user.map(str::to_owned),
70        };
71        self.answer(command, |reply| match reply {
72            Reply::Shell { command: shell, .. } => Ok(shell),
73            other => Err(Box::new(other)),
74        })
75        .await
76    }
77
78    /// What opens running `machine` of run `run` in its hypervisor's own app, its hypervisor
79    /// asked with `options`' values and secrets.
80    ///
81    /// # Errors
82    ///
83    /// `no_console` when the hypervisor has no app or the machine isn't running; the
84    /// connection ended.
85    pub async fn native_console(&self, run: &RunName, target: Option<Target>, options: OpOptions, machine: &str) -> Result<NativeConsole> {
86        let command = Command::NativeConsole {
87            run: run.clone(),
88            target,
89            options,
90            machine: machine.to_owned(),
91        };
92        self.answer(command, |reply| match reply {
93            Reply::Native { console, .. } => Ok(console),
94            other => Err(Box::new(other)),
95        })
96        .await
97    }
98
99    /// Running `machine`'s graphical console, its hypervisor asked with `options`' values and
100    /// secrets, on a connection of its own that keeps its tunnel (when one carries it) open until
101    /// the [`HeldConsole`] is dropped.
102    ///
103    /// # Errors
104    ///
105    /// `no_console` when the machine has none, or it doesn't answer; `server_auth_failed` when
106    /// a server refuses the credentials; the service doesn't answer.
107    pub async fn graphical_console(&self, run: &RunName, target: Option<Target>, options: OpOptions, machine: &str) -> Result<HeldConsole> {
108        let (mut reader, mut writer) = self.dedicated().await?;
109        let command = Command::GraphicalConsole {
110            run: run.clone(),
111            target,
112            options,
113            machine: machine.to_owned(),
114        };
115        write_line(&mut writer, &Request { id: 1, command }).await?;
116        let console = console::of_reply(reader.next::<Reply>().await?)?;
117        Ok(HeldConsole {
118            console,
119            reader,
120            _writer: writer,
121        })
122    }
123
124    /// The service endpoints run `run` publishes, each where this computer reaches it: as the run
125    /// gives it, or at a local forward through its jump host, which the service keeps open. One
126    /// whose forward didn't open says why.
127    ///
128    /// # Errors
129    ///
130    /// The run's outputs can't be read; the connection ended.
131    pub async fn service_endpoints(&self, run: &RunName, target: Option<Target>, options: OpOptions) -> Result<Vec<ServiceEndpoint>> {
132        let command = Command::ServiceEndpoints {
133            run: run.clone(),
134            target,
135            options,
136        };
137        self.answer(command, |reply| match reply {
138            Reply::Endpoints { endpoints, .. } => Ok(endpoints),
139            other => Err(Box::new(other)),
140        })
141        .await
142    }
143
144    /// What each running machine of run `run` uses now (CPU and memory), by name, as its engine
145    /// samples it once; none for a format whose tool reports no per-machine figure.
146    ///
147    /// # Errors
148    ///
149    /// The run's engine doesn't answer, or its answer can't be read; the connection ended.
150    pub async fn usage(&self, run: &RunName, target: Option<Target>, options: OpOptions) -> Result<Vec<MachineUsage>> {
151        let command = Command::Usage {
152            run: run.clone(),
153            target,
154            options,
155        };
156        self.answer(command, |reply| match reply {
157            Reply::Usage { machines, .. } => Ok(machines),
158            other => Err(Box::new(other)),
159        })
160        .await
161    }
162
163    /// What the runs' own downloads fetched and the home records (images a pull pulled, boxes an
164    /// `up` added), oldest first, each with its size when it can be read.
165    ///
166    /// # Errors
167    ///
168    /// The store couldn't be read, or the connection ended.
169    pub async fn downloads(&self) -> Result<Vec<Download>> {
170        self.answer(Command::Downloads, |reply| match reply {
171            Reply::Downloads { downloads, .. } => Ok(downloads),
172            other => Err(Box::new(other)),
173        })
174        .await
175    }
176
177    /// Removes the recorded downloads `which` names, each on its own (never forced): how each
178    /// went, one its tool refused kept and said, the others removed.
179    ///
180    /// # Errors
181    ///
182    /// The store couldn't be read or written, or the connection ended.
183    pub async fn remove_downloads(&self, which: DownloadsToRemove) -> Result<Vec<DownloadRemoval>> {
184        self.answer(Command::RemoveDownloads { which }, |reply| match reply {
185            Reply::DownloadsRemoved { removed, .. } => Ok(removed),
186            other => Err(Box::new(other)),
187        })
188        .await
189    }
190
191    /// Adopts `adopted`, downloads fetched outside the runs (by an earlier program's own record),
192    /// into the home's record, each one on this computer now as it was fetched: they are listed
193    /// and removed like the runs' own. The downloads recorded for them, new or not.
194    ///
195    /// # Errors
196    ///
197    /// The engine or Vagrant couldn't say what they hold (nothing was recorded), the store
198    /// couldn't be written, or the connection ended.
199    pub async fn adopt_downloads(&self, adopted: Vec<DownloadToAdopt>) -> Result<Vec<Download>> {
200        self.answer(Command::AdoptDownloads { adopted }, |reply| match reply {
201            Reply::DownloadsAdopted { adopted: recorded, .. } => Ok(recorded),
202            other => Err(Box::new(other)),
203        })
204        .await
205    }
206
207    /// The IPv4 address blocks (CIDR) the networks of the engine Docker context `docker_context`
208    /// reaches hold (the current one when none is named), but those of run `except`'s own
209    /// networks: what a deployment's networks must stay clear of.
210    ///
211    /// # Errors
212    ///
213    /// Docker is missing or the engine can't say, or the connection ended.
214    pub async fn address_blocks_in_use(&self, except: Option<RunName>, docker_context: Option<String>) -> Result<Vec<String>> {
215        self.answer(Command::AddressBlocksInUse { except, docker_context }, |reply| match reply {
216            Reply::AddressBlocks { blocks, .. } => Ok(blocks),
217            other => Err(Box::new(other)),
218        })
219        .await
220    }
221
222    /// The public half of the runner's SSH key, one line (made when it has none).
223    ///
224    /// # Errors
225    ///
226    /// The key couldn't be made (`tool_missing` without `ssh-keygen`) or read; the connection
227    /// ended.
228    pub async fn public_key(&self) -> Result<String> {
229        self.answer(Command::PublicKey, |reply| match reply {
230            Reply::PublicKey { key, .. } => Ok(key),
231            other => Err(Box::new(other)),
232        })
233        .await
234    }
235}