mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
A VM's proxy runs as two processes, as design.md's "The proxy's broker"
says: devvm _proxy, the broker, which keeps what only the host should
do, and devvm _proxy-child, which reads the VM's network and can be
confined by the follow-ups.
- wire.go: the protocol over one socketpair (close-on-exec from the
start: SOCK_CLOEXEC on Linux, ForkLock elsewhere), length-prefixed JSON
frames of at most 2 MiB, unknown fields refused, bytes as base64, one
descriptor on a frame's first bytes (SCM_RIGHTS, MSG_CTRUNC breaks the
rules), wire types for every secret (redact.Secret at once).
- broker.go: newBroker, the start (handshake: version 1 and each side's
executable's SHA-256, within 4 s), the answers (value through lookups,
kept 30 s or 5 min, a failure 5 s, dropped when the bindings change;
file by number; link connected by the broker and passed as a
descriptor; token exchanged by the broker), each by something in its
own config, with caps 1/8/4/256; live: the lifeline closes the socket
and kills the child 6 s later, SIGTERM stops it within a second, a
child that ends ends the broker, a rule broken stops the child.
- child.go: the start (startOf), the child's server (newChildServer),
the broker as hostSide over the socket (brokerClient), runChildOn;
ready only after it reads the host's addresses (kept: the last good
read), roots and time zone loaded first.
- process.go: Main(ctx, ...) and ChildMain; the child spawned with
/proc/self/exe on Linux, PR_SET_PDEATHSIG from a locked thread
(daemon.Cmd.DieWithThread), descriptors 3 and 4, and TZ, SSL_CERT_*
and GODEBUG with updatemaxprocs=0 alone; run/proxy-child.pid and
run/proxy.confined ("none" until the follow-ups); KeepLogs in the
broker. ChildMain refuses to start unless descriptors 3 and 4 are a
unix socket and an IP one (checkInherited): run by hand, without
them, those numbers can be the Go runtime's own, which closing
crashed it (signal_recv: inconsistent state).
- capture.go: a captured token request goes to the broker
(captureToken, exchanger), so a login's real tokens never enter the
child; an error reply passes up to 1 MiB, longer gets 502.
- watched.go: the child stats each changing file and asks the broker
for it once it changed, keeping the stamp of what the broker read.
- rotate.go: proxy.log rotated by both through its descriptor, under a
lock of a description of its own; OpenLog opens a log never through a
link, one link, yours, replacing what a child left in its place.
- nixcache.go: the trim and its count through a safefile.Root, nar/
only as a folder, links deleted as themselves; reads never through a
link; the lock tried for 5 s (ErrNixLocked, nix_cache_locked).
- daemon: Cmd.Err, Files, Env, DieWithThread; Handle.Kill, Exit;
WritePID.
- netpolicy: Proxy.Stop also stops a child that outlived its broker
(run/proxy-child.pid, _proxy-child -for); proxy.log opened with
OpenLog; a refused launch keeps a running VM only while both run.
devvm network log and lock read the event log through safefile.
- vm, vmssh, vmlog: links.log and ports.log opened with OpenLog, read
through safefile, trimmed only as a regular file with one link.
- backend: the build proxy's logs in a logs/ folder of their own.
- cli: _proxy-child; _proxy waits for its child on a signal
(StopsItsOwn); the child reads none of devvm's folders (no
makePrivate); ui.Files.
- Tests: FuzzBrokerFrames, the frames' rules, the handshake and the
pair's end in synctest bubbles, the caps, the broker naming its own
alone, the client over a real socketpair with a passed descriptor,
ChildMain, TestInheritedSocket and proxy.txtar's child run by hand,
the frozen 0.1.0 configs starting a broker and child,
two writers rotating once, planted links, FIFOs and hard links; the
testscript runner stops _proxy-child too; e2e: broker and child, their
arguments, descriptors and environment, stop, SIGKILL either, planted
files in the logs folder and the Nix cache, build proxies gone.
- Review fixes: the lifeline closes the socket and starts the kill's
timer before logging; every log lock (proxy.log's, the event log's
rotation) is tried without blocking for 200 ms (flockWithin, which the
Nix lock shares), then written without or the rotation skipped; a
copied log's rotation streams at most twice its limit from a line's
start (copyFrom, copyAtomic); a reply too long to send goes as
too_long; kept token headers capped at 1 KiB; the child gives up on a
request whose context ended, dropping its late reply and holding its
slot until then; a write deadline on the start frame; errors reach the
child as codes (not_found, refused, busy, too_long, failed), their
text in the broker's log; FuzzFrameStreams, and FuzzBrokerFrames
writes from a goroutine; nix_cache_locked links to How it works.
- Docs: processes, network, overview, design (with threat rows for the
logs' locks and a log made huge), troubleshooting, the proxy's
README, structure, testing; CHANGELOG.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
191 lines
6.1 KiB
Go
191 lines
6.1 KiB
Go
package daemon
|
|
|
|
import (
|
|
"os"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
// A Proc is one of devvm's background processes, found by its pid file:
|
|
// the process that file names, while it runs and its arguments say it's
|
|
// that one (Is), so a process given the pid since, or a file left by one
|
|
// that ended, is never taken for it.
|
|
type Proc struct {
|
|
// PIDFile is where its pid is kept, on a line of its own.
|
|
PIDFile string
|
|
// Is reports whether a process's arguments, its program first, are
|
|
// this one's.
|
|
Is func(args []string) bool
|
|
// Args returns a running process's arguments (platform.ProcessArgs).
|
|
Args func(pid int) ([]string, error)
|
|
// Signal sends it, and its group, a signal: SignalGroup, or a test's.
|
|
Signal func(pid int, sig syscall.Signal) error
|
|
// Alive reports whether a process has pid: Alive, or a test's.
|
|
Alive func(pid int) bool
|
|
}
|
|
|
|
// alive reports whether a process has pid (Alive).
|
|
func (p Proc) alive(pid int) bool {
|
|
if p.Alive == nil {
|
|
return Alive(pid)
|
|
}
|
|
return p.Alive(pid)
|
|
}
|
|
|
|
// HasFlag reports whether args, its program first, run devvm's command
|
|
// cmd with flag's value val (-vm NAME).
|
|
func HasFlag(args []string, cmd, flag, val string) bool {
|
|
if len(args) < 2 || args[1] != cmd {
|
|
return false
|
|
}
|
|
i := slices.Index(args, flag)
|
|
return i >= 0 && i+1 < len(args) && args[i+1] == val
|
|
}
|
|
|
|
// PID returns the process's pid while it runs.
|
|
func (p Proc) PID() (int, bool) {
|
|
pid, ok := readLine(p.PIDFile)
|
|
if !ok || !p.alive(pid) {
|
|
return 0, false
|
|
}
|
|
args, err := p.Args(pid)
|
|
if err != nil || !p.Is(args) {
|
|
return 0, false
|
|
}
|
|
return pid, true
|
|
}
|
|
|
|
// Running reports whether the process runs.
|
|
func (p Proc) Running() bool {
|
|
_, ok := p.PID()
|
|
return ok
|
|
}
|
|
|
|
// runs reports whether pid is still the process.
|
|
func (p Proc) runs(pid int) bool {
|
|
cur, ok := p.PID()
|
|
return ok && cur == pid
|
|
}
|
|
|
|
// Start starts c with start (Detach, or a test's), after removing the
|
|
// status file an earlier start left, and records its pid in the pid file.
|
|
func (p Proc) Start(start Starter, c Cmd) (int, error) {
|
|
if c.Status != "" {
|
|
if err := os.Remove(c.Status); err != nil && !os.IsNotExist(err) {
|
|
return 0, err
|
|
}
|
|
}
|
|
pid, err := start(c)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return pid, writeLine(p.PIDFile, strconv.Itoa(pid))
|
|
}
|
|
|
|
// Stop stops the process, if it runs: SIGTERM, then after wait SIGKILL,
|
|
// then up to wait more, looking every twentieth of it. A process given
|
|
// the pid since is never signalled: SIGKILL goes only to a process whose
|
|
// arguments still say it's this one, so not to one still ending, whose
|
|
// arguments can't be read (ended), nor to another given the pid whose
|
|
// arguments can't be read either. Once it has ended its pid file goes,
|
|
// unless a start since has written another pid there. It reports whether
|
|
// none runs then. Each signal reaches the process's group too
|
|
// (SignalGroup), so what it started ends with it.
|
|
func (p Proc) Stop(wait time.Duration) bool {
|
|
pid, ok := p.PID()
|
|
if !ok {
|
|
return true
|
|
}
|
|
signal := p.Signal
|
|
if signal == nil {
|
|
signal = SignalGroup
|
|
}
|
|
for _, sig := range []syscall.Signal{syscall.SIGTERM, syscall.SIGKILL} {
|
|
if sig == syscall.SIGTERM || p.runs(pid) {
|
|
_ = signal(pid, sig)
|
|
}
|
|
for range 20 {
|
|
if p.ended(pid) {
|
|
if cur, ok := readLine(p.PIDFile); ok && cur == pid {
|
|
_ = os.Remove(p.PIDFile)
|
|
}
|
|
return true
|
|
}
|
|
time.Sleep(wait / 20)
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ended reports whether the process pid, which was this one, has ended:
|
|
// no process has the pid, or another one does now. One whose arguments
|
|
// can't be read is still ending: its memory goes before its files, so a
|
|
// port it listens on is still its own a moment after (macOS's
|
|
// kern.procargs2 fails first).
|
|
func (p Proc) ended(pid int) bool {
|
|
if !p.alive(pid) {
|
|
return true
|
|
}
|
|
args, err := p.Args(pid)
|
|
return err == nil && !p.Is(args)
|
|
}
|
|
|
|
// Ready waits for the process pid, which Start started with status, to
|
|
// say it's ready there (WaitReady), while it runs as this one.
|
|
func (p Proc) Ready(status string, pid int, tick time.Duration, tries int) (string, bool) {
|
|
return WaitReady(status, pid, func() bool { return p.starting(pid) }, tick, tries)
|
|
}
|
|
|
|
// starting reports whether pid, which Start just started, still runs as
|
|
// this one, as runs does, except that one whose arguments don't say so
|
|
// yet still counts while they read as none or as devvm's own: Linux lets
|
|
// the parent go on as exec begins, while the child still has the
|
|
// parent's memory, and so its arguments, then shows none as exec
|
|
// replaces that memory, and its new ones only once the program is
|
|
// loaded. One that has ended is reaped (Detach), so it no longer counts
|
|
// once it's gone.
|
|
func (p Proc) starting(pid int) bool {
|
|
cur, ok := readLine(p.PIDFile)
|
|
if !ok || cur != pid || !p.alive(pid) {
|
|
return false
|
|
}
|
|
args, err := p.Args(pid)
|
|
return err != nil || p.Is(args) || slices.Equal(args, os.Args)
|
|
}
|
|
|
|
// WritePID writes pid as the pid file path's one line, as Start does for
|
|
// the process it starts: for one that another started, such as a proxy's
|
|
// child, which its broker starts.
|
|
func WritePID(path string, pid int) error { return writeLine(path, strconv.Itoa(pid)) }
|
|
|
|
// writeLine writes s as a file's one line, mode 600, in a single write:
|
|
// a reader that finds no line end yet (readLine, readStatus) has caught it
|
|
// part-way, and takes it as not written yet, as it takes no file. daemon
|
|
// is the standard library only, so it doesn't use state.WriteFile.
|
|
func writeLine(path, s string) error {
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:forbidigo,gosec // devvm's own run folder; a part-way line reads as none (readLine, readStatus)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = f.WriteString(s + "\n")
|
|
if cerr := f.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
return err
|
|
}
|
|
|
|
// readLine reads the pid on a file's first line, written whole
|
|
// (writeLine): ok is false for none, a partial one or no pid.
|
|
func readLine(path string) (int, bool) {
|
|
b, err := os.ReadFile(path) //nolint:gosec // devvm's own run folder
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
first, _, whole := strings.Cut(string(b), "\n")
|
|
pid, err := strconv.Atoi(strings.TrimSpace(first))
|
|
return pid, whole && err == nil && pid > 0
|
|
}
|