-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathutils.rs
More file actions
294 lines (260 loc) · 8.53 KB
/
utils.rs
File metadata and controls
294 lines (260 loc) · 8.53 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2021 Red Hat, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use std::str::FromStr;
use crate::{KrunvmConfig, VmConfig, APP_NAME};
pub enum BuildahCommand {
From,
Inspect,
Mount,
Unmount,
Remove,
}
#[cfg(target_os = "linux")]
pub fn get_buildah_args(_cfg: &KrunvmConfig, cmd: BuildahCommand) -> Vec<String> {
match cmd {
BuildahCommand::From => vec!["from".to_string()],
BuildahCommand::Inspect => vec!["inspect".to_string()],
BuildahCommand::Mount => vec!["mount".to_string()],
BuildahCommand::Unmount => vec!["umount".to_string()],
BuildahCommand::Remove => vec!["rm".to_string()],
}
}
#[cfg(target_os = "macos")]
pub fn get_buildah_args(cfg: &KrunvmConfig, cmd: BuildahCommand) -> Vec<String> {
let mut hbpath = std::env::current_exe().unwrap();
hbpath.pop();
hbpath.pop();
let hbpath = hbpath.as_path().display();
let policy_json = format!("{hbpath}/etc/containers/policy.json");
let registries_json = format!("{hbpath}/etc/containers/registries.conf");
let storage_root = format!("{}/root", cfg.storage_volume);
let storage_runroot = format!("{}/runroot", cfg.storage_volume);
let mut args = vec![
"--root".to_string(),
storage_root,
"--runroot".to_string(),
storage_runroot,
];
match cmd {
BuildahCommand::From => {
args.push("--signature-policy".to_string());
args.push(policy_json);
args.push("--registries-conf".to_string());
args.push(registries_json);
args.push("from".to_string());
args.push("--os".to_string());
args.push("linux".to_string());
}
BuildahCommand::Inspect => {
args.push("inspect".to_string());
}
BuildahCommand::Mount => {
args.push("mount".to_string());
}
BuildahCommand::Unmount => {
args.push("umount".to_string());
}
BuildahCommand::Remove => {
args.push("rm".to_string());
}
}
args
}
#[derive(Debug, Clone)]
pub struct PortPair {
pub host_port: String,
pub guest_port: String,
}
pub fn port_pairs_to_hash_map(
port_pairs: impl IntoIterator<Item = PortPair>,
) -> HashMap<String, String> {
port_pairs
.into_iter()
.map(|pair: PortPair| (pair.host_port, pair.guest_port))
.collect()
}
impl FromStr for PortPair {
type Err = &'static str;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let vtuple: Vec<&str> = input.split(':').collect();
if vtuple.len() != 2 {
return Err("Too many ':' separators");
}
let host_port: u16 = match vtuple[0].parse() {
Ok(p) => p,
Err(_) => {
return Err("Invalid host port");
}
};
let guest_port: u16 = match vtuple[1].parse() {
Ok(p) => p,
Err(_) => {
return Err("Invalid guest port");
}
};
Ok(PortPair {
host_port: host_port.to_string(),
guest_port: guest_port.to_string(),
})
}
}
#[derive(Debug, Clone)]
pub struct PathPair {
pub host_path: String,
pub guest_path: String,
}
pub fn path_pairs_to_hash_map(
volume_pairs: impl IntoIterator<Item = PathPair>,
) -> HashMap<String, String> {
volume_pairs
.into_iter()
.map(|pair: PathPair| (pair.host_path, pair.guest_path))
.collect()
}
impl FromStr for PathPair {
type Err = &'static str;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let vtuple: Vec<&str> = input.split(':').collect();
if vtuple.len() != 2 {
return Err("Too many ':' separators");
}
let host_path = Path::new(vtuple[0]);
if !host_path.is_absolute() {
return Err("Invalid volume, host_path is not an absolute path");
}
if !host_path.exists() {
return Err("Invalid volume, host_path does not exists");
}
let guest_path = Path::new(vtuple[1]);
if !guest_path.is_absolute() {
return Err("Invalid volume, guest_path is not an absolute path");
}
if guest_path.components().count() != 2 {
return Err(
"Invalid volume, only single direct root children are supported as guest_path",
);
}
Ok(Self {
host_path: vtuple[0].to_string(),
guest_path: vtuple[1].to_string(),
})
}
}
#[cfg(target_os = "macos")]
fn fix_root_mode(rootfs: &str) {
let mut args = vec!["-w", "user.containers.override_stat", "0:0:0555"];
args.push(rootfs);
let output = match Command::new("xattr")
.args(&args)
.stderr(std::process::Stdio::inherit())
.output()
{
Ok(output) => output,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
println!("{} requires xattr to manage the OCI images, and it wasn't found on this system.", APP_NAME);
} else {
println!("Error executing xattr: {}", err);
}
std::process::exit(-1);
}
};
let exit_code = output.status.code().unwrap_or(-1);
if exit_code != 0 {
println!("xattr returned an error: {}", exit_code);
std::process::exit(-1);
}
}
#[allow(unused_variables)]
pub fn mount_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result<String, std::io::Error> {
let mut args = get_buildah_args(cfg, BuildahCommand::Mount);
args.push(vmcfg.container.clone());
let output = match Command::new("buildah")
.args(&args)
.stderr(std::process::Stdio::inherit())
.output()
{
Ok(output) => output,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME);
} else {
println!("Error executing buildah: {}", err);
}
std::process::exit(-1);
}
};
let exit_code = output.status.code().unwrap_or(-1);
if exit_code != 0 {
println!(
"buildah returned an error: {}",
std::str::from_utf8(&output.stdout).unwrap()
);
std::process::exit(-1);
}
let rootfs = std::str::from_utf8(&output.stdout).unwrap().trim();
#[cfg(target_os = "macos")]
fix_root_mode(rootfs);
Ok(rootfs.to_string())
}
#[allow(unused_variables)]
pub fn umount_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result<(), std::io::Error> {
let mut args = get_buildah_args(cfg, BuildahCommand::Unmount);
args.push(vmcfg.container.clone());
let output = match Command::new("buildah")
.args(&args)
.stderr(std::process::Stdio::inherit())
.output()
{
Ok(output) => output,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME);
} else {
println!("Error executing buildah: {}", err);
}
std::process::exit(-1);
}
};
let exit_code = output.status.code().unwrap_or(-1);
if exit_code != 0 {
println!(
"buildah returned an error: {}",
std::str::from_utf8(&output.stdout).unwrap()
);
std::process::exit(-1);
}
Ok(())
}
#[allow(unused_variables)]
pub fn remove_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result<(), std::io::Error> {
let mut args = get_buildah_args(cfg, BuildahCommand::Remove);
args.push(vmcfg.container.clone());
let output = match Command::new("buildah")
.args(&args)
.stderr(std::process::Stdio::inherit())
.output()
{
Ok(output) => output,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME);
} else {
println!("Error executing buildah: {}", err);
}
std::process::exit(-1);
}
};
let exit_code = output.status.code().unwrap_or(-1);
if exit_code != 0 {
println!(
"buildah returned an error: {}",
std::str::from_utf8(&output.stdout).unwrap()
);
std::process::exit(-1);
}
Ok(())
}