Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion crates/kiri-init/src/linux/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ struct Prepared {
init: bool,
/// `--cgroupns host`: no cgroup namespace of its own.
cgroupns_host: bool,
/// Timer slack in nanoseconds for the container's PID 1 (`timerslack_ns`).
timer_slack_ns: Option<u64>,
/// Ulimits, groups and device nodes from the `opts` lines.
host: HostApplied,
/// The child's end of the pipe that says its root is in place (mounts
Expand Down Expand Up @@ -618,6 +620,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
}
let (masked, readonly) = (host.masked.take(), host.readonly.take());
prepared.cgroupns_host = host.cgroupns_host;
prepared.timer_slack_ns = host.timer_slack_ns;
prepared.host = HostApplied { rlimits: host.rlimits.clone(), groups: host.groups.clone(), nodes, masked, readonly };
// Small, short-lived files: kept in memory (/run is tmpfs), not on the data disk.
let etc_dir = PathBuf::from("/run/kiri").join(spec.id);
Expand Down Expand Up @@ -1525,6 +1528,7 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname:
shm_size: 64 << 20,
init: flags & run_flags::INIT != 0,
cgroupns_host: false,
timer_slack_ns: None,
host: HostApplied::default(),
root_ready: None,
cgroup_ready: None,
Expand Down Expand Up @@ -2541,6 +2545,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec<RawFd> {
shm_size: _,
init: _,
cgroupns_host: _,
timer_slack_ns: _,
// Paths, numbers and names only.
host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ },
root_ready,
Expand Down Expand Up @@ -2779,6 +2784,11 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! {
// While still root with every capability: raising a hard limit needs
// CAP_SYS_RESOURCE.
apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e));
if console
&& let Some(ns) = p.timer_slack_ns
{
apply_timer_slack(ns);
}

