Skip to content
1        10        20        30        40        50        60        70        80        90        1001use std::{2    collections::HashMap,3    io::{IsTerminal, Write},4};56use bollard::{7    Docker,8    exec::{CreateExecOptions, StartExecOptions, StartExecResults},9    models::{ContainerCreateBody, NetworkCreateRequest, VolumeCreateRequest},10    query_parameters::{11        ContainerArchiveInfoOptionsBuilder, CreateContainerOptionsBuilder,12        CreateImageOptionsBuilder, DownloadFromContainerOptionsBuilder,13        ListContainersOptionsBuilder, ListNetworksOptionsBuilder, ListVolumesOptionsBuilder,14        LogsOptionsBuilder, UploadToContainerOptionsBuilder,15    },16};1718use super::error::OnceError;1920#[derive(Debug, Clone, PartialEq, Eq)]21pub struct ContainerRecord {22    pub id: String,23    pub names: Vec<String>,24    pub state: String,25    pub created: i64,26    pub labels: HashMap<String, String>,27}2829#[derive(Debug, Clone, PartialEq, Eq)]30pub struct CapturedExec {31    pub exit_code: i32,32    pub stdout: String,33    pub stderr: String,34    pub truncated: bool,35}3637#[derive(Debug, Clone, PartialEq, Eq)]38pub struct BoundedLogs {39    pub output: String,40    pub truncated: bool,41}4243pub struct DockerEngine {44    client: Docker,45}4647impl DockerEngine {48    pub fn connect() -> Result<Self, OnceError> {49        let client = Docker::connect_with_local_defaults()50            .map_err(|error| OnceError::Docker(error.to_string()))?;51        Ok(Self { client })52    }5354    pub async fn list_containers(&self) -> Result<Vec<ContainerRecord>, OnceError> {55        let options = ListContainersOptionsBuilder::default().all(true).build();56        let containers: Vec<bollard::models::ContainerSummary> =57            self.client.list_containers(Some(options)).await?;5859        Ok(containers60            .into_iter()61            .map(|container| ContainerRecord {62                id: container.id.unwrap_or_default(),63                names: container.names.unwrap_or_default(),64                state: container65                    .state66                    .map(|state| state.to_string())67                    .unwrap_or_default(),68                created: container.created.unwrap_or_default(),69                labels: container.labels.unwrap_or_default(),70            })71            .collect())72    }7374    pub async fn ensure_network(&self, name: &str) -> Result<(), OnceError> {75        let networks = self76            .client77            .list_networks(Some(ListNetworksOptionsBuilder::default().build()))78            .await?;79        if networks80            .iter()81            .any(|network| network.name.as_deref() == Some(name))82        {83            return Ok(());84        }85        self.client86            .create_network(NetworkCreateRequest {87                name: name.to_owned(),88                driver: Some("bridge".to_owned()),89                ..Default::default()90            })91            .await?;92        Ok(())93    }9495    pub async fn remove_network(&self, name: &str) -> Result<(), OnceError> {96        match self.client.remove_network(name).await {97            Ok(())98            | Err(bollard::errors::Error::DockerResponseServerError {99                status_code: 404, ..100            }) => Ok(()),101            Err(error) => Err(OnceError::Docker(error.to_string())),102        }103    }104105    pub async fn list_volume_names(&self) -> Result<Vec<String>, OnceError> {106        let volumes = self107            .client108            .list_volumes(Some(ListVolumesOptionsBuilder::default().build()))109            .await?;110        Ok(volumes111            .volumes112            .unwrap_or_default()113            .into_iter()114            .map(|volume| volume.name)115            .collect())116    }117118    pub async fn volume_label(&self, name: &str, label: &str) -> Result<Option<String>, OnceError> {119        let volume = self.client.inspect_volume(name).await?;120        Ok(volume.labels.get(label).cloned())121    }122123    pub async fn container_path_exists(124        &self,125        container_id: &str,126        path: &str,127    ) -> Result<bool, OnceError> {128        let options = ContainerArchiveInfoOptionsBuilder::default()129            .path(path)130            .build();131        match self132            .client133            .get_container_archive_info(container_id, Some(options))134            .await135        {136            Ok(_) => Ok(true),137            Err(bollard::errors::Error::DockerResponseServerError {138                status_code: 404, ..139            }) => Ok(false),140            Err(error) => Err(OnceError::Docker(error.to_string())),141        }142    }143144    pub async fn download_container_path(145        &self,146        container_id: &str,147        path: &str,148        destination: &mut impl Write,149    ) -> Result<(), OnceError> {150        use futures_util::StreamExt;151        let options = DownloadFromContainerOptionsBuilder::default()152            .path(path)153            .build();154        let mut stream = self155            .client156            .download_from_container(container_id, Some(options));157        while let Some(chunk) = stream.next().await {158            destination159                .write_all(&chunk?)160                .map_err(|error| OnceError::Io(error.to_string()))?;161        }162        Ok(())163    }164165    pub async fn upload_archive_to_container(166        &self,167        container_id: &str,168        destination: &str,169        archive: std::fs::File,170    ) -> Result<(), OnceError> {171        let options = UploadToContainerOptionsBuilder::default()172            .path(destination)173            .build();174        let archive = tokio::fs::File::from_std(archive);175        let body = bollard::body_try_stream(tokio_util::io::ReaderStream::new(archive));176        self.client177            .upload_to_container(container_id, Some(options), body)178            .await?;179        Ok(())180    }181182    pub async fn pause_container(&self, container_id: &str) -> Result<(), OnceError> {183        self.client.pause_container(container_id).await?;184        Ok(())185    }186187    pub async fn unpause_container(&self, container_id: &str) -> Result<(), OnceError> {188        self.client.unpause_container(container_id).await?;189        Ok(())190    }191192    pub async fn ensure_volume(193        &self,194        name: &str,195        labels: HashMap<String, String>,196    ) -> Result<bool, OnceError> {197        match self.client.inspect_volume(name).await {198            Ok(_) => Ok(false),199            Err(bollard::errors::Error::DockerResponseServerError {200                status_code: 404, ..201            }) => {202                self.client203                    .create_volume(VolumeCreateRequest {204                        name: Some(name.to_owned()),205                        labels: Some(labels),206                        ..Default::default()207                    })208                    .await?;209                Ok(true)210            }211            Err(error) => Err(OnceError::Docker(error.to_string())),212        }213    }214215    pub async fn create_container(216        &self,217        name: &str,218        config: ContainerCreateBody,219    ) -> Result<String, OnceError> {220        let options = CreateContainerOptionsBuilder::default().name(name).build();221        let response = self.client.create_container(Some(options), config).await?;222        Ok(response.id)223    }224225    pub async fn pull_image(&self, image: &str) -> Result<(), OnceError> {226        self.pull_image_with_credentials(image, None).await227    }228229    pub async fn pull_image_with_credentials(230        &self,231        image: &str,232        registry: Option<&super::model::RegistrySettings>,233    ) -> Result<(), OnceError> {234        use futures_util::StreamExt;235        let options = CreateImageOptionsBuilder::default()236            .from_image(image)237            .build();238        let credentials = registry.map(|registry| bollard::auth::DockerCredentials {239            username: Some(registry.username.clone()),240            password: Some(registry.password.clone()),241            serveraddress: Some(registry.host.clone()),242            ..Default::default()243        });244        let mut stream = self.client.create_image(Some(options), None, credentials);245        while let Some(result) = stream.next().await {246            result?;247        }248        Ok(())249    }250251    pub async fn image_id(&self, image: &str) -> Result<String, OnceError> {252        let image_reference = image;253        let image = self.client.inspect_image(image_reference).await?;254        image.id.ok_or_else(|| {255            OnceError::Docker(format!(256                "Docker returned no ID for image {image_reference:?}"257            ))258        })259    }260261    pub async fn image_exists(&self, image: &str) -> Result<bool, OnceError> {262        match self.client.inspect_image(image).await {263            Ok(_) => Ok(true),264            Err(bollard::errors::Error::DockerResponseServerError {265                status_code: 404, ..266            }) => Ok(false),267            Err(error) => Err(OnceError::Docker(error.to_string())),268        }269    }270271    pub async fn container_image_id(&self, container_id: &str) -> Result<String, OnceError> {272        let container = self.client.inspect_container(container_id, None).await?;273        container274            .image275            .ok_or_else(|| OnceError::Docker("Docker returned no container image ID".into()))276    }277278    pub async fn container_environment(279        &self,280        container_id: &str,281    ) -> Result<Vec<String>, OnceError> {282        let container = self.client.inspect_container(container_id, None).await?;283        Ok(container284            .config285            .and_then(|config| config.env)286            .unwrap_or_default())287    }288289    pub async fn start_container(&self, container_id: &str) -> Result<(), OnceError> {290        self.client.start_container(container_id, None).await?;291        Ok(())292    }293294    pub async fn stop_container(&self, container_id: &str) -> Result<(), OnceError> {295        self.client.stop_container(container_id, None).await?;296        Ok(())297    }298299    pub async fn remove_container(&self, container_id: &str) -> Result<(), OnceError> {300        self.client301            .remove_container(302                container_id,303                Some(304                    bollard::query_parameters::RemoveContainerOptionsBuilder::default()305                        .force(true)306                        .build(),307                ),308            )309            .await?;310        Ok(())311    }312313    pub async fn remove_volume(&self, volume_name: &str) -> Result<(), OnceError> {314        self.client315            .remove_volume(316                volume_name,317                Some(318                    bollard::query_parameters::RemoveVolumeOptionsBuilder::default()319                        .force(true)320                        .build(),321                ),322            )323            .await?;324        Ok(())325    }326327    pub async fn exec(&self, container_id: &str, command: &[String]) -> Result<i32, OnceError> {328        use futures_util::StreamExt;329        let tty = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();330        if tty {331            crossterm::terminal::enable_raw_mode()332                .map_err(|error| OnceError::Io(format!("setting terminal raw mode: {error}")))?;333        }334        let _raw_terminal = RawTerminal(tty);335        let exec = self336            .client337            .create_exec(338                container_id,339                CreateExecOptions::<String> {340                    cmd: Some(command.to_vec()),341                    attach_stdin: Some(true),342                    attach_stdout: Some(true),343                    attach_stderr: Some(true),344                    tty: Some(tty),345                    ..Default::default()346                },347            )348            .await?;349        let response = self350            .client351            .start_exec(352                &exec.id,353                Some(StartExecOptions {354                    detach: false,355                    tty,356                    output_capacity: None,357                }),358            )359            .await?;360361        if tty {362            resize_exec(&self.client, &exec.id).await;363        }364365        if let StartExecResults::Attached {366            mut output,367            mut input,368        } = response369        {370            let input_task = tokio::spawn(async move {371                let mut stdin = tokio::io::stdin();372                let _ = tokio::io::copy(&mut stdin, &mut input).await;373            });374            let resize_task = if tty {375                Some(spawn_resize_monitor(self.client.clone(), exec.id.clone()))376            } else {377                None378            };379380            let output_result = async {381                while let Some(result) = output.next().await {382                    match result? {383                        bollard::container::LogOutput::StdErr { message } if !tty => {384                            std::io::stderr()385                                .write_all(&message)386                                .map_err(|error| OnceError::Io(error.to_string()))?;387                        }388                        bollard::container::LogOutput::StdOut { message }389                        | bollard::container::LogOutput::Console { message }390                        | bollard::container::LogOutput::StdIn { message }391                        | bollard::container::LogOutput::StdErr { message } => {392                            std::io::stdout()393                                .write_all(&message)394                                .map_err(|error| OnceError::Io(error.to_string()))?;395                        }396                    }397                }398                Ok::<(), OnceError>(())399            }400            .await;401            input_task.abort();402            if let Some(resize_task) = resize_task {403                resize_task.abort();404            }405            output_result?;406        }407408        let inspect = self.client.inspect_exec(&exec.id).await?;409        Ok(inspect410            .exit_code411            .unwrap_or_default()412            .try_into()413            .unwrap_or(i32::MAX))414    }415416    pub async fn exec_capture(417        &self,418        container_id: &str,419        command: &[String],420    ) -> Result<(i32, String), OnceError> {421        let exec = self422            .client423            .create_exec(424                container_id,425                CreateExecOptions::<String> {426                    cmd: Some(command.to_vec()),427                    attach_stdout: Some(true),428                    attach_stderr: Some(true),429                    ..Default::default()430                },431            )432            .await?;433        let response = self434            .client435            .start_exec(436                &exec.id,437                Some(StartExecOptions {438                    detach: false,439                    tty: false,440                    output_capacity: None,441                }),442            )443            .await?;444        let mut text = String::new();445        if let StartExecResults::Attached { mut output, .. } = response {446            use futures_util::StreamExt;447            while let Some(result) = output.next().await {448                text.push_str(&result?.to_string());449            }450        }451        let inspect = self.client.inspect_exec(&exec.id).await?;452        Ok((453            inspect454                .exit_code455                .unwrap_or_default()456                .try_into()457                .unwrap_or(i32::MAX),458            text,459        ))460    }461462    pub async fn exec_capture_bounded(463        &self,464        container_id: &str,465        command: &[String],466        max_bytes: usize,467    ) -> Result<CapturedExec, OnceError> {468        let exec = self469            .client470            .create_exec(471                container_id,472                CreateExecOptions::<String> {473                    cmd: Some(command.to_vec()),474                    attach_stdout: Some(true),475                    attach_stderr: Some(true),476                    tty: Some(false),477                    ..Default::default()478                },479            )480            .await?;481        let response = self482            .client483            .start_exec(484                &exec.id,485                Some(StartExecOptions {486                    detach: false,487                    tty: false,488                    output_capacity: None,489                }),490            )491            .await?;492493        let mut stdout = Vec::new();494        let mut stderr = Vec::new();495        let mut remaining = max_bytes;496        let mut truncated = false;497        if let StartExecResults::Attached { mut output, .. } = response {498            use futures_util::StreamExt;499            while let Some(result) = output.next().await {500                let log = result?;501                let (destination, message) = match log {502                    bollard::container::LogOutput::StdOut { message }503                    | bollard::container::LogOutput::Console { message } => (&mut stdout, message),504                    bollard::container::LogOutput::StdErr { message } => (&mut stderr, message),505                    bollard::container::LogOutput::StdIn { .. } => continue,506                };507                append_capped(destination, &message, &mut remaining, &mut truncated);508                if remaining == 0 && truncated {509                    break;510                }511            }512        }513514        let inspect = self.client.inspect_exec(&exec.id).await?;515        let exit_code = inspect516            .exit_code517            .unwrap_or_default()518            .try_into()519            .unwrap_or(i32::MAX);520        Ok(CapturedExec {521            exit_code,522            stdout: String::from_utf8_lossy(&stdout).into_owned(),523            stderr: String::from_utf8_lossy(&stderr).into_owned(),524            truncated,525        })526    }527528    /// Reads the last `tail` lines. With `timestamps`, each line starts with529    /// its RFC 3339 time and a space, as Docker writes it.530    pub async fn logs_bounded(531        &self,532        container_id: &str,533        tail: u16,534        timestamps: bool,535        max_bytes: usize,536    ) -> Result<BoundedLogs, OnceError> {537        use futures_util::StreamExt;538539        let tail = tail.max(1).to_string();540        let options = LogsOptionsBuilder::default()541            .follow(false)542            .stdout(true)543            .stderr(true)544            .timestamps(timestamps)545            .tail(&tail)546            .build();547        let mut stream = self.client.logs(container_id, Some(options));548        let mut output = Vec::new();549        let mut remaining = max_bytes;550        let mut truncated = false;551        while let Some(result) = stream.next().await {552            let message = match result? {553                bollard::container::LogOutput::StdOut { message }554                | bollard::container::LogOutput::StdErr { message }555                | bollard::container::LogOutput::Console { message } => message,556                bollard::container::LogOutput::StdIn { .. } => continue,557            };558            append_capped(&mut output, &message, &mut remaining, &mut truncated);559            if remaining == 0 && truncated {560                break;561            }562        }563        Ok(BoundedLogs {564            output: String::from_utf8_lossy(&output).into_owned(),565            truncated,566        })567    }568}569570fn append_capped(571    destination: &mut Vec<u8>,572    message: &[u8],573    remaining: &mut usize,574    truncated: &mut bool,575) {576    let length = message.len().min(*remaining);577    destination.extend_from_slice(&message[..length]);578    *remaining -= length;579    if length < message.len() {580        *truncated = true;581    }582}583584struct RawTerminal(bool);585586impl Drop for RawTerminal {587    fn drop(&mut self) {588        if self.0 {589            let _ = crossterm::terminal::disable_raw_mode();590        }591    }592}593594async fn resize_exec(client: &Docker, exec_id: &str) {595    if let Ok((width, height)) = crossterm::terminal::size() {596        let options = bollard::query_parameters::ResizeExecOptionsBuilder::default()597            .w(i32::from(width))598            .h(i32::from(height))599            .build();600        let _ = client.resize_exec(exec_id, options).await;601    }602}603604fn spawn_resize_monitor(client: Docker, exec_id: String) -> tokio::task::JoinHandle<()> {605    tokio::spawn(async move {606        #[cfg(unix)]607        {608            let Ok(mut resize_signal) =609                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change())610            else {611                return;612            };613            while resize_signal.recv().await.is_some() {614                resize_exec(&client, &exec_id).await;615            }616        }617    })618}619620#[cfg(test)]621mod tests {622    use super::append_capped;623624    #[test]625    fn output_capture_caps_bytes_and_tracks_truncation() {626        let mut output = Vec::new();627        let mut remaining = 5;628        let mut truncated = false;629630        append_capped(&mut output, b"abc", &mut remaining, &mut truncated);631        append_capped(&mut output, b"def", &mut remaining, &mut truncated);632633        assert_eq!(output, b"abcde");634        assert_eq!(remaining, 0);635        assert!(truncated);636    }637}