summaryrefslogtreecommitdiffstats
path: root/crates/runner/src/lib.rs
blob: 97d8815df8f93a70b310ef1b6fb6c91858d50e85 (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
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
mod init;
mod jobserver;
mod ns;
pub mod paths;
mod tar;
mod task;
mod util;

use std::{
	fs::File,
	net,
	os::unix::{net::UnixStream, prelude::*},
	slice,
};

use capctl::prctl;
use nix::{
	errno::Errno,
	sched::CloneFlags,
	sys::{signal, signalfd::SignalFd, stat, wait},
	unistd::{self, Gid, Pid, Uid},
};
use uds::UnixSeqpacketConn;

use common::{error::*, types::*};

use self::{
	jobserver::Jobserver,
	util::{clone, unix},
};

#[derive(Debug, Clone)]
pub struct Options {
	pub jobs: Option<usize>,
}

fn handle_request(
	jobserver: Jobserver,
	socket: UnixSeqpacketConn,
	request_socket: UnixStream,
) -> (Jobserver, UnixSeqpacketConn) {
	let child = |(mut jobserver, socket): (Jobserver, UnixSeqpacketConn)| {
		drop(socket);
		unsafe { signal::signal(signal::Signal::SIGCHLD, signal::SigHandler::SigDfl) }.unwrap();

		let task: Task =
			bincode::deserialize_from(&request_socket).expect("Failed to decode task description");

		prctl::set_name(&task.label).expect("prctl(PR_SET_NAME)");

		let token = jobserver.wait();
		let (pid, mut jobserver) = unsafe {
			clone::spawn(None, jobserver, |jobserver| {
				let result = task::handle(task, jobserver);
				bincode::serialize_into(&request_socket, &result)
					.expect("Failed to send task result");
				drop(request_socket);
			})
		}
		.expect("fork()");
		let wait_res = wait::waitpid(pid, None);
		jobserver.post(token);
		wait_res.expect("waitpid()");
	};

	unsafe { clone::spawn(None, (jobserver, socket), child) }
		.expect("fork()")
		.1
}

fn runner_loop(mut socket: UnixSeqpacketConn, options: &Options) {
	let jobs = options
		.jobs
		.unwrap_or_else(|| unix::nproc().expect("Failed to get number of available CPUs"));
	let mut jobserver = Jobserver::new(jobs).expect("Failed to initialize jobserver pipe");

	let mut fd = 0;

	while let Ok((1, _, n_fd)) = socket.recv_fds(&mut [0], slice::from_mut(&mut fd)) {
		assert!(n_fd == 1);

		let request_socket = unsafe { UnixStream::from_raw_fd(fd) };

		let ret = handle_request(jobserver, socket, request_socket);
		jobserver = ret.0;
		socket = ret.1;
	}
}

fn runner(uid: Uid, gid: Gid, socket: UnixSeqpacketConn, _lockfile: File, options: &Options) {
	ns::mount_proc();
	ns::setup_userns(Uid::from_raw(0), Gid::from_raw(0), uid, gid);

	stat::umask(stat::Mode::from_bits_truncate(0o022));

	init::init_runner().unwrap();

	let mut signals = signal::SigSet::empty();
	signals.add(signal::Signal::SIGCHLD);
	signal::pthread_sigmask(signal::SigmaskHow::SIG_BLOCK, Some(&signals), None)
		.expect("pthread_sigmask()");
	let mut sfd = SignalFd::new(&signals).expect("Failed to create signal file descriptor");

	let msg_handler = unsafe {
		clone::spawn(None, (), |()| {
			signal::signal(signal::Signal::SIGCHLD, signal::SigHandler::SigIgn).unwrap();
			runner_loop(socket, options);
		})
	}
	.expect("fork()")
	.0;

	loop {
		let _signal = sfd.read_signal().expect("read_signal()").unwrap();

		loop {
			let status = match wait::waitpid(Pid::from_raw(-1), Some(wait::WaitPidFlag::WNOHANG)) {
				Ok(wait::WaitStatus::StillAlive) | Err(Errno::ECHILD) => break,
				res => res.expect("waitpid()"),
			};
			let pid = status.pid().unwrap();

			if pid == msg_handler {
				return;
			}
		}
	}
}

pub struct Runner {
	socket: UnixSeqpacketConn,
}

impl Runner {
	/// Creates a new container runner
	///
	/// # Safety
	///
	/// Do not call in multithreaded processes.
	pub unsafe fn new(options: &Options) -> Result<Self> {
		let lockfile = unix::lock(paths::LOCKFILE, true, false)
			.context("Failed to get lock on build directory, is another instance running?")?;

		let uid = unistd::geteuid();
		let gid = unistd::getegid();

		let (local, remote) = UnixSeqpacketConn::pair().expect("socketpair()");

		let (local, _remote) = clone::spawn(
			Some(CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_NEWNS | CloneFlags::CLONE_NEWPID),
			(local, remote),
			|(local, remote)| {
				drop(local);
				runner(uid, gid, remote, lockfile, options);
			},
		)
		.expect("clone()")
		.1;

		Ok(Runner { socket: local })
	}

	pub fn spawn(&self, task: &Task) -> UnixStream {
		let (local, remote) = UnixStream::pair().expect("socketpair()");

		self.socket
			.send_fds(&[0], &[remote.as_raw_fd()])
			.expect("send()");

		bincode::serialize_into(&local, task).expect("Task submission failed");
		local.shutdown(net::Shutdown::Write).expect("shutdown()");

		local
	}

	pub fn result(socket: &UnixStream) -> Result<TaskOutput> {
		bincode::deserialize_from(socket).expect("Failed to read task result")
	}
}