bridge_common/
docker.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright 2024 StarfleetAI
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::path::Path;

use anyhow::Context;
use bollard::models::{ContainerInspectResponse, PortBinding};
use bollard::{
    container::{Config, RemoveContainerOptions},
    exec::{CreateExecOptions, StartExecResults},
    image::CreateImageOptions,
    secret::HostConfig,
};
use futures_util::{StreamExt, TryStreamExt};
use tokio::sync::OnceCell;
use tracing::trace;

use crate::types::Result;

const CONTAINER_WORKDIR: &str = "/bridge";
const DEFAULT_PYTHON_IMAGE: &str = "python:slim";
const DEFAULT_CHROMEDRIVER_IMAGE: &str = "zenika/alpine-chrome:with-chromedriver";

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Bollard(#[from] bollard::errors::Error),
}

/// Run a Python code in a container.
///
/// # Errors
///
/// Will return an error if there was a problem while running the code.
/// TODO move to `ContainerManager`
pub async fn run_python_code(script: &str, maybe_workdir: Option<&Path>) -> Result<String> {
    let binds = binds_for(maybe_workdir);
    let cmd = vec!["python", "-c", &script];

    run_in_container(DEFAULT_PYTHON_IMAGE, binds, cmd).await
}

/// Run a Python script in a container.
///
/// # Errors
///
/// Will return an error if there was a problem while running the script.
/// TODO move to `ContainerManager`
pub async fn run_python_script(workdir: &Path, script_name: &str) -> Result<String> {
    let binds = binds_for(Some(workdir));
    let script_name = format!("{CONTAINER_WORKDIR}/{script_name}");
    let cmd = vec!["python", &script_name];

    run_in_container(DEFAULT_PYTHON_IMAGE, binds, cmd).await
}

/// Run a shell command in a container.
///
/// # Errors
///
/// Will return an error if there was a problem while running the command.
pub async fn run_cmd(cmd: &str, maybe_workdir: Option<&Path>) -> Result<String> {
    let binds = binds_for(maybe_workdir);
    let cmd = vec!["sh", "-c", cmd];

    run_in_container(DEFAULT_PYTHON_IMAGE, binds, cmd).await
}

/// TODO move to `ContainerManager`
async fn run_in_container(
    image: &str,
    binds: Option<Vec<String>>,
    cmd: Vec<&str>,
) -> Result<String> {
    let docker = bollard::Docker::connect_with_local_defaults().map_err(Error::Bollard)?;

    docker
        .create_image(
            Some(CreateImageOptions {
                from_image: image,
                ..Default::default()
            }),
            None,
            None,
        )
        .try_collect::<Vec<_>>()
        .await
        .context("Failed to create image")?;

    let has_binds = binds.is_some();

    let config = Config {
        image: Some(image),
        tty: Some(true),
        host_config: Some(HostConfig {
            binds,
            auto_remove: Some(true),
            ..Default::default()
        }),
        ..Default::default()
    };

    let id = docker
        .create_container::<&str, &str>(None, config)
        .await
        .map_err(Error::Bollard)?
        .id;

    docker
        .start_container::<String>(&id, None)
        .await
        .map_err(Error::Bollard)?;

    let mut out = String::new();

    // If there were no binds, we should use the default workdir
    let working_dir = if has_binds {
        Some(CONTAINER_WORKDIR)
    } else {
        None
    };

    let exec = docker
        .create_exec(
            &id,
            CreateExecOptions {
                attach_stdout: Some(true),
                attach_stderr: Some(true),
                cmd: Some(cmd),
                working_dir,
                ..Default::default()
            },
        )
        .await
        .map_err(Error::Bollard)?
        .id;

    if let StartExecResults::Attached { mut output, .. } = docker
        .start_exec(&exec, None)
        .await
        .map_err(Error::Bollard)?
    {
        while let Some(Ok(msg)) = output.next().await {
            out.push_str(&msg.to_string());
        }
    }

    docker
        .remove_container(
            &id,
            Some(RemoveContainerOptions {
                force: true,
                ..Default::default()
            }),
        )
        .await
        .map_err(Error::Bollard)?;

    out = out.trim().to_string();

    trace!("Script output: {:?}", out);

    Ok(out.to_string())
}

fn binds_for(maybe_workdir: Option<&Path>) -> Option<Vec<String>> {
    maybe_workdir.map(|workdir| vec![format!("{}:{CONTAINER_WORKDIR}", workdir.to_string_lossy())])
}

/// Сentrally manages containers.
pub struct ContainerManager {
    /// The docker client
    client: bollard::Docker,
}

static CONTAINER_MANAGER: OnceCell<ContainerManager> = OnceCell::const_new();

impl ContainerManager {
    /// Initialises the docker client.
    ///
    /// # Errors
    ///
    /// Will return an error if there was a problem while initialising the docker client.
    pub async fn get() -> Result<&'static Self> {
        CONTAINER_MANAGER
            .get_or_try_init(|| async {
                Ok(ContainerManager {
                    client: bollard::Docker::connect_with_local_defaults()
                        .map_err(Error::Bollard)?,
                })
            })
            .await
    }

    /// Function for starting chromedriver container.
    ///
    /// # Errors
    ///
    /// Will return an error if there was a problem while starting the chromedriver container.
    pub async fn launch_chromedriver_container(&self) -> Result<String> {
        let container_config = Config {
            image: Some(DEFAULT_CHROMEDRIVER_IMAGE),
            tty: Some(true),
            host_config: Some(HostConfig {
                auto_remove: Some(true),
                port_bindings: {
                    let mut map = HashMap::with_capacity(1);
                    map.insert(
                        "9515/tcp".to_string(),
                        Some(vec![PortBinding {
                            host_ip: None,
                            host_port: Some(String::new()),
                        }]),
                    );
                    Some(map)
                },
                ..Default::default()
            }),
            ..Default::default()
        };

        let container_id = self
            .client
            .create_container::<&str, &str>(None, container_config)
            .await
            .map_err(Error::Bollard)?
            .id;

        self.client
            .start_container::<String>(&container_id, None)
            .await
            .map_err(Error::Bollard)?;

        Ok(container_id)
    }

    /// Get container information.
    ///
    /// # Errors
    ///
    /// Will return an error if there was a problem while getting the container information.
    pub async fn inspect_container(&self, container_id: &str) -> Result<ContainerInspectResponse> {
        let container_info = self
            .client
            .inspect_container(container_id, None)
            .await
            .map_err(Error::Bollard)?;
        Ok(container_info)
    }

    /// Destroys the container.
    ///
    /// # Errors
    ///
    /// Will return an error if there was a problem while destroying the container.
    pub async fn kill_container(&self, container_name: &str) -> Result<()> {
        self.client
            .kill_container::<String>(container_name, None)
            .await
            .map_err(Error::Bollard)?;
        Ok(())
    }
}