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