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
use super::*;
use docker_api::{conn::TtyChunk, Docker};
use futures::{
    future::ready,
    stream::{iter, once, StreamExt},
};
use reqwest::Client;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
use tokio::{fs::File, io::AsyncWriteExt};
use tracing::info;

const DEFAULT_DOCKER_SOCKET: &str = "unix:///var/run/docker.sock";

#[cfg(feature = "options")]
pub(crate) mod options;

#[cfg(test)]
mod tests;

/// Build strategy that uses Docker.
#[derive(Clone, Debug)]
pub struct DockerStrategy {
    client: Client,
    docker: Docker,
}

#[async_trait]
impl Strategy for DockerStrategy {
    async fn builder_from_path(&self, path: &Path) -> Result<DynBuilder> {
        Ok(Box::new(DockerBuilder::new(self.docker.clone(), path)))
    }

    async fn builder_from_crate(&self, _krate: &Path) -> Result<DynBuilder> {
        todo!()
    }

    async fn builder_from_url(&self, url: &Url, _checksum: &[u8]) -> Result<DynBuilder> {
        let dir = TempDir::new()?;

        info!("Downloading crate from {url}");

        let crate_file = self.client.get(url.as_str()).send().await?;
        let mut stream = crate_file.bytes_stream();
        let download_crate = dir.path().join("download.crate");
        let download_folder = dir.path().join("output");

        let mut file = File::create(&download_crate).await?;
        while let Some(item) = stream.next().await {
            file.write_all(&item?).await?;
        }
        file.flush().await?;

        info!("Extracting crate");

        let download_folder_clone = download_folder.clone();
        tokio::spawn(async move {
            use flate2::read::GzDecoder;
            use tar::Archive;
            let file = std::fs::File::open(&download_crate)?;
            std::fs::create_dir(&download_folder)?;
            let tar = GzDecoder::new(file);
            let mut archive = Archive::new(tar);
            archive.unpack(download_folder)?;
            Ok(()) as Result<()>
        })
        .await??;

        info!("Extracted crate");

        // find crate subfolder
        let mut download_folder = tokio::fs::read_dir(&download_folder_clone).await?;
        let download_folder = download_folder.next_entry().await?.unwrap().path();

        let mut builder = DockerBuilder::new(self.docker.clone(), download_folder);
        builder.tempdir = Some(dir);
        Ok(Box::new(builder))
    }
}

/// Crate builder that uses Docker to execute Cargo commands.
#[derive(Debug)]
pub struct DockerBuilder {
    docker: Docker,
    folder: PathBuf,
    tempdir: Option<TempDir>,
}

impl DockerBuilder {
    /// Create new Docker builer from Docker handle and path.
    pub fn new<P: Into<PathBuf>>(docker: Docker, path: P) -> Self {
        Self {
            docker,
            folder: path.into(),
            tempdir: None,
        }
    }

    /// Get reference to Docker handle.
    pub fn docker(&self) -> &Docker {
        &self.docker
    }

    /// Get path that this crate is extracted at.
    pub fn folder(&self) -> &Path {
        &self.folder
    }

    /// Delete this crate.
    pub async fn delete(self) -> Result<()> {
        tokio::fs::remove_dir_all(&self.folder).await?;
        Ok(())
    }
}

#[async_trait]
impl Builder for DockerBuilder {
    async fn metadata(&self) -> Result<OutputStream<Metadata>> {
        let containers = self.docker.containers();
        let opts = docker_api::opts::ContainerCreateOpts::builder()
            .attach_stdout(true)
            .auto_remove(true)
            .command(["cargo", "metadata", "--no-deps", "--format-version=1"])
            .image("docker.io/library/rust")
            .volumes([format!("{}:/crates:ro", self.folder.display())])
            .working_dir("/crates")
            .network_mode("none")
            .build();
        let container = containers.create(&opts).await?;

        info!("Created docker container");

        let output = container.attach().await?;
        container.start().await?;

        info!("Launched docker container");

        let mut stderr = vec![];
        let mut stdout = vec![];

        let output = output
            .map(Some)
            .chain(once(ready(None)))
            .flat_map(move |chunk| {
                let items = match chunk {
                    // end of stream, emit final logs and artifact.
                    None => {
                        let mut output = vec![];
                        if !stderr.is_empty() {
                            output.push(Ok(Output::Build(std::mem::take(&mut stderr))));
                        }
                        output.push(
                            serde_json::from_slice(&stdout)
                                .map(Output::Data)
                                .map_err(|err| err.into()),
                        );
                        output
                    }
                    // error, emit unchanged.
                    Some(Err(error)) => vec![Err(error.into())],
                    // error log, turn into one output per line.
                    Some(Ok(TtyChunk::StdErr(mut out))) => {
                        stderr.append(&mut out);
                        let mut lines: Vec<Vec<u8>> = stderr
                            .split_inclusive(|c| *c == b'\n')
                            .map(|slice| slice.to_vec())
                            .collect();

                        // if the last line is incomplete, because it does not have a trailing
                        // newline, then keep it and wait for more data.
                        if let Some(last) = lines.last() {
                            if last.last() != Some(&b'\n') {
                                stderr = lines.pop().unwrap();
                            }
                        }

                        stderr.clear();
                        lines
                            .into_iter()
                            .map(|line| Ok(Output::Build(line)))
                            .collect()
                    }
                    // standard output, only collect.
                    Some(Ok(TtyChunk::StdOut(mut out))) => {
                        stdout.append(&mut out);
                        vec![]
                    }
                    // standard input, we should never be seeing this.
                    Some(Ok(TtyChunk::StdIn(_))) => vec![],
                };
                iter(items)
            })
            .boxed();

        Ok(output)
    }
}