mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
fix(build): fit base's CPUs to the host, as its memory is
Base asked for base.yaml's 4 CPUs whatever the host had. It now gets base.yaml's CPUs, or the host's count when the host has fewer, by the same shared rule as its memory. What happens above the host's count (from published docs, not checked on a VM): - Lima accepts cpus above the host's count: its template's default is min(4, host CPU cores), and its proposed check that refused more than runtime.NumCPU() (lima-vm/lima#2309) was closed unmerged. On vz, a VM given more CPUs than the Mac has can start so slowly that ssh never comes up (lima-vm/lima#1621, open). - Apple's Virtualization framework only requires cpuCount <= VZVirtualMachineConfiguration.maximumAllowedCPUCount, whose docs don't tie it to the host's count. - smolvm and libkrun document no limit for --cpus. - Docker refuses --cpus above its engine's machine's count ("Range of CPUs is from 0.01 to N.00, as there are only N CPUs available"). Changes: - internal/backend/fit.go: FitCPUs(want, hostCPUs int) int and FitMemory(wantGiB float64, hostBytes uint64) float64, pure and exported; fitMemory's rule moved there from Lima, with table tests. - Lima: buildSize replaces buildMemory and reads base.yaml's cpus and memory; limactl create gets --cpus and --memory for base and the --from conversion VM (createArgs). A CPUs field (runtime.NumCPU) is the host-CPU seam beside Memory. - smolvm: baseSize fits CPUs and memory with the shared rules, for base's build, tool builds and VMs given no size; a CPUs field is the seam. spec.Size.CPUs still wins. - Docker: the engine's NCPU is read from docker info beside MemTotal (engineSize replaces engineMemory), and baseSize fits both. - Image keys are unchanged: neither the fitted memory nor CPUs are in them. - Tests: TestFitCPUs, TestFitMemory, Lima's TestBuildImageSmallHost and "no CPUs" case, smolvm's TestSmallHost, Docker's TestBaseSize; the build and from testscripts expect --cpus. - Docs: using/ports-size.md and using/images.md say what a small machine gets; internals/images.md has a Base's size section on the mechanism; internals/smolvm.md and internals/docker.md match it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
19 files changed
+221
-84
No files matched your search
@@ -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/<you>.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:
|
||||
|
||||
|
||||
@@ -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/<name>.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)).
|
||||
|
||||
@@ -25,7 +25,7 @@ The VM's user has your user name and uid, as on Lima, with its home at `/home/<y
|
||||
|
||||
The scripts run as that user, with stand-ins for `systemctl` and `rc-update` while they run. Base's services are enabled the Lima way, and devvm starts them itself ([below](#no-init-system)). The stand-ins are gone before the image is packed.
|
||||
|
||||
Builds use smolvm's default network, which reaches the internet but not the host's loopback. A pack keeps its build machine's network, CPUs and memory, so devvm sets all three on every VM it makes. Base's CPUs, memory and disk come from `base.yaml`: 4 CPUs, 8 GiB of memory (half the host's memory on a small host) and a 100 GiB disk.
|
||||
Builds use smolvm's default network, which reaches the internet but not the host's loopback. A pack keeps its build machine's network, CPUs and memory, so devvm sets all three on every VM it makes. Base's CPUs, memory and disk come from `base.yaml`, which sets 4 CPUs, 8 GiB of memory and a 100 GiB disk. On a host with fewer than 4 CPUs, base and the VMs you give no size get as many CPUs as the host has, and when 8 GiB would leave the host less than 2 GiB, they get half of its memory ([base's size](images.md#bases-size)).
|
||||
|
||||
devvm's own scripts for these steps are in `base`'s key, together with the backend, so smolvm's images are never Lima's. They are `prepare.sh`, `shims.sh` and `sshd.sh`. `sshd.sh` installs sshd after base's scripts, from the Ubuntu snapshot they pin, and keeps the snapshot's package lists for layers.
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ flowchart TD
|
||||
|
||||
`base` is the image that every other image is built on. It is Ubuntu 26.04's cloud image with git, build-essential, ripgrep, jq and mise added, followed by the optional [features](customizing.md#base-image-features) you chose, such as oh-my-bash and fzf. Docker comes as a [layer of devvm's](#built-in-layers), so you ask for it with `devvm node+docker`. With `--from`, base starts from a container image instead of Ubuntu's ([details](from.md)).
|
||||
|
||||
A VM made from base gets 4 CPUs, 8 GiB of memory and a 100 GiB disk unless you give it another [size](ports-size.md#size).
|
||||
A VM made from base gets 4 CPUs, 8 GiB of memory and a 100 GiB disk unless you give it another [size](ports-size.md#size). On a small machine it gets fewer CPUs and less memory, which [the size section](ports-size.md#size-and-ports) explains.
|
||||
|
||||
base drops the server extras that Ubuntu's cloud image comes with, which are snapd, multipath, ModemManager, udisks, firmware updates, crash reporting, tracing tools, kernel headers, and apt's background updates and upgrades. That saves 0.9 GB of disk and 100 MB of memory per VM. The everyday tools stay, such as htop, tmux, lsof, strace, tcpdump, rsync and nano.
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ This page covers the ports a VM forwards to this machine and the CPUs, memory an
|
||||
|
||||
## Size and ports
|
||||
|
||||
A new VM gets its image's size unless you set one with `--cpus`, `--memory` and `--disk`, as in `devvm --cpus 6 base`. For `base` that's 4 CPUs, 8 GiB of memory and a 100 GiB disk.
|
||||
A new VM gets its image's size unless you set one with `--cpus`, `--memory` and `--disk`, as in `devvm --cpus 6 base`. For `base` that's 4 CPUs, 8 GiB of memory and a 100 GiB disk. On a machine with fewer than 4 CPUs, base gets as many CPUs as the machine has, and when 8 GiB would leave the machine less than 2 GiB of its own, base gets half of the machine's memory.
|
||||
|
||||
- `--cpus` takes a whole number. `--memory` and `--disk` take a size in GiB, written `16`, `16G` or `16GiB`, and decimals are allowed.
|
||||
- What the flags leave unset comes from `~/.config/devvm/size` when that file sets it, with one `cpus=`, `memory=` or `disk=` line each. `devvm size -g` writes that file.
|
||||
|
||||
@@ -371,8 +371,9 @@ var (
|
||||
)
|
||||
|
||||
// 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 engine's machine less than 2 GiB.
|
||||
// CPUs, memory and disk, as Lima's base has them, its CPUs and memory
|
||||
// fitted to the engine's machine (backend.FitCPUs, backend.FitMemory) once
|
||||
// Problems has read them.
|
||||
func (d *Docker) baseSize() (cpus int, mem, disk float64, err error) {
|
||||
data, err := fs.ReadFile(d.Assets, "base.yaml")
|
||||
if err != nil {
|
||||
@@ -395,10 +396,11 @@ func (d *Docker) baseSize() (cpus int, mem, disk float64, err error) {
|
||||
if disk, err = get(diskLine); err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
if host := float64(d.engineMemory() / gib); host > 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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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() },
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Vendored
+1
-1
@@ -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$'
|
||||
|
||||
Vendored
+2
-2
@@ -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 .
|
||||
|
||||
Reference in new issue
Block a user