Merge commit from fork

A container's start waits until the container's child has made its mounts
and has its own root (#343), so that nothing enters it before then. The
guest agent serves every container from one thread, and it waited there: a
start that fills a new volume from a large image folder held up every other
container's start, exec and output for as long as the fill took.

The agent now waits for the root only briefly (20 ms). Past that the start
is answered as "starting": the agent goes on serving, and lets nothing
enter that container until its child says its root is in place. The daemon
keeps `docker start` waiting for that, and makes exec, copy, pause and
unpause, update and network connect and disconnect for that container wait
too, so each of them still reaches a container that has its own root.

- A start that fails while starting is reported as the start's own error,
  and is cleaned up before anything that waited for it goes on.
- A container removed while a call waited for its start is "No such
  container" for that call.
- A start waits for an earlier start that is still filling a volume the two
  share, so a second container never runs on a half-filled volume. Every
  start has a gate of its own, so two starts cannot wait for each other.
- A start that waited does not run if Kiri began to stop meanwhile; one
  made by the restart policy stays pending, so Start brings it back.
- A container that joined another container's network namespace and is
  still starting is not used for a join, stats, listening ports or a
  network attach.
- A container's child keeps only the descriptors it uses.
- The agent protocol version goes up by one.

tests/start-stall.sh shows the stall on the engine before this change and
checks, during a slow fill: an exec in another container is not held up; an
exec, a copy, a pause, a commit and a network join aimed at the starting
container wait and then act inside it, never in the engine's own root; a
second container on the same volume sees the whole folder; a fill that
fails leaves no half-filled volume behind a restart.
This commit is contained in:
Precious Okwu authored and GitHub committed 2026-11-19 06:39:03 +01:00
1 parent d971596abb
commit 43b2e6034d
11 files changed
+2071 -111

No files matched your search

+386 -43
View File
@@ -10,7 +10,7 @@ use std::path::Path;
use kiri_proto::{Exited, MAX_OUTPUT_CHUNK, Msg, Stats, Stream};
use super::container::{self, NetCtx, Paths, Process};
use super::container::{self, NetCtx, Paths, Process, Root};
use super::net::{self, Bridges, Dhcp};
use super::{fsnotify, layers, meminfo, sys};
@@ -34,10 +34,43 @@ struct Proc {
tty_hup: Option<std::time::Instant>,
}
impl Proc {
/// The one rule for what may be entered (exec, copy): a container's
/// own process, not an exec; its root in place; its setup not failed;
/// not exited. Nothing may enter a container before its root is in
/// place.
fn enterable(&self) -> bool {
self.run.container.is_none() && self.run.entered() && self.exited.is_none()
}
}
/// How long a hung-up terminal waits before it's polled again.
const TTY_HUP_WAIT: std::time::Duration = std::time::Duration::from_millis(100);
pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
pub fn serve(conn: File, paths: &Paths) -> io::Result<()> {
let mut procs: HashMap<libc::pid_t, Proc> = HashMap::new();
let served = serve_loop(conn, paths, &mut procs);
leave(&mut procs, super::transport::is_host_process());
served
}
/// However the agent leaves its loop (Shutdown, SIGTERM, the daemon gone,
/// or an error, such as a write to a daemon that died before its end of
/// stream was read), no child still filling a new volume is killed half
/// way (see `Process::wait_root`): on a Linux host, everything is then
/// stopped and torn down (`run` sweeps what is left after this); in the
/// VM, which powers off next, it is waited for.
fn leave(procs: &mut HashMap<libc::pid_t, Proc>, host_process: bool) {
if host_process {
stop_containers(procs);
} else {
for p in procs.values_mut() {
p.run.wait_root();
}
}
}
fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Proc>) -> io::Result<()> {
let sigfd = child_signals()?;
// In the VM a DHCP lease gives the uplink and DNS; on a Linux host the
// host has them already.
@@ -93,7 +126,9 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
let (usage_tx, usage_rx) = std::sync::mpsc::channel::<Vec<String>>();
let mut measuring = false;
let mut relays: Vec<super::relay::Relay> = Vec::new();
let mut procs: HashMap<libc::pid_t, Proc> = HashMap::new();
// Starts that failed after they were answered `starting`: the error the
// daemon's next `AwaitStart` for that id gets.
let mut failed_starts: HashMap<String, String> = HashMap::new();
let mut fds: Vec<libc::pollfd> = Vec::with_capacity(16);
let mut frame = Vec::with_capacity(4096);
let mut out = Vec::with_capacity(4096);
@@ -102,6 +137,10 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
let mut fs_events = fsnotify::Pending::default();
loop {
// Woken by a starting container's word (its pipe is polled below):
// settled here, so its output is read from then on, or its failed
// start torn down.
settle_roots(procs, &mut dns, &mut failed_starts);
fds.clear();
fds.push(libc::pollfd { fd: conn.as_raw_fd(), events: libc::POLLIN, revents: 0 });
fds.push(libc::pollfd { fd: sigfd.as_raw_fd(), events: libc::POLLIN, revents: 0 });
@@ -132,8 +171,15 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
hung = true;
continue;
}
for fd in [&p.run.stdout, &p.run.stderr].into_iter().flatten() {
fds.push(libc::pollfd { fd: fd.as_raw_fd(), events: libc::POLLIN, revents: 0 });
if let Some(fd) = p.run.starting_fd() {
fds.push(libc::pollfd { fd, events: libc::POLLIN, revents: 0 });
}
// Before its root is in place a child writes nothing there but
// the reason it failed, which the agent keeps for `AwaitStart`.
if p.run.entered() {
for fd in [&p.run.stdout, &p.run.stderr].into_iter().flatten() {
fds.push(libc::pollfd { fd: fd.as_raw_fd(), events: libc::POLLIN, revents: 0 });
}
}
if let (Some(fd), false) = (&p.run.stdin, p.input.is_empty()) {
fds.push(libc::pollfd { fd: fd.as_raw_fd(), events: libc::POLLOUT, revents: 0 });
@@ -192,7 +238,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
continue;
}
if term.as_ref().is_some_and(|t| t.as_raw_fd() == pfd.fd) {
stop_containers(&mut procs);
stop_containers(procs);
return Ok(());
}
if pfd.fd == usage_wake.as_raw_fd() {
@@ -240,8 +286,15 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
continue;
}
if pfd.fd == copies.as_raw_fd() {
let running: Vec<(&str, libc::pid_t)> =
procs.iter().filter(|(_, p)| p.run.container.is_none() && p.exited.is_none()).map(|(pid, p)| (p.run.id.as_str(), *pid)).collect();
// Nothing may enter a container before its root is in
// place: one still making it is copied through its mounted
// root instead, as a stopped one is.
settle_roots(procs, &mut dns, &mut failed_starts);
let running: Vec<(&str, libc::pid_t)> = procs
.iter()
.filter(|(_, p)| p.enterable())
.map(|(pid, p)| (p.run.id.as_str(), *pid))
.collect();
super::copy::accept(&copies, &running, paths);
continue;
}
@@ -277,10 +330,10 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
}
// Only process stdin is polled for writing beyond this point.
if pfd.events & libc::POLLOUT != 0 {
flush_input(&mut procs, pfd.fd, &mut conn, &mut out)?;
flush_input(procs, pfd.fd, &mut conn, &mut out)?;
continue;
}
let Some((pid, stream)) = owner(&procs, pfd.fd) else { continue };
let Some((pid, stream)) = owner(procs, pfd.fd) else { continue };
let p = procs.get_mut(&pid).expect("owner found it");
let slot = if stream == Stream::Stdout { &mut p.run.stdout } else { &mut p.run.stderr };
let fd = slot.as_ref().expect("polled fd is open").as_raw_fd();
@@ -308,7 +361,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
if fds[1].revents != 0 {
drain_signals(&sigfd);
reap(&mut procs);
reap(procs);
}
// Report processes that have exited and whose output is fully read,
@@ -320,7 +373,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
.collect();
for pid in done {
let p = procs.remove(&pid).expect("listed above");
finish(&mut conn, &mut dns, &procs, p, true)?;
finish(&mut conn, &mut dns, procs, p, true)?;
}
if fds[0].revents != 0 {
@@ -328,11 +381,14 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
// The host went away: on a Linux host, the daemon died. Its
// containers do not outlive it (there is no live restore).
if host_process {
stop_containers(&mut procs);
stop_containers(procs);
}
return Ok(());
}
let received_ns = sys::boottime_ns();
// Whatever this request is, it sees where starting containers'
// roots stand now.
settle_roots(procs, &mut dns, &mut failed_starts);
out.clear();
match kiri_proto::decode(&frame) {
Ok(Msg::Ping(v)) => Msg::Pong(v).encode(&mut out),
@@ -340,10 +396,14 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
if host_process {
// The daemon has stopped them Docker's way already;
// what is left is killed and torn down.
stop_containers(&mut procs);
stop_containers(procs);
} else {
for p in procs.values().filter(|p| p.exited.is_none()) {
// SAFETY: signalling a child we started and have not reaped.
for p in procs.values_mut().filter(|p| p.exited.is_none()) {
// Never half-way through filling a volume.
p.run.wait_root();
// SAFETY: signalling a child we started and have
// not reaped (one that ended before its root was
// ready is a zombie until reaped).
unsafe { libc::kill(p.run.pid, libc::SIGKILL) };
}
}
@@ -369,7 +429,10 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
if spec.flags & (kiri_proto::run_flags::NET_NONE | kiri_proto::run_flags::NET_HOST) == 0 {
wait_for_lease(&mut dhcp, std::time::Duration::from_secs(3));
}
let join_pid = kiri_proto::net_opts::values(spec.net.opts, kiri_proto::net_opts::NETNS).next().and_then(|t| running_pid(&procs, t));
// Only its network namespace is joined, which exists from
// clone: a container still filling a volume will do.
let join_pid = kiri_proto::net_opts::values(spec.net.opts, kiri_proto::net_opts::NETNS).next().and_then(|t| netns_pid(procs, t));
failed_starts.remove(spec.id);
container::spawn(
&spec,
paths,
@@ -378,22 +441,26 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
} {
Ok(run) => {
let cloned_ns = sys::boottime_ns();
Msg::Started { id: &run.id, pid: run.pid as u32 }.encode(&mut out);
admit(&mut conn, &mut dns, &mut procs, new_proc(run, received_ns, cloned_ns))?;
Msg::Started { id: &run.id, pid: run.pid as u32, starting: !run.entered() }.encode(&mut out);
admit(&mut conn, &mut dns, procs, new_proc(run, received_ns, cloned_ns))?;
}
Err(e) => Msg::Error(&format!("run {}: {e}", spec.id)).encode(&mut out),
},
Ok(Msg::AwaitStart { id }) => match await_start(procs, &mut failed_starts, id) {
Ok((pid, starting)) => Msg::Started { id, pid, starting }.encode(&mut out),
Err(e) => Msg::Error(&e).encode(&mut out),
},
Ok(Msg::Exec(spec)) => {
// Its namespaces are entered through /proc/<pid>: only a
// container still running, never one exited under a freed pid.
// The container's own seccomp profile goes with it, if it has one.
match running_pid(&procs, spec.container_id).and_then(|pid| procs.get(&pid).map(|p| (pid, p.run.seccomp.clone()))) {
match running_pid(procs, spec.container_id).and_then(|pid| procs.get(&pid).map(|p| (pid, p.run.seccomp.clone()))) {
None => Msg::Error(&format!("container {} is not running", spec.container_id)).encode(&mut out),
Some((pid, profile)) => match container::exec(&spec, pid, paths, &profile) {
Ok(run) => {
let cloned_ns = sys::boottime_ns();
Msg::Started { id: &run.id, pid: run.pid as u32 }.encode(&mut out);
admit(&mut conn, &mut dns, &mut procs, new_proc(run, received_ns, cloned_ns))?;
Msg::Started { id: &run.id, pid: run.pid as u32, starting: false }.encode(&mut out);
admit(&mut conn, &mut dns, procs, new_proc(run, received_ns, cloned_ns))?;
}
Err(e) => Msg::Error(&format!("exec in {}: {e}", spec.container_id)).encode(&mut out),
},
@@ -413,7 +480,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
}
}
if let Some(fd) = target {
flush_input(&mut procs, fd, &mut conn, &mut out)?;
flush_input(procs, fd, &mut conn, &mut out)?;
}
continue;
}
@@ -431,16 +498,22 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
continue;
}
Ok(Msg::Resize { id, rows, cols }) => {
if let Some(fd) = running(&procs, id).filter(|p| p.run.tty).and_then(|p| p.run.stdout.as_ref()) {
if let Some(fd) = running(procs, id).filter(|p| p.run.tty).and_then(|p| p.run.stdout.as_ref()) {
sys::resize_pty(fd.as_raw_fd(), rows, cols);
}
continue;
}
Ok(Msg::Kill { id, signal }) => {
if let Some(p) = running(&procs, id) {
// SAFETY: signalling a child we started and have not
// reaped, so its pid can't belong to another process.
unsafe { libc::kill(p.run.pid, signal as libc::c_int) };
if let Some(p) = procs.values_mut().find(|p| p.run.id == id && p.exited.is_none()) {
// A child still filling a new volume finishes first
// (see `Process::wait_root`); one that ended before
// its root was ready has failed its start, and is
// torn down by `settle_roots`, not signalled.
if p.run.wait_root() != Root::Ended {
// SAFETY: signalling a child we started and have not
// reaped, so its pid can't belong to another process.
unsafe { libc::kill(p.run.pid, signal as libc::c_int) };
}
}
continue; // no reply: the exit, if any, is reported as Exited
}
@@ -531,28 +604,28 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
}
continue;
}
Ok(Msg::Update { id, limits }) => match running_pid(&procs, id) {
Ok(Msg::Update { id, limits }) => match live_pid(procs, id) {
Some(_) => match super::cgroup::apply_limits(&paths.cgroup.join(id), &limits) {
Ok(()) => Msg::Ack.encode(&mut out),
Err(e) => Msg::Error(&format!("update: {e}")).encode(&mut out),
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::Freeze { id, frozen }) => match running_pid(&procs, id) {
Some(_) => match super::cgroup::freeze(&paths.cgroup.join(id), frozen) {
Ok(Msg::Freeze { id, frozen }) => match freeze_target(procs, id, frozen) {
Ok(_) => match super::cgroup::freeze(&paths.cgroup.join(id), frozen) {
Ok(()) => Msg::Ack.encode(&mut out),
Err(e) => Msg::Error(&format!("freeze: {e}")).encode(&mut out),
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
Err(e) => Msg::Error(&e).encode(&mut out),
},
Ok(Msg::StatsQuery { id }) => match running_pid(&procs, id) {
Ok(Msg::StatsQuery { id }) => match netns_pid(procs, id) {
Some(pid) => match super::cgroup::stats(&paths.cgroup.join(id), pid) {
Ok(s) => Msg::ContainerStats(s).encode(&mut out),
Err(e) => Msg::Error(&format!("stats: {e}")).encode(&mut out),
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::TopQuery { id }) => match running_pid(&procs, id) {
Ok(Msg::TopQuery { id }) => match live_pid(procs, id) {
Some(_) => {
let lines = super::cgroup::top(&paths.cgroup.join(id));
kiri_proto::encode_top(&mut out, &lines);
@@ -560,11 +633,11 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::UsbNodesQuery) => kiri_proto::encode_usb_nodes(&mut out, &super::usb::nodes()),
Ok(Msg::ListenQuery { id }) => match running_pid(&procs, id) {
Ok(Msg::ListenQuery { id }) => match netns_pid(procs, id) {
Some(pid) => kiri_proto::encode_listening(&mut out, &net::listening(pid)),
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::NetAttach { id, ifname, net: n }) => match running_pid(&procs, id) {
Ok(Msg::NetAttach { id, ifname, net: n }) => match netns_pid(procs, id) {
Some(pid) => {
let num: u32 = ifname.strip_prefix("eth").and_then(|v| v.parse().ok()).unwrap_or(1);
let host_if = extra_veth(id, num);
@@ -604,7 +677,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
Ok(()) => Msg::Ack.encode(&mut out),
Err(e) => Msg::Error(&format!("route: {e}")).encode(&mut out),
},
Ok(Msg::NetDetach { id, ifname, bridge, ip }) => match running_pid(&procs, id) {
Ok(Msg::NetDetach { id, ifname, bridge, ip }) => match netns_pid(procs, id) {
Some(pid) => {
let num: u32 = ifname.strip_prefix("eth").and_then(|v| v.parse().ok()).unwrap_or(1);
dns.unregister(bridge, ip);
@@ -621,7 +694,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
}
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::FsStatRequest { id, path }) => match running_rootfs(&procs, paths, id) {
Ok(Msg::FsStatRequest { id, path }) => match running_rootfs(procs, paths, id) {
Some(root) => match super::fsview::stat(&root, path) {
Ok(meta) => {
let name = path.rsplit('/').next().unwrap_or("");
@@ -631,7 +704,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::FsListRequest { id, path }) => match running_rootfs(&procs, paths, id) {
Ok(Msg::FsListRequest { id, path }) => match running_rootfs(procs, paths, id) {
Some(root) => match super::fsview::list(&root, path) {
Ok(list) => {
let entries: Vec<_> = list.iter().map(|(n, m)| super::fsview::entry(n, *m)).collect();
@@ -641,7 +714,7 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::FsRead { id, path, offset, len }) => match running_rootfs(&procs, paths, id) {
Ok(Msg::FsRead { id, path, offset, len }) => match running_rootfs(procs, paths, id) {
Some(root) => match super::fsview::read(&root, path, offset, len as usize, &mut fs_buf) {
Ok(()) => Msg::FsData(&fs_buf).encode(&mut out),
Err(e) => Msg::Error(&format!("read {path}: {e}")).encode(&mut out),
@@ -685,11 +758,103 @@ fn memory_pressure_trigger() -> Option<std::fs::File> {
Some(f)
}
/// A running container's init (not an exec).
/// A running container's init that may be entered (see `Proc::enterable`):
/// one still filling a new volume reads as not running.
fn running_pid(procs: &HashMap<libc::pid_t, Proc>, id: &str) -> Option<libc::pid_t> {
procs.iter().find(|(_, p)| p.run.id == id && p.enterable()).map(|(pid, _)| *pid)
}
/// A running container's init (not an exec), its root in place or not: for
/// what only touches its cgroup or network namespace.
fn live_pid(procs: &HashMap<libc::pid_t, Proc>, id: &str) -> Option<libc::pid_t> {
procs.iter().find(|(_, p)| p.run.container.is_none() && p.run.id == id && p.exited.is_none()).map(|(pid, _)| *pid)
}
/// The init of a container whose network namespace may be joined: one
/// still filling a volume will do, since its own namespace exists from the
/// clone. Not one that itself joined another's (`--network container:`)
/// and is not yet entered: its child has perhaps not joined it, and
/// `/proc/<pid>/ns/net` could still be the host's. Answered as for a
/// container that is not running.
fn netns_pid(procs: &HashMap<libc::pid_t, Proc>, id: &str) -> Option<libc::pid_t> {
procs.iter().find(|(_, p)| p.run.container.is_none() && p.run.id == id && p.exited.is_none() && (!p.run.joins_netns || p.enterable())).map(|(pid, _)| *pid)
}
/// The container a `Freeze` may act on. A child still filling a new volume
/// is never frozen: the daemon's start waits (`AwaitStart`) for it to say
/// its root is in place, which a frozen child never does, and a `docker
/// commit` that paused it would then wait for that start forever. The
/// daemon waits for the start before it pauses; this is the second line.
/// Thawing touches nothing the child does, so it needs only a live one.
fn freeze_target(procs: &HashMap<libc::pid_t, Proc>, id: &str, frozen: bool) -> Result<libc::pid_t, String> {
match (live_pid(procs, id), running_pid(procs, id)) {
(None, _) => Err(format!("container {id} is not running")),
(Some(pid), _) if !frozen => Ok(pid),
(Some(_), Some(pid)) => Ok(pid),
(Some(_), None) => Err(format!("container {id} is still starting")),
}
}
/// Looks again, without waiting, at the roots of containers that started
/// before theirs was in place (see `Process::root`).
fn settle_roots(procs: &mut HashMap<libc::pid_t, Proc>, dns: &mut super::dns::Dns, failed: &mut HashMap<String, String>) {
let mut ended = Vec::new();
for (pid, p) in procs.iter_mut().filter(|(_, p)| !p.run.entered()) {
if p.run.root() == Root::Ended {
ended.push(*pid);
}
}
for pid in ended {
let p = procs.remove(&pid).expect("listed above");
let why = format!("run {}: {}", p.run.id, p.run.start_failure().unwrap_or_default());
failed.insert(p.run.id.clone(), why);
drop_failed_start(dns, procs, p);
}
}
/// Tears down a container whose child ended before its root was in place,
/// as `spawn` does for a start that fails within its wait: no `Exited`,
/// since the start itself failed (the daemon hears it from `AwaitStart`),
/// and its output, only the failure message, is not forwarded.
fn drop_failed_start(dns: &mut super::dns::Dns, procs: &HashMap<libc::pid_t, Proc>, p: Proc) {
if p.exited.is_none() {
// Its pipe closed because it exited (it never execs before its
// root is ready), and it isn't reaped yet: the pid is still ours.
// SAFETY: reaping our own unreaped child.
unsafe { libc::waitpid(p.run.pid, std::ptr::null_mut(), 0) };
}
for (bridge, ip) in &p.run.dns_entries {
dns.unregister(bridge, *ip);
}
dns.drop_container(p.run.pid);
let shared = p.run.netns != 0 && procs.values().any(|o| o.exited.is_none() && o.run.netns == p.run.netns);
container::teardown(&p.run, shared);
}
/// `AwaitStart`: the container's pid, and whether its root is still being
/// made; an error once it is not running, or ended before its root was in
/// place (its exit is reported as usual).
fn await_start(procs: &mut HashMap<libc::pid_t, Proc>, failed: &mut HashMap<String, String>, id: &str) -> Result<(u32, bool), String> {
if let Some(why) = failed.remove(id) {
return Err(why);
}
// The run still starting, before an earlier run of the same id whose
// exit is still being reported.
let mine = |p: &Proc| p.run.container.is_none() && p.run.id == id;
let pid = procs.iter().find(|(_, p)| mine(p) && !p.run.entered()).or_else(|| procs.iter().find(|(_, p)| mine(p))).map(|(pid, _)| *pid);
let Some((pid, p)) = pid.and_then(|pid| procs.get_mut(&pid).map(|p| (pid, p))) else {
// Its root was in place and it has exited since, its exit reported
// as usual: the start itself succeeded.
return Ok((0, false));
};
match p.run.root() {
Root::Ready => Ok((pid as u32, false)),
// Ended: the next `settle_roots` tears it down, and the next ask
// gets its reason.
Root::Starting | Root::Ended => Ok((pid as u32, true)),
}
}
/// The host side of a container's `eth{n}` for n > 0: 15 characters at most.
fn extra_veth(id: &str, n: u32) -> String {
format!("kx{}{n}", &id[..id.len().min(9)])
@@ -819,7 +984,9 @@ fn child_signals() -> io::Result<OwnedFd> {
/// writable layer of a `--rm` one. Veths go with their network namespaces.
fn stop_containers(procs: &mut HashMap<libc::pid_t, Proc>) {
super::copy::stop_all();
for p in procs.values().filter(|p| p.exited.is_none()) {
for p in procs.values_mut().filter(|p| p.exited.is_none()) {
// Never half-way through filling a volume (see `Process::wait_root`).
p.run.wait_root();
// SAFETY: signalling a child we started and have not reaped.
unsafe { libc::kill(p.run.pid, libc::SIGKILL) };
}
@@ -983,7 +1150,7 @@ fn reap(procs: &mut HashMap<libc::pid_t, Proc>) {
#[cfg(test)]
mod running_tests {
use super::{Process, new_proc, running, running_pid};
use super::{Process, await_start, live_pid, netns_pid, new_proc, running, running_pid, settle_roots};
use std::collections::HashMap;
#[test]
@@ -1005,6 +1172,112 @@ mod running_tests {
}
}
#[test]
fn a_container_still_making_its_root_cannot_be_entered() {
use std::io::Write;
let (r, mut w) = pipe();
let mut procs = HashMap::new();
let mut dns = super::super::dns::Dns::default();
let mut failed = HashMap::new();
procs.insert(300, new_proc(Process::starting_for_test("c1", 300, r.into(), None), 0, 0));
// Exec (and copy) see it as not running; signals, stats and its
// network still find it.
assert_eq!(running_pid(&procs, "c1"), None, "no exec while its root is not in place");
assert_eq!(live_pid(&procs, "c1"), Some(300), "its network can be joined");
assert_eq!(netns_pid(&procs, "c1"), Some(300), "it owns its namespace, which exists from the clone");
assert_eq!(running(&procs, "c1").map(|p| p.run.pid), Some(300), "kill still reaches it");
assert_eq!(await_start(&mut procs, &mut failed, "c1"), Ok((300, true)));
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(running_pid(&procs, "c1"), None);
// The child's byte: in place now.
w.write_all(b"r").unwrap();
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(running_pid(&procs, "c1"), Some(300));
assert_eq!(await_start(&mut procs, &mut failed, "c1"), Ok((300, false)));
// Gone since, its exit reported as usual: the start succeeded.
assert_eq!(await_start(&mut procs, &mut failed, "nope"), Ok((0, false)));
// Restarted while the first run's exit is still being reported: the
// ask is about the run still starting.
let mut old = new_proc(Process::for_test("c3", 400), 0, 0);
old.exited = Some((0, 0));
procs.insert(400, old);
let (r, _w) = pipe();
procs.insert(401, new_proc(Process::starting_for_test("c3", 401, r.into(), None), 0, 0));
assert_eq!(await_start(&mut procs, &mut failed, "c3"), Ok((401, true)));
}
#[test]
fn a_container_still_joining_a_network_cannot_be_joined_itself() {
use std::io::Write;
let (r, mut w) = pipe();
let mut procs = HashMap::new();
let mut dns = super::super::dns::Dns::default();
let mut failed = HashMap::new();
let mut p = Process::starting_for_test("c1", 300, r.into(), None);
p.joins_netns = true;
procs.insert(300, new_proc(p, 0, 0));
assert_eq!(live_pid(&procs, "c1"), Some(300));
assert_eq!(netns_pid(&procs, "c1"), None, "its child may not have joined yet: as if not running");
w.write_all(b"r").unwrap();
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(netns_pid(&procs, "c1"), Some(300), "entered: its namespace is the one joined");
}
#[test]
fn a_start_that_fails_while_starting_is_an_error_not_an_exit() {
use std::io::Write;
let (r, w) = pipe();
let r_fd = std::os::fd::AsRawFd::as_raw_fd(&r);
let (err_r, mut err_w) = pipe();
let mut procs = HashMap::new();
let mut dns = super::super::dns::Dns::default();
let mut failed = HashMap::new();
let mut p = new_proc(Process::starting_for_test("c2", 301, r.into(), Some(err_r.into())), 0, 0);
// Already reaped, so the teardown does not wait for pid 301.
p.exited = Some((127, 0));
procs.insert(301, p);
err_w.write_all(b"kiri: cannot start container: mount /payload: No space left on device (os error 28)\n").unwrap();
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(await_start(&mut procs, &mut failed, "c2"), Ok((301, true)), "still starting until the pipe closes");
drop(w);
wait_all_writers_gone(r_fd);
settle_roots(&mut procs, &mut dns, &mut failed);
assert!(procs.is_empty(), "torn down, never left for the exit path (no Exited)");
assert_eq!(running_pid(&procs, "c2"), None);
assert_eq!(
await_start(&mut procs, &mut failed, "c2"),
Err("run c2: mount /payload: No space left on device (os error 28)".into()),
"the start fails with the child's own reason"
);
assert!(failed.is_empty(), "answered once");
}
/// Waits, for at most 5 seconds, until no writer of the pipe is left:
/// `poll` reports POLLHUP on the read end then, whatever the events
/// asked for. Tests run as threads of one process, and a child another
/// test forks holds a copy of every open descriptor until it execs or
/// exits, so a write end dropped here is not yet closed for the reader.
/// The real agent is single-threaded, so this cannot happen there.
fn wait_all_writers_gone(read_end: std::os::fd::RawFd) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let left = deadline.saturating_duration_since(std::time::Instant::now());
let mut pfd = libc::pollfd { fd: read_end, events: 0, revents: 0 };
// SAFETY: one valid pollfd.
let n = unsafe { libc::poll(&mut pfd, 1, left.as_millis().min(i32::MAX as u128) as i32) };
if n > 0 && pfd.revents & libc::POLLHUP != 0 {
return;
}
if n < 0 {
assert_eq!(std::io::Error::last_os_error().kind(), std::io::ErrorKind::Interrupted, "poll failed");
}
assert!(
std::time::Instant::now() < deadline,
"the write end is still held somewhere 5 s after it was dropped"
);
}
}
fn pipe() -> (std::fs::File, std::fs::File) {
use std::os::fd::FromRawFd;
let mut fds = [0; 2];
@@ -1128,6 +1401,76 @@ mod running_tests {
assert!(exited, "the old one's exit goes out");
assert!(output > 0 && output <= super::LAST_OUTPUT_MAX, "its buffered output goes out, up to the limit: {output}");
}
#[test]
fn a_container_still_making_its_root_is_never_frozen() {
use std::io::Write;
let (r, mut w) = pipe();
let mut procs = HashMap::new();
let mut dns = super::super::dns::Dns::default();
let mut failed = HashMap::new();
procs.insert(300, new_proc(Process::starting_for_test("c1", 300, r.into(), None), 0, 0));
// Frozen while filling its volume, it never says its root is in
// place, and the daemon's start (and a commit that paused it) would
// wait for that forever.
assert_eq!(super::freeze_target(&procs, "c1", true), Err("container c1 is still starting".into()));
assert_eq!(super::freeze_target(&procs, "c1", false), Ok(300), "thawing is harmless");
assert_eq!(super::freeze_target(&procs, "nope", true), Err("container nope is not running".into()));
w.write_all(b"r").unwrap();
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(super::freeze_target(&procs, "c1", true), Ok(300), "its root in place: frozen as usual");
}
/// The container files view (`FsStat`, `FsList`, `FsRead`) reads through
/// the container's own root. A container still making its root has not
/// pivoted: /proc/<pid>/root is the agent's own root then, so it is
/// read through the overlay the agent mounted for it, as a stopped one
/// is, until its root is in place.
#[test]
fn the_files_view_never_reads_through_a_container_still_making_its_root() {
use std::io::Write;
let (r, mut w) = pipe();
let mut procs = HashMap::new();
let mut dns = super::super::dns::Dns::default();
let mut failed = HashMap::new();
let paths = super::Paths { layers: "/l".into(), containers: "/c".into(), cgroup: "/g".into() };
procs.insert(300, new_proc(Process::starting_for_test("c1", 300, r.into(), None), 0, 0));
assert_eq!(super::running_rootfs(&procs, &paths, "c1"), Some("/c/c1/rootfs".into()), "not /proc/300/root, which is the agent's own root");
assert_eq!(super::running_rootfs(&procs, &paths, "nope"), None);
w.write_all(b"r").unwrap();
settle_roots(&mut procs, &mut dns, &mut failed);
assert_eq!(super::running_rootfs(&procs, &paths, "c1"), Some("/proc/300/root".into()), "its root in place: its own view, with its volumes");
}
/// The agent leaving on a Linux host, by error as much as by Shutdown,
/// waits for a child still filling a new volume before it kills it.
#[test]
fn leaving_waits_for_a_child_still_making_its_root() {
use std::os::fd::AsRawFd;
// A real child, so the kill and the reap are real.
let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap();
let pid = child.id() as libc::pid_t;
let (r, w) = pipe();
let mut procs = HashMap::new();
procs.insert(pid, new_proc(Process::starting_for_test("c1", pid, r.into(), None), 0, 0));
let speaker = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(150));
// SAFETY: signal 0 only asks whether the process exists.
let alive = unsafe { libc::kill(pid, 0) } == 0;
// SAFETY: one byte to a pipe we own.
unsafe { libc::write(w.as_raw_fd(), b"r".as_ptr().cast(), 1) };
alive
});
let t = std::time::Instant::now();
super::leave(&mut procs, true);
let waited = t.elapsed();
assert!(speaker.join().unwrap(), "not killed while it was still making its root");
assert!(waited >= std::time::Duration::from_millis(140), "left after {waited:?}, before the child spoke");
assert!(procs.is_empty(), "stopped and torn down");
// SAFETY: signal 0 only asks whether the process exists.
assert_ne!(unsafe { libc::kill(pid, 0) }, 0, "killed and reaped once its root was in place");
let _ = child.try_wait();
}
}
#[cfg(test)]
+414 -17
View File
@@ -84,13 +84,97 @@ pub struct Process {
/// the host's and for execs. Says whether a namespace outlives this
/// container (see `teardown`).
pub netns: u64,
/// It joined another container's network namespace (`--network
/// container:`): its child does that after the clone, so until its root
/// is in place its own `/proc/<pid>/ns/net` may still be the host's.
pub joins_netns: bool,
/// A container's own compiled seccomp program, empty when it runs under
/// the default. Its execs run under the same one.
pub seccomp: Vec<u8>,
/// What to undo when a container exits; None for execs.
teardown: Option<Teardown>,
/// A container whose root was not in place when `spawn` returned: the
/// read end of its child's "root ready" pipe, until `root` sees the
/// byte (or the end). None for every other process.
starting: Option<OwnedFd>,
/// Its child ended before its root was in place: the reason it gave
/// (see `child_report`). The start failed; the agent answers the
/// daemon's `AwaitStart` with it and tears the container down, with no
/// `Exited`, as a start that fails within `ROOT_READY_WAIT` is.
ended_before_ready: Option<String>,
}
/// Where a container's root stands (see [`Process::root`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Root {
/// Mounts made and `pivot_root` done: an exec or copy may enter it.
Ready,
/// Still being made (a new volume is being filled from the image).
Starting,
/// The child ended before its root was in place.
Ended,
}
impl Process {
/// Settles where its root stands, without waiting: the child's byte
/// means ready, the pipe's end means it ended first, nothing yet means
/// still starting.
pub fn root(&mut self) -> Root {
self.settle(Some(std::time::Duration::ZERO))
}
/// Waits, as long as it takes, for the child to say its root is in
/// place or to end. Called before the agent kills a container: a child
/// still filling a new volume must finish first, or the volume is left
/// half full and, no longer empty, is never filled again.
pub fn wait_root(&mut self) -> Root {
self.settle(None)
}
fn settle(&mut self, wait: Option<std::time::Duration>) -> Root {
if self.ended_before_ready.is_some() {
return Root::Ended;
}
let Some(fd) = &self.starting else { return Root::Ready };
match root_word(fd.as_raw_fd(), wait) {
Ok(RootWord::NotYet) => Root::Starting,
Ok(RootWord::Ready) => {
self.starting = None;
Root::Ready
}
Ok(RootWord::Ended) | Err(_) => {
self.starting = None;
// Written before it exited, and not forwarded while it was
// starting: still in the pipe.
let why = self.stderr.as_ref().and_then(|f| child_report(f.as_raw_fd()));
self.ended_before_ready = Some(why.unwrap_or_else(|| NOT_READY.to_owned()));
Root::Ended
}
}
}
/// Whether its root was in place when last settled (see `root`).
/// Nothing may enter a container before its root is in place, and its
/// output is not read until then (only a failure message can be there).
pub fn entered(&self) -> bool {
self.starting.is_none() && self.ended_before_ready.is_none()
}
/// The pipe the child says "root ready" on, while it is still starting:
/// the agent polls it, so it settles as soon as the child speaks.
pub fn starting_fd(&self) -> Option<RawFd> {
self.starting.as_ref().map(AsRawFd::as_raw_fd)
}
/// Why its start failed, once settled as `Root::Ended`.
pub fn start_failure(&self) -> Option<&str> {
self.ended_before_ready.as_deref()
}
}
/// A child that ended before its root was in place and said nothing.
const NOT_READY: &str = "the container exited before its root was ready";
/// What a started container gives the DNS server (see `spawn`).
struct Names {
/// Its A records: not on an IPv6-only network.
@@ -115,10 +199,19 @@ impl Process {
dns_entries: Vec::new(),
veths: Vec::new(),
netns: 0,
joins_netns: false,
seccomp: Vec::new(),
teardown: None,
starting: None,
ended_before_ready: None,
}
}
/// The same, still waiting for its root on `ready` (see `root`), with
/// the read end of its stderr if given.
pub fn starting_for_test(id: &str, pid: libc::pid_t, ready: OwnedFd, stderr: Option<OwnedFd>) -> Self {
Process { starting: Some(ready), stderr, ..Process::for_test(id, pid) }
}
}
#[derive(Debug)]
@@ -197,6 +290,67 @@ enum ParentStdio {
Pipes { stdin: Option<OwnedFd>, stdout: OwnedFd, stderr: OwnedFd },
}
/// How long a start waits for the child to say its root is in place before
/// it goes on without it. The usual child is ready within a few
/// milliseconds, so a normal start waits for it exactly as before. One that
/// first fills a new volume from a big image folder can take seconds, and
/// the agent serves every other container's exec, output, DNS and ports
/// from this same thread: waiting longer would hold all of them up. Past
/// this, the start is answered `starting` and the daemon asks again.
const ROOT_READY_WAIT: std::time::Duration = std::time::Duration::from_millis(20);
/// What the child's "root ready" pipe says.
#[derive(Debug, PartialEq, Eq)]
enum RootWord {
Ready,
/// Closed without the byte: the child ended first.
Ended,
NotYet,
}
/// Reads the child's word on its root, waiting at most `wait` (None: as long
/// as it takes).
fn root_word(fd: RawFd, wait: Option<std::time::Duration>) -> io::Result<RootWord> {
let deadline = wait.map(|w| std::time::Instant::now() + w);
loop {
let timeout = deadline.map_or(-1, |d| {
// Rounded up: poll counts whole milliseconds.
d.saturating_duration_since(std::time::Instant::now()).as_micros().div_ceil(1000).min(i32::MAX as u128) as i32
});
let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 };
// SAFETY: one valid pollfd.
let n = unsafe { libc::poll(&mut pfd, 1, timeout) };
if n == 0 {
return Ok(RootWord::NotYet);
}
if n > 0 {
break;
}
let e = io::Error::last_os_error();
if e.kind() != io::ErrorKind::Interrupted {
return Err(e);
}
}
let mut ready = [0u8; 1];
loop {
// SAFETY: reading one byte into a local buffer from a pipe that has
// data or is closed, so this does not wait.
let n = unsafe { libc::read(fd, ready.as_mut_ptr().cast(), 1) };
match n {
1 => return Ok(RootWord::Ready),
0 => return Ok(RootWord::Ended),
_ => {
let e = io::Error::last_os_error();
match e.kind() {
io::ErrorKind::Interrupted => continue,
io::ErrorKind::WouldBlock => return Ok(RootWord::NotYet),
_ => return Err(e),
}
}
}
}
}
/// What the child said before it ended, if it could not start (see
/// `sys::child_fail`): read from where it reports, without waiting.
fn child_report(fd: RawFd) -> Option<String> {
@@ -381,9 +535,17 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
ParentStdio::Tty { sock } => sock.as_raw_fd(),
ParentStdio::Pipes { stderr, .. } => stderr.as_raw_fd(),
};
// Set once the start goes on without the child's root (see below).
let starting = std::cell::Cell::new(false);
// The child never becomes a Process, so nothing else tears it down:
// its root goes back here, with its cgroup and runtime files.
let kill_child = |e: io::Error| {
// A child still filling a new volume finishes first, as it did when
// the start always waited for it: killed half-way, the volume would
// stay half full and, no longer empty, never be filled again.
if starting.get() {
let _ = root_word(root_ready.as_raw_fd(), None);
}
let own = child_report(report);
// SAFETY: killing the child we just cloned.
unsafe { libc::kill(pid, libc::SIGKILL) };
@@ -397,23 +559,27 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
None => e,
}
};
// Do not report the start until the child's root is in place: before
// `pivot_root`, an exec joining its mount namespace gets the agent's
// `/etc/passwd`, and an image user such as `dev` is unknown (#311).
let mut ready = [0u8; 1];
let got = loop {
// SAFETY: reading one byte into a local buffer from a pipe we own.
let n = unsafe { libc::read(root_ready.as_raw_fd(), ready.as_mut_ptr().cast(), 1) };
if n >= 0 {
break n;
}
let e = io::Error::last_os_error();
if e.kind() != io::ErrorKind::Interrupted {
return Err(kill_child(e));
}
};
if got != 1 {
return Err(kill_child(io::Error::other("the container exited before its root was ready")));
// Before `pivot_root`, an exec joining its mount namespace gets the
// agent's `/etc/passwd`, and an image user such as `dev` is unknown
// (#311). So the start waits for the root, briefly (ROOT_READY_WAIT):
// past that the child is filling a new volume, and the start goes on
// without it, answered `starting`; the agent lets nothing enter it until
// `Process::root` says it is in place, and the daemon waits for that
// with `AwaitStart`. Nothing below needs the child's root: the network,
// DNS and sysctls go through its namespaces (/proc/<pid>/ns).
// A start with a terminal (`-t`) is the exception: its master comes from
// the child only once its root and network are in place
// (`finish_stdio` waits for it), so it waits for the root as before.
match root_word(root_ready.as_raw_fd(), Some(ROOT_READY_WAIT)) {
Ok(RootWord::Ready) => {}
Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))),
Ok(RootWord::NotYet) if prepared.tty => match root_word(root_ready.as_raw_fd(), None) {
Ok(RootWord::Ready) => {}
Ok(_) => return Err(kill_child(io::Error::other(NOT_READY))),
Err(e) => return Err(kill_child(e)),
},
Ok(RootWord::NotYet) => starting.set(true),
Err(e) => return Err(kill_child(e)),
}
let mut veths = Vec::new();
// Names, AAAA records and `--dns` servers to give the DNS server, once
@@ -498,8 +664,11 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
dns_entries: (bridged && embedded_dns).then(|| (spec.net.bridge.to_owned(), spec.net.ip)).into_iter().collect(),
veths,
netns,
joins_netns: net_opts::values(spec.net.opts, net_opts::NETNS).next().is_some(),
seccomp: spec.seccomp.to_vec(),
teardown: Some(Teardown { base, cgroup, remove }),
starting: starting.get().then_some(root_ready),
ended_before_ready: None,
})
}
@@ -657,8 +826,11 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
dns_entries: Vec::new(),
veths: Vec::new(),
netns: 0,
joins_netns: false,
seccomp: Vec::new(),
teardown: None,
starting: None,
ended_before_ready: None,
})
}
@@ -1274,9 +1446,66 @@ fn report_fd(io: &ChildStdio) -> RawFd {
}
}
/// The descriptors a container's child, right after its clone, still uses
/// of those it inherited: its standard streams (or terminal socket), which
/// are also where it reports a failure; the network namespace it joins;
/// the pipes it says "root ready" on and waits for its network on. Every
/// other descriptor it uses it opens itself, later (its root, the image's
/// tree, its terminal). Standard input, output and error (0, 1, 2) always
/// stay. Every field of `Prepared` is named, so a descriptor added to it
/// is not closed by mistake: the compiler asks about it here.
fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec<RawFd> {
let Prepared {
argv: _,
envp: _,
path_dirs: _,
hostname: _,
domainname: _,
net_join,
etc_files: _,
mounts: _,
net_ready,
cwd: _,
user: _,
net_none: _,
tty: _,
stdin: _,
privileged: _,
caps: _,
seccomp: _,
profile: _,
no_new_privs: _,
readonly_rootfs: _,
shm_size: _,
init: _,
// Paths, numbers and names only.
host: HostApplied { rlimits: _, groups: _, nodes: _ },
root_ready,
} = p;
let mut fds = match io {
ChildStdio::Tty { sock } => vec![sock.as_raw_fd()],
ChildStdio::Pipes { stdin, stdout, stderr } => {
let mut v = vec![stdout.as_raw_fd(), stderr.as_raw_fd()];
v.extend(stdin.as_ref().map(AsRawFd::as_raw_fd));
v
}
};
fds.extend(net_join.as_ref().map(AsRawFd::as_raw_fd));
fds.extend(net_ready.as_ref().map(AsRawFd::as_raw_fd));
fds.extend(root_ready.as_ref().map(AsRawFd::as_raw_fd));
fds
}
/// Runs in the cloned child: PID 1 of the container, in its own namespaces
/// and cgroup. Never returns: it execs or exits 127 with a message.
fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio) -> ! {
// First of all: the clone gave this child a copy of every descriptor
// the agent had open, and filling a new volume can take seconds while
// the agent goes on. Held here, a network's DNS socket keeps its
// address bound after the network is removed (created again, it cannot
// bind it), and other containers' stdin and relayed connections never
// see their end. Only what this child uses is kept.
sys::close_now(&sys::close_ranges(&child_fds(p, io)));
let err = report_fd(io);
let fail = |what: &str, e: io::Error| -> ! { child_fail(err, what, e) };
@@ -1798,6 +2027,174 @@ fn find_executable(p: &Prepared) -> Option<CString> {
#[cfg(test)]
mod tests {
/// Waits, for at most 5 seconds, until no writer of the pipe is left:
/// `poll` reports POLLHUP on the read end then, whatever the events
/// asked for. Tests run as threads of one process, and a child another
/// test forks holds a copy of every open descriptor until it execs or
/// exits, so a write end dropped here is not yet closed for the reader.
/// The real agent is single-threaded, so this cannot happen there.
fn wait_all_writers_gone(read_end: std::os::fd::RawFd) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let left = deadline.saturating_duration_since(std::time::Instant::now());
let mut pfd = libc::pollfd { fd: read_end, events: 0, revents: 0 };
// SAFETY: one valid pollfd.
let n = unsafe { libc::poll(&mut pfd, 1, left.as_millis().min(i32::MAX as u128) as i32) };
if n > 0 && pfd.revents & libc::POLLHUP != 0 {
return;
}
if n < 0 {
assert_eq!(std::io::Error::last_os_error().kind(), std::io::ErrorKind::Interrupted, "poll failed");
}
assert!(
std::time::Instant::now() < deadline,
"the write end is still held somewhere 5 s after it was dropped"
);
}
}
/// A container's child closes every inherited descriptor but these
/// (see `child_fds`): each one it uses must be among them, for a plain
/// start with stdin, one with a terminal, one that joins another
/// container's network and one whose network and sysctls it waits for.
#[test]
fn a_container_child_keeps_every_descriptor_it_uses() {
use super::{ChildStdio, child_fds, sys};
use std::os::fd::{AsRawFd, RawFd};
let mut buf = Vec::new();
let net = Net { bridge: "kiri1", ip: [10, 5, 0, 2], prefix: 24, gateway: [10, 5, 0, 1], extra_hosts: &[], dns_names: &[], opts: &[] };
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", run_flags::INIT, net, &[], &Limits::default(), 0, &[] as &[&str], &[]);
let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
let mut p = super::prepare(spec.argv, spec.env, spec.cwd, spec.user, Some(spec.hostname), spec.flags, spec.caps).unwrap();
let sorted = |mut v: Vec<RawFd>| {
v.sort_unstable();
v
};
// Nothing of its own yet: only its streams.
let (r0, w0) = sys::pipe().unwrap();
let (r1, w1) = sys::pipe().unwrap();
let (r2, w2) = sys::pipe().unwrap();
let pipes = ChildStdio::Pipes { stdin: Some(r0), stdout: w1, stderr: w2 };
let streams = |io: &ChildStdio| match io {
ChildStdio::Pipes { stdin, stdout, stderr } => {
let mut v = vec![stdout.as_raw_fd(), stderr.as_raw_fd()];
v.extend(stdin.as_ref().map(|f| f.as_raw_fd()));
v
}
ChildStdio::Tty { sock } => vec![sock.as_raw_fd()],
};
assert_eq!(sorted(child_fds(&p, &pipes)), sorted(streams(&pipes)));
// Every descriptor a start can hand it.
let joined = std::fs::File::open("/dev/null").unwrap();
let (net_ready, go) = sys::pipe().unwrap();
let (root_r, root_ready) = sys::pipe().unwrap();
let theirs = [joined.as_raw_fd(), net_ready.as_raw_fd(), root_ready.as_raw_fd()];
p.net_join = Some(joined);
p.net_ready = Some(net_ready);
p.root_ready = Some(root_ready);
assert_eq!(sorted(child_fds(&p, &pipes)), sorted([streams(&pipes), theirs.to_vec()].concat()));
// A terminal: the socket its pty master goes back on, nothing else.
p.tty = true;
let (_agent, sock) = sys::socketpair().unwrap();
let tty = ChildStdio::Tty { sock };
assert_eq!(sorted(child_fds(&p, &tty)), sorted([streams(&tty), theirs.to_vec()].concat()));
drop((w0, r1, r2, go, root_r));
}
#[test]
fn a_starting_root_settles_without_waiting() {
use super::{Process, Root};
use std::os::fd::AsRawFd;
// Nothing written yet: still starting, and asking does not wait.
let (r, w) = super::sys::pipe().unwrap();
let mut p = Process::starting_for_test("c1", 100, r, None);
let t = std::time::Instant::now();
assert_eq!(p.root(), Root::Starting);
assert!(t.elapsed() < std::time::Duration::from_millis(50), "settling must not wait");
assert!(!p.entered());
// The child's byte: ready, and stays so.
// SAFETY: one byte to a pipe we own.
assert_eq!(unsafe { libc::write(w.as_raw_fd(), b"r".as_ptr().cast(), 1) }, 1);
assert_eq!(p.root(), Root::Ready);
assert!(p.entered());
drop(w);
assert_eq!(p.root(), Root::Ready, "the pipe is let go once ready");
// Closed without the byte: the child ended first, and stays so.
let (r, w) = super::sys::pipe().unwrap();
let r_fd = r.as_raw_fd();
let mut p = Process::starting_for_test("c2", 101, r, None);
drop(w);
wait_all_writers_gone(r_fd);
assert_eq!(p.root(), Root::Ended);
assert_eq!(p.root(), Root::Ended);
assert!(!p.entered());
assert_eq!(p.start_failure(), Some(super::NOT_READY), "it said nothing");
// A process that never waited is ready.
assert_eq!(Process::for_test("c3", 102).root(), Root::Ready);
assert_eq!(Process::for_test("c3", 102).start_failure(), None);
}
#[test]
fn a_child_that_fails_while_starting_gives_its_own_reason() {
use super::{Process, Root};
use std::os::fd::AsRawFd;
let (r, w) = super::sys::pipe().unwrap();
let (err_r, err_w) = super::sys::pipe().unwrap();
let r_fd = r.as_raw_fd();
let mut p = Process::starting_for_test("c1", 100, r, Some(err_r));
let said = b"kiri: cannot start container: mount /payload: No space left on device (os error 28)\n";
// SAFETY: writing a local buffer to a pipe we own.
assert_eq!(unsafe { libc::write(err_w.as_raw_fd(), said.as_ptr().cast(), said.len()) }, said.len() as isize);
assert_eq!(p.root(), Root::Starting, "its message alone settles nothing");
drop(w);
wait_all_writers_gone(r_fd);
assert_eq!(p.root(), Root::Ended);
assert_eq!(p.start_failure(), Some("mount /payload: No space left on device (os error 28)"));
}
#[test]
fn waiting_for_a_root_lasts_until_the_child_says() {
use super::{Process, Root};
use std::os::fd::AsRawFd;
let (r, w) = super::sys::pipe().unwrap();
let mut p = Process::starting_for_test("c1", 100, r, None);
let writer = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
// SAFETY: one byte to a pipe we own.
unsafe { libc::write(w.as_raw_fd(), b"r".as_ptr().cast(), 1) };
w
});
let t = std::time::Instant::now();
assert_eq!(p.wait_root(), Root::Ready);
assert!(t.elapsed() >= std::time::Duration::from_millis(90), "waited {:?}", t.elapsed());
drop(writer.join().unwrap());
// Ended while waited for.
let (r, w) = super::sys::pipe().unwrap();
let mut p = Process::starting_for_test("c2", 101, r, None);
let closer = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
drop(w);
});
assert_eq!(p.wait_root(), Root::Ended);
closer.join().unwrap();
}
#[test]
fn a_start_waits_for_the_root_only_briefly() {
use std::os::fd::AsRawFd;
let (r, w) = super::sys::pipe().unwrap();
let t = std::time::Instant::now();
assert_eq!(super::root_word(r.as_raw_fd(), Some(super::ROOT_READY_WAIT)).unwrap(), super::RootWord::NotYet);
let waited = t.elapsed();
assert!(waited >= super::ROOT_READY_WAIT && waited < super::ROOT_READY_WAIT * 10, "waited {waited:?}");
// SAFETY: one byte to a pipe we own.
assert_eq!(unsafe { libc::write(w.as_raw_fd(), b"r".as_ptr().cast(), 1) }, 1);
assert_eq!(super::root_word(r.as_raw_fd(), Some(super::ROOT_READY_WAIT)).unwrap(), super::RootWord::Ready);
drop(w);
wait_all_writers_gone(r.as_raw_fd());
assert_eq!(super::root_word(r.as_raw_fd(), Some(super::ROOT_READY_WAIT)).unwrap(), super::RootWord::Ended);
}
use kiri_proto::{Limits, Msg, Net, decode, encode_run, run_flags};
// #227: a new container's writable layer is marked plain before it is
+67
View File
@@ -325,6 +325,35 @@ pub fn open_pty() -> io::Result<(OwnedFd, OwnedFd)> {
}
}
/// The descriptor ranges to close so that only 0, 1, 2 and `keep` stay
/// open: (first, last), inclusive, in order.
pub fn close_ranges(keep: &[RawFd]) -> Vec<(libc::c_uint, libc::c_uint)> {
let mut keep: Vec<libc::c_uint> = keep.iter().filter(|&&fd| fd > 2).map(|&fd| fd as libc::c_uint).collect();
keep.sort_unstable();
keep.dedup();
let mut out = Vec::with_capacity(keep.len() + 1);
let mut next = 3;
for fd in keep {
if fd > next {
out.push((next, fd - 1));
}
next = fd + 1;
}
out.push((next, libc::c_uint::MAX));
out
}
/// Closes the ranges `close_ranges` gave, without allocating. Before Linux
/// 5.9 there is no close_range, and the descriptors stay open, as they
/// always did before.
pub fn close_now(ranges: &[(libc::c_uint, libc::c_uint)]) {
for &(first, last) in ranges {
// SAFETY: closing descriptors of this process, which the caller
// no longer uses.
unsafe { libc::syscall(libc::SYS_close_range, first, last, 0) };
}
}
pub fn resize_pty(fd: RawFd, rows: u16, cols: u16) {
let ws = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
// SAFETY: TIOCSWINSZ with a valid winsize on a descriptor we own.
@@ -345,6 +374,44 @@ mod tests {
assert_eq!(super::one_line("x\ny\rz"), "x y z");
}
#[test]
fn only_the_kept_descriptors_stay_open() {
let all = libc::c_uint::MAX;
assert_eq!(super::close_ranges(&[]), vec![(3, all)]);
// Standard streams are never closed; order and repeats don't matter.
assert_eq!(super::close_ranges(&[9, 2, 4, 9, 5, 0]), vec![(3, 3), (6, 8), (10, all)]);
assert_eq!(super::close_ranges(&[3]), vec![(4, all)]);
// The real thing, in a child of its own: the kept ones stay open,
// the rest are closed. Forked from a test with threads, so the
// child only makes system calls (the ranges are worked out first).
let (unrelated, unrelated_w) = super::pipe().unwrap();
let (kept, kept_w) = super::pipe().unwrap();
let (report, report_w) = super::pipe().unwrap();
use std::os::fd::AsRawFd;
let keep = [kept.as_raw_fd(), report_w.as_raw_fd()];
let ranges = super::close_ranges(&keep);
let check = [unrelated.as_raw_fd(), unrelated_w.as_raw_fd(), kept_w.as_raw_fd(), report.as_raw_fd()];
// SAFETY: the child makes only async-signal-safe system calls and
// leaves with _exit.
unsafe {
let pid = libc::fork();
assert!(pid >= 0);
if pid == 0 {
super::close_now(&ranges);
let open = |fd| libc::fcntl(fd, libc::F_GETFD) >= 0;
let mut ok = keep.iter().all(|&fd| open(fd)) && (0..3).all(open);
ok &= check.iter().all(|&fd| !open(fd));
libc::write(report_w.as_raw_fd(), if ok { b"y".as_ptr() } else { b"n".as_ptr() }.cast(), 1);
libc::_exit(0);
}
drop(report_w);
let mut said = [0u8; 1];
assert_eq!(libc::read(report.as_raw_fd(), said.as_mut_ptr().cast(), 1), 1, "the child said nothing");
libc::waitpid(pid, std::ptr::null_mut(), 0);
assert_eq!(&said, b"y", "a kept descriptor was closed, or another left open");
}
}
/// A command that may not be run ends 126 and one that is missing 127,
/// as with Docker (`docker run alpine /etc/passwd` is 126).
#[test]
+54 -6
View File
@@ -38,8 +38,11 @@ pub const INPUT_WINDOW: usize = 4 << 20;
/// `UsageQuery`, which has no reply: an older agent's "unexpected" error
/// would be taken as the reply to the next request. 5 added `RunSpec::seccomp`,
/// the container's own seccomp program: an older agent would ignore it and
/// run the container under the default filter instead of its profile.
pub const PROTOCOL: u16 = 5;
/// run the container under the default filter instead of its profile. 6
/// added `Started::starting` and `AwaitStart`: an older host would read a
/// start still filling a new volume as started, and let an exec in before
/// the container's root is in place.
pub const PROTOCOL: u16 = 6;
// `Run` is the one big message and is built and read once per container.
#[allow(clippy::large_enum_variant)]
@@ -68,7 +71,14 @@ pub enum Msg<'a> {
/// Host → guest: start a container. Answered by `Started` (or `Error`),
/// then any number of `Output`, then `Exited`.
Run(RunSpec<'a>),
Started { id: &'a str, pid: u32 },
/// `starting`: the container's process is running but its root is not
/// in place yet (a new volume is still being filled); ask `AwaitStart`
/// until it is. Always false for an exec, and from older agents.
Started { id: &'a str, pid: u32, starting: bool },
/// Host → guest: is the root of a container that started `starting` in
/// place now? Answered by `Started` for that container (`starting`
/// false once it is), or `Error` when it is not running.
AwaitStart { id: &'a str },
Output { id: &'a str, stream: Stream, data: &'a [u8] },
Exited(Exited<'a>),
/// Host → guest: send `signal` to the container's process. No reply;
@@ -689,6 +699,7 @@ mod kind {
pub const USB_NODES_QUERY: u16 = 76;
pub const USB_NODES: u16 = 77;
pub const FS_EVENTS: u16 = 78;
pub const AWAIT_START: u16 = 79;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -917,10 +928,15 @@ impl Msg<'_> {
o.extend_from_slice(r.opts.raw);
put_bytes(o, r.seccomp);
}),
Msg::Started { id, pid } => frame(out, kind::STARTED, |o| {
Msg::Started { id, pid, starting } => frame(out, kind::STARTED, |o| {
put_str(o, id);
put_u32(o, pid);
// Only when set: a normal start's frame stays as it was.
if starting {
o.push(1);
}
}),
Msg::AwaitStart { id } => frame(out, kind::AWAIT_START, |o| put_str(o, id)),
Msg::Output { id, stream, data } => frame(out, kind::OUTPUT, |o| {
put_str(o, id);
o.push(stream as u8);
@@ -1226,7 +1242,13 @@ pub fn decode(frame: &[u8]) -> Result<Msg<'_>, DecodeError> {
}
run
}),
kind::STARTED => Msg::Started { id: r.str()?, pid: r.u32()? },
kind::STARTED => Msg::Started {
id: r.str()?,
pid: r.u32()?,
// An older agent doesn't say: its root was in place.
starting: r.remaining() >= 1 && r.u8()? != 0,
},
kind::AWAIT_START => Msg::AwaitStart { id: r.str()? },
kind::OUTPUT => {
let id = r.str()?;
let stream = match r.u8()? {
@@ -1362,7 +1384,20 @@ mod tests {
round(Msg::LayerStatus(true));
round(Msg::LayerBegin(LayerBegin { digest: "sha256:ab", media_type: "x+gzip", size: 9 }));
round(Msg::LayerStored(LayerStored { unpacked_bytes: 1, elapsed_ns: 2 }));
round(Msg::Started { id: "c1", pid: 42 });
round(Msg::Started { id: "c1", pid: 42, starting: false });
round(Msg::Started { id: "c1", pid: 42, starting: true });
// A normal start's frame is the one older agents send; and an older
// agent's Started, without the flag, reads as root in place.
let mut buf = Vec::new();
Msg::Started { id: "c1", pid: 42, starting: true }.encode(&mut buf);
let mut old = buf[..buf.len() - 1].to_vec();
let len = (old.len() - 4) as u32;
old[..4].copy_from_slice(&len.to_le_bytes());
assert_eq!(decode(&old).unwrap(), Msg::Started { id: "c1", pid: 42, starting: false });
let mut normal = Vec::new();
Msg::Started { id: "c1", pid: 42, starting: false }.encode(&mut normal);
assert_eq!(normal, old, "a normal start's frame is unchanged");
round(Msg::AwaitStart { id: "c1" });
round(Msg::Output { id: "c1", stream: Stream::Stderr, data: b"hi\n" });
round(Msg::Exited(Exited { id: "c1", code: -1, setup_ns: 3, run_ns: 4, oom_killed: false }));
round(Msg::Exited(Exited { id: "c1", code: 137, setup_ns: 3, run_ns: 4, oom_killed: true }));
@@ -1406,6 +1441,19 @@ mod tests {
assert_eq!(buf, again);
}
#[test]
fn the_protocol_version_covers_starting() {
// A host from before `Started::starting` would take a start still
// filling a new volume for started and never ask `AwaitStart`; it
// speaks 5, and refuses this agent (and this host refuses an agent
// that speaks 5, which never answers `starting`).
const { assert!(PROTOCOL >= 6) };
let mut buf = Vec::new();
Msg::Hello(Hello { protocol: PROTOCOL, init_start_ns: 1, ready_ns: 2, mem_total_kib: 3, mem_available_kib: 4 }).encode(&mut buf);
let Msg::Hello(h) = decode(&buf).unwrap() else { panic!() };
assert_eq!(h.protocol, 6);
}
#[test]
fn the_protocol_version_covers_the_seccomp_field() {
// An agent from before `RunSpec::seccomp` says 4, and the host refuses
+715 -36
View File
@@ -363,10 +363,72 @@ pub struct ExtraNetwork {
pub mac_address: String,
}
/// Shut while a container's start is under way: from when it is marked
/// Running until the guest has answered the start, which waits until the
/// container's root is in place (a new volume filled). An exec or a copy
/// sent meanwhile waits here, then reaches a container that can be
/// entered, as it did when the guest answered nothing else meanwhile.
///
/// Every start has a gate of its own (`Container::begin_start` replaces the
/// container's gate with a new one), so a gate is shut once in its life and
/// opened once, by its start's guard. Whoever holds a gate waits for the
/// one start that was under way when it took it, never for a later start
/// of the same container: else two starts could wait for each other (A
/// took B's gate; B starts again, and its new start takes A's).
///
/// Only those wait, and they hold no lock while they do. A start waits
/// only for the gates that were already shut when it shut its own, each of
/// a start that began earlier, which itself waits only for still earlier
/// ones: no wait can be part of a cycle. The start holds its gate across
/// the waits and `VmLink::run`, which waits for nothing but the guest.
#[derive(Debug, Default)]
struct StartGate {
shut: Mutex<bool>,
opened: Condvar,
}
impl StartGate {
fn shut(self: &Arc<Self>) -> StartGuard {
*self.shut.lock().unwrap_or_else(|e| e.into_inner()) = true;
StartGuard(self.clone())
}
fn is_shut(&self) -> bool {
*self.shut.lock().unwrap_or_else(|e| e.into_inner())
}
fn wait(&self) {
let mut shut = self.shut.lock().unwrap_or_else(|e| e.into_inner());
while *shut {
shut = self.opened.wait(shut).unwrap_or_else(|e| e.into_inner());
}
}
}
/// See `Engine::take_early`.
#[derive(Debug, PartialEq, Eq)]
enum Early {
Input(Vec<u8>),
Live { close: bool },
Gone,
}
/// Opens the gate again when dropped, whichever way the start ends.
struct StartGuard(Arc<StartGate>);
impl Drop for StartGuard {
fn drop(&mut self) {
*self.0.shut.lock().unwrap_or_else(|e| e.into_inner()) = false;
self.0.opened.notify_all();
}
}
#[derive(Debug)]
pub struct Container {
/// Serializes start with stop/kill/remove through guest creation.
lifecycle: Arc<Mutex<u64>>,
/// See `StartGate`.
start_gate: Arc<StartGate>,
pub id: String,
pub name: String,
pub spec: Spec,
@@ -414,12 +476,26 @@ pub struct Container {
live: bool,
early_input: Vec<u8>,
early_close: bool,
/// This run's `start` event is still to be sent: by the start once it
/// makes the container live, or by its exit, if that came first (a
/// start that waited for a new volume to fill can be overtaken by its
/// exit), so `start` always comes before `die`.
start_owed: bool,
/// `docker logs`: its output on disk, and who follows it.
log: Arc<Mutex<super::logfile::Log>>,
attached: Vec<Sender<(Stream, Vec<u8>)>>,
}
impl Container {
/// Begins a start: a new gate (see `StartGate`), shut. Under the engine
/// lock, with the container's lifecycle lock held, which serialises the
/// starts of one container: the old gate is open by then, its start's
/// guard having dropped before that start returned.
fn begin_start(&mut self) -> StartGuard {
self.start_gate = Arc::default();
self.start_gate.shut()
}
pub fn argv(&self) -> Vec<String> {
self.spec.entrypoint.iter().chain(&self.spec.cmd).cloned().collect()
}
@@ -1438,6 +1514,12 @@ impl Engine {
});
}
/// Kiri is stopped, parking the VM or shutting down: every one of
/// them is set before the running containers are signalled.
fn halting(&self) -> bool {
self.is_stopped() || self.parking.load(std::sync::atomic::Ordering::SeqCst) || SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst)
}
pub fn is_stopped(&self) -> bool {
self.stopped.load(std::sync::atomic::Ordering::SeqCst)
}
@@ -1543,6 +1625,7 @@ impl Engine {
let was_running = s.status == Status::Running;
let mut c = Container {
lifecycle: Arc::new(Mutex::new(0)),
start_gate: Arc::default(),
id: s.id.clone(),
name: s.name,
layers: s.layers,
@@ -1564,6 +1647,7 @@ impl Engine {
live: false,
early_input: Vec::new(),
early_close: false,
start_owed: false,
paused: false,
extra_ips: Vec::new(),
extra_ifs: Vec::new(),
@@ -1807,6 +1891,8 @@ impl Engine {
let mut persist = false;
let mut closed_ports = None;
let actor = st.containers.get(id).map(|c| (c.spec.image.clone(), container_attrs(c)));
// Exited before its start made it live: its `start` first.
let start_owed = st.containers.get_mut(id).is_some_and(|c| std::mem::take(&mut c.start_owed));
// Docker stops a container's healthcheck when it exits.
if let Some(h) = st.health.get_mut(id) {
close_monitor(h);
@@ -1869,6 +1955,9 @@ impl Engine {
}
drop(st);
if let Some((image, attrs)) = actor {
if start_owed {
self.emit_container_with("start", id, &image, attrs.clone(), &[]);
}
self.emit_container_with("die", id, &image, attrs.clone(), &[("exitCode", code.to_string())]);
if remove {
self.emit_container_with("destroy", id, &image, attrs, &[]);
@@ -2219,6 +2308,7 @@ impl Engine {
id.clone(),
Container {
lifecycle: Arc::new(Mutex::new(0)),
start_gate: Arc::default(),
id: id.clone(),
name,
layers: image.layers.iter().rev().map(|l| l.digest.clone()).collect(),
@@ -2241,6 +2331,7 @@ impl Engine {
live: false,
early_input: Vec::new(),
early_close: false,
start_owed: false,
paused: false,
extra_ips: Vec::new(),
extra_ifs: Vec::new(),
@@ -2322,7 +2413,7 @@ impl Engine {
/// The lifecycle lock is held by start_inner for this entire attempt.
fn start_on_vm(&self, key: &str, reason: Start, vm: Arc<VmLink>) -> Result<(), Error> {
let (id, layers, argv, mut spec, size) = {
let (id, layers, argv, mut spec, size, gate) = {
let mut st = self.lock();
let id = resolve(&st, key)?;
// Under the same lock as Lost: either this claim belongs to
@@ -2375,8 +2466,26 @@ impl Engine {
c.stopped_by_user = false;
c.restart_count = 0;
}
(id, c.layers.clone(), argv, c.spec.clone(), c.size.or(c.spec.console_size))
// Shut under the same lock that marks it Running: an exec or
// copy that sees Running also finds the gate shut.
let gate = c.begin_start();
// This run's exit, once reported, counts one more.
let exits = c.exits;
c.start_owed = true;
let out = (id.clone(), c.layers.clone(), argv, c.spec.clone(), c.size.or(c.spec.console_size), (gate, exits));
// A volume is filled from the image by the first start that
// finds it empty, while that start is under way. Collected
// here, under the lock that shut the gate just above, and only
// of gates shut already by other containers: every wait below
// is for a start that began earlier than this one, and each of
// those gates belongs to that one start alone (see `StartGate`),
// so no two starts can wait for each other. (A container that
// shares nothing with an earlier start has no wait at all.)
let earlier = shared_volume_gates(&st, &id, &out.3);
let halted = self.halting();
(out.0, out.1, out.2, out.3, out.4, (out.5.0, out.5.1, earlier, halted))
};
let (gate, exits, earlier, halted_at_claim) = gate;
// A bind source that is a link is followed again at every start, as
// Docker does: re-pointing it between runs (a `current` release
// link) mounts the new target.
@@ -2530,18 +2639,44 @@ impl Engine {
return Err(e);
}
};
match vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp) {
Ok(pid) => {
if let Some(c) = self.lock().containers.get_mut(&id).filter(|c| c.status == Status::Running) {
c.pid = pid;
}
}
Err(e) => {
crate::diag::warn!("container did not start", id = &id[..12], image = spec.image, error = e);
self.fail_start(&id, &spec, &e);
return Err(Error::Io(e));
}
// Waits for the fill of a volume this container shares with a start
// still under way, as it did when the guest's one thread did the
// fill: else it would run on a half-filled volume. No lock is held.
// If that start failed, its gate is open too and this one finds the
// volume still empty and fills it; if that container was removed,
// its gate (an Arc kept here) was opened by its start's guard all
// the same.
for g in &earlier {
g.wait();
}
// The guest knows nothing of this container while it waits, so a
// stop signal sent meanwhile (Kiri's Stop, the VM's sleep, the
// daemon's shutdown: each sets its flag before it signals) was
// dropped there. Looked at again under the lock Stop reads the
// containers with: running it now would leave it running after Stop.
// It ends as a start that failed, which Stop sees as no longer Running.
if !earlier.is_empty()
&& let Some(e) = self.refuse_waited_start(&id, &spec, reason, halted_at_claim, || vm.is_disconnected())
{
return Err(e);
}
let started = vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp);
if let Ok(pid) = started
&& let Some(c) = self.lock().containers.get_mut(&id).filter(|c| c.status == Status::Running)
{
c.pid = pid;
}
// A failed start is cleaned up before the gate opens, as on every
// earlier failure above: an exec or a copy waiting on it then finds
// the container as the failure left it, not half-way there.
if let Err(e) = started {
crate::diag::warn!("container did not start", id = &id[..12], image = spec.image, error = e);
self.fail_start(&id, &spec, &e);
return Err(Error::Io(e));
}
// Before anything below, which may itself exec (a health probe),
// and after the pid is set.
drop(gate);
if let (true, Some((rows, cols))) = (spec.tty, size) {
let _ = vm.resize(&id, rows, cols);
}
@@ -2566,7 +2701,11 @@ impl Engine {
}
Err(e) => {
crate::diag::warn!("ports not published; container stopped", id = &id[..12], error = e);
// Docker refuses to run a container whose ports clash.
// Docker refuses to run a container whose ports clash:
// no `start` for it.
if let Some(c) = self.lock().containers.get_mut(&id) {
c.start_owed = false;
}
let _ = vm.kill(&id, libc::SIGKILL as u32);
return Err(Error::Conflict(e.to_string()));
}
@@ -2581,16 +2720,13 @@ impl Engine {
// arriving meanwhile (and its CloseStdin) queues behind it rather
// than overtaking it.
loop {
let (early, close) = {
let mut st = self.lock();
let Some(c) = st.containers.get_mut(&id) else { break };
let early = std::mem::take(&mut c.early_input);
if !early.is_empty() {
(early, false)
} else {
c.live = true;
(early, std::mem::take(&mut c.early_close))
}
let (early, close) = match self.take_early(&id, exits) {
Early::Input(early) => (early, false),
Early::Live { close } => (Vec::new(), close),
// Exited already (its exit overtook the end of a start that
// waited for its root): not live, and no `start` after its
// `die`.
Early::Gone => return Ok(()),
};
if early.is_empty() {
if close {
@@ -2604,10 +2740,41 @@ impl Engine {
if !spec.auto_remove {
self.save();
}
self.emit_container("start", &id, &[]);
Ok(())
}
/// The next step in making a started container live (see
/// `start_on_vm`), under the lock: input that arrived early to deliver
/// first, or live now (and whether its stdin closed early), its `start`
/// sent, or nothing, when this run (`exits`: its count of exits when it
/// started) has already exited. Its exit is reported apart from the
/// start, and with a start that waits for a new volume to fill it can
/// come first: the container is then not made live again, which would
/// send the next run's early input straight to a guest that has no
/// process for it; what was early for this run goes with it, and its
/// exit sent the `start` before its `die`.
fn take_early(&self, id: &str, exits: u64) -> Early {
let mut st = self.lock();
let Some(c) = st.containers.get_mut(id) else { return Early::Gone };
if c.status != Status::Running || c.exits != exits {
c.early_input.clear();
c.early_close = false;
return Early::Gone;
}
let early = std::mem::take(&mut c.early_input);
if !early.is_empty() {
return Early::Input(early);
}
c.live = true;
if std::mem::take(&mut c.start_owed) {
// Under the lock, so its exit, reported under it too, sends its
// `die` only after this.
let (image, attrs) = (c.spec.image.clone(), container_attrs(c));
self.emit_container_with("start", id, &image, attrs, &[]);
}
Early::Live { close: std::mem::take(&mut c.early_close) }
}
/// Sends an event to every listener and keeps it for `--since`.
pub fn emit(&self, typ: &str, action: &str, actor: &str, attributes: serde_json::Map<String, serde_json::Value>, legacy: Option<(&str, &str)>) {
log_event(typ, action, actor, &attributes);
@@ -2756,6 +2923,35 @@ impl Engine {
Ok(out)
}
/// The look after a start's wait (see the call): `Some(error)` when the
/// start must end instead of running, already failed (`fail_start`).
/// `vm_gone` is read under the engine lock. A start by the restart
/// policy or recovery took `restart_pending` at its claim; refused
/// because Kiri began to stop, it puts it back under that same lock, so
/// Stop's hold keeps the container (Exited, pending) whether its loop
/// ran before or after this, and Start brings it back, as the same error
/// at the top of `start_on_vm` leaves it. Not when the VM is gone
/// (recovery and Lost own that) and not for `--rm` (`comes_back`).
fn refuse_waited_start(&self, id: &str, spec: &Spec, reason: Start, halted_at_claim: bool, vm_gone: impl FnOnce() -> bool) -> Option<Error> {
let (gone, refuse) = {
let mut st = self.lock();
let gone = vm_gone();
let refuse = refuse_after_wait(halted_at_claim, self.halting(), gone);
if refuse && !gone && reason != Start::User
&& let Some(c) = st.containers.get_mut(id)
{
c.restart_pending = true;
}
(gone, refuse)
};
if !refuse {
return None;
}
let e = if gone { Error::Io(io::Error::other("the VM stopped")) } else { Error::Io(io::Error::new(io::ErrorKind::WouldBlock, STOPPED)) };
self.fail_start(id, spec, &e);
Some(e)
}
/// Records a start that never reached the guest as an immediate exit,
/// with the exit code Docker gives that failure (see `start_exit_code`).
/// A start the VM's crash ended keeps the crash's exit (255).
@@ -2769,6 +2965,8 @@ impl Engine {
// Lost may have run before this start finished allocating addresses.
// Reclaim those even when preserving the crash's exit accounting.
if let Some(c) = st.containers.get_mut(id) {
// A start that failed sends no `start`.
c.start_owed = false;
if let Some(ip) = c.ip.take() {
self.release_ip(&c.spec.network_mode, ip);
}
@@ -2921,9 +3119,31 @@ impl Engine {
super::ports::open_relay(&vm, ip, port)
}
/// Waits for a start of the container (see `StartGate`) and gives its
/// id, or the not-found error when it is gone by then: a `--rm`
/// container whose start failed, or that exited, while the call waited.
fn resolve_after_start(&self, key: &str) -> Result<String, Error> {
let id = self.resolve(key)?;
self.wait_for_start(&id);
resolve(&self.lock(), &id)
}
/// Waits for a start of this container still under way (see
/// `StartGate`). Holds no lock while it waits.
fn wait_for_start(&self, id: &str) {
let gate = self.lock().containers.get(id).map(|c| c.start_gate.clone());
if let Some(gate) = gate {
gate.wait();
}
}
/// Opens a `docker cp` session with the guest for a container, running
/// or not: the request frame is sent, the caller does the rest.
pub fn copy(&self, key: &str, op: u8, path: &str, flags: u32) -> Result<kiri_vmm::VsockStream, Error> {
self.wait_for_start(&self.resolve(key)?);
// Looked up after the wait: a `--rm` start that failed meanwhile has
// removed the container, and a copy must not then write into a
// folder made again for a container that no longer exists.
let (id, layers) = {
let st = self.lock();
let id = resolve(&st, key)?;
@@ -3149,7 +3369,9 @@ impl Engine {
/// `docker network connect`.
pub fn connect(&self, network: &str, key: &str, aliases: Vec<String>, ipv4_address: String, ipv6_address: String, mac_address: String) -> Result<(), Error> {
let id = self.resolve(key)?;
// After the start, as when the guest answered nothing else during
// it, so this and the start's own networks are numbered in turn.
let id = self.resolve_after_start(key)?;
let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?;
if let Some(ip) = super::network::parse_ip(&ipv4_address) {
net.check_static(ip).map_err(Error::BadRequest)?;
@@ -3159,7 +3381,7 @@ impl Engine {
}
let (n, running) = {
let mut st = self.lock();
let c = st.containers.get_mut(&id).expect("resolved");
let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?;
if c.spec.network_mode == net.name || c.spec.extra_networks.iter().any(|x| x.name == net.name) {
return Err(Error::Conflict(format!("endpoint with name {} already exists in network {}", c.name, net.name)));
}
@@ -3177,7 +3399,7 @@ impl Engine {
};
self.save();
if running {
let extra = self.lock().containers.get(&id).and_then(|c| c.spec.extra_networks.last().cloned()).expect("just added");
let extra = self.lock().containers.get(&id).and_then(|c| c.spec.extra_networks.last().cloned()).ok_or_else(|| gone(&id))?;
let vm = self.vm()?;
if let Err(e) = self.attach_extra(&vm, &id, n, &extra) {
if let Some(c) = self.lock().containers.get_mut(&id) {
@@ -3192,11 +3414,12 @@ impl Engine {
/// `docker network disconnect`.
pub fn disconnect(&self, network: &str, key: &str) -> Result<(), Error> {
let id = self.resolve(key)?;
// As for connect.
let id = self.resolve_after_start(key)?;
let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?;
let (n, ip) = {
let mut st = self.lock();
let c = st.containers.get_mut(&id).expect("resolved");
let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?;
if c.spec.network_mode == net.name {
return Err(Error::BadRequest(format!("Kiri cannot disconnect a container from its first network ({})", net.name)));
}
@@ -3229,10 +3452,15 @@ impl Engine {
/// `docker pause` / `docker unpause`.
pub fn pause(&self, key: &str, paused: bool) -> Result<(), Error> {
let id = self.resolve(key)?;
// A container still filling a new volume is not frozen: its start
// waits for the fill, which a frozen child never finishes, and a
// `docker commit` (which pauses first) would wait for that start
// forever, and stop, kill and rm behind it. So pause and unpause
// wait for the start, as exec and copy do.
let id = self.resolve_after_start(key)?;
{
let st = self.lock();
let c = st.containers.get(&id).expect("resolved");
let c = st.containers.get(&id).ok_or_else(|| gone(&id))?;
if c.status != Status::Running {
return Err(Error::Conflict(format!("Container {} is not running", &id[..12])));
}
@@ -3259,10 +3487,13 @@ impl Engine {
/// `docker update`: new limits now, and at every later start.
pub fn update(&self, key: &str, limits: Limits, restart: Option<RestartPolicy>) -> Result<(), Error> {
let id = self.resolve(key)?;
// New limits reach the container once its start is done, as when
// the guest answered nothing else during a start: a memory limit
// cut while a new volume fills could end the fill half way.
let id = self.resolve_after_start(key)?;
let running = {
let mut st = self.lock();
let c = st.containers.get_mut(&id).expect("resolved");
let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?;
c.spec.limits = limits;
if let Some(r) = restart {
c.spec.restart = r;
@@ -3321,7 +3552,7 @@ impl Engine {
let id = self.resolve(key)?;
let (old_ports, old_fw, running, target) = {
let mut st = self.lock();
let c = st.containers.get_mut(&id).expect("resolved");
let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?;
if c.spec.network_mode == "none" && !ports.is_empty() {
return Err(Error::BadRequest("a container with --network none cannot publish ports".into()));
}
@@ -3365,7 +3596,7 @@ impl Engine {
let id = self.resolve(key)?;
let running = {
let mut st = self.lock();
let c = st.containers.get_mut(&id).expect("resolved");
let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?;
c.spec.env = env;
c.status == Status::Running
};
@@ -3737,6 +3968,7 @@ impl Engine {
}
flags |= exec_security.0;
let console = config.console_size;
self.wait_for_start(&container_id);
let started = self.vm()?.exec(&container_id, exec_id, &config.argv, &env, &config.cwd, &config.user, flags, exec_security.1, &exec_security.2);
if let Ok(pid) = started {
if let Some(x) = self.lock().execs.get_mut(exec_id).filter(|x| x.exit_code.is_none()) {
@@ -3984,6 +4216,40 @@ pub fn is_builder(c: &Container) -> bool {
c.name.starts_with("buildx_buildkit_")
}
/// Every volume (named, anonymous or `--mount`) a spec uses.
fn volume_names(spec: &Spec) -> Vec<&str> {
let mut v: Vec<&str> = spec.volumes.iter().chain(&spec.anon_volumes).map(String::as_str).collect();
v.extend(spec.mount_info.iter().filter(|m| m["Type"] == "volume").filter_map(|m| m["Name"].as_str()));
v
}
/// The start gates already shut of other containers that share a volume
/// with `spec` (of container `id`). Bind and tmpfs mounts are not volumes.
fn shared_volume_gates(st: &State, id: &str, spec: &Spec) -> Vec<Arc<StartGate>> {
let mine = volume_names(spec);
if mine.is_empty() {
return Vec::new();
}
st.containers
.values()
.filter(|c| c.id != id && c.start_gate.is_shut() && volume_names(&c.spec).iter().any(|v| mine.contains(v)))
.map(|c| c.start_gate.clone())
.collect()
}
/// Whether a start that waited for other starts must not run its container
/// after all: Kiri began to stop meanwhile (not already when the start was
/// claimed: Stop's signals reach the guest only for containers it knows,
/// which this one was not), or the VM is gone.
fn refuse_after_wait(halted_at_claim: bool, halting: bool, vm_gone: bool) -> bool {
(halting && !halted_at_claim) || vm_gone
}
/// The error for a container removed while a call waited for its start.
fn gone(id: &str) -> Error {
Error::NotFound(format!("No such container: {id}"))
}
fn resolve(st: &State, key: &str) -> Result<String, Error> {
let key = key.trim_start_matches('/');
if st.containers.contains_key(key) {
@@ -5227,3 +5493,416 @@ mod save_speed_tests {
let _ = std::fs::remove_dir_all(root);
}
}
#[cfg(test)]
mod start_gate_tests {
use super::StartGate;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[test]
fn an_exec_during_a_start_waits_for_it_and_no_longer() {
let gate = Arc::new(StartGate::default());
// Open: no wait at all.
let t = Instant::now();
gate.wait();
assert!(t.elapsed() < Duration::from_millis(50));
// Shut by a start: a waiter goes on only once the start is done,
// however it ended (the guard opens it when dropped).
let guard = gate.shut();
let waiter = {
let gate = gate.clone();
std::thread::spawn(move || {
let t = Instant::now();
gate.wait();
t.elapsed()
})
};
std::thread::sleep(Duration::from_millis(100));
assert!(!waiter.is_finished(), "an exec waits while the start is under way");
drop(guard);
let waited = waiter.join().unwrap();
assert!(waited >= Duration::from_millis(90) && waited < Duration::from_secs(5), "waited {waited:?}");
let t = Instant::now();
gate.wait();
assert!(t.elapsed() < Duration::from_millis(50), "open again");
}
}
#[cfg(test)]
mod start_wait_tests {
use super::*;
/// An engine that never boots a VM, with one container that reads as
/// Running, as during its start.
fn engine(name: &str) -> (Arc<Engine>, String, PathBuf) {
let dir = std::env::temp_dir().join(format!("kiri-start-wait-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let engine = Engine::boot(Store::open(&dir).unwrap()).unwrap();
engine.stopped.store(true, std::sync::atomic::Ordering::SeqCst);
let image = Image {
name: "test:local".into(), digest: "sha256:test".into(), index_digest: None, config_digest: "sha256:test".into(),
layers: Vec::new(), size: 0, platform: "linux/arm64".into(), created: String::new(), pulled_at: 0, config: Default::default(),
};
let spec: Spec = serde_json::from_value(serde_json::json!({
"image": "test:local", "image_id": "sha256:test", "entrypoint": [], "cmd": ["sleep", "60"],
"env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {},
"restart": {"name": "no", "max_retries": 0}
})).unwrap();
let id = engine.create(Some(name.into()), spec, &image).unwrap();
engine.lock().containers.get_mut(&id).unwrap().status = Status::Running;
(engine, id, dir)
}
fn shut(engine: &Engine, id: &str) -> StartGuard {
engine.lock().containers.get_mut(id).unwrap().begin_start()
}
/// `docker pause` (and the pause `docker commit` makes first) during a
/// start waits for it: a child frozen while it fills a new volume never
/// finishes, and the start, the commit and every stop behind them would
/// wait forever.
#[test]
fn a_pause_during_a_start_waits_for_it() {
let (engine, id, dir) = engine("pause");
for paused in [true, false] {
let guard = shut(&engine, &id);
let pausing = {
let (engine, id) = (engine.clone(), id.clone());
std::thread::spawn(move || engine.pause(&id, paused))
};
std::thread::sleep(Duration::from_millis(150));
assert!(!pausing.is_finished(), "pause({paused}) went ahead during a start");
drop(guard);
// No VM here: it fails then, but only once the start is done.
let _ = pausing.join().unwrap();
}
for (what, call) in [
("update", Box::new(|e: &Engine, id: &str| e.update(id, Limits::default(), None).map(|_| ())) as Box<dyn Fn(&Engine, &str) -> Result<(), Error> + Send>),
("connect", Box::new(|e: &Engine, id: &str| e.connect("bridge", id, Vec::new(), String::new(), String::new(), String::new()))),
("disconnect", Box::new(|e: &Engine, id: &str| e.disconnect("bridge", id))),
] {
let guard = shut(&engine, &id);
let calling = {
let (engine, id) = (engine.clone(), id.clone());
std::thread::spawn(move || call(&engine, &id))
};
std::thread::sleep(Duration::from_millis(150));
assert!(!calling.is_finished(), "{what} went ahead during a start");
drop(guard);
let _ = calling.join().unwrap();
}
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// A copy sent while a start is under way looks the container up once
/// the start is done: a `--rm` one whose start failed meanwhile is gone,
/// and the copy must fail rather than write into a folder made again
/// for a container that no longer exists.
#[test]
fn a_copy_during_a_start_looks_again_once_it_is_done() {
let (engine, id, dir) = engine("copy");
let guard = shut(&engine, &id);
let copying = {
let (engine, id) = (engine.clone(), id.clone());
std::thread::spawn(move || engine.copy(&id, kiri_proto::copy_op::IN, "/", 0).map(|_| ()))
};
std::thread::sleep(Duration::from_millis(150));
assert!(!copying.is_finished(), "a copy went ahead during a start");
// The start fails and takes the `--rm` container with it.
engine.lock().containers.remove(&id);
drop(guard);
let r = copying.join().unwrap();
assert!(matches!(r, Err(Error::NotFound(_))), "{r:?}");
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// The exit of a container whose start waited for its root can be
/// reported before the start ends: it is then not made live (the next
/// run's early input would go straight to a guest with no process for
/// it), and its `start` still comes before its `die`, once.
#[test]
fn an_exit_that_overtakes_its_start() {
let (engine, id, dir) = engine("overtaken");
let (_, events) = engine.subscribe();
let actions = || events.try_iter().filter(|e| e["Actor"]["ID"] == id.as_str()).map(|e| e["Action"].as_str().unwrap_or("").to_owned()).collect::<Vec<_>>();
// In order: live, and its `start` sent.
engine.lock().containers.get_mut(&id).unwrap().start_owed = true;
assert_eq!(engine.take_early(&id, 0), Early::Live { close: false });
assert!(engine.lock().containers[&id].live);
assert_eq!(actions(), ["start"]);
// Its exit first, then the end of the start: no second `start`.
{
let mut st = engine.lock();
let c = st.containers.get_mut(&id).unwrap();
c.live = false;
c.start_owed = true;
c.early_input = b"early".to_vec();
c.early_close = true;
}
let exits = engine.lock().containers[&id].exits;
engine.on_event(Event::Exited { id: &id, code: 0, oom: false });
assert_eq!(engine.take_early(&id, exits), Early::Gone);
let st = engine.lock();
let c = &st.containers[&id];
assert!(!c.live, "an exited run is not made live again");
assert!(c.early_input.is_empty() && !c.early_close, "its early input went with it");
drop(st);
assert_eq!(actions(), ["start", "die"]);
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// A container removed while a call waited for its start (a `--rm` one
/// whose start failed, or that exited before the start returned) is
/// not found by that call. It must not abort the daemon.
#[test]
fn a_container_removed_while_a_call_waited_for_its_start_is_not_found() {
for what in ["pause", "update", "connect", "disconnect"] {
let (engine, id, dir) = engine(&format!("removed-{what}"));
let guard = shut(&engine, &id);
let calling = {
let (engine, id) = (engine.clone(), id.clone());
std::thread::spawn(move || match what {
"pause" => engine.pause(&id, true),
"update" => engine.update(&id, Limits::default(), None),
"connect" => engine.connect("bridge", &id, Vec::new(), String::new(), String::new(), String::new()),
_ => engine.disconnect("bridge", &id),
})
};
std::thread::sleep(Duration::from_millis(150));
assert!(!calling.is_finished(), "{what} went ahead during a start");
engine.lock().containers.remove(&id);
drop(guard);
let r = calling.join().unwrap_or_else(|_| panic!("{what} panicked"));
assert!(matches!(r, Err(Error::NotFound(_))), "{what}: {r:?}");
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
}
/// A second container made with a volume (named or anonymous) that a
/// start under way also uses waits for that start before it reaches the
/// guest; one sharing no volume, or only a bind or tmpfs mount, does not.
#[test]
fn a_start_sharing_a_volume_waits_for_the_earlier_one() {
let (engine, first, dir) = engine("shared-volume");
let spec = |v: serde_json::Value| -> Spec {
let mut s = engine.lock().containers[&first].spec.clone();
s.volumes = v["named"].as_array().into_iter().flatten().map(|x| x.as_str().unwrap().to_owned()).collect();
s.anon_volumes = v["anon"].as_array().into_iter().flatten().map(|x| x.as_str().unwrap().to_owned()).collect();
s.mount_info = v["info"].as_array().cloned().unwrap_or_default();
s
};
{
let mut st = engine.lock();
let c = st.containers.get_mut(&first).unwrap();
c.spec.volumes = vec!["data".into()];
c.spec.anon_volumes = vec!["anon1".into()];
}
let guard = shut(&engine, &first);
let gates = |spec: &Spec| shared_volume_gates(&engine.lock(), "other", spec);
// Named, anonymous and `--mount` volumes are all found.
for s in [spec(serde_json::json!({"anon": ["anon1"]})), spec(serde_json::json!({"info": [{"Type": "volume", "Name": "data"}]}))] {
assert_eq!(gates(&s).len(), 1);
}
let found = gates(&spec(serde_json::json!({"named": ["data"]})));
assert_eq!(found.len(), 1);
let waiting = {
let g = found[0].clone();
std::thread::spawn(move || g.wait())
};
std::thread::sleep(Duration::from_millis(100));
assert!(!waiting.is_finished(), "a start sharing a volume goes ahead during the fill");
drop(guard);
waiting.join().unwrap();
let guard = shut(&engine, &first);
// No volume shared: nothing to wait for.
assert!(gates(&spec(serde_json::json!({"named": ["other"]}))).is_empty());
assert!(gates(&spec(serde_json::json!({}))).is_empty());
// A bind or tmpfs mount is not a volume, even at the same place.
assert!(gates(&spec(serde_json::json!({"info": [{"Type": "bind", "Name": "data", "Source": "data"}, {"Type": "tmpfs", "Destination": "/data"}]}))).is_empty());
// The container itself is not collected, and an open gate is not.
let own = spec(serde_json::json!({"named": ["data"]}));
assert!(shared_volume_gates(&engine.lock(), &first, &own).is_empty());
drop(guard);
assert!(gates(&spec(serde_json::json!({"named": ["data"]}))).is_empty());
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// What `start_on_vm` does under the engine lock for container `id`:
/// begin its start, then collect the shut gates of others sharing a volume.
fn begin(engine: &Engine, id: &str) -> (StartGuard, Vec<Arc<StartGate>>) {
let mut st = engine.lock();
let guard = st.containers.get_mut(id).unwrap().begin_start();
let spec = st.containers[id].spec.clone();
let earlier = shared_volume_gates(&st, id, &spec);
(guard, earlier)
}
/// C fills v1 for a long time; B uses v2; A uses both.
fn three(name: &str) -> (Arc<Engine>, [String; 3], PathBuf) {
let (engine, c, dir) = engine(name);
let image = Image {
name: "test:local".into(), digest: "sha256:test".into(), index_digest: None, config_digest: "sha256:test".into(),
layers: Vec::new(), size: 0, platform: "linux/arm64".into(), created: String::new(), pulled_at: 0, config: Default::default(),
};
let base = engine.lock().containers[&c].spec.clone();
let with = |vols: &[&str]| {
let mut s = base.clone();
s.volumes = vols.iter().map(|v| (*v).to_owned()).collect();
s
};
engine.lock().containers.get_mut(&c).unwrap().spec = with(&["v1"]);
let b = engine.create(Some(format!("{name}-b")), with(&["v2"]), &image).unwrap();
let a = engine.create(Some(format!("{name}-a")), with(&["v1", "v2"]), &image).unwrap();
(engine, [c, b, a], dir)
}
/// A waits for C's fill and for B's first start; B's first start ends
/// and B starts again (restart policy, `docker restart`) while A still
/// waits: B's second start waits for A, which began before it. Each
/// start has a gate of its own, so A is not held by B's second start,
/// and both end once C's fill is done. Waits are bounded: a hang shows
/// as a failed assertion, not a stuck test.
#[test]
fn a_restarted_container_and_one_waiting_for_it_do_not_wait_for_each_other() {
let (engine, [c, b, a], dir) = three("restart-cycle");
let (guard_c, earlier_c) = begin(&engine, &c);
assert!(earlier_c.is_empty());
let (guard_b1, earlier_b1) = begin(&engine, &b);
assert!(earlier_b1.is_empty(), "B shares nothing with C");
let gate_c = engine.lock().containers[&c].start_gate.clone();
let (guard_a, mut earlier_a) = begin(&engine, &a);
assert_eq!(earlier_a.len(), 2, "A waits for C and for B");
// The map's order is arbitrary: C's first, as in the hang.
earlier_a.sort_by_key(|g| !Arc::ptr_eq(g, &gate_c));
let start_a = std::thread::spawn(move || {
for g in &earlier_a {
g.wait();
}
drop(guard_a);
});
std::thread::sleep(Duration::from_millis(100));
drop(guard_b1);
let (guard_b2, earlier_b2) = begin(&engine, &b);
assert_eq!(earlier_b2.len(), 1, "B's second start waits for A, which began before it");
let start_b2 = std::thread::spawn(move || {
for g in &earlier_b2 {
g.wait();
}
drop(guard_b2);
});
std::thread::sleep(Duration::from_millis(100));
drop(guard_c);
let t0 = std::time::Instant::now();
while !(start_a.is_finished() && start_b2.is_finished()) && t0.elapsed() < Duration::from_secs(3) {
std::thread::sleep(Duration::from_millis(20));
}
let (a_done, b_done) = (start_a.is_finished(), start_b2.is_finished());
drop(engine);
let _ = std::fs::remove_dir_all(dir);
assert!(a_done && b_done, "after C's fill ended: A's start finished: {a_done}, B's second start finished: {b_done}");
}
/// A gate opened by an older start stays open when the container starts
/// again: waiters that took it are not held by the new start.
#[test]
fn a_new_start_does_not_shut_the_gate_an_older_start_opened() {
let (engine, id, dir) = engine("own-gate");
let guard = shut(&engine, &id);
let old = engine.lock().containers[&id].start_gate.clone();
drop(guard);
let guard = shut(&engine, &id);
assert!(!old.is_shut() && engine.lock().containers[&id].start_gate.is_shut());
drop(guard);
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// A start that waited ends instead of running when Kiri began to stop
/// meanwhile or the VM went; not when it was stopping already at the
/// claim (its signals did not reach it, as before), and not when it had
/// nothing to wait for (the caller does not look).
#[test]
fn a_start_that_waited_does_not_run_after_a_stop() {
// (halted at claim, halting now, vm gone) -> refuse
assert!(refuse_after_wait(false, true, false), "Kiri began to stop while it waited");
assert!(refuse_after_wait(false, false, true), "the VM went");
assert!(refuse_after_wait(true, true, true));
assert!(!refuse_after_wait(false, false, false));
assert!(!refuse_after_wait(true, true, false), "stopping before the claim: as it was");
assert!(!refuse_after_wait(true, false, false));
// The flags it reads.
let (engine, _id, dir) = engine("halting");
engine.stopped.store(false, std::sync::atomic::Ordering::SeqCst);
assert!(!engine.halting());
engine.parking.store(true, std::sync::atomic::Ordering::SeqCst);
assert!(engine.halting());
engine.parking.store(false, std::sync::atomic::Ordering::SeqCst);
engine.stopped.store(true, std::sync::atomic::Ordering::SeqCst);
assert!(engine.halting());
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
/// A start by the restart policy that waited and is refused because Kiri
/// began to stop stays pending, so Stop's hold keeps it and Start
/// brings it back; a user start is not made pending; nothing is refused
/// when Kiri was stopping at the claim, or is not stopping.
#[test]
fn a_refused_policy_start_stays_pending_for_stop_to_hold() {
let (engine, id, dir) = engine("refused");
let spec = {
let mut st = engine.lock();
let c = st.containers.get_mut(&id).unwrap();
c.spec.restart.name = "always".into();
c.spec.clone()
};
// As after the claim: Running, pending taken, gate shut.
let claimed = |engine: &Engine, pending: bool| {
let mut st = engine.lock();
let c = st.containers.get_mut(&id).unwrap();
c.status = Status::Running;
c.restart_pending = pending;
};
let holds = |engine: &Engine| {
let st = engine.lock();
let c = &st.containers[&id];
(c.status == Status::Running || c.restart_pending) && comes_back(c)
};
// (1) Kiri began to stop during the wait (the engine's stopped flag is set).
for reason in [Start::Restart, Start::DaemonRestart, Start::Held] {
claimed(&engine, false);
let guard = shut(&engine, &id);
let e = engine.refuse_waited_start(&id, &spec, reason, false, || false);
drop(guard);
assert!(matches!(&e, Some(Error::Io(e)) if e.kind() == io::ErrorKind::WouldBlock), "refused");
let st = engine.lock();
let c = &st.containers[&id];
assert!(c.status != Status::Running && c.restart_pending, "still pending, not running");
drop(st);
assert!(holds(&engine), "Stop holds it");
}
// (2) A user start is not made pending.
claimed(&engine, false);
assert!(engine.refuse_waited_start(&id, &spec, Start::User, false, || false).is_some());
assert!(!engine.lock().containers[&id].restart_pending);
// The VM gone: not put back (recovery's own path).
claimed(&engine, false);
assert!(engine.refuse_waited_start(&id, &spec, Start::Restart, false, || true).is_some());
assert!(!engine.lock().containers[&id].restart_pending);
// (3) Stopping at the claim: as it was. Not stopping: not refused.
claimed(&engine, false);
assert!(engine.refuse_waited_start(&id, &spec, Start::Restart, true, || false).is_none());
assert!(engine.lock().containers[&id].status == Status::Running);
engine.stopped.store(false, std::sync::atomic::Ordering::SeqCst);
assert!(engine.refuse_waited_start(&id, &spec, Start::Restart, false, || false).is_none());
assert!(engine.lock().containers[&id].status == Status::Running);
drop(engine);
let _ = std::fs::remove_dir_all(dir);
}
}
+67 -8
View File
@@ -23,8 +23,9 @@ use kiri_vmm::Vm;
pub enum Reply {
LayerStatus(bool),
LayerStored,
/// The process's PID, as the agent's kernel numbers it.
Started(u32),
/// The process's PID, as the agent's kernel numbers it, and whether
/// its root is still being made (see `VmLink::run`).
Started(u32, bool),
Stats(Stats),
Pong,
FsStat(FileInfo),
@@ -261,7 +262,7 @@ impl VmLink {
}
Ok(Msg::LayerStatus(have)) => Reply::LayerStatus(have),
Ok(Msg::LayerStored(_)) => Reply::LayerStored,
Ok(Msg::Started { pid, .. }) => Reply::Started(pid),
Ok(Msg::Started { pid, starting, .. }) => Reply::Started(pid, starting),
Ok(Msg::Stats(s)) => Reply::Stats(s),
Ok(Msg::Pong(_)) => Reply::Pong,
Ok(Msg::FsStat(e)) => Reply::FsStat(FileInfo::from(e)),
@@ -385,7 +386,19 @@ impl VmLink {
seccomp: &[u8],
) -> io::Result<u32> {
self.windows.open(id);
let r = self.call(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None).and_then(started);
// Its process runs, but its root may not be in place yet (a new
// volume is being filled): the agent answered at once rather than
// stall every other container meanwhile. The start is reported only
// once an exec can enter it (#311), or fails as a start.
let r = self
.call(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None)
.and_then(started)
.and_then(|(pid, starting)| {
if starting {
wait_started(|| self.call(|o| Msg::AwaitStart { id }.encode(o), None), std::thread::sleep)?;
}
Ok(pid)
});
if r.is_err() {
self.windows.close(id);
}
@@ -458,7 +471,7 @@ impl VmLink {
#[allow(clippy::too_many_arguments)]
pub fn exec(&self, container_id: &str, exec_id: &str, argv: &[String], env: &[String], cwd: &str, user: &str, flags: u32, caps: u64, opts: &[String]) -> io::Result<u32> {
self.windows.open(exec_id);
let r = self.call(|o| kiri_proto::encode_exec(o, container_id, exec_id, argv, env, cwd, user, flags, caps, opts), None).and_then(started);
let r = self.call(|o| kiri_proto::encode_exec(o, container_id, exec_id, argv, env, cwd, user, flags, caps, opts), None).and_then(started).map(|(pid, _)| pid);
if r.is_err() {
self.windows.close(exec_id);
}
@@ -644,14 +657,42 @@ impl VmLink {
}
}
/// The PID a `Run` or `Exec` was answered with.
fn started(r: Reply) -> io::Result<u32> {
/// The PID a `Run` or `Exec` was answered with, and whether its root is
/// still being made.
fn started(r: Reply) -> io::Result<(u32, bool)> {
match r {
Reply::Started(pid) => Ok(pid),
Reply::Started(pid, starting) => Ok((pid, starting)),
other => Err(io::Error::other(format!("expected Started, got {other:?}"))),
}
}
/// The pauses between `AwaitStart` asks: the first at once, then 1, 2, 4,
/// 8, 16 ms, then every 25 ms. Most volumes fill within the first few; a
/// big one is noticed within 25 ms of being done.
fn await_backoff() -> impl Iterator<Item = std::time::Duration> {
[0, 1, 2, 4, 8, 16].into_iter().chain(std::iter::repeat(25)).map(std::time::Duration::from_millis)
}
/// Asks (`ask` sends `AwaitStart`) until the agent says the root is in
/// place. An error fails the start, as it would have failed the `Run`
/// itself: the child ended before its root was ready (the agent answers
/// with the child's own reason, and sends no `Exited`), or the VM stopped.
/// No lock is held while it sleeps: `call` takes and lets go of its own for
/// each ask.
fn wait_started(mut ask: impl FnMut() -> io::Result<Reply>, mut sleep: impl FnMut(std::time::Duration)) -> io::Result<()> {
for pause in await_backoff() {
if !pause.is_zero() {
sleep(pause);
}
match ask()? {
Reply::Started(_, true) => {}
Reply::Started(_, false) => return Ok(()),
other => return Err(io::Error::other(format!("expected Started, got {other:?}"))),
}
}
unreachable!("the backoff never ends")
}
fn read_frame(conn: &mut File, buf: &mut Vec<u8>) -> io::Result<()> {
buf.resize(4, 0);
conn.read_exact(&mut buf[..4])?;
@@ -666,6 +707,24 @@ mod tests {
use super::*;
use std::os::unix::net::UnixStream;
#[test]
fn a_starting_container_is_asked_about_until_its_root_is_in_place() {
use std::time::Duration;
let ms = |v: &[u64]| v.iter().map(|&m| Duration::from_millis(m)).collect::<Vec<_>>();
assert_eq!(await_backoff().take(9).collect::<Vec<_>>(), ms(&[0, 1, 2, 4, 8, 16, 25, 25, 25]));
// Starting twice, then in place: three asks, the first at once.
let mut answers = vec![Reply::Started(7, false), Reply::Started(7, true), Reply::Started(7, true)];
let (mut asks, mut slept) = (0, Vec::new());
assert!(wait_started(|| { asks += 1; Ok(answers.pop().unwrap()) }, |d| slept.push(d)).is_ok());
assert_eq!((asks, slept), (3, ms(&[1, 2])));
// An error (the child failed before its root was ready, the VM
// stopped) ends the wait and fails the start with it.
let mut answers = vec![Err(io::Error::other("run c1: mount /payload: No space left on device")), Ok(Reply::Started(7, true))];
let mut asks = 0;
let e = wait_started(|| { asks += 1; answers.pop().unwrap() }, |_| {}).unwrap_err();
assert_eq!((asks, e.to_string().as_str()), (2, "run c1: mount /payload: No space left on device"));
}
#[test]
fn a_failed_write_disconnects_before_the_reader_accounts_loss() {
let (socket, peer) = UnixStream::pair().unwrap();
+8 -1
View File
@@ -308,7 +308,14 @@ impl Guest {
self.conn.write_all(&self.out)?;
loop {
match self.read()? {
Msg::Started { .. } => {}
Msg::Started { starting: false, .. } => {}
// Its root is still being made (a new volume filled): ask
// again until it is, as the daemon's link does. A start that
// fails meanwhile answers with an error, and sends no exit.
Msg::Started { starting: true, .. } => {
std::thread::sleep(Duration::from_millis(5));
self.send(Msg::AwaitStart { id: req.id })?;
}
Msg::Output { stream, data, .. } => on_output(stream, data),
Msg::Exited(e) => {
return Ok(RunResult {
+7
View File
@@ -621,6 +621,13 @@ t redis-volume "PONG OK running" bash -c "$D run -d --name rv -v tredis:/data re
# `docker run -d` must not return before the container's root is in place, or
# an immediate exec resolves users against the host's /etc/passwd (#311).
t volume-user-ready "passed passed passed" bash -c "$D run --name ready-seed alpine sh -c 'adduser -D dev && mkdir /payload && dd if=/dev/zero of=/payload/blob bs=1M count=64' >/dev/null && $D commit -c 'USER dev' ready-seed kiri-test/ready:1 >/dev/null && $D rm -f ready-seed >/dev/null; for i in 1 2 3; do v=ready-vol-\$i; c=\$($D run -d --mount type=volume,source=\$v,target=/payload kiri-test/ready:1 sleep 60); if $D exec --user dev \$c id >/dev/null 2>&1; then printf 'passed '; else printf 'failed '; fi; $D rm -f \$c >/dev/null; $D volume rm \$v >/dev/null 2>&1; done; $D rmi kiri-test/ready:1 >/dev/null; echo"
# A start that fills a new volume from a big image folder still waits for the
# fill (#311), but the engine keeps serving every other container meanwhile;
# an exec sent to it meanwhile waits for it, a pause, a commit and a
# container joining its network sent meanwhile all finish, and a start that
# fails during the fill is still a start error with a whole volume
# (tests/start-stall.sh).
t start-stall-exec "pass:" sh "$(dirname "$0")/start-stall.sh"
# A volume over part of a bind (`./:/app` and `/app/node_modules`) is filled
# from the image, as Docker does, never from the host's folder under it.
t vol-copyup-under-bind "index.html" bash -c "h=\$(mktemp -d); mkdir \$h/html; echo mac > \$h/html/from-host.txt; $D run --rm -v \$h:/usr/share/nginx -v /usr/share/nginx/html nginx:alpine sh -c 'cd /usr/share/nginx/html; [ -e from-host.txt ] && echo from the host || ls'; rm -rf \$h"
+10
View File
@@ -81,6 +81,16 @@ t volume "kept" "docker run --rm -v lhv:/d alpine sh -c 'echo kept > /d/f' && do
# `docker run -d` must not return before the container's root is in place, or
# an immediate exec resolves users against the host's /etc/passwd (#311).
t volume-user-ready "passed passed passed" "docker run --name ready-seed alpine sh -c 'adduser -D dev && mkdir /payload && dd if=/dev/zero of=/payload/blob bs=1M count=64' >/dev/null && docker commit -c 'USER dev' ready-seed kiri-test/ready:1 >/dev/null && docker rm -f ready-seed >/dev/null; for i in 1 2 3; do v=ready-vol-\$i; c=\$(docker run -d --mount type=volume,source=\$v,target=/payload kiri-test/ready:1 sleep 60); if docker exec --user dev \$c id >/dev/null 2>&1; then printf 'passed '; else printf 'failed '; fi; docker rm -f \$c >/dev/null; docker volume rm \$v >/dev/null 2>&1; done; docker rmi kiri-test/ready:1 >/dev/null; echo"
# A start that fills a new volume from a big image folder still waits for the
# fill (#311), but the engine keeps serving every other container meanwhile;
# an exec sent to it meanwhile waits for it, a pause, a commit and a
# container joining its network sent meanwhile all finish, and a start that
# fails during the fill is still a start error with a whole volume
# (tests/start-stall.sh).
$D cp "$(dirname "$0")/start-stall.sh" "$N":/start-stall.sh >/dev/null
# Here the engine's own root is the test's: a copy into the container while
# it is still starting must not land in it.
t start-stall-exec "pass:" "sh /start-stall.sh cp"
t memory-limit "67108864" "docker run --rm --memory 64m alpine cat /sys/fs/cgroup/memory.max"
# A working directory through one of the agent's descriptors is refused, and
# before that nothing is made outside the container: the missing directory
+335
View File
@@ -0,0 +1,335 @@
#!/bin/sh
# A container that starts with a new volume over a big image folder fills the
# volume before its root is in place. Its start must wait for that (#311),
# but the engine must keep serving every other container meanwhile.
#
# Prints one line, beginning "pass:" or "fail:". It fails when:
# - while the slow start had not returned, an exec in a bystander container
# failed, or took both half that start's own time and at least 250 ms (a
# stall: see `stalled` below);
# - an exec into the starting container itself, sent during the fill, did
# not wait for the start and then run as the image's user;
# - right after the start returned, an exec as the image's user failed, or
# the volume does not hold the whole folder;
# - a `docker pause`, a `docker commit` and a container that joins its
# network (`--network container:`), all sent during the fill, did not
# each finish, the start with them, or `docker unpause`, `stop` and `rm`
# did not work on it afterwards;
# - a second container started on the same new volume during the fill did
# not run, or counted fewer files than the folder holds (it must wait
# for the fill, not run on a half filled volume), or the first start
# failed with it;
# - a start that fails after the fill began (an unknown sysctl) left the
# volume half filled;
# - a start whose fill runs out of space did not fail with "No space left",
# or its restart policy started it anyway.
# A disk so fast that even the biggest payload fills in under 500 ms cannot
# show a stall either way: "pass: not measured", as when the time runs out.
# Every check that needs no timing still runs then.
#
# `start-stall.sh cp`, where the engine's own root is this shell's (a Linux
# host engine): also copies a uniquely named marker into the volume's path
# while the container is still starting. The copy must succeed and the
# marker be inside the container once it runs. Nothing may enter a container
# before its root is in place, so the marker must never appear in the
# engine's own root. When the fill could be measured, the copy and the exec
# into the starting container must have been sent before the start
# returned, or they prove nothing: if they were not, the try is made once
# more with a bigger payload, and it fails if they are late again.
#
# Run by tests/linux-host.sh, tests/wsl.sh and tests/e2e.sh (under its
# 60 s alarm): plain POSIX shell, the docker CLI ($D, default docker), at
# most START_STALL_BUDGET seconds (default 40) of tries started, then the
# checks on a failing fill, and no step waited for longer than the alarm
# leaves room for.
set -u
D=${D:-docker}
mode=${1:-}
budget=${START_STALL_BUDGET:-40}
# Milliseconds (10 ms steps on Linux, where busybox date has no %N; perl
# on macOS, which has no /proc).
now() {
if [ -r /proc/uptime ]; then
read -r up _ </proc/uptime
echo $((${up%.*} * 1000 + 1${up#*.} * 10 - 1000))
else
perl -MTime::HiRes=time -e 'printf "%d\n", time * 1000'
fi
}
begun=$(now)
run=$(date +%s)$$
tmp=${TMPDIR:-/tmp}/start-stall-$run
mkdir -p "$tmp"
names=
cleanup() {
for n in $names; do
case $n in
c:*) $D rm -f "${n#c:}" ;;
v:*) $D volume rm -f "${n#v:}" ;;
i:*) $D rmi -f "${n#i:}" ;;
esac
done >/dev/null 2>&1
rm -rf "$tmp"
}
trap cleanup EXIT
# Cut short (e2e.sh's alarm, ^C): still clean up.
trap 'exit 1' INT TERM HUP ALRM
say() {
echo "$1"
exit 0
}
# `job NAME CMD...` runs CMD in the background: its output goes to
# $tmp/NAME.out and, once it ends, its exit status to $tmp/NAME. It holds
# none of this script's own streams, so one that never ends cannot keep a
# caller reading them (e2e.sh) waiting after the verdict.
job() {
j=$1
shift
rm -f "$tmp/$j" "$tmp/$j.out"
( "$@" >"$tmp/$j.out" 2>&1; echo $? >"$tmp/$j" ) </dev/null >/dev/null 2>&1 &
}
# `await NAME DEADLINE`: true once job NAME has ended, false if it has not
# by DEADLINE (milliseconds, as `now` counts).
await() {
while [ ! -f "$tmp/$1" ]; do
[ "$(now)" -lt "$2" ] || return 1
sleep 0.1
done
}
# A job's exit status ("none" if it never ran or has not ended) and the
# start of its output.
status() { cat "$tmp/$1" 2>/dev/null || echo none; }
said() { head -c 200 "$tmp/$1.out" 2>/dev/null; }
# The start, timed: $tmp/slow holds its milliseconds once it returns.
timed() {
s=$(now)
"$@"
r=$?
echo $(($(now) - s)) >"$tmp/slow"
return $r
}
# A pause or a commit (which pauses too, then unpauses) refused because the
# other has the container paused at that moment has finished all the same.
finished() { [ "$(status "$1")" = 0 ] || grep -q "already paused" "$tmp/$1.out" 2>/dev/null; }
# A stall: an exec in another container that waited for the fill. On main a
# bystander exec sent during the fill waits for all of what is left of it,
# so it takes most of the start (the first is sent about 100 to 200 ms in);
# with the fix one takes a few tens of milliseconds, and on a loaded
# machine one may take 200 ms. So both: half the start or more (a ratio, so
# a long start is not judged by a short exec's rules) and 250 ms or more (a
# floor, so one slow exec on a loaded machine is not a stall). Only starts
# of 500 ms or more are judged: on main their bystander exec waits at
# least 300 ms, above the floor.
measurable=500
stalled() { [ $(($1 * 2)) -ge "$2" ] && [ "$1" -ge 250 ]; }
# Checks that need no timing, on a start that fails during its fill.
# Appends to $fails.
fill_checks() {
img=$1 files=$2 tag=$3
names="$names c:stall-cut-$tag c:stall-full-$tag v:stall-cut-$tag v:stall-full-$tag"
# A start that fails after its fill began must not leave the volume half
# filled: no longer empty, it would never be filled again.
if $D run -d --name stall-cut-$tag --sysctl net.ipv4.kiri_no_such_key=1 --mount type=volume,source=stall-cut-$tag,target=/payload "$img" sleep 300 >"$tmp/cut.out" 2>&1; then
fail "a start with an unknown sysctl did not fail"
fi
got=$($D run --rm --mount type=volume,source=stall-cut-$tag,target=/payload "$img" sh -c "$sum" 2>&1)
[ "$got" = "$want" ] || fail "a start that failed after its fill began left the volume half filled"
# A fill that runs out of room (inodes for half the files) fails the
# start with the reason, and a restart policy does not start it anyway.
$D volume create --opt type=tmpfs --opt device=tmpfs --opt o=size=512m,nr_inodes=$((files / 2)) stall-full-$tag >/dev/null
if $D run -d --name stall-full-$tag --restart always --mount type=volume,source=stall-full-$tag,target=/payload "$img" sleep 300 >"$tmp/full.out" 2>&1; then
fail "a start whose volume ran out of room did not fail"
elif ! grep -q "No space left" "$tmp/full.out"; then
fail "a start whose volume ran out of room did not say why: $(head -c 200 "$tmp/full.out")"
fi
sleep 2
state=$($D inspect -f '{{.RestartCount}} {{.State.Running}}' stall-full-$tag 2>&1)
[ "$state" = "0 false" ] || fail "a failed start was restarted by its restart policy (restarts, running: $state)"
}
fails=
fail() { fails="$fails; $1"; }
# One try with a payload of $1 MB in one file and $2 small files in folders
# of 10,000, plus this run's own tag, so its layer is never one an earlier
# run (or another build) already unpacked. Sets $result: "slow" when the
# fill was too quick to measure and every other check passed, else the line
# to print. Leaves $img, $tag, $sum and $want for `fill_checks`.
attempt() {
tag=$run-$2
img=kiri-test/stall:$tag by=stall-by-$tag big=stall-big-$tag vol=stall-vol-$tag join=stall-join-$tag second=stall-second-$tag
names="$names c:stall-seed-$tag c:$join c:$second c:$by c:$big v:$vol i:$img i:$img-c"
marker=kiri-start-stall-marker-$tag
$D run --name stall-seed-$tag alpine sh -c "adduser -D dev && mkdir -p /payload && echo $tag > /payload/tag &&
dd if=/dev/zero of=/payload/big bs=1M count=$1 2>/dev/null &&
seq $2 | xargs -n 1000 sh -c 'd=/payload/d\$((\$1 / 10000)); mkdir -p \$d; for f; do echo \$f > \$d/f\$f; done' _ &&
chown -R dev /payload" >/dev/null 2>"$tmp/err" || say "fail: could not make the test image: $(head -c 300 "$tmp/err")"
$D commit -c 'USER dev' stall-seed-$tag "$img" >/dev/null 2>"$tmp/err" || say "fail: could not commit the test image: $(head -c 300 "$tmp/err")"
$D rm -f stall-seed-$tag >/dev/null
sum="cd /payload && find . -type f ! -name 'kiri-start-stall-marker-*' | sort | xargs md5sum | md5sum"
want=$($D run --rm "$img" sh -c "$sum")
$D run -d --name "$by" alpine sleep 300 >/dev/null
$D exec "$by" true || say "fail: the bystander container cannot exec"
rm -f "$tmp/slow"
job start timed $D run -d --name "$big" --mount type=volume,source="$vol",target=/payload "$img" sleep 300
begin=$(now)
max=0 execs=0 bad=0 w=
# Sent once it shows as running, while it still starts (or right after,
# if no pass saw it): an exec into it, a pause, a commit, a container
# joining its network, and in `cp` mode a copy into its volume. In the
# background, so a request that waits does not stop the timing.
send() {
[ -f "$tmp/slow" ] && w=after || w=before
job inner $D exec --user dev "$big" id -un
job pause $D pause "$big"
job commit $D commit "$big" "$img-c"
job join $D run -d --name "$join" --network container:"$big" alpine sleep 300
# A second container on the same new volume counts what it sees once it
# runs: its start must wait for the fill (the marker of `cp` is not
# part of the folder).
job second $D run --rm --name "$second" --mount type=volume,source="$vol",target=/payload "$img" sh -c "find /payload -type f ! -name 'kiri-start-stall-marker-*' | wc -l"
if [ "$mode" = cp ]; then
echo marker >"$tmp/$marker"
job cp $D cp "$tmp/$marker" "$big:/payload/$marker"
fi
}
# Every exec begun before the start returned counts, however long it
# took. A start still not back after 15 s is frozen (a pause or a commit
# during its fill froze the child filling the volume): thawed, so the
# clean-up can go on, and failed.
while [ ! -f "$tmp/slow" ]; do
if [ $(($(now) - begin)) -ge 15000 ]; then
$D unpause "$big" >/dev/null 2>&1
say "fail: the start did not return within 15 s, with a pause, a commit and a container joining its network sent during its fill; execs=$execs exec-max=${max}ms"
fi
if [ -z "$w" ] && [ "$($D inspect -f '{{.State.Status}}' "$big" 2>/dev/null)" = running ]; then
send
fi
s=$(now)
$D exec "$by" true >/dev/null 2>&1 || bad=$((bad + 1))
e=$(($(now) - s))
execs=$((execs + 1))
[ $e -gt $max ] && max=$e
# A pause, so the execs measure the engine rather than load it.
sleep 0.1
done
[ -n "$w" ] || send
slow=$(cat "$tmp/slow")
await start $(($(now) + 5000))
[ "$(status start)" = 0 ] && [ "$($D inspect -f '{{.State.Running}}' "$big" 2>/dev/null)" = true ] ||
say "fail: the slow start failed: $(said start)"
# Every check runs, and every failure is listed.
fails=
late=
# The pause and the commit first: an exec or a copy that started while
# the container was paused goes on only once it is unpaused.
until=$(($(now) + 10000))
for j in pause commit; do
await $j $until || late="$late $j"
done
finished pause || fail "a pause sent $w the start returned failed: $(said pause)"
finished commit || fail "a commit sent $w the start returned failed: $(said commit)"
if [ "$($D inspect -f '{{.State.Paused}}' "$big" 2>&1)" = true ]; then
$D unpause "$big" >"$tmp/unpause.out" 2>&1 || fail "docker unpause afterwards failed: $(said unpause)"
fi
jobs="inner join second"
[ "$mode" = cp ] && jobs="$jobs cp"
for j in $jobs; do
await $j $until || late="$late $j"
done
[ -z "$late" ] || fail "sent during the start, these never finished:$late"
# The pause sent with it can get there first: the exec is then refused
# because the container is paused, which says nothing about the start.
# It must work now that the container is unpaused.
if [ "$(status inner)" != 0 ] && said inner | grep -q 'is paused'; then
$D exec --user dev "$big" id -un >"$tmp/inner.out" 2>&1
echo $? >"$tmp/inner"
fi
line="start=${slow}ms exec-max=${max}ms execs=$execs sent=$w"
[ $bad -eq 0 ] || fail "$bad bystander exec(s) failed"
if [ "$slow" -ge $measurable ] && stalled "$max" "$slow"; then
fail "an exec in another container waited for the fill (a stall)"
fi
user=$($D exec --user dev "$big" id -un 2>&1)
got=$($D exec "$big" sh -c "$sum" 2>&1)
[ "$user" = dev ] || fail "an exec as the image's user right after the start failed: $user"
[ "$got" = "$want" ] || fail "the volume does not hold the whole folder"
if [ "$(status inner)" = 0 ] && [ "$(said inner)" = dev ]; then
line="$line inner-exec=$w"
else
fail "an exec into the starting container, sent $w the start returned, did not wait for it and run as its user: $(said inner)"
fi
if [ "$(status join)" = 0 ] && [ "$($D inspect -f '{{.State.Running}}' "$join" 2>&1)" = true ]; then
:
else
fail "a container joining the starting container's network, sent $w the start returned, did not start: $(said join)"
fi
# The folder holds the tag file, the big file and $2 small ones.
seen=$(said second | tr -d ' \n')
if [ "$(status second)" != 0 ] || [ "$seen" != "$(($2 + 2))" ]; then
fail "a second container on the volume, started $w the first start returned, saw ${seen:-nothing} of $(($2 + 2)) files: $(said second)"
fi
if [ "$mode" = cp ]; then
[ "$(status cp)" = 0 ] || fail "a copy into the starting container, sent $w the start returned, failed: $(said cp)"
if [ -e "/payload/$marker" ] || [ -e "/$marker" ]; then
rm -f "/payload/$marker" "/$marker"
fail "a copy into the starting container landed in the engine's own root"
fi
$D exec "$big" test -e "/payload/$marker" || fail "a copy into the starting container is not in its volume"
line="$line cp=$w"
fi
# Nothing is left holding it: stop and rm go through.
$D rm -f "$join" "$second" >/dev/null 2>&1
until=$(($(now) + 10000))
job stop $D stop -t 0 "$big"
await stop $until && [ "$(status stop)" = 0 ] || fail "docker stop afterwards did not finish: $(said stop)"
job rm $D rm "$big"
await rm $until && [ "$(status rm)" = 0 ] || fail "docker rm afterwards did not finish: $(said rm)"
$D rm -f "$by" >/dev/null 2>&1
$D volume rm -f "$vol" >/dev/null 2>&1
$D rmi -f "$img-c" >/dev/null 2>&1
if [ -n "$fails" ]; then
result="fail: ${fails#; }; $line"
elif [ "$slow" -lt $measurable ]; then
result=slow
elif [ "$mode" = cp ] && [ "$w" = after ]; then
result=late
else
fill_checks "$img" "$2" "$tag"
if [ -n "$fails" ]; then
result="fail: ${fails#; }; $line"
else
result="pass: $line"
fi
fi
}
# Bigger payloads when the disk is too fast to measure, while time allows
# (a try takes longer than the last one, so the next is started only when
# twice the last one's time is still left).
prev='' retried=''
sent_late="the exec and the copy into the starting container were sent only after its start returned"
for size in "32 30000" "64 60000" "128 100000"; do
[ -z "$prev" ] || $D rmi -f "$prev" >/dev/null 2>&1
t0=$(now)
attempt $size
case $result in
slow) ;;
late)
[ -z "$retried" ] || say "fail: $sent_late, twice, so they prove nothing; $line"
retried=1
;;
*) say "$result" ;;
esac
prev=$img last=${size#* }
took=$(($(now) - t0))
[ $(($(now) - begun + 2 * took)) -lt $((budget * 1000)) ] || break
done
[ -z "$retried" ] || say "fail: $sent_late, and there was no time or bigger payload left to try again; $line"
# Not measured: what needs no timing still has to hold.
fails=
fill_checks "$prev" "$last" "$tag"
[ -z "$fails" ] || say "fail: ${fails#; }; not measured"
say "pass: not measured (the disk filled even the biggest volume tried in under ${measurable} ms, or time ran out)"
+8
View File
@@ -63,6 +63,14 @@ t volume "kept" "docker run --rm -v wv:/d alpine sh -c 'echo kept > /d/f' && doc
# `docker run -d` must not return before the container's root is in place, or
# an immediate exec resolves users against the host's /etc/passwd (#311).
t volume-user-ready "passed passed passed" "docker run --name ready-seed alpine sh -c 'adduser -D dev && mkdir /payload && dd if=/dev/zero of=/payload/blob bs=1M count=64' >/dev/null && docker commit -c 'USER dev' ready-seed kiri-test/ready:1 >/dev/null && docker rm -f ready-seed >/dev/null; for i in 1 2 3; do v=ready-vol-\$i; c=\$(docker run -d --mount type=volume,source=\$v,target=/payload kiri-test/ready:1 sleep 60); if docker exec --user dev \$c id >/dev/null 2>&1; then printf 'passed '; else printf 'failed '; fi; docker rm -f \$c >/dev/null; docker volume rm \$v >/dev/null 2>&1; done; docker rmi kiri-test/ready:1 >/dev/null; echo"
# A start that fills a new volume from a big image folder still waits for the
# fill (#311), but the engine keeps serving every other container meanwhile;
# an exec sent to it meanwhile waits for it, a pause, a commit and a
# container joining its network sent meanwhile all finish, and a start that
# fails during the fill is still a start error with a whole volume
# (tests/start-stall.sh).
$D cp "$(dirname "$0")/start-stall.sh" kiri-wsl-cli:/start-stall.sh >/dev/null
t start-stall-exec "pass:" "sh /start-stall.sh"
t seccomp "Seccomp: 2" "docker run --rm alpine grep Seccomp: /proc/self/status"
t cleanup "web" "docker rm -f web db"
# The agent (kiri-init under the daemon) dies with nobody asking (#50):