mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
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]>
404 lines
13 KiB
Go
404 lines
13 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/devvmhq/devvm/internal/backend"
|
|
"github.com/devvmhq/devvm/internal/image"
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/paths"
|
|
"github.com/devvmhq/devvm/internal/platform"
|
|
"github.com/devvmhq/devvm/internal/state"
|
|
"github.com/devvmhq/devvm/internal/trust"
|
|
)
|
|
|
|
// LockShare holds the share's lock, for a build writing tool images or a
|
|
// swap of the lock, until unlock is called or the process ends, however
|
|
// it ends: it's an OS lock on an open file. Another devvm holding it is
|
|
// waited for until ctx ends, under a status line (share_waiting).
|
|
func (t *Env) LockShare(ctx context.Context) (unlock func(), err error) {
|
|
if err := os.MkdirAll(t.Dirs.Tools(), 0o700); err != nil {
|
|
return nil, err
|
|
}
|
|
return platform.LockFile(ctx, t.Dirs.ShareLock(), msg.Waiting(t.Status, msg.ShareWaiting(t.Dirs.Tools())))
|
|
}
|
|
|
|
// holdShare takes the share's lock without waiting, for a cleanup after
|
|
// the build let go of it (backend.ToolsSpec.Hold): false when another
|
|
// devvm holds it, or it can't be taken.
|
|
func (t *Env) holdShare() (release func(), ok bool) {
|
|
unlock, ok, err := platform.TryLockFile(t.Dirs.ShareLock())
|
|
if err != nil || !ok {
|
|
return nil, false
|
|
}
|
|
return unlock, true
|
|
}
|
|
|
|
// ShareBusy reports whether another devvm holds the share's lock
|
|
// (LockShare) now; false when it can't tell.
|
|
func (t *Env) ShareBusy() bool {
|
|
unlock, ok, err := platform.TryLockFile(t.Dirs.ShareLock())
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if ok {
|
|
unlock()
|
|
}
|
|
return !ok
|
|
}
|
|
|
|
// Built reports whether a tool image is in the share with the record
|
|
// devvm wrote when it moved it in (FILE.json).
|
|
func (t Share) Built(file string) bool {
|
|
if fi, err := os.Stat(t.Dirs.ToolImage(file)); err != nil || !fi.Mode().IsRegular() {
|
|
return false
|
|
}
|
|
rec, err := state.ReadToolImage(t.Dirs, file)
|
|
return err == nil && (rec.Format != "" || !cutShort(t.Dirs.ToolImage(file)))
|
|
}
|
|
|
|
// The EROFS superblock, 1024 bytes into an image: its magic, then at 12
|
|
// the log2 of its block size and at 36 its block count, little-endian.
|
|
const (
|
|
erofsSuper = 1024
|
|
erofsMagic = 0xE0F5E1E2
|
|
erofsBlkszBits = 12
|
|
erofsBlocks = 36
|
|
)
|
|
|
|
// cutShort reports whether path, an EROFS tool image (build.sh's own
|
|
// format), ends before its superblock does (empty included), or is
|
|
// shorter than its superblock says: what Linux's 9p client can leave of a
|
|
// file written into a mount with Lima's mmap cache, as builds were before
|
|
// devvm chose none. Such an image counts as not built (Built), so the next
|
|
// build makes it again. A file long enough whose superblock isn't EROFS's
|
|
// is left to the guest's mount to refuse.
|
|
func cutShort(path string) bool {
|
|
f, err := os.Open(path) //nolint:gosec // a tool image in devvm's own share
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
fi, err := f.Stat()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
sb := make([]byte, erofsBlocks+4)
|
|
if fi.Size() < erofsSuper+int64(len(sb)) {
|
|
return true // empty, or ending before its superblock does
|
|
}
|
|
if _, err := f.ReadAt(sb, erofsSuper); err != nil || binary.LittleEndian.Uint32(sb) != erofsMagic {
|
|
return false
|
|
}
|
|
bits := sb[erofsBlkszBits]
|
|
if bits < 9 || bits > 16 {
|
|
return false
|
|
}
|
|
return int64(binary.LittleEndian.Uint32(sb[erofsBlocks:]))<<bits > fi.Size()
|
|
}
|
|
|
|
// Build builds the tool images these files name that the share lacks,
|
|
// each in a throwaway VM of its own made from base's image (key base) on
|
|
// b, its features checked against rv, in tg's format. base must be the
|
|
// base they're for (buildsFor). The VMs run upstream installers, so none
|
|
// sees the share, and none sees another tool's build: each writes into a
|
|
// folder of its own, and its one image is checked to be a plain file,
|
|
// moved into the share and its hash recorded.
|
|
func (t Share) Build(ctx context.Context, rv backend.Review, b backend.Backend, base string, tg Target, files []string) error {
|
|
var todo []string
|
|
for _, f := range files {
|
|
if !t.Built(f) {
|
|
todo = append(todo, f)
|
|
}
|
|
}
|
|
if len(todo) == 0 {
|
|
return nil
|
|
}
|
|
if err := t.buildsFor(base, tg); err != nil {
|
|
return err
|
|
}
|
|
// The company proxy the build goes through, with config.toml's
|
|
// password saved, before anything starts.
|
|
if t.Proxy != nil {
|
|
if _, err := t.Proxy.Upstream(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
spec := backend.ToolsSpec{Net: backend.NetInternet}
|
|
if err := rv.RequireFor(b, Label(todo), spec.Features()...); err != nil {
|
|
return err
|
|
}
|
|
unlock, err := t.LockShare(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer unlock()
|
|
lock, err := Versions(t).Lock(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var build []string
|
|
for _, f := range todo {
|
|
if t.Built(f) {
|
|
continue // another devvm built it while this one waited
|
|
}
|
|
tool, v, ok := image.ParseToolFile(f)
|
|
if !ok {
|
|
return msg.ToolBadOutput(f)
|
|
}
|
|
// build.sh installs the lock's version: the lock may have moved
|
|
// on while this one waited.
|
|
if cur, err := t.File(lock, tool, tg); err != nil {
|
|
return err
|
|
} else if cur != f {
|
|
return msg.ToolsChanged()
|
|
}
|
|
if t.noDownload(lock, tool, tg.Libc) {
|
|
return msg.ToolUnbuilt(tool, v)
|
|
}
|
|
build = append(build, f)
|
|
}
|
|
if len(build) == 0 {
|
|
return nil
|
|
}
|
|
// The build VMs are the backend's, as many as build at once (plan);
|
|
// the images come out into devvm's data folder, whatever the backend.
|
|
// Both grow with the tools built.
|
|
label := Label(build)
|
|
n, size, err := t.plan(ctx, b, label, len(build))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := (backend.Space{Free: t.FreeSpace}).CheckDir(t.Dirs.Data, label, backend.ToolImages(len(build))); err != nil {
|
|
return err
|
|
}
|
|
t.Info(msg.BuildingTools(label))
|
|
t.LogNote()
|
|
return t.buildAll(ctx, b, base, tg, lock, build, n, size)
|
|
}
|
|
|
|
// buildsFor refuses to build tg's tool images in the image with key base
|
|
// unless its record says it's the base they're for: devvm's own Ubuntu
|
|
// base for gnu, whatever base the VM has, and for musl a --from base
|
|
// with tg's digest, which their keys hash. So a gnu image, which any VM
|
|
// may mount, never builds in a --from image, whose code root in its
|
|
// build ran, and a musl one is only ever another VM's on the same image.
|
|
func (t Share) buildsFor(base string, tg Target) error {
|
|
rec, err := state.ReadImage(t.Dirs, base)
|
|
if err != nil {
|
|
return msg.ToolsWrongBase(base).Because(err)
|
|
}
|
|
ok := rec.Name == image.Base && rec.Libc == tg.Libc
|
|
switch tg.Libc {
|
|
case "gnu":
|
|
ok = ok && rec.From == "" && tg.Base == ""
|
|
case "musl":
|
|
ok = ok && rec.From != "" && rec.Digest != "" && rec.Digest == tg.Base
|
|
default:
|
|
ok = false
|
|
}
|
|
if !ok {
|
|
return msg.ToolsWrongBase(base)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// buildOne builds one tool image in a throwaway VM with a folder of its
|
|
// own, for tg, then moves it into the share. One VM and folder for each
|
|
// tool: whatever a tool's installer does in its VM, as root or not, it
|
|
// can't reach another tool's image, which its key doesn't hash. The VM is
|
|
// at's slot's (buildAll's).
|
|
func (t Share) buildOne(ctx context.Context, b backend.Backend, base string, tg Target, lock Lock, file string, at slot) error {
|
|
out, err := os.MkdirTemp(t.Dirs.Data, paths.ToolsBuildPrefix)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
remove := t.AddCleanup(func(context.Context) { _ = os.RemoveAll(out) })
|
|
defer func() {
|
|
_ = os.RemoveAll(out)
|
|
remove()
|
|
}()
|
|
if out, err = filepath.EvalSymlinks(out); err != nil {
|
|
return err
|
|
}
|
|
build := filepath.Join(out, ".build")
|
|
if err := os.Mkdir(build, 0o700); err != nil {
|
|
return err
|
|
}
|
|
config, err := t.config()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
script, err := image.OwnScript(t.Assets, "shared-tools/build.sh")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for name, data := range map[string][]byte{"mise.toml": config, "mise.lock": lock.Bytes()} {
|
|
if err := state.WriteFile(filepath.Join(build, name), data); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
tool, version, _ := image.ParseToolFile(file)
|
|
// The user's CAs, trusted in the build VM, which is deleted: a tool
|
|
// image's key holds none of them.
|
|
cas, err := trust.Read(t.Dirs.TrustedCAs())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ca, err := cas.Build(t.Assets)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
args := []string{tool, version, file}
|
|
if image.OwnDownload(tool) {
|
|
// build.sh fetches it itself, from the lock's download for this
|
|
// VM's platform, checked against the lock's checksum.
|
|
url, sum := lock.Download(tool, t.platform(tg.Libc))
|
|
if !strings.HasPrefix(url, "https://") || !strings.HasPrefix(sum, "sha512:") {
|
|
return msg.ToolUnbuilt(tool, version)
|
|
}
|
|
args = append(args, url, strings.TrimPrefix(sum, "sha512:"))
|
|
}
|
|
spec := backend.ToolsSpec{
|
|
Name: Label([]string{file}), Base: base, Out: out, OutAt: ShareAt, Args: args, Format: tg.Format,
|
|
Net: backend.NetInternet, Script: backend.Script{Name: "build.sh", Data: script}, Trust: ca,
|
|
Slot: at.at, Slots: at.n, Size: at.size, Hold: t.holdShare,
|
|
}
|
|
if err := b.BuildTools(ctx, spec); err != nil {
|
|
return err
|
|
}
|
|
return t.moveIn(b, out, tg, file)
|
|
}
|
|
|
|
// moveIn moves the tool image file that a build wrote into out, its VM
|
|
// gone, so nothing changes out now, into the share, with its record. Plain
|
|
// files only (a link could name a host file). Only the image leaves out;
|
|
// its hash is written in the share, never through a name the VM could
|
|
// have planted.
|
|
func (t Share) moveIn(b backend.Backend, out string, tg Target, file string) error {
|
|
src := filepath.Join(out, file)
|
|
if fi, err := os.Lstat(src); err != nil || !fi.Mode().IsRegular() || tg.Format == "" && cutShort(src) {
|
|
return msg.ToolBadOutput(file)
|
|
}
|
|
sum, err := image.SHA256File(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Its file name doesn't say what it's built for: the record does.
|
|
rec := state.ToolImage{SHA256: sum, Libc: tg.Libc, Base: tg.Base, Format: tg.Format, Backend: b.Name(), Built: t.Now().UTC().Truncate(time.Second), MadeBy: t.Version}
|
|
if tg.Libc == "gnu" {
|
|
if rec.Glibc, err = neededGlibc(filepath.Join(out, file+".glibc")); err != nil {
|
|
return msg.ToolBadOutput(file + ".glibc")
|
|
}
|
|
}
|
|
if err := os.Rename(src, t.Dirs.ToolImage(file)); err != nil {
|
|
return err
|
|
}
|
|
return state.WriteToolImage(t.Dirs, file, rec)
|
|
}
|
|
|
|
// maxGlibcOutput caps what's read of build.sh's FILE.glibc: one version.
|
|
const maxGlibcOutput = 64
|
|
|
|
// neededGlibc reads what build.sh measured of a gnu tool image, FILE.glibc
|
|
// in the build's folder: the newest glibc version its programs and
|
|
// libraries need, or nothing when they need none. It must be a plain file
|
|
// holding just that (image.ValidGlibc).
|
|
func neededGlibc(path string) (string, error) {
|
|
fi, err := os.Lstat(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !fi.Mode().IsRegular() || fi.Size() > maxGlibcOutput {
|
|
return "", errors.New("not a version")
|
|
}
|
|
data, err := os.ReadFile(path) //nolint:gosec // devvm's own build folder, checked to be a plain file
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
v := strings.TrimSuffix(string(data), "\n")
|
|
if v != "" && !image.ValidGlibc(v) {
|
|
return "", errors.New("not a version")
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
// HasBuilds refuses tool files that have no build for tg's C library
|
|
// before any is built: on a musl base, a tool whose project releases
|
|
// builds for glibc alone (image.GlibcOnly) refuses (tool_glibc_only),
|
|
// naming the first. mise's lock gives it the glibc download there too,
|
|
// which wouldn't run.
|
|
func HasBuilds(files []string, tg Target) error {
|
|
if tg.Libc != "musl" {
|
|
return nil
|
|
}
|
|
for _, f := range files {
|
|
if tool, _, _ := image.ParseToolFile(f); image.GlibcOnly(tool) {
|
|
return msg.ToolGlibcOnly(tool)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Runs checks that each of these tool images, built, runs on tg's base:
|
|
// a --from gnu base whose glibc is older than the newest one a tool image
|
|
// needs refuses it (tool_needs_glibc), naming the tool and both versions.
|
|
// A base without a glibc version (Ubuntu's own, musl) isn't checked.
|
|
func (t Share) Runs(files []string, tg Target) error {
|
|
if tg.Libc != "gnu" || !image.ValidGlibc(tg.Glibc) {
|
|
return nil
|
|
}
|
|
for _, f := range files {
|
|
rec, err := state.ReadToolImage(t.Dirs, f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// A record without a glibc version that's one (musl's) isn't checked.
|
|
if older, ok := image.GlibcOlder(tg.Glibc, rec.Glibc); ok && older {
|
|
tool, v, _ := image.ParseToolFile(f)
|
|
return msg.ToolNeedsGlibc(tg.Glibc, rec.Glibc, tool, v)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Unused returns the tool images of a List that it calls unused: neither
|
|
// the lock's version nor listed by a VM. Without a lock, none is. Callers
|
|
// deleting them hold the share's lock from before the List, so no build
|
|
// or lock swap changes the share meanwhile.
|
|
func Unused(ls []Listed) []Listed {
|
|
var out []Listed
|
|
for _, l := range ls {
|
|
if l.State == StateUnused && l.File != "" {
|
|
out = append(out, l)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Delete deletes tool images from the share, with their records. Only
|
|
// tool image names are taken, nothing else in the share.
|
|
func (t Share) Delete(files []string) error {
|
|
for _, f := range files {
|
|
if _, _, ok := image.ParseToolFile(f); !ok || filepath.Base(f) != f {
|
|
return fmt.Errorf("not a tool image: %q", f)
|
|
}
|
|
}
|
|
for _, f := range files {
|
|
for _, name := range []string{t.Dirs.ToolImage(f), t.Dirs.ToolRecord(f)} {
|
|
if err := os.Remove(name); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|