mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-01 23:40:13 +08:00
docs: fill the SDK documentation gaps and refresh the README's features (#110)
* docs: document snapshots, host commands, Tailscale, VA-API, fetchRoutes, UDP, the microphone and the camera in the SDK docs and README, and list the newer devices and uses in the README's introduction * docs: split the Display page into Display and Input, and Sound and Camera --------- Co-authored-by: Pooya Parsa <pooya@pi0.io>
This commit is contained in:
123
README.md
123
README.md
@@ -74,9 +74,13 @@ overlayfs, behaves as it does on a server, because it runs the same code.
|
||||
- **cgroups, namespaces, userfaultfd, fanotify and TUN**: enough for
|
||||
systemd to boot Ubuntu 26.10 to `multi-user.target`.
|
||||
- **Devices**: a [framebuffer (`/dev/fb0`), evdev keyboard, mouse and touch,
|
||||
sound through ALSA and `/dev/dsp`](#display-input-and-sound),
|
||||
[AF_VSOCK](#talk-over-vsock), and [shared memory](#share-memory) with the
|
||||
host.
|
||||
sound and a microphone through ALSA and `/dev/dsp`, a V4L2
|
||||
camera](#display-input-and-sound), [AF_VSOCK](#talk-over-vsock),
|
||||
[shared memory](#share-memory) with the host, a virtio-gpu with [guest
|
||||
GL](#gl-in-the-guest-browsers) and [Vulkan](#vulkan-in-the-guest-browsers-with-webgpu)
|
||||
on the page's WebGL2 and WebGPU, [VA-API video](#video-in-the-guest-browsers-with-webcodecs)
|
||||
on WebCodecs, and [serial ports](#serial-ports), [Bluetooth](#bluetooth)
|
||||
and [USB devices](#usb-devices) from Web Serial, Web Bluetooth and WebUSB.
|
||||
- **aarch64 user space**: ARMv8.0-A with FP and AdvSIMD plus the AES,
|
||||
PMULL, SHA1, SHA2, SHA512, SHA3, CRC32 and LSE atomics extensions, so
|
||||
distribution binaries and
|
||||
@@ -97,7 +101,19 @@ overlayfs, behaves as it does on a server, because it runs the same code.
|
||||
way; `community` is added the first time a command needs it.
|
||||
- **Run real runtimes and tools**: Node and npm, Python, OpenSSL, curl and
|
||||
`wget`, straight from the distribution. Debian 13 boots the same way as
|
||||
Alpine (`--distro debian`), with apt.
|
||||
Alpine (`--distro debian`), with apt. x86-64 and i386 binaries run too,
|
||||
through box64 on Debian and qemu-user on Alpine.
|
||||
- **Run desktop apps on the GPU** (Debian, in the browser): Wayland and X11
|
||||
apps open as windows of the page, such as Firefox, Chromium, Zed and Xfce.
|
||||
The guest's Mesa renders on the page's WebGL2 and its Vulkan on WebGPU,
|
||||
enough for 3D games and for llama.cpp and Ollama, and video decodes in the
|
||||
browser's own decoder through VA-API. The page's launcher installs and
|
||||
starts each app.
|
||||
- **Use real hardware from a page**: boards on [serial
|
||||
ports](#serial-ports) (esptool, arduino-cli, MicroPython through Thonny),
|
||||
BLE devices through BlueZ ([Bluetooth](#bluetooth)), and [USB
|
||||
devices](#usb-devices) through libusb (`adb`, `fastboot`, `dfu-util`), in
|
||||
Chromium-based browsers.
|
||||
- **[Write graphics and sound programs](#display-input-and-sound)** against
|
||||
`/dev/fb0`, evdev and ALSA. Try `glimmer`, a tiny game with sound.
|
||||
- **[Embed Linux in your app](#-use-it-from-javascript)** with a
|
||||
@@ -105,14 +121,17 @@ overlayfs, behaves as it does on a server, because it runs the same code.
|
||||
[`unkernel`](https://www.npmjs.com/package/unkernel). The same kernel file
|
||||
runs in Node and in every supported browser, optionally [in a
|
||||
worker](#run-it-in-a-worker). [Disks](#add-disks) can be local ext4 images,
|
||||
http(s) images fetched by range, or a persistent disk in IndexedDB. The SDK
|
||||
http(s) images fetched by range, or a persistent disk in OPFS or
|
||||
IndexedDB. [Save a running machine](#save-and-restore-a-machine) and resume it
|
||||
later, and [join a tailnet](#join-a-tailnet) from Node or a page. The SDK
|
||||
is MIT-licensed, and there is no closed engine or license key behind it, so
|
||||
you can ship it in your product and host it wherever you like.
|
||||
- **Talk to the guest** through [terminal sessions](#run-programs), each
|
||||
with its own pty and shell, [host directories and in-memory file
|
||||
systems](#mount-host-files) mounted in the guest, [vsock byte
|
||||
streams](#talk-over-vsock) and [zero-copy shared memory](#share-memory),
|
||||
with no network in between.
|
||||
with no network in between. Guest programs can call your JavaScript as
|
||||
[host commands](#host-commands).
|
||||
- **Script and test**: [the CLI](#-run-it-from-the-terminal) types input on a
|
||||
schedule, stops on a timeout, and reports how the guest ended in its exit
|
||||
code.
|
||||
@@ -266,7 +285,8 @@ Devices are small paravirtual drivers that talk to the JavaScript host:
|
||||
[block](#add-disks) (kwblk), [network](#add-a-network) (kwnet, with a
|
||||
user-mode TCP/IP stack in JS), [display, input and
|
||||
sound](#display-input-and-sound) (kwfb, kwinput, kwsnd), a
|
||||
[camera](#display-input-and-sound) (kwcam, V4L2),
|
||||
[camera](#display-input-and-sound) (kwcam, V4L2), a
|
||||
[virtio-gpu](#gl-in-the-guest-browsers) (kwvirtio),
|
||||
[vsock](#talk-over-vsock) (kwvsock), [shared memory](#share-memory)
|
||||
(kwshm), [serial ports](#serial-ports) (kwserial),
|
||||
[Bluetooth](#bluetooth) (kwbt, an HCI transport) and a [USB host
|
||||
@@ -366,10 +386,24 @@ await createKernel({ net: wispBackend("wss://wisp.example/") }); // anywhere:
|
||||
|
||||
Networking is off unless you pass `net`. Any object with `connect` and
|
||||
`lookup` methods can carry the guest's TCP and DNS (and with a `udp`
|
||||
method its UDP), so you can write your own backend. Wisp carries no DNS and
|
||||
method its UDP), so you can write your own backend; `directBackend()` and
|
||||
`wispBackend()` carry UDP too (Wisp where the server does). Wisp carries no DNS and
|
||||
no half-close ([Known limits](#-known-limits)); `wispBackend(servers, {
|
||||
lookup })` takes a resolver of your own, such as DNS over HTTPS, for real
|
||||
addresses.
|
||||
addresses. With `hostLoopback` in the network spec, the guest reaches the
|
||||
host's 127.0.0.1 at the gateway, 10.0.2.2.
|
||||
|
||||
```js
|
||||
const net = fetchRoutes(wispBackend("wss://wisp.example/"), {
|
||||
"deb.debian.org": "https://debian-mirror.example", // http://deb.debian.org/x → https://debian-mirror.example/x
|
||||
"api.local": (req) => Response.json({ ok: true }), // your own handler
|
||||
});
|
||||
```
|
||||
|
||||
`fetchRoutes(inner, routes)` answers the guest's plain-HTTP requests to the
|
||||
named hosts with the host's `fetch()` and passes everything else to `inner`
|
||||
(`undefined`: nothing else). The page uses it to fetch Debian packages from
|
||||
a CORS mirror instead of through its Wisp proxy.
|
||||
|
||||
### Join a tailnet
|
||||
|
||||
@@ -430,7 +464,10 @@ const vm = await createKernel({
|
||||
template the kernel carries (`bundledBoot(module).datadisk`). In the
|
||||
browser, `openHttpDisk(url)` keeps your writes in IndexedDB and
|
||||
`openDataDisk()` gives you the persistent data disk that
|
||||
[the page](#-try-it-in-the-browser) uses. Anything that implements
|
||||
[the page](#-try-it-in-the-browser) uses, in IndexedDB or, several times
|
||||
faster, in the origin private file system (`backend: "opfs"`, for a kernel
|
||||
in a worker: `{ kind: "data", template: "bundled", backend: "opfs" }`);
|
||||
`migrateDataDisk()` moves one from IndexedDB to OPFS. Anything that implements
|
||||
`BlockDevice` works too, and a disk of your own can be the root:
|
||||
`cmdline: "console=hvc0 root=/dev/wda rw"` with `initrd: null`.
|
||||
|
||||
@@ -484,6 +521,30 @@ console.log((await zipped).length);
|
||||
With `pty: false` the program gets pipes: `stdin`, `stdout` and `stderr`
|
||||
web streams, byte for byte.
|
||||
|
||||
### Host commands
|
||||
|
||||
```js
|
||||
const vm = await createKernel({
|
||||
commands: {
|
||||
hello: (c) => `hello ${c.args.join(" ")} from the host\n`,
|
||||
upper: (c) => c.stdin.pipeThrough(new TextDecoderStream())
|
||||
.pipeThrough(new TransformStream({ transform: (s, out) => out.enqueue(s.toUpperCase()) }))
|
||||
.pipeTo(c.stdout),
|
||||
fail: () => ({ exitCode: 3 }),
|
||||
},
|
||||
});
|
||||
await vm.exec("sh", ["-c", "hello world | upper; fail; echo $?"]); // "HELLO WORLD FROM THE HOST\n3\n"
|
||||
await vm.addCommand("notify", (c) => console.log(c.args)); // at any time; removeCommand() too
|
||||
```
|
||||
|
||||
The reverse of `exec()`: each name becomes `/run/kw/bin/NAME` in the guest,
|
||||
first on `PATH`, and a guest process that runs it is a real process whose
|
||||
arguments, environment, working directory and stdio (web streams; stdin is
|
||||
read only as you read it) the function gets, with a `signal` that aborts when
|
||||
it is killed. What the function returns ends it: nothing or a number is
|
||||
its exit status, a string or bytes go to its stdout, `{ signal: "TERM" }`
|
||||
kills it, and a throw prints the message and exits 1.
|
||||
|
||||
### Mount host files
|
||||
|
||||
```js
|
||||
@@ -746,6 +807,48 @@ by readback); vkcube, vkmark, SDL's GPU API and GTK 4's Vulkan renderer run
|
||||
on it. Node has no WebGPU, so there `vk` is ignored with a log line.
|
||||
[vk/PROTOCOL.md](vk/PROTOCOL.md) has the design.
|
||||
|
||||
### Video in the guest (browsers with WebCodecs)
|
||||
|
||||
```js
|
||||
const vm = await createKernel({ distro: "/distros/debian.erofs", gl: true, gpu: true, va: true });
|
||||
await vm.exec("sudo", ["apt-get", "install", "-y", "vainfo"]);
|
||||
const r = await vm.exec("vainfo"); // the kwva driver and the profiles it decodes
|
||||
```
|
||||
|
||||
The base carries a VA-API driver that Debian's libva loads for the
|
||||
virtio-gpu device by itself. It hands each picture to a WebCodecs
|
||||
`VideoDecoder` on the page, so the guest's ffmpeg, mpv and Chromium decode
|
||||
VP9, H.264, AV1 and HEVC in the browser's decoder (in hardware where it has
|
||||
one), and ffmpeg's `vp9_vaapi` encodes on a `VideoEncoder`. Pictures come
|
||||
back as NV12, or with `gl` as dmabufs filled on the GPU (mpv's
|
||||
`--hwdec=vaapi --vo=dmabuf-wayland`). `vm.va.status` lists what is offered.
|
||||
Node has no WebCodecs, so there `va` is ignored with a log line.
|
||||
[va/PROTOCOL.md](va/PROTOCOL.md) has the design.
|
||||
|
||||
### Save and restore a machine
|
||||
|
||||
```js
|
||||
import { createKernel, decodeSnapshot, encodeSnapshot } from "unkernel";
|
||||
|
||||
const sh = await vm.spawn("sh", [], { detachable: true }); // survives the restore
|
||||
await vm.snapshot({ commit: (snap) => writeFile("vm.snap", encodeSnapshot(snap)) }); // stored, then stopped
|
||||
|
||||
const snap = decodeSnapshot(await readFile("vm.snap"));
|
||||
const restored = await createKernel({ distro, restore: snap }); // same kernel, disks and devices
|
||||
const again = await restored.attach(snap.ttys[0]);
|
||||
```
|
||||
|
||||
The kernel parks every task, so a snapshot is the guest's memory (free
|
||||
pages and, when it stops, the clean file cache left out: the idle base
|
||||
shell in a 2 GiB guest saved to 46 MiB on 2026-11-30) plus a few host values. `snapshot()` alone lets
|
||||
the machine run on, `{ stop: true }` stops it, and `{ commit }` stops it only
|
||||
once the snapshot is stored, so a failed save never loses the machine.
|
||||
Disks are not copied: a restore needs the same disks, unwritten since, and
|
||||
the same devices and CPU count, or `createKernel()` rejects with the reason.
|
||||
Host mounts and detachable sessions survive; other vsock sessions and TCP
|
||||
connections are reset. The CLI's `--input '{save=FILE}'` and `--restore
|
||||
FILE` use it, and the page suspends a session with it.
|
||||
|
||||
### Run it in a worker
|
||||
|
||||
```js
|
||||
|
||||
@@ -90,10 +90,19 @@ Changes to the root file system stay in memory, unless a persistent data disk (l
|
||||
|
||||
::card
|
||||
---
|
||||
title: Display, input and sound
|
||||
title: Display and input
|
||||
icon: ph:monitor-duotone
|
||||
to: /sdk/display
|
||||
---
|
||||
A framebuffer, evdev input and ALSA sound.
|
||||
A framebuffer, keyboard and mouse.
|
||||
::
|
||||
|
||||
::card
|
||||
---
|
||||
title: Sound and camera
|
||||
icon: ph:speaker-high-duotone
|
||||
to: /sdk/sound
|
||||
---
|
||||
ALSA playback and capture, and a V4L2 camera.
|
||||
::
|
||||
::
|
||||
|
||||
32
docs/1.sdk/10.display.md
Normal file
32
docs/1.sdk/10.display.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
icon: ph:monitor-duotone
|
||||
---
|
||||
|
||||
# Display and Input
|
||||
|
||||
> A framebuffer, a keyboard and a mouse for guest programs.
|
||||
|
||||
```js
|
||||
import { createKernel, domCodeToLinux } from "unkernel";
|
||||
|
||||
const vm = await createKernel({
|
||||
display: { width: 800, height: 600 }, // the guest gets /dev/fb0
|
||||
onDisplay: (mode) => console.log(mode), // a program opened it (its mode) or closed it (null)
|
||||
});
|
||||
|
||||
const frame = vm.frame(); // RGBA, or null while nothing draws
|
||||
if (frame) ctx.putImageData(new ImageData(frame.data, frame.width, frame.height), 0, 0);
|
||||
|
||||
addEventListener("keydown", (e) => {
|
||||
const key = domCodeToLinux(e.code);
|
||||
if (key && vm.evdev.keyboardOpen) vm.evdev.key(key, true);
|
||||
});
|
||||
```
|
||||
|
||||
`display` is `true` (640x480), a size, or a function that returns the size each time a program first opens the device, such as the window's size. A program may set its own mode, and `onDisplay` reports every change. `frame()` reads the latest picture and `readFrame()` waits for a fresh one.
|
||||
|
||||
## Input
|
||||
|
||||
With a display, the guest also gets a keyboard and a mouse (evdev, `/dev/input/event0` and `event1`). `evdev` has `key()`, and `button()`, `move()`, `moveTo()` and `wheel()` for a mouse or tablet. `onInput` tells you when a program opens the keyboard and mouse; until then, send keys to the console.
|
||||
|
||||
For guest GL, Vulkan and a virtio-gpu display, see [GL, Vulkan and Video](/sdk/graphics). For sound, see [Sound and Camera](/sdk/sound).
|
||||
61
docs/1.sdk/11.sound.md
Normal file
61
docs/1.sdk/11.sound.md
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
icon: ph:speaker-high-duotone
|
||||
---
|
||||
|
||||
# Sound and Camera
|
||||
|
||||
> A sound card with playback and capture, and a V4L2 camera, for guest programs.
|
||||
|
||||
```js
|
||||
import { createKernel, pcmToFloat32 } from "unkernel";
|
||||
|
||||
const vm = await createKernel({
|
||||
sound: { onChunk: ({ data, format }) => play(pcmToFloat32(data, format)) }, // ALSA hw:0,0 and /dev/dsp
|
||||
});
|
||||
```
|
||||
|
||||
`sound` gives the guest a sound card (ALSA `hw:0,0` and OSS `/dev/dsp`): `true` drops what it plays, or a sink receives the PCM chunks with their format and the playback state.
|
||||
|
||||
## Sound in browsers
|
||||
|
||||
`createAudioOut()` plays the guest's sound with Web Audio:
|
||||
|
||||
```js
|
||||
import { createAudioOut, createKernel } from "unkernel/web";
|
||||
|
||||
button.hidden = true;
|
||||
const audio = createAudioOut({
|
||||
onChange: (state) => {
|
||||
button.hidden = state !== "waiting"; // "click to play"
|
||||
},
|
||||
});
|
||||
const vm = await createKernel({ sound: audio });
|
||||
button.onclick = () => audio.resume(); // or any other click or key press on the page
|
||||
```
|
||||
|
||||
Browsers start sound only after a click, tap or key press on the page. Until then the latest `holdSeconds` (10) of what the guest plays are held: a clip that has ended by then plays whole, a stream joins live. `audio.muted = true` silences it.
|
||||
|
||||
One sink serves one kernel at a time, and outlives it: pass it to the next kernel, or `close()` it.
|
||||
|
||||
## Microphone
|
||||
|
||||
`soundIn` gives the sound card a capture substream: what `arecord` records, or a read of `/dev/dsp`. `createAudioIn()` from `unkernel/web` is the user's microphone. It is asked for only when a guest program starts recording and released when the program closes the device; until then the guest records silence. Anywhere else, `true` records silence, or a source's `read(out, rate)` fills `out` with mono samples in [-1, 1].
|
||||
|
||||
```js
|
||||
import { createAudioIn, createAudioOut, createKernel } from "unkernel/web";
|
||||
|
||||
const vm = await createKernel({ sound: createAudioOut(), soundIn: createAudioIn() });
|
||||
```
|
||||
|
||||
## Camera
|
||||
|
||||
`camera` gives the guest `/dev/video0`, a V4L2 device with I420, NV12 and YUYV up to 1280x720 at 30 frames a second, for `v4l2-ctl`, ffmpeg, GStreamer or a browser in the guest. `createCamera()` from `unkernel/web` is the user's camera. It is asked for only when a guest program starts streaming and released when the program stops; until then the guest gets black frames. Anywhere else, `true` gives black frames, or a source's `read(out, format)` writes the current frame in the stream's format.
|
||||
|
||||
```js
|
||||
import { createCamera, createKernel } from "unkernel/web";
|
||||
|
||||
const vm = await createKernel({ camera: createCamera() });
|
||||
// in the guest: ffmpeg -f v4l2 -input_format h264 -i /dev/video0 -c:v copy out.mkv
|
||||
```
|
||||
|
||||
Where the browser's `VideoEncoder` makes H.264, the camera offers it too, encoded on the host, so the guest copies the stream instead of encoding it, as with a webcam that encodes. The CLI's `--camera` shows a test pattern, and `--camera=h264` also offers it as H.264.
|
||||
@@ -2,12 +2,12 @@
|
||||
icon: ph:cube-duotone
|
||||
---
|
||||
|
||||
# GL and Vulkan
|
||||
# GL, Vulkan and Video
|
||||
|
||||
> Guest GL on the page's WebGL2 and guest Vulkan on its WebGPU.
|
||||
> Guest GL on the page's WebGL2, guest Vulkan on its WebGPU, and VA-API video on WebCodecs.
|
||||
|
||||
::note
|
||||
Both are browser-only. Node has no WebGL or WebGPU, so there `gl` and `vk` are ignored with a log line.
|
||||
All three are browser-only. Node has no WebGL, WebGPU or WebCodecs, so there `gl`, `vk` and `va` are ignored with a log line.
|
||||
::
|
||||
|
||||
## GL
|
||||
@@ -48,3 +48,15 @@ const r = await vm.exec("vulkaninfo", ["--summary"]); // deviceName = kwvk (WebG
|
||||
The base carries a Vulkan driver (an ICD the Vulkan loader finds by itself) that sends the guest's Vulkan calls to a renderer on the page's WebGPU device; SPIR-V shaders become WGSL through `kwvk-naga.wasm`. Nothing loads before the guest's first Vulkan program (`vm.vk.status`).
|
||||
|
||||
Vulkan 1.2 with Wayland, X11 and headless presentation (frames come back by readback); vkcube, vkmark, SDL's GPU API and GTK 4's Vulkan renderer run on it.
|
||||
|
||||
## Video (VA-API)
|
||||
|
||||
```js
|
||||
const vm = await createKernel({ distro: "/distros/debian.erofs", gl: true, gpu: true, va: true });
|
||||
await vm.exec("sudo", ["apt-get", "install", "-y", "vainfo"]);
|
||||
const r = await vm.exec("vainfo"); // the kwva driver and the profiles it decodes
|
||||
```
|
||||
|
||||
The base carries a VA-API driver that Debian's libva loads for the virtio-gpu device with no variables set. It hands each compressed picture to a WebCodecs `VideoDecoder` on the page, so the guest's ffmpeg, mpv and Chromium decode video in the browser's decoder, in hardware where it has one. It decodes VP9 profile 0, H.264, AV1 Main and HEVC Main where WebCodecs does, and encodes VP9 where the page has a `VideoEncoder` for it (ffmpeg's `vp9_vaapi`).
|
||||
|
||||
Decoded pictures come back as NV12. With `gl` they can instead be exported as dmabufs that the host fills on the GPU, so mpv's `--hwdec=vaapi` with `--vo=dmabuf-wayland` shows video without a copy through the guest. libva needs the virtio-gpu device (`gpu: true`), and the driver is built for glibc, so it works on Debian. `vm.va.status` lists the profiles offered and whether WebCodecs decodes them in hardware. Nothing is asked of WebCodecs before the guest first opens the driver.
|
||||
54
docs/1.sdk/13.snapshots.md
Normal file
54
docs/1.sdk/13.snapshots.md
Normal file
@@ -0,0 +1,54 @@
|
||||
---
|
||||
icon: ph:clock-counter-clockwise-duotone
|
||||
---
|
||||
|
||||
# Snapshots
|
||||
|
||||
> Save a running machine and resume it later, in this process or another.
|
||||
|
||||
```js
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createKernel, decodeSnapshot, encodeSnapshot } from "unkernel";
|
||||
|
||||
const vm = await createKernel({ distro });
|
||||
await vm.exec("sh", ["-c", "echo kept > /tmp/state"]);
|
||||
|
||||
// park every task, store the snapshot, then stop
|
||||
await vm.snapshot({ commit: (snap) => writeFile("vm.snap", encodeSnapshot(snap)) });
|
||||
|
||||
// later: the same kernel, disks and devices
|
||||
const restored = await createKernel({ distro, restore: decodeSnapshot(await readFile("vm.snap")) });
|
||||
await restored.exec("cat", ["/tmp/state"]); // "kept"
|
||||
```
|
||||
|
||||
The kernel parks every task where its whole state is in memory, so a snapshot is the guest's memory plus a few host values. Without a data disk, that memory also holds the root file system's changes. `encodeSnapshot()` leaves out free pages, and by default a snapshot that stops the machine first drops the guest's clean file cache, so the idle base shell in a 2 GiB guest saved to 46 MiB (2026-11-30).
|
||||
|
||||
- `snapshot()` alone copies the machine and lets it run on.
|
||||
- `snapshot({ stop: true })` stops it right after the copy (exit kind `"stopped"`).
|
||||
- `snapshot({ commit })` stops it only once `commit` has stored the snapshot. If `commit` rejects or times out (`commitTimeoutMs`), the machine runs on and `snapshot()` rejects with a `SnapshotCommitError`, so a failed save never loses the machine.
|
||||
- `snapshot({ commit, hold })` keeps the stored machine waiting at that point until `hold` returns `"stop"` or `"continue"`. Nothing runs in the guest while it waits, and if it continues, its clocks have moved on by the wait, as for a VM its hypervisor paused.
|
||||
|
||||
## What a restore needs
|
||||
|
||||
- **The same kernel build.** The snapshot's `fingerprint` must match. `initrd`, `cmdline` and `memoryMiB` are ignored.
|
||||
- **The same disks, unchanged.** Disks are not copied: a snapshot records each disk's identity and write generation, and a restore refuses a disk written since then. Once the restored guest writes, the snapshot is stale. The distro image is identified by its content. A writable image file gets a `FILE.kwsnap` beside it with its write generation.
|
||||
- **The same devices.** `display`, `sound`, `soundIn`, `camera`, `vsock`, `shm`, `gpu` and the network must be given or left out as they were (the network with the same MAC). A snapshot is refused while virtio-gpu holds resources.
|
||||
- **The same number of CPUs.** `cpus` defaults to the snapshot's.
|
||||
|
||||
`createKernel()` rejects with the reason when something does not match, and `snapshotDiskMismatch()`, `snapshotDeviceMismatch()` and `snapshotCpuMismatch()` check ahead.
|
||||
|
||||
## What survives
|
||||
|
||||
Host [mounts](/sdk/mounts) survive: pass the same mount paths (read-only as before) and the guest's open files on them are opened again by path. [Host commands](/sdk/commands) are replaced by the ones you pass. vsock sessions (`spawn()`, `exec()`, `connect()`, `fetch()`, listeners) and the guest's TCP connections do not survive: the guest's ends are reset. Serial ports, Bluetooth and USB devices come back unplugged.
|
||||
|
||||
Terminal sessions survive if they are detachable:
|
||||
|
||||
```js
|
||||
const sh = await vm.spawn("sh", [], { detachable: true });
|
||||
const snap = await vm.snapshot({ stop: true });
|
||||
|
||||
const restored = await createKernel({ distro, restore: snap });
|
||||
const again = await restored.attach(snap.ttys[0]); // within detachTimeout (default 60 s of guest time)
|
||||
```
|
||||
|
||||
In worker mode the snapshot's memory is copied to the worker; `transferRestore: true` hands it over instead, for a snapshot used once. The CLI's `--input '{save=FILE}'` and `--restore FILE` are built on this.
|
||||
@@ -24,12 +24,23 @@ const vm = await createKernel({
|
||||
|
||||
`createKernel()` rejects with a `BootError` if the kernel cannot start.
|
||||
|
||||
Other options:
|
||||
|
||||
- `signal`: an `AbortSignal` that cancels the downloads and, once the kernel has booted, stops it.
|
||||
- `consoleSize: { cols, rows }`: the console's size at boot; `resize()` changes it later.
|
||||
- `log`: where host diagnostics (`[host] ...`, `[net] ...`) go. Default `console.error`.
|
||||
- `onDiskError(index, error)`: a disk built from a spec failed to save a flush (such as a full quota); the guest gets EIO for it.
|
||||
- `memoryFallbackMiB`: smaller sizes to try in order if `memoryMiB` cannot be allocated (browsers default to `DEFAULT_MEMORY_FALLBACK_MIB`).
|
||||
- `profile: true`: sample where guest user time goes; `vm.profile()` reads the report and `formatProfile()` prints it. Time samples need several CPUs and Node; elsewhere only instruction samples are taken.
|
||||
|
||||
`vm.distro` describes the distro image the guest booted, and `vm.stats()` has the counters of every device.
|
||||
|
||||
## Limits
|
||||
|
||||
On top of the kernel's own limits:
|
||||
|
||||
- There is no guest agent beyond terminal sessions, so you drive the guest through a terminal or its console, or over [vsock](/sdk/vsock) with your own program.
|
||||
- Devices beyond the console are off unless asked for: `display`, `sound`, `shm`, `gpu`, `gl`, `vk`, `va`, `net`, [`serial`](/sdk/serial), [`bluetooth`](/sdk/bluetooth) and [`usb`](/sdk/usb) (vsock is on unless `vsock: false`).
|
||||
- There is no guest agent beyond terminal sessions, so you drive the guest through a terminal or its console, or over [vsock](/sdk/vsock) with your own program; guest programs reach you through [host commands](/sdk/commands).
|
||||
- Devices beyond the console are off unless asked for: `display`, `sound`, `soundIn`, `camera`, `shm`, `gpu`, `gl`, `vk`, `va`, `net`, [`serial`](/sdk/serial), [`bluetooth`](/sdk/bluetooth) and [`usb`](/sdk/usb) (vsock is on unless `vsock: false`).
|
||||
- `stop()` doesn't shut the guest down cleanly, so prefer `poweroff`.
|
||||
- Only one kernel can run per thread.
|
||||
- Types ship as `.d.mts` and use the DOM's `WebAssembly` types, so a Node-only TypeScript project needs `"lib": ["dom"]` or `skipLibCheck`.
|
||||
39
docs/1.sdk/3.commands.md
Normal file
39
docs/1.sdk/3.commands.md
Normal file
@@ -0,0 +1,39 @@
|
||||
---
|
||||
icon: ph:function-duotone
|
||||
---
|
||||
|
||||
# Host Commands
|
||||
|
||||
> JavaScript functions the guest runs as programs.
|
||||
|
||||
```js
|
||||
const vm = await createKernel({
|
||||
commands: {
|
||||
hello: (c) => `hello ${c.args.join(" ")} from the host\n`,
|
||||
upper: (c) =>
|
||||
c.stdin
|
||||
.pipeThrough(new TextDecoderStream())
|
||||
.pipeThrough(new TransformStream({ transform: (s, out) => out.enqueue(s.toUpperCase()) }))
|
||||
.pipeTo(c.stdout),
|
||||
fail: () => ({ exitCode: 3 }),
|
||||
},
|
||||
});
|
||||
await vm.exec("sh", ["-c", "hello world | upper; fail; echo $?"]); // "HELLO WORLD FROM THE HOST\n3\n"
|
||||
|
||||
await vm.addCommand("notify", (c) => console.log(c.args)); // at any time
|
||||
await vm.removeCommand("notify");
|
||||
```
|
||||
|
||||
Host commands are the reverse of [`exec()`](/sdk/programs): a guest program runs a function on your side. Each name becomes `/run/kw/bin/NAME` in the guest, first on `PATH`, so shells, scripts and other programs run it like any other command. Each run is a real guest process with its own pid, arguments, environment, stdio and exit status, and the function is called once for each.
|
||||
|
||||
The function gets the process's `name`, `args`, `env`, `cwd`, `pid`, `uid` and `gid`, which of its stdio are terminals (`isTTY`) and the terminal's `cols` and `rows`. It also gets `stdin`, `stdout` and `stderr` as web streams, and a `signal` that aborts when the process is gone (killed, Ctrl-C, a closed pipe). `stdin` is pulled: the guest reads its stdin only as you read, so whatever the function leaves unread stays for the next reader.
|
||||
|
||||
What it returns ends the process:
|
||||
|
||||
- nothing: exit status 0
|
||||
- a number (or `{ exitCode }`): that exit status
|
||||
- a string or bytes: written to stdout, status 0
|
||||
- `{ signal: "TERM" }`: the process dies by that signal
|
||||
- a throw or rejection: the message on stderr, status 1
|
||||
|
||||
`spawn()` and `exec()` wait until the commands exist in the guest; if they could not be made, the calls reject with a `CommandError`. Commands need vsock (on by default) and run on the thread that owns the VM, in worker mode too. The handlers are not part of a [snapshot](/sdk/snapshots): with `restore`, the guest's commands are replaced by the ones you pass.
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
icon: ph:globe-duotone
|
||||
---
|
||||
|
||||
# Network
|
||||
|
||||
> Give the guest's TCP/IP stack a way out.
|
||||
|
||||
```js
|
||||
import { createKernel, directBackend, wispBackend } from "unkernel";
|
||||
|
||||
await createKernel({ net: directBackend() }); // Node: host sockets
|
||||
await createKernel({ net: wispBackend("wss://wisp.example/") }); // anywhere: your Wisp proxy
|
||||
```
|
||||
|
||||
Networking is off unless you pass `net`. The guest runs Linux's own TCP/IP stack, with DHCP and DNS; the backend carries its connections.
|
||||
|
||||
- **`directBackend()`** (Node) opens real sockets on the host.
|
||||
- **`wispBackend(servers)`** goes through a [Wisp](https://github.com/MercuryWorkshop/wisp-protocol) proxy that you run or choose (one URL, or several to race). Browsers can't open raw TCP sockets, so this is the backend for the web. The proxy sees the host names and ports the guest connects to and plain-HTTP content; TLS from the guest is end to end. In Node, pass `headers` (e.g. `{ Origin: "https://your.site" }`) if your proxy checks the Origin.
|
||||
|
||||
Any object with `connect` and `lookup` methods can carry the guest's TCP and DNS, so you can write your own backend.
|
||||
|
||||
## Wisp limits
|
||||
|
||||
Wisp carries TCP streams and nothing else, and a guest program can tell:
|
||||
|
||||
- **No half-close.** When the guest shuts down its sending side (`shutdown(SHUT_WR)`, which `nc` does at the end of its input), the server is not told. A client that waits for the server to see end of file before it answers hangs, such as `echo hi | nc HOST PORT` against a server that reads to the end, or an HTTP/1.0 request with a body and no Content-Length.
|
||||
- **No DNS.** Names resolve to placeholder addresses in 198.18.0.0/15, and the server resolves the name when the guest connects. Every name resolves (a bad one fails at connect time, as a reset), the address the guest sees is not the host's, and each name has one address.
|
||||
- **No connect acknowledgement.** A connect succeeds at once; a refused or unreachable host shows up as a reset.
|
||||
|
||||
For real addresses, pass a resolver of your own, such as DNS over HTTPS. It takes a name and returns IPv4 addresses, or rejects with `{ code: "ENOTFOUND" }` for a name that does not exist:
|
||||
|
||||
```js
|
||||
await createKernel({ net: wispBackend(servers, { lookup: (name) => resolveOverHttps(name) }) });
|
||||
```
|
||||
|
||||
For half-close, use a backend of your own over a transport that has it.
|
||||
|
||||
::note
|
||||
No IPv6, no UDP beyond DHCP and DNS, and no inbound connections. To reach a server in the guest, use [`vm.connect()` and `vm.fetch()`](/sdk/vsock#reach-guest-servers), which go over vsock.
|
||||
::
|
||||
55
docs/1.sdk/4.network.md
Normal file
55
docs/1.sdk/4.network.md
Normal file
@@ -0,0 +1,55 @@
|
||||
---
|
||||
icon: ph:globe-duotone
|
||||
---
|
||||
|
||||
# Network
|
||||
|
||||
> Give the guest's TCP/IP stack a way out.
|
||||
|
||||
```js
|
||||
import { createKernel, directBackend, wispBackend } from "unkernel";
|
||||
|
||||
await createKernel({ net: directBackend() }); // Node: host sockets
|
||||
await createKernel({ net: wispBackend("wss://wisp.example/") }); // anywhere: your Wisp proxy
|
||||
```
|
||||
|
||||
Networking is off unless you pass `net`. The guest runs Linux's own TCP/IP stack, with DHCP and DNS; the backend carries its TCP connections and UDP flows.
|
||||
|
||||
- **`directBackend()`** (Node) opens real TCP and UDP sockets on the host. With `hostLoopback` in the network spec, the gateway (10.0.2.2) reaches the host's 127.0.0.1.
|
||||
- **`wispBackend(servers)`** goes through a [Wisp](https://github.com/MercuryWorkshop/wisp-protocol) proxy that you run or choose (one URL, or several to race), with UDP where the server carries it. Browsers can't open raw TCP sockets, so this is the backend for the web. The proxy sees the host names and ports the guest connects to and plain-HTTP content; TLS from the guest is end to end. In Node, pass `headers` (e.g. `{ Origin: "https://your.site" }`) if your proxy checks the Origin.
|
||||
|
||||
Any object with `connect` and `lookup` methods can carry the guest's TCP and DNS, and with a `udp` method its UDP, so you can write your own backend. To join a tailnet, see [Tailscale](/sdk/tailscale).
|
||||
|
||||
## Wisp limits
|
||||
|
||||
Wisp carries streams and nothing else, and a guest program can tell:
|
||||
|
||||
- **No half-close.** When the guest shuts down its sending side (`shutdown(SHUT_WR)`, which `nc` does at the end of its input), the server is not told. A client that waits for the server to see end of file before it answers hangs, such as `echo hi | nc HOST PORT` against a server that reads to the end, or an HTTP/1.0 request with a body and no Content-Length.
|
||||
- **No DNS.** Names resolve to placeholder addresses in 198.18.0.0/15, and the server resolves the name when the guest connects. Every name resolves (a bad one fails at connect time, as a reset), the address the guest sees is not the host's, and each name has one address.
|
||||
- **No connect acknowledgement.** A connect succeeds at once; a refused or unreachable host shows up as a reset.
|
||||
|
||||
For real addresses, pass a resolver of your own, such as DNS over HTTPS. It takes a name and returns IPv4 addresses, or rejects with `{ code: "ENOTFOUND" }` for a name that does not exist:
|
||||
|
||||
```js
|
||||
await createKernel({ net: wispBackend(servers, { lookup: (name) => resolveOverHttps(name) }) });
|
||||
```
|
||||
|
||||
For half-close, use a backend of your own over a transport that has it.
|
||||
|
||||
::note
|
||||
No IPv6, no ICMP beyond the gateway, and no inbound connections (except from tailnet peers with [Tailscale](/sdk/tailscale)). To reach a server in the guest, use [`vm.connect()` and `vm.fetch()`](/sdk/vsock#reach-guest-servers), which go over vsock.
|
||||
::
|
||||
|
||||
## Answer HTTP from the host
|
||||
|
||||
```js
|
||||
import { fetchRoutes, wispBackend } from "unkernel";
|
||||
|
||||
const net = fetchRoutes(wispBackend("wss://wisp.example/"), {
|
||||
"deb.debian.org": "https://debian-mirror.example", // http://deb.debian.org/x → https://debian-mirror.example/x
|
||||
"api.local": (req) => Response.json({ path: new URL(req.url).pathname }), // your own handler
|
||||
});
|
||||
await createKernel({ net });
|
||||
```
|
||||
|
||||
`fetchRoutes(inner, routes)` answers the guest's plain-HTTP requests (port 80, GET and HEAD) to the named hosts with the host's `fetch()`, and passes everything else to `inner`. Pass `undefined` for `inner` to allow only the routes. A string route rewrites the URL's prefix and forwards only the range and cache headers; in a browser the target must allow them through CORS. A function gets a `Request` with the guest's headers. Wisp specs take string routes as `routes`. [unkernel.dev](https://unkernel.dev/) uses this to fetch Debian packages from a CORS mirror instead of through its proxy.
|
||||
43
docs/1.sdk/5.tailscale.md
Normal file
43
docs/1.sdk/5.tailscale.md
Normal file
@@ -0,0 +1,43 @@
|
||||
---
|
||||
icon: ph:share-network-duotone
|
||||
---
|
||||
|
||||
# Tailscale
|
||||
|
||||
> Join the guest to your tailnet, from Node or a browser.
|
||||
|
||||
```js
|
||||
let state = load(); // the node's keys from an earlier run, if any
|
||||
const vm = await createKernel({
|
||||
net: {
|
||||
kind: "net",
|
||||
backend: { kind: "direct" }, // or { kind: "wisp", servers: "wss://wisp.example/" }
|
||||
tailscale: { authKey: "tskey-auth-...", state, hostname: "box", exitNode: "my-server" },
|
||||
},
|
||||
onTailscale(e) {
|
||||
if (e.type === "state") save(e.state); // keep it secret: it is the node's identity
|
||||
if (e.type === "authurl") console.log("log in at", e.url); // no auth key: interactive login
|
||||
if (e.type === "status") console.log(e.status.state, e.status.addresses);
|
||||
},
|
||||
});
|
||||
vm.tailscale.setExitNode(null); // back to the backend; a name picks another
|
||||
```
|
||||
|
||||
With `tailscale` in the network spec, the guest joins your [Tailscale](https://tailscale.com) network, or a [headscale](https://github.com/juanfont/headscale) one (`controlURL`). The client is JavaScript inside the SDK and loads only when the option is used. It talks to the coordination server over a WebSocket and carries WireGuard over Tailscale's DERP relays, so it needs no UDP and no helper on the host, and every packet is relayed.
|
||||
|
||||
The guest gets its 100.x address on a `tailscale0` interface and reaches the tailnet's devices by address or MagicDNS name. Inbound works too: tailnet devices can reach servers in the guest. Everything else keeps going through `backend`.
|
||||
|
||||
## Options
|
||||
|
||||
- `authKey`: a pre-auth key. Without one, login is interactive, through an `authurl` event.
|
||||
- `state`: what the last `state` event gave. Pass it back to keep the same node instead of registering a new one.
|
||||
- `hostname` (default `unkernel`), `ephemeral` and `tags`, as with `tailscale up`.
|
||||
- `exitNode`: a device's name or 100.x address. It takes all the guest's other IPv4 traffic and its DNS instead of the backend. The device has to advertise itself as an exit node and be approved, and the tailnet's policy has to let this node use it. `status.exitNodes` lists the devices that qualify, and `status.exitNode` says whether the chosen one is usable. While it is not usable (offline, not found, not approved), that traffic is refused, never sent through the backend.
|
||||
- `acceptRoutes`: add the peers' subnet routes.
|
||||
- `controlURL`: a headscale server. A page must also pass `controlPublicKey` (`mkey:...`), because headscale serves its key without CORS.
|
||||
|
||||
`vm.tailscale` has `status()`, `on("status", fn)`, `setExitNode(choice)` and `logout()`.
|
||||
|
||||
::note
|
||||
No IPv6, and the tunnel's MTU is 1280. From the terminal, `npx unkernel --tailscale-authkey KEY --tailscale-state ts.json --tailscale-exit-node my-server` does the same (`--help` lists the `--tailscale-*` options).
|
||||
::
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
icon: ph:monitor-duotone
|
||||
---
|
||||
|
||||
# Display, Input and Sound
|
||||
|
||||
> A framebuffer, evdev input and ALSA sound for guest programs.
|
||||
|
||||
```js
|
||||
import { createKernel, domCodeToLinux, pcmToFloat32 } from "unkernel";
|
||||
|
||||
const vm = await createKernel({
|
||||
display: { width: 800, height: 600 }, // the guest gets /dev/fb0
|
||||
onDisplay: (mode) => console.log(mode), // a program opened it (its mode) or closed it (null)
|
||||
sound: { onChunk: ({ data, format }) => play(pcmToFloat32(data, format)) },
|
||||
});
|
||||
|
||||
const frame = vm.frame(); // RGBA, or null while nothing draws
|
||||
if (frame) ctx.putImageData(new ImageData(frame.data, frame.width, frame.height), 0, 0);
|
||||
|
||||
addEventListener("keydown", (e) => {
|
||||
const key = domCodeToLinux(e.code);
|
||||
if (key && vm.evdev.keyboardOpen) vm.evdev.key(key, true);
|
||||
});
|
||||
```
|
||||
|
||||
## Input
|
||||
|
||||
`evdev` also has `button()`, `move()`, `moveTo()` and `wheel()` for a mouse or tablet. `onInput` tells you when a program opens the keyboard and mouse; until then, send keys to the console. `readFrame()` waits for a fresh frame.
|
||||
|
||||
## Sound in browsers
|
||||
|
||||
`createAudioOut()` plays the guest's sound with Web Audio:
|
||||
|
||||
```js
|
||||
import { createAudioOut, createKernel } from "unkernel/web";
|
||||
|
||||
button.hidden = true;
|
||||
const audio = createAudioOut({
|
||||
onChange: (state) => {
|
||||
button.hidden = state !== "waiting"; // "click to play"
|
||||
},
|
||||
});
|
||||
const vm = await createKernel({ sound: audio });
|
||||
button.onclick = () => audio.resume(); // or any other click or key press on the page
|
||||
```
|
||||
|
||||
Browsers start sound only after a click, tap or key press on the page. Until then the latest `holdSeconds` (10) of what the guest plays are held: a clip that has ended by then plays whole, a stream joins live. `audio.muted = true` silences it.
|
||||
|
||||
One sink serves one kernel at a time, and outlives it: pass it to the next kernel, or `close()` it.
|
||||
@@ -73,7 +73,7 @@ Anything a program relies on, from `/proc` and `epoll` to cgroups and overlayfs,
|
||||
- **Linux's own file systems**: ext4, overlayfs, tmpfs, loop devices, FUSE, and 9p. The root file system is an overlay: a read-only distro image under your changes, which go to a persistent ext4 disk.
|
||||
- **Linux's own TCP/IP stack**, with DHCP and DNS, reaching the internet through your host's sockets or a Wisp proxy.
|
||||
- **cgroups, namespaces, userfaultfd, fanotify and TUN**: enough for systemd to boot Ubuntu 26.10 to `multi-user.target`.
|
||||
- **Devices**: a framebuffer, evdev keyboard, mouse and touch, sound through ALSA, AF_VSOCK, shared memory with the host, and guest GL and Vulkan on the page's WebGL2 and WebGPU.
|
||||
- **Devices**: a framebuffer, evdev keyboard, mouse and touch, sound and a microphone through ALSA, a V4L2 camera, AF_VSOCK, shared memory with the host, a virtio-gpu with guest GL and Vulkan on the page's WebGL2 and WebGPU, VA-API video on WebCodecs, and serial ports, Bluetooth and USB devices from Web Serial, Web Bluetooth and WebUSB.
|
||||
- **aarch64 user space**: ARMv8.0-A with FP and AdvSIMD plus the crypto, CRC32 and LSE atomics extensions, so distribution binaries run unchanged.
|
||||
|
||||
## How it works
|
||||
|
||||
Reference in New Issue
Block a user