-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcontainer.rs
394 lines (351 loc) · 11.9 KB
/
container.rs
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
use anyhow::{anyhow, Result};
use console::{style, user_attended};
use dialoguer::{theme::ColorfulTheme, Confirm, Input};
use git2::Repository;
use nix::unistd::sync;
use rand::random;
use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
};
use crate::{
actions::{ensure_host_sanity, OMA_UPDATE_SCRIPT},
common::*,
config, error, info,
machine::{self, get_container_ns_name, inspect_instance, spawn_container},
network::download_file_progress,
overlayfs, warn,
};
use super::{for_each_instance, APT_UPDATE_SCRIPT};
/// Get the branch name of the workspace TREE repository
#[inline]
fn get_branch_name() -> Result<String> {
let repo = Repository::open("TREE")?;
let head = repo.head()?;
Ok(head
.shorthand()
.ok_or_else(|| anyhow!("Unable to resolve Git ref"))?
.to_owned())
}
/// Determine the output directory name
#[inline]
pub fn get_output_directory(sep_mount: bool) -> String {
if sep_mount {
format!(
"OUTPUT-{}",
get_branch_name().unwrap_or_else(|_| "HEAD".to_string())
)
} else {
"OUTPUT".to_string()
}
}
fn commit(instance: &str) -> Result<()> {
get_instance_ns_name(instance)?;
info!("Un-mounting all the instances...");
// Un-mount all the instances
for_each_instance(&container_down)?;
info!("{}: committing instance...", instance);
let spinner = create_spinner("Committing upper layer...", 200);
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
man.commit()?;
sync();
spinner.finish_and_clear();
Ok(())
}
/// Rollback the container (by removing the upper layer)
fn rollback(instance: &str) -> Result<()> {
get_instance_ns_name(instance)?;
info!("{}: rolling back instance...", instance);
let spinner = create_spinner("Removing upper layer...", 200);
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
man.rollback()?;
sync();
spinner.finish_and_clear();
Ok(())
}
/// Remove everything in the current workspace
pub fn farewell(path: &Path) -> Result<()> {
if !user_attended() {
eprintln!("DELETE THIS CIEL WORKSPACE?");
info!("Not controlled by an user. Automatically confirmed.");
// Un-mount all the instances
for_each_instance(&container_down)?;
fs::remove_dir_all(path.join(".ciel"))?;
return Ok(());
}
let theme = ColorfulTheme::default();
let delete = Confirm::with_theme(&theme)
.with_prompt("DELETE THIS CIEL WORKSPACE?")
.default(false)
.interact()?;
if !delete {
info!("Not confirmed.");
return Ok(());
}
info!(
"If you are absolutely sure, please type the following:\n{}",
style("Do as I say!").bold()
);
if Input::<String>::with_theme(&theme)
.with_prompt("Your turn")
.interact()?
!= "Do as I say!"
{
info!("Prompt answered incorrectly. Not confirmed.");
return Ok(());
}
info!("... as you wish. Commencing destruction ...");
info!("Un-mounting all the instances...");
// Un-mount all the instances
for_each_instance(&container_down)?;
fs::remove_dir_all(path.join(".ciel"))?;
Ok(())
}
/// Download the OS tarball and then extract it for use as the base layer
pub fn load_os(url: &str, sha256: Option<String>, tarball: bool) -> Result<()> {
info!("Downloading base OS rootfs...");
let path = Path::new(url);
let filename = path
.file_name()
.ok_or_else(|| anyhow!("Unable to convert path to string"))?
.to_str()
.ok_or_else(|| anyhow!("Unable to decode path string"))?;
let is_local_file = path.is_file();
let total = if !is_local_file {
download_file_progress(url, filename)?
} else {
let tarball = fs::File::open(path)?;
tarball.metadata()?.len()
};
if let Some(sha256) = sha256 {
info!("Verifying tarball checksum...");
let tarball = fs::File::open(Path::new(filename))?;
let checksum = sha256sum(tarball)?;
if sha256 == checksum {
info!("Checksum verified.");
} else {
return Err(anyhow!(
"Checksum mismatch: expected {} but got {}",
sha256,
checksum
));
}
}
if is_local_file {
extract_system_rootfs(&PathBuf::from(path), total, tarball)?;
} else {
extract_system_rootfs(Path::new(filename), total, tarball)?;
}
Ok(())
}
/// Ask user for the configuration and then apply it
pub fn config_os(instance: Option<&str>) -> Result<()> {
let config;
let mut prev_volatile = None;
if let Ok(c) = config::read_config() {
prev_volatile = Some(c.volatile_mount);
config = config::ask_for_config(Some(c));
} else {
config = config::ask_for_config(None);
}
let path;
if let Some(instance) = instance {
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
path = man.get_config_layer()?;
} else {
path = PathBuf::from(CIEL_DIST_DIR);
}
if let Ok(c) = config {
info!("Shutting down instance(s) before applying config...");
if let Some(instance) = instance {
container_down(instance)?;
} else {
for_each_instance(&container_down)?;
}
config::apply_config(path, &c)?;
fs::create_dir_all(CIEL_DATA_DIR)?;
fs::write(
Path::new(CIEL_DATA_DIR).join("config.toml"),
c.save_config()?,
)?;
info!("Configurations applied.");
let volatile_changed = if let Some(prev_voltile) = prev_volatile {
prev_voltile != c.volatile_mount
} else {
false
};
if volatile_changed {
warn!("You have changed the volatile mount option, please save your work and\x1b[1m\x1b[93m rollback \x1b[4mall the instances\x1b[0m.");
return Ok(());
}
warn!(
"Please rollback {} for the new config to take effect!",
if let Some(inst) = instance {
inst
} else {
"all your instances"
}
);
} else {
return Err(anyhow!("Could not recognize the configuration."));
}
Ok(())
}
/// Mount the filesystem of the instance
pub fn mount_fs(instance: &str) -> Result<()> {
let config = config::read_config()?;
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
man.set_volatile(config.volatile_mount)?;
machine::mount_layers(man, instance)?;
info!("{}: filesystem mounted.", instance);
Ok(())
}
/// Un-mount the filesystem of the container
pub fn unmount_fs(instance: &str) -> Result<()> {
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
let target = std::env::current_dir()?.join(instance);
let mut retry = 0usize;
while man.is_mounted(&target)? {
retry += 1;
if retry > 10 {
return Err(anyhow!("Unable to unmount filesystem after 10 attempts."));
}
man.unmount(&target)?;
}
info!("{}: filesystem un-mounted.", instance);
Ok(())
}
/// Remove the mount point (usually a directory) of the container overlay filesystem
pub fn remove_mount(instance: &str) -> Result<()> {
let target = std::env::current_dir()?.join(instance);
if !target.exists() {
return Ok(());
} else if !target.is_dir() {
warn!("{}: mount point is not a directory.", instance);
return Ok(());
}
match fs::read_dir(&target) {
Ok(mut entry) => {
if entry.any(|_| true) {
warn!(
"Mount point {:?} still contains files, so it will not be removed.",
target
);
return Ok(());
}
}
Err(e) => {
error!("Error when querying {:?}: {}", target, e);
}
}
fs::remove_dir(target)?;
info!("{}: mount point removed.", instance);
Ok(())
}
fn get_instance_ns_name(instance: &str) -> Result<String> {
if !is_instance_exists(instance) {
error!("Instance `{}` does not exist.", instance);
info!(
"You can add a new instance like this: `ciel add {}`",
instance
);
return Err(anyhow!("Unable to acquire container information."));
}
let legacy = is_legacy_workspace()?;
get_container_ns_name(instance, legacy)
}
/// Start the container/instance, also mounting the container filesystem prior to the action
pub fn start_container(instance: &str) -> Result<String> {
let ns_name = get_instance_ns_name(instance)?;
let inst = inspect_instance(instance, &ns_name)?;
let (mut extra_options, mounts) = ensure_host_sanity()?;
if std::env::var("CIEL_OFFLINE").is_ok() {
// FIXME: does not work with current version of systemd
// add the offline option (private-network means don't share the host network)
extra_options.push("--private-network".to_string());
info!("{}: network disconnected.", instance);
}
if !inst.mounted {
mount_fs(instance)?;
}
if !inst.started {
spawn_container(&ns_name, instance, &extra_options, &mounts)?;
}
Ok(ns_name)
}
/// Execute the specified command in the container
pub fn run_in_container<S: AsRef<OsStr>>(instance: &str, args: &[S]) -> Result<i32> {
let ns_name = start_container(instance)?;
let status = machine::execute_container_command(&ns_name, args)?;
Ok(status)
}
/// Stop the container/instance (without un-mounting the filesystem)
pub fn stop_container(instance: &str) -> Result<()> {
let ns_name = get_instance_ns_name(instance)?;
let inst = inspect_instance(instance, &ns_name)?;
if !inst.started {
info!("{}: instance is not running!", instance);
return Ok(());
}
info!("{}: stopping...", instance);
machine::terminate_container_by_name(&ns_name)?;
machine::clean_child_process();
info!("{}: instance stopped.", instance);
Ok(())
}
/// Stop and un-mount the container and its filesystem
pub fn container_down(instance: &str) -> Result<()> {
stop_container(instance)?;
unmount_fs(instance)?;
remove_mount(instance)?;
Ok(())
}
/// Commit the container/instance upper layer changes to the base layer of the filesystem
pub fn commit_container(instance: &str) -> Result<()> {
container_down(instance)?;
commit(instance)?;
info!("{}: instance has been committed.", instance);
Ok(())
}
/// Clear the upper layer of the container/instance filesystem
pub fn rollback_container(instance: &str) -> Result<()> {
container_down(instance)?;
rollback(instance)?;
info!("{}: instance has been rolled back.", instance);
Ok(())
}
/// Create a new instance
#[inline]
pub fn add_instance(instance: &str) -> Result<()> {
overlayfs::create_new_instance_fs(CIEL_INST_DIR, instance)?;
info!("{}: instance created.", instance);
Ok(())
}
/// Remove the container/instance and its filesystem from the host filesystem
pub fn remove_instance(instance: &str) -> Result<()> {
container_down(instance)?;
info!("{}: removing instance...", instance);
let spinner = create_spinner("Removing the instance...", 200);
let man = &mut *overlayfs::get_overlayfs_manager(instance)?;
man.destroy()?;
spinner.finish_and_clear();
info!("{}: instance removed.", instance);
Ok(())
}
/// Update AOSC OS in the container/instance
pub fn update_os() -> Result<()> {
info!("Updating base OS...");
let instance = format!("update-{:x}", random::<u32>());
add_instance(&instance)?;
let mut status = run_in_container(&instance, &["/bin/bash", "-ec", OMA_UPDATE_SCRIPT])?;
if status != 0 {
status = run_in_container(&instance, &["/bin/bash", "-ec", APT_UPDATE_SCRIPT])?;
if status != 0 {
return Err(anyhow!("Failed to update OS: {}", status));
}
}
commit_container(&instance)?;
remove_instance(&instance)?;
Ok(())
}