use crate::{
ContainerInfo, ContainerSpec, ExecHandle, ExecOpts, LogOpts, MANAGED_LABEL, Mount, NAME_PREFIX,
Runtime, is_managed, seccomp_supported,
};
use bytes::{Buf, Bytes, BytesMut};
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::io;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::sync::mpsc;
#[derive(Clone)]
pub struct Docker {
sock: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct ListItem {
id: String,
#[serde(default)]
names: Vec<String>,
#[serde(default)]
image: String,
#[serde(default, rename = "ImageID")]
image_id: String,
#[serde(default)]
created: i64,
#[serde(default)]
ports: Vec<Port>,
#[serde(default)]
labels: Option<BTreeMap<String, String>>,
#[serde(default)]
state: String,
#[serde(default)]
network_settings: Option<NetSettings>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Port {
#[serde(default)]
private_port: u16,
#[serde(default, rename = "Type")]
proto: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct NetSettings {
#[serde(default)]
networks: BTreeMap<String, Net>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Net {
#[serde(default, rename = "IPAddress")]
ip: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Inspect {
#[serde(default)]
id: String,
state: InspectState,
#[serde(default)]
restart_count: u64,
config: InspectConfig,
#[serde(default)]
name: String,
#[serde(default)]
image: String,
#[serde(default)]
network_settings: Option<NetSettings>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct InspectState {
#[serde(default)]
status: String,
#[serde(default)]
pid: i64,
#[serde(default)]
exit_code: i64,
#[serde(default, rename = "OOMKilled")]
oom_killed: bool,
#[serde(default)]
started_at: String,
#[serde(default)]
finished_at: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct InspectConfig {
#[serde(default)]
tty: bool,
#[serde(default)]
image: String,
#[serde(default)]
labels: Option<BTreeMap<String, String>>,
}
impl Docker {
pub fn new(sock: impl Into<String>) -> Self {
Self { sock: sock.into() }
}
async fn request(&self, path: &str) -> io::Result<Response<Incoming>> {
self.call(Method::GET, path, None).await
}
async fn call(
&self,
method: Method,
path: &str,
body: Option<Value>,
) -> io::Result<Response<Incoming>> {
let stream = UnixStream::connect(&self.sock).await?;
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
.await
.map_err(io::Error::other)?;
tokio::spawn(async move {
let _ = conn.await;
});
let mut req = Request::builder()
.method(method)
.uri(path)
.header("Host", "docker");
let payload = match body {
Some(v) => {
req = req.header("Content-Type", "application/json");
Bytes::from(serde_json::to_vec(&v).map_err(io::Error::other)?)
}
None => Bytes::new(),
};
let req = req.body(Full::new(payload)).map_err(io::Error::other)?;
let resp = sender.send_request(req).await.map_err(io::Error::other)?;
let status = resp.status();
if status.is_success() || status == StatusCode::NOT_MODIFIED {
return Ok(resp);
}
let text = resp
.into_body()
.collect()
.await
.map(|b| b.to_bytes())
.unwrap_or_default();
let msg = serde_json::from_slice::<Value>(&text)
.ok()
.and_then(|v| v["message"].as_str().map(str::to_string))
.unwrap_or_else(|| String::from_utf8_lossy(&text).into_owned());
let kind = match status {
StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
StatusCode::CONFLICT => io::ErrorKind::AlreadyExists,
_ => io::ErrorKind::Other,
};
Err(io::Error::new(
kind,
format!("docker {path} {status}: {}", msg.trim()),
))
}
async fn call_bytes(
&self,
method: Method,
path: &str,
body: Option<Value>,
) -> io::Result<Bytes> {
let resp = self.call(method, path, body).await?;
Ok(resp
.into_body()
.collect()
.await
.map_err(io::Error::other)?
.to_bytes())
}
async fn get_json(&self, path: &str) -> io::Result<Bytes> {
self.call_bytes(Method::GET, path, None).await
}
async fn hijack(&self, path: &str, body: Value) -> io::Result<(UnixStream, BytesMut)> {
let mut stream = UnixStream::connect(&self.sock).await?;
let payload = serde_json::to_vec(&body).map_err(io::Error::other)?;
let head = format!(
"POST {path} HTTP/1.1\r\nHost: docker\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n",
payload.len()
);
stream.write_all(head.as_bytes()).await?;
stream.write_all(&payload).await?;
stream.flush().await?;
let mut buf = BytesMut::new();
let split = loop {
if let Some(w) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
break w;
}
let mut tmp = [0u8; 1024];
let n = stream.read(&mut tmp).await?;
if n == 0 {
return Err(io::Error::other(
"docker: connection closed while reading response",
));
}
buf.extend_from_slice(&tmp[..n]);
};
let status = String::from_utf8_lossy(&buf[..split])
.lines()
.next()
.unwrap_or_default()
.to_string();
buf.advance(split + 4);
if !status.contains(" 200") && !status.contains(" 101") {
return Err(io::Error::other(format!("docker: {status}")));
}
Ok((stream, buf))
}
async fn ensure_managed(&self, id: &str) -> io::Result<()> {
let mut info = ContainerInfo {
id: id.to_string(),
..Default::default()
};
self.inspect(&mut info).await?;
if is_managed(&info) {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("container {id} is not managed by krab"),
))
}
}
async fn managed_object(&self, path: &str, name: &str) -> io::Result<()> {
let body = self.get_json(path).await?;
let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
if name.starts_with("krab") && v["Labels"][MANAGED_LABEL].as_str() == Some("true") {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{name} is not managed by krab"),
))
}
}
}
pub fn split_image(image: &str) -> (&str, &str) {
if let Some((repo, digest)) = image.split_once('@') {
return (repo, digest);
}
match image.rfind(':') {
Some(i) if !image[i..].contains('/') => (&image[..i], &image[i + 1..]),
_ => (image, "latest"),
}
}
fn enc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
const SUPPORTED_SECCOMP: &[&str] = &["RuntimeDefault"];
fn create_body(spec: &ContainerSpec) -> Value {
let mut exposed = serde_json::Map::new();
let mut bindings = serde_json::Map::new();
for p in &spec.ports {
let key = format!("{}/{}", p.container_port, p.protocol.to_lowercase());
exposed.insert(key.clone(), json!({}));
if let Some(hp) = p.host_port {
bindings.insert(
key,
json!([{"HostIp": p.host_ip.clone().unwrap_or_default(), "HostPort": hp.to_string()}]),
);
}
}
let mut mounts = Vec::new();
let mut tmpfs = serde_json::Map::new();
for m in &spec.mounts {
match m {
Mount::Bind {
src,
dst,
read_only,
} => mounts.push(json!({
"Type": "bind",
"Source": src,
"Target": dst,
"ReadOnly": read_only,
})),
Mount::Volume {
name,
dst,
read_only,
} => mounts.push(json!({
"Type": "volume",
"Source": name,
"Target": dst,
"ReadOnly": read_only,
"VolumeOptions": {"Labels": {MANAGED_LABEL: "true"}}
})),
Mount::Tmpfs { dst } => {
tmpfs.insert(dst.clone(), json!(""));
}
}
}
let mut host = json!({
"RestartPolicy": {"Name": spec.restart.docker_name()},
"Mounts": mounts,
"Tmpfs": tmpfs,
"PortBindings": bindings,
"DnsSearch": spec.dns_search,
"DnsOptions": spec.dns_options,
"CapDrop": ["NET_RAW"],
"PidsLimit": 4096,
"ReadonlyRootfs": spec.read_only_root,
});
if !spec.allow_privilege_escalation {
host["SecurityOpt"] = json!(["no-new-privileges"]);
}
if let Some(m) = spec.memory_bytes {
host["Memory"] = json!(m);
}
if let Some(c) = spec.nano_cpus {
host["NanoCpus"] = json!(c);
}
let mut body = json!({
"Image": spec.image,
"Env": spec.env.iter().map(|e| e.replace(crate::POD_IP_TOKEN, "")).collect::<Vec<_>>(),
"Labels": spec.labels,
"ExposedPorts": exposed,
"Tty": spec.tty,
"OpenStdin": spec.stdin,
"HostConfig": host,
});
if !spec.extra_gids.is_empty() {
body["HostConfig"]["GroupAdd"] = json!(
spec.extra_gids
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
);
}
if !spec.sysctls.is_empty() {
body["HostConfig"]["Sysctls"] = spec
.sysctls
.iter()
.map(|(k, v)| (k.clone(), json!(v)))
.collect::<serde_json::Map<_, _>>()
.into();
}
if !spec.host_aliases.is_empty() {
body["HostConfig"]["ExtraHosts"] = json!(
spec.host_aliases
.iter()
.map(|(ip, n)| format!("{n}:{ip}"))
.collect::<Vec<_>>()
);
}
if !spec.command.is_empty() {
body["Entrypoint"] = json!(spec.command);
}
if !spec.args.is_empty() || !spec.command.is_empty() {
body["Cmd"] = json!(spec.args);
}
if let Some(w) = &spec.working_dir {
body["WorkingDir"] = json!(w);
}
if let Some(h) = &spec.hostname {
body["Hostname"] = json!(h);
}
if let Some(u) = &spec.user {
body["User"] = json!(u);
}
if let Some(net) = &spec.network {
body["HostConfig"]["NetworkMode"] = json!(net);
body["NetworkingConfig"] =
json!({"EndpointsConfig": {net.as_str(): {"Aliases": spec.aliases}}});
}
body
}
fn demux(buf: &mut BytesMut, out: &mut Vec<u8>, limit: usize) {
while buf.len() >= 8 {
let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
if buf.len() < 8 + len {
break;
}
buf.advance(8);
let chunk = buf.split_to(len);
let room = limit.saturating_sub(out.len());
out.extend_from_slice(&chunk[..chunk.len().min(room)]);
}
}
impl Runtime for Docker {
fn name(&self) -> &str {
"docker"
}
async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
let body = self.get_json("/containers/json?all=1").await?;
let items: Vec<ListItem> = serde_json::from_slice(&body).map_err(io::Error::other)?;
Ok(items
.into_iter()
.map(|i| {
let ip = i
.network_settings
.and_then(|n| {
n.networks
.into_values()
.map(|n| n.ip)
.find(|ip| !ip.is_empty())
})
.unwrap_or_default();
ContainerInfo {
name: i
.names
.first()
.map(|n| n.trim_start_matches('/').to_string())
.unwrap_or_else(|| i.id[..12.min(i.id.len())].to_string()),
id: i.id,
image: i.image,
image_id: i.image_id,
state: i.state,
created: i.created,
labels: i.labels.unwrap_or_default(),
ports: i
.ports
.into_iter()
.filter(|p| p.private_port > 0)
.map(|p| (p.private_port, p.proto))
.collect(),
ip,
..Default::default()
}
})
.collect())
}
async fn inspect(&self, info: &mut ContainerInfo) -> io::Result<()> {
let body = self
.get_json(&format!("/containers/{}/json", enc(&info.id)))
.await?;
let i: Inspect = serde_json::from_slice(&body).map_err(io::Error::other)?;
info.started_at = i.state.started_at;
info.finished_at = i.state.finished_at;
info.exit_code = i.state.exit_code;
info.oom_killed = i.state.oom_killed;
info.pid = i.state.pid;
info.restart_count = i.restart_count;
info.tty = i.config.tty;
if !i.id.is_empty() {
info.id = i.id;
}
if !i.state.status.is_empty() {
info.state = i.state.status;
}
if !i.name.is_empty() {
info.name = i.name.trim_start_matches('/').to_string();
}
if !i.image.is_empty() {
info.image_id = i.image;
}
if info.image.is_empty() {
info.image = i.config.image;
}
if info.labels.is_empty() {
info.labels = i.config.labels.unwrap_or_default();
}
if let Some(ip) = i.network_settings.and_then(|n| {
n.networks
.into_values()
.map(|n| n.ip)
.find(|ip| !ip.is_empty())
}) {
info.ip = ip;
}
Ok(())
}
async fn logs(
&self,
info: &ContainerInfo,
opts: &LogOpts,
) -> io::Result<mpsc::Receiver<Bytes>> {
let mut path = format!("/containers/{}/logs?stdout=1&stderr=1", enc(&info.id));
if let Some(t) = opts.tail {
path.push_str(&format!("&tail={t}"));
}
if opts.follow {
path.push_str("&follow=1");
}
if opts.timestamps {
path.push_str("×tamps=1");
}
if let Some(s) = opts.since_seconds {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
path.push_str(&format!("&since={}", now.saturating_sub(s)));
}
let resp = self.request(&path).await?;
let tty = info.tty;
let (tx, rx) = mpsc::channel(8);
tokio::spawn(async move {
let mut body = resp.into_body();
let mut buf = BytesMut::new();
while let Some(Ok(frame)) = body.frame().await {
let Ok(data) = frame.into_data() else {
continue;
};
if tty {
if tx.send(data).await.is_err() {
return;
}
continue;
}
buf.extend_from_slice(&data);
while buf.len() >= 8 {
let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
if buf.len() < 8 + len {
break;
}
buf.advance(8);
let chunk = buf.split_to(len).freeze();
if tx.send(chunk).await.is_err() {
return;
}
}
}
});
Ok(rx)
}
async fn pull_image(&self, image: &str) -> io::Result<()> {
let (repo, tag) = split_image(image);
let path = format!("/images/create?fromImage={}&tag={}", enc(repo), enc(tag));
let resp = self.call(Method::POST, &path, None).await?;
let mut body = resp.into_body();
let mut buf = BytesMut::new();
let mut err = None;
while let Some(frame) = body.frame().await {
let Ok(data) = frame.map_err(io::Error::other)?.into_data() else {
continue;
};
buf.extend_from_slice(&data);
while let Some(i) = buf.iter().position(|b| *b == b'\n') {
let line = buf.split_to(i + 1);
if let Ok(v) = serde_json::from_slice::<Value>(&line)
&& let Some(e) = v["error"].as_str()
{
err = Some(e.to_string());
}
}
}
match err {
Some(e) => Err(io::Error::other(format!("pull {image}: {e}"))),
None => Ok(()),
}
}
async fn create_container(&self, spec: &ContainerSpec) -> io::Result<String> {
if !spec.name.starts_with(NAME_PREFIX)
|| spec.labels.get(MANAGED_LABEL).map(String::as_str) != Some("true")
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"container spec is not krab-managed",
));
}
seccomp_supported("docker", spec.seccomp.as_deref(), SUPPORTED_SECCOMP)?;
let path = format!("/containers/create?name={}", enc(&spec.name));
let body = self
.call_bytes(Method::POST, &path, Some(create_body(spec)))
.await?;
let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
v["Id"]
.as_str()
.map(str::to_string)
.ok_or_else(|| io::Error::other("docker create: no Id"))
}
async fn start(&self, id: &str) -> io::Result<()> {
self.ensure_managed(id).await?;
self.call(
Method::POST,
&format!("/containers/{}/start", enc(id)),
None,
)
.await
.map(|_| ())
}
async fn stop(&self, id: &str, timeout_secs: u64) -> io::Result<()> {
self.ensure_managed(id).await?;
self.call(
Method::POST,
&format!("/containers/{}/stop?t={timeout_secs}", enc(id)),
None,
)
.await
.map(|_| ())
}
async fn remove(&self, id: &str, force: bool) -> io::Result<()> {
self.ensure_managed(id).await?;
let f = if force { 1 } else { 0 };
self.call(
Method::DELETE,
&format!("/containers/{}?force={f}&v=1", enc(id)),
None,
)
.await
.map(|_| ())
}
async fn ensure_network(&self, name: &str) -> io::Result<()> {
match self.get_json(&format!("/networks/{}", enc(name))).await {
Ok(_) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let body = json!({"Name": name, "Driver": "bridge", "CheckDuplicate": true, "Labels": {MANAGED_LABEL: "true"}});
match self
.call(Method::POST, "/networks/create", Some(body))
.await
{
Ok(_) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) => Err(e),
}
}
Err(e) => Err(e),
}
}
async fn remove_network(&self, name: &str) -> io::Result<()> {
let path = format!("/networks/{}", enc(name));
self.managed_object(&path, name).await?;
self.call(Method::DELETE, &path, None).await.map(|_| ())
}
async fn connect_network(
&self,
container: &str,
network: &str,
aliases: &[String],
) -> io::Result<()> {
self.ensure_managed(container).await?;
let body = json!({"Container": container, "EndpointConfig": {"Aliases": aliases}});
self.call(
Method::POST,
&format!("/networks/{}/connect", enc(network)),
Some(body),
)
.await
.map(|_| ())
}
async fn disconnect_network(&self, container: &str, network: &str) -> io::Result<()> {
self.ensure_managed(container).await?;
let body = json!({"Container": container, "Force": true});
self.call(
Method::POST,
&format!("/networks/{}/disconnect", enc(network)),
Some(body),
)
.await
.map(|_| ())
}
async fn remove_volume(&self, name: &str) -> io::Result<()> {
let path = format!("/volumes/{}", enc(name));
self.managed_object(&path, name).await?;
self.call(Method::DELETE, &path, None).await.map(|_| ())
}
async fn exec_run(&self, id: &str, cmd: &[String]) -> io::Result<(i64, Vec<u8>)> {
self.ensure_managed(id).await?;
let body = json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": false});
let created = self
.call_bytes(
Method::POST,
&format!("/containers/{}/exec", enc(id)),
Some(body),
)
.await?;
let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
let eid = v["Id"]
.as_str()
.ok_or_else(|| io::Error::other("docker exec: no Id"))?
.to_string();
let resp = self
.call(
Method::POST,
&format!("/exec/{}/start", enc(&eid)),
Some(json!({"Detach": false, "Tty": false})),
)
.await?;
let mut body = resp.into_body();
let mut buf = BytesMut::new();
let mut out = Vec::new();
while let Some(Ok(frame)) = body.frame().await {
if let Ok(data) = frame.into_data() {
buf.extend_from_slice(&data);
demux(&mut buf, &mut out, 64 * 1024);
}
}
let info = self.get_json(&format!("/exec/{}/json", enc(&eid))).await?;
let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
Ok((v["ExitCode"].as_i64().unwrap_or(-1), out))
}
async fn exec_stream(&self, id: &str, opts: &ExecOpts) -> io::Result<ExecHandle> {
self.ensure_managed(id).await?;
let body = json!({
"Cmd": opts.cmd,
"AttachStdin": opts.stdin,
"AttachStdout": true,
"AttachStderr": !opts.tty,
"Tty": opts.tty,
});
let created = self
.call_bytes(
Method::POST,
&format!("/containers/{}/exec", enc(id)),
Some(body),
)
.await?;
let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
let eid = v["Id"]
.as_str()
.ok_or_else(|| io::Error::other("docker exec: no Id"))?
.to_string();
let (stream, head_buf) = self
.hijack(
&format!("/exec/{}/start", enc(&eid)),
json!({"Detach": false, "Tty": opts.tty}),
)
.await?;
let (r, w) = tokio::io::split(stream);
type Sink = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
let (stdin, hold): (Option<Sink>, Option<Sink>) = if opts.stdin {
(Some(Box::new(w)), None)
} else {
(None, Some(Box::new(w)))
};
let (otx, orx) = mpsc::channel::<Bytes>(16);
let (etx, erx) = mpsc::channel::<Bytes>(16);
let tty = opts.tty;
tokio::spawn(async move {
let mut r = r;
let mut buf = head_buf;
let mut eof = false;
loop {
loop {
if tty {
if buf.is_empty() {
break;
}
if otx.send(buf.split().freeze()).await.is_err() {
return;
}
} else if buf.len() >= 8 {
let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
if buf.len() < 8 + len {
break;
}
let stream_ty = buf[0];
buf.advance(8);
let chunk = buf.split_to(len).freeze();
let tx = if stream_ty == 2 { &etx } else { &otx };
if !chunk.is_empty() && tx.send(chunk).await.is_err() {
return;
}
} else {
break;
}
}
if eof {
break;
}
let mut tmp = [0u8; 8192];
match r.read(&mut tmp).await {
Ok(0) => eof = true,
Ok(n) => buf.extend_from_slice(&tmp[..n]),
Err(_) => break,
}
}
});
Ok(ExecHandle {
exec_id: eid,
stdout: orx,
stderr: erx,
stdin,
hold,
})
}
async fn exec_resize(&self, exec_id: &str, width: u32, height: u32) -> io::Result<()> {
self.call(
Method::POST,
&format!("/exec/{}/resize?h={height}&w={width}", enc(exec_id)),
None,
)
.await
.map(|_| ())
}
async fn exec_exit_code(&self, exec_id: &str) -> io::Result<i64> {
let info = self
.get_json(&format!("/exec/{}/json", enc(exec_id)))
.await?;
let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
Ok(v["ExitCode"].as_i64().unwrap_or(-1))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn image_split() {
assert_eq!(split_image("nginx:alpine"), ("nginx", "alpine"));
assert_eq!(split_image("nginx"), ("nginx", "latest"));
assert_eq!(split_image("reg:5000/a/b"), ("reg:5000/a/b", "latest"));
assert_eq!(split_image("reg:5000/a/b:1.2"), ("reg:5000/a/b", "1.2"));
assert_eq!(split_image("a@sha256:ff"), ("a", "sha256:ff"));
}
#[test]
fn ids_are_escaped_in_paths() {
assert_eq!(
enc("abc/archive?path=/etc&"),
"abc%2Farchive%3Fpath%3D%2Fetc%26"
);
assert_eq!(enc("krab_default_p_c"), "krab_default_p_c");
}
#[test]
fn create_body_maps_spec() {
let spec = ContainerSpec {
name: "krab_default_p_c".into(),
image: "nginx:alpine".into(),
command: vec!["sh".into()],
restart: crate::RestartPolicy::OnFailure,
memory_bytes: Some(1 << 20),
nano_cpus: Some(500_000_000),
ports: vec![crate::PortSpec {
container_port: 80,
protocol: "TCP".into(),
host_port: Some(8080),
host_ip: None,
}],
mounts: vec![
Mount::Bind {
src: "/a".into(),
dst: "/b".into(),
read_only: true,
},
Mount::Tmpfs { dst: "/t".into() },
],
network: Some("krab".into()),
aliases: vec!["web".into()],
..Default::default()
};
let b = create_body(&spec);
assert_eq!(b["HostConfig"]["RestartPolicy"]["Name"], "on-failure");
assert_eq!(b["HostConfig"]["Memory"], 1 << 20);
assert_eq!(b["HostConfig"]["NanoCpus"], 500_000_000);
assert_eq!(
b["HostConfig"]["Mounts"][0],
json!({"Type": "bind", "Source": "/a", "Target": "/b", "ReadOnly": true})
);
assert_eq!(b["HostConfig"]["SecurityOpt"][0], "no-new-privileges");
assert_eq!(b["HostConfig"]["CapDrop"][0], "NET_RAW");
assert_eq!(
b["HostConfig"]["PortBindings"]["80/tcp"][0]["HostPort"],
"8080"
);
assert_eq!(b["Cmd"], json!([]));
assert_eq!(
b["NetworkingConfig"]["EndpointsConfig"]["krab"]["Aliases"][0],
"web"
);
}
#[test]
fn seccomp_modes_checked() {
for t in [None, Some("RuntimeDefault")] {
seccomp_supported("docker", t, SUPPORTED_SECCOMP).unwrap();
}
for t in [Some("Localhost"), Some("Unconfined"), Some("Weird")] {
assert_eq!(
seccomp_supported("docker", t, SUPPORTED_SECCOMP)
.unwrap_err()
.kind(),
io::ErrorKind::InvalidInput
);
}
}
#[test]
fn runtime_default_keeps_docker_default_profile() {
let spec = ContainerSpec {
name: "krab_default_p_c".into(),
image: "nginx:alpine".into(),
seccomp: Some("RuntimeDefault".into()),
..Default::default()
};
assert!(
!create_body(&spec)
.to_string()
.to_lowercase()
.contains("seccomp")
);
}
}