for cap in 0..=LAST_CAP {
if !p.privileged && p.caps & (1 << cap) == 0 {
Expand Down Expand Up @@ -2881,6 +2891,22 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! {
sys::exec_fail(2, &exe, io::Error::last_os_error(), false)
}

/// Applies timer slack (`ns`) to the container's PID 1 before `execve`.
/// Writing `/proc/self/timerslack_ns` updates both `timer_slack_ns` and
/// `default_timer_slack_ns` in Linux (`fs/proc/base.c`), so the slack survives
/// `execve` into `/bin/k3s` and coalesces staggered sub-100 ms tickers (#989).
fn apply_timer_slack(ns: u64) {
let _ = apply_timer_slack_to(Path::new("/proc/self/timerslack_ns"), ns);
// SAFETY: `PR_SET_TIMERSLACK` takes the slack in nanoseconds as `arg2`.
unsafe {
libc::prctl(libc::PR_SET_TIMERSLACK, ns as libc::c_ulong, 0, 0, 0);
}
}

fn apply_timer_slack_to(path: &Path, ns: u64) -> io::Result<()> {
fs::write(path, ns.to_string())
}

/// How the container's root is remounted once it is `/`, if at all:
/// read-only for `--read-only`, and `nodev` when the device filter could not
/// be attached. Without the filter, a block or character device node that an
Expand Down Expand Up @@ -4747,14 +4773,22 @@ mod tests {
fn hostopts_cgroupns_host_is_parsed_cleanly() {
let mut buf = Vec::new();
let net = Net { bridge: "", ip: [0; 4], prefix: 0, gateway: [0; 4], extra_hosts: &[], dns_names: &[], opts: &[] };
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost"], &[]);
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost", "timerslack\t10000000"], &[]);
let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
let parsed = super::super::hostopts::parse(spec.opts).unwrap();
assert!(parsed.cgroupns_host);
assert_eq!(parsed.timer_slack_ns, Some(10_000_000));
let mut prepared = super::prepare(spec.argv, spec.env, spec.cwd, spec.user, Some(spec.hostname), spec.flags, spec.caps).unwrap();
assert!(!prepared.cgroupns_host);
assert_eq!(prepared.timer_slack_ns, None);
prepared.cgroupns_host = parsed.cgroupns_host;
prepared.timer_slack_ns = parsed.timer_slack_ns;
assert!(prepared.cgroupns_host);
assert_eq!(prepared.timer_slack_ns, Some(10_000_000));
let tmp = std::env::temp_dir().join(format!("kiri-timerslack-{}", std::process::id()));
super::apply_timer_slack_to(&tmp, 10_000_000).unwrap();
assert_eq!(std::fs::read_to_string(&tmp).unwrap(), "10000000");
let _ = std::fs::remove_file(&tmp);
}

#[test]
Expand Down
18 changes: 18 additions & 0 deletions crates/kiri-init/src/linux/hostopts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ pub struct HostOpts {
/// `--cgroupns host`: share the agent's cgroup namespace instead of
/// unsharing one rooted at the container's cgroup.
pub cgroupns_host: bool,
/// Timer slack (`timerslack_ns`, in nanoseconds) applied to the container's
/// init process so high-frequency background pollers coalesce cleanly (#989).
pub timer_slack_ns: Option<u64>,
}

fn bad(line: &str) -> io::Error {
Expand Down Expand Up @@ -131,6 +134,13 @@ pub fn parse(list: StrList<'_>) -> io::Result<HostOpts> {
*(if *kind == "masked" { &mut o.masked } else { &mut o.readonly }) = Some(paths);
}
["cgroupns", "host"] => o.cgroupns_host = true,
["timerslack", ns] => {
let ns: u64 = ns.parse().map_err(|_| bad(line))?;
if ns == 0 || ns > 1_000_000_000 {
return Err(bad(line));
}
o.timer_slack_ns = Some(ns);
}
_ => return Err(bad(line)),
}
}
Expand Down Expand Up @@ -466,6 +476,10 @@ mod tests {
assert_eq!(o.masked, Some(vec![]));
assert_eq!(o.readonly, Some(vec![c"/proc/sys".to_owned(), c"/data".to_owned()]));
assert!(o.cgroupns_host);
assert_eq!(o.timer_slack_ns, None);
let buf = list(&["timerslack\t10000000"]);
let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() };
assert_eq!(parse(l).unwrap().timer_slack_ns, Some(10_000_000));
for bad_path in ["masked\tproc/kcore", "masked\t/../etc", "readonly\t/proc/../etc"] {
let buf = list(&[bad_path]);
let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() };
Expand All @@ -480,6 +494,10 @@ mod tests {
"cgroupns",
"cgroupns\tprivate",
"cgroupns\tbogus",
"timerslack",
"timerslack\t0",
"timerslack\t1000000001",
"timerslack\tnope",
"nope",
] {
let buf = list(&[bad]);
Expand Down
10 changes: 10 additions & 0 deletions crates/kiri-win/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ pub(crate) fn on_external_wake() {
send(Cmd::Refresh);
}

/// Called after an external `POST /kiri/stop` (`kiri engine stop`) stops the
/// WSL daemon through the named pipe: marks `kiri-win` stopped immediately so
/// subsequent pipe/status checks see the stopped gate without a race, then
/// tells the engine thread to tear down bridges/relays, terminate Kiri's
/// dedicated WSL distro, and update the window and tray (#983).
pub(crate) fn on_external_stop() {
crate::serve::set_stopped(true);
send(Cmd::Stop);
}

fn engine(rx: &Receiver<Cmd>, tx: Sender<Cmd>) {
watch(tx);
// Windows' proxy and root certificates for the daemon, now and every
Expand Down
39 changes: 35 additions & 4 deletions crates/kiri-win/src/refuse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ fn strip_version(path: &str) -> &str {
path
}

/// Whether the first HTTP request line in `request` is `POST /kiri/wake`
/// (or versioned `POST /v*/kiri/wake`).
pub fn is_wake_request(request: &[u8]) -> bool {
fn matches_post_endpoint(request: &[u8], endpoint: &str) -> bool {
let line_end = request.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(request.len().min(1024));
let Ok(line) = std::str::from_utf8(&request[..line_end]) else {
return false;
Expand All @@ -48,7 +46,19 @@ pub fn is_wake_request(request: &[u8]) -> bool {
return false;
}
let path = target.split('?').next().unwrap_or(target);
strip_version(path) == "/kiri/wake"
strip_version(path) == endpoint
}

/// Whether the first HTTP request line in `request` is `POST /kiri/wake`
/// (or versioned `POST /v*/kiri/wake`).
pub fn is_wake_request(request: &[u8]) -> bool {
matches_post_endpoint(request, "/kiri/wake")
}

/// Whether the first HTTP request line in `request` is `POST /kiri/stop`
/// (or versioned `POST /v*/kiri/stop`).
pub fn is_stop_request(request: &[u8]) -> bool {
matches_post_endpoint(request, "/kiri/stop")
}

/// Returns `Some(d)` only when `distro` is Kiri's dedicated bundled distro
Expand All @@ -66,6 +76,9 @@ pub enum GateDecision {
/// Engine was stopped and the request is `POST /kiri/wake` (or `/v*/kiri/wake`):
/// gate and marker are now cleared; forward the already-read request bytes.
Wake,
/// Engine is already stopped and the request is `POST /kiri/stop`: reply
/// HTTP 204 No Content immediately without spawning `wsl.exe`.
AlreadyStopped,
/// Engine is stopped and the request is not a wake: reply HTTP 503 with
/// [`STOPPED`] without spawning `wsl.exe`.
Refuse,
Expand Down Expand Up @@ -121,6 +134,8 @@ impl StoppedGate {
if is_wake_request(first_request) {
self.set(false, marker);
GateDecision::Wake
} else if is_stop_request(first_request) {
GateDecision::AlreadyStopped
} else {
GateDecision::Refuse
}
Expand Down Expand Up @@ -288,6 +303,12 @@ mod tests {
let after_start = StoppedGate::new();
assert!(!after_start.init_from(Some(&marker)));

// POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker.
gate.set(true, Some(&marker));
assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped);
assert!(gate.is_stopped());
assert!(marker.is_file());

let _ = std::fs::remove_dir_all(&dir);
}

Expand All @@ -309,6 +330,10 @@ mod tests {
assert!(!is_wake_request(b"GET /v1.47/containers/json HTTP/1.1\r\n\r\n"));
assert!(!is_wake_request(b"POST /containers/create HTTP/1.1\r\n\r\n"));
assert!(!is_wake_request(b"POST /kiri/stop HTTP/1.1\r\n\r\n"));
assert!(is_stop_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n"));
assert!(is_stop_request(b"POST /v1.47/kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n"));
assert!(!is_stop_request(b"GET /kiri/stop HTTP/1.1\r\n\r\n"));
assert!(!is_stop_request(b"POST /kiri/wake HTTP/1.1\r\n\r\n"));
assert!(!is_wake_request(b"POST /kiri/wake/extra HTTP/1.1\r\n\r\n"));
assert!(!is_wake_request(b"POST /v/kiri/wake HTTP/1.1\r\n\r\n"));
assert!(!is_wake_request(b"POST /v./kiri/wake HTTP/1.1\r\n\r\n"));
Expand Down Expand Up @@ -352,6 +377,12 @@ mod tests {
assert!(!gate.is_stopped());
assert!(!marker.exists());

// POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker.
gate.set(true, Some(&marker));
assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped);
assert!(gate.is_stopped());
assert!(marker.is_file());

let _ = std::fs::remove_dir_all(&dir);
}

Expand Down
15 changes: 15 additions & 0 deletions crates/kiri-win/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1816,6 +1816,15 @@ fn serve_shared(hub: &Hub, pipe: Arc<Pipe>) {
prefetched = Some(first);
woke = true;
}
crate::refuse::GateDecision::AlreadyStopped => {
if pipe.write(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").is_ok() {
pipe.flush();
if !pipe.is_aborted() && pipe.write(&[]).is_ok() {
linger(pipe);
}
}
return;
}
crate::refuse::GateDecision::Refuse => {
if refuse(pipe, is_head(&first), crate::refuse::STOPPED) {
linger(pipe);
Expand Down Expand Up @@ -1981,6 +1990,7 @@ fn serve_shared(hub: &Hub, pipe: Arc<Pipe>) {
let writer = thread::spawn(move || to_client(&p, &rx, &queued, &b, w.as_deref().map(|w| (id, w)), &r, &po));
let mut buf = vec![0u8; 64 * 1024];
let mut first_chunk = true;
let mut stopped_req = false;
let end = loop {
let from_prefetch = prefetched.take();
let chunk: &[u8] = match from_prefetch.as_deref() {
Expand All @@ -1995,6 +2005,9 @@ fn serve_shared(hub: &Hub, pipe: Arc<Pipe>) {
let n = chunk.len();
if first_chunk {
first_chunk = false;
if crate::refuse::is_stop_request(chunk) {
stopped_req = true;
}
if crate::ports::is_port_affecting_request(chunk) {
port_op.store(true, Ordering::SeqCst);
crate::ports::before_container_op();
Expand Down Expand Up @@ -2032,6 +2045,8 @@ fn serve_shared(hub: &Hub, pipe: Arc<Pipe>) {
let replies_ended = writer.join().unwrap_or(false);
if woke && HUB.get().is_some() {
crate::engine::on_external_wake();
} else if stopped_req && HUB.get().is_some() {
crate::engine::on_external_stop();
}
if port_op.load(Ordering::Relaxed) {
crate::ports::notify();
Expand Down
14 changes: 14 additions & 0 deletions crates/kiri/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,20 @@ fn check_alive_at(sock: &Path, not_running: &str) -> io::Result<()> {
}
}

#[cfg(unix)]
pub(crate) fn probe_socket(sock: &Path) -> io::Result<()> {
check_alive_at(sock, not_running_message())
}

#[cfg(unix)]
pub(crate) fn get_background_at(sock: &Path, path: &str) -> io::Result<Value> {
let r = send_to(sock, "GET", path, None, "X-Kiri-Background: 1\r\n")?;
if !r.ok() {
return Err(io::Error::other(r.error()));
}
Ok(r.json())
}

/// Probes the engine socket, distinguishing `PermissionDenied` (`EACCES`) from
/// the daemon not running and formatting OS-appropriate guidance.
pub fn check_alive() -> io::Result<()> {
Expand Down
Loading
Loading