From cfae579fece920f1af76290bd58a92af3caa28f2 Mon Sep 17 00:00:00 2001 From: w3cj Date: Sat, 24 Oct 2026 20:09:02 -0600 Subject: [PATCH] feat(size): devvm size, --cpus/--memory/--disk, and -g for new VMs devvm size shows this folder's VM's CPUs, memory and disk (cpus=4 memory=8GiB disk=100GiB), with a note when a change waits for its next start; --cpus, --memory and --disk change them, at once for a stopped VM, from its next start for a running one. Disks only grow; more than this machine has is refused. -g/--global shows (cpus=, memory=, disk= lines) or changes the size new VMs get (~/.config/devvm/size), keeping what it leaves unset. A change checks the backend's features first. - vm: Env.ShowSize, Env.SetSize, SizeText, pendingSize (also used by applySize), defaultSize (also used by up), folderVM (shared by ports, ssh-agent and size) - messages: vm_size, size_pending, size_defaults, no_vm_size, size_failed; size_flags_ignored names devvm size - tests: size.txtar (show, set, running vs stopped, -g, a hand-edited size file, refusals), TestSetSize, TestSizeText; the limactl stub's edit applies --cpus/--memory/--disk; e2e project: a new VM gets its size, devvm size shows it, a running VM's new size waits for restart then applies, a smaller disk is refused - docs: images.md Size and Disk use, commands.md rows, CLI reference Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +- docs/content/docs/cli/_index.md | 1 + docs/content/docs/cli/devvm.md | 1 + docs/content/docs/cli/devvm_size.md | 38 +++++ docs/content/docs/cli/devvm_ssh-agent.md | 2 +- docs/content/docs/cli/devvm_ssh-agent_add.md | 2 +- docs/content/docs/cli/devvm_ssh-agent_keys.md | 2 +- docs/content/docs/cli/devvm_update.md | 2 +- docs/content/docs/commands.md | 8 +- docs/content/docs/images.md | 24 +++ internal/cli/docgen/docgen_test.go | 2 +- internal/cli/root.go | 2 +- internal/cli/size.go | 43 +++++ internal/msg/messages_gen.go | 32 +++- internal/vm/commands.go | 12 +- internal/vm/existing.go | 12 +- internal/vm/ports.go | 20 +-- internal/vm/size.go | 149 ++++++++++++++++++ internal/vm/size_test.go | 103 ++++++++++++ internal/vm/up.go | 6 +- locales/en.toml | 21 ++- testdata/script/size.txtar | 101 ++++++++++++ testdata/stubs/limactl | 15 +- tests/e2e.sh | 16 +- 24 files changed, 566 insertions(+), 58 deletions(-) create mode 100644 docs/content/docs/cli/devvm_size.md create mode 100644 internal/cli/size.go create mode 100644 internal/vm/size_test.go create mode 100644 testdata/script/size.txtar diff --git a/AGENTS.md b/AGENTS.md index 6396e103..28c2e2dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch | Path | What | | --- | --- | | `cmd/devvm/` | the entry point: the root command through `ui.Main`; the only `os.Exit` | -| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `restart`, `update`, `remove`, `adopt`, `rm`, `ls`, `log`, `doctor`, `secret`, `auth`, `ssh-agent`, `ports`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_refresh-tools`); `script_test.go` runs testscript; `docgen/` writes the CLI reference | +| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `restart`, `update`, `remove`, `adopt`, `rm`, `ls`, `log`, `doctor`, `secret`, `auth`, `ssh-agent`, `ports`, `size`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_refresh-tools`); `script_test.go` runs testscript; `docgen/` writes the CLI reference | | `internal/vm/` | up for a new VM (`up.go`) and an existing one (`existing.go`), the commands on a folder's VM (`commands.go`); `--clone` (`clone.go`); agents' mounts; the setup it sends (`sync.go`) | | `internal/project/`, `internal/gitprotect/` | a project folder (VM name, unsafe folders, detection, set-id files); `.git` protection | | `internal/sshconfig/`, `internal/sshagent/` | the ssh config for running VMs by name, their pinned host keys, the `~/.ssh/config` Include line; each VM's SSH agent choice, devvm's own agent and its keys | @@ -86,7 +86,7 @@ Still to come: smolvm and docker backends; `install.sh`, `scripts/`, `packaging/ - **Don't touch the user's own VMs or images.** Manual runs: `DEVVM_LIMA_HOME=~/.lt LIMA_HOME=~/.lt XDG_DATA_HOME=/tmp/x/data XDG_CONFIG_HOME=/tmp/x/config DEVVM_SECRET_SERVICE=devvm-sandbox-test` (devvm's Lima home is `$XDG_DATA_HOME/devvm/lima` unless `DEVVM_LIMA_HOME`; `LIMA_HOME` is for your `limactl`). Add a `base-features` file and pass `--network-policy`/`--no-network-policy` so nothing prompts. Delete test Keychain items. Never use the user's tokens or logins: a network-policy VM reads its agent's login file from `HOME`, so give it its own (the Keychain needs the real `HOME`: test it apart). - **End-to-end:** `tests/e2e.sh` builds devvm from the checkout and drives real VMs in its sandbox (`~/.lt-e2e-go`, `/tmp/devvm-go-e2e`, service `devvm-go-e2e`), deleting only what it made; images stay cached (`--clean`). `tools` first resolves the newest tool versions. Run it in the background. Sections: `images`, `project`, `clone` (a throwaway repo, its own `HOME`), `tools` (a node VM), `network` (a claude VM), `from` (Debian 12, Alpine and Ubuntu bases, a docker that isn't running). Tiers: none (all but `from`, no features); `--from` (everything, every feature; before merging `layers/`, `tools/`, `features/`, `oci/` or `--from` changes); `--only a,b` (with `from`: every feature); to come: `--quick` (project, `--clone`, size, gc, network; after most changes). Hosted CI can't run it on macOS. - **Linux hosts:** `LIMA_HOME=~/.lt-linux-go`, VM `linuxhost` (nested virtualization, the repo read-only, copied to `~/devvm`), set up as [testing.md](docs/content/docs/testing.md) says; never `~/.lt-linux`, which is the user's. -- **e2e to come:** `--backend`; `size gc from`; network: git over SSH, opencode's login; project: `devvm stop`, `git-protect`; tools: python, uv, claude, codex, rust, go, adding in place, gc. +- **e2e to come:** `--backend`; `gc from`; network: git over SSH, opencode's login; project: `devvm stop`, `git-protect`; tools: python, uv, claude, codex, rust, go, adding in place, gc. - **Delete test VMs and temp files afterwards.** Long builds run in the background. Tests that `chflags` real files unlock them (`chflags -R nouchg`), only in their own temp folders. - **The testscript runner stops the sandbox's proxies** (`pkill -f` on `-lifeline`): the stub hostagent is gone before they look, so they'd wait 15 minutes. - **`limactl shell` reads stdin:** give it none unless the input is meant for it. @@ -155,8 +155,7 @@ Bats files (pending cases, by task): | `install.bats` | all (install.sh) | | `network.bats` | ssh/code (direct route) | | `project.bats` | git-protect (strict) | -| `size.bats` | size (three) | -| `build`, `from`, `layers`, `lint`, `messages`, `oci`, `ports`, `tools` | none | +| `build`, `from`, `layers`, `lint`, `messages`, `oci`, `ports`, `size`, `tools` | none | Dropped: `build_proxy` (two), `json_str` (`encoding/json`), the claude-token, features-file, pre-folder-check and pre-git-protection migrations. @@ -185,9 +184,10 @@ Deliberate changes from the bash: - `secret`: `ls` (and `devvm secret`) is a table of every secret, SAVED and USED BY; set, rm, use and unuse rewrite running proxies' bindings (no touch); `secret_saved`/`_keychain`, `secret_removed`, `secret_used`/`_unused` replace `secret_saved keychain=`, `removed`, `secret_bound`; `unuse claude` on an image with claude is `secret_with_image`; control characters are refused too; `use` warns when no token is saved; bad names are cobra's `usage_error`. - `ssh-agent`: an unchanged mode is `agent_already`; a stopped VM's forwarding changes at its next launch (`agent_set_*`, no `agent_off`), a running one's warns `agent_next_start` (was `agent_on_restart`); a new VM without forwarding carries no agent from the start; `agent_key_unpinned` names no older devvm; a missing key is `agent_key_not_found`, a bad lifetime `agent_lifetime_invalid` (no usage); `keys` shows the default lifetime beside other options. - `ports`: `add`/`rm` subcommands with `-g`/`--global` anywhere; a running VM's pending ports are `ports_pending` on stderr (no `next_start` on stdout); `add`/`rm` of all or none is `ports_list_needed`, other bad usage cobra's `usage_error` (no `usage_ports`); `-g` refuses a hand-edited ports file too; a change checks the backend's port forwarding first. +- `size`: its own `--cpus`/`--memory`/`--disk` and `-g`/`--global`; a running VM's pending size is `size_pending` on stderr (no `next_start` on stdout); a running VM's unchanged size is `vm_size` too; `size_defaults` shows sizes as `vm_size` does; `-g` refuses a hand-edited size file too; a change checks the backend's features first; `no_vm_size`/`size_failed` (no `usage_size`, `usage_size_flag`, `size_change_failed`: cobra's `usage_error`, `lima_edit_failed`). Pending in code: -- deadcode's list: `backendtest` (tests'), `backend.Emulated` (an emulating backend), `state.WriteSize`/`WriteBackend` (size, setup), `Lock.Version` (images), `tools.Garbage` and `Tools.All` (gc). The other `*_flag_ignored` warnings name `devvm git-protect`, `size` once those exist; `devvm export` reuses rm's export. +- deadcode's list: `backendtest` (tests'), `backend.Emulated` (an emulating backend), `state.WriteBackend` (setup), `Lock.Version` (images), `tools.Garbage` and `Tools.All` (gc). The other `*_flag_ignored` warnings name `devvm git-protect` once it exists; `devvm export` reuses rm's export. - `EnsureInclude` (asks, then adds the Include line) waits for `devvm ssh`/`code`, which load devvm's agent's keys and apply forwarding too. `devvm setup` brings `base_will_rebuild`, `gc_old_hint`, the features in `--help`, and `base_features` naming it. `devvm images` labels images with `image_from` too. `log_ref`, `see_log`/`see_output` come with their callers; `tools_not_images_rm` and the tools listing with `devvm images`. - Release builds set the version with `-ldflags "-X github.com/w3cj/devvm/internal/cli.version=…"` (`.goreleaser.yaml` comes with releases); `doctor_ok` shows it. diff --git a/docs/content/docs/cli/_index.md b/docs/content/docs/cli/_index.md index 6b16b3c1..8b7c001b 100644 --- a/docs/content/docs/cli/_index.md +++ b/docs/content/docs/cli/_index.md @@ -31,6 +31,7 @@ Every devvm command, with its arguments and flags. `devvm --help` prin - [devvm secret set](devvm_secret_set.md): Save a token on this machine - [devvm secret unuse](devvm_secret_unuse.md): Stop this folder's VM using a token - [devvm secret use](devvm_secret_use.md): Let this folder's VM use a token +- [devvm size](devvm_size.md): Show or change this folder's VM's size - [devvm ssh-agent](devvm_ssh-agent.md): Show or change SSH agent forwarding for this folder's VM - [devvm ssh-agent add](devvm_ssh-agent_add.md): Load a key into devvm's own SSH agent - [devvm ssh-agent keys](devvm_ssh-agent_keys.md): List the keys in devvm's own SSH agent diff --git a/docs/content/docs/cli/devvm.md b/docs/content/docs/cli/devvm.md index 06eeccd8..65efcd4c 100644 --- a/docs/content/docs/cli/devvm.md +++ b/docs/content/docs/cli/devvm.md @@ -49,5 +49,6 @@ devvm [IMAGE] [flags] - [devvm restart](devvm_restart.md): Restart this folder's VM and open a shell in it - [devvm rm](devvm_rm.md): Delete this folder's VM - [devvm secret](devvm_secret.md): Tokens kept on this machine, for VMs to use +- [devvm size](devvm_size.md): Show or change this folder's VM's size - [devvm ssh-agent](devvm_ssh-agent.md): Show or change SSH agent forwarding for this folder's VM - [devvm update](devvm_update.md): Move this folder's VM to the newest shared tools, then open a shell in it diff --git a/docs/content/docs/cli/devvm_size.md b/docs/content/docs/cli/devvm_size.md new file mode 100644 index 00000000..7f4c28f5 --- /dev/null +++ b/docs/content/docs/cli/devvm_size.md @@ -0,0 +1,38 @@ +--- +title: devvm size +weight: 27 +--- + +Show or change this folder's VM's size + +## Synopsis + +Show this folder's VM's CPUs, memory and disk, and what changes when it next starts. --cpus, --memory and --disk change them, at once for a stopped VM, from its next start for a running one: devvm restart. A disk only grows. With -g, show or change the size new VMs get instead; what it leaves unset is the image's. + +```text +devvm size [flags] +``` + +## Options + +```text + --cpus N the N CPUs the VM gets + --disk GiB the VM's disk in GiB, at least what it has + -g, --global show or change the size new VMs get instead + -h, --help help for size + --memory GiB the VM's memory in GiB: 16, 16G or 16GiB +``` + +## Options inherited from parent commands + +```text + --backend NAME the NAME of the backend a new VM or image gets (default: the default backend file's, else lima) + --from IMAGE the container IMAGE a new VM's or image's base starts from instead of Ubuntu's cloud image: node:24, debian:13, ghcr.io/org/image@sha256:… (default: $DEVVM_FROM's) + --network-policy create the VM with network policy: it reaches only an allowlist of hosts, through a proxy on this machine, and your tokens stay here (default: ask in a terminal, else off) + --no-network-policy create the VM without network policy: it reaches anything this machine can + --ports PORTS which PORTS a new VM forwards to this machine's localhost: all, none, or a list like 5173,8000-8010 (default: the ports file's, else all) +``` + +## See also + +- [devvm](devvm.md): Open a shell in this folder's VM, creating it first diff --git a/docs/content/docs/cli/devvm_ssh-agent.md b/docs/content/docs/cli/devvm_ssh-agent.md index 37bd7675..b3c4a629 100644 --- a/docs/content/docs/cli/devvm_ssh-agent.md +++ b/docs/content/docs/cli/devvm_ssh-agent.md @@ -1,6 +1,6 @@ --- title: devvm ssh-agent -weight: 27 +weight: 28 --- Show or change SSH agent forwarding for this folder's VM diff --git a/docs/content/docs/cli/devvm_ssh-agent_add.md b/docs/content/docs/cli/devvm_ssh-agent_add.md index 15736fb0..8061ef6b 100644 --- a/docs/content/docs/cli/devvm_ssh-agent_add.md +++ b/docs/content/docs/cli/devvm_ssh-agent_add.md @@ -1,6 +1,6 @@ --- title: devvm ssh-agent add -weight: 28 +weight: 29 --- Load a key into devvm's own SSH agent diff --git a/docs/content/docs/cli/devvm_ssh-agent_keys.md b/docs/content/docs/cli/devvm_ssh-agent_keys.md index c7540419..1b3ef4f6 100644 --- a/docs/content/docs/cli/devvm_ssh-agent_keys.md +++ b/docs/content/docs/cli/devvm_ssh-agent_keys.md @@ -1,6 +1,6 @@ --- title: devvm ssh-agent keys -weight: 29 +weight: 30 --- List the keys in devvm's own SSH agent diff --git a/docs/content/docs/cli/devvm_update.md b/docs/content/docs/cli/devvm_update.md index 72183a5c..1be22721 100644 --- a/docs/content/docs/cli/devvm_update.md +++ b/docs/content/docs/cli/devvm_update.md @@ -1,6 +1,6 @@ --- title: devvm update -weight: 30 +weight: 31 --- Move this folder's VM to the newest shared tools, then open a shell in it diff --git a/docs/content/docs/commands.md b/docs/content/docs/commands.md index 39db43e8..2f5726f6 100644 --- a/docs/content/docs/commands.md +++ b/docs/content/docs/commands.md @@ -19,6 +19,8 @@ Every command, with all its flags: the [CLI reference](cli/_index.md). | `devvm ports [all\|none\|LIST]` | show or change which ports this folder's VM forwards to this machine's `localhost`: at once when it's stopped, from its next start when it runs ([details](images.md#ports)) | | `devvm ports add\|rm LIST` | forward more ports, or stop forwarding some | | `devvm ports -g ...` | the same for what new VMs forward | +| `devvm size [--cpus N] [--memory GiB] [--disk GiB]` | show or change this folder's VM's CPUs, memory and disk: at once when it's stopped, from its next start when it runs; disks only grow ([details](images.md#size)) | +| `devvm size -g ...` | the same for the size new VMs get | A new VM is made from its image (built first if it isn't, with its [shared tools](images.md#shared-tools)), with only the project folder mounted, read-write, the shared tools and its [agents' config folders](coding-agents.md) read-only, and its `.git` hooks and config locked ([`.git` protection](git-protection.md)); with `--clone`, the folder isn't mounted and the VM gets its own clone of the repo ([working on a clone](clone.md)). Then devvm starts it, sets it up ([the VM's setup](coding-agents.md#the-vms-setup)), makes it reachable [by name over SSH](ssh.md) and opens a shell in it, in place of devvm: when the shell ends, so does devvm. Without a terminal, the shell reads its commands from devvm's input. @@ -46,14 +48,14 @@ Options that take a value also work as `--cpus=N` and so on. A new VM gets its image's size (`base.yaml`'s: 4 CPUs, 8 GiB of memory and a 100 GiB disk) unless you set one: - `--cpus` takes a whole number, `--memory` and `--disk` a size in GiB: `16`, `16G` or `16GiB`, decimals allowed. -- What the flags leave unset comes from `~/.config/devvm/size`, one `cpus=`, `memory=` or `disk=` line each, if it has one. +- What the flags leave unset comes from `~/.config/devvm/size`, one `cpus=`, `memory=` or `disk=` line each, if it has one (`devvm size -g` sets it). - devvm refuses more CPUs or memory than this machine has, and a disk smaller than the image's (disks can't shrink), before it builds anything. Ports the VM listens on are forwarded to the same port on this machine's `localhost`: all of them, unless `--ports` says otherwise: - `all`, `none`, or ports and ranges like `5173,8000-8010`. - Without `--ports`, `~/.config/devvm/ports` holds the default, one line: `all`, `none` or a list (`devvm ports -g` sets it). -- `devvm ports` changes an existing VM's ([ports](images.md#ports)). +- `devvm ports` changes an existing VM's ([ports](images.md#ports)), and `devvm size` its size ([size](images.md#size)). A size or ports file that doesn't hold one is refused, like a bad flag. @@ -64,7 +66,7 @@ A size or ports file that doesn't hold one is refused, like a bad flag. 1. With an IMAGE that names what the VM lacks (`devvm go` in a base VM), devvm asks before adding it in place ([below](#adding-to-a-vm)). 2. It warns when an image the VM was made from has changed since ([outdated VMs](images.md#outdated-vms)), or there are newer shared tools than the VM's (`devvm update` moves it to them), and checks for newer tools once a day. 3. It matches the VM's [agent folder mounts](coding-agents.md#mounts) to the folders on this machine. -4. The options for new VMs are ignored, each with a warning: the VM keeps its network policy (`devvm network` changes it), `.git` protection, size, ports (`devvm ports` changes them), SSH agent forwarding (`devvm ssh-agent` changes it), backend and `--from`. +4. The options for new VMs are ignored, each with a warning: the VM keeps its network policy (`devvm network` changes it), `.git` protection, size (`devvm size` changes it), ports (`devvm ports` changes them), SSH agent forwarding (`devvm ssh-agent` changes it), backend and `--from`. 5. It checks `.git` ([`.git` protection](git-protection.md#on-each-launch)) and, on Linux hosts, names set-id files in the folder; not for a `--clone` VM, which mounts neither. 6. A stopped VM gets the size, ports and [SSH agent forwarding](ssh.md#agent-forwarding) its state asks for; a running one gets them when it next starts, and devvm says so. A VM that forwards your agent has it checked for keys; one that uses devvm's own gets the keys it lacks loaded. 7. It starts the VM if it's stopped. A running VM with network policy keeps its proxy, unless what the proxy was started with has changed ([the proxy](network.md#the-proxy)); so does one whose network policy was turned off since it started confined, until it next starts. diff --git a/docs/content/docs/images.md b/docs/content/docs/images.md index de06631a..31d0a390 100644 --- a/docs/content/docs/images.md +++ b/docs/content/docs/images.md @@ -157,6 +157,30 @@ devvm ports -g none # what new VMs forward (default: all) - `add` and `rm` take ports and ranges, not `all` or `none`; `rm` on a VM that forwards every port is refused, as there's no list to remove from. `-g` works with them too. - Ports are forwarded with or without [network policy](network.md). Builds forward none. +## Size + +A VM gets its image's size, `base.yaml`'s 4 CPUs, 8 GiB of memory and a 100 GiB disk, unless it's given another: + +```sh +devvm size # what this folder's VM has: cpus=4 memory=8GiB disk=100GiB +devvm size --cpus 6 --memory 16 # change it; what isn't given stays +devvm size --disk 200 # a bigger disk; never a smaller one +devvm size -g --memory 16 # the size new VMs get (default: the image's) +devvm size -g # cpus=, memory= and disk= lines, empty for the image's +``` + +- A new VM gets `--cpus`, `--memory` and `--disk` (`devvm --cpus 6 base`), else what `devvm size -g` set (`~/.config/devvm/size`), else the image's ([details](commands.md#size-and-ports)). +- `--cpus` takes a whole number, `--memory` and `--disk` a size in GiB: `16`, `16G` or `16GiB`, decimals allowed. More CPUs or memory than this machine has is refused. +- A stopped VM changes at once. A running one keeps its size until it next starts (`devvm restart`): until then, `devvm size` shows what it has now and says what changes. +- Disks grow but never shrink: a disk smaller than the VM's is refused. + +### Disk use + +A VM's disk size is how far it can grow, not what it takes. A project VM starts as a copy of its image's disk that shares its blocks, so a new VM takes almost nothing until it writes ([clones and overlays](lima.md#clones-and-overlays)): + +- **macOS:** an APFS clone. `du` counts the shared blocks as its own, so it overcounts. +- **Linux:** a qcow2 overlay of the image's disk, holding only the VM's changes: about 12 MB for a new VM instead of 2 GB. + ## Where state lives Nothing is written into the project folder. devvm keeps everything in two folders: diff --git a/internal/cli/docgen/docgen_test.go b/internal/cli/docgen/docgen_test.go index ef0f8491..d6c7a0c7 100644 --- a/internal/cli/docgen/docgen_test.go +++ b/internal/cli/docgen/docgen_test.go @@ -113,7 +113,7 @@ func TestHiddenCommandsAreLeftOut(t *testing.T) { "devvm_ports.md", "devvm_ports_add.md", "devvm_ports_rm.md", "devvm_rebuild.md", "devvm_remove.md", "devvm_restart.md", "devvm_rm.md", "devvm_secret.md", "devvm_secret_ls.md", "devvm_secret_rm.md", "devvm_secret_set.md", "devvm_secret_unuse.md", "devvm_secret_use.md", - "devvm_ssh-agent.md", "devvm_ssh-agent_add.md", "devvm_ssh-agent_keys.md", "devvm_update.md", + "devvm_size.md", "devvm_ssh-agent.md", "devvm_ssh-agent_add.md", "devvm_ssh-agent_keys.md", "devvm_update.md", } if !slices.Equal(names, want) { t.Errorf("files = %v, want %v", names, want) diff --git a/internal/cli/root.go b/internal/cli/root.go index e5236e49..1d9ef4f1 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -39,7 +39,7 @@ func NewRoot() *cobra.Command { addUpFlags(root, u) addVersion(root) root.AddCommand(newBuildCmd(g), newRebuildCmd(g), newMsgCmd(), - newRestartCmd(g), newRemoveCmd(g), newUpdateCmd(g), newAdoptCmd(), newRmCmd(), newLsCmd(), newLogCmd(), newPolicyCmd(), newNetworkCmd(), newSSHAgentCmd(), newPortsCmd(), newDoctorCmd(g), newQEMUCmd(), newProxyCmd(), newRefreshToolsCmd(), newSecretCmd(), + newRestartCmd(g), newRemoveCmd(g), newUpdateCmd(g), newAdoptCmd(), newRmCmd(), newLsCmd(), newLogCmd(), newPolicyCmd(), newNetworkCmd(), newSSHAgentCmd(), newPortsCmd(), newSizeCmd(), newDoctorCmd(g), newQEMUCmd(), newProxyCmd(), newRefreshToolsCmd(), newSecretCmd(), newAuthCmd(), newVersionCmd(), newCompletionCmd()) addCompletions(root) return root diff --git a/internal/cli/size.go b/internal/cli/size.go new file mode 100644 index 00000000..b93cc82b --- /dev/null +++ b/internal/cli/size.go @@ -0,0 +1,43 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/ui" + "github.com/w3cj/devvm/internal/vm" +) + +// newSizeCmd is devvm size [--cpus N] [--memory GiB] [--disk GiB], with -g +// for the size new VMs get. Its size flags are its own, in place of the +// root's for new VMs. +func newSizeCmd() *cobra.Command { + var ( + global bool + s vm.Size + ) + cmd := &cobra.Command{ + Use: "size", + Short: "Show or change this folder's VM's size", + Long: "Show this folder's VM's CPUs, memory and disk, and what changes when it next starts. " + + "--cpus, --memory and --disk change them, at once for a stopped VM, from its next start for " + + "a running one: devvm restart. A disk only grows. With -g, show or change the size new VMs " + + "get instead; what it leaves unset is the image's.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + withEnv(func(env *vm.Env) error { + if s == (vm.Size{}) { + return env.ShowSize(cmd.Context(), ui.Stdout(), global) + } + return env.SetSize(cmd.Context(), s, global) + }, msg.SizeFailed) + return nil + }, + } + f := cmd.Flags() + f.BoolVarP(&global, "global", "g", false, "show or change the size new VMs get instead") + f.StringVar(&s.CPUs, "cpus", "", "the `N` CPUs the VM gets") + f.StringVar(&s.Memory, "memory", "", "the VM's memory in `GiB`: 16, 16G or 16GiB") + f.StringVar(&s.Disk, "disk", "", "the VM's disk in `GiB`, at least what it has") + return cmd +} diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 176c92c5..a23a2ef5 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -987,6 +987,11 @@ func NoVMPorts(dir string) M { return M{id: "no_vm_ports", vals: []val{{"dir", dir}}} } +// NoVMSize is [no_vm_size]: "no VM for {{.dir}}: devvm --cpus N makes one with a size, or -g sets the size new VMs get" +func NoVMSize(dir string) M { + return M{id: "no_vm_size", vals: []val{{"dir", dir}}} +} + // NoVMSSHAgent is [no_vm_ssh_agent]: "no VM for {{.dir}}: devvm makes one, devvm --ssh-agent one that forwards your SSH agent" func NoVMSSHAgent(dir string) M { return M{id: "no_vm_ssh_agent", vals: []val{{"dir", dir}}} @@ -1277,7 +1282,17 @@ func ShareWaiting(dir string) M { return M{id: "share_waiting", vals: []val{{"dir", dir}}} } -// SizeFlagsIgnored is [size_flags_ignored]: "--cpus, --memory and --disk only apply to new VMs" +// SizeDefaults is [size_defaults]: "new VMs get {{.size}}" +func SizeDefaults(size string) M { + return M{id: "size_defaults", vals: []val{{"size", size}}} +} + +// SizeFailed is [size_failed]: "couldn't show or change the size: {{.reason}}" +func SizeFailed(reason string) M { + return M{id: "size_failed", vals: []val{{"reason", reason}}} +} + +// SizeFlagsIgnored is [size_flags_ignored]: "--cpus, --memory and --disk only apply to new VMs: devvm size --cpus N" func SizeFlagsIgnored() M { return M{id: "size_flags_ignored"} } @@ -1292,6 +1307,11 @@ func SizeNotGib(flag string, value string) M { return M{id: "size_not_gib", vals: []val{{"flag", flag}, {"value", value}}} } +// SizePending is [size_pending]: "{{.vm}} gets {{.size}} from its next start: devvm restart" +func SizePending(size string, vm string) M { + return M{id: "size_pending", vals: []val{{"size", size}, {"vm", vm}}} +} + // SSHAgentEmpty is [ssh_agent_empty]: "your SSH agent has no keys, so git over SSH won't work in the VM" func SSHAgentEmpty() M { return M{id: "ssh_agent_empty"} @@ -1582,6 +1602,11 @@ func VMOutdated(changed string) M { return M{id: "vm_outdated", vals: []val{{"changed", changed}}} } +// VMSize is [vm_size]: "{{.vm}} has {{.size}}" +func VMSize(size string, vm string) M { + return M{id: "vm_size", vals: []val{{"size", size}, {"vm", vm}}} +} + // VMUnfinished is [vm_unfinished]: "{{.vm}}'s creation didn't finish: devvm rm deletes it, and devvm makes it again" func VMUnfinished(vm string) M { return M{id: "vm_unfinished", vals: []val{{"vm", vm}}} @@ -1786,6 +1811,7 @@ var specs = map[string]spec{ "no_vm": {fields: []string{"dir"}}, "no_vm_policy": {fields: []string{"dir"}}, "no_vm_ports": {fields: []string{"dir"}}, + "no_vm_size": {fields: []string{"dir"}}, "no_vm_ssh_agent": {fields: []string{"dir"}}, "not_a_rule": {fields: []string{"rule"}}, "not_an_image": {fields: []string{"name"}}, @@ -1844,9 +1870,12 @@ var specs = map[string]spec{ "setid_files": {fields: []string{"files"}}, "share_lock_held": {fields: []string{"dir"}}, "share_waiting": {fields: []string{"dir"}}, + "size_defaults": {fields: []string{"size"}}, + "size_failed": {fields: []string{"reason"}}, "size_flags_ignored": {}, "size_next_start": {fields: []string{"vm"}}, "size_not_gib": {fields: []string{"flag", "value"}}, + "size_pending": {fields: []string{"size", "vm"}}, "ssh_agent_empty": {}, "ssh_agent_failed": {fields: []string{"reason"}}, "ssh_agent_flag_ignored": {}, @@ -1905,5 +1934,6 @@ var specs = map[string]spec{ "vm_other_folder_adopt": {fields: []string{"vm", "was"}}, "vm_other_folder_rm": {fields: []string{"vm", "was"}}, "vm_outdated": {fields: []string{"changed"}}, + "vm_size": {fields: []string{"size", "vm"}}, "vm_unfinished": {fields: []string{"vm"}}, } diff --git a/internal/vm/commands.go b/internal/vm/commands.go index 07dd58cc..98eec056 100644 --- a/internal/vm/commands.go +++ b/internal/vm/commands.go @@ -324,15 +324,19 @@ func (e *Env) SetNetwork(ctx context.Context, on bool) error { return nil } -// agentVM finds the folder's VM for devvm ssh-agent, which must exist, be -// made for this folder and have finished being made. -func (e *Env) agentVM(ctx context.Context) (*found, error) { +// agentVM finds the folder's VM for devvm ssh-agent. +func (e *Env) agentVM(ctx context.Context) (*found, error) { return e.folderVM(ctx, msg.NoVMSSHAgent) } + +// folderVM finds the folder's VM for a command that shows or changes it, +// which must exist (else noVM), be made for this folder and have finished +// being made. +func (e *Env) folderVM(ctx context.Context, noVM func(dir string) msg.M) (*found, error) { t, err := e.find(ctx, "") if err != nil { return nil, err } if !t.exists { - return nil, msg.NoVMSSHAgent(t.f.Dir) + return nil, noVM(t.f.Dir) } if err := e.checkFolder(t.f, t.st); err != nil { return nil, err diff --git a/internal/vm/existing.go b/internal/vm/existing.go index 7c498b08..d1776ceb 100644 --- a/internal/vm/existing.go +++ b/internal/vm/existing.go @@ -216,17 +216,7 @@ func (e *Env) run(ctx context.Context, b backend.Backend, st *state.VM) (backend // applySize makes a stopped VM's size what its state asks for, where it // differs (disks only grow). A running VM's waits for its next start. func applySize(ctx context.Context, b backend.Backend, st *state.VM, in backend.Instance) error { - want := Size{CPUs: st.Get(KeyCPUs), Memory: st.Get(KeyMemory), Disk: st.Get(KeyDisk)}.Backend() - var edit backend.Size - if want.CPUs != 0 && want.CPUs != in.Size.CPUs { - edit.CPUs = want.CPUs - } - if want.MemoryGiB != 0 && want.MemoryGiB != in.Size.MemoryGiB { - edit.MemoryGiB = want.MemoryGiB - } - if want.DiskGiB > in.Size.DiskGiB { - edit.DiskGiB = want.DiskGiB - } + edit := pendingSize(st, in.Size) if edit == (backend.Size{}) { return nil } diff --git a/internal/vm/ports.go b/internal/vm/ports.go index 0eecec85..fee0be7b 100644 --- a/internal/vm/ports.go +++ b/internal/vm/ports.go @@ -140,24 +140,8 @@ func (e *Env) defaultPorts() (string, error) { return ParsePorts(def) } -// portsVM finds the folder's VM for devvm ports, which must exist, be -// made for this folder and have finished being made. -func (e *Env) portsVM(ctx context.Context) (*found, error) { - t, err := e.find(ctx, "") - if err != nil { - return nil, err - } - if !t.exists { - return nil, msg.NoVMPorts(t.f.Dir) - } - if err := e.checkFolder(t.f, t.st); err != nil { - return nil, err - } - if !t.st.Exists() || t.st.Get(KeyNet) == "" { - return nil, msg.VMUnfinished(t.f.Name) - } - return t, nil -} +// portsVM finds the folder's VM for devvm ports. +func (e *Env) portsVM(ctx context.Context) (*found, error) { return e.folderVM(ctx, msg.NoVMPorts) } // Ports writes to w which ports the folder's VM forwards (all, none or a // list), saying so when that changes at its next start; with global, diff --git a/internal/vm/size.go b/internal/vm/size.go index 34825cf9..3feda5c1 100644 --- a/internal/vm/size.go +++ b/internal/vm/size.go @@ -2,6 +2,8 @@ package vm import ( "bufio" + "context" + "io" "os" "path/filepath" "regexp" @@ -12,6 +14,8 @@ import ( "github.com/w3cj/devvm/internal/backend" "github.com/w3cj/devvm/internal/msg" "github.com/w3cj/devvm/internal/platform" + "github.com/w3cj/devvm/internal/state" + "github.com/w3cj/devvm/internal/ui" ) // Size is a VM's size as devvm stores it: CPUs a whole number, memory and @@ -120,6 +124,151 @@ func (s Size) Backend() backend.Size { return b } +// pendingSize returns what of the size st asks for the VM, which has has, +// lacks: zero where it matches. Disks only grow, so a smaller one asked +// for is had. +func pendingSize(st *state.VM, has backend.Size) backend.Size { + want := Size{CPUs: st.Get(KeyCPUs), Memory: st.Get(KeyMemory), Disk: st.Get(KeyDisk)}.Backend() + var p backend.Size + if want.CPUs != 0 && want.CPUs != has.CPUs { + p.CPUs = want.CPUs + } + if want.MemoryGiB != 0 && want.MemoryGiB != has.MemoryGiB { + p.MemoryGiB = want.MemoryGiB + } + if want.DiskGiB > has.DiskGiB { + p.DiskGiB = want.DiskGiB + } + return p +} + +// SizeText returns a size as devvm size shows it, without what's unset: +// cpus=4 memory=8GiB disk=100GiB. +func SizeText(s backend.Size) string { + var f []string + if s.CPUs > 0 { + f = append(f, KeyCPUs+"="+strconv.Itoa(s.CPUs)) + } + if s.MemoryGiB > 0 { + f = append(f, KeyMemory+"="+strconv.FormatFloat(s.MemoryGiB, 'g', -1, 64)+"GiB") + } + if s.DiskGiB > 0 { + f = append(f, KeyDisk+"="+strconv.FormatFloat(s.DiskGiB, 'g', -1, 64)+"GiB") + } + return strings.Join(f, " ") +} + +// fields returns a size's keys and values, as the size file has them. +func (s Size) fields() [][2]string { + return [][2]string{{KeyCPUs, s.CPUs}, {KeyMemory, s.Memory}, {KeyDisk, s.Disk}} +} + +// defaultSize reads the size new VMs get, checked: the file may have +// been edited by hand. +func (e *Env) defaultSize() (Size, error) { + def, err := state.ReadSize(e.Dirs) + if err != nil { + return Size{}, err + } + return Size{CPUs: def.CPUs, Memory: def.Memory, Disk: def.Disk}.Parse() +} + +// ShowSize writes to w the size of the folder's VM (cpus=4 memory=8GiB +// disk=100GiB), saying what changes at its next start; with global, the +// size new VMs get, a key=value line each, empty for the image's. +func (e *Env) ShowSize(ctx context.Context, w io.Writer, global bool) error { + if global { + def, err := e.defaultSize() + if err != nil { + return err + } + var b strings.Builder + for _, kv := range def.fields() { + b.WriteString(kv[0] + "=" + kv[1] + "\n") + } + _, err = io.WriteString(w, b.String()) + return err + } + t, err := e.folderVM(ctx, msg.NoVMSize) + if err != nil { + return err + } + in, err := t.b.Inspect(ctx, t.f.Name) + if err != nil { + return err + } + if _, err := io.WriteString(w, SizeText(in.Size)+"\n"); err != nil { + return err + } + if p := pendingSize(t.st, in.Size); p != (backend.Size{}) { + ui.Note(msg.SizePending(SizeText(p), t.f.Name)) + } + return nil +} + +// SetSize changes the folder's VM's size to what s sets: at once when it's +// stopped, from its next start when it runs. A disk only grows. With +// global, it changes the size new VMs get instead. +func (e *Env) SetSize(ctx context.Context, s Size, global bool) error { + s, err := s.Parse() + if err != nil { + return err + } + host, err := e.Host() + if err != nil { + return err + } + if global { + old, err := e.defaultSize() + if err != nil { + return err + } + if err := s.Check(host, 0, ""); err != nil { + return err + } + def := s.Or(old) + if err := state.WriteSize(e.Dirs, state.Size{CPUs: def.CPUs, Memory: def.Memory, Disk: def.Disk}); err != nil { + return err + } + ui.Info(msg.SizeDefaults(SizeText(def.Backend()))) + return nil + } + t, err := e.folderVM(ctx, msg.NoVMSize) + if err != nil { + return err + } + vm, st, b := t.f.Name, t.st, t.b + if err := backend.Require(b, vm, s.Backend().Features()...); err != nil { + return err + } + in, err := b.Inspect(ctx, vm) + if err != nil { + return err + } + if err := s.Check(host, in.Size.DiskGiB, vm); err != nil { + return err + } + for _, kv := range s.fields() { + if kv[1] == "" { + continue + } + if err := st.Set(kv[0], kv[1]); err != nil { + return err + } + } + if err := applySize(ctx, b, st, in); err != nil { + return err + } + // Otherwise applySize said it waits for the next start. + if in, err = b.Inspect(ctx, vm); err != nil { + return err + } + if pendingSize(st, in.Size) == (backend.Size{}) { + ui.Info(msg.VMSize(SizeText(in.Size), vm)) + } + return nil +} + // BaseDisk returns the disk size in GiB that base.yaml in root gives base, // and so every image and new VM (disks can't shrink); 0 when it sets none. func BaseDisk(root string) float64 { diff --git a/internal/vm/size_test.go b/internal/vm/size_test.go new file mode 100644 index 00000000..9193c436 --- /dev/null +++ b/internal/vm/size_test.go @@ -0,0 +1,103 @@ +package vm + +import ( + "slices" + "strings" + "testing" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/state" +) + +func TestSizeText(t *testing.T) { + for s, want := range map[backend.Size]string{ + {CPUs: 4, MemoryGiB: 8, DiskGiB: 100}: "cpus=4 memory=8GiB disk=100GiB", + {MemoryGiB: 1.5}: "memory=1.5GiB", + {}: "", + } { + if got := SizeText(s); got != want { + t.Errorf("SizeText(%+v) = %q, want %q", s, got, want) + } + } +} + +// devvm size: a stopped VM's size changes at once, only where it differs; +// a running one's waits, and shows as pending. A smaller disk, or a size +// the backend can't set, is refused before the state changes. -g changes +// the size file and keeps what it leaves unset. +func TestSetSize(t *testing.T) { + e, f, _ := upEnv(t, allNative()) + var b strings.Builder + if err := e.ShowSize(t.Context(), &b, false); names(err) != "no_vm_size dir="+e.Dir { + t.Errorf("no VM: %s", names(err)) + } + st := existingVM(t, e, Options{Image: "base", NoNetworkPolicy: true}) + vm := st.Name() + in := f.Instances[vm] + in.Size = backend.Size{CPUs: 4, MemoryGiB: 8, DiskGiB: 100} + f.Instances[vm] = in + + before := len(f.Calls()) + if err := e.SetSize(t.Context(), Size{CPUs: "2", Memory: "8G"}, false); err != nil { + t.Fatal(names(err)) + } + if ms := f.Methods()[before:]; slices.Contains(ms, "SetSize") { + t.Errorf("a running VM was changed: %q", ms) + } + if st, _ := state.ReadVM(e.Dirs, vm); st.Get(KeyCPUs) != "2" || st.Get(KeyMemory) != "8" { + t.Errorf("state cpus=%q memory=%q", st.Get(KeyCPUs), st.Get(KeyMemory)) + } + st, _ = state.ReadVM(e.Dirs, vm) + if p := pendingSize(st, f.Instances[vm].Size); p != (backend.Size{CPUs: 2}) { + t.Errorf("pending = %+v", p) + } + + if err := e.SetSize(t.Context(), Size{Disk: "50"}, false); names(err) != "disk_shrink have=100 vm="+vm+" want=50" { + t.Errorf("smaller disk: %s", names(err)) + } + caps := allNative() + caps[backend.FeatureDisk] = backend.None + f.Capabilities = caps + if err := e.SetSize(t.Context(), Size{Disk: "200"}, false); !strings.HasPrefix(names(err), "backend_lacks ") { + t.Errorf("without the feature: %s", names(err)) + } + if st, _ := state.ReadVM(e.Dirs, vm); st.Get(KeyDisk) != "" { + t.Errorf("disk=%q", st.Get(KeyDisk)) + } + f.Capabilities = allNative() + + if err := f.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + before = len(f.Calls()) + if err := e.SetSize(t.Context(), Size{Disk: "120"}, false); err != nil { + t.Fatal(names(err)) + } + var set []backend.Size + for _, c := range f.Calls()[before:] { + if c.Method == "SetSize" { + set = append(set, c.Args[1].(backend.Size)) + } + } + if len(set) != 1 || set[0] != (backend.Size{CPUs: 2, DiskGiB: 120}) { + t.Errorf("SetSize calls = %+v", set) + } + b.Reset() + if err := e.ShowSize(t.Context(), &b, false); err != nil || b.String() != "cpus=2 memory=8GiB disk=120GiB\n" { + t.Errorf("ShowSize = %q, %v", b.String(), names(err)) + } + + if err := e.SetSize(t.Context(), Size{CPUs: "2", Memory: "3"}, true); err != nil { + t.Fatal(names(err)) + } + if err := e.SetSize(t.Context(), Size{Memory: "4GiB"}, true); err != nil { + t.Fatal(names(err)) + } + if err := e.SetSize(t.Context(), Size{CPUs: "16"}, true); names(err) != "too_many_cpus have=8 want=16" { + t.Errorf("-g --cpus 16: %s", names(err)) + } + b.Reset() + if err := e.ShowSize(t.Context(), &b, true); err != nil || b.String() != "cpus=2\nmemory=4\ndisk=\n" { + t.Errorf("ShowSize -g = %q, %v", b.String(), names(err)) + } +} diff --git a/internal/vm/up.go b/internal/vm/up.go index 70ddafa8..b9889104 100644 --- a/internal/vm/up.go +++ b/internal/vm/up.go @@ -249,13 +249,11 @@ func (e *Env) create(ctx context.Context, o Options, f project.Folder, b backend } // Defaults are checked again: the files may be edited by hand. All // before the build, which can take minutes. - def, err := state.ReadSize(e.Dirs) + def, err := e.defaultSize() if err != nil { return err } - if size, err = size.Or(Size{CPUs: def.CPUs, Memory: def.Memory, Disk: def.Disk}).Parse(); err != nil { - return err - } + size = size.Or(def) host, err := e.Host() if err != nil { return err diff --git a/locales/en.toml b/locales/en.toml index 0e97a935..dcd25311 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -394,7 +394,7 @@ other = "--network-policy and --no-network-policy only apply to new VMs: devvm n other = "--no-git-protect only applies to new VMs" [size_flags_ignored] -other = "--cpus, --memory and --disk only apply to new VMs" +other = "--cpus, --memory and --disk only apply to new VMs: devvm size --cpus N" [ports_flag_ignored] other = "--ports only applies to new VMs: devvm ports LIST" @@ -460,6 +460,25 @@ other = "this machine has {{.have}} CPUs: --cpus {{.want}} is more" description = "have and want are sizes in GiB" other = "this machine has {{.have}} GiB of memory: --memory {{.want}} is more" +[vm_size] +description = "size is what the VM has: cpus=4 memory=8GiB disk=100GiB" +other = "{{.vm}} has {{.size}}" + +[size_pending] +description = "size is what changes: cpus=6 memory=16GiB" +other = "{{.vm}} gets {{.size}} from its next start: devvm restart" + +[size_defaults] +description = "size is what's set: cpus=6 memory=16GiB" +other = "new VMs get {{.size}}" + +[no_vm_size] +other = "no VM for {{.dir}}: devvm --cpus N makes one with a size, or -g sets the size new VMs get" + +[size_failed] +description = "reason is an error from the system, in English" +other = "couldn't show or change the size: {{.reason}}" + [port_invalid] description = "value is quoted, as given" other = "{{.value}} isn't a port list: use all, none, or ports and ranges like 5173,8000-8010" diff --git a/testdata/script/size.txtar b/testdata/script/size.txtar new file mode 100644 index 00000000..03923f71 --- /dev/null +++ b/testdata/script/size.txtar @@ -0,0 +1,101 @@ +# devvm size: a folder's VM's CPUs, memory and disk, changed at once for a +# stopped VM, from its next start for a running one; with -g, the size new +# VMs get (the size file). +env DEVVM_MESSAGES=names +env VMS=$XDG_DATA_HOME/devvm/vms +env CFG=$XDG_CONFIG_HOME/devvm + +# No VM yet. +mkdir $WORK/web +cd $WORK/web +! exec devvm size +stderr '^devvm: no_vm_size dir=\S*/web$' +! exec devvm size big +stderr '^devvm: usage_error ' + +# -g: the size new VMs get, unset (the image's) until it's set; each change +# keeps what it leaves unset. No VM is looked at. +exec sh -c ': > "$STUB_LOG"' +exec devvm size -g +cmp stdout $WORK/unset +exec devvm size -g --cpus 2 --memory 3G +stdout '^==> size_defaults size=cpus=2 memory=3GiB$' +exec devvm size -g --memory=2.5GiB +stdout '^==> size_defaults size=cpus=2 memory=2\.5GiB$' +exec devvm size -g +cmp stdout $WORK/set +exec sh -c 'cat "$CFG/size"' +stdout '^cpus=2$' +stdout '^memory=2\.5$' +! stdout disk +! exec devvm size -g --cpus 9999 +stderr '^devvm: too_many_cpus have=[0-9]+ want=9999$' +! exec devvm size -g --memory 16M +stderr '^devvm: size_not_gib flag=--memory value="16M"$' +! stub_calls +# A hand-edited size file is refused, to show or change. +cp $WORK/bad-size $CFG/size +! exec devvm size -g +stderr '^devvm: size_not_gib flag=--memory value="1\$\(touch x\)"$' +! exec devvm size -g --cpus 2 +stderr '^devvm: size_not_gib ' +rm $CFG/size + +# A new VM. Running: devvm size shows what it has, and a change waits for +# its next start. +exec devvm --no-network-policy --no-git-protect base +exec devvm size +stdout '\Acpus=4 memory=8GiB disk=100GiB\n\z' +! stderr . +exec sh -c ': > "$STUB_LOG"' +exec devvm size --cpus 2 --memory 3 +stderr '^devvm: size_next_start vm=devvm-web-[0-9a-f]{14}$' +! stdout vm_size +stub_calls +! stdout 'limactl edit' +exec sh -c 'cat "$VMS"/devvm-web-*' +stdout '^cpus=2$' +stdout '^memory=3$' +exec devvm size +stdout '\Acpus=4 memory=8GiB disk=100GiB\n\z' +stderr '^size_pending size=cpus=2 memory=3GiB vm=devvm-web-[0-9a-f]{14}$' +# Back to what it has: nothing waits. +exec devvm size --cpus 4 --memory 8 +stdout '^==> vm_size size=cpus=4 memory=8GiB disk=100GiB vm=devvm-web-[0-9a-f]{14}$' +! stderr . +# A smaller disk is refused, running or not, and so is more than this +# machine has. +! exec devvm size --disk 50 +stderr '^devvm: disk_shrink have=100 vm=devvm-web-[0-9a-f]{14} want=50$' +! exec devvm size --cpus 9999 +stderr '^devvm: too_many_cpus have=[0-9]+ want=9999$' +! exec devvm size --cpus 1.5 +stderr '^devvm: cpus_not_number value="1\.5"$' + +# Stopped: changed at once, only what differs. +exec sh -c 'limactl stop "$(basename "$VMS"/devvm-web-*)"' +exec sh -c ': > "$STUB_LOG"' +exec devvm size --cpus 2 --memory 8 --disk 120GiB +stdout '^==> vm_size size=cpus=2 memory=8GiB disk=120GiB vm=devvm-web-[0-9a-f]{14}$' +stub_calls +stdout '^limactl edit --tty=false devvm-web-[0-9a-f]{14} --cpus 2 --disk 120$' +exec devvm size +stdout '\Acpus=2 memory=8GiB disk=120GiB\n\z' +! stderr . +! exec devvm size --disk 100 +stderr '^devvm: disk_shrink have=120 vm=devvm-web-[0-9a-f]{14} want=100$' + +# --cpus on devvm is ignored, with a warning naming devvm size. +exec devvm --cpus 3 +stderr '^devvm: size_flags_ignored$' + +-- unset -- +cpus= +memory= +disk= +-- set -- +cpus=2 +memory=2.5 +disk= +-- bad-size -- +memory=1$(touch x) diff --git a/testdata/stubs/limactl b/testdata/stubs/limactl index 94dde849..792b49d4 100755 --- a/testdata/stubs/limactl +++ b/testdata/stubs/limactl @@ -5,7 +5,7 @@ # Stopped), which create, clone, start, stop and delete keep up to date. A # VM's config is $STUB_DIR/config-.json, else {}; its size # ("CPUS MEMORY DISK", in bytes) $STUB_DIR/size-, else 4 CPUs, 8 GiB -# and 100 GiB. A VM's ssh config is $LIMA_HOME//ssh.config, as start +# and 100 GiB, which edit's --cpus, --memory and --disk change. A VM's ssh config is $LIMA_HOME//ssh.config, as start # writes it (Lima's own options, host keys unchecked) unless it exists; its # host keys, read with a shell, are one made-up key per VM, unless # $STUB_DIR/hostkeys-fail exists. @@ -107,6 +107,19 @@ case ${1:-} in "${names[0]}" "$LIMA_HOME" "$LIMA_HOME/${names[0]}" > "$cfg" [[ ! -e $STUB_DIR/start-fails ]] || exit 1 ;; stop) set_status "${names[0]}" Stopped ;; + edit) + # --cpus N, --memory GiB and --disk GiB change the VM's size. + read -r cpus mem disk < <(cat "$STUB_DIR/size-${names[0]}" 2>/dev/null || echo "4 8589934592 107374182400") + args=("$@") + for ((i = 0; i < ${#args[@]} - 1; i++)); do + v=${args[i + 1]} + case ${args[i]} in + --cpus) cpus=$v ;; + --memory) mem=$(awk -v g="$v" 'BEGIN { printf "%.0f", g * 1073741824 }') ;; + --disk) disk=$(awk -v g="$v" 'BEGIN { printf "%.0f", g * 1073741824 }') ;; + esac + done + echo "$cpus $mem $disk" > "$STUB_DIR/size-${names[0]}" ;; delete) for n in "${names[@]}"; do set_status "$n"; done [[ ! -e $STUB_DIR/delete-fails ]] || exit 1 ;; diff --git a/tests/e2e.sh b/tests/e2e.sh index 1f9c851d..54d0e2a4 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -5,7 +5,7 @@ # Ubuntu's cloud image to download). images builds, rebuilds and interrupts images; # project makes a VM from base in a project folder and checks its mounts, ssh by # name with pinned host keys, .git protection and shell, then opening it again, -# restart, devvm ports and rm, an agent VM's folders and exported history, and SSH agent forwarding +# restart, devvm size, devvm ports and rm, an agent VM's folders and exported history, and SSH agent forwarding # (a throwaway agent's, and devvm's own with a throwaway key); clone makes a --clone # VM of a throwaway repo and checks its clone, the remote, fetching, and rm's checks # for unfetched commits and uncommitted changes and the work it keeps; tools makes a node @@ -268,10 +268,13 @@ if want project; then section "a base project" p=$(newproj web); git -C "$p" init -q # The shell devvm opens reads its commands from devvm's input: these, then it ends. -launch "$p" 'pwd; echo e2e-shell-ran' --no-network-policy base +launch "$p" 'pwd; echo e2e-shell-ran' --no-network-policy --cpus 2 --memory 3 --disk 120 base check "devvm creates the VM from base, and opens a shell in the folder" bash -c " [[ -n '$vm' && \$(status_of '$vm') == Running ]] && grep -qx '$p' '$work/last.log' && grep -qx e2e-shell-ran '$work/last.log' && grep -qx image=base '$vms/$vm' && grep -qx net=off '$vms/$vm' && grep -qx 'dir=$p' '$vms/$vm'" +check "it gets --cpus, --memory and --disk" in_vm "$vm" \ + '[[ $(nproc) == 2 ]] && (( $(awk "/^MemTotal:/ { print int(\$2 / 1048576 + 0.5) }" /proc/meminfo) == 3 )) && (( $(df -BG --output=size / | tail -1 | tr -dc 0-9) >= 115 ))' +check "devvm size shows it" bash -c "cd '$p' && [[ \$('$D' size 2>&1) == 'cpus=2 memory=3GiB disk=120GiB' ]]" check "ls lists it, and no image" bash -c "'$D' ls >'$work/ls.out' 2>&1 && grep -Eq '^$vm +Running +base +(on|off) +off +lima +$p\$' '$work/ls.out' && ! grep -q '^devvm-img-' '$work/ls.out'" check "the folder is mounted read-write" bash -c "limactl shell --workdir / $vm bash -c 'echo from-vm > $p/vm.txt' &1 | grep -qF \"\$(m ports_next_start vm=$vm)\" && [[ \$('$D' ports 2>/dev/null) == all ]]" -check "and apply on restart" bash -c "cd '$p' && printf 'exit\n' | '$D' restart >'$work/last.log' 2>&1 && - [[ \$('$D' ports 2>&1) == 47170-47173 ]]" +check "so does its new size" bash -c "cd '$p' && '$D' size --cpus 3 2>&1 | grep -qF \"\$(m size_next_start vm=$vm)\" && + '$D' size 2>&1 >/dev/null | grep -qF \"\$(m size_pending size=cpus=3 vm=$vm)\"" +check "and they apply on restart" bash -c "cd '$p' && printf 'exit\n' | '$D' restart >'$work/last.log' 2>&1 && + [[ \$('$D' ports 2>&1) == 47170-47173 && \$(limactl shell --workdir / $vm nproc &1) == 'cpus=3 memory=3GiB disk=120GiB' ]]" +check "a smaller disk is refused" bash -c "cd '$p' && ! '$D' size --disk 100 '$work/last.log' 2>&1 && + grep -qF \"\$(m disk_shrink have=120 vm=$vm want=100)\" '$work/last.log'" # Listeners on each kind of address Lima matches differently (loopback, every address; IPv4 and 6), on # listed ports (47170-47173) and unlisted ones (47174-47177). Their output goes nowhere, or the SSH # session waits for them.