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
use crate::{Error, ErrorKind, Status, SystemHarness, SystemTerminal};
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};
use std::process::{Command, Output, Stdio, Child};

fn strip_last_newline(input: &str) -> &str {
    input
        .strip_suffix("\r\n")
        .or(input.strip_suffix("\n"))
        .unwrap_or(input)
}

/// Process output to result
fn output_to_result(output: Output) -> Result<String, Error> {
    match output.status.success() {
        true => Ok(strip_last_newline(
                std::str::from_utf8(&output.stdout)?
        ).to_string()),
        false => {
            let error = std::str::from_utf8(&output.stderr)?;
            Err(Error::new(ErrorKind::HarnessError, error))
        }
    }
}

/// A container system config
#[derive(Clone, Serialize, Deserialize)]
pub struct ContainerSystemConfig {

    /// Container runtime
    tool: String,

    /// Container image
    image: String,

}

impl ContainerSystemConfig {

    /// Build and run a container based on name
    pub fn build(&self) -> Result<ContainerSystem, Error> {
        let id = Command::new(&self.tool)
            .arg("create")
            .arg("-t") 
            .arg(&self.image)
            .output()
            .map_err(|err| err.into())
            .and_then(output_to_result)
            .map_err(|err| { log::warn!("{err}"); err })?;
        log::trace!("Created container: {id}");

        Command::new(&self.tool)
            .stdout(Stdio::null())
            .arg("start")
            .arg(&id)
            .status()?;

        Ok(ContainerSystem {
            id,
            tool: self.tool.clone()
        })
    }

}

pub struct ContainerSystem {
    tool: String,
    id: String,
}

pub struct ContainerSystemTerminal {
    process: Child
}

#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct State {
    running: bool,
    paused: bool
}

#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Inspect {
    state: State
}

impl SystemTerminal for ContainerSystemTerminal {

    fn send_key(&mut self, _key: crate::Key) -> Result<(), Error> {
        Err(Error::new(ErrorKind::HarnessError, "Sending a keystroke not supported"))
    }

}

impl Read for ContainerSystemTerminal {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.process.stdout.as_mut()
            .ok_or(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe, 
                    "Can't read from container"
                    ))
            .and_then(|stdout| stdout.read(buf))
    }
}

impl Write for ContainerSystemTerminal {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.process.stdin.as_mut()
            .ok_or(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe, 
                    "Can't write to container"
                    ))
            .and_then(|stdin| stdin.write(buf))
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.process.stdin.as_mut()
            .ok_or(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe, 
                    "Can't write to container"
                    ))
            .and_then(|stdin| stdin.flush())
    }
}



impl SystemHarness for ContainerSystem {

    type Terminal = ContainerSystemTerminal;

    fn terminal(&self) -> Result<Self::Terminal, Error> {
        let process = Command::new(&self.tool)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .arg("exec")
            .arg("-it")
            .arg(&self.id)
            .arg("sh")
            .spawn()?;
        Ok(Self::Terminal {
            process
        })
    }

    fn pause(&mut self) -> Result<(), Error> {
        log::trace!("Pausing container: {}", &self.id); 
        Command::new(&self.tool)
            .arg("pause")
            .arg(&self.id)
            .output()
            .map_err(|err| err.into())
            .and_then(output_to_result)
            .map(|_| log::trace!("Paused container: {}", self.id))
    }

    fn resume(&mut self) -> Result<(), Error> {
        log::trace!("Resuming container: {}", &self.id); 
        Command::new(&self.tool)
            .arg("unpause")
            .arg(&self.id)
            .output()
            .map_err(|err| err.into())
            .and_then(output_to_result)
            .map(|_| log::trace!("Resumed container: {}", self.id))
    }

    fn shutdown(&mut self) -> Result<(), Error> {
        log::trace!("Shutting down container: {}", &self.id); 
         Command::new(&self.tool)
            .arg("stop")
            .arg(&self.id)
            .output()
            .map_err(|err| err.into())
            .and_then(output_to_result)
            .map(|_| log::trace!("Stopped container: {}", self.id))
    }

    fn status(&mut self) -> Result<Status, Error> {
        Command::new(&self.tool)
            .arg("inspect")
            .arg(&self.id)
            .output()
            .map_err(|err| err.into())
            .and_then(output_to_result)
            .map_err(|err| { log::warn!("{err}"); err })
            .and_then(|stdout| {
                let inspect: Vec<Inspect> = serde_json::from_str(&stdout)?;
                inspect.into_iter()
                    .next()
                    .ok_or(Error::new(ErrorKind::HarnessError, "Container doesn't exist"))
                    .and_then(|inspect| {
                        let state = &inspect.state;
                        if state.running {
                            Ok(Status::Running)
                        } else if state.paused {
                            Ok(Status::Paused)
                        } else if !state.running && !state.paused {
                            Ok(Status::Shutdown)
                        } else {
                            Err(Error::new(ErrorKind::HarnessError,
                                    format!("Unhandled status")))
                        }
                    })
            })
    }

    fn running(&mut self) -> Result<bool, Error> {
        self.status().map(|status| status == Status::Running)
    }

}

impl Drop for ContainerSystem {
    fn drop(&mut self) {
        if let Ok(running) = self.running() {
            if running {
                if let Ok(()) = self.shutdown() {
                    log::trace!("Deleting container: {}", &self.id); 
                    let _ = Command::new(&self.tool)
                        .args(&["rm", "-f", &self.id])
                        .output();
                } else {
                    log::warn!("Failed to shutdown: {}", &self.id);
                }
            }
        }
    }
}