use std::{future::Future, pin::Pin, sync::Arc};
use async_channel::{Receiver, Sender};
use askama::Template as _;
use crate::ContainerPath;
use crate::ssh::{SshEnvironments, SshServer, SshServerError};
use crate::stdin_watch::StdinWatchSignal;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub enum ExecLifetime {
Foreground,
Background {
stdin_blocked: Sender<StdinWatchSignal>,
},
}
#[derive(Debug)]
pub enum ContainerExecOutcome {
Completed {
output: std::process::Output,
killed: Vec<crate::JobProcess>,
},
Killed,
}
pub trait ContainerExec: Send + Sync {
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;
fn exec_streamed(
&self,
container_id: &str,
script: &str,
working_dir: &str,
kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
stdout: Sender<Vec<u8>>,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
}
pub trait ContainerExecImpl: Send + Sync {
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>>;
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>>,
) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
}
#[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 {
#[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>>,
) -> 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,
)
.await
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BridgeAddress(std::net::IpAddr);
#[derive(Debug, thiserror::Error)]
pub enum BridgeAddressError {
#[error("the unspecified address {0} would expose the container IPC bridge on every interface")]
Unspecified(std::net::IpAddr),
#[error("the multicast address {0} cannot bind the container IPC bridge")]
Multicast(std::net::IpAddr),
}
impl TryFrom<std::net::IpAddr> for BridgeAddress {
type Error = BridgeAddressError;
fn try_from(address: std::net::IpAddr) -> Result<Self, Self::Error> {
if address.is_unspecified() {
return Err(BridgeAddressError::Unspecified(address));
}
if address.is_multicast() {
return Err(BridgeAddressError::Multicast(address));
}
Ok(Self(address))
}
}
impl BridgeAddress {
#[must_use]
pub const fn ip(&self) -> std::net::IpAddr {
self.0
}
}
#[derive(Clone, Debug)]
pub struct ContainerIpcRoute {
host: String,
bind: BridgeAddress,
}
impl ContainerIpcRoute {
#[must_use]
pub fn new(host: impl Into<String>, bind: BridgeAddress) -> Self {
let host = host.into();
assert!(
!host.trim().is_empty(),
"container IPC route requires a non-empty host"
);
Self { host, bind }
}
#[must_use]
pub fn host(&self) -> &str {
&self.host
}
#[must_use]
pub const fn bind(&self) -> BridgeAddress {
self.bind
}
}
#[derive(Clone)]
pub struct ContainerShellRuntime {
exec: Arc<dyn ContainerExecImpl>,
container_id: String,
ipc_route: ContainerIpcRoute,
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("ipc_route", &self.ipc_route)
.field("workspace_mount", &self.workspace_mount)
.finish_non_exhaustive()
}
}
impl ContainerShellRuntime {
#[must_use]
pub fn new(
container_id: impl Into<String>,
ipc_route: ContainerIpcRoute,
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,
ipc_route,
workspace_mount: None,
}
}
#[must_use]
pub fn with_workspace_mount(mut self, mount: crate::MountRoot) -> Self {
self.workspace_mount = Some(mount);
self
}
#[must_use]
pub const fn workspace_mount(&self) -> Option<&crate::MountRoot> {
self.workspace_mount.as_ref()
}
#[must_use]
pub fn container_id(&self) -> &str {
&self.container_id
}
#[must_use]
pub const fn ipc_route(&self) -> &ContainerIpcRoute {
&self.ipc_route
}
pub(crate) fn exec(&self) -> Arc<dyn ContainerExecImpl> {
Arc::clone(&self.exec)
}
#[must_use]
pub fn probe(&self) -> ContainerProbe {
ContainerProbe::from_parts(self.exec(), self.container_id.clone())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ContainerProbeError {
#[error("the container could not run the probe: {0}")]
Exec(String),
#[error("the probe exited with {status}: {stderr}")]
Failed {
status: std::process::ExitStatus,
stderr: String,
},
#[error("the container killed the probe")]
Killed,
#[error("the probe answered bytes that are not UTF-8")]
NotText,
#[error("the probe answered `{0}`, which is not understood")]
Unreadable(String),
}
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)
}
#[derive(Clone)]
pub struct ContainerProbe {
exec: Arc<dyn ContainerExecImpl>,
container_id: String,
home: ContainerPath,
}
#[derive(askama::Template)]
#[template(path = "container_disk_free.sh", escape = "none")]
struct DiskFreeScript<'a> {
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 {
#[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"),
}
}
#[must_use]
pub fn with_home(mut self, home: ContainerPath) -> Self {
self.home = home;
self
}
#[must_use]
pub const fn home(&self) -> &ContainerPath {
&self.home
}
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))
}
pub async fn read(&self, script: &str) -> Result<String, ContainerProbeError> {
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>>,
) -> 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))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ShellBackend {
Local,
Container,
}
#[derive(Debug, Clone, Serialize)]
pub struct ShellRuntimeAvailability {
pub local: bool,
pub container: bool,
}
impl Default for ShellRuntimeAvailability {
fn default() -> Self {
Self {
local: true,
container: false,
}
}
}
#[derive(Clone)]
pub struct ShellSessionRegistry {
availability: ShellRuntimeAvailability,
ssh: SshEnvironments,
container_runtime: Option<ContainerShellRuntime>,
pub(crate) prepared_tools: Option<crate::tool_environment::PreparedToolEnvironments>,
}
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 {
#[must_use]
pub fn new(availability: ShellRuntimeAvailability) -> Self {
Self {
availability,
ssh: SshEnvironments::default(),
container_runtime: None,
prepared_tools: None,
}
}
#[must_use]
pub const fn with_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
self.availability = availability;
self
}
#[must_use]
pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
self.container_runtime = Some(runtime);
self
}
#[must_use]
pub fn availability(&self) -> ShellRuntimeAvailability {
self.availability.clone()
}
pub fn add_ssh_server(&self, server: SshServer) -> Result<(), SshServerError> {
self.ssh.add(server)
}
#[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)
}
#[must_use]
pub fn ssh_servers(&self) -> Vec<SshServer> {
self.ssh.list()
}
pub(crate) const fn ssh_environments(&self) -> &SshEnvironments {
&self.ssh
}
#[cfg(test)]
pub(crate) fn with_ssh_client(mut self, client: crate::ssh::SshClient) -> Self {
self.ssh = self.ssh.with_client(client);
self
}
pub(crate) const fn container_runtime(&self) -> Option<&ContainerShellRuntime> {
self.container_runtime.as_ref()
}
pub fn resolve_local_backend(&self) -> Result<ShellBackend, String> {
let availability = self.availability();
if availability.container {
return Ok(ShellBackend::Container);
}
if availability.local {
return Ok(ShellBackend::Local);
}
Err("no local backend available".to_string())
}
}
#[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::*;
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>>,
) -> 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::{ShellRuntimeAvailability, ShellSessionRegistry, SshServer};
#[test]
fn every_clone_of_a_registry_shares_its_live_server_set() {
let registry = ShellSessionRegistry::new(ShellRuntimeAvailability::default());
let subagent = registry.clone();
let prod = SshServer {
name: "prod".to_string(),
target: "root@example.com".to_string(),
};
registry.add_ssh_server(prod.clone()).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(), []);
}
#[test]
fn bridge_address_rejects_the_unspecified_and_multicast_addresses() {
use super::{BridgeAddress, BridgeAddressError};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
for address in [
IpAddr::V4(Ipv4Addr::UNSPECIFIED),
IpAddr::V6(Ipv6Addr::UNSPECIFIED),
] {
assert!(
matches!(
BridgeAddress::try_from(address),
Err(BridgeAddressError::Unspecified(_))
),
"{address} must be rejected as unspecified"
);
}
for address in [
IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)),
IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)),
] {
assert!(
matches!(
BridgeAddress::try_from(address),
Err(BridgeAddressError::Multicast(_))
),
"{address} must be rejected as multicast"
);
}
for address in [
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V4(Ipv4Addr::new(172, 17, 0, 1)),
] {
assert_eq!(
BridgeAddress::try_from(address)
.expect("a concrete host address should be accepted")
.ip(),
address
);
}
}
}