From b679907d1e948691c5c0b8d1308b900c9cffd2a4 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Mon, 23 Nov 2026 14:47:17 -0300 Subject: [PATCH 1/2] lab: io and build, what a running workspace's I/O and build cost the host (#563) #563's first section asks what nesting costs a running workspace, not its boot: the host CPU each unit of work takes, nested against metal. Two probes measure it. io runs fio inside the guest against a raw disk attached after the boot, one job a row: 4 KiB random read and write at 1 and 32 in flight, 1 MiB sequential at 8. It records IOPS, MiB/s, completion latency, and the CPU each GiB moved took, QEMU's (every thread, /proc/PID/stat) and the guest's. fio is the new fio edit, built from a release versions.yaml pins. build times `go build cmd/go` with an empty cache inside the guest, on an attached ext4 disk holding the host's Go toolchain, and records QEMU's and the guest's CPU over it. Both disks are raw files on the host's tmpfs. The bench's scratch is NVMe and bench-metal's is EBS, and QEMU writes through the host's page cache, so either device would have been measured beside the hypervisors. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/lab.yml | 2 + cmd/spin-machine-dev/lab.go | 2 +- docs/cli.md | 17 ++ internal/lab/density.go | 6 +- internal/lab/experiment_test.go | 2 +- internal/lab/fio.Dockerfile | 30 +++ internal/lab/gobuild.go | 126 ++++++++++++ internal/lab/io.go | 349 ++++++++++++++++++++++++++++++++ internal/lab/io_test.go | 55 +++++ internal/lab/lane_test.go | 12 +- internal/lab/overlay.go | 4 +- internal/lab/probe.go | 2 + versions.yaml | 12 ++ 13 files changed, 613 insertions(+), 6 deletions(-) create mode 100644 internal/lab/fio.Dockerfile create mode 100644 internal/lab/gobuild.go create mode 100644 internal/lab/io.go create mode 100644 internal/lab/io_test.go diff --git a/.github/workflows/lab.yml b/.github/workflows/lab.yml index 9db1ce24..5dadf627 100644 --- a/.github/workflows/lab.yml +++ b/.github/workflows/lab.yml @@ -36,6 +36,8 @@ on: - bootchart - ledger - exits + - io + - build - check:firmware - check:firmware-stages - check:waits diff --git a/cmd/spin-machine-dev/lab.go b/cmd/spin-machine-dev/lab.go index 7f1a84df..78da592a 100644 --- a/cmd/spin-machine-dev/lab.go +++ b/cmd/spin-machine-dev/lab.go @@ -55,7 +55,7 @@ func treeFlags(fs *pflag.FlagSet, s *lab.TreeSpec) { fs.StringVar(&s.Append, "append", "", "added to the kernel command line of every boot") fs.StringArrayVar(&s.Boot, "boot", nil, "a spin-machine boot flag for every boot of the tree, e.g. --boot --cpu=Skylake-Server-v4") fs.StringVar(&s.CPU, "cpu", "", "baseline: the newest named CPU model the host making the tree can run, chosen there (machine.QEMU.CPUModels, internal/lab)") - fs.StringArrayVar(&s.Edits, "edit", nil, "an edit of every boot's overlay, by name: lane (the first login's lane as this checkout builds it), pressure (the pressure probe's guest sender as this checkout builds it into the image), floor (no systemd before sshd: a bound, with --append init=/usr/local/sbin/spin-floor), nolinger (spin not lingering, as this checkout builds the image), forwarder-early (login=spin's forwarder, spin's supervisor, without systemd's default dependencies), carry-masks, carry-generators and carry-coldplug (optimize-systemd.sh's boot-time changes and the coldplug filter taken back, after lane), carry-journal, carry-docker, carry-lane-logind and carry-keygen (four of the image's deviations, each as Ubuntu ships it, after lane; docs/image.md, \"Measured in this review\"), bootchart (systemd-bootchart as PID 1, which the bootchart probe draws), ledger (sshd at DEBUG1 and the ledger probe's scripts, with --append '"+lab.LedgerAppend+"': the scheduler traced from the kernel's start, which the ledger probe accounts for)") + fs.StringArrayVar(&s.Edits, "edit", nil, "an edit of every boot's overlay, by name: lane (the first login's lane as this checkout builds it), pressure (the pressure probe's guest sender as this checkout builds it into the image), floor (no systemd before sshd: a bound, with --append init=/usr/local/sbin/spin-floor), nolinger (spin not lingering, as this checkout builds the image), forwarder-early (login=spin's forwarder, spin's supervisor, without systemd's default dependencies), carry-masks, carry-generators and carry-coldplug (optimize-systemd.sh's boot-time changes and the coldplug filter taken back, after lane), carry-journal, carry-docker, carry-lane-logind and carry-keygen (four of the image's deviations, each as Ubuntu ships it, after lane; docs/image.md, \"Measured in this review\"), bootchart (systemd-bootchart as PID 1, which the bootchart probe draws), ledger (sshd at DEBUG1 and the ledger probe's scripts, with --append '"+lab.LedgerAppend+"': the scheduler traced from the kernel's start, which the ledger probe accounts for), fio (fio, built from the release versions.yaml pins, which the io probe runs)") fs.StringVar(&s.Systemd, "systemd", "", "an image/systemd/experiments patch: systemd built with it here, in every overlay") fs.BoolVar(&s.OpenSSH, "openssh", false, "OpenSSH as this checkout builds it (image/openssh), built here, in every overlay") fs.StringArrayVar(&s.Options, "opt", nil, "a probe option NAME=VALUE for this tree's boots in place of the run's, e.g. --opt memory=2048 --opt plugged=0: two shapes as two trees of one run. Not login, nor one that changes the probe's rows") diff --git a/docs/cli.md b/docs/cli.md index 2f890cc1..abd7213a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -225,6 +225,8 @@ laid out as one (`--from _output`). It replaces what its flags ask for: - `--edit bootchart`: systemd-bootchart as PID 1, spin-stack's fork at the commit versions.yaml pins, compiled here in a container, which samples the boot and execs systemd. The `bootchart` probe draws only a tree that carries it (measuring.md, "Boot charts"). +- `--edit fio`: fio, built here from the release versions.yaml pins, at /usr/local/bin/fio, + which the `io` probe runs. - `--edit ledger`: sshd at LogLevel DEBUG1 and the `ledger` probe's two scripts. Its tree also boots a kernel that can be traced and the scheduler's tracepoints from the kernel's start, `--kernel traceable:TAG --append ''` (measuring.md, "The ledger"). @@ -414,6 +416,21 @@ burst's counts, with every restore's `running`. each number in `crowds` (default `0 8 16 32`). The running workspaces are idle, or keep their vCPUs busy with `load=cpu`, and settle for `settle` seconds (default 10) before the measured boot. +`io` is what a running workspace's disk I/O costs the host (#563). Each row is a fio job in +`jobs` (default all six: 4 KiB random read and write at 1 and at 32 in flight, 1 MiB sequential +read and write at 8), run for `runtime` seconds (default 10) with no ramp. The guest boots and is +logged into, then gets a raw disk of `size` MiB (default 1024) attached as spin attaches one, +and fio runs against its device with O_DIRECT and io_uring. It records IOPS, MiB/s, the +completion latency's p50 and p99, and the CPU each GiB moved took: QEMU's, every thread +(`/proc/PID/stat`), and the guest's busy time. The disk is on the host's tmpfs on every host, so +two hosts differ only in the path through the hypervisors, not in their scratch devices. The tree +needs `--edit fio`. + +`build` is what a build a workspace runs costs the host (#563): `go build cmd/go` with an empty +cache and its `sync`, inside the guest, on an ext4 disk attached after the boot that holds the +host's Go toolchain, on the host's tmpfs as `io`'s is. It records the wall time on the guest's +clock, QEMU's CPU time and the guest's busy time over it. + `transport` says how much of each goal number QMP and vsock are. It boots and restores as `restore-first` does, with QEMU traced (QMP and the run state, in host time). From the trace it reads which commands each path waits on: `cont` for a cold boot, and `migrate-incoming` and what diff --git a/internal/lab/density.go b/internal/lab/density.go index fd402a41..0b4635c8 100644 --- a/internal/lab/density.go +++ b/internal/lab/density.go @@ -146,7 +146,7 @@ func (m *Measurement) bootLoggedIn(name string) (*Machine, uint32, time.Duration return nil, 0, 0, err } cid := NewCID() - qmp := filepath.Join(m.Socks, name+".qmp") + qmp := m.qmpPath(name) args := append([]string{"--vsock-cid", fmt.Sprint(cid), "--console", "file:" + m.Dir + "/" + name + ".console", "--append", m.Tree.Cmdline(m.Key.Init())}, m.qmpToPlug(qmp)...) t0 := time.Now() @@ -161,3 +161,7 @@ func (m *Measurement) bootLoggedIn(name string) (*Machine, uint32, time.Duration } return mc, cid, login, plugged() } + +// qmpPath is the monitor bootLoggedIn opens for the machine it boots as name, when the options size +// the guest. +func (m *Measurement) qmpPath(name string) string { return filepath.Join(m.Socks, name+".qmp") } diff --git a/internal/lab/experiment_test.go b/internal/lab/experiment_test.go index 72ce89c4..08dc72ad 100644 --- a/internal/lab/experiment_test.go +++ b/internal/lab/experiment_test.go @@ -666,7 +666,7 @@ func TestAStatesDataIsReadAndASocketWaitedFor(t *testing.T) { } func TestTheProbesAreTheGoalsAndTheKernels(t *testing.T) { - if got := ProbeNames(); !slices.Equal(got, []string{"bootchart", "density", "exits", "initcalls", "ledger", "prestart", "restore-first", "restore-together", "run-delay", "ssh-first", "transport", "usage"}) { + if got := ProbeNames(); !slices.Equal(got, []string{"bootchart", "build", "density", "exits", "initcalls", "io", "ledger", "prestart", "restore-first", "restore-together", "run-delay", "ssh-first", "transport", "usage"}) { t.Errorf("probes %v", got) } for _, name := range ProbeNames() { diff --git a/internal/lab/fio.Dockerfile b/internal/lab/fio.Dockerfile new file mode 100644 index 00000000..64543f77 --- /dev/null +++ b/internal/lab/fio.Dockerfile @@ -0,0 +1,30 @@ +# internal/lab's fio edit: fio compiled from the release tarball versions.yaml pins, for a lab +# overlay and never for the base image. The context is the directory holding the tarball, which +# fioEdit fetched and checked; it is checked again here, on the bytes that are compiled. +# +# On the Ubuntu the guest runs, so the binary links the guest's own libc and nothing else: the +# io probe's jobs use io_uring, which fio reaches through its own system calls, not a library. +ARG UBUNTU_IMAGE +FROM ${UBUNTU_IMAGE} AS build + +ARG FIO_VERSION +ARG FIO_SHA256 +ENV DEBIAN_FRONTEND=noninteractive + +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +RUN apt-get update && \ + apt-get install -y --no-install-recommends gcc libc6-dev make + +COPY fio-${FIO_VERSION}.tar.gz /build/source.tar.gz +WORKDIR /build +RUN echo "${FIO_SHA256} source.tar.gz" | sha256sum -c - && \ + mkdir src && tar -xzf source.tar.gz -C src --strip-components=1 && \ + cd src && ./configure --disable-native && \ + make -j"$(nproc)" && \ + ./fio --enghelp | grep -qx '[[:space:]]*io_uring' && \ + test "$(./fio --version)" = "fio-${FIO_VERSION}" && \ + install -D -m 0755 fio /out/fio + +FROM scratch AS bin +COPY --from=build /out/ / diff --git a/internal/lab/gobuild.go b/internal/lab/gobuild.go new file mode 100644 index 00000000..3f39453b --- /dev/null +++ b/internal/lab/gobuild.go @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: Apache-2.0 + +package lab + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + + xssh "golang.org/x/crypto/ssh" +) + +// goBuild is what nesting costs a build a workspace runs (#563): the Go toolchain building cmd/go +// from its own source with an empty build cache, on a workspace disk attached after the boot, as +// spin hands a workspace its filesystem. It is compile-bound with the reads and writes a build +// makes, and needs nothing the image lacks but the toolchain, which the disk carries. +// +// The toolchain is the host's own (`go env GOROOT`), which go.mod's toolchain line pins and the +// checksum database verified when it was downloaded, so the nested run and the metal run of one +// commit build with the same compiler. The disk is a raw ext4 image on the host's tmpfs, for the +// reason the io probe's is. +type goBuild struct{} + +func (goBuild) Name() string { return "build" } +func (goBuild) About() string { + return "`go build cmd/go` inside the guest with an empty cache, on an ext4 disk on the host's tmpfs attached after the boot, `sync` included" +} + +func (goBuild) Options() []Option { return shape } + +func (goBuild) Rows(Options) []string { return []string{"cmd/go"} } +func (goBuild) Phases() int { return 1 } + +func (goBuild) Needs(o Options) []Need { + return append(append(bootNeeds, Need{"boot", "vsock-cid"}, Need{"boot", "console"}, Need{"boot", "append"}, + Need{"boot", "qmp"}, Need{"attach", "disk-serial"}), plugNeeds(o)...) +} + +func (goBuild) Metrics() []Metric { + return []Metric{ + {"wall", "ms", "the build and its sync, on the guest's clock"}, + {"host_cpu", "ms", "QEMU's CPU time over the build, every thread"}, + {"guest_cpu", "ms", "the guest's busy time over the build, all vCPUs"}, + } +} + +// goDisk makes the workspace disk a build starts from at path: a raw ext4 image holding the +// host's Go toolchain at /go. It returns the toolchain's version. +func goDisk(path string) (string, error) { + out, err := exec.Command("go", "env", "GOROOT", "GOVERSION").Output() + f := strings.Fields(string(out)) + if err != nil || len(f) != 2 { + return "", fmt.Errorf("asking go for its GOROOT and version: %v %q", err, out) + } + tree := path + ".tree" + if err := os.Mkdir(tree, 0o755); err != nil { + return "", fmt.Errorf("making %s: %w", tree, err) + } + if err := run("cp", "-r", f[0], filepath.Join(tree, "go")); err != nil { + return "", err + } + if err := run("mkfs.ext4", "-q", "-F", "-E", "root_owner=0:0", "-d", tree, path, "4G"); err != nil { + return "", err + } + // The module cache's toolchain is read-only, and so is its copy. + return f[1], run("sh", "-c", `chmod -R u+w "$1" && rm -rf "$1"`, "-", tree) +} + +// mutate-lane: TestEveryProbeMeasuresATree +func (goBuild) Measure(_ context.Context, m *Measurement) error { + dir, remove, err := tmpfsDir() + if err != nil { + return err + } + defer remove() + disk := filepath.Join(dir, "workspace.raw") + version, err := goDisk(disk) + if err != nil { + return err + } + mc, cid, _, err := m.bootLoggedIn("build.qcow2") + if mc != nil { + defer mc.Stop() + } + if err != nil { + return err + } + dev, err := m.attachRaw(cid, "build.qcow2", disk, "ws") + if err != nil { + return err + } + env := "export GOROOT=/mnt/ws/go PATH=/mnt/ws/go/bin:$PATH GOCACHE=/mnt/ws/cache GOTMPDIR=/mnt/ws/tmp GOPATH=/mnt/ws/gopath GOTOOLCHAIN=local CGO_ENABLED=0 GOFLAGS=" + if _, _, err := m.Key.Run(cid, xssh.KeyExchangeMLKEM768X25519, "mkdir -p /mnt/ws && mount "+dev+" /mnt/ws && mkdir -p /mnt/ws/tmp && "+env+" && test \"$(go env GOVERSION)\" = "+version); err != nil { + return Miss("mounting the workspace disk and finding %s on it: %v", version, err) + } + script := env + "; head -1 /proc/stat; s=$(date +%s%N); go build -o /mnt/ws/out cmd/go >&2 && sync && e=$(date +%s%N) && echo $(( (e - s) / 1000 )); head -1 /proc/stat" + host0, err := qemuCPU(mc.PID()) + if err != nil { + return err + } + _, out, err := m.Key.Run(cid, xssh.KeyExchangeMLKEM768X25519, script) + if err != nil { + return Miss("go build cmd/go: %v", err) + } + host1, err := qemuCPU(mc.PID()) + if err != nil { + return err + } + guest, between, err := guestBusyAround(out) + if err != nil { + return Miss("go build cmd/go: %v", err) + } + us, err := strconv.ParseInt(strings.TrimSpace(between), 10, 64) + if err != nil { + return Miss("go build cmd/go said no time: %q", between) + } + m.Record("wall", float64(us)/1000) + m.Record("host_cpu", ms(host1-host0)) + m.Record("guest_cpu", ms(guest)) + m.Logf("go build cmd/go (%s): %d ms, host CPU %.0f ms, guest CPU %.0f ms", version, us/1000, ms(host1-host0), ms(guest)) + return nil +} diff --git a/internal/lab/io.go b/internal/lab/io.go new file mode 100644 index 00000000..6db72710 --- /dev/null +++ b/internal/lab/io.go @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: Apache-2.0 + +package lab + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + + "github.com/spin-stack/go-tools/versions" + "github.com/spin-stack/machine/internal/build" + xssh "golang.org/x/crypto/ssh" + "golang.org/x/sys/unix" +) + +// fioName is the edit that puts fio in a tree's overlays, which the io probe runs. +const fioName = "fio" + +// fioEdit is fio, built from the release versions.yaml pins on the guest's Ubuntu, installed in the +// overlay at /usr/local/bin/fio. +func fioEdit(checkout, dir string) (Edit, error) { + pins, err := versions.Load(filepath.Join(checkout, versions.File)) + if err != nil { + return Edit{}, err + } + e, err := pins.Get("fio") + if err != nil { + return Edit{}, err + } + source := filepath.Join(dir, fioName, "source") + if err := fetchPinned(e.URL(), e.Pin, filepath.Join(source, "fio-"+e.Version+".tar.gz")); err != nil { + return Edit{}, err + } + args, err := build.Args(pins, strings.Fields("ubuntu fio")...) + if err != nil { + return Edit{}, err + } + out := filepath.Join(dir, fioName) + cmd := exec.Command("docker", slices.Concat([]string{"buildx", "build", "--progress=plain", "--platform", "linux/amd64", + "--file", filepath.Join(checkout, "internal", "lab", "fio.Dockerfile")}, args, + []string{"--output", "type=local,dest=" + out, source})...) + if b, err := cmd.CombinedOutput(); err != nil { + return Edit{}, fmt.Errorf("building fio %s: %w: %s", e.Version, err, b) + } + bin := filepath.Join(out, "fio") + sum, err := fileSHA256(bin) + if err != nil { + return Edit{}, fmt.Errorf("the fio %s build wrote no binary: %w", e.Version, err) + } + return Edit{Setup: `echo "` + sum + ` ` + bin + `" | sha256sum -c --quiet +install -m 0755 ` + bin + ` "$MNT/usr/local/bin/fio" +`}, nil +} + +// ioProbe is what nesting costs a running workspace's disk I/O (#563): fio inside the guest +// against a disk attached after the boot, as spin attaches a workspace's disks, one job a row. +// +// The number the cost model needs is the host CPU a GiB moved takes, nested against metal: QEMU's +// own CPU time, which holds the guest's vCPUs (the guest's own time included) and the threads that +// do its disk I/O. Throughput alone can tie while one side burns more CPU to get it. +// +// The disk is a raw file on the host's tmpfs, on both hosts. The bench's scratch is local NVMe and +// bench-metal's is EBS, and QEMU writes through the host's page cache (no cache.direct), so a disk +// on either would have measured the writeback to two different devices beside the virtualization. +// On tmpfs every request ends in the host's memory, and what is left to differ is the path through +// one hypervisor or two. Which device spin's hosts should keep a workspace on is another question. +// +// Each job runs time-based with no ramp: the CPU is read around the whole of fio's run, so the +// bytes it is divided by are the whole run's too. +type ioProbe struct{} + +// ioJob is one fio job, named as its row. +type ioJob struct { + name, rw, bs string + depth int +} + +// ioJobs are 4 KiB random I/O at one request in flight and at 32, and 1 MiB sequential at 8: the +// small requests a build or a database makes, where the cost is per request, and the large ones a +// copy makes, where it is per byte. +var ioJobs = []ioJob{ + {"randread-4k-qd1", "randread", "4k", 1}, + {"randwrite-4k-qd1", "randwrite", "4k", 1}, + {"randread-4k-qd32", "randread", "4k", 32}, + {"randwrite-4k-qd32", "randwrite", "4k", 32}, + {"read-1m-qd8", "read", "1m", 8}, + {"write-1m-qd8", "write", "1m", 8}, +} + +func (ioProbe) Name() string { return "io" } +func (ioProbe) About() string { + return "fio inside the guest against a raw disk on the host's tmpfs, attached after the boot; host CPU is QEMU's, guest CPU is the guest's busy time" +} + +func (ioProbe) Options() []Option { + names := make([]string, len(ioJobs)) + for i, j := range ioJobs { + names[i] = j.name + } + return append(shape, + Option{"jobs", strings.Join(names, " "), "the fio jobs, a row each"}, + Option{"runtime", "10", "seconds each job runs"}, + Option{"size", "1024", "MiB of the attached disk, every page of it allocated before the boot"}) +} + +func (ioProbe) Rows(o Options) []string { return o.Fields("jobs") } +func (ioProbe) Phases() int { return 1 } + +func (ioProbe) Needs(o Options) []Need { + return append(append(bootNeeds, Need{"boot", "vsock-cid"}, Need{"boot", "console"}, Need{"boot", "append"}, + Need{"boot", "qmp"}, Need{"attach", "disk-serial"}), plugNeeds(o)...) +} + +func (ioProbe) Metrics() []Metric { + return []Metric{ + {"iops", "IOPS", "fio's requests a second"}, + {"mibps", "MiB/s", "fio's bytes a second"}, + {"clat_p50", "µs", "a request's completion latency, median"}, + {"clat_p99", "µs", "a request's completion latency, 99th percentile"}, + {"host_cpu", "ms/GiB", "QEMU's CPU time, every thread, for each GiB moved"}, + {"guest_cpu", "ms/GiB", "the guest's busy time, all vCPUs, for each GiB moved"}, + } +} + +// mutate-lane: TestEveryProbeMeasuresATree +func (ioProbe) Measure(_ context.Context, m *Measurement) error { + i := slices.IndexFunc(ioJobs, func(j ioJob) bool { return j.name == m.Row }) + if i < 0 { + return fmt.Errorf("io has no job %q", m.Row) + } + job := ioJobs[i] + disk, remove, err := tmpfsDisk("io.raw", int64(m.Options.Int("size"))<<20) + if err != nil { + return err + } + defer remove() + mc, cid, _, err := m.bootLoggedIn("io.qcow2") + if mc != nil { + defer mc.Stop() + } + if err != nil { + return err + } + dev, err := m.attachRaw(cid, "io.qcow2", disk, "io") + if err != nil { + return err + } + if _, _, err := m.Key.Run(cid, xssh.KeyExchangeMLKEM768X25519, "test -x /usr/local/bin/fio"); err != nil { + return Refuse("the tree has no fio: make it with --edit fio") + } + fio := fmt.Sprintf("/usr/local/bin/fio --output-format=json --name=%s --filename=%s --direct=1 --ioengine=io_uring --rw=%s --bs=%s --iodepth=%d --time_based --runtime=%d", + job.name, dev, job.rw, job.bs, job.depth, m.Options.Int("runtime")) + host0, err := qemuCPU(mc.PID()) + if err != nil { + return err + } + _, out, err := m.Key.Run(cid, xssh.KeyExchangeMLKEM768X25519, "head -1 /proc/stat; "+fio+"; head -1 /proc/stat") + if err != nil { + return Miss("fio's %s: %v", job.name, err) + } + host1, err := qemuCPU(mc.PID()) + if err != nil { + return err + } + guest, report, err := guestBusyAround(out) + if err != nil { + return Miss("fio's %s: %v", job.name, err) + } + r, err := parseFio(report) + if err != nil { + return Miss("fio's %s: %v", job.name, err) + } + gib := float64(r.bytes) / (1 << 30) + if gib == 0 { + return Miss("fio's %s moved nothing", job.name) + } + m.Record("iops", r.iops) + m.Record("mibps", float64(r.bytes)/(1<<20)/r.seconds) + m.Record("clat_p50", r.p50) + m.Record("clat_p99", r.p99) + m.Record("host_cpu", ms(host1-host0)/gib) + m.Record("guest_cpu", ms(guest)/gib) + m.Logf("%s: %.0f IOPS, host %.0f ms/GiB, guest %.0f ms/GiB", job.name, r.iops, ms(host1-host0)/gib, ms(guest)/gib) + return nil +} + +// tmpfsDir is a directory on the host's tmpfs for a measurement's disks, and what removes it, which +// the caller runs once the machine that has them open is stopped: left to the experiment's end, a +// run's disks would fill the host's memory. +func tmpfsDir() (string, func(), error) { + dir, err := os.MkdirTemp("/dev/shm", "lab-disk") + if err != nil { + return "", nil, fmt.Errorf("making a directory on /dev/shm for a disk: %w", err) + } + return dir, removeAll(dir), nil +} + +// tmpfsDisk is a raw disk of size bytes on the host's tmpfs, every page allocated, and what removes +// it (tmpfsDir). +func tmpfsDisk(name string, size int64) (string, func(), error) { + dir, remove, err := tmpfsDir() + if err != nil { + return "", nil, err + } + path := filepath.Join(dir, name) + f, err := os.Create(path) + if err == nil { + err = unix.Fallocate(int(f.Fd()), 0, 0, size) + err = errors.Join(err, f.Close()) + } + if err != nil { + remove() + return "", nil, fmt.Errorf("allocating %d MiB at %s: %w", size>>20, path, err) + } + return path, remove, nil +} + +// attachRaw gives the machine booted as name (bootLoggedIn's, sized through its monitor) the raw +// disk at path, as spin attaches a workspace's disks, and returns the device the guest made of it. +// mutate-lane: TestEveryProbeMeasuresATree +func (m *Measurement) attachRaw(cid uint32, name, path, serial string) (string, error) { + if m.Options.Int("plugged") == 0 { + return "", fmt.Errorf("a disk is attached over the monitor that sizes the guest, and plugged=0 opens none") + } + if err := m.SpinMachine("attach", "--qmp", m.qmpPath(name), "--release", m.Tree.Dir, "--disk", path, + "--disk-format", "raw", "--disk-serial", serial); err != nil { + return "", Miss("attaching %s: %v", path, err) + } + // The disk sits on the hotplug controller, a SCSI disk to the guest, and the guest makes its + // device asynchronously after QEMU has it. + wait := fmt.Sprintf(`for i in $(seq 200); do d=$(lsblk -dnpo NAME,SERIAL | awk '$2 == "%s" { print $1 }'); test -n "$d" && break; sleep 0.05; done; echo "$d"`, serial) + _, out, err := m.Key.Run(cid, xssh.KeyExchangeMLKEM768X25519, wait) + dev := strings.TrimSpace(out) + if err != nil || !strings.HasPrefix(dev, "/dev/") { + return "", Miss("the guest made no device of the disk %s: %q %v", serial, dev, err) + } + return dev, nil +} + +// qemuCPU is the CPU time process pid has had, every thread's, the exited ones' included: +// /proc/PID/stat's utime and stime. A vCPU thread's time running the guest is in its utime. +func qemuCPU(pid int) (time.Duration, error) { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return 0, fmt.Errorf("reading QEMU's CPU time: %w", err) + } + return statCPU(string(b)) +} + +// statCPU is utime plus stime of a /proc/PID/stat, read after the command's closing parenthesis, +// since a command may hold spaces. Both are in USER_HZ ticks, 100 a second on Linux's ABI. +func statCPU(stat string) (time.Duration, error) { + i := strings.LastIndexByte(stat, ')') + if i < 0 { + return 0, fmt.Errorf("a /proc/PID/stat with no command: %q", stat) + } + f := strings.Fields(stat[i+1:]) + if len(f) < 13 { + return 0, fmt.Errorf("a /proc/PID/stat with no utime and stime: %q", stat) + } + u, err1 := strconv.ParseInt(f[11], 10, 64) + s, err2 := strconv.ParseInt(f[12], 10, 64) + if err1 != nil || err2 != nil { + return 0, fmt.Errorf("a /proc/PID/stat whose utime and stime are not numbers: %q", stat) + } + return time.Duration(u+s) * 10 * time.Millisecond, nil +} + +// guestBusyAround reads a command's output that began and ended with the guest's /proc/stat cpu +// line, and returns the busy time between them and what came between. Busy is user, nice, system, +// irq and softirq: steal is time the vCPU did not run at all, and idle and iowait are not work. +func guestBusyAround(out string) (time.Duration, string, error) { + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + if len(lines) < 3 { + return 0, "", fmt.Errorf("no /proc/stat lines around the output: %q", out) + } + before, err := busyTicks(lines[0]) + if err != nil { + return 0, "", err + } + after, err := busyTicks(lines[len(lines)-1]) + if err != nil { + return 0, "", err + } + return time.Duration(after-before) * 10 * time.Millisecond, strings.Join(lines[1:len(lines)-1], "\n"), nil +} + +func busyTicks(line string) (int64, error) { + f := strings.Fields(line) + if len(f) < 9 || f[0] != "cpu" { + return 0, fmt.Errorf("not /proc/stat's cpu line: %q", line) + } + var busy int64 + for _, i := range []int{1, 2, 3, 6, 7} { + n, err := strconv.ParseInt(f[i], 10, 64) + if err != nil { + return 0, fmt.Errorf("/proc/stat's cpu line has %q for a count: %q", f[i], line) + } + busy += n + } + return busy, nil +} + +// fioResult is one job's numbers from fio's JSON report, the read side's or the write side's. +type fioResult struct { + iops, p50, p99, seconds float64 + bytes int64 +} + +func parseFio(report string) (fioResult, error) { + type side struct { + IOBytes int64 `json:"io_bytes"` + IOPS float64 `json:"iops"` + Runtime float64 `json:"runtime"` // ms + Clat struct { + Percentile map[string]float64 `json:"percentile"` + } `json:"clat_ns"` + } + var r struct { + Jobs []struct { + Error int `json:"error"` + Read side `json:"read"` + Write side `json:"write"` + } `json:"jobs"` + } + if err := json.Unmarshal([]byte(report), &r); err != nil { + return fioResult{}, fmt.Errorf("reading fio's report: %w: %.200q", err, report) + } + if len(r.Jobs) != 1 || r.Jobs[0].Error != 0 { + return fioResult{}, fmt.Errorf("fio's report has %d jobs, or an error: %.200q", len(r.Jobs), report) + } + s := r.Jobs[0].Read + if s.IOBytes == 0 { + s = r.Jobs[0].Write + } + if s.Runtime == 0 { + return fioResult{}, fmt.Errorf("fio's report has no runtime: %.200q", report) + } + return fioResult{iops: s.IOPS, bytes: s.IOBytes, seconds: s.Runtime / 1000, + p50: s.Clat.Percentile["50.000000"] / 1000, p99: s.Clat.Percentile["99.000000"] / 1000}, nil +} diff --git a/internal/lab/io_test.go b/internal/lab/io_test.go new file mode 100644 index 00000000..e779450d --- /dev/null +++ b/internal/lab/io_test.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 + +package lab + +import ( + "testing" + "time" +) + +func TestQEMUsCPUIsUtimeAndStimeAfterItsName(t *testing.T) { + // A command with a space and a parenthesis in it, as a thread's name can have. + stat := "4242 (qemu-system-x86) (x) S 1 4242 4242 0 -1 4194560 100 0 0 0 250 50 0 0 20 0 9 0 100 0 0" + got, err := statCPU(stat) + if err != nil || got != 3*time.Second { + t.Errorf("statCPU = %v, %v; want 3s", got, err) + } + if _, err := statCPU("4242 qemu S 1"); err == nil { + t.Error("a stat with no command read as one") + } +} + +func TestTheGuestsBusyTimeLeavesOutIdleIowaitAndSteal(t *testing.T) { + out := "cpu 100 1 50 9000 30 2 3 40 0 0\n{\"jobs\": []}\nline two\ncpu 300 1 70 9900 90 4 5 400 0 0\n" + busy, between, err := guestBusyAround(out) + if err != nil { + t.Fatal(err) + } + // user +200, system +20, irq +2, softirq +2: 224 ticks of 10 ms. + if busy != 2240*time.Millisecond { + t.Errorf("busy = %v, want 2.24s", busy) + } + if between != "{\"jobs\": []}\nline two" { + t.Errorf("between = %q", between) + } + if _, _, err := guestBusyAround("cpu 1 2 3 4 5 6 7 8\n"); err == nil { + t.Error("output with nothing between the lines read as a run") + } +} + +func TestFiosReportIsReadFromTheSideThatMovedBytes(t *testing.T) { + report := `{"jobs": [{"error": 0, + "read": {"io_bytes": 0, "iops": 0, "runtime": 0}, + "write": {"io_bytes": 2147483648, "iops": 52428.8, "runtime": 10000, + "clat_ns": {"percentile": {"50.000000": 18432, "99.000000": 61440}}}}]}` + r, err := parseFio(report) + if err != nil { + t.Fatal(err) + } + if r.bytes != 2<<30 || r.iops != 52428.8 || r.seconds != 10 || r.p50 != 18.432 || r.p99 != 61.44 { + t.Errorf("parseFio = %+v", r) + } + if _, err := parseFio(`{"jobs": [{"error": 5}]}`); err == nil { + t.Error("a job that failed read as a result") + } +} diff --git a/internal/lab/lane_test.go b/internal/lab/lane_test.go index 57bb5eeb..a479c100 100644 --- a/internal/lab/lane_test.go +++ b/internal/lab/lane_test.go @@ -60,17 +60,25 @@ func TestEveryProbeMeasuresATree(t *testing.T) { if err != nil { t.Fatal(err) } + // io runs only a tree that carries fio. + fioed, err := MakeTree(filepath.Join(t.TempDir(), "fioed"), TreeSpec{Name: "fioed", From: from, SpinMachine: "here", Edits: []string{"lane", fioName}}, + Sources{Checkout: checkoutRoot(t), Cache: t.TempDir(), Log: io.Discard}) + if err != nil { + t.Fatal(err) + } for _, name := range ProbeNames() { t.Run(name, func(t *testing.T) { p := Probes[name] - trees, keep := trees, t.TempDir() + trees, keep, opts := trees, t.TempDir(), Options{} switch name { case bootchartName: trees = []*Tree{charted} case ledgerName: trees = []*Tree{traced} + case "io": + trees, opts = []*Tree{fioed}, Options{"jobs": "randwrite-4k-qd32", "runtime": "1"} } - r, err := Experiment{Probe: p, Trees: trees, Reps: 1, Options: Options{}, Scratch: t.TempDir(), Keep: keep, Log: io.Discard}.Run(t.Context()) + r, err := Experiment{Probe: p, Trees: trees, Reps: 1, Options: opts, Scratch: t.TempDir(), Keep: keep, Log: io.Discard}.Run(t.Context()) if err != nil { t.Fatal(err) } diff --git a/internal/lab/overlay.go b/internal/lab/overlay.go index 6adacaa8..2a0b97f6 100644 --- a/internal/lab/overlay.go +++ b/internal/lab/overlay.go @@ -217,8 +217,10 @@ func namedEdit(name, checkout, dir string) (Edit, error) { return bootchartEdit(checkout, dir) case ledgerName: return ledgerEdit, nil + case fioName: + return fioEdit(checkout, dir) } - return Edit{}, fmt.Errorf("no edit named %q; the edits are: lane, pressure, floor, nolinger, forwarder-early, carry-masks, carry-generators, carry-coldplug, carry-journal, carry-docker, carry-lane-logind, carry-keygen, bootchart, ledger", name) + return Edit{}, fmt.Errorf("no edit named %q; the edits are: lane, pressure, floor, nolinger, forwarder-early, carry-masks, carry-generators, carry-coldplug, carry-journal, carry-docker, carry-lane-logind, carry-keygen, bootchart, ledger, fio", name) } // The carry-* edits take back, from a release's overlay, what the image does to systemd for boot diff --git a/internal/lab/probe.go b/internal/lab/probe.go index d45806fc..ae4cde37 100644 --- a/internal/lab/probe.go +++ b/internal/lab/probe.go @@ -447,9 +447,11 @@ func (m *Measurement) SpinMachine(args ...string) error { // Probes are the probes there are, by name. var Probes = map[string]Probe{ "bootchart": bootchart{}, + "build": goBuild{}, "density": density{}, "exits": exitsProbe{}, "initcalls": initcalls{}, + "io": ioProbe{}, "ledger": ledgerProbe{}, "prestart": prestart{}, "restore-first": restoreFirst{}, diff --git a/versions.yaml b/versions.yaml index 90a4387b..8845d837 100644 --- a/versions.yaml +++ b/versions.yaml @@ -222,6 +222,18 @@ is deleted; `spin-machine-dev build image` (sshd-auth's version, the packages held), then `task boot:sshd-delay`. +- name: fio + kind: download + source: https://github.com/axboe/fio/archive/refs/tags/fio-{version}.tar.gz + version: '3.43' + pin: efa49b3f36eda9adf29294f27a87d7e457747d676cd0f73996d6365357832cfe + track: github-release https://github.com/axboe/fio fio- + note: >- + internal/lab's fio edit: fio compiled by internal/lab/fio.Dockerfile into a lab overlay and + never into the base image, for the io probe, which times a workspace's disk I/O from inside the + guest (spin-stack/machine#563). After the bump: `spin-machine-dev lab dispatch io --tree + 'release=--from release --edit fio' --reps 1` records every job's IOPS and CPU per GiB. + - name: systemd-bootchart kind: download source: https://github.com/spin-stack/systemd-bootchart/archive/{version}.tar.gz From 6fdc778f4a3441ec5ce75d674c334db66ef992ec Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Mon, 23 Nov 2026 14:52:12 -0300 Subject: [PATCH 2/2] lab: io's parsers held by tests, its host-only helpers by the KVM lane (#563) Co-Authored-By: Claude Opus 5.5 --- internal/lab/gobuild.go | 1 + internal/lab/io.go | 7 ++++-- internal/lab/io_test.go | 48 ++++++++++++++++++++++++++++++++++------- 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/internal/lab/gobuild.go b/internal/lab/gobuild.go index 3f39453b..152052a5 100644 --- a/internal/lab/gobuild.go +++ b/internal/lab/gobuild.go @@ -50,6 +50,7 @@ func (goBuild) Metrics() []Metric { // goDisk makes the workspace disk a build starts from at path: a raw ext4 image holding the // host's Go toolchain at /go. It returns the toolchain's version. +// mutate-lane: TestEveryProbeMeasuresATree func goDisk(path string) (string, error) { out, err := exec.Command("go", "env", "GOROOT", "GOVERSION").Output() f := strings.Fields(string(out)) diff --git a/internal/lab/io.go b/internal/lab/io.go index 6db72710..26b36b11 100644 --- a/internal/lab/io.go +++ b/internal/lab/io.go @@ -195,6 +195,7 @@ func (ioProbe) Measure(_ context.Context, m *Measurement) error { // tmpfsDir is a directory on the host's tmpfs for a measurement's disks, and what removes it, which // the caller runs once the machine that has them open is stopped: left to the experiment's end, a // run's disks would fill the host's memory. +// mutate-lane: TestEveryProbeMeasuresATree func tmpfsDir() (string, func(), error) { dir, err := os.MkdirTemp("/dev/shm", "lab-disk") if err != nil { @@ -205,6 +206,7 @@ func tmpfsDir() (string, func(), error) { // tmpfsDisk is a raw disk of size bytes on the host's tmpfs, every page allocated, and what removes // it (tmpfsDir). +// mutate-lane: TestEveryProbeMeasuresATree func tmpfsDisk(name string, size int64) (string, func(), error) { dir, remove, err := tmpfsDir() if err != nil { @@ -247,6 +249,7 @@ func (m *Measurement) attachRaw(cid uint32, name, path, serial string) (string, // qemuCPU is the CPU time process pid has had, every thread's, the exited ones' included: // /proc/PID/stat's utime and stime. A vCPU thread's time running the guest is in its utime. +// mutate-lane: TestEveryProbeMeasuresATree func qemuCPU(pid int) (time.Duration, error) { b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) if err != nil { @@ -259,10 +262,10 @@ func qemuCPU(pid int) (time.Duration, error) { // since a command may hold spaces. Both are in USER_HZ ticks, 100 a second on Linux's ABI. func statCPU(stat string) (time.Duration, error) { i := strings.LastIndexByte(stat, ')') - if i < 0 { + if i < 0 { // mutate-exempt: < 1 differs only on a stat that starts with ')', which none does return 0, fmt.Errorf("a /proc/PID/stat with no command: %q", stat) } - f := strings.Fields(stat[i+1:]) + f := strings.Fields(stat[i+1:]) // mutate-exempt: the kernel writes a space after the command, so i+2 reads the same fields if len(f) < 13 { return 0, fmt.Errorf("a /proc/PID/stat with no utime and stime: %q", stat) } diff --git a/internal/lab/io_test.go b/internal/lab/io_test.go index e779450d..6e8303ac 100644 --- a/internal/lab/io_test.go +++ b/internal/lab/io_test.go @@ -14,20 +14,31 @@ func TestQEMUsCPUIsUtimeAndStimeAfterItsName(t *testing.T) { if err != nil || got != 3*time.Second { t.Errorf("statCPU = %v, %v; want 3s", got, err) } - if _, err := statCPU("4242 qemu S 1"); err == nil { - t.Error("a stat with no command read as one") + for _, bad := range []string{ + "4242 qemu S 1 1 1 0 -1 0 0 0 0 0 250 50 0", + "4242 (q) S 1 1 1 0 -1 0 0 0 0 0 250", + "4242 (q) S 1 1 1 0 -1 0 0 0 0 0 x 50", + "4242 (q) S 1 1 1 0 -1 0 0 0 0 0 250 x", + } { + if _, err := statCPU(bad); err == nil { + t.Errorf("statCPU(%q) read a CPU time", bad) + } + } + // The thirteen fields after the command that utime and stime need, and no more. + if got, err := statCPU("1 (q) S 1 1 1 0 -1 0 0 0 0 0 7 3"); err != nil || got != 100*time.Millisecond { + t.Errorf("statCPU of the shortest stat = %v, %v", got, err) } } func TestTheGuestsBusyTimeLeavesOutIdleIowaitAndSteal(t *testing.T) { - out := "cpu 100 1 50 9000 30 2 3 40 0 0\n{\"jobs\": []}\nline two\ncpu 300 1 70 9900 90 4 5 400 0 0\n" + out := "cpu 100 1 50 9000 30 2 3 40 0 0\n{\"jobs\": []}\nline two\ncpu 300 1 70 9900 90 4 8 400 0 0\n" busy, between, err := guestBusyAround(out) if err != nil { t.Fatal(err) } - // user +200, system +20, irq +2, softirq +2: 224 ticks of 10 ms. - if busy != 2240*time.Millisecond { - t.Errorf("busy = %v, want 2.24s", busy) + // user +200, system +20, irq +2, softirq +5: 227 ticks of 10 ms. + if busy != 2270*time.Millisecond { + t.Errorf("busy = %v, want 2.27s", busy) } if between != "{\"jobs\": []}\nline two" { t.Errorf("between = %q", between) @@ -35,6 +46,13 @@ func TestTheGuestsBusyTimeLeavesOutIdleIowaitAndSteal(t *testing.T) { if _, _, err := guestBusyAround("cpu 1 2 3 4 5 6 7 8\n"); err == nil { t.Error("output with nothing between the lines read as a run") } + // The shortest: the two lines, eight counts each, and one line between. + if busy, between, err := guestBusyAround("cpu 1 0 0 0 0 0 0 0\nx\ncpu 2 0 0 0 0 0 0 0\n"); err != nil || busy != 10*time.Millisecond || between != "x" { + t.Errorf("guestBusyAround of the shortest output = %v, %q, %v", busy, between, err) + } + if _, _, err := guestBusyAround("cpu0 1 0 0 0 0 0 0 0\nx\ncpu0 2 0 0 0 0 0 0 0\n"); err == nil { + t.Error("one CPU's line read as the guest's") + } } func TestFiosReportIsReadFromTheSideThatMovedBytes(t *testing.T) { @@ -49,7 +67,21 @@ func TestFiosReportIsReadFromTheSideThatMovedBytes(t *testing.T) { if r.bytes != 2<<30 || r.iops != 52428.8 || r.seconds != 10 || r.p50 != 18.432 || r.p99 != 61.44 { t.Errorf("parseFio = %+v", r) } - if _, err := parseFio(`{"jobs": [{"error": 5}]}`); err == nil { - t.Error("a job that failed read as a result") + for _, bad := range []string{ + `{"jobs": [{"error": 5}]}`, + `{"jobs": [{"error": 0, "read": {"io_bytes": 1, "runtime": 1}}, {"error": 0, "read": {"io_bytes": 1, "runtime": 1}}]}`, + `{"jobs": [{"error": 0, "read": {"io_bytes": 4096, "iops": 1, "runtime": 0}}]}`, + } { + if _, err := parseFio(bad); err == nil { + t.Errorf("parseFio(%s) read a result", bad) + } + } +} + +func TestIOAndBuildMeasureInOnePass(t *testing.T) { + for _, name := range []string{"io", "build"} { + if n := Probes[name].Phases(); n != 1 { + t.Errorf("%s makes %d passes: each measurement boots its own machine and measures it once", name, n) + } } }