Files
w3cjandClaude Opus 5.5 dd46dd7a0f feat(tools): tool images build side by side
A first run built its tool images one after another, each paying a
build VM's boot (5.7 s on vz, 9.3 s on QEMU) before a download of a few
seconds to a minute. Share.Build now hands the images out to up to four
slots (buildAll), each slot's builds one after another in a build VM of
its own:

- slots: as many as the host's memory, less what the backend's running
  VMs have, and its CPUs give a build VM of 2 GiB and 2 CPUs each after
  keeping 6 GiB and 2 CPUs, at most backend.MaxToolSlots (4) and the
  number of images; one alone keeps base's size. A backend that can't
  list its VMs builds one at a time. A running VM's memory counts whole
  (7.5 GiB, not 7): TestBuildSlotsFit's running VMs fail when it isn't
  counted or is truncated.
- plan lowers the slots until the backend's disks have room:
  Floors.ForTools counts Tools once for each build VM at once, as on a
  disk without copy on write each is a whole copy of base.
- backend.ToolsSpec gets Slot, Slots, Size and Hold; Lima's slot VMs are
  the constants ToolsVM to ToolsVM4, sized with --cpus/--memory, and the
  first slot's build deletes what a killed run left in the slots this
  run doesn't use. Builds hold the share's lock, so one devvm uses the
  slots.
