summaryrefslogtreecommitdiffstats
path: root/src/runner/runc/run.rs
blob: e7fb393b65fa1102e0245f118f9037cc7b6ea7c5 (plain)
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
use std::{io, process};

use nix::{
	mount::{self, MsFlags},
	sched::{self, CloneFlags},
};
use oci_spec::runtime;
use serde::{Deserialize, Serialize};

use crate::{
	types::*,
	unshare,
	util::{Checkable, ToIOResult},
};

#[derive(Debug, Deserialize, Serialize)]
pub enum Error {
	Code(i32),
	String(String),
}

impl From<io::Error> for Error {
	fn from(error: io::Error) -> Self {
		match error.raw_os_error() {
			Some(code) => Error::Code(code),
			None => Error::String(error.to_string()),
		}
	}
}

impl From<Error> for io::Error {
	fn from(error: Error) -> Self {
		match error {
			Error::Code(code) => io::Error::from_raw_os_error(code),
			Error::String(string) => io::Error::new(io::ErrorKind::Other, string),
		}
	}
}

fn init_task() -> Result<(), Error> {
	sched::unshare(CloneFlags::CLONE_NEWNS).to_io_result()?;

	mount::mount::<_, _, _, str>(
		Some("runc"),
		"build/tmp/runc",
		Some("tmpfs"),
		MsFlags::empty(),
		None,
	)
	.to_io_result()?;

	Ok(())
}

fn configure_spec(path: &str, run: &str) {
	let mut spec = runtime::Spec::load(path).unwrap();

	let process = spec.process.as_mut().unwrap();
	process.terminal = Some(false);
	process.user = runtime::User {
		uid: unshare::BUILD_UID,
		gid: unshare::BUILD_GID,
		additional_gids: None,
		username: None,
	};
	process.args = Some(
		vec!["sh", "-c", run]
			.into_iter()
			.map(str::to_string)
			.collect(),
	);
	process.cwd = "/rebel".to_string();

	let root = spec.root.as_mut().unwrap();
	root.path = "../rootfs".to_string();

	spec.hostname = Some("rebel-builder".to_string());

	spec.save(path).unwrap();
}

pub fn handle_task(task: TaskRef, task_def: Task) -> Result<(), Error> {
	init_task()?;

	process::Command::new("runc")
		.arg("spec")
		.current_dir("build/tmp/runc")
		.status()?
		.check()?;

	configure_spec("build/tmp/runc/config.json", task_def.run.as_str());

	let output = process::Command::new("runc")
		.arg("--root")
		.arg("build/tmp/runc/state")
		.arg("run")
		.arg("rebel")
		.current_dir("build/tmp/runc")
		.output()?;

	if output.status.success() {
		println!(
			"{}:\n{}",
			task,
			String::from_utf8_lossy(output.stdout.as_slice()),
		);
	} else {
		println!(
			"{}:\n{}",
			task,
			String::from_utf8_lossy(output.stderr.as_slice()),
		);
	}

	Ok(())
}