1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use std::{future::Future, pin::Pin, sync::Arc};
use async_channel::{Receiver, Sender};
use askama::Template as _;
use crate::ssh::{PrepareSsh, SshEnvironments, SshServer, SshServerError};
use crate::stdin_watch::StdinWatchSignal;
use crate::{ContainerPath, HostRoute};
/// How long the processes a container command leaves running when its
/// top-level shell exits may live.
#[derive(Debug, Clone)]
pub enum ExecLifetime {
/// None: they are killed with the shell and reported in
/// [`ContainerExecOutcome::Completed`]'s `killed`. Its stdin is not
/// watched.
Foreground,
/// All of them: the execution ends with its last process. Its stdin is
/// watched: implementations send one [`StdinWatchSignal::Blocked`] each
/// time a process of the command's tree starts waiting to read the stdin
/// pipe with nothing buffered — and send again only after the command was
/// fed and blocks anew — or a single [`StdinWatchSignal::Failed`] when the
/// watch cannot run at all.
Background {
/// Where the stdin watch reports.
stdin_blocked: Sender<StdinWatchSignal>,
},
}
/// Outcome of a container execution request.
#[derive(Debug)]
pub enum ContainerExecOutcome {
/// The command ran to completion.
Completed {
/// Its exit status and output.
output: std::process::Output,
/// The processes it left running that an [`ExecLifetime::Foreground`]
/// execution killed; empty for any other.
killed: Vec<crate::JobProcess>,
},
/// The command was terminated before it finished.
Killed,
}
/// Trait for executing commands inside a container.
///
/// Implementations provide the bridge between aither-sandbox and a specific
/// container runtime (e.g., Docker via bollard). The framework defines this trait;
/// the application (may) provides the implementation.
pub trait ContainerExec: Send + Sync {
/// Execute a terminal command payload inside the container, returning stdout/stderr and exit code.
///
/// `stdin_rx` is the command's stdin; a closed channel is EOF. When
/// `stdin_blocked` is given, implementations send one
/// [`StdinWatchSignal::Blocked`] each time a process of the command's
/// tree starts waiting to read the stdin pipe with nothing buffered —
/// and send again only after the command was fed and blocks anew — or a
/// single [`StdinWatchSignal::Failed`] when the watch cannot run at all.
fn exec(
&self,
container_id: &str,
script: &str,
working_dir: &str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
/// Executes a command like [`Self::exec`], handing its stdout on chunk by
/// chunk through `stdout` as it arrives instead of collecting it.
///
/// The returned outcome carries the exit status and stderr; its stdout is
/// empty. `stdout` is bounded, so a consumer that stops reading holds the
/// command back. The command is killed, as when `kill_rx` fires, once
/// `kill_rx` fires or closes, or once `stdout` has no receiver left.
/// `lifetime` is [`Self::exec`]'s.
#[allow(clippy::too_many_arguments)]
fn exec_streamed(
&self,
container_id: &str,
script: &str,
working_dir: &str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
stdout: Sender<Vec<u8>>,
lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
}
/// Object-safe twin of [`ContainerExec`], used only through
/// [`AnyContainerExec`].
pub trait ContainerExecImpl: Send + Sync {
/// Execute a command inside a container through a boxed future.
fn exec_boxed<'a>(
&'a self,
container_id: &'a str,
script: &'a str,
working_dir: &'a str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
lifetime: ExecLifetime,
) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
/// Execute a command inside a container, streaming its stdout, through a
/// boxed future.
#[allow(clippy::too_many_arguments)]
fn exec_streamed_boxed<'a>(
&'a self,
container_id: &'a str,
script: &'a str,
working_dir: &'a str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
stdout: Sender<Vec<u8>>,
lifetime: ExecLifetime,
) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
}
/// Backend-agnostic container executor handle.
///
/// This wraps any [`ContainerExec`] implementation into a cloneable concrete
/// type that can be passed around without exposing runtime-specific concrete
/// executor types.
#[derive(Clone)]
pub struct AnyContainerExec {
inner: Arc<dyn ContainerExecImpl>,
}
impl std::fmt::Debug for AnyContainerExec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyContainerExec").finish_non_exhaustive()
}
}
impl AnyContainerExec {
/// Creates a new handle from a concrete container executor implementation.
#[must_use]
pub fn new<T>(inner: Arc<T>) -> Self
where
T: ContainerExec + 'static,
{
Self { inner }
}
}
impl ContainerExec for AnyContainerExec {
fn exec(
&self,
container_id: &str,
script: &str,
working_dir: &str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
let inner = Arc::clone(&self.inner);
let container_id = container_id.to_string();
let script = script.to_string();
let working_dir = working_dir.to_string();
async move {
inner
.exec_boxed(
&container_id,
&script,
&working_dir,
kill_rx,
stdin_rx,
lifetime,
)
.await
}
}
fn exec_streamed(
&self,
container_id: &str,
script: &str,
working_dir: &str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
stdout: Sender<Vec<u8>>,
lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
let inner = Arc::clone(&self.inner);
let container_id = container_id.to_string();
let script = script.to_string();
let working_dir = working_dir.to_string();
async move {
inner
.exec_streamed_boxed(
&container_id,
&script,
&working_dir,
kill_rx,
stdin_rx,
stdout,
lifetime,
)
.await
}
}
}
/// Container runtime session metadata.
#[derive(Clone)]
pub struct ContainerShellRuntime {
exec: Arc<dyn ContainerExecImpl>,
container_id: String,
host_route: HostRoute,
/// The host directory the container mounts as its workspace, declared by
/// whoever mounts it.
workspace_mount: Option<crate::MountRoot>,
}
impl std::fmt::Debug for ContainerShellRuntime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContainerShellRuntime")
.field("container_id", &self.container_id)
.field("host_route", &self.host_route)
.field("workspace_mount", &self.workspace_mount)
.finish_non_exhaustive()
}
}
impl ContainerShellRuntime {
/// Creates a container shell runtime.
///
/// # Panics
/// Panics if `container_id` is empty after trimming.
#[must_use]
pub fn new(
container_id: impl Into<String>,
host_route: HostRoute,
exec: AnyContainerExec,
) -> Self {
let container_id = container_id.into();
assert!(
!container_id.trim().is_empty(),
"container runtime requires a non-empty container_id"
);
Self {
exec: exec.inner,
container_id,
host_route,
workspace_mount: None,
}
}
/// Declares the host directory the container mounts as its workspace and
/// where it appears inside. A subagent's commands are confined in the
/// container through it, so a container session without it cannot launch
/// subagents.
#[must_use]
pub fn with_workspace_mount(mut self, mount: crate::MountRoot) -> Self {
self.workspace_mount = Some(mount);
self
}
/// The workspace mount, when declared.
#[must_use]
pub const fn workspace_mount(&self) -> Option<&crate::MountRoot> {
self.workspace_mount.as_ref()
}
#[must_use]
/// Returns the container id.
pub fn container_id(&self) -> &str {
&self.container_id
}
/// Returns where the host is reachable from inside the container.
#[must_use]
pub const fn host_route(&self) -> &HostRoute {
&self.host_route
}
pub(crate) fn exec(&self) -> Arc<dyn ContainerExecImpl> {
Arc::clone(&self.exec)
}
/// A reader of the container's own state: what a harness that watches
/// the container's memory and disk asks it.
#[must_use]
pub fn probe(&self) -> ContainerProbe {
ContainerProbe::from_parts(self.exec(), self.container_id.clone())
}
}
/// Why a probe of a container failed.
#[derive(Debug, thiserror::Error)]
pub enum ContainerProbeError {
/// The container could not run the script.
#[error("the container could not run the probe: {0}")]
Exec(String),
/// The script ran and failed.
#[error("the probe exited with {status}: {stderr}")]
Failed {
/// The exit status it returned.
status: std::process::ExitStatus,
/// What it wrote to its standard error.
stderr: String,
},
/// The container killed the probe before it finished.
#[error("the container killed the probe")]
Killed,
/// The script answered bytes that are not text.
#[error("the probe answered bytes that are not UTF-8")]
NotText,
/// The script answered text that is not what it was asked for.
#[error("the probe answered `{0}`, which is not understood")]
Unreadable(String),
}
/// The free bytes `df -Pk` reports: the `Available` column, in KiB, of its
/// last line.
fn free_bytes_from_df(output: &str) -> Option<u64> {
let kib: u64 = output
.lines()
.last()?
.split_whitespace()
.nth(3)?
.parse()
.ok()?;
kib.checked_mul(1024)
}
/// Runs short read-only scripts inside a container and returns what they
/// print, through the same exec path commands use.
#[derive(Clone)]
pub struct ContainerProbe {
exec: Arc<dyn ContainerExecImpl>,
container_id: String,
/// The directory the agent works in inside the container.
home: ContainerPath,
}
/// `df` over the filesystem holding a path, in POSIX format.
#[derive(askama::Template)]
#[template(path = "container_disk_free.sh", escape = "none")]
struct DiskFreeScript<'a> {
/// The path, quoted for the shell.
path: std::borrow::Cow<'a, str>,
}
impl std::fmt::Debug for ContainerProbe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContainerProbe")
.field("container_id", &self.container_id)
.finish_non_exhaustive()
}
}
impl ContainerProbe {
/// A probe of container `container_id` through `exec`.
///
/// The agent's home directory in the container is the one commands run
/// in until [`Self::with_home`] says otherwise.
#[must_use]
pub fn new(exec: &AnyContainerExec, container_id: impl Into<String>) -> Self {
Self::from_parts(Arc::clone(&exec.inner), container_id.into())
}
fn from_parts(exec: Arc<dyn ContainerExecImpl>, container_id: String) -> Self {
Self {
exec,
container_id,
home: ContainerPath::new(crate::terminal::CONTAINER_EXEC_WORKING_DIR)
.expect("the container working directory is absolute"),
}
}
/// Names the directory the agent works in inside the container.
#[must_use]
pub fn with_home(mut self, home: ContainerPath) -> Self {
self.home = home;
self
}
/// The directory the agent works in inside the container.
#[must_use]
pub const fn home(&self) -> &ContainerPath {
&self.home
}
/// The bytes free to the container's processes on the filesystem that
/// holds the agent's home directory, as that filesystem reports them:
/// bounded by its own size limit when the container has one.
///
/// # Errors
///
/// Fails when the container cannot run `df` or answers something else.
///
/// # Panics
///
/// Panics when the built-in probe template does not render.
pub async fn free_bytes(&self) -> Result<u64, ContainerProbeError> {
let script = DiskFreeScript {
path: shell_words::quote(self.home.as_str()),
}
.render()
.expect("the disk probe template renders");
let output = self.read(&script).await?;
free_bytes_from_df(&output).ok_or(ContainerProbeError::Unreadable(output))
}
/// Runs `script` in the container's root directory and returns its
/// standard output.
///
/// # Errors
///
/// Fails when the container cannot run the script, the script exits
/// non-zero or its output is not text.
pub async fn read(&self, script: &str) -> Result<String, ContainerProbeError> {
// Dropping the kill sender would kill the exec, so it lives to the
// end of the call; the dropped stdin sender is the EOF the script
// reads.
let (_kill, kill_rx) = async_channel::bounded::<()>(1);
let (stdin, stdin_rx) = async_channel::unbounded::<Vec<u8>>();
drop(stdin);
let outcome = self
.exec
.exec_boxed(
&self.container_id,
script,
"/",
kill_rx,
stdin_rx,
ExecLifetime::Foreground,
)
.await
.map_err(ContainerProbeError::Exec)?;
match outcome {
ContainerExecOutcome::Completed { output, .. } if output.status.success() => {
String::from_utf8(output.stdout).map_err(|_| ContainerProbeError::NotText)
}
ContainerExecOutcome::Completed { output, .. } => Err(ContainerProbeError::Failed {
status: output.status,
stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
}),
ContainerExecOutcome::Killed => Err(ContainerProbeError::Killed),
}
}
}
impl<T: ContainerExec> ContainerExecImpl for T {
fn exec_boxed<'a>(
&'a self,
container_id: &'a str,
script: &'a str,
working_dir: &'a str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
lifetime: ExecLifetime,
) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
Box::pin(self.exec(
container_id,
script,
working_dir,
kill_rx,
stdin_rx,
lifetime,
))
}
fn exec_streamed_boxed<'a>(
&'a self,
container_id: &'a str,
script: &'a str,
working_dir: &'a str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
stdout: Sender<Vec<u8>>,
lifetime: ExecLifetime,
) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
Box::pin(self.exec_streamed(
container_id,
script,
working_dir,
kill_rx,
stdin_rx,
stdout,
lifetime,
))
}
}
/// The SSH servers a shell's commands may run on, as the embedder prepared
/// them.
///
/// The home environment is the shell's [`Sandbox`](crate::Sandbox): its
/// backend says where commands with no `location` run.
///
/// Cloning shares the SSH server set: a server added or removed through one
/// holder is seen by every other, the terminals of subagents included.
#[derive(Clone, Default)]
pub struct ShellSessionRegistry {
ssh: SshEnvironments,
}
impl std::fmt::Debug for ShellSessionRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ShellSessionRegistry")
.finish_non_exhaustive()
}
}
impl ShellSessionRegistry {
/// Adds `server` to the set commands may run on, for every holder of this
/// registry. Its name and target are trimmed.
///
/// The server is not contacted: `prepare` runs when the first command
/// names it, see [`PrepareSsh`]. A [`PreparedSsh`](crate::PreparedSsh)
/// is a preparation already done.
///
/// # Errors
/// Rejects a blank name or target and a name another server has.
pub fn add_ssh_server(
&self,
server: SshServer,
prepare: impl PrepareSsh,
) -> Result<(), SshServerError> {
self.ssh.add(server, prepare)
}
/// Removes the server named `name`, returning it; `None` when no server
/// has that name. Commands already running there keep running; the next
/// command naming it fails.
#[must_use = "the removed server, or `None` when no server has the name"]
pub fn remove_ssh_server(&self, name: &str) -> Option<SshServer> {
self.ssh.remove(name)
}
/// The SSH servers commands may run on now, in the order they were added.
#[must_use]
pub fn ssh_servers(&self) -> Vec<SshServer> {
self.ssh.list()
}
pub(crate) const fn ssh_environments(&self) -> &SshEnvironments {
&self.ssh
}
/// Reaches every server through `client` instead of the default one.
#[cfg(test)]
pub(crate) fn with_ssh_client(mut self, client: crate::ssh::SshClient) -> Self {
self.ssh = self.ssh.with_client(client);
self
}
}
#[cfg(all(test, unix))]
mod disk_probe_tests {
use std::os::unix::process::ExitStatusExt as _;
use std::sync::Mutex;
use async_channel::{Receiver, Sender};
use super::*;
/// Answers `df` the way a container would, and records what it ran.
struct Df {
answer: &'static str,
exit: i32,
scripts: Mutex<Vec<String>>,
}
impl ContainerExec for Df {
fn exec(
&self,
_container_id: &str,
script: &str,
working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
self.scripts
.lock()
.unwrap()
.push(format!("{working_dir}: {script}"));
std::future::ready(Ok(ContainerExecOutcome::Completed {
output: std::process::Output {
status: std::process::ExitStatus::from_raw(self.exit << 8),
stdout: self.answer.as_bytes().to_vec(),
stderr: b"df: no such directory".to_vec(),
},
killed: Vec::new(),
}))
}
fn exec_streamed(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_stdout: Sender<Vec<u8>>,
_lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
std::future::ready(Err("a probe is never streamed".to_string()))
}
}
fn probe(answer: &'static str, exit: i32) -> (Arc<Df>, ContainerProbe) {
let df = Arc::new(Df {
answer,
exit,
scripts: Mutex::new(Vec::new()),
});
let exec = AnyContainerExec::new(Arc::clone(&df));
(df, ContainerProbe::new(&exec, "box"))
}
const DF: &str = "Filesystem 1024-blocks Used Available Capacity Mounted on\noverlay 10485760 4194304 6291456 41% /workspace\n";
#[tokio::test]
async fn the_container_reports_the_free_space_of_its_home_filesystem() {
let (df, probe) = probe(DF, 0);
assert_eq!(probe.free_bytes().await.unwrap(), 6_291_456 * 1024);
let scripts = df.scripts.lock().unwrap();
assert_eq!(*scripts, ["/: df -Pk -- /workspace"]);
}
#[tokio::test]
async fn a_home_with_spaces_is_quoted_for_the_shell() {
let (df, probe) = probe(DF, 0);
let probe = probe.with_home(ContainerPath::new("/my work").unwrap());
probe.free_bytes().await.unwrap();
assert_eq!(*df.scripts.lock().unwrap(), ["/: df -Pk -- '/my work'"]);
}
#[tokio::test]
async fn a_df_that_fails_or_answers_something_else_is_an_error() {
let (_, failing) = probe("", 1);
assert!(matches!(
failing.free_bytes().await,
Err(ContainerProbeError::Failed { .. })
));
let (_, odd) = probe("all clear\n", 0);
assert!(matches!(
odd.free_bytes().await,
Err(ContainerProbeError::Unreadable(_))
));
}
}
#[cfg(test)]
mod tests {
use super::{ShellSessionRegistry, SshServer};
use crate::{PreparedSsh, RemoteLaunch};
#[test]
fn every_clone_of_a_registry_shares_its_live_server_set() {
let registry = ShellSessionRegistry::default();
let subagent = registry.clone();
let prod = SshServer {
name: "prod".to_string(),
target: "root@example.com".to_string(),
};
registry
.add_ssh_server(
prod.clone(),
PreparedSsh::new(None, RemoteLaunch::new("/opt/tools/bin", "/bin/bash")),
)
.unwrap();
assert_eq!(subagent.ssh_servers(), std::slice::from_ref(&prod));
assert_eq!(subagent.remove_ssh_server("prod"), Some(prod));
assert_eq!(registry.ssh_servers(), []);
}
}