diff --git a/docs/content/docs/internals/docker.md b/docs/content/docs/internals/docker.md index 788f6a11..300d7108 100644 --- a/docs/content/docs/internals/docker.md +++ b/docs/content/docs/internals/docker.md @@ -43,7 +43,7 @@ Docker's engine is yours, and Docker Desktop's especially, so devvm marks and na Before `assets/layers/base.sh` runs, devvm adds what Ubuntu's cloud image has and a container lacks: `sudo`, CA certificates, `bash` and the VM's user, and on Alpine also OpenRC and ssh's client. After base's scripts, it adds `sshd` without host keys. These are the same scripts as on [smolvm](smolvm.md#building-images), and they're in `base`'s key. The user has your name and uid, and on Linux your group's id too, so the files it makes in the project folder are yours. Its home is `/home/.guest`. -The scripts run as that user, with stand-ins for `systemctl` and `rc-update` while they run, because containers run no init system. Base's CPUs and memory come from `base.yaml`: 4 CPUs and 8 GiB (half the engine's memory on a small one). +The scripts run as that user, with stand-ins for `systemctl` and `rc-update` while they run, because containers run no init system. Base's CPUs and memory come from `base.yaml`, which sets 4 CPUs and 8 GiB. When the engine's machine has fewer than 4 CPUs, base and the VMs you give no size get as many CPUs as it has, and when 8 GiB would leave it less than 2 GiB, they get half of its memory ([base's size](images.md#bases-size)). How devvm confines a build depends on the engine: diff --git a/docs/content/docs/internals/images.md b/docs/content/docs/internals/images.md index 4cb59617..e286fa0e 100644 --- a/docs/content/docs/internals/images.md +++ b/docs/content/docs/internals/images.md @@ -14,7 +14,7 @@ devvm builds each image in a VM of its own, and that VM then is the image: 3. The script runs. For base, that's `assets/layers/base.sh` and then the [features](../using/customizing.md) you chose, and for a layer, it's the layer's script. 4. The VM stops. devvm writes the image's record last, with its chain, what base started from, and its C library. -Nothing from the host is mounted into a build, because layer scripts run third-party installers, which mustn't see your files. base gets `base.yaml`'s memory, or half the host's memory when `base.yaml`'s would leave the host less than 2 GiB. The images built on base, and their VMs, keep that amount. +Nothing from the host is mounted into a build, because layer scripts run third-party installers, which mustn't see your files. base gets `base.yaml`'s CPUs, or as many as the host has when it has fewer. It gets `base.yaml`'s memory, or half the host's memory when `base.yaml`'s would leave the host less than 2 GiB. The images built on base, and their VMs, keep that size ([base's size](#bases-size)). ## Keys and caching @@ -74,10 +74,20 @@ The pinned release and its SHA-256 are part of base's key, so a new pin rebuilds ## Base's settings and pins -`assets/base.yaml` holds base's VM settings, which are 4 CPUs, 8 GiB of memory and a 100 GiB disk. `assets/layers/base.sh` installs base, and the optional [features](../using/customizing.md) you chose follow it. +`assets/base.yaml` holds base's VM settings, which are 4 CPUs, 8 GiB of memory and a 100 GiB disk, and devvm fits the CPUs and memory to the host ([base's size](#bases-size)). `assets/layers/base.sh` installs base, and the optional [features](../using/customizing.md) you chose follow it. Each download in `assets/layers/base.sh` is pinned to a version and a SHA-256 at the top of the script, and the build fails if a checksum doesn't match. Each feature pins its downloads in the same way, at the top of its script, `assets/features/.sh` in the repo, which is built into devvm. While base builds, apt's packages come from a dated snapshot of Ubuntu's archive (`apt_snapshot`, from snapshot.ubuntu.com), and project VMs use the live archive ([base](../using/images.md#base)). +## Base's size + +devvm fits base's CPUs and memory to the host with one rule that every backend uses. Base gets `base.yaml`'s 4 CPUs, or the host's count when the host has fewer. Docker refuses a `--cpus` above its machine's count, and a Lima `vz` VM given more CPUs than the Mac has can start so slowly that its ssh never comes up, as [Lima's issue](https://github.com/lima-vm/lima/issues/1621) reports. Base gets `base.yaml`'s 8 GiB of memory, or half the host's whole GiB when 8 GiB would leave the host less than 2 GiB, because a VM asking for all of the host's memory doesn't start. + +- **Lima** passes the fitted size to `limactl create` as `--cpus` and `--memory`, for base and for the VM that converts a `--from` image. The images built on base are clones of it, so they and their VMs keep that size. +- **smolvm** sets the fitted size on base's build machine and on every VM you give no size, because a pack would otherwise give a VM its build machine's CPUs and memory. +- **Docker** fits to the engine's machine, as `docker info` reports its CPUs and memory, for base's build container and every VM you give no size. Until devvm has read `docker info`, base gets `base.yaml`'s size. + +A size you set with `--cpus`, `--memory` or `devvm size -g` replaces the fitted one. The fitted size isn't in image keys, because the host's size doesn't change what an image holds. + ## The docker layer The built-in [`docker` layer](../using/images.md#built-in-layers)'s script is `assets/layers/docker.sh`, embedded in devvm, and its [allowlist](../safety/network.md#allowlists) is `assets/layers/docker.policy`. The script pins the checksum of the signing key of Docker's apt repository and each package's version at the top. On `--from alpine`, it installs Alpine's own packages, which aren't pinned. Running Docker's engine in a VM is a backend feature of its own, `docker-layer` ([features](backends.md#features)). diff --git a/docs/content/docs/internals/smolvm.md b/docs/content/docs/internals/smolvm.md index 5e42d589..fd8a29a9 100644 --- a/docs/content/docs/internals/smolvm.md +++ b/docs/content/docs/internals/smolvm.md @@ -25,7 +25,7 @@ The VM's user has your user name and uid, as on Lima, with its home at `/home/ 0 && mem+2 > host { - mem = host / 2 + hostCPUs, hostMem := d.engineSize() + if hostMem > 0 { + mem = backend.FitMemory(mem, uint64(hostMem)) } - return int(c), mem, disk, nil + return backend.FitCPUs(int(c), hostCPUs), mem, disk, nil } // sizeArgs are docker's options that set CPUs and memory (without swap); diff --git a/internal/backend/docker/check.go b/internal/backend/docker/check.go index 5a47313f..56117d9e 100644 --- a/internal/backend/docker/check.go +++ b/internal/backend/docker/check.go @@ -46,6 +46,7 @@ type engine struct { OperatingSystem string `json:"OperatingSystem"` Name string `json:"Name"` MemTotal int64 `json:"MemTotal"` + NCPU int `json:"NCPU"` SecurityOptions []string `json:"SecurityOptions"` // Runtimes are the container runtimes it has, by name: sysbox-runc // where Sysbox is installed. @@ -152,15 +153,15 @@ func (d *Docker) engineKind() string { return d.eng.kind } -// engineMemory is the memory the engine's machine has, in bytes; 0 until -// Problems looked. -func (d *Docker) engineMemory() int64 { +// engineSize is the CPUs and memory (in bytes) the engine's machine has; +// 0 until Problems looked. +func (d *Docker) engineSize() (cpus int, mem int64) { d.mu.Lock() defer d.mu.Unlock() if d.eng == nil { - return 0 + return 0, 0 } - return d.eng.MemTotal + return d.eng.NCPU, d.eng.MemTotal } // recent reports whether a version is 29.1 or newer. diff --git a/internal/backend/docker/docker_test.go b/internal/backend/docker/docker_test.go index 155a777f..88287b73 100644 --- a/internal/backend/docker/docker_test.go +++ b/internal/backend/docker/docker_test.go @@ -340,6 +340,26 @@ func TestRecent(t *testing.T) { } } +// base's size, fitted to the engine's machine once Problems has read it: +// base.yaml's until then. +func TestBaseSize(t *testing.T) { + for _, c := range []struct { + eng *engine + cpus int + mem, disk float64 + }{ + {nil, 4, 8, 100}, + {&engine{NCPU: 16, MemTotal: 64 << 30}, 4, 8, 100}, + {&engine{NCPU: 2, MemTotal: 8 << 30}, 2, 4, 100}, + } { + d := &Docker{Assets: assets.FS, eng: c.eng} + cpus, mem, disk, err := d.baseSize() + if err != nil || cpus != c.cpus || mem != c.mem || disk != c.disk { + t.Errorf("engine %+v: baseSize = %d, %v, %v, %v; want %d, %v, %v", c.eng, cpus, mem, disk, err, c.cpus, c.mem, c.disk) + } + } +} + // doctor's report: which engine, and on Docker Desktop which folders it // shares (its settings', or its defaults when they don't say). func TestReport(t *testing.T) { diff --git a/internal/backend/fit.go b/internal/backend/fit.go new file mode 100644 index 00000000..8ef17496 --- /dev/null +++ b/internal/backend/fit.go @@ -0,0 +1,26 @@ +package backend + +// gib is a GiB in bytes. +const gib = 1 << 30 + +// FitCPUs is the CPUs a VM asking for want gets on a host with hostCPUs: +// want, or the host's count when it has fewer. A hostCPUs of 0 or less +// is unknown, and gives want. +func FitCPUs(want, hostCPUs int) int { + if hostCPUs <= 0 { + return want + } + return min(want, hostCPUs) +} + +// FitMemory is the memory in GiB a VM asking for wantGiB gets on a host +// with hostBytes: wantGiB, or half the host's whole GiB when wantGiB +// would leave the host less than 2 GiB, as a VM asking for all of it +// doesn't start. +func FitMemory(wantGiB float64, hostBytes uint64) float64 { + h := float64(hostBytes / gib) + if wantGiB+2 <= h { + return wantGiB + } + return h / 2 +} diff --git a/internal/backend/fit_test.go b/internal/backend/fit_test.go new file mode 100644 index 00000000..d556c024 --- /dev/null +++ b/internal/backend/fit_test.go @@ -0,0 +1,41 @@ +package backend + +import "testing" + +func TestFitCPUs(t *testing.T) { + for _, c := range []struct{ want, host, fitted int }{ + {4, 16, 4}, + {4, 4, 4}, + {4, 2, 2}, + {4, 1, 1}, + {4, 0, 4}, // unknown + {4, -1, 4}, + } { + if got := FitCPUs(c.want, c.host); got != c.fitted { + t.Errorf("FitCPUs(%d, %d) = %d, want %d", c.want, c.host, got, c.fitted) + } + } +} + +// base's memory: base.yaml's, or half the host's whole GiB when that +// leaves it less than 2 GiB. +func TestFitMemory(t *testing.T) { + for _, c := range []struct { + want float64 + hostBytes uint64 + fitted float64 + }{ + {8, 16*gib + gib/2, 8}, + {8, 10*gib + gib/2, 8}, + {8, 10 * gib, 8}, + {8, 9*gib + gib/2, 4.5}, + {8, 8*gib + gib/2, 4}, + {8, 7*gib + gib/2, 3.5}, + {2, 4 * gib, 2}, + {8, 0, 0}, + } { + if got := FitMemory(c.want, c.hostBytes); got != c.fitted { + t.Errorf("FitMemory(%v, %d) = %v, want %v", c.want, c.hostBytes, got, c.fitted) + } + } +} diff --git a/internal/backend/lima/build.go b/internal/backend/lima/build.go index 5c1dae27..899c459b 100644 --- a/internal/backend/lima/build.go +++ b/internal/backend/lima/build.go @@ -87,37 +87,34 @@ func (l *Lima) BuildImage(ctx context.Context, spec backend.ImageSpec) (backend. var built backend.Built var conv *converted if spec.Parent == "" { - mem := spec.MemoryGiB - if mem == 0 { - var err error - if mem, err = l.buildMemory(); err != nil { - return backend.Built{}, err - } + size, err := l.buildSize() + if err != nil { + return backend.Built{}, err + } + if spec.MemoryGiB > 0 { + size.MemoryGiB = spec.MemoryGiB } if spec.From == nil { - img, err := l.createFromUbuntu(ctx, inst, mem) + img, err := l.createFromUbuntu(ctx, inst, size) if err != nil { return backend.Built{}, err } built = backend.Built{Origin: img.String(), Libc: "gnu"} } else { - var err error - if conv, err = l.convert(ctx, spec.From, mem); err != nil { + if conv, err = l.convert(ctx, spec.From, size); err != nil { return backend.Built{}, err } // base.yaml's settings, booting the converted disk. - images := yqJSON([]limaImage{{ + images := []limaImage{{ Location: filepath.Join(conv.dir, "disk.raw"), Arch: limaArch(l.Arch), Kernel: &limaKernel{Location: filepath.Join(conv.dir, "kernel"), Cmdline: conv.cmdline}, Initrd: &limaFile{Location: filepath.Join(conv.dir, "initrd")}, - }}) + }} assets, err := l.assets() if err != nil { return backend.Built{}, err } - if err := l.Runner.Run(ctx, msg.Creating(inst), l.limactl(ctx, "create", "--tty=false", - "--mount-none", "--name="+inst, "--set", ".images = "+images, - "--memory="+gibString(mem), filepath.Join(assets, "base.yaml"))); err != nil { + if err := l.Runner.Run(ctx, msg.Creating(inst), l.limactl(ctx, createArgs(inst, images, size, assets)...)); err != nil { return backend.Built{}, backend.Logged(msg.VMCreateFailed(inst)) } built = backend.Built{Origin: spec.From.Digest, Libc: conv.libc} @@ -191,8 +188,8 @@ type limaFile struct { // createFromUbuntu creates a VM from Ubuntu's newest cloud image, with // base.yaml's settings and nothing from the host mounted, or the mounts a // --set in opts gives it (--set applies after --mount-none). It returns -// the image it used. -func (l *Lima) createFromUbuntu(ctx context.Context, vm string, mem float64, opts ...string) (ubuntu.Image, error) { +// the image it used. It gets size's CPUs and memory (buildSize's). +func (l *Lima) createFromUbuntu(ctx context.Context, vm string, size backend.Size, opts ...string) (ubuntu.Image, error) { img, err := l.Ubuntu(ctx) if err != nil { return ubuntu.Image{}, err @@ -201,15 +198,22 @@ func (l *Lima) createFromUbuntu(ctx context.Context, vm string, mem float64, opt if err != nil { return ubuntu.Image{}, err } - images := yqJSON([]limaImage{{Location: img.URL, Arch: limaArch(l.Arch), Digest: img.Digest}}) - args := append([]string{"create", "--tty=false", "--mount-none", "--name=" + vm, "--set", ".images = " + images}, opts...) - args = append(args, "--memory="+gibString(mem), filepath.Join(assets, "base.yaml")) - if err := l.Runner.Run(ctx, msg.CreatingFromUbuntu(vm), l.limactl(ctx, args...)); err != nil { + images := []limaImage{{Location: img.URL, Arch: limaArch(l.Arch), Digest: img.Digest}} + if err := l.Runner.Run(ctx, msg.CreatingFromUbuntu(vm), l.limactl(ctx, createArgs(vm, images, size, assets, opts...)...)); err != nil { return ubuntu.Image{}, backend.Logged(msg.VMCreateFailed(vm)) } return img, nil } +// createArgs are limactl create's arguments for a VM booting images, with +// nothing from the host mounted but what opts' --set gives it, size's CPUs +// and memory, and the rest of base.yaml's settings (from devvm's files, +// written out in assets). +func createArgs(vm string, images []limaImage, size backend.Size, assets string, opts ...string) []string { + args := append([]string{"create", "--tty=false", "--mount-none", "--name=" + vm, "--set", ".images = " + yqJSON(images)}, opts...) + return append(args, "--cpus="+strconv.Itoa(size.CPUs), "--memory="+gibString(size.MemoryGiB), filepath.Join(assets, "base.yaml")) +} + // limaArch is Lima's name for a Go architecture. func limaArch(goarch string) string { switch goarch { @@ -245,37 +249,40 @@ func (l *Lima) unfinished(ctx context.Context, inst string) { _ = l.delete(ctx, inst) } -var memoryLine = regexp.MustCompile(`(?m)^memory:\s*([0-9.]+)GiB\s*$`) +var ( + cpusLine = regexp.MustCompile(`(?m)^cpus:\s*([0-9]+)\s*$`) + memoryLine = regexp.MustCompile(`(?m)^memory:\s*([0-9.]+)GiB\s*$`) +) -// buildMemory is base's memory in GiB: base.yaml's, or half the host's -// when that would leave the host less than 2 GiB (a VM asking for all of -// it doesn't start). Images built from base, and their VMs, keep it. -func (l *Lima) buildMemory() (float64, error) { +// buildSize is base's CPUs and memory: base.yaml's, fitted to the host +// (backend.FitCPUs, backend.FitMemory), so a host with fewer CPUs gets +// its own count and one that base.yaml's memory would leave less than 2 +// GiB gets half its memory. Images built from base, and their VMs, keep +// them. +func (l *Lima) buildSize() (backend.Size, error) { data, err := fs.ReadFile(l.Assets, "base.yaml") if err != nil { - return 0, err + return backend.Size{}, err + } + c := cpusLine.FindSubmatch(data) + if c == nil { + return backend.Size{}, errors.New("lima: base.yaml sets no CPUs") + } + cpus, err := strconv.Atoi(string(c[1])) + if err != nil { + return backend.Size{}, err } m := memoryLine.FindSubmatch(data) if m == nil { - return 0, errors.New("lima: base.yaml sets no memory in GiB") + return backend.Size{}, errors.New("lima: base.yaml sets no memory in GiB") } - want, err := strconv.ParseFloat(string(m[1]), 64) + mem, err := strconv.ParseFloat(string(m[1]), 64) if err != nil { - return 0, err + return backend.Size{}, err } host, err := l.Memory() if err != nil { - return 0, err + return backend.Size{}, err } - return fitMemory(want, host), nil -} - -// fitMemory is want GiB, or half the host's whole GiB when want would -// leave it less than 2. -func fitMemory(want float64, hostBytes uint64) float64 { - h := float64(hostBytes / gib) - if want+2 <= h { - return want - } - return h / 2 + return backend.Size{CPUs: backend.FitCPUs(cpus, l.CPUs()), MemoryGiB: backend.FitMemory(mem, host)}, nil } diff --git a/internal/backend/lima/build_test.go b/internal/backend/lima/build_test.go index db13f524..2d8059b1 100644 --- a/internal/backend/lima/build_test.go +++ b/internal/backend/lima/build_test.go @@ -32,6 +32,7 @@ func buildLima(t *testing.T, os string, parentStatus string) (*Lima, *fakeRunner return ubuntu.Image{URL: "https://example.com/r/ubuntu.img", Digest: "sha256:1111"}, nil } l.Memory = func() (uint64, error) { return 16 * gib, nil } + l.CPUs = func() int { return 8 } l.Info = func(msg.M) {} list := "" if parentStatus != "" { @@ -104,7 +105,7 @@ func TestBuildImageBase(t *testing.T) { checkLines(t, f.lines(), []string{ "limactl create --tty=false --mount-none --name=" + inst + ` --set .images = [{"location":"https://example.com/r/ubuntu.img","arch":"aarch64","digest":"sha256:1111"}]` + - " --memory=8 " + filepath.Join(assetsDir(t, l), "base.yaml"), + " --cpus=4 --memory=8 " + filepath.Join(assetsDir(t, l), "base.yaml"), "limactl edit --tty=false " + inst + " --set .ssh.localPort=", "sandbox-exec -f " + l.profileFile(inst) + " ", "limactl shell " + inst + " bash -s", @@ -187,6 +188,7 @@ func TestBuildImageRefuses(t *testing.T) { "an existing image": func(s *backend.ImageSpec) { s.Key = baseKey; s.Parent = "" }, "no Ubuntu image": func(*backend.ImageSpec) {}, "no memory in GiB": func(*backend.ImageSpec) {}, + "no CPUs": func(*backend.ImageSpec) {}, "no host memory": func(*backend.ImageSpec) {}, "a missing base.yml": func(*backend.ImageSpec) {}, } { @@ -202,7 +204,9 @@ func TestBuildImageRefuses(t *testing.T) { return ubuntu.Image{}, msg.NoUbuntuImage("release-20260101", "x", "26.04") } case "no memory in GiB": - l.Assets = fstest.MapFS{"base.yaml": {Data: []byte("memory: 8G\n")}} + l.Assets = fstest.MapFS{"base.yaml": {Data: []byte("cpus: 4\nmemory: 8G\n")}} + case "no CPUs": + l.Assets = fstest.MapFS{"base.yaml": {Data: []byte("memory: 8GiB\n")}} case "no host memory": l.Memory = func() (uint64, error) { return 0, errors.ErrUnsupported } case "a missing base.yml": @@ -222,13 +226,17 @@ func TestBuildImageRefuses(t *testing.T) { } } -// base's memory: base.yaml's, or half the host's when that leaves it less -// than 2 GiB. -func TestFitMemory(t *testing.T) { - for host, want := range map[uint64]float64{16: 8, 10: 8, 8: 4, 7: 3.5} { - if got := fitMemory(8, host*gib+gib/2); got != want { - t.Errorf("fitMemory(8, %d GiB) = %v, want %v", host, got, want) - } +// On a host of 2 CPUs and 8 GiB, base gets 2 CPUs and 4 GiB. +func TestBuildImageSmallHost(t *testing.T) { + l, f := buildLima(t, "darwin", "") + l.CPUs = func() int { return 2 } + l.Memory = func() (uint64, error) { return 8 * gib, nil } + if _, err := l.BuildImage(t.Context(), backend.ImageSpec{Image: "base", Key: baseKey, Net: backend.NetInternet}); err != nil { + t.Fatal(err) + } + lines := f.lines() + if len(lines) == 0 || !strings.HasPrefix(lines[0], "limactl create ") || !strings.Contains(lines[0], " --cpus=2 --memory=4 ") { + t.Errorf("calls:\n%s\nwant base created with --cpus=2 --memory=4", strings.Join(lines, "\n")) } } diff --git a/internal/backend/lima/lima.go b/internal/backend/lima/lima.go index c3fc146c..9fda184f 100644 --- a/internal/backend/lima/lima.go +++ b/internal/backend/lima/lima.go @@ -63,6 +63,8 @@ type Lima struct { Ubuntu func(ctx context.Context) (ubuntu.Image, error) // Memory returns the host's memory in bytes. Memory func() (uint64, error) + // CPUs returns the host's CPU count. + CPUs func() int // MacOS returns macOS's version, "" when unknown. MacOS func() string // KVM is Linux's KVM device: /dev/kvm, unless DEVVM_KVM is set. @@ -111,7 +113,7 @@ func New(d paths.Dirs, assets fs.FS, u UI) *Lima { return &Lima{ Dirs: d, Runner: logRunner{u.LoggedCmd}, OS: runtime.GOOS, Arch: runtime.GOARCH, Self: self, Assets: assets, SSHTimeout: sshTimeout, OCIWait: time.Second, Getenv: os.Getenv, - Ubuntu: ubuntu.New(assets, os.Getenv, u).Image, Memory: platform.Memory, + Ubuntu: ubuntu.New(assets, os.Getenv, u).Image, Memory: platform.Memory, CPUs: runtime.NumCPU, MacOS: platform.MacOSVersion, KVM: cmp.Or(os.Getenv("DEVVM_KVM"), "/dev/kvm"), DockerRunning: from.DockerRunning, Info: u.Info, Warn: func(m msg.M) { u.Warn(m); u.LogNote() }, diff --git a/internal/backend/lima/oci.go b/internal/backend/lima/oci.go index 1290afd9..3a922188 100644 --- a/internal/backend/lima/oci.go +++ b/internal/backend/lima/oci.go @@ -50,7 +50,7 @@ type converted struct { // subfolder of devvm's temporary folder, and what comes out is checked // before Lima sees it. One conversion runs at a time. The build VM and // the folder go however the run ends. -func (l *Lima) convert(ctx context.Context, f *backend.From, mem float64) (*converted, error) { +func (l *Lima) convert(ctx context.Context, f *backend.From, size backend.Size) (*converted, error) { if f.Digest == "" { return nil, msg.NoDigest(f.Ref) } @@ -105,7 +105,7 @@ func (l *Lima) convert(ctx context.Context, f *backend.From, mem float64) (*conv if err != nil { return nil, err } - if _, err := l.createFromUbuntu(ctx, OCIVM, mem, "--set", mounts); err != nil { + if _, err := l.createFromUbuntu(ctx, OCIVM, size, "--set", mounts); err != nil { return nil, err } // crane pulls from the registry. diff --git a/internal/backend/smolvm/build.go b/internal/backend/smolvm/build.go index d997484a..5d62d15d 100644 --- a/internal/backend/smolvm/build.go +++ b/internal/backend/smolvm/build.go @@ -437,12 +437,9 @@ var ( diskLine = regexp.MustCompile(`(?m)^disk:\s*([0-9.]+)GiB\s*$`) ) -// gib is a GiB in bytes. -const gib = 1 << 30 - // baseSize is what images and VMs get unless told otherwise: base.yaml's -// CPUs, memory and disk, as Lima's base has them; the memory halved when -// it would leave the host less than 2 GiB. +// CPUs, memory and disk, as Lima's base has them, its CPUs and memory +// fitted to the host (backend.FitCPUs, backend.FitMemory). func (s *Smolvm) baseSize() (cpus int, mem, disk float64, err error) { data, err := fs.ReadFile(s.Assets, "base.yaml") if err != nil { @@ -469,8 +466,5 @@ func (s *Smolvm) baseSize() (cpus int, mem, disk float64, err error) { if err != nil { return 0, 0, 0, err } - if h := float64(host / gib); mem+2 > h { - mem = h / 2 - } - return int(c), mem, disk, nil + return backend.FitCPUs(int(c), s.CPUs()), backend.FitMemory(mem, host), disk, nil } diff --git a/internal/backend/smolvm/smolvm.go b/internal/backend/smolvm/smolvm.go index d7f05b37..4c1020fa 100644 --- a/internal/backend/smolvm/smolvm.go +++ b/internal/backend/smolvm/smolvm.go @@ -74,6 +74,8 @@ type Smolvm struct { User func() (*user.User, error) // Memory returns the host's memory in bytes. Memory func() (uint64, error) + // CPUs returns the host's CPU count. + CPUs func() int // KVM is Linux's KVM device: /dev/kvm, unless DEVVM_KVM is set. KVM string // Terminal reports whether devvm's input is a terminal (a shell gets @@ -126,7 +128,7 @@ func New(d paths.Dirs, assets fs.FS, u UI) *Smolvm { } return &Smolvm{ Dirs: d, Runner: logRunner{u.LoggedCmd}, OS: runtime.GOOS, Arch: runtime.GOARCH, Assets: assets, - Getenv: os.Getenv, User: user.Current, Memory: platform.Memory, + Getenv: os.Getenv, User: user.Current, Memory: platform.Memory, CPUs: runtime.NumCPU, KVM: kvm, Terminal: u.StdinIsTerminal, FreePort: freePort, PortFree: platform.PortFree, diff --git a/internal/backend/smolvm/smolvm_test.go b/internal/backend/smolvm/smolvm_test.go index bb505cc2..935b6eb3 100644 --- a/internal/backend/smolvm/smolvm_test.go +++ b/internal/backend/smolvm/smolvm_test.go @@ -72,8 +72,8 @@ func newSandbox(t *testing.T) sandbox { Dirs: d, Runner: execRunner{}, OS: "darwin", Arch: "arm64", Assets: assets.FS, Getenv: func(string) string { return "" }, User: func() (*user.User, error) { return &user.User{Username: "u", Uid: "501"}, nil }, - Memory: func() (uint64, error) { return 64 << 30, nil }, - KVM: "/dev/kvm", Terminal: func() bool { return false }, + Memory: func() (uint64, error) { return 64 << 30, nil }, CPUs: func() int { return 8 }, + KVM: "/dev/kvm", Terminal: func() bool { return false }, FreePort: func(context.Context) (int, error) { return 61022, nil }, PortFree: func(context.Context, int) bool { return true }, Info: func(msg.M) {}, Warn: func(msg.M) {}, WithSteps: testUI{}.WithSteps, AddCleanup: testUI{}.AddCleanup, Interrupted: testUI{}.Interrupted, @@ -745,6 +745,30 @@ func TestBuildBase(t *testing.T) { } } +// On a host of 2 CPUs and 8 GiB, base's build machine and a VM given no +// size get 2 CPUs and 4 GiB; a VM's own CPUs still win. +func TestSmallHost(t *testing.T) { + s := newSandbox(t) + s.CPUs = func() int { return 2 } + s.Memory = func() (uint64, error) { return 8 << 30, nil } + if _, err := s.BuildImage(t.Context(), backend.ImageSpec{Image: "base", Key: "0123456789ab", Net: backend.NetInternet}); err != nil { + t.Fatal(err) + } + if got := s.calls(t); len(got) == 0 || !strings.Contains(got[0], "machine create ") || !strings.Contains(got[0], " --cpus 2 --mem 4096 ") { + t.Errorf("calls:\n%s\nwant base made with --cpus 2 --mem 4096", strings.Join(got, "\n")) + } + for vm, size := range map[string]backend.Size{"devvm-p-0123456789abcd": {}, "devvm-q-0123456789abcd": {CPUs: 1}} { + if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: vm, Size: size}); err != nil { + t.Fatal(err) + } + } + got := s.calls(t) + got = got[max(0, len(got)-2):] + if len(got) != 2 || !strings.Contains(got[0]+got[1], " --cpus 2 --mem 4096 ") || !strings.Contains(got[0]+got[1], " --cpus 1 --mem 4096 ") { + t.Errorf("calls:\n%s\nwant --cpus 2 and --cpus 1, each with --mem 4096", strings.Join(got, "\n")) + } +} + // A failed script keeps the build machine, stopped; an image only Docker // has is refused. func TestBuildFails(t *testing.T) { diff --git a/testdata/script/build.txtar b/testdata/script/build.txtar index a2759166..f6c7ffc4 100644 --- a/testdata/script/build.txtar +++ b/testdata/script/build.txtar @@ -15,7 +15,7 @@ stdout '^base_build_time$' stdout '^==> image_ready image=base$' stub_calls stdout '^gpgv --keyring /\S*/devvm-ubuntu\.[0-9]+/ubuntu-cloud\.gpg ' -stdout '^limactl create --tty=false --mount-none --name=devvm-img-[0-9a-f]{12} --set \.images = \[\{"location":"file://.*/release-[0-9]{8}/ubuntu-26\.04-server-cloudimg-(arm64|amd64)\.img","arch":"(aarch64|x86_64)","digest":"sha256:[0-9a-f]{64}"\}\] --memory=[0-9.]+ /\S*/data/devvm/assets/[0-9a-f]{16}/base\.yaml$' +stdout '^limactl create --tty=false --mount-none --name=devvm-img-[0-9a-f]{12} --set \.images = \[\{"location":"file://.*/release-[0-9]{8}/ubuntu-26\.04-server-cloudimg-(arm64|amd64)\.img","arch":"(aarch64|x86_64)","digest":"sha256:[0-9a-f]{64}"\}\] --cpus=[0-9]+ --memory=[0-9.]+ /\S*/data/devvm/assets/[0-9a-f]{16}/base\.yaml$' stdout '^limactl edit --tty=false devvm-img-[0-9a-f]{12} .*--set \.portForwards = \[\{"guestIP":"127\.0\.0\.1"' stdout '^limactl start --tty=false devvm-img-[0-9a-f]{12}$' stdout '^limactl shell devvm-img-[0-9a-f]{12} bash -s$' diff --git a/testdata/script/from.txtar b/testdata/script/from.txtar index a6cafd1c..5d197afb 100644 --- a/testdata/script/from.txtar +++ b/testdata/script/from.txtar @@ -37,10 +37,10 @@ stdout '^==> image_ready image=base$' stub_calls ! stdout '^docker' stdout '^gpgv --keyring ' -stdout '^limactl create --tty=false --mount-none --name=devvm-oci-build --set \.images = \[\{"location":"file://.*/release-[0-9]{8}/ubuntu-26\.04-server-cloudimg-(arm64|amd64)\.img","arch":"(aarch64|x86_64)","digest":"sha256:[0-9a-f]{64}"\}\] --set \.mounts = \[\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm","writable":true\},\{"location":"/\S*/oci","writable":false\}\] --memory=[0-9.]+ /\S*/base\.yaml$' +stdout '^limactl create --tty=false --mount-none --name=devvm-oci-build --set \.images = \[\{"location":"file://.*/release-[0-9]{8}/ubuntu-26\.04-server-cloudimg-(arm64|amd64)\.img","arch":"(aarch64|x86_64)","digest":"sha256:[0-9a-f]{64}"\}\] --set \.mounts = \[\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm","writable":true\},\{"location":"/\S*/oci","writable":false\}\] --cpus=[0-9]+ --memory=[0-9.]+ /\S*/base\.yaml$' stdout '^limactl start --tty=false devvm-oci-build$' stdout '^limactl shell --workdir / devvm-oci-build sudo bash /\S*/data/devvm/assets/[0-9a-f]{16}/oci/build\.sh /\S*/data/devvm/assets/[0-9a-f]{16}/oci /\S*/tmp/devvm-oci\.[0-9]+/vm node:24@sha256:a{64} node:24@sha256:a{64} \S+ [0-9]+ /home/\S+\.guest 20G$' -stdout '^limactl delete -f devvm-oci-build\nlimactl create --tty=false --mount-none --name=devvm-img-[0-9a-f]{12} --set \.images = \[\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/disk\.raw","arch":"(aarch64|x86_64)","kernel":\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/kernel","cmdline":"root=/dev/vda rw console=hvc0"\},"initrd":\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/initrd"\}\}\] --memory=[0-9.]+ /\S*/base\.yaml$' +stdout '^limactl delete -f devvm-oci-build\nlimactl create --tty=false --mount-none --name=devvm-img-[0-9a-f]{12} --set \.images = \[\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/disk\.raw","arch":"(aarch64|x86_64)","kernel":\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/kernel","cmdline":"root=/dev/vda rw console=hvc0"\},"initrd":\{"location":"/\S*/tmp/devvm-oci\.[0-9]+/vm/initrd"\}\}\] --cpus=[0-9]+ --memory=[0-9.]+ /\S*/base\.yaml$' stdout '^limactl shell devvm-img-[0-9a-f]{12} bash -s$' exec sh -c 'ls "$TMPDIR"' ! stdout .