Skip to main content

krab_runtime/
docker.rs

1use crate::{
2    ContainerInfo, ContainerSpec, ExecHandle, ExecOpts, LogOpts, MANAGED_LABEL, Mount, NAME_PREFIX,
3    Runtime, is_managed, seccomp_supported,
4};
5use bytes::{Buf, Bytes, BytesMut};
6use http_body_util::{BodyExt, Full};
7use hyper::body::Incoming;
8use hyper::{Method, Request, Response, StatusCode};
9use hyper_util::rt::TokioIo;
10use serde::Deserialize;
11use serde_json::{Value, json};
12use std::collections::BTreeMap;
13use std::io;
14use tokio::io::{AsyncReadExt, AsyncWriteExt};
15use tokio::net::UnixStream;
16use tokio::sync::mpsc;
17
18#[derive(Clone)]
19pub struct Docker {
20    sock: String,
21}
22
23#[derive(Deserialize)]
24#[serde(rename_all = "PascalCase")]
25struct ListItem {
26    id: String,
27    #[serde(default)]
28    names: Vec<String>,
29    #[serde(default)]
30    image: String,
31    #[serde(default, rename = "ImageID")]
32    image_id: String,
33    #[serde(default)]
34    created: i64,
35    #[serde(default)]
36    ports: Vec<Port>,
37    #[serde(default)]
38    labels: Option<BTreeMap<String, String>>,
39    #[serde(default)]
40    state: String,
41    #[serde(default)]
42    network_settings: Option<NetSettings>,
43}
44
45#[derive(Deserialize)]
46#[serde(rename_all = "PascalCase")]
47struct Port {
48    #[serde(default)]
49    private_port: u16,
50    #[serde(default, rename = "Type")]
51    proto: String,
52}
53
54#[derive(Deserialize)]
55#[serde(rename_all = "PascalCase")]
56struct NetSettings {
57    #[serde(default)]
58    networks: BTreeMap<String, Net>,
59}
60
61#[derive(Deserialize)]
62#[serde(rename_all = "PascalCase")]
63struct Net {
64    #[serde(default, rename = "IPAddress")]
65    ip: String,
66}
67
68#[derive(Deserialize)]
69#[serde(rename_all = "PascalCase")]
70struct Inspect {
71    #[serde(default)]
72    id: String,
73    state: InspectState,
74    #[serde(default)]
75    restart_count: u64,
76    config: InspectConfig,
77    #[serde(default)]
78    name: String,
79    #[serde(default)]
80    image: String,
81    #[serde(default)]
82    network_settings: Option<NetSettings>,
83}
84
85#[derive(Deserialize)]
86#[serde(rename_all = "PascalCase")]
87struct InspectState {
88    #[serde(default)]
89    status: String,
90    #[serde(default)]
91    pid: i64,
92    #[serde(default)]
93    exit_code: i64,
94    #[serde(default, rename = "OOMKilled")]
95    oom_killed: bool,
96    #[serde(default)]
97    started_at: String,
98    #[serde(default)]
99    finished_at: String,
100}
101
102#[derive(Deserialize)]
103#[serde(rename_all = "PascalCase")]
104struct InspectConfig {
105    #[serde(default)]
106    tty: bool,
107    #[serde(default)]
108    image: String,
109    #[serde(default)]
110    labels: Option<BTreeMap<String, String>>,
111}
112
113impl Docker {
114    pub fn new(sock: impl Into<String>) -> Self {
115        Self { sock: sock.into() }
116    }
117
118    async fn request(&self, path: &str) -> io::Result<Response<Incoming>> {
119        self.call(Method::GET, path, None).await
120    }
121
122    async fn call(
123        &self,
124        method: Method,
125        path: &str,
126        body: Option<Value>,
127    ) -> io::Result<Response<Incoming>> {
128        let stream = UnixStream::connect(&self.sock).await?;
129        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
130            .await
131            .map_err(io::Error::other)?;
132        tokio::spawn(async move {
133            let _ = conn.await;
134        });
135        let mut req = Request::builder()
136            .method(method)
137            .uri(path)
138            .header("Host", "docker");
139        let payload = match body {
140            Some(v) => {
141                req = req.header("Content-Type", "application/json");
142                Bytes::from(serde_json::to_vec(&v).map_err(io::Error::other)?)
143            }
144            None => Bytes::new(),
145        };
146        let req = req.body(Full::new(payload)).map_err(io::Error::other)?;
147        let resp = sender.send_request(req).await.map_err(io::Error::other)?;
148        let status = resp.status();
149        if status.is_success() || status == StatusCode::NOT_MODIFIED {
150            return Ok(resp);
151        }
152        let text = resp
153            .into_body()
154            .collect()
155            .await
156            .map(|b| b.to_bytes())
157            .unwrap_or_default();
158        let msg = serde_json::from_slice::<Value>(&text)
159            .ok()
160            .and_then(|v| v["message"].as_str().map(str::to_string))
161            .unwrap_or_else(|| String::from_utf8_lossy(&text).into_owned());
162        let kind = match status {
163            StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
164            StatusCode::CONFLICT => io::ErrorKind::AlreadyExists,
165            _ => io::ErrorKind::Other,
166        };
167        Err(io::Error::new(
168            kind,
169            format!("docker {path} {status}: {}", msg.trim()),
170        ))
171    }
172
173    async fn call_bytes(
174        &self,
175        method: Method,
176        path: &str,
177        body: Option<Value>,
178    ) -> io::Result<Bytes> {
179        let resp = self.call(method, path, body).await?;
180        Ok(resp
181            .into_body()
182            .collect()
183            .await
184            .map_err(io::Error::other)?
185            .to_bytes())
186    }
187
188    async fn get_json(&self, path: &str) -> io::Result<Bytes> {
189        self.call_bytes(Method::GET, path, None).await
190    }
191
192    async fn hijack(&self, path: &str, body: Value) -> io::Result<(UnixStream, BytesMut)> {
193        let mut stream = UnixStream::connect(&self.sock).await?;
194        let payload = serde_json::to_vec(&body).map_err(io::Error::other)?;
195        let head = format!(
196            "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",
197            payload.len()
198        );
199        stream.write_all(head.as_bytes()).await?;
200        stream.write_all(&payload).await?;
201        stream.flush().await?;
202        let mut buf = BytesMut::new();
203        let split = loop {
204            if let Some(w) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
205                break w;
206            }
207            let mut tmp = [0u8; 1024];
208            let n = stream.read(&mut tmp).await?;
209            if n == 0 {
210                return Err(io::Error::other(
211                    "docker: connection closed while reading response",
212                ));
213            }
214            buf.extend_from_slice(&tmp[..n]);
215        };
216        let status = String::from_utf8_lossy(&buf[..split])
217            .lines()
218            .next()
219            .unwrap_or_default()
220            .to_string();
221        buf.advance(split + 4);
222        if !status.contains(" 200") && !status.contains(" 101") {
223            return Err(io::Error::other(format!("docker: {status}")));
224        }
225        Ok((stream, buf))
226    }
227
228    async fn ensure_managed(&self, id: &str) -> io::Result<()> {
229        let mut info = ContainerInfo {
230            id: id.to_string(),
231            ..Default::default()
232        };
233        self.inspect(&mut info).await?;
234        if is_managed(&info) {
235            Ok(())
236        } else {
237            Err(io::Error::new(
238                io::ErrorKind::PermissionDenied,
239                format!("container {id} is not managed by krab"),
240            ))
241        }
242    }
243
244    async fn managed_object(&self, path: &str, name: &str) -> io::Result<()> {
245        let body = self.get_json(path).await?;
246        let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
247        if name.starts_with("krab") && v["Labels"][MANAGED_LABEL].as_str() == Some("true") {
248            Ok(())
249        } else {
250            Err(io::Error::new(
251                io::ErrorKind::PermissionDenied,
252                format!("{name} is not managed by krab"),
253            ))
254        }
255    }
256}
257
258pub fn split_image(image: &str) -> (&str, &str) {
259    if let Some((repo, digest)) = image.split_once('@') {
260        return (repo, digest);
261    }
262    match image.rfind(':') {
263        Some(i) if !image[i..].contains('/') => (&image[..i], &image[i + 1..]),
264        _ => (image, "latest"),
265    }
266}
267
268fn enc(s: &str) -> String {
269    let mut out = String::with_capacity(s.len());
270    for b in s.bytes() {
271        if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
272            out.push(b as char);
273        } else {
274            out.push_str(&format!("%{b:02X}"));
275        }
276    }
277    out
278}
279
280const SUPPORTED_SECCOMP: &[&str] = &["RuntimeDefault"];
281
282fn create_body(spec: &ContainerSpec) -> Value {
283    let mut exposed = serde_json::Map::new();
284    let mut bindings = serde_json::Map::new();
285    for p in &spec.ports {
286        let key = format!("{}/{}", p.container_port, p.protocol.to_lowercase());
287        exposed.insert(key.clone(), json!({}));
288        if let Some(hp) = p.host_port {
289            bindings.insert(
290                key,
291                json!([{"HostIp": p.host_ip.clone().unwrap_or_default(), "HostPort": hp.to_string()}]),
292            );
293        }
294    }
295    let mut mounts = Vec::new();
296    let mut tmpfs = serde_json::Map::new();
297    for m in &spec.mounts {
298        match m {
299            Mount::Bind {
300                src,
301                dst,
302                read_only,
303            } => mounts.push(json!({
304                "Type": "bind",
305                "Source": src,
306                "Target": dst,
307                "ReadOnly": read_only,
308            })),
309            Mount::Volume {
310                name,
311                dst,
312                read_only,
313            } => mounts.push(json!({
314                "Type": "volume",
315                "Source": name,
316                "Target": dst,
317                "ReadOnly": read_only,
318                "VolumeOptions": {"Labels": {MANAGED_LABEL: "true"}}
319            })),
320            Mount::Tmpfs { dst } => {
321                tmpfs.insert(dst.clone(), json!(""));
322            }
323        }
324    }
325    let mut host = json!({
326        "RestartPolicy": {"Name": spec.restart.docker_name()},
327        "Mounts": mounts,
328        "Tmpfs": tmpfs,
329        "PortBindings": bindings,
330        "DnsSearch": spec.dns_search,
331        "DnsOptions": spec.dns_options,
332        "CapDrop": ["NET_RAW"],
333        "PidsLimit": 4096,
334        "ReadonlyRootfs": spec.read_only_root,
335    });
336    if !spec.allow_privilege_escalation {
337        host["SecurityOpt"] = json!(["no-new-privileges"]);
338    }
339    if let Some(m) = spec.memory_bytes {
340        host["Memory"] = json!(m);
341    }
342    if let Some(c) = spec.nano_cpus {
343        host["NanoCpus"] = json!(c);
344    }
345    let mut body = json!({
346        "Image": spec.image,
347        "Env": spec.env.iter().map(|e| e.replace(crate::POD_IP_TOKEN, "")).collect::<Vec<_>>(),
348        "Labels": spec.labels,
349        "ExposedPorts": exposed,
350        "Tty": spec.tty,
351        "OpenStdin": spec.stdin,
352        "HostConfig": host,
353    });
354    if !spec.extra_gids.is_empty() {
355        body["HostConfig"]["GroupAdd"] = json!(
356            spec.extra_gids
357                .iter()
358                .map(u32::to_string)
359                .collect::<Vec<_>>()
360        );
361    }
362    if !spec.sysctls.is_empty() {
363        body["HostConfig"]["Sysctls"] = spec
364            .sysctls
365            .iter()
366            .map(|(k, v)| (k.clone(), json!(v)))
367            .collect::<serde_json::Map<_, _>>()
368            .into();
369    }
370    if !spec.host_aliases.is_empty() {
371        body["HostConfig"]["ExtraHosts"] = json!(
372            spec.host_aliases
373                .iter()
374                .map(|(ip, n)| format!("{n}:{ip}"))
375                .collect::<Vec<_>>()
376        );
377    }
378    if !spec.command.is_empty() {
379        body["Entrypoint"] = json!(spec.command);
380    }
381    if !spec.args.is_empty() || !spec.command.is_empty() {
382        body["Cmd"] = json!(spec.args);
383    }
384    if let Some(w) = &spec.working_dir {
385        body["WorkingDir"] = json!(w);
386    }
387    if let Some(h) = &spec.hostname {
388        body["Hostname"] = json!(h);
389    }
390    if let Some(u) = &spec.user {
391        body["User"] = json!(u);
392    }
393    if let Some(net) = &spec.network {
394        body["HostConfig"]["NetworkMode"] = json!(net);
395        body["NetworkingConfig"] =
396            json!({"EndpointsConfig": {net.as_str(): {"Aliases": spec.aliases}}});
397    }
398    body
399}
400
401fn demux(buf: &mut BytesMut, out: &mut Vec<u8>, limit: usize) {
402    while buf.len() >= 8 {
403        let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
404        if buf.len() < 8 + len {
405            break;
406        }
407        buf.advance(8);
408        let chunk = buf.split_to(len);
409        let room = limit.saturating_sub(out.len());
410        out.extend_from_slice(&chunk[..chunk.len().min(room)]);
411    }
412}
413
414impl Runtime for Docker {
415    fn name(&self) -> &str {
416        "docker"
417    }
418
419    async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
420        let body = self.get_json("/containers/json?all=1").await?;
421        let items: Vec<ListItem> = serde_json::from_slice(&body).map_err(io::Error::other)?;
422        Ok(items
423            .into_iter()
424            .map(|i| {
425                let ip = i
426                    .network_settings
427                    .and_then(|n| {
428                        n.networks
429                            .into_values()
430                            .map(|n| n.ip)
431                            .find(|ip| !ip.is_empty())
432                    })
433                    .unwrap_or_default();
434                ContainerInfo {
435                    name: i
436                        .names
437                        .first()
438                        .map(|n| n.trim_start_matches('/').to_string())
439                        .unwrap_or_else(|| i.id[..12.min(i.id.len())].to_string()),
440                    id: i.id,
441                    image: i.image,
442                    image_id: i.image_id,
443                    state: i.state,
444                    created: i.created,
445                    labels: i.labels.unwrap_or_default(),
446                    ports: i
447                        .ports
448                        .into_iter()
449                        .filter(|p| p.private_port > 0)
450                        .map(|p| (p.private_port, p.proto))
451                        .collect(),
452                    ip,
453                    ..Default::default()
454                }
455            })
456            .collect())
457    }
458
459    async fn inspect(&self, info: &mut ContainerInfo) -> io::Result<()> {
460        let body = self
461            .get_json(&format!("/containers/{}/json", enc(&info.id)))
462            .await?;
463        let i: Inspect = serde_json::from_slice(&body).map_err(io::Error::other)?;
464        info.started_at = i.state.started_at;
465        info.finished_at = i.state.finished_at;
466        info.exit_code = i.state.exit_code;
467        info.oom_killed = i.state.oom_killed;
468        info.pid = i.state.pid;
469        info.restart_count = i.restart_count;
470        info.tty = i.config.tty;
471        if !i.id.is_empty() {
472            info.id = i.id;
473        }
474        if !i.state.status.is_empty() {
475            info.state = i.state.status;
476        }
477        if !i.name.is_empty() {
478            info.name = i.name.trim_start_matches('/').to_string();
479        }
480        if !i.image.is_empty() {
481            info.image_id = i.image;
482        }
483        if info.image.is_empty() {
484            info.image = i.config.image;
485        }
486        if info.labels.is_empty() {
487            info.labels = i.config.labels.unwrap_or_default();
488        }
489        if let Some(ip) = i.network_settings.and_then(|n| {
490            n.networks
491                .into_values()
492                .map(|n| n.ip)
493                .find(|ip| !ip.is_empty())
494        }) {
495            info.ip = ip;
496        }
497        Ok(())
498    }
499
500    async fn logs(
501        &self,
502        info: &ContainerInfo,
503        opts: &LogOpts,
504    ) -> io::Result<mpsc::Receiver<Bytes>> {
505        let mut path = format!("/containers/{}/logs?stdout=1&stderr=1", enc(&info.id));
506        if let Some(t) = opts.tail {
507            path.push_str(&format!("&tail={t}"));
508        }
509        if opts.follow {
510            path.push_str("&follow=1");
511        }
512        if opts.timestamps {
513            path.push_str("&timestamps=1");
514        }
515        if let Some(s) = opts.since_seconds {
516            let now = std::time::SystemTime::now()
517                .duration_since(std::time::UNIX_EPOCH)
518                .map(|d| d.as_secs())
519                .unwrap_or(0);
520            path.push_str(&format!("&since={}", now.saturating_sub(s)));
521        }
522        let resp = self.request(&path).await?;
523        let tty = info.tty;
524        let (tx, rx) = mpsc::channel(8);
525        tokio::spawn(async move {
526            let mut body = resp.into_body();
527            let mut buf = BytesMut::new();
528            while let Some(Ok(frame)) = body.frame().await {
529                let Ok(data) = frame.into_data() else {
530                    continue;
531                };
532                if tty {
533                    if tx.send(data).await.is_err() {
534                        return;
535                    }
536                    continue;
537                }
538                buf.extend_from_slice(&data);
539                while buf.len() >= 8 {
540                    let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
541                    if buf.len() < 8 + len {
542                        break;
543                    }
544                    buf.advance(8);
545                    let chunk = buf.split_to(len).freeze();
546                    if tx.send(chunk).await.is_err() {
547                        return;
548                    }
549                }
550            }
551        });
552        Ok(rx)
553    }
554
555    async fn pull_image(&self, image: &str) -> io::Result<()> {
556        let (repo, tag) = split_image(image);
557        let path = format!("/images/create?fromImage={}&tag={}", enc(repo), enc(tag));
558        let resp = self.call(Method::POST, &path, None).await?;
559        let mut body = resp.into_body();
560        let mut buf = BytesMut::new();
561        let mut err = None;
562        while let Some(frame) = body.frame().await {
563            let Ok(data) = frame.map_err(io::Error::other)?.into_data() else {
564                continue;
565            };
566            buf.extend_from_slice(&data);
567            while let Some(i) = buf.iter().position(|b| *b == b'\n') {
568                let line = buf.split_to(i + 1);
569                if let Ok(v) = serde_json::from_slice::<Value>(&line)
570                    && let Some(e) = v["error"].as_str()
571                {
572                    err = Some(e.to_string());
573                }
574            }
575        }
576        match err {
577            Some(e) => Err(io::Error::other(format!("pull {image}: {e}"))),
578            None => Ok(()),
579        }
580    }
581
582    async fn create_container(&self, spec: &ContainerSpec) -> io::Result<String> {
583        if !spec.name.starts_with(NAME_PREFIX)
584            || spec.labels.get(MANAGED_LABEL).map(String::as_str) != Some("true")
585        {
586            return Err(io::Error::new(
587                io::ErrorKind::PermissionDenied,
588                "container spec is not krab-managed",
589            ));
590        }
591        seccomp_supported("docker", spec.seccomp.as_deref(), SUPPORTED_SECCOMP)?;
592        let path = format!("/containers/create?name={}", enc(&spec.name));
593        let body = self
594            .call_bytes(Method::POST, &path, Some(create_body(spec)))
595            .await?;
596        let v: Value = serde_json::from_slice(&body).map_err(io::Error::other)?;
597        v["Id"]
598            .as_str()
599            .map(str::to_string)
600            .ok_or_else(|| io::Error::other("docker create: no Id"))
601    }
602
603    async fn start(&self, id: &str) -> io::Result<()> {
604        self.ensure_managed(id).await?;
605        self.call(
606            Method::POST,
607            &format!("/containers/{}/start", enc(id)),
608            None,
609        )
610        .await
611        .map(|_| ())
612    }
613
614    async fn stop(&self, id: &str, timeout_secs: u64) -> io::Result<()> {
615        self.ensure_managed(id).await?;
616        self.call(
617            Method::POST,
618            &format!("/containers/{}/stop?t={timeout_secs}", enc(id)),
619            None,
620        )
621        .await
622        .map(|_| ())
623    }
624
625    async fn remove(&self, id: &str, force: bool) -> io::Result<()> {
626        self.ensure_managed(id).await?;
627        let f = if force { 1 } else { 0 };
628        self.call(
629            Method::DELETE,
630            &format!("/containers/{}?force={f}&v=1", enc(id)),
631            None,
632        )
633        .await
634        .map(|_| ())
635    }
636
637    async fn ensure_network(&self, name: &str) -> io::Result<()> {
638        match self.get_json(&format!("/networks/{}", enc(name))).await {
639            Ok(_) => Ok(()),
640            Err(e) if e.kind() == io::ErrorKind::NotFound => {
641                let body = json!({"Name": name, "Driver": "bridge", "CheckDuplicate": true, "Labels": {MANAGED_LABEL: "true"}});
642                match self
643                    .call(Method::POST, "/networks/create", Some(body))
644                    .await
645                {
646                    Ok(_) => Ok(()),
647                    Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
648                    Err(e) => Err(e),
649                }
650            }
651            Err(e) => Err(e),
652        }
653    }
654
655    async fn remove_network(&self, name: &str) -> io::Result<()> {
656        let path = format!("/networks/{}", enc(name));
657        self.managed_object(&path, name).await?;
658        self.call(Method::DELETE, &path, None).await.map(|_| ())
659    }
660
661    async fn connect_network(
662        &self,
663        container: &str,
664        network: &str,
665        aliases: &[String],
666    ) -> io::Result<()> {
667        self.ensure_managed(container).await?;
668        let body = json!({"Container": container, "EndpointConfig": {"Aliases": aliases}});
669        self.call(
670            Method::POST,
671            &format!("/networks/{}/connect", enc(network)),
672            Some(body),
673        )
674        .await
675        .map(|_| ())
676    }
677
678    async fn disconnect_network(&self, container: &str, network: &str) -> io::Result<()> {
679        self.ensure_managed(container).await?;
680        let body = json!({"Container": container, "Force": true});
681        self.call(
682            Method::POST,
683            &format!("/networks/{}/disconnect", enc(network)),
684            Some(body),
685        )
686        .await
687        .map(|_| ())
688    }
689
690    async fn remove_volume(&self, name: &str) -> io::Result<()> {
691        let path = format!("/volumes/{}", enc(name));
692        self.managed_object(&path, name).await?;
693        self.call(Method::DELETE, &path, None).await.map(|_| ())
694    }
695
696    async fn exec_run(&self, id: &str, cmd: &[String]) -> io::Result<(i64, Vec<u8>)> {
697        self.ensure_managed(id).await?;
698        let body = json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": false});
699        let created = self
700            .call_bytes(
701                Method::POST,
702                &format!("/containers/{}/exec", enc(id)),
703                Some(body),
704            )
705            .await?;
706        let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
707        let eid = v["Id"]
708            .as_str()
709            .ok_or_else(|| io::Error::other("docker exec: no Id"))?
710            .to_string();
711        let resp = self
712            .call(
713                Method::POST,
714                &format!("/exec/{}/start", enc(&eid)),
715                Some(json!({"Detach": false, "Tty": false})),
716            )
717            .await?;
718        let mut body = resp.into_body();
719        let mut buf = BytesMut::new();
720        let mut out = Vec::new();
721        while let Some(Ok(frame)) = body.frame().await {
722            if let Ok(data) = frame.into_data() {
723                buf.extend_from_slice(&data);
724                demux(&mut buf, &mut out, 64 * 1024);
725            }
726        }
727        let info = self.get_json(&format!("/exec/{}/json", enc(&eid))).await?;
728        let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
729        Ok((v["ExitCode"].as_i64().unwrap_or(-1), out))
730    }
731
732    async fn exec_stream(&self, id: &str, opts: &ExecOpts) -> io::Result<ExecHandle> {
733        self.ensure_managed(id).await?;
734        let body = json!({
735            "Cmd": opts.cmd,
736            "AttachStdin": opts.stdin,
737            "AttachStdout": true,
738            "AttachStderr": !opts.tty,
739            "Tty": opts.tty,
740        });
741        let created = self
742            .call_bytes(
743                Method::POST,
744                &format!("/containers/{}/exec", enc(id)),
745                Some(body),
746            )
747            .await?;
748        let v: Value = serde_json::from_slice(&created).map_err(io::Error::other)?;
749        let eid = v["Id"]
750            .as_str()
751            .ok_or_else(|| io::Error::other("docker exec: no Id"))?
752            .to_string();
753        let (stream, head_buf) = self
754            .hijack(
755                &format!("/exec/{}/start", enc(&eid)),
756                json!({"Detach": false, "Tty": opts.tty}),
757            )
758            .await?;
759        let (r, w) = tokio::io::split(stream);
760        type Sink = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
761        let (stdin, hold): (Option<Sink>, Option<Sink>) = if opts.stdin {
762            (Some(Box::new(w)), None)
763        } else {
764            (None, Some(Box::new(w)))
765        };
766        let (otx, orx) = mpsc::channel::<Bytes>(16);
767        let (etx, erx) = mpsc::channel::<Bytes>(16);
768        let tty = opts.tty;
769        tokio::spawn(async move {
770            let mut r = r;
771            let mut buf = head_buf;
772            let mut eof = false;
773            loop {
774                loop {
775                    if tty {
776                        if buf.is_empty() {
777                            break;
778                        }
779                        if otx.send(buf.split().freeze()).await.is_err() {
780                            return;
781                        }
782                    } else if buf.len() >= 8 {
783                        let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
784                        if buf.len() < 8 + len {
785                            break;
786                        }
787                        let stream_ty = buf[0];
788                        buf.advance(8);
789                        let chunk = buf.split_to(len).freeze();
790                        let tx = if stream_ty == 2 { &etx } else { &otx };
791                        if !chunk.is_empty() && tx.send(chunk).await.is_err() {
792                            return;
793                        }
794                    } else {
795                        break;
796                    }
797                }
798                if eof {
799                    break;
800                }
801                let mut tmp = [0u8; 8192];
802                match r.read(&mut tmp).await {
803                    Ok(0) => eof = true,
804                    Ok(n) => buf.extend_from_slice(&tmp[..n]),
805                    Err(_) => break,
806                }
807            }
808        });
809        Ok(ExecHandle {
810            exec_id: eid,
811            stdout: orx,
812            stderr: erx,
813            stdin,
814            hold,
815        })
816    }
817
818    async fn exec_resize(&self, exec_id: &str, width: u32, height: u32) -> io::Result<()> {
819        self.call(
820            Method::POST,
821            &format!("/exec/{}/resize?h={height}&w={width}", enc(exec_id)),
822            None,
823        )
824        .await
825        .map(|_| ())
826    }
827
828    async fn exec_exit_code(&self, exec_id: &str) -> io::Result<i64> {
829        let info = self
830            .get_json(&format!("/exec/{}/json", enc(exec_id)))
831            .await?;
832        let v: Value = serde_json::from_slice(&info).map_err(io::Error::other)?;
833        Ok(v["ExitCode"].as_i64().unwrap_or(-1))
834    }
835}
836
837#[cfg(test)]
838mod tests {
839    use super::*;
840
841    #[test]
842    fn image_split() {
843        assert_eq!(split_image("nginx:alpine"), ("nginx", "alpine"));
844        assert_eq!(split_image("nginx"), ("nginx", "latest"));
845        assert_eq!(split_image("reg:5000/a/b"), ("reg:5000/a/b", "latest"));
846        assert_eq!(split_image("reg:5000/a/b:1.2"), ("reg:5000/a/b", "1.2"));
847        assert_eq!(split_image("a@sha256:ff"), ("a", "sha256:ff"));
848    }
849
850    #[test]
851    fn ids_are_escaped_in_paths() {
852        assert_eq!(
853            enc("abc/archive?path=/etc&"),
854            "abc%2Farchive%3Fpath%3D%2Fetc%26"
855        );
856        assert_eq!(enc("krab_default_p_c"), "krab_default_p_c");
857    }
858
859    #[test]
860    fn create_body_maps_spec() {
861        let spec = ContainerSpec {
862            name: "krab_default_p_c".into(),
863            image: "nginx:alpine".into(),
864            command: vec!["sh".into()],
865            restart: crate::RestartPolicy::OnFailure,
866            memory_bytes: Some(1 << 20),
867            nano_cpus: Some(500_000_000),
868            ports: vec![crate::PortSpec {
869                container_port: 80,
870                protocol: "TCP".into(),
871                host_port: Some(8080),
872                host_ip: None,
873            }],
874            mounts: vec![
875                Mount::Bind {
876                    src: "/a".into(),
877                    dst: "/b".into(),
878                    read_only: true,
879                },
880                Mount::Tmpfs { dst: "/t".into() },
881            ],
882            network: Some("krab".into()),
883            aliases: vec!["web".into()],
884            ..Default::default()
885        };
886        let b = create_body(&spec);
887        assert_eq!(b["HostConfig"]["RestartPolicy"]["Name"], "on-failure");
888        assert_eq!(b["HostConfig"]["Memory"], 1 << 20);
889        assert_eq!(b["HostConfig"]["NanoCpus"], 500_000_000);
890        assert_eq!(
891            b["HostConfig"]["Mounts"][0],
892            json!({"Type": "bind", "Source": "/a", "Target": "/b", "ReadOnly": true})
893        );
894        assert_eq!(b["HostConfig"]["SecurityOpt"][0], "no-new-privileges");
895        assert_eq!(b["HostConfig"]["CapDrop"][0], "NET_RAW");
896        assert_eq!(
897            b["HostConfig"]["PortBindings"]["80/tcp"][0]["HostPort"],
898            "8080"
899        );
900        assert_eq!(b["Cmd"], json!([]));
901        assert_eq!(
902            b["NetworkingConfig"]["EndpointsConfig"]["krab"]["Aliases"][0],
903            "web"
904        );
905    }
906
907    #[test]
908    fn seccomp_modes_checked() {
909        for t in [None, Some("RuntimeDefault")] {
910            seccomp_supported("docker", t, SUPPORTED_SECCOMP).unwrap();
911        }
912        for t in [Some("Localhost"), Some("Unconfined"), Some("Weird")] {
913            assert_eq!(
914                seccomp_supported("docker", t, SUPPORTED_SECCOMP)
915                    .unwrap_err()
916                    .kind(),
917                io::ErrorKind::InvalidInput
918            );
919        }
920    }
921
922    #[test]
923    fn runtime_default_keeps_docker_default_profile() {
924        let spec = ContainerSpec {
925            name: "krab_default_p_c".into(),
926            image: "nginx:alpine".into(),
927            seccomp: Some("RuntimeDefault".into()),
928            ..Default::default()
929        };
930        assert!(
931            !create_body(&spec)
932                .to_string()
933                .to_lowercase()
934                .contains("seccomp")
935        );
936    }
937}