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
use std::path::PathBuf;
use anyhow::{Context, Result};
use libcontainer::{container::builder::ContainerBuilder, syscall::syscall::create_syscall};
use liboci_cli::Run;
use nix::{
sys::{
signal::{self, kill},
signalfd::SigSet,
wait::{waitpid, WaitPidFlag, WaitStatus},
},
unistd::Pid,
};
use crate::workload::executor::default_executors;
pub fn run(args: Run, root_path: PathBuf, systemd_cgroup: bool) -> Result<i32> {
let syscall = create_syscall();
let mut container = ContainerBuilder::new(args.container_id.clone(), syscall.as_ref())
.with_executor(default_executors())?
.with_pid_file(args.pid_file.as_ref())?
.with_console_socket(args.console_socket.as_ref())
.with_root_path(root_path)?
.with_preserved_fds(args.preserve_fds)
.validate_id()?
.as_init(&args.bundle)
.with_systemd(systemd_cgroup)
.with_detach(args.detach)
.build()?;
container
.start()
.with_context(|| format!("failed to start container {}", args.container_id))?;
if args.detach {
return Ok(0);
}
// Using `debug_assert` here rather than returning an error because this is
// a invariant. The design when the code path arrives to this point, is that
// the container state must have recorded the container init pid.
debug_assert!(
container.pid().is_some(),
"expects a container init pid in the container state"
);
handle_foreground(container.pid().unwrap())
}
// handle_foreground will match the `runc` behavior running the foreground mode.
// The youki main process will wait and reap the container init process. The
// youki main process also forwards most of the signals to the container init
// process.
fn handle_foreground(init_pid: Pid) -> Result<i32> {
// We mask all signals here and forward most of the signals to the container
// init process.
let signal_set = SigSet::all();
signal_set
.thread_set_mask()
.with_context(|| "failed to call pthread_sigmask")?;
loop {
match signal_set
.wait()
.with_context(|| "failed to call sigwait")?
{
signal::SIGCHLD => {
// Reap all child until either container init process exits or
// no more child to be reaped. Once the container init process
// exits we can then return.
loop {
match waitpid(None, Some(WaitPidFlag::WNOHANG))? {
WaitStatus::Exited(pid, status) => {
if pid.eq(&init_pid) {
return Ok(status);
}
// Else, some random child process exited, ignoring...
}
WaitStatus::Signaled(pid, signal, _) => {
if pid.eq(&init_pid) {
return Ok(signal as i32);
}
// Else, some random child process exited, ignoring...
}
WaitStatus::StillAlive => {
// No more child to reap.
break;
}
_ => {}
}
}
}
signal::SIGURG => {
// In `runc`, SIGURG is used by go runtime and should not be forwarded to
// the container process. Here, we just ignore the signal.
}
signal::SIGWINCH => {
// TODO: resize the terminal
}
signal => {
// There is nothing we can do if we fail to forward the signal.
let _ = kill(init_pid, Some(signal));
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use nix::{
sys::{signal::Signal::SIGKILL, wait},
unistd,
};
use super::*;
#[test]
fn test_foreground_forward_sigkill() -> Result<()> {
// To set up the test correctly, we need to run the test in dedicated
// process, so the rust unit test runtime and other unit tests will not
// mess with the signal handling. We use `sigkill` as a simple way to
// make sure the signal is properly forwarded. In this test, P0 is the
// rust process that runs this unit test (in a thread). P1 mocks youki
// main and P2 mocks the container init process
match unsafe { unistd::fork()? } {
unistd::ForkResult::Parent { child } => {
// Inside P0
//
// We need to make sure that the child process has entered into
// the signal forwarding loops. There is no way to 100% sync
// that the child has executed the for loop waiting to forward
// the signal. There are sync mechanisms with condvar or
// channels to make it as close to calling the handle_foreground
// function as possible, but still have a tiny (highly unlikely
// but probable) window that a race can still happen. So instead
// we just wait for 1 second for everything to settle. In
// general, I don't like sleep in tests to avoid race condition,
// but I'd rather not over-engineer this now. We can revisit
// this later if the test becomes flaky.
std::thread::sleep(Duration::from_secs(1));
// Send the `sigkill` signal to P1 who will forward the signal
// to P2. P2 will then exit and send a sigchld to P1. P1 will
// then reap P2 and exits. In P0, we can then reap P1.
kill(child, SIGKILL)?;
wait::waitpid(child, None)?;
}
unistd::ForkResult::Child => {
// Inside P1. Fork P2 as mock container init process and run
// signal handler process inside.
match unsafe { unistd::fork()? } {
unistd::ForkResult::Parent { child } => {
// Inside P1.
handle_foreground(child)?;
}
unistd::ForkResult::Child => {
// Inside P2. This process block and waits the `sigkill`
// from the parent. Use thread::sleep here with a long
// duration to minimic blocking forever.
std::thread::sleep(Duration::from_secs(3600));
}
};
}
};
Ok(())
}
#[test]
fn test_foreground_exit() -> Result<()> {
// The setup is similar to `handle_foreground`, but instead of
// forwarding signal, the container init process will exit. Again, we
// use `sleep` to simulate the conditions to aovid fine grained
// synchronization for now.
match unsafe { unistd::fork()? } {
unistd::ForkResult::Parent { child } => {
// Inside P0
std::thread::sleep(Duration::from_secs(1));
wait::waitpid(child, None)?;
}
unistd::ForkResult::Child => {
// Inside P1. Fork P2 as mock container init process and run
// signal handler process inside.
match unsafe { unistd::fork()? } {
unistd::ForkResult::Parent { child } => {
// Inside P1.
handle_foreground(child)?;
}
unistd::ForkResult::Child => {
// Inside P2. The process exits after 1 second.
std::thread::sleep(Duration::from_secs(1));
}
};
}
};
Ok(())
}
}