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
use crate::cmd::Command;
use crate::workspace::Workspace;
use failure::Error;
use getrandom::getrandom;
use log::info;
static PROBE_FILENAME: &str = "rustwide-probe";
pub(crate) struct CurrentContainer {
metadata: Metadata,
}
impl CurrentContainer {
pub(crate) fn detect(workspace: &Workspace) -> Result<Option<Self>, Error> {
if let Some(id) = probe_container_id(workspace)? {
info!("inspecting the current container");
let inspect = Command::new(workspace, "docker")
.args(&["inspect", &id])
.log_output(false)
.log_command(false)
.run_capture()?;
let content = inspect.stdout_lines().join("\n");
let mut metadata: Vec<Metadata> = serde_json::from_str(&content)?;
if metadata.len() != 1 {
failure::bail!("invalid output returned by `docker inspect`");
}
Ok(Some(CurrentContainer {
metadata: metadata.pop().unwrap(),
}))
} else {
Ok(None)
}
}
pub(crate) fn mounts(&self) -> &[Mount] {
&self.metadata.mounts
}
}
pub(crate) fn probe_container_id(workspace: &Workspace) -> Result<Option<String>, Error> {
info!("detecting the ID of the container where rustwide is running");
let probe_path = std::env::temp_dir().join(PROBE_FILENAME);
let probe_path_str = probe_path.to_str().unwrap();
let mut probe_content = [0u8; 64];
getrandom(&mut probe_content)?;
let probe_content = base64::encode(&probe_content[..]);
std::fs::write(&probe_path, probe_content.as_bytes())?;
let out = Command::new(workspace, "docker")
.args(&["ps", "--format", "{{.ID}}", "--no-trunc"])
.log_output(false)
.log_command(false)
.run_capture()?;
for id in out.stdout_lines() {
info!("probing container id {}", id);
let res = Command::new(workspace, "docker")
.args(&["exec", &id, "cat", probe_path_str])
.log_output(false)
.log_command(false)
.run_capture();
if let Ok(&[ref probed]) = res.as_ref().map(|out| out.stdout_lines()) {
if *probed == probe_content {
info!("probe successful, this is container ID {}", id);
return Ok(Some(id.clone()));
}
}
}
info!("probe unsuccessful, this is not running inside a container");
Ok(None)
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Metadata {
mounts: Vec<Mount>,
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct Mount {
source: String,
destination: String,
}
impl Mount {
pub(crate) fn source(&self) -> &str {
&self.source
}
pub(crate) fn destination(&self) -> &str {
&self.destination
}
}