Files
netris-nestri/crates/nesprotocol/src/lifecycle.rs
T
Wanjohi 4a0a790fd1 feat(nesinit): several launches in one box, and mounting into a running box (#424)
Runtime half of the window streams contract (joins 1 and 6).

- nesinit runs any number of launches side by side, keyed by launch id.
Each process gets NESTRI_LAUNCH_ID
(nesprotocol::lifecycle::LAUNCH_ID_ENV), set after the caller's
environment so it cannot be overridden. Stop and restart reach one
launch only. A second launch under an id that is already running is
refused.
- A terminal launch ends the box only when no other launch is running,
so the box stops when its last launch exits. A box with one launch
behaves as before.
- New lifecycle messages, additive, no CONTROL_VERSION bump: host to
guest `mount {id, images, overlays}`; guest to host `launch_mounted
{id}` / `launch_mount_failed {id, reason}`. A failed mount does not take
the box down.
- A mount source that is a regular file (in a virtiofs share) is
attached to a loop device first (LOOP_CONFIGURE, autoclear), because
nesbox cannot hot-add block devices to a running VM. The guest kernel
fragment gains CONFIG_BLK_DEV_LOOP=y, so this needs a new guest
kernel/image to work end to end.

Tests: cargo test -p nesinit (117 passed) and the nesprotocol lifecycle
tests on nestripc-1. New session tests cover two launches side by side,
refusing a duplicate id, stopping one launch, the box ending with its
last launch, and mount success/failure/before boot. Not run in a real
box.

Companion: nestrilabs/nescore feat/window-streams-runtime (neslet
launch.start/launch.stop, nesteam --join-compositor).

Content layout and trust:
- Game and compat images come from a read-only virtiofs share
`launch-images` (mounted read-only at
/nestri/launch-images/<launchId>/build.erofs and compat.erofs). The
per-launch writable layer is in the read-write share `launches`
(/nestri/launches/<launchId>/upper.ext4). Which shares exist is decided
host-side in the boot descriptor; nesinit mounts what it is told.
- The share's only guest-writable files are the per-launch upper.ext4
files.
- Mount sources are opened with openat2(RESOLVE_NO_SYMLINKS): a link at
any component is refused, and only block devices and regular files are
accepted. Loop attach and mounts run on the blocking pool, so other
launches' exits and stops are not stalled.
- CONFIG_BLK_DEV_LOOP must ship in the guest kernel together with this
nesinit (build/kernel/nestri.fragment has it); without it a mount into a
running box fails with a launch_mount_failed.
2026-10-17 16:37:05 +03:00

1012 lines
39 KiB
Rust

// The lifecycle layer of the control channel between a box and whatever runs
// it: the document describing the box, the commands that run things inside it,
// and what the guest says back about carrying either out.
//
// It lives beside the media types for the same reason they live here — one
// definition, so the two ends cannot drift from each other silently.
//
// Nothing in this module describes *what* the guest runs. A set of share tags,
// a command line, and what an exit means: that is the whole vocabulary, and a
// field that only makes sense for one kind of workload does not belong in it.
// ref(d-0033)
//
// # The box outlives what runs in it
//
// The guest init is resident: it mounts what the descriptor names, brings up
// the box's service stack, says so, and then takes commands for as long as the
// box lives. So the descriptor describes the *box* — which shares are mounted
// where — and a command describes an occupant. A box may be launched into many
// times. ref(d-0064)
//
// That is why every launch carries an id and every event about a launch carries
// it back. Without one, a second launch's exit is indistinguishable from the
// first's, which reads as an ended session that keeps billing or a running one
// reported as stopped.
//
// # What is deliberately absent
//
// **Output geometry.** The compositor wraps the workload rather than running as
// a service, so it is started by a launch with that launch's geometry in its own
// argv, and the numbers appear nowhere else. Two sources of truth for one number
// is a worse failure than either choice, because the wrong one is used silently.
//
// The channel also carries a second layer, which the guest relays as opaque
// bytes and never parses. Those types land with the relay that needs them.
use std::collections::BTreeMap;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
/// The vsock port the guest dials.
///
/// The guest dials out rather than being connected to, which is worth keeping
/// for two reasons: the listener is up before the VM starts, so nothing races a
/// booting kernel and nothing has to retry; and the connection establishing is
/// itself the liveness signal, without which a caller needs a timeout to tell a
/// slow boot from a dead one.
pub const CONTROL_PORT: u32 = 7000;
/// The vsock port an attached shell's bytes travel on.
///
/// The host sends [`HostToGuest::Attach`] on the control channel and the guest
/// answers by dialling this, the same direction the control channel itself goes,
/// so nothing in the box has to listen. The stream is the frames in
/// [`crate::attach`]. It is a port of its own because a screenful of output on
/// the control channel would hold every other message in the box behind it.
pub const ATTACH_PORT: u32 = 7001;
/// Version of this layer. Both ends compare it during the handshake and refuse
/// on mismatch, so a guest built against one version meeting a caller built
/// against another fails immediately and legibly, rather than later on a field
/// that turned out to be missing.
///
/// Adding a variant or a field does not need a bump; removing or renaming one
/// does.
///
/// Version 3 took three fields off the descriptor and put an id on three
/// messages, so a version-2 peer and a version-3 peer do not talk at all.
/// There is deliberately no shim: nothing is deployed, and a shim would be the
/// second definition of this wire that one shared crate exists to prevent.
///
/// Version 4 replaced the descriptor's `drives` with `overlays`: a build is a
/// read-only image now, and a box writes into a layer of its own over it.
///
/// Version 5 added `images`: a read-only image mounted on its own, which is how
/// the compatibility layer reaches a box now that the guest image no longer
/// carries one. It is a bump although it is only a field, because the
/// descriptor refuses fields it does not know and a guest image without that
/// layer is useless to a host that does not send one: the mismatch should be
/// named at the handshake and not found as a launch that cannot start.
pub const CONTROL_VERSION: u32 = 5;
/// The variable a launched process finds its launch id in.
///
/// Set by the guest on every launch, over anything the caller put in the
/// launch's own environment, because the id on the message is the one every
/// report about the launch carries. What reads it: the compositor, to say
/// which launch a window belongs to (`/proc/<pid>/environ` of the window's
/// owner), and so a client can find its own window. ref(d-0085)
pub const LAUNCH_ID_ENV: &str = "NESTRI_LAUNCH_ID";
/// The command to run, and who runs it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Exec {
/// The program and its arguments. Never a shell string: a guest that splits
/// words is a guest that can split them differently than the caller meant.
pub argv: Vec<String>,
/// Environment for the process. Sorted, so two descriptors that say the
/// same thing serialize identically.
#[serde(default)]
pub env: BTreeMap<String, String>,
/// Working directory. `None` means the root of the guest filesystem.
#[serde(default)]
pub cwd: Option<String>,
/// The uid and gid to drop to before exec.
///
/// These are load-bearing rather than hygiene. Whoever writes this
/// descriptor is also whoever exported the writable share, so the ids have
/// to agree; when they do not, the share refuses the first write and the
/// failure surfaces here as `EACCES` with a path, instead of as a workload
/// that misbehaves much later for no visible reason.
pub uid: u32,
pub gid: u32,
}
/// One share to mount, named by tag.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Mount {
/// The share's tag. Never a path on the other side of the channel — the
/// guest learns nothing about the filesystem it is being handed a piece of.
pub tag: String,
/// Where it lands inside the guest.
///
/// The caller names this, not the guest: choosing a mount point means
/// knowing what the workload expects to find there, which is exactly the
/// knowledge a workload-independent init does not have. ref(d-0033)
pub at: String,
#[serde(default)]
pub ro: bool,
}
/// A read-only block device with a writable one layered over it.
///
/// This is how a game's install reaches a box. The build is an EROFS image
/// every box on the host shares, and the box's own writes land on an ext4 of
/// its own that is thrown away with it; the guest stacks the two with
/// overlayfs, so a game that writes into its install directory works and the
/// build under it cannot change.
///
/// Stacked in the guest rather than on the host because the host has no
/// filesystem it can do it on: the host-side equivalent was a ZFS clone, and a
/// host that needs ZFS is what this replaced.
///
/// There are no mount options on this and that is deliberate: how each layer
/// is mounted is a property of how it was built -- EROFS read-only, a
/// journal-less ext4 upper, `nosuid`, `nodev` -- and not something a
/// descriptor is in a position to know.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Overlay {
/// The read-only build image, as the guest names the device.
pub lower: String,
/// The box's writable layer, as the guest names the device.
pub upper: String,
/// Where the stacked result lands.
pub at: String,
}
/// A read-only filesystem image, mounted where the descriptor says.
///
/// What reaches a box this way is something every box on a host shares and none
/// of them writes: the compatibility layer a Windows title runs under. Unlike
/// an [`Overlay`] there is no writable layer over it, so anything that writes
/// into its own directory fails, and that is the point -- two boxes cannot
/// disagree about what is in it.
///
/// Mounted as EROFS, with the same guards every layer has (`nosuid`, `nodev`)
/// and without `noexec`, because the programs in it are what gets run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Image {
/// The block device, as the guest names it.
pub device: String,
/// Where it lands inside the guest.
pub at: String,
}
/// Names one launch, for as long as anything has something to say about it.
///
/// Minted by the caller and only ever echoed by the guest. A guest that
/// generated these would be naming things the caller then has to correlate
/// against something else.
///
/// Opaque on purpose: nothing in this layer parses it, and a caller that wants
/// meaning in it can put meaning in it without this crate having an opinion.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LaunchId(pub String);
impl LaunchId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for LaunchId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// Names one attached shell, for as long as the connection that carries it.
///
/// Minted by the host and echoed by the guest in the first frame of the stream,
/// which is how the host knows which waiting command line a connection belongs
/// to. Not a [`LaunchId`]: a shell is not a launch and has no exit that means
/// anything to the session.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AttachId(pub String);
impl AttachId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for AttachId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// A terminal's size, in character cells.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Winsize {
pub cols: u16,
pub rows: u16,
}
/// What the workload exiting means for the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnExit {
/// Whether the exit ends the session.
///
/// This says what an exit *means*; it is not a restart policy. The guest
/// reports the exit and stops, and starting something again is a new
/// command from the caller — the only end that can see whether restarting
/// is repair or a loop. ref(d-0033)
///
/// It rides on the launch rather than on the descriptor, because a box that
/// can be launched into repeatedly cannot have one answer to this fixed at
/// boot. ref(d-0064)
pub terminal: bool,
}
/// What the box *is*, in one document: the shares it has and where they land.
///
/// Sent once, immediately after the handshake, and read once. Deliberately not
/// a conversation: this much is a document, and a document cannot half-arrive.
/// What runs *in* the box is a conversation, and a separate one — see
/// [`HostToGuest::Launch`]. ref(d-0064)
///
/// An empty `mounts` is legitimate. A box with nothing mounted still boots and
/// still brings up its services.
///
/// `deny_unknown_fields` is load-bearing rather than strictness for its own
/// sake. A descriptor still carrying a command line is a caller that has not
/// been updated, and the default behaviour — ignore what it does not recognise —
/// would mount the shares, silently drop the command, and leave a box that came
/// up correctly and runs nothing. Refusing it says so instead.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BootDescriptor {
#[serde(default)]
pub mounts: Vec<Mount>,
#[serde(default)]
pub overlays: Vec<Overlay>,
/// Read-only images with nothing over them. Left out of the wire form when
/// there are none, so a descriptor that needs none reads the same as before.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub images: Vec<Image>,
/// What the box may spend on video.
///
/// Here rather than on a launch because its consumer is `neshub`, which is
/// a service and comes up with the box. Geometry went the other way for the
/// same reason: its consumer is the compositor, which is started per launch.
/// A number travels to where the thing that reads it is started.
#[serde(default)]
pub video: VideoLimits,
}
/// Ceilings on what a box's video may cost.
///
/// A struct rather than a bare number so the next video-shaped limit joins it
/// instead of arriving loose alongside it.
///
/// Note what `deny_unknown_fields` on [`BootDescriptor`] means for this: a host
/// that sends `video` to a guest too old to know the field is *refused*, not
/// quietly accepted. That is the intended direction of failure -- the
/// alternative is a box that comes up, streams, and ignores the ceiling it was
/// given, which is exactly the shape of failure this stack produces too easily.
/// The guest image is rebuilt before a host starts sending it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VideoLimits {
/// Ceiling on the video bitrate, in kbps.
///
/// `None` means nobody said, which is not the same as zero and is not the
/// same as unlimited. A reader that was told nothing should say so and pick
/// a conservative default of its own; a reader that treats "unsaid" as
/// "unlimited" reproduces the bug this exists to fix, where every session
/// offered 10 Mbps because nothing had ever set a number.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub bitrate_kbps: Option<u32>,
}
/// How a workload ended.
///
/// Exactly one of these is set: a process that was signalled has no exit code,
/// and reporting `0` for one would make a kill look like a clean run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Exit {
#[serde(skip_serializing_if = "Option::is_none", default)]
pub exit_code: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub signal: Option<i32>,
}
impl Exit {
pub fn code(code: i32) -> Self {
Self {
exit_code: Some(code),
signal: None,
}
}
pub fn signal(signal: i32) -> Self {
Self {
exit_code: None,
signal: Some(signal),
}
}
}
/// What the guest says.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum GuestToHost {
/// First line on the connection, before anything else is read or written.
///
/// **This is the handshake, not readiness.** It says a connection exists
/// and both ends speak the same version. Whether anything in the box works
/// is [`GuestToHost::Initialized`], which is a different fact and must not
/// be merged with this one — a caller that treats this as readiness has a
/// wait stage that succeeds before the guest has started anything.
Ready { protocol_version: u32 },
/// Every share the descriptor named is where it said to put it.
Mounted,
/// A share could not be mounted, in the words the operating system used.
///
/// Kept separate from `StartFailed` because the two want different things
/// looked at: a share that did not appear and a command that did not run
/// are not the same incident.
MountFailed { reason: String },
/// The box's own services are up and it will accept launches.
///
/// The one fact a caller waits on before it may launch anything. It names
/// what came up, so a log says which — an empty list is a box with no
/// service stack, which is legitimate and worth being able to see.
Initialized {
#[serde(default)]
services: Vec<String>,
},
/// The box's services could not be brought up, in the words of whatever
/// refused.
///
/// Kept separate from [`GuestToHost::MountFailed`] and
/// [`GuestToHost::StartFailed`] for the reason those two are separate from
/// each other: a share that did not appear, a box that could not be made,
/// and a command that did not run are three incidents that want three
/// different things looked at. A box in this state cannot be launched into
/// at all, which is what distinguishes it from a refused launch.
InitFailed { reason: String },
/// A service in the box's own stack exited.
///
/// **Reported, never repaired.** Nothing else in the guest is watching
/// these, so a death that is not said here is a box that looks healthy and
/// cannot work. Restarting one is a decision for whoever can see whether
/// restarting is repair or a loop, and that is not this end. ref(d-0064)
ServiceDied {
name: String,
#[serde(flatten)]
exit: Exit,
},
/// The shell with this id could not be started, in the words the operating
/// system used. Said on the control channel because nothing has connected to
/// the data port yet, and a host that heard nothing would wait out a timeout
/// to find out.
AttachFailed { id: AttachId, reason: String },
/// The launch with this id is running.
Started { id: LaunchId },
/// The launch with this id could not be run, in the words the operating
/// system used.
StartFailed { id: LaunchId, reason: String },
/// The launch with this id has ended. Terminal or not is the launch's own
/// answer, not this message's.
WorkloadExited {
id: LaunchId,
#[serde(flatten)]
exit: Exit,
},
/// Everything a [`HostToGuest::Mount`] for this launch named is in place.
///
/// Answers that command and nothing else: the boot descriptor's own mounts
/// are still answered by [`GuestToHost::Mounted`], once.
LaunchMounted { id: LaunchId },
/// A [`HostToGuest::Mount`] for this launch could not be carried out, in
/// the operating system's words. The box stays up: a game whose image will
/// not mount is one launch that cannot start, not a box that cannot work.
LaunchMountFailed { id: LaunchId, reason: String },
/// How a client reaches this box's media, once it is known.
Ticket { ticket: String },
/// How many clients are watching this box. Sent once when first known and
/// again whenever it changes, so a host can tell a run nobody is using
/// from one somebody is. A host that does not know it skips it.
Viewers { count: u32 },
/// Bytes from the workload, relayed. See [`Payload`].
Payload {
#[serde(flatten)]
payload: Payload,
},
}
/// What the guest is told.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HostToGuest {
/// The boot descriptor. One per connection.
Boot {
#[serde(flatten)]
descriptor: Box<BootDescriptor>,
},
/// Run something in the box. Any number of times, after `initialized`.
///
/// The caller mints `id` and every message about this launch carries it
/// back. `on_exit` belongs here rather than on the descriptor because a box
/// that can be launched into repeatedly has one answer per launch, not one
/// per boot. ref(d-0064)
Launch {
id: LaunchId,
exec: Exec,
on_exit: OnExit,
},
/// Mount content for a launch into a box that is already running.
///
/// How a second game reaches a box: the host already holds its build, and
/// the box mounts it on request rather than at boot. ref(d-0085) The same
/// shapes as the descriptor's, carried out in the same order (images, then
/// overlays), and answered with [`GuestToHost::LaunchMounted`] or
/// [`GuestToHost::LaunchMountFailed`] for this id.
///
/// A device here may also be a regular file inside a share, which the
/// guest attaches to a loop device first: a box cannot be given a new
/// block device once it has booted.
///
/// Added without a version bump, as an addition: a guest that predates it
/// skips the line, and the host's wait for the answer is what notices.
Mount {
id: LaunchId,
#[serde(default)]
images: Vec<Image>,
#[serde(default)]
overlays: Vec<Overlay>,
},
/// Stop one launch. Idempotent, and does not end the session.
Stop { id: LaunchId },
/// Stop one launch and start it again with the same command.
///
/// **Defined as a kill followed by a launch of the same `Exec`, and nothing
/// more.** No retry, no backoff, no policy of any kind in the guest — it
/// exists as one message only because a caller sending two has the same
/// effect with a worse race in it. The relaunch keeps the id. ref(d-0064)
Restart { id: LaunchId },
/// Run something on a terminal and connect it to the host on
/// [`ATTACH_PORT`].
///
/// **Not a launch.** It has no `on_exit`, because nothing it does ends the
/// session, and it is not the running launch, so a shell can come and go
/// while a game plays. `size` present means a person is at a terminal and the
/// PTY is an ordinary one; absent means a command is being run for its
/// output, and the PTY is put in raw mode so it is a byte pipe and not a
/// terminal that rewrites line endings.
Attach {
id: AttachId,
exec: Exec,
#[serde(default)]
size: Option<Winsize>,
},
/// Shut the guest down.
Shutdown,
/// Bytes for the workload, relayed. See [`Payload`].
Payload {
#[serde(flatten)]
payload: Payload,
},
}
/// The second layer of the channel: bytes the guest carries and never reads.
///
/// `body` is a string rather than nested JSON, and that is the structural part
/// of it. A document the guest can index into is a document the guest can grow
/// to depend on, and then this layer is no longer opaque and the boundary it
/// exists to draw is gone.
///
/// **An envelope is never logged.** Not the body, not truncated, not at debug
/// level. The channel name and the byte count are the whole of what may be
/// said about one, because what crosses here includes credentials meant for
/// the workload and nothing else. ref(d-0033)
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Payload {
/// Which conversation this belongs to. Loggable.
pub channel: String,
/// Opaque bytes. Never logged, never parsed, never inspected.
pub body: String,
}
impl Payload {
pub fn new(channel: impl Into<String>, body: impl Into<String>) -> Self {
Self {
channel: channel.into(),
body: body.into(),
}
}
/// What may be said about an envelope, and all of it.
pub fn summary(&self) -> String {
format!("{} ({} bytes)", self.channel, self.body.len())
}
}
/// Written by hand, and it is load-bearing: a derived `Debug` puts the body
/// one careless `{:?}` away from a log line.
impl std::fmt::Debug for Payload {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Payload")
.field("channel", &self.channel)
.field("body", &format_args!("<{} bytes>", self.body.len()))
.finish()
}
}
/// Encode one message as a line, framing included.
///
/// Newline-delimited JSON: the channel is a byte stream, so it needs a frame,
/// and a frame a person can read in a log of the channel itself is worth more
/// here than a compact one.
pub fn to_line<T: Serialize>(message: &T) -> Result<String, serde_json::Error> {
let mut line = serde_json::to_string(message)?;
line.push('\n');
Ok(line)
}
/// Decode one line. The trailing newline is optional, so a caller may pass what
/// a line-oriented reader handed it either way.
pub fn from_line<T: DeserializeOwned>(line: &str) -> Result<T, serde_json::Error> {
serde_json::from_str(line.trim_end_matches(['\n', '\r']))
}
#[cfg(test)]
mod tests {
use super::*;
fn descriptor() -> BootDescriptor {
BootDescriptor {
mounts: vec![Mount {
tag: "install".into(),
at: "/mnt/install".into(),
ro: true,
}],
overlays: Vec::new(),
images: Vec::new(),
video: VideoLimits::default(),
}
}
fn exec() -> Exec {
Exec {
argv: vec!["/usr/bin/true".into()],
env: BTreeMap::from([("HOME".to_string(), "/mnt/user".to_string())]),
cwd: Some("/mnt/user".into()),
uid: 1000,
gid: 1000,
}
}
/// A mount for a running box is named by its launch on the wire, both ways,
/// and an empty list may be left out.
#[test]
fn a_mount_into_a_running_box_round_trips_by_launch() {
let mount = HostToGuest::Mount {
id: LaunchId::new("launch_01"),
images: Vec::new(),
overlays: vec![Overlay {
lower: "/nestri/launch-images/launch_01/build.erofs".into(),
upper: "/nestri/launches/launch_01/upper.ext4".into(),
at: "/nestri/installs/launch_01".into(),
}],
};
let line = to_line(&mount).unwrap();
assert!(line.contains(r#""type":"mount""#), "{line}");
assert_eq!(from_line::<HostToGuest>(&line).unwrap(), mount);
let bare: HostToGuest = from_line(r#"{"type":"mount","id":"launch_02"}"#).unwrap();
assert_eq!(
bare,
HostToGuest::Mount {
id: LaunchId::new("launch_02"),
images: Vec::new(),
overlays: Vec::new(),
}
);
let failed = GuestToHost::LaunchMountFailed {
id: LaunchId::new("launch_01"),
reason: "ENOENT".into(),
};
let line = to_line(&failed).unwrap();
assert!(line.contains(r#""type":"launch_mount_failed""#), "{line}");
assert_eq!(from_line::<GuestToHost>(&line).unwrap(), failed);
let line = to_line(&GuestToHost::LaunchMounted {
id: LaunchId::new("launch_01"),
})
.unwrap();
assert!(line.contains(r#""type":"launch_mounted""#), "{line}");
}
#[test]
fn a_line_round_trips() {
let line = to_line(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.unwrap();
assert!(line.ends_with('\n'), "a line has to carry its own frame");
assert!(!line.trim_end().contains('\n'), "one message is one line");
let back: HostToGuest = from_line(&line).unwrap();
assert_eq!(
back,
HostToGuest::Boot {
descriptor: Box::new(descriptor())
}
);
}
#[test]
fn a_launch_round_trips_with_its_id() {
let launch = HostToGuest::Launch {
id: LaunchId::new("l-1"),
exec: exec(),
on_exit: OnExit { terminal: true },
};
let back: HostToGuest = from_line(&to_line(&launch).unwrap()).unwrap();
assert_eq!(back, launch);
}
/// The reason ids exist: a caller has to be able to tell which launch it is
/// being told about, or the second one's exit overwrites the first's record.
#[test]
fn every_event_about_a_launch_carries_the_launch_it_is_about() {
let first = LaunchId::new("l-1");
let second = LaunchId::new("l-2");
let events = [
GuestToHost::Started { id: first.clone() },
GuestToHost::StartFailed {
id: first.clone(),
reason: "ENOENT".into(),
},
GuestToHost::WorkloadExited {
id: first.clone(),
exit: Exit::code(0),
},
];
for event in events {
let line = to_line(&event).unwrap();
assert!(
line.contains(first.as_str()) && !line.contains(second.as_str()),
"an event does not say which launch it is about: {line}"
);
let back: GuestToHost = from_line(&line).unwrap();
assert_eq!(back, event);
}
}
/// The descriptor describes the box. A caller still sending a command in it
/// has not been updated, and the cost of accepting one quietly is a box that
/// mounts, comes up, and runs nothing.
#[test]
fn a_descriptor_carrying_a_command_is_refused_rather_than_ignored() {
let stale = r#"{"exec":{"argv":["/bin/sh"],"uid":1000,"gid":1000},
"mounts":[],
"geometry":{"width":1280,"height":720,"fps":60},
"on_exit":{"terminal":true}}"#;
let parsed: Result<BootDescriptor, _> = from_line(stale);
assert!(
parsed.is_err(),
"a descriptor with a command in it parsed: {parsed:?}"
);
}
/// Geometry is in the launched argv and nowhere else, so there is no field
/// here for it to disagree with.
#[test]
fn geometry_is_not_on_this_layer() {
let line = to_line(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.unwrap();
for named in ["width", "height", "fps", "hdr", "geometry"] {
assert!(
!line.contains(named),
"the descriptor names {named}, which belongs in the launch: {line}"
);
}
}
/// A dead service is not a dead workload: they are different incidents and
/// want different things looked at.
#[test]
fn a_dead_service_says_which_one_and_how() {
let died = GuestToHost::ServiceDied {
name: "pipewire".into(),
exit: Exit::signal(9),
};
let line = to_line(&died).unwrap();
assert!(line.contains("pipewire"), "no service name: {line}");
assert!(
!line.contains("exit_code"),
"a signalled service has no exit code: {line}"
);
let back: GuestToHost = from_line(&line).unwrap();
assert_eq!(back, died);
}
/// `ready` is the handshake and `initialized` is the box working. A caller
/// waiting on the wrong one succeeds before anything has started.
#[test]
fn readiness_and_initialisation_are_two_messages() {
let ready = to_line(&GuestToHost::Ready {
protocol_version: CONTROL_VERSION,
})
.unwrap();
let initialized = to_line(&GuestToHost::Initialized {
services: vec!["dbus".into(), "pipewire".into()],
})
.unwrap();
assert_ne!(ready, initialized);
// An empty stack is legitimate and has to survive the round trip, or a
// box with no services looks like a box that never came up.
let empty = GuestToHost::Initialized { services: vec![] };
let back: GuestToHost = from_line(&to_line(&empty).unwrap()).unwrap();
assert_eq!(back, empty);
}
#[test]
fn a_signalled_exit_is_not_a_zero_exit() {
let signalled = to_line(&GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::signal(9),
})
.unwrap();
assert!(
!signalled.contains("exit_code"),
"a signalled workload has no exit code: {signalled}"
);
let clean = to_line(&GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::code(0),
})
.unwrap();
assert!(
!clean.contains("signal"),
"a clean exit was not signalled: {clean}"
);
}
#[test]
fn an_envelope_does_not_print_its_body() {
let payload = Payload::new("identity", "a-credential-nobody-should-read");
let printed = format!("{payload:?}");
assert!(
!printed.contains("a-credential"),
"the body reached a log line: {printed}"
);
assert!(
printed.contains("identity"),
"the channel name is loggable: {printed}"
);
assert_eq!(payload.summary(), "identity (31 bytes)");
}
#[test]
fn an_envelope_body_stays_a_string_in_both_directions() {
// Nested JSON in the body has to survive as text: the moment it
// arrives as structure, this layer is one field access from being
// parsed.
let body = r#"{"looks":"structured"}"#;
let line = to_line(&GuestToHost::Payload {
payload: Payload::new("identity", body),
})
.unwrap();
let back: GuestToHost = from_line(&line).unwrap();
let GuestToHost::Payload { payload } = back else {
panic!("not an envelope: {line}")
};
assert_eq!(payload.body, body);
let line = to_line(&HostToGuest::Payload {
payload: Payload::new("identity", body),
})
.unwrap();
let back: HostToGuest = from_line(&line).unwrap();
let HostToGuest::Payload { payload } = back else {
panic!("not an envelope: {line}")
};
assert_eq!(payload.body, body);
}
#[test]
fn a_mount_failure_keeps_its_reason_verbatim() {
let reason = "EACCES: /mnt/user";
let line = to_line(&GuestToHost::MountFailed {
reason: reason.into(),
})
.unwrap();
let back: GuestToHost = from_line(&line).unwrap();
assert_eq!(
back,
GuestToHost::MountFailed {
reason: reason.into()
}
);
}
#[test]
fn defaults_cover_what_a_caller_may_leave_out() {
// A box with nothing mounted is a legitimate box.
let parsed: BootDescriptor = from_line("{}").unwrap();
assert!(parsed.mounts.is_empty());
let launch = r#"{"type":"launch","id":"l-1",
"exec":{"argv":["/bin/sh"],"uid":1000,"gid":1000},
"on_exit":{"terminal":false}}"#;
let HostToGuest::Launch { id, exec, on_exit } = from_line(launch).unwrap() else {
panic!("not a launch: {launch}")
};
assert_eq!(id, LaunchId::new("l-1"));
assert!(exec.env.is_empty());
assert_eq!(exec.cwd, None);
assert!(!on_exit.terminal);
}
}
#[cfg(test)]
mod video_limits_tests {
use super::*;
#[test]
fn a_descriptor_without_video_still_reads() {
// An older host says nothing about video. That has to keep working, and
// it has to be distinguishable from a host that said "no limit".
let d: BootDescriptor = serde_json::from_str(r#"{"mounts":[],"overlays":[]}"#).unwrap();
assert_eq!(d.video.bitrate_kbps, None);
}
#[test]
fn an_unsaid_ceiling_is_not_serialised() {
// So a host that has nothing to say produces the same bytes it always
// did, and an older guest keeps accepting it.
let d = BootDescriptor {
mounts: Vec::new(),
overlays: Vec::new(),
images: Vec::new(),
video: VideoLimits::default(),
};
let json = serde_json::to_string(&d).unwrap();
assert!(!json.contains("bitrate"), "{json}");
}
#[test]
fn a_ceiling_survives_the_round_trip() {
let d = BootDescriptor {
mounts: Vec::new(),
overlays: Vec::new(),
images: Vec::new(),
video: VideoLimits {
bitrate_kbps: Some(8_000),
},
};
let back: BootDescriptor =
serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
assert_eq!(back, d);
}
#[test]
fn zero_is_not_the_same_as_unsaid() {
// A reader that conflates them cannot tell "the host wants no video" from
// "the host never mentioned it", and the second must not be read as a
// licence to send whatever it likes.
let said: BootDescriptor = serde_json::from_str(r#"{"video":{"bitrate_kbps":0}}"#).unwrap();
let unsaid: BootDescriptor = serde_json::from_str("{}").unwrap();
assert_eq!(said.video.bitrate_kbps, Some(0));
assert_eq!(unsaid.video.bitrate_kbps, None);
}
#[test]
fn an_unknown_video_field_is_refused() {
// Same reasoning as the descriptor's own `deny_unknown_fields`: a limit
// this build does not understand is one it would otherwise ignore while
// reporting success.
let r: Result<BootDescriptor, _> =
serde_json::from_str(r#"{"video":{"bitrate_kbps":8000,"fps_cap":30}}"#);
assert!(r.is_err(), "an unknown video limit must not be ignored");
}
}
#[cfg(test)]
mod image_tests {
use super::*;
#[test]
fn a_descriptor_with_no_images_reads_and_writes_as_it_always_did() {
let d: BootDescriptor = serde_json::from_str(r#"{"mounts":[],"overlays":[]}"#).unwrap();
assert!(d.images.is_empty());
let json = serde_json::to_string(&d).unwrap();
assert!(!json.contains("images"), "{json}");
}
#[test]
fn an_image_survives_the_round_trip() {
let d = BootDescriptor {
mounts: Vec::new(),
overlays: Vec::new(),
images: vec![Image {
device: "/dev/vdd".into(),
at: "/nestri/compat".into(),
}],
video: VideoLimits::default(),
};
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains(r#""images":[{"device":"/dev/vdd","at":"/nestri/compat"}]"#));
let back: BootDescriptor = serde_json::from_str(&json).unwrap();
assert_eq!(back, d);
}
}
#[cfg(test)]
mod attach_tests {
use super::*;
#[test]
fn an_attach_round_trips_with_and_without_a_terminal() {
for size in [
Some(Winsize {
cols: 120,
rows: 40,
}),
None,
] {
let attach = HostToGuest::Attach {
id: AttachId::new("a-1"),
exec: Exec {
argv: vec!["/bin/bash".into()],
env: Default::default(),
cwd: None,
uid: 0,
gid: 0,
},
size,
};
let back: HostToGuest = from_line(&to_line(&attach).unwrap()).unwrap();
assert_eq!(back, attach);
}
}
/// A host that leaves `size` out is asking for a command, not a terminal.
#[test]
fn an_attach_with_no_size_is_not_a_terminal() {
let line = r#"{"type":"attach","id":"a-1","exec":{"argv":["/bin/true"],"uid":0,"gid":0}}"#;
let HostToGuest::Attach { size, .. } = from_line(line).unwrap() else {
panic!("not an attach")
};
assert_eq!(size, None);
}
#[test]
fn a_failed_attach_says_which() {
let failed = GuestToHost::AttachFailed {
id: AttachId::new("a-1"),
reason: "no such file".into(),
};
let back: GuestToHost = from_line(&to_line(&failed).unwrap()).unwrap();
assert_eq!(back, failed);
}
/// The attach port is not the control port.
#[test]
fn the_data_port_is_its_own() {
assert_ne!(ATTACH_PORT, CONTROL_PORT);
}
}