- A failed build's VM goes in the run's cleanup, which runs after the
  build let go of the share's lock: it deletes the VM only once it has
  the lock again (ToolsSpec.Hold, Env.holdShare's TryLockFile), and
  leaves it while another devvm holds it (a build, gc or the daily
  refresh) (TestBuildToolsCleanupHolds, TestBuildHoldsShareForCleanup).
  The next tools build deletes what it finds in the slots, and so does
  devvm gc, which holds the share's lock: backend.Images'
  DeleteToolsLeft, Lima's deleting the slots' build VMs that are there
  and no other VM, which gc asks of every backend first, without
  asking, a backend that can't being a run log line. It returns what
  it deleted, which gc names in one line (tools_build_vms_deleted), and
  gc then never says nothing_to_clean or nothing_deleted
  (gc_tools_build.txtar, TestDeleteToolsLeft in lima and vm, the fake's
  ToolsLeft). The cli skill's judgment.md names this exception to "gc
  --force deletes exactly what gc lists". The conformance suite's
  delete-tools-left checks that it deletes no other VM, not even the
  project VM of a folder named tools (devvm-tools-<hash>), and no image
  (TestConformanceFinds: deletesAllVMs, deletesImage, deletesByPrefix).
  The share's lock
  is the data folder's, so devvms with their own data folders and one
  Lima home don't exclude each other's builds: the docs say not to build
  tools or run gc in two at once (a lock per build VM in the Lima home
  would close it, but it would replace Hold and needs e2e).
- Side by side, one status line covers the builds
  (building_tools_together), and their commands' lines in the run log
  are tagged with their tool (msg.WithLogTag): the UI's LoggedCmd
  prefixes them and shows no status line of its own. Every write starts
  with the tag, as does every line in it, one ended by "\r" included,
  so no build can pass a line off as another's (TestTaggedWrites), and
  a tool's lines are found after another's "\r" (taggedLines splits
  there, a progress bar's updates staying one line: TestTaggedLines). The
  first failure cancels the others and is what Build returns, tagged
  (backend.LoggedIn), so ErrorLogged shows that tool's lines' end.
- A test build's DEVVM_TOOL_SLOTS caps the slots; the CLI tests set 1,
  so the stub's calls keep their order, and tools_side_by_side.txtar
  sets 3, with an interrupt that leaves no build VM. The stub keeps each
  build VM's folder by its name, and the fake backend's BuildTools runs
  its builds outside its lock, as a real backend's would, passing
  ToolsBuild its context.

Docs: images.md's Building tools and Free space, ports-size.md,
space.md, images.md (using) and gc's help (the build VMs gc deletes),
settings.md (one Lima home for two data folders), extending.md,
testing.md and tests.md; the cli skill's judgment.md; the CHANGELOG's
first highlight and the release page's A faster first run.

New messages: building_tools_together, tools_build_vms_deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 22:57:15 -07:00

214 lines
6.7 KiB
Go

package lima
import (
"bytes"
"context"
"errors"
"slices"
"strconv"
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/vmname"
)
// The throwaway VMs shared tools are built in, one for each slot of the
// builds running side by side (backend.MaxToolSlots): ToolsVM is the
// first's.
const (
ToolsVM vmname.VM = "devvm-tools-build"
ToolsVM2 vmname.VM = "devvm-tools-build-2"
ToolsVM3 vmname.VM = "devvm-tools-build-3"
ToolsVM4 vmname.VM = "devvm-tools-build-4"
)
// toolsVMs are the slots' build VMs, by slot.
func toolsVMs() [backend.MaxToolSlots]vmname.VM {
return [...]vmname.VM{ToolsVM, ToolsVM2, ToolsVM3, ToolsVM4}
}
// BuildTools clones base's instance into its slot's build VM (toolsVMs),
// with spec.Out its only mount and spec.Size's CPUs and memory where
// they're set, starts it confined as spec.Net asks, runs the script with
// its arguments, and deletes it. A build VM a killed run left in the slot
// is deleted first, and the first slot's build deletes those left in the
// slots this run doesn't use (spec.Slots), so none stays however few
// later runs use. The VM goes however the run ends (a cleanup on the ui
// stack). The registry's guard has checked spec (ToolsSpec.Validate).
func (l *images) BuildTools(ctx context.Context, spec backend.ToolsSpec) error {
base, err := vmname.Image(spec.Base)
if err != nil {
return msg.ImageMissing(spec.Base)
}
ins, err := l.list(ctx)
if err != nil {
return err
}
in, ok := findInstance(ins, base)
if !ok {
return msg.ImageMissing(spec.Base)
}
if backend.Status(in.Status) != backend.StatusStopped {
if err := l.stop(ctx, base); err != nil {
return err
}
}
vm := toolsVMs()[spec.Slot]
for _, left := range toolsLeft(ins, spec) {
if err := l.delete(ctx, left); err != nil {
return err
}
}
mounts, err := mountsSet([]mount{outMount(spec.Out, spec.OutAt)})
if err != nil {
return err
}
// A failure leaves it to the cleanup, which runs once the caller has
// shown the run log's end, by then without the share's lock: unless
// it gets the lock again, another devvm's build may be using the
// slot, and that build deletes the leftover itself.
done := l.AddCleanup(func(ctx context.Context) {
if spec.Hold != nil {
release, ok := spec.Hold()
if !ok {
return
}
defer release()
}
_ = l.deleteIfThere(ctx, vm)
})
// Its steps: clone, configure (its new ssh port) and start, the script
// (the user's CAs before it), delete.
steps := 5
if !spec.Trust.None() {
steps++
}
// Each step names the tool it builds, not the build VM, which every
// tool's build in its slot shares.
ctx = withShown(l.WithSteps(ctx, steps), vm, msg.ToolsBuildVM(spec.Name).Text())
if err := l.Runner.Run(ctx, msg.CloningForTools(spec.Name), l.limactl(ctx, toolsArgs(base, vm, mounts, spec.Size)...)); err != nil {
return backend.Logged(msg.VMCreateFailed(vm))
}
// Behind a company proxy, through a proxy of devvm's (buildproxy.go).
conf, hp, proxyDone, err := buildProxy(ctx, l.Lima, vm, spec.Net)
if err != nil {
return err
}
if err := l.start(ctx, vm, nil, conf); err != nil {
return err
}
if err := l.runScript(ctx, vm, spec.Trust.Add, true); err != nil {
return err
}
cmd := l.limactl(ctx, append([]string{"shell", "--workdir", "/", vm.String(), "bash", "-s", "--"}, spec.Args...)...)
// The CAs' variables and the build's proxy for its commands, as each
// image build's step has them, never written into the VM.
cmd.Stdin = bytes.NewReader(slices.Concat(spec.Trust.Env, withProxy(hp, spec.Script).Data))
if err := l.Runner.Run(ctx, msg.BuildingTool(spec.Name), cmd); err != nil {
return backend.Logged(msg.ToolsBuildFailed())
}
if err := l.delete(ctx, vm); err != nil {
return err
}
proxyDone(true)
done()
return nil
}
// toolsArgs are limactl clone's arguments for a build VM: a clone of
// base's instance with mounts (mountsSet's), size's CPUs and memory where
// they're set, and nothing else from the host.
func toolsArgs(base, vm vmname.VM, mounts string, size backend.Size) []string {
args := []string{"clone", "--tty=false", "--mount-none", "--set", mounts}
if size.CPUs > 0 {
args = append(args, "--cpus="+strconv.Itoa(size.CPUs))
}
if size.MemoryGiB > 0 {
args = append(args, "--memory="+gibString(size.MemoryGiB))
}
return append(args, base.String(), vm.String())
}
// findInstance is the one of ins named vm.
func findInstance(ins []instance, vm vmname.VM) (instance, bool) {
for _, in := range ins {
if in.Name == vm {
return in, true
}
}
return instance{}, false
}
// toolsLeft are the build VMs in ins that spec's build deletes first, as
// a killed run left them: its own slot's, and from the first slot, those
// of the slots past the ones this run uses, which none of its builds is
// in (the share's lock keeps every other devvm of this data folder's out).
func toolsLeft(ins []instance, spec backend.ToolsSpec) []vmname.VM {
var out []vmname.VM
for s, vm := range toolsVMs() {
if s != spec.Slot && (spec.Slot != 0 || s < max(spec.Slots, 1)) {
continue
}
if _, ok := findInstance(ins, vm); ok {
out = append(out, vm)
}
}
return out
}
// DeleteToolsLeft deletes the slots' build VMs that are there (toolsVMs),
// and no other VM, returning those it deleted: the caller holds the
// share's lock, so none is a build of this data folder's that's running.
func (l *images) DeleteToolsLeft(ctx context.Context) ([]vmname.VM, error) {
ins, err := l.list(ctx)
if err != nil {
return nil, err
}
var deleted []vmname.VM
for _, vm := range toolsVMs() {
if _, ok := findInstance(ins, vm); ok {
if err := l.delete(ctx, vm); err != nil {
return deleted, err
}
deleted = append(deleted, vm)
}
}
return deleted, nil
}
// ToolFormat is build.sh's own: Lima's guests mount compressed EROFS.
func (l *images) ToolFormat() string { return "" }
type shownKey struct{}
// shownName is what a phase's steps call one VM.
type shownName struct {
vm vmname.VM
as string
}
// withShown has the steps on vm under ctx name it as as: a tool's build
// VM by its tool.
func withShown(ctx context.Context, vm vmname.VM, as string) context.Context {
return context.WithValue(ctx, shownKey{}, shownName{vm, as})
}
// shown is the name the steps on vm under ctx give it: withShown's, else
// its own.
func shown(ctx context.Context, vm vmname.VM) string {
if s, ok := ctx.Value(shownKey{}).(shownName); ok && s.vm == vm {
return s.as
}
return vm.String()
}
// deleteIfThere deletes a VM if devvm's Lima home has it.
func (l *images) deleteIfThere(ctx context.Context, vm vmname.VM) error {
if _, err := l.inspect(ctx, vm); errors.Is(err, backend.ErrNotFound) {
return nil
} else if err != nil {
return err
}
return l.delete(ctx, vm)
}