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

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

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

use super::spec;

#[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(())
}

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

	spec::generate_spec(task_def.run.as_str())
		.save("build/tmp/runc/config.json")
		.expect("Saving runtime spec failed");

	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(())
}