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
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use docker_api::api::{ContainerCreateOpts, PullOpts, RegistryAuth, RmContainerOpts};
use futures_util::{StreamExt, TryStreamExt};
use std::path::PathBuf;
use tar::Archive;

use super::container::Container;

pub struct Image {
    pub image: String,
    pub repo: String,
    pub tag: String,
    pub runtime: docker_api::Docker,
}

#[async_trait]
impl Container for Image {
    // pull ensures that the image is present locally and, if it is isn't
    // will do the work necessary to pull it.
    async fn pull(&self, username: String, password: String, force: bool) -> Result<()> {
        if self.present_locally().await {
            if !force {
                debug!("✅ Skipping the pull process as the image was found locally");
                return Ok(());
            }
            debug!("🔧 Force was set, ignoring images present locally")
        }

        let auth = RegistryAuth::builder()
            .username(username)
            .password(password)
            .build();

        let pull_opts = PullOpts::builder()
            .image(&self.repo)
            .tag(&self.tag)
            .auth(auth)
            .build();

        let images = self.runtime.images();
        let mut stream = images.pull(&pull_opts);
        while let Some(pull_result) = stream.next().await {
            match pull_result {
                Ok(output) => {
                    debug!("🔧 {:?}", output);
                }
                Err(e) => {
                    return Err(anyhow!("{}", e));
                }
            }
        }

        debug!("✅ Successfully pulled the image");
        Ok(())
    }

    // copy_files uses the image_structs values to copy files from the
    // image's file systems appropriately.
    async fn copy_files(
        &self,
        content_path: String,
        download_path: String,
        write_to_stdout: bool,
    ) -> Result<()> {
        // Create the container
        let container_id = match self.start().await {
            Ok(id) => id,
            Err(e) => {
                return Err(anyhow!("failed to start the image: {}", e));
            }
        };

        let mut content_path_buffer = PathBuf::new();
        content_path_buffer.push(&content_path);

        let mut download_path_buffer = PathBuf::new();
        download_path_buffer.push(&download_path);

        // Get the files from the container
        let bytes = self
            .runtime
            .containers()
            .get(&*container_id)
            .copy_from(&content_path_buffer)
            .try_concat()
            .await?;

        // Fail out if the buffer data processed is empty
        if bytes.is_empty() {
            return Err(anyhow!("failed to retrieve the files from the container"));
        }

        // Unpack the archive
        let mut archive = Archive::new(&bytes[..]);
        if write_to_stdout {
            unimplemented!()
        } else {
            archive.unpack(&download_path_buffer)?;
        }

        info!(
            "✅ Copied content to {} successfully",
            download_path_buffer.display()
        );

        // Stop the container
        match self.stop(container_id).await {
            Ok(_) => {}
            Err(e) => {
                return Err(anyhow!("failed to stop the image: {}", e));
            }
        }

        Ok(())
    }

    // start takes the the image struct's values to build a container
    // by interacting the container runtime's socket.
    async fn start(&self) -> Result<String> {
        // note(tflannag): Use a "dummy" command "FROM SCRATCH" container images.
        let cmd = vec![""];
        let create_opts = ContainerCreateOpts::builder(&self.image).cmd(&cmd).build();
        let container = self.runtime.containers().create(&create_opts).await?;
        let id = container.id().to_string();

        debug!("📦 Created container with id: {:?}", id);
        Ok(id)
    }

    // stop takes the given container ID and interacts with the container
    // runtime socket to stop the container.
    async fn stop(&self, id: String) -> Result<()> {
        let delete_opts = RmContainerOpts::builder().force(true).build();
        if let Err(e) = self
            .runtime
            .containers()
            .get(&*id)
            .remove(&delete_opts)
            .await
        {
            return Err(anyhow!("{}", e));
        }

        debug!("📦 Cleaned up container {:?} successfully", id);
        Ok(())
    }

    // present_locally determines if this container's image is pulled locally
    async fn present_locally(&self) -> bool {
        debug!("📦 Searching for image {} locally", self.image);
        match self.runtime.images().list(&Default::default()).await {
            Ok(images) => {
                for image in images {
                    if let Some(repo_tag) = image.repo_tags {
                        for tag in repo_tag {
                            if tag == self.image {
                                debug!("📦 Found image {} locally", self.image);
                                return true;
                            }
                        }
                    }
                }
            }
            Err(e) => error!("error occurred while searching for image locally: {}", e),
        }

        return false;
    }
}