1use std::{future::Future, pin::Pin, sync::Arc};
2
3use async_channel::{Receiver, Sender};
4
5use askama::Template as _;
6
7use crate::ssh::{PrepareSsh, SshEnvironments, SshServer, SshServerError};
8use crate::stdin_watch::StdinWatchSignal;
9use crate::{ContainerPath, HostRoute};
10
11#[derive(Debug, Clone)]
14pub enum ExecLifetime {
15 Foreground,
19 Background {
26 stdin_blocked: Sender<StdinWatchSignal>,
28 },
29}
30
31#[derive(Debug)]
33pub enum ContainerExecOutcome {
34 Completed {
36 output: std::process::Output,
38 killed: Vec<crate::JobProcess>,
41 },
42 Killed,
44}
45
46pub trait ContainerExec: Send + Sync {
52 fn exec(
61 &self,
62 container_id: &str,
63 script: &str,
64 working_dir: &str,
65 kill_rx: Receiver<()>,
66 stdin_rx: Receiver<Vec<u8>>,
67 lifetime: ExecLifetime,
68 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
69
70 #[allow(clippy::too_many_arguments)]
79 fn exec_streamed(
80 &self,
81 container_id: &str,
82 script: &str,
83 working_dir: &str,
84 kill_rx: Receiver<()>,
85 stdin_rx: Receiver<Vec<u8>>,
86 stdout: Sender<Vec<u8>>,
87 lifetime: ExecLifetime,
88 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
89}
90
91pub trait ContainerExecImpl: Send + Sync {
94 fn exec_boxed<'a>(
96 &'a self,
97 container_id: &'a str,
98 script: &'a str,
99 working_dir: &'a str,
100 kill_rx: Receiver<()>,
101 stdin_rx: Receiver<Vec<u8>>,
102 lifetime: ExecLifetime,
103 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
104
105 #[allow(clippy::too_many_arguments)]
108 fn exec_streamed_boxed<'a>(
109 &'a self,
110 container_id: &'a str,
111 script: &'a str,
112 working_dir: &'a str,
113 kill_rx: Receiver<()>,
114 stdin_rx: Receiver<Vec<u8>>,
115 stdout: Sender<Vec<u8>>,
116 lifetime: ExecLifetime,
117 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
118}
119
120#[derive(Clone)]
126pub struct AnyContainerExec {
127 inner: Arc<dyn ContainerExecImpl>,
128}
129
130impl std::fmt::Debug for AnyContainerExec {
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 f.debug_struct("AnyContainerExec").finish_non_exhaustive()
133 }
134}
135
136impl AnyContainerExec {
137 #[must_use]
139 pub fn new<T>(inner: Arc<T>) -> Self
140 where
141 T: ContainerExec + 'static,
142 {
143 Self { inner }
144 }
145}
146
147impl ContainerExec for AnyContainerExec {
148 fn exec(
149 &self,
150 container_id: &str,
151 script: &str,
152 working_dir: &str,
153 kill_rx: Receiver<()>,
154 stdin_rx: Receiver<Vec<u8>>,
155 lifetime: ExecLifetime,
156 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
157 let inner = Arc::clone(&self.inner);
158 let container_id = container_id.to_string();
159 let script = script.to_string();
160 let working_dir = working_dir.to_string();
161
162 async move {
163 inner
164 .exec_boxed(
165 &container_id,
166 &script,
167 &working_dir,
168 kill_rx,
169 stdin_rx,
170 lifetime,
171 )
172 .await
173 }
174 }
175
176 fn exec_streamed(
177 &self,
178 container_id: &str,
179 script: &str,
180 working_dir: &str,
181 kill_rx: Receiver<()>,
182 stdin_rx: Receiver<Vec<u8>>,
183 stdout: Sender<Vec<u8>>,
184 lifetime: ExecLifetime,
185 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
186 let inner = Arc::clone(&self.inner);
187 let container_id = container_id.to_string();
188 let script = script.to_string();
189 let working_dir = working_dir.to_string();
190
191 async move {
192 inner
193 .exec_streamed_boxed(
194 &container_id,
195 &script,
196 &working_dir,
197 kill_rx,
198 stdin_rx,
199 stdout,
200 lifetime,
201 )
202 .await
203 }
204 }
205}
206
207#[derive(Clone)]
209pub struct ContainerShellRuntime {
210 exec: Arc<dyn ContainerExecImpl>,
211 container_id: String,
212 host_route: HostRoute,
213 workspace_mount: Option<crate::MountRoot>,
216}
217
218impl std::fmt::Debug for ContainerShellRuntime {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 f.debug_struct("ContainerShellRuntime")
221 .field("container_id", &self.container_id)
222 .field("host_route", &self.host_route)
223 .field("workspace_mount", &self.workspace_mount)
224 .finish_non_exhaustive()
225 }
226}
227
228impl ContainerShellRuntime {
229 #[must_use]
234 pub fn new(
235 container_id: impl Into<String>,
236 host_route: HostRoute,
237 exec: AnyContainerExec,
238 ) -> Self {
239 let container_id = container_id.into();
240 assert!(
241 !container_id.trim().is_empty(),
242 "container runtime requires a non-empty container_id"
243 );
244 Self {
245 exec: exec.inner,
246 container_id,
247 host_route,
248 workspace_mount: None,
249 }
250 }
251
252 #[must_use]
257 pub fn with_workspace_mount(mut self, mount: crate::MountRoot) -> Self {
258 self.workspace_mount = Some(mount);
259 self
260 }
261
262 #[must_use]
264 pub const fn workspace_mount(&self) -> Option<&crate::MountRoot> {
265 self.workspace_mount.as_ref()
266 }
267
268 #[must_use]
269 pub fn container_id(&self) -> &str {
271 &self.container_id
272 }
273
274 #[must_use]
276 pub const fn host_route(&self) -> &HostRoute {
277 &self.host_route
278 }
279
280 pub(crate) fn exec(&self) -> Arc<dyn ContainerExecImpl> {
281 Arc::clone(&self.exec)
282 }
283
284 #[must_use]
287 pub fn probe(&self) -> ContainerProbe {
288 ContainerProbe::from_parts(self.exec(), self.container_id.clone())
289 }
290}
291
292#[derive(Debug, thiserror::Error)]
294pub enum ContainerProbeError {
295 #[error("the container could not run the probe: {0}")]
297 Exec(String),
298 #[error("the probe exited with {status}: {stderr}")]
300 Failed {
301 status: std::process::ExitStatus,
303 stderr: String,
305 },
306 #[error("the container killed the probe")]
308 Killed,
309 #[error("the probe answered bytes that are not UTF-8")]
311 NotText,
312 #[error("the probe answered `{0}`, which is not understood")]
314 Unreadable(String),
315}
316
317fn free_bytes_from_df(output: &str) -> Option<u64> {
320 let kib: u64 = output
321 .lines()
322 .last()?
323 .split_whitespace()
324 .nth(3)?
325 .parse()
326 .ok()?;
327 kib.checked_mul(1024)
328}
329
330#[derive(Clone)]
333pub struct ContainerProbe {
334 exec: Arc<dyn ContainerExecImpl>,
335 container_id: String,
336 home: ContainerPath,
338}
339
340#[derive(askama::Template)]
342#[template(path = "container_disk_free.sh", escape = "none")]
343struct DiskFreeScript<'a> {
344 path: std::borrow::Cow<'a, str>,
346}
347
348impl std::fmt::Debug for ContainerProbe {
349 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350 f.debug_struct("ContainerProbe")
351 .field("container_id", &self.container_id)
352 .finish_non_exhaustive()
353 }
354}
355
356impl ContainerProbe {
357 #[must_use]
362 pub fn new(exec: &AnyContainerExec, container_id: impl Into<String>) -> Self {
363 Self::from_parts(Arc::clone(&exec.inner), container_id.into())
364 }
365
366 fn from_parts(exec: Arc<dyn ContainerExecImpl>, container_id: String) -> Self {
367 Self {
368 exec,
369 container_id,
370 home: ContainerPath::new(crate::terminal::CONTAINER_EXEC_WORKING_DIR)
371 .expect("the container working directory is absolute"),
372 }
373 }
374
375 #[must_use]
377 pub fn with_home(mut self, home: ContainerPath) -> Self {
378 self.home = home;
379 self
380 }
381
382 #[must_use]
384 pub const fn home(&self) -> &ContainerPath {
385 &self.home
386 }
387
388 pub async fn free_bytes(&self) -> Result<u64, ContainerProbeError> {
400 let script = DiskFreeScript {
401 path: shell_words::quote(self.home.as_str()),
402 }
403 .render()
404 .expect("the disk probe template renders");
405 let output = self.read(&script).await?;
406 free_bytes_from_df(&output).ok_or(ContainerProbeError::Unreadable(output))
407 }
408
409 pub async fn read(&self, script: &str) -> Result<String, ContainerProbeError> {
417 let (_kill, kill_rx) = async_channel::bounded::<()>(1);
421 let (stdin, stdin_rx) = async_channel::unbounded::<Vec<u8>>();
422 drop(stdin);
423 let outcome = self
424 .exec
425 .exec_boxed(
426 &self.container_id,
427 script,
428 "/",
429 kill_rx,
430 stdin_rx,
431 ExecLifetime::Foreground,
432 )
433 .await
434 .map_err(ContainerProbeError::Exec)?;
435 match outcome {
436 ContainerExecOutcome::Completed { output, .. } if output.status.success() => {
437 String::from_utf8(output.stdout).map_err(|_| ContainerProbeError::NotText)
438 }
439 ContainerExecOutcome::Completed { output, .. } => Err(ContainerProbeError::Failed {
440 status: output.status,
441 stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
442 }),
443 ContainerExecOutcome::Killed => Err(ContainerProbeError::Killed),
444 }
445 }
446}
447
448impl<T: ContainerExec> ContainerExecImpl for T {
449 fn exec_boxed<'a>(
450 &'a self,
451 container_id: &'a str,
452 script: &'a str,
453 working_dir: &'a str,
454 kill_rx: Receiver<()>,
455 stdin_rx: Receiver<Vec<u8>>,
456 lifetime: ExecLifetime,
457 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
458 Box::pin(self.exec(
459 container_id,
460 script,
461 working_dir,
462 kill_rx,
463 stdin_rx,
464 lifetime,
465 ))
466 }
467
468 fn exec_streamed_boxed<'a>(
469 &'a self,
470 container_id: &'a str,
471 script: &'a str,
472 working_dir: &'a str,
473 kill_rx: Receiver<()>,
474 stdin_rx: Receiver<Vec<u8>>,
475 stdout: Sender<Vec<u8>>,
476 lifetime: ExecLifetime,
477 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
478 Box::pin(self.exec_streamed(
479 container_id,
480 script,
481 working_dir,
482 kill_rx,
483 stdin_rx,
484 stdout,
485 lifetime,
486 ))
487 }
488}
489
490#[derive(Clone, Default)]
499pub struct ShellSessionRegistry {
500 ssh: SshEnvironments,
501}
502
503impl std::fmt::Debug for ShellSessionRegistry {
504 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
505 f.debug_struct("ShellSessionRegistry")
506 .finish_non_exhaustive()
507 }
508}
509
510impl ShellSessionRegistry {
511 pub fn add_ssh_server(
521 &self,
522 server: SshServer,
523 prepare: impl PrepareSsh,
524 ) -> Result<(), SshServerError> {
525 self.ssh.add(server, prepare)
526 }
527
528 #[must_use = "the removed server, or `None` when no server has the name"]
532 pub fn remove_ssh_server(&self, name: &str) -> Option<SshServer> {
533 self.ssh.remove(name)
534 }
535
536 #[must_use]
538 pub fn ssh_servers(&self) -> Vec<SshServer> {
539 self.ssh.list()
540 }
541
542 pub(crate) const fn ssh_environments(&self) -> &SshEnvironments {
543 &self.ssh
544 }
545
546 #[cfg(test)]
548 pub(crate) fn with_ssh_client(mut self, client: crate::ssh::SshClient) -> Self {
549 self.ssh = self.ssh.with_client(client);
550 self
551 }
552}
553
554#[cfg(all(test, unix))]
555mod disk_probe_tests {
556 use std::os::unix::process::ExitStatusExt as _;
557 use std::sync::Mutex;
558
559 use async_channel::{Receiver, Sender};
560
561 use super::*;
562
563 struct Df {
565 answer: &'static str,
566 exit: i32,
567 scripts: Mutex<Vec<String>>,
568 }
569
570 impl ContainerExec for Df {
571 fn exec(
572 &self,
573 _container_id: &str,
574 script: &str,
575 working_dir: &str,
576 _kill_rx: Receiver<()>,
577 _stdin_rx: Receiver<Vec<u8>>,
578 _lifetime: ExecLifetime,
579 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
580 self.scripts
581 .lock()
582 .unwrap()
583 .push(format!("{working_dir}: {script}"));
584 std::future::ready(Ok(ContainerExecOutcome::Completed {
585 output: std::process::Output {
586 status: std::process::ExitStatus::from_raw(self.exit << 8),
587 stdout: self.answer.as_bytes().to_vec(),
588 stderr: b"df: no such directory".to_vec(),
589 },
590 killed: Vec::new(),
591 }))
592 }
593
594 fn exec_streamed(
595 &self,
596 _container_id: &str,
597 _script: &str,
598 _working_dir: &str,
599 _kill_rx: Receiver<()>,
600 _stdin_rx: Receiver<Vec<u8>>,
601 _stdout: Sender<Vec<u8>>,
602 _lifetime: ExecLifetime,
603 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
604 std::future::ready(Err("a probe is never streamed".to_string()))
605 }
606 }
607
608 fn probe(answer: &'static str, exit: i32) -> (Arc<Df>, ContainerProbe) {
609 let df = Arc::new(Df {
610 answer,
611 exit,
612 scripts: Mutex::new(Vec::new()),
613 });
614 let exec = AnyContainerExec::new(Arc::clone(&df));
615 (df, ContainerProbe::new(&exec, "box"))
616 }
617
618 const DF: &str = "Filesystem 1024-blocks Used Available Capacity Mounted on\noverlay 10485760 4194304 6291456 41% /workspace\n";
619
620 #[tokio::test]
621 async fn the_container_reports_the_free_space_of_its_home_filesystem() {
622 let (df, probe) = probe(DF, 0);
623 assert_eq!(probe.free_bytes().await.unwrap(), 6_291_456 * 1024);
624 let scripts = df.scripts.lock().unwrap();
625 assert_eq!(*scripts, ["/: df -Pk -- /workspace"]);
626 }
627
628 #[tokio::test]
629 async fn a_home_with_spaces_is_quoted_for_the_shell() {
630 let (df, probe) = probe(DF, 0);
631 let probe = probe.with_home(ContainerPath::new("/my work").unwrap());
632 probe.free_bytes().await.unwrap();
633 assert_eq!(*df.scripts.lock().unwrap(), ["/: df -Pk -- '/my work'"]);
634 }
635
636 #[tokio::test]
637 async fn a_df_that_fails_or_answers_something_else_is_an_error() {
638 let (_, failing) = probe("", 1);
639 assert!(matches!(
640 failing.free_bytes().await,
641 Err(ContainerProbeError::Failed { .. })
642 ));
643 let (_, odd) = probe("all clear\n", 0);
644 assert!(matches!(
645 odd.free_bytes().await,
646 Err(ContainerProbeError::Unreadable(_))
647 ));
648 }
649}
650
651#[cfg(test)]
652mod tests {
653 use super::{ShellSessionRegistry, SshServer};
654 use crate::{PreparedSsh, RemoteLaunch};
655
656 #[test]
657 fn every_clone_of_a_registry_shares_its_live_server_set() {
658 let registry = ShellSessionRegistry::default();
659 let subagent = registry.clone();
660 let prod = SshServer {
661 name: "prod".to_string(),
662 target: "root@example.com".to_string(),
663 };
664 registry
665 .add_ssh_server(
666 prod.clone(),
667 PreparedSsh::new(None, RemoteLaunch::new("/opt/tools/bin", "/bin/bash")),
668 )
669 .unwrap();
670 assert_eq!(subagent.ssh_servers(), std::slice::from_ref(&prod));
671 assert_eq!(subagent.remove_ssh_server("prod"), Some(prod));
672 assert_eq!(registry.ssh_servers(), []);
673 }
674}