From 5bfb89c371c2f048345ef7fb5e8a537e6d7a170b Mon Sep 17 00:00:00 2001 From: w3cj Date: Sat, 31 Oct 2026 13:08:52 -0700 Subject: [PATCH] feat(gc): gc --caches frees devvm's share of the backends' own caches Lima's download cache (9.1G on the user's machine) and smolvm's caches (22G) are filled by devvm's builds but are the backends' own and hold the user's own downloads too. devvm never prunes them on its own and never runs limactl prune, smolvm pack prune or smolvm machine prune (each reaches the user's own entries). gc --caches, only in a terminal (gc_caches_need_terminal otherwise, before anything is deleted), then lists devvm's share of each backend's cache with sizes and asks for each backend apart (backend.CacheCleaner): - Lima: entries of download/by-url-sha256 whose url hashes to the folder's name and is Ubuntu's cloud image at the address devvm downloads base from, for its release, a dated release, that no image record names, unchanged for an hour (a build may be downloading). Lima copies a VM's disk out of the cache, so no VM needs an entry. - smolvm (macOS): the disks smolvm unpacks of each pack (vms/_pack-storage-seeds/v2--auto, found on the user's machine: 20G of the 22G), tied to devvm's packs by their SHA-256 - packs devvm has, and every pack it makes from now on, which smolvm/packs records - that no machine of devvm's was made from, unchanged for an hour, with their lock files. Disks of packs that are gone and unrecorded can't be tied to devvm and stay; so do the machines' folders and smolvm's other caches. On Linux smolvm's state is devvm's own folder: nothing listed. - Docker: volumes with devvm's label that no VM has, not the tools' volume, not one of a VM devvm has state for (a VM being made makes its volumes before its container). Never an unlabelled one, never a prune. Each delete checks the entry again first. With --backend, only that backend's cache. Messages: gc_caches_need_terminal, gc_cache, gc_cache_entry, gc_cache_confirm, deleted_cache. Docs: the What devvm keeps page (the backends' caches, Lima, smolvm, Docker), backends/smolvm.md's Cleaning smolvm's caches, backends/lima.md, the uninstall steps, using/images.md's Cleaning up, the CLI reference. Review (touches nothing of the user's): limactl prune empties the whole cache and isn't used; --keep-referred would see only devvm's Lima home. smolvm pack prune removes any unused cached extraction, the user's own packs' included, and machine prune works on a named machine's images; neither is used. Lima entries are tied by address and hash, smolvm disks by the SHA-256 of devvm's own packs, Docker volumes by devvm's label. Tests: lima TestDevvmCache (your download, a recorded release, one being written, a wrong layout, another file kept); smolvm TestDevvmCache (a VM's pack, someone else's, a recent disk, a machine's folder kept; a recorded deleted pack's disk freed; Linux lists none), TestPackRecorded; docker TestDevvmCacheVolumes (a VM's, the tools', one being made, someone else's kept); gc_caches.txtar (refused without a terminal before anything is deleted; the default run leaves the caches). Co-Authored-By: Claude Opus 5.5 --- docs/content/docs/backends/lima.md | 2 +- docs/content/docs/backends/smolvm.md | 2 +- docs/content/docs/cli/devvm_gc.md | 3 +- docs/content/docs/getting-started/install.md | 2 +- docs/content/docs/using/images.md | 1 + docs/content/docs/using/space.md | 8 +- internal/backend/caches.go | 25 +++ internal/backend/docker/caches.go | 92 ++++++++++ internal/backend/docker/docker_test.go | 39 +++++ internal/backend/lima/caches.go | 149 ++++++++++++++++ internal/backend/lima/caches_test.go | 88 ++++++++++ internal/backend/smolvm/build.go | 5 +- internal/backend/smolvm/caches.go | 171 +++++++++++++++++++ internal/backend/smolvm/caches_test.go | 125 ++++++++++++++ internal/cli/gc.go | 24 ++- internal/cli/gc_caches.go | 62 +++++++ internal/msg/docs.go | 1 + internal/msg/messages_gen.go | 30 ++++ internal/structure/structure_test.go | 6 +- locales/en.toml | 17 ++ testdata/script/gc_caches.txtar | 19 +++ 21 files changed, 860 insertions(+), 11 deletions(-) create mode 100644 internal/backend/caches.go create mode 100644 internal/backend/docker/caches.go create mode 100644 internal/backend/lima/caches.go create mode 100644 internal/backend/lima/caches_test.go create mode 100644 internal/backend/smolvm/caches.go create mode 100644 internal/backend/smolvm/caches_test.go create mode 100644 internal/cli/gc_caches.go create mode 100644 testdata/script/gc_caches.txtar diff --git a/docs/content/docs/backends/lima.md b/docs/content/docs/backends/lima.md index af013176..1092b486 100644 --- a/docs/content/docs/backends/lima.md +++ b/docs/content/docs/backends/lima.md @@ -61,7 +61,7 @@ Set the variables in the VM's shell or in your project's scripts, before the too ## Cleaning up -`devvm gc --backend lima` deletes all of devvm's Lima images, except on Linux hosts one whose disk VMs use, and the shared tools built for Lima that no VM has and that aren't current, and it leaves your VMs as they are ([cleaning up](../using/images.md#cleaning-up)). Lima also keeps a download cache of its own, which holds Ubuntu's cloud images that devvm's builds downloaded, and which your own Lima VMs share ([what devvm keeps](../using/space.md#lima)). +`devvm gc --backend lima` deletes all of devvm's Lima images, except on Linux hosts one whose disk VMs use, and the shared tools built for Lima that no VM has and that aren't current, and it leaves your VMs as they are ([cleaning up](../using/images.md#cleaning-up)). Lima also keeps a download cache of its own, which holds Ubuntu's cloud images that devvm's builds downloaded, and which your own Lima VMs share. `devvm gc --caches` deletes the cloud images that devvm downloads and that no image of devvm's names, after listing them and asking, and devvm never runs `limactl prune`, which empties the whole cache ([what devvm keeps](../using/space.md#lima)). ## Limits diff --git a/docs/content/docs/backends/smolvm.md b/docs/content/docs/backends/smolvm.md index b93cdd0a..5f369d51 100644 --- a/docs/content/docs/backends/smolvm.md +++ b/docs/content/docs/backends/smolvm.md @@ -32,4 +32,4 @@ When a build fails, devvm keeps its machine, stopped. To look inside, run `smolv ## Cleaning smolvm's caches -Each of devvm's smolvm images is a full pack, and `base`'s is about 450 MB. When you stop using smolvm, `devvm gc --backend smolvm` deletes all of devvm's packs and the shared tools built for smolvm that no VM has and that aren't current, except a pack that a VM was made from ([cleaning up](../using/images.md#cleaning-up)). smolvm also keeps caches of its own (`~/Library/Caches/smolvm` on macOS), which `smolvm machine prune` and `smolvm pack prune` clean. Before a build or a new VM, devvm checks the free space on the disk of its data folder, and on macOS also on that of your home folder, where smolvm keeps machines ([free space](../using/ports-size.md#free-space)). +Each of devvm's smolvm images is a full pack, and `base`'s is about 450 MB. When you stop using smolvm, `devvm gc --backend smolvm` deletes all of devvm's packs and the shared tools built for smolvm that no VM has and that aren't current, except a pack that a VM was made from ([cleaning up](../using/images.md#cleaning-up)). smolvm also keeps caches of its own (`~/Library/Caches/smolvm` on macOS), which also hold your own machines and packs. The largest part is the disk smolvm unpacks of each pack that a machine is made from, which stays after the pack is gone. `devvm gc --caches` frees those of devvm's packs that no VM of devvm's was made from, after listing them and asking ([what devvm keeps](../using/space.md#smolvm)). devvm never runs `smolvm pack prune` or `smolvm machine prune`, because they also clean what belongs to your own packs and machines. Before a build or a new VM, devvm checks the free space on the disk of its data folder, and on macOS also on that of your home folder, where smolvm keeps machines ([free space](../using/ports-size.md#free-space)). diff --git a/docs/content/docs/cli/devvm_gc.md b/docs/content/docs/cli/devvm_gc.md index 390689bf..3d80dfe9 100644 --- a/docs/content/docs/cli/devvm_gc.md +++ b/docs/content/docs/cli/devvm_gc.md @@ -7,7 +7,7 @@ Delete stale images and unused tool images ## Synopsis -Delete what devvm images lists as stale or unfinished, on every backend, with their records, the shared tool images it lists as unused, the copies of devvm's own files older versions wrote out, and the older versions of the mise devvm runs on this machine. With --backend, only that backend's images, its current ones too, and its unused tool images; without it, every backend's, whatever the default backend is. With --tools, also the current tool images no VM has, on every backend and C library, or only those of the TOOLs named (node, claude). With --exports, also the agents' history devvm export and devvm rm saved, the only copy of a deleted VM's, or only those older than --older-than (30d, 2w, 12h). With --orphans, also what devvm keeps for VMs deleted outside it, as devvm rm does, for each VM whose backend answers that it no longer has it. It lists them first, and in a terminal asks. VMs are never deleted; on Linux hosts, an image whose disk VMs use stays, and so does a smolvm or Docker image a VM was made from. +Delete what devvm images lists as stale or unfinished, on every backend, with their records, the shared tool images it lists as unused, the copies of devvm's own files older versions wrote out, and the older versions of the mise devvm runs on this machine. With --backend, only that backend's images, its current ones too, and its unused tool images; without it, every backend's, whatever the default backend is. With --tools, also the current tool images no VM has, on every backend and C library, or only those of the TOOLs named (node, claude). With --exports, also the agents' history devvm export and devvm rm saved, the only copy of a deleted VM's, or only those older than --older-than (30d, 2w, 12h). With --orphans, also what devvm keeps for VMs deleted outside it, as devvm rm does, for each VM whose backend answers that it no longer has it. With --caches, then what devvm's builds put in the backends' own caches that nothing of devvm's needs (Lima's Ubuntu downloads, smolvm's disks of devvm's packs, Docker volumes of devvm's no VM has), each backend listed and asked for apart, and only in a terminal. It lists them first, and in a terminal asks. VMs are never deleted; on Linux hosts, an image whose disk VMs use stays, and so does a smolvm or Docker image a VM was made from. ```text devvm gc [--tools [TOOL...]] [flags] @@ -16,6 +16,7 @@ devvm gc [--tools [TOOL...]] [flags] ## Options ```text + --caches then free devvm's share of the backends' own caches, asking for each backend; only in a terminal --exports also delete the saved exports of agents' history -h, --help help for gc --older-than AGE with --exports, only those older than AGE: 30d, 2w or 12h diff --git a/docs/content/docs/getting-started/install.md b/docs/content/docs/getting-started/install.md index 8363c188..ce62d2a8 100644 --- a/docs/content/docs/getting-started/install.md +++ b/docs/content/docs/getting-started/install.md @@ -112,7 +112,7 @@ Images whose inputs changed are built again the next time you use them. Existing 1. Delete your VMs: `devvm ls`, then `devvm rm` in each folder. For a `--clone` VM, this also removes the `devvm` git remote from the repo. 2. Delete the images: `devvm gc`, then `devvm images rm` with every name `devvm images` lists. Images built `--from` a container image need the same `--from`: `devvm --from node:24 images rm base`. 3. On Docker, delete the volumes and networks that devvm's label is still on, such as the shared tools' volume. `docker volume ls --filter label=devvm.data=$HOME/.local/share/devvm` and `docker network ls --filter label=devvm.data=$HOME/.local/share/devvm` list them, and `docker volume rm` and `docker network rm` delete them by name. -4. Free the backends' caches, if you don't use the backend yourself. Lima keeps Ubuntu's cloud images in `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux, and `limactl prune` deletes that whole cache. On macOS, smolvm keeps its caches and its machines in `~/Library/Caches/smolvm`, so delete that folder only once `smolvm machine ls` lists no machine you want to keep ([what devvm keeps](../using/space.md#smolvm)). +4. Free the backends' caches. In a terminal, `devvm gc --caches` frees devvm's share of them and of Docker's labelled volumes, after asking for each backend. If you don't use a backend yourself, you can also empty its cache: Lima keeps Ubuntu's cloud images in `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux, and `limactl prune` deletes that whole cache. On macOS, smolvm keeps its caches and its machines in `~/Library/Caches/smolvm`, so delete that folder only once `smolvm machine ls` lists no machine you want to keep ([what devvm keeps](../using/space.md#smolvm)). 5. Delete your saved secrets: `devvm secret rm NAME` for each one `devvm secret ls` lists. On macOS they're in the Keychain under the service `devvm`, and on Linux in `~/.config/devvm/secrets/`. 6. Remove devvm itself, with the command for the way you installed it: diff --git a/docs/content/docs/using/images.md b/docs/content/docs/using/images.md index a4126b91..9bc5a7f5 100644 --- a/docs/content/docs/using/images.md +++ b/docs/content/docs/using/images.md @@ -160,6 +160,7 @@ After the tables, devvm says on stderr how many images are stale or unfinished a - `devvm gc --tools` also deletes the current shared tools that no VM has, such as a toolchain you tried once, on every backend and C library. `devvm gc --tools node claude` deletes only those tools' builds, by the names images use, so `node` also covers pnpm and bun. A tool that a VM's state lists stays, including a stopped VM's, and so does one built in the last hour, because the VM it was built for may not list it yet. A VM whose image names a deleted tool builds it again when it needs it. - `devvm gc --exports` also deletes the [exports](coding-agents.md#history) of agents' history that `devvm export` and `devvm rm` saved, which are the only copy of a deleted VM's history, and `--older-than AGE` keeps those newer than `AGE`, such as `30d`, `2w` or `12h`. gc never deletes exports without `--exports`. - `devvm gc --orphans` also deletes what devvm keeps for VMs that their backend no longer has, such as one you deleted with `limactl delete` instead of `devvm rm`, and with it the hold their state has on their shared tools ([leftovers](space.md#leftovers-of-a-vm-deleted-outside-devvm)). +- `devvm gc --caches` then frees devvm's share of the backends' own caches, such as Lima's downloads of Ubuntu's cloud image, asking for each backend apart, and only in a terminal ([the backends' caches](space.md#the-backends-caches)). - `devvm gc --backend NAME` acts on that backend alone, for example once you stop using smolvm. It deletes all of that backend's images, the current ones too, and its shared tools that are `unused`, and it leaves every other backend's images and devvm's own files as they are. Without `--backend`, gc acts on every backend, whichever backend new VMs get by default. An image that a smolvm or Docker VM was made from stays, and devvm names the VMs that use it. - gc never deletes VMs. Without `--backend` it keeps current images, and without `--tools` the current shared tools. It always keeps every shared tool that any VM has, including a stopped VM's and that of a VM deleted outside devvm whose state is left, until `--orphans` deletes that state. - On Linux hosts, a stale image whose disk VMs are overlays of stays, and devvm says which VMs use it. diff --git a/docs/content/docs/using/space.md b/docs/content/docs/using/space.md index fcf7807a..9f7eff63 100644 --- a/docs/content/docs/using/space.md +++ b/docs/content/docs/using/space.md @@ -24,6 +24,8 @@ Sizes count each file's blocks once, as `du` does. On macOS a Lima VM's disk sha The second table lists the caches that belong to the backends, with the backend, what each cache holds, how many entries it has, its size and where it is. These are Lima's download cache, smolvm's caches on macOS and the Docker volumes with devvm's label that aren't one VM's own, such as the shared tools' volume. devvm's builds fill them, but Lima's and smolvm's caches can also hold your own downloads, so they aren't in the total. The sections below say what each one holds. +devvm never prunes these caches on its own. `devvm gc --caches` frees devvm's share of them, which is what devvm's builds put there and nothing of devvm's needs. For each backend in turn, it lists the entries it would delete with their sizes and asks, and without a terminal it refuses. With `--backend NAME`, it asks only about that backend's cache. + ## devvm's data folder devvm keeps its state in `~/.local/share/devvm`, or in `$XDG_DATA_HOME/devvm` when `XDG_DATA_HOME` is set. Only you can read it. Everything in it is devvm's own, and devvm makes all of it again when it's needed, except the exports, which are the only copy of a deleted VM's agent history. @@ -82,13 +84,13 @@ A VM can also be the other way around: the backend has it, with devvm's label, b The Lima backend's VMs and images are in devvm's Lima home, `~/.local/share/devvm/lima`. Each image is a stopped VM named `devvm-img-`, and each project VM is a clone of one. On macOS a clone's disk shares its image's blocks until the VM writes them, so `du` counts those blocks twice. On Linux hosts a VM's disk is an overlay of its image's. `devvm rm` deletes a VM, `devvm gc` and `devvm images rm` delete images, and `devvm gc --backend lima` deletes all of them. -Lima keeps a download cache of its own, `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux. When devvm builds base, Lima downloads Ubuntu's cloud image into that cache, which is 600 to 900 MB for each release, and on macOS it also keeps a copy converted to a raw disk, which takes about 2.4 GB more. The cache is Lima's and it isn't in devvm's Lima home, so your own Lima VMs' downloads share it. devvm never deletes anything in it. `limactl prune` deletes the whole cache, your own downloads included, and Lima downloads what a VM needs again the next time it makes one. +Lima keeps a download cache of its own, `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux. When devvm builds base, Lima downloads Ubuntu's cloud image into that cache, which is 600 to 900 MB for each release, and on macOS it also keeps a copy converted to a raw disk, which takes about 2.4 GB more. The cache is Lima's and it isn't in devvm's Lima home, so your own Lima VMs' downloads share it. devvm deletes something in it only when you run `devvm gc --caches`. Lima keeps each download in a folder named by the SHA-256 of its address, and gc frees only the folders of Ubuntu's cloud images at the address devvm downloads base from, for its Ubuntu release, that no image record of devvm's names and that haven't changed in the last hour. A cloud image that one of your own Lima VMs downloaded from that same address can be among them, and Lima downloads it again the next time it needs it. No VM needs its entry once it's made, because Lima copies the disk out of the cache. `limactl prune` deletes the whole cache, your own downloads included, so devvm never runs it. ## smolvm The smolvm backend keeps each image as a pack in `~/.local/share/devvm/smolvm/images/`, and base's is about 450 MB. A VM is a smolvm machine made from its image's pack. The machine reads the pack when its disk grows, so devvm doesn't delete an image that a VM was made from. `smolvm/vms/` holds what devvm sets on each VM. `devvm rm` deletes a VM, `devvm gc` and `devvm images rm` delete images, and `devvm gc --backend smolvm` deletes all of them but those a VM was made from. -On macOS, smolvm keeps every machine, devvm's and your own, in its own folders under `~/Library/Caches/smolvm`, and devvm marks its machines with a label. That folder also holds smolvm's caches, which grow with every pack that a machine is made from. smolvm unpacks a pack's disk once, which takes 1 to 3 GB, and keeps it for the next machine made from that pack. Those copies stay after devvm deletes the pack. Because the folder also holds the machines' own disks, never delete it by hand. [Cleaning smolvm's caches](../backends/smolvm.md#cleaning-smolvms-caches) says what smolvm's own commands clean. On Linux, smolvm's state and caches belong to devvm alone, in `~/.local/share/devvm/smolvm/state`. +On macOS, smolvm keeps every machine, devvm's and your own, in its own folders under `~/Library/Caches/smolvm`, and devvm marks its machines with a label. That folder also holds smolvm's caches, which grow with every pack that a machine is made from. smolvm unpacks a pack's disk once, which takes 1 to 3 GB, and keeps it for the next machine made from that pack. Those copies stay after devvm deletes the pack. Each one's name holds the SHA-256 of its pack, and devvm records the SHA-256 of every pack it makes, so `devvm gc --caches` frees the copies of devvm's packs that no machine of devvm's was made from and that haven't changed in the last hour. A copy whose pack is gone and isn't in that record can't be tied to devvm, so it stays, as do the copies of your own packs and smolvm's other caches. Because the folder also holds the machines' own disks, never delete it by hand. [Cleaning smolvm's caches](../backends/smolvm.md#cleaning-smolvms-caches) says what smolvm's own commands clean. On Linux, smolvm's state and caches belong to devvm alone, in `~/.local/share/devvm/smolvm/state`. ## Docker @@ -96,6 +98,8 @@ The Docker backend keeps its VMs and images in Docker's engine. Each VM is a con Docker also keeps the container image that base starts from, which it pulls as it would any image you pull. devvm doesn't delete it, because it isn't labelled and you may use it. +`devvm gc --caches` deletes the volumes with devvm's label that no VM of devvm's has, such as the home volume that `docker rm` left of a VM, after listing them and asking. It keeps the shared tools' volume, every VM's own volumes, and the volumes of a VM that devvm has state for, which includes a VM that is still being made. It never prunes and never touches what doesn't have devvm's label. + `~/.local/share/devvm/docker` holds what devvm sets on each VM, which tools it unpacked into the tools volume, the sockets that network policy's relays reach the proxy through, the files of a build's proxy, which a failed build keeps together with its proxy's logs, and on macOS the copy of devvm's Linux build that a release fetches for network policy's relays. ## Outside devvm's folders diff --git a/internal/backend/caches.go b/internal/backend/caches.go new file mode 100644 index 00000000..4bfca085 --- /dev/null +++ b/internal/backend/caches.go @@ -0,0 +1,25 @@ +package backend + +import "context" + +// CacheEntry is one entry of a backend's own cache that devvm's builds +// put there: what devvm gc --caches frees. +type CacheEntry struct { + What string // what it is, as gc lists it + Path string // the file or folder, "" for one in the backend's engine + Name string // its name in the engine (a Docker volume's) + Size int64 +} + +// CacheCleaner is a backend whose own caches devvm's builds fill, and +// which can tell devvm's share of them apart: entries only devvm's +// builds make, that no image or VM of devvm's needs. Never the user's +// own: a backend that can't tell an entry apart leaves it. +type CacheCleaner interface { + // DevvmCache lists devvm's share of the backend's caches. It changes + // nothing. + DevvmCache(ctx context.Context) ([]CacheEntry, error) + // DeleteCache deletes entries DevvmCache listed, each checked again + // first: one that isn't devvm's any more stays. + DeleteCache(ctx context.Context, entries []CacheEntry) error +} diff --git a/internal/backend/docker/caches.go b/internal/backend/docker/caches.go new file mode 100644 index 00000000..06edc437 --- /dev/null +++ b/internal/backend/docker/caches.go @@ -0,0 +1,92 @@ +package docker + +import ( + "context" + "os" + "slices" + "strings" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/paths" +) + +var _ backend.CacheCleaner = (*Docker)(nil) + +// DevvmCache lists devvm's volumes in the engine that no VM of devvm's +// has: those with its label that aren't a listed VM's own (its home, a +// --clone VM's clone, the docker layer's engine files) and aren't the +// shared tools' volume, such as the home of a VM docker rm deleted. +// Anything without devvm's label is never one, and Docker is never +// pruned. +func (d *Docker) DevvmCache(ctx context.Context) ([]backend.CacheEntry, error) { + free, err := freeVolumes(ctx, d) + if err != nil { + return nil, err + } + sizes, err := d.volumeSizes(ctx) + if err != nil { + return nil, err + } + out := make([]backend.CacheEntry, 0, len(free)) + for _, v := range free { + out = append(out, backend.CacheEntry{What: "volume " + v, Name: v, Size: sizes[v]}) + } + return out, nil +} + +// DeleteCache deletes volumes DevvmCache listed that still are devvm's +// and no VM's. +func (d *Docker) DeleteCache(ctx context.Context, entries []backend.CacheEntry) error { + free, err := freeVolumes(ctx, d) + if err != nil { + return err + } + for _, e := range entries { + if e.Name != "" && slices.Contains(free, e.Name) { + if err := d.removeVolume(ctx, e.Name); err != nil { + return err + } + } + } + return nil +} + +// freeVolumes are devvm's labelled volumes that no listed VM has and +// that aren't the shared tools'. +func freeVolumes(ctx context.Context, d *Docker) ([]string, error) { + vms, err := d.List(ctx) + if err != nil { + return nil, err + } + owned := map[string]bool{d.toolsVolume(): true} + for _, in := range vms { + for _, v := range append([]string{homeVolume(in.Name), cloneVolume(in.Name)}, engineVolumes(in.Name)...) { + owned[v] = true + } + } + ours, err := d.volumes(ctx) + if err != nil { + return nil, err + } + var out []string + for _, v := range ours { + if !owned[v] && !hasState(d.Dirs, v) { + out = append(out, v) + } + } + return out, nil +} + +// hasState reports whether a volume is one of a VM's that devvm has +// state for: a VM being made has its volumes before its container, and +// one whose container is gone is gc --orphans's. +func hasState(dirs paths.Dirs, volume string) bool { + for _, suffix := range []string{"-home", "-clone", "-docker", "-containerd"} { + if vm, ok := strings.CutSuffix(volume, suffix); ok { + if _, err := os.Stat(dirs.VMState(vm)); err == nil { + return true + } + } + } + return false +} diff --git a/internal/backend/docker/docker_test.go b/internal/backend/docker/docker_test.go index f16357fd..9b5db219 100644 --- a/internal/backend/docker/docker_test.go +++ b/internal/backend/docker/docker_test.go @@ -893,6 +893,45 @@ func TestUsage(t *testing.T) { } } +// devvm's share of Docker: its labelled volumes no VM has, never a VM's +// own, the tools', one of a VM being made (it has state), nor anyone +// else's. +func TestDevvmCacheVolumes(t *testing.T) { + s := newSandbox(t) + s.createVM(t, backend.VMSpec{Project: "/p/web"}) + vols := filepath.Join(s.stub, "docker", "volumes") + for _, v := range []string{"devvm-gone-12345612345612-home", "devvm-new-12345612345612-home", "theirs", s.toolsVolume()} { + if err := os.MkdirAll(filepath.Join(vols, v), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(vols, v, "labels"), []byte(LabelKey+"="+s.Data+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + s.touch(t, "docker-foreign-theirs") + if err := os.MkdirAll(s.Dirs.VMs(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(s.Dirs.VMState("devvm-new-12345612345612"), []byte("backend=docker\n"), 0o600); err != nil { + t.Fatal(err) + } + got, err := s.DevvmCache(t.Context()) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Name != "devvm-gone-12345612345612-home" { + t.Fatalf("DevvmCache = %+v", got) + } + if err := s.DeleteCache(t.Context(), append(got, backend.CacheEntry{Name: homeVolume(vm)})); err != nil { + t.Fatal(err) + } + for v, want := range map[string]bool{"devvm-gone-12345612345612-home": false, homeVolume(vm): true, "theirs": true, s.toolsVolume(): true, "devvm-new-12345612345612-home": true} { + if _, err := os.Stat(filepath.Join(vols, v)); (err == nil) != want { + t.Errorf("%s: there %v, want %v", v, err == nil, want) + } + } +} + // Commands in a VM run as its user with a login's environment; a shell // gets a terminal when devvm has one; without ssh, through docker exec. func TestExecAndShell(t *testing.T) { diff --git a/internal/backend/lima/caches.go b/internal/backend/lima/caches.go new file mode 100644 index 00000000..ac83de98 --- /dev/null +++ b/internal/backend/lima/caches.go @@ -0,0 +1,149 @@ +package lima + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/platform" + "github.com/w3cj/devvm/internal/state" + "github.com/w3cj/devvm/internal/ubuntu" +) + +var _ backend.CacheCleaner = (*Lima)(nil) + +// cacheRecent is how long an entry of Lima's cache is left alone after it +// changed: a build may be downloading into it. +const cacheRecent = time.Hour + +// DevvmCache lists the entries of Lima's download cache that hold one of +// Ubuntu's cloud images as devvm downloads them for base (its series, +// from its address, a dated release) that no image record of devvm's +// names, so no build of devvm's needs. Lima keeps each download in +// by-url-sha256/, with the address in url: +// an entry whose url doesn't hash to its name is never one, and nor is +// anything else in the cache (your own downloads). Lima copies a VM's +// disk out of the cache when it makes the VM, so no VM needs an entry. +func (l *Lima) DevvmCache(context.Context) ([]backend.CacheEntry, error) { + dir, err := downloadCache() + if err != nil { + return nil, err + } + entries, err := os.ReadDir(dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } else if err != nil { + return nil, err + } + c := l.cache() + keep, err := c.recordedURLs() + if err != nil { + return nil, err + } + var out []backend.CacheEntry + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if url, ok := c.devvmEntry(p, keep); ok { + n, _ := platform.DiskUsage(p) + out = append(out, backend.CacheEntry{What: "Ubuntu's cloud image " + ubuntu.ReleaseDate(url), Path: p, Size: n}) + } + } + return out, nil +} + +// DeleteCache deletes entries DevvmCache listed, each one checked again. +func (l *Lima) DeleteCache(_ context.Context, entries []backend.CacheEntry) error { + dir, err := downloadCache() + if err != nil { + return err + } + c := l.cache() + keep, err := c.recordedURLs() + if err != nil { + return err + } + for _, e := range entries { + if filepath.Dir(e.Path) != dir { + continue + } + if _, ok := c.devvmEntry(e.Path, keep); ok { + if err := os.RemoveAll(e.Path); err != nil { + return err + } + } + } + return nil +} + +// limaCache tells devvm's entries in Lima's download cache apart. +type limaCache struct { + dirs paths.Dirs + getenv func(string) string +} + +func (l *Lima) cache() limaCache { return limaCache{dirs: l.Dirs, getenv: l.Getenv} } + +// cloudURL is the address devvm downloads Ubuntu's cloud image from, for +// any dated release. +func (l limaCache) cloudURL() *regexp.Regexp { + base := ubuntu.DefaultURL + if v := l.getenv(ubuntu.URLEnv); v != "" { + base = v + } + return regexp.MustCompile(`^` + regexp.QuoteMeta(strings.TrimRight(base, "/")) + + `/release-[0-9]{8}/ubuntu-` + regexp.QuoteMeta(ubuntu.Version) + `-server-cloudimg-(arm64|amd64)\.img$`) +} + +// devvmEntry reports whether a cache entry is devvm's to free, with its +// address: a folder, unchanged for an hour, whose url hashes to its name +// and is devvm's address for a cloud image no record keeps. +func (l limaCache) devvmEntry(path string, keep map[string]bool) (string, bool) { + fi, err := os.Lstat(path) + if err != nil || !fi.IsDir() || time.Since(fi.ModTime()) < cacheRecent { + return "", false + } + data, err := os.ReadFile(filepath.Join(path, "url")) //nolint:gosec // Lima's cache, read only + if err != nil { + return "", false + } + url := strings.TrimSpace(string(data)) + sum := sha256.Sum256([]byte(url)) + if hex.EncodeToString(sum[:]) != filepath.Base(path) || !l.cloudURL().MatchString(url) || keep[url] { + return "", false + } + return url, true +} + +// recordedURLs are the cloud images devvm's image records name: a base's +// record keeps its image's address and digest. +func (l limaCache) recordedURLs() (map[string]bool, error) { + entries, err := os.ReadDir(l.dirs.Images()) + if errors.Is(err, fs.ErrNotExist) { + return map[string]bool{}, nil + } else if err != nil { + return nil, err + } + keep := map[string]bool{} + for _, e := range entries { + if !keyPattern.MatchString(e.Name()) { + continue + } + rec, err := state.ReadImage(l.dirs, e.Name()) + if err != nil { + continue + } + if f := strings.Fields(rec.Digest); len(f) > 0 { + keep[f[0]] = true + } + } + return keep, nil +} diff --git a/internal/backend/lima/caches_test.go b/internal/backend/lima/caches_test.go new file mode 100644 index 00000000..52c6509b --- /dev/null +++ b/internal/backend/lima/caches_test.go @@ -0,0 +1,88 @@ +package lima + +import ( + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/state" + "github.com/w3cj/devvm/internal/ubuntu" +) + +// devvm's share of Lima's download cache: Ubuntu's cloud images from +// devvm's address that no image record names, unchanged for an hour. Never +// another download (yours), one a record names, one being written, or an +// entry whose url doesn't hash to its name. +func TestDevvmCache(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + dir, err := downloadCache() + if err != nil { + t.Fatal(err) + } + d := paths.Dirs{Data: filepath.Join(home, "data"), Lima: filepath.Join(home, "lima")} + l := &Lima{Dirs: d, Getenv: func(string) string { return "" }} + cloud := func(date string) string { + return ubuntu.DefaultURL + "/release-" + date + "/ubuntu-" + ubuntu.Version + "-server-cloudimg-arm64.img" + } + old := time.Now().Add(-2 * time.Hour) + entry := func(url, name string, recent bool) string { + if name == "" { + sum := sha256.Sum256([]byte(url)) + name = hex.EncodeToString(sum[:]) + } + p := filepath.Join(dir, name) + if err := os.MkdirAll(p, 0o700); err != nil { + t.Fatal(err) + } + for f, data := range map[string]string{"url": url, "data": "x"} { + if err := os.WriteFile(filepath.Join(p, f), []byte(data), 0o600); err != nil { + t.Fatal(err) + } + } + if !recent { + if err := os.Chtimes(p, old, old); err != nil { + t.Fatal(err) + } + } + return p + } + stale := entry(cloud("20260101"), "", false) + kept := entry(cloud("20260201"), "", false) + entry(cloud("20260301"), "", true) // a build downloading it + entry("https://example.com/yours.img", "", false) // your own download + entry(cloud("20260401"), "0123456789abcdef", false) // not Lima's layout + entry(ubuntu.DefaultURL+"/release-20260101/other.img", "", false) // not a cloud image of devvm's + if err := state.WriteImage(d, "0123456789ab", state.Image{Name: "base", Digest: cloud("20260201") + " sha256:" + hex.EncodeToString(make([]byte, 32))}); err != nil { + t.Fatal(err) + } + got, err := l.DevvmCache(t.Context()) + if err != nil { + t.Fatal(err) + } + var paths []string + for _, e := range got { + paths = append(paths, e.Path) + } + if !slices.Equal(paths, []string{stale}) { + t.Fatalf("DevvmCache = %v, want only %s", paths, stale) + } + if err := l.DeleteCache(t.Context(), got); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(stale); !os.IsNotExist(err) { + t.Errorf("the stale entry stayed: %v", err) + } + if _, err := os.Stat(kept); err != nil { + t.Errorf("the recorded entry went: %v", err) + } + if entries, _ := os.ReadDir(dir); len(entries) != 5 { + t.Errorf("left %d entries, want 5", len(entries)) + } +} diff --git a/internal/backend/smolvm/build.go b/internal/backend/smolvm/build.go index 3ebda4af..4947182c 100644 --- a/internal/backend/smolvm/build.go +++ b/internal/backend/smolvm/build.go @@ -264,7 +264,10 @@ func (s *Smolvm) packInto(ctx context.Context, vm, key string) error { _ = os.RemoveAll(tmp) return backend.Logged(msg.PackFailed(vm)) } - return os.Rename(tmp, dir) + if err := os.Rename(tmp, dir); err != nil { + return err + } + return packCache{s}.record(key) } // unfinished deletes an image's build machine that didn't finish: on an diff --git a/internal/backend/smolvm/caches.go b/internal/backend/smolvm/caches.go new file mode 100644 index 00000000..7271023c --- /dev/null +++ b/internal/backend/smolvm/caches.go @@ -0,0 +1,171 @@ +package smolvm + +import ( + "bufio" + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/image" + "github.com/w3cj/devvm/internal/platform" +) + +var _ backend.CacheCleaner = (*Smolvm)(nil) + +// seedName is a pack's disk in smolvm's cache: v2--auto, which smolvm unpacks the first time a +// machine is made from the pack and keeps for the next. +var seedName = regexp.MustCompile(`^v2-([0-9a-f]{64})-auto$`) + +// cacheRecent is how long a pack's disk is left alone after it changed: +// a machine may be being made from it. +const cacheRecent = time.Hour + +// packCache ties the disks in smolvm's cache to devvm's packs. +type packCache struct{ *Smolvm } + +// packsFile lists every pack devvm made, " " per line, so a +// pack's disk in smolvm's cache can be tied to devvm's pack after the +// pack is deleted. +func (s packCache) packsFile() string { return filepath.Join(s.Dirs.Smolvm(), "packs") } + +// record adds a new pack to packsFile. +func (s packCache) record(key string) error { + sum, err := image.SHA256File(s.packFile(key)) + if err != nil { + return err + } + f, err := os.OpenFile(s.packsFile(), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) + if err != nil { + return err + } + _, err = f.WriteString(key + " " + sum + "\n") + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +// packs are devvm's packs by SHA-256: each packsFile names, and each +// pack in its images folder (one made before packsFile was kept is +// hashed now). +func (s packCache) packs() (map[string]string, error) { + out := map[string]string{} + f, err := os.Open(s.packsFile()) + if err == nil { + sc := bufio.NewScanner(f) + for sc.Scan() { + if key, sum, ok := strings.Cut(sc.Text(), " "); ok && keyPattern.MatchString(key) { + out[sum] = key + } + } + _ = f.Close() + } else if !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + known := map[string]bool{} + for _, k := range out { + known[k] = true + } + entries, err := os.ReadDir(filepath.Join(s.Dirs.Smolvm(), "images")) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + for _, e := range entries { + if !keyPattern.MatchString(e.Name()) || known[e.Name()] { + continue + } + if sum, err := image.SHA256File(s.packFile(e.Name())); err == nil { + out[sum] = e.Name() + } + } + return out, nil +} + +// DevvmCache lists the disks smolvm unpacked of devvm's packs (on macOS, +// in smolvm's cache) that no machine of devvm's was made from: a disk +// whose name is the SHA-256 of one of devvm's packs, unchanged for an +// hour. Any other disk there may be of your own packs and is never one; +// so are the folders of machines beside them, and smolvm's other caches. +// On Linux smolvm's state, caches included, is devvm's own folder. +func (s *Smolvm) DevvmCache(ctx context.Context) ([]backend.CacheEntry, error) { + if s.OS != "darwin" { + return nil, nil + } + seeds, err := packCache{s}.freeSeeds(ctx) + if err != nil { + return nil, err + } + out := make([]backend.CacheEntry, 0, len(seeds)) + for p, key := range seeds { + n, _ := platform.DiskUsage(p) + out = append(out, backend.CacheEntry{What: "the disk of image " + key, Path: p, Size: n}) + } + return out, nil +} + +// DeleteCache deletes pack disks DevvmCache listed that are still free. +func (s *Smolvm) DeleteCache(ctx context.Context, entries []backend.CacheEntry) error { + seeds, err := packCache{s}.freeSeeds(ctx) + if err != nil { + return err + } + for _, e := range entries { + if _, ok := seeds[e.Path]; !ok { + continue + } + if err := os.RemoveAll(e.Path); err != nil { + return err + } + if err := os.Remove(e.Path + ".lock"); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + } + return nil +} + +// freeSeeds are the pack disks in smolvm's cache that are devvm's and no +// machine of devvm's was made from, by path, each with its image's key. +func (s packCache) freeSeeds(ctx context.Context) (map[string]string, error) { + base, err := os.UserCacheDir() + if err != nil { + return nil, err + } + dir := filepath.Join(base, "smolvm", "vms", packSeeds) + entries, err := os.ReadDir(dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } else if err != nil { + return nil, err + } + packs, err := s.packs() + if err != nil { + return nil, err + } + out := map[string]string{} + for _, e := range entries { + m := seedName.FindStringSubmatch(e.Name()) + if m == nil || !e.IsDir() { + continue + } + key, ours := packs[m[1]] + fi, err := e.Info() + if !ours || err != nil || time.Since(fi.ModTime()) < cacheRecent { + continue + } + users, err := s.imageUsers(ctx, key) + if err != nil { + return nil, err + } + if len(users) == 0 { + out[filepath.Join(dir, e.Name())] = key + } + } + return out, nil +} diff --git a/internal/backend/smolvm/caches_test.go b/internal/backend/smolvm/caches_test.go new file mode 100644 index 00000000..3cfd3453 --- /dev/null +++ b/internal/backend/smolvm/caches_test.go @@ -0,0 +1,125 @@ +package smolvm + +import ( + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/w3cj/devvm/internal/image" +) + +// devvm's share of smolvm's cache: the disks smolvm unpacked of devvm's +// packs (a pack there, or one packsFile records), unchanged for an hour, +// that no machine of devvm's was made from. Never a disk of anyone +// else's pack, a recent one, a machine's folder or another cache. +func TestDevvmCache(t *testing.T) { + s := newSandbox(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + base, err := os.UserCacheDir() + if err != nil { + t.Fatal(err) + } + seeds := filepath.Join(base, "smolvm", "vms", packSeeds) + // Packs: a (no machine), b (a VM was made from it), and c, deleted + // but recorded. + for _, k := range []string{"aaaaaaaaaaaa", "bbbbbbbbbbbb"} { + s.image(t, k) + if err := os.WriteFile(s.packFile(k), []byte(k), 0o600); err != nil { + t.Fatal(err) + } + } + sum := func(k string) string { + v, err := image.SHA256File(s.packFile(k)) + if err != nil { + t.Fatal(err) + } + return v + } + sa, sb, sc := sum("aaaaaaaaaaaa"), sum("bbbbbbbbbbbb"), "cc"+sum("aaaaaaaaaaaa")[2:] + if err := os.WriteFile(packCache{s.Smolvm}.packsFile(), []byte("cccccccccccc "+sc+"\n"), 0o600); err != nil { + t.Fatal(err) + } + s.machine(t, "devvm-web-12345612345612", "running 4 8192 100 true") + if err := s.writeRecord("devvm-web-12345612345612", record{Image: "bbbbbbbbbbbb"}); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-2 * time.Hour) + seed := func(name string, recent bool) string { + p := filepath.Join(seeds, name) + if err := os.MkdirAll(p, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(p, "storage.raw"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p+".lock", nil, 0o600); err != nil { + t.Fatal(err) + } + if !recent { + if err := os.Chtimes(p, old, old); err != nil { + t.Fatal(err) + } + } + return p + } + free, deleted := seed("v2-"+sa+"-auto", false), seed("v2-"+sc+"-auto", false) + seed("v2-"+sb+"-auto", false) // a VM's + seed("v2-"+"dd"+sa[2:]+"-auto", false) // someone else's pack + seed("v2-"+sa[:62]+"ee-auto", true) // not ours + if err := os.MkdirAll(filepath.Join(base, "smolvm", "vms", "3d40063296df941a"), 0o700); err != nil { // a machine's + t.Fatal(err) + } + got, err := s.DevvmCache(t.Context()) + if err != nil { + t.Fatal(err) + } + var ps []string + for _, e := range got { + ps = append(ps, e.Path) + } + slices.Sort(ps) + want := []string{free, deleted} + slices.Sort(want) + if !slices.Equal(ps, want) { + t.Fatalf("DevvmCache = %v, want %v", ps, want) + } + if err := s.DeleteCache(t.Context(), got); err != nil { + t.Fatal(err) + } + for _, p := range want { + if _, err := os.Stat(p); !os.IsNotExist(err) { + t.Errorf("%s stayed", p) + } + if _, err := os.Stat(p + ".lock"); !os.IsNotExist(err) { + t.Errorf("%s.lock stayed", p) + } + } + if entries, _ := os.ReadDir(seeds); len(entries) != 6 { // 3 disks and their locks + t.Errorf("left %d entries, want 6", len(entries)) + } + // On Linux smolvm's caches are in devvm's own folder: none listed. + s.OS = "linux" + if got, _ := s.DevvmCache(t.Context()); len(got) != 0 { + t.Errorf("Linux: %v", got) + } +} + +// Each new pack is recorded with its SHA-256. +func TestPackRecorded(t *testing.T) { + s := newSandbox(t) + s.image(t, "aaaaaaaaaaaa") + if err := (packCache{s.Smolvm}).record("aaaaaaaaaaaa"); err != nil { + t.Fatal(err) + } + packs, err := packCache{s.Smolvm}.packs() + if err != nil { + t.Fatal(err) + } + if len(packs) != 1 { + t.Errorf("packs = %v", packs) + } +} diff --git a/internal/cli/gc.go b/internal/cli/gc.go index 9def5444..d09d5921 100644 --- a/internal/cli/gc.go +++ b/internal/cli/gc.go @@ -38,6 +38,9 @@ type gcOpts struct { // orphans is --orphans: also what devvm keeps for VMs their backend // no longer has. orphans bool + // caches is --caches: then devvm's share of the backends' own + // caches, each backend asked for apart, only in a terminal. + caches bool } // newGCCmd is devvm gc. @@ -55,7 +58,10 @@ func newGCCmd(u *ui.UI, g *globals) *cobra.Command { "TOOLs named (node, claude). With --exports, also the agents' history devvm export and " + "devvm rm saved, the only copy of a deleted VM's, or only those older than --older-than " + "(30d, 2w, 12h). With --orphans, also what devvm keeps for VMs deleted outside it, as devvm rm " + - "does, for each VM whose backend answers that it no longer has it. It lists them first, and in a terminal asks. VMs are never " + + "does, for each VM whose backend answers that it no longer has it. With --caches, then " + + "what devvm's builds put in the backends' own caches that nothing of devvm's needs (Lima's " + + "Ubuntu downloads, smolvm's disks of devvm's packs, Docker volumes of devvm's no VM has), " + + "each backend listed and asked for apart, and only in a terminal. It lists them first, and in a terminal asks. VMs are never " + "deleted; on Linux hosts, an image whose disk VMs use stays, and so does a smolvm or " + "Docker image a VM was made from.", Args: func(_ *cobra.Command, args []string) error { return o.checkArgs(args) }, @@ -69,6 +75,7 @@ func newGCCmd(u *ui.UI, g *globals) *cobra.Command { c.Flags().BoolVar(&o.exports, "exports", false, "also delete the saved exports of agents' history") c.Flags().StringVar(&o.olderThan, "older-than", "", "with --exports, only those older than `AGE`: 30d, 2w or 12h") c.Flags().BoolVar(&o.orphans, "orphans", false, "also delete what devvm keeps for VMs their backend no longer has, as devvm rm does") + c.Flags().BoolVar(&o.caches, "caches", false, "then free devvm's share of the backends' own caches, asking for each backend; only in a terminal") return c } @@ -125,6 +132,21 @@ func gc(ctx context.Context, u *ui.UI, g *globals, o gcOpts) error { return err } defer unlock() + if o.caches && !u.StdinIsTerminal() { + return msg.GCCachesNeedTerminal() + } + if err := gcRun(ctx, u, b, o); err != nil { + return err + } + if o.caches { + return gcCaches(ctx, u, b, o.only) + } + return nil +} + +// gcRun is gc's run but the backends' caches: it lists what it deletes, +// asks in a terminal, and deletes it. +func gcRun(ctx context.Context, u *ui.UI, b *build.Env, o gcOpts) error { p, err := planGC(ctx, u, b, o) if err != nil { return err diff --git a/internal/cli/gc_caches.go b/internal/cli/gc_caches.go new file mode 100644 index 00000000..2fb094c1 --- /dev/null +++ b/internal/cli/gc_caches.go @@ -0,0 +1,62 @@ +package cli + +import ( + "context" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/backend/registry" + "github.com/w3cj/devvm/internal/build" + "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/ui" +) + +// gcCaches frees devvm's share of each backend's own caches (gc +// --caches): what each backend can tell only devvm's builds put there and +// no image or VM of devvm's needs. It lists each backend's apart and asks +// for each; it never runs a backend's own prune, which reaches the user's +// own entries too. With only, that backend alone. +func gcCaches(ctx context.Context, u *ui.UI, b *build.Env, only string) error { + reg, err := registry.New(b.Dirs, b.Assets, u) + if err != nil { + return err + } + for _, be := range reg.All() { + c, ok := be.(backend.CacheCleaner) + if !ok || (only != "" && be.Name() != only) { + continue + } + entries, ok := cacheEntries(ctx, be, c) + if !ok || len(entries) == 0 { + continue + } + var size int64 + for _, e := range entries { + size += e.Size + } + u.Say(msg.GCCache(be.Name(), len(entries), humanSize(size))) + for _, e := range entries { + u.Say(msg.GCCacheEntry(humanSize(e.Size), e.What)) + } + if !u.Confirm(msg.GCCacheConfirm(be.Name())) { + u.Info(msg.NothingDeleted()) + continue + } + if err := c.DeleteCache(ctx, entries); err != nil { + return err + } + u.Info(msg.DeletedCache(be.Name(), len(entries))) + } + return nil +} + +// cacheEntries is devvm's share of a backend's caches; ok is false when +// the backend can't be asked. +func cacheEntries(ctx context.Context, be backend.Backend, c backend.CacheCleaner) ([]backend.CacheEntry, bool) { + ctx, cancel := context.WithTimeout(ctx, spaceTimeout) + defer cancel() + if be.Check(ctx) != nil { + return nil, false + } + entries, err := c.DevvmCache(ctx) + return entries, err == nil +} diff --git a/internal/msg/docs.go b/internal/msg/docs.go index fdc32886..7f7a610c 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -106,6 +106,7 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "layer_exists": "using/customizing#your-own-layers", "images_stale_note": "using/images#cleaning-up", "images_unused": "using/images#cleaning-up", + "gc_caches_need_terminal": "using/space#the-backends-caches", "gc_orphans_unknown": "using/space#leftovers-of-a-vm-deleted-outside-devvm", "gc_orphan_elsewhere": "using/space#leftovers-of-a-vm-deleted-outside-devvm", "gc_orphan_recent": "using/space#leftovers-of-a-vm-deleted-outside-devvm", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 7c20e02f..40652f94 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -504,6 +504,11 @@ func DeletedAssets(count int) M { return M{id: "deleted_assets", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}}} } +// DeletedCache is [deleted_cache]: "deleted {{.count}} entries of {{.backend}}'s cache" +func DeletedCache(backend string, count int) M { + return M{id: "deleted_cache", plural: true, count: count, vals: []val{{"backend", backend}, {"count", strconv.Itoa(count)}}} +} + // DeletedExports is [deleted_exports]: "deleted {{.count}} exports" func DeletedExports(count int) M { return M{id: "deleted_exports", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}}} @@ -1049,6 +1054,26 @@ func GCBadAge(age string) M { return M{id: "gc_bad_age", vals: []val{{"age", age}}} } +// GCCache is [gc_cache]: "{{.count}} entries of {{.backend}}'s own cache that devvm's builds put there and nothing of devvm's needs ({{.size}}):" +func GCCache(backend string, count int, size string) M { + return M{id: "gc_cache", plural: true, count: count, vals: []val{{"backend", backend}, {"count", strconv.Itoa(count)}, {"size", size}}} +} + +// GCCacheConfirm is [gc_cache_confirm]: "Your own entries in {{.backend}}'s cache stay. Delete these?" +func GCCacheConfirm(backend string) M { + return M{id: "gc_cache_confirm", vals: []val{{"backend", backend}}} +} + +// GCCacheEntry is [gc_cache_entry]: " {{.what}} ({{.size}})" +func GCCacheEntry(size string, what string) M { + return M{id: "gc_cache_entry", vals: []val{{"size", size}, {"what", what}}} +} + +// GCCachesNeedTerminal is [gc_caches_need_terminal]: "--caches asks before it frees each backend's cache, so it runs only in a terminal. Run devvm gc --caches in one." +func GCCachesNeedTerminal() M { + return M{id: "gc_caches_need_terminal"} +} + // GCConfirm is [gc_confirm]: "Your VMs stay as they are. Delete these?" func GCConfirm() M { return M{id: "gc_confirm"} @@ -2756,6 +2781,7 @@ var specs = map[string]spec{ "delete_parent_vm": {fields: []string{"dir", "vm"}}, "deleted": {fields: []string{"vm"}}, "deleted_assets": {plural: true, fields: []string{"count"}}, + "deleted_cache": {plural: true, fields: []string{"backend", "count"}}, "deleted_exports": {plural: true, fields: []string{"count"}}, "deleted_image": {fields: []string{"image", "key"}}, "deleted_mise": {plural: true, fields: []string{"count"}}, @@ -2865,6 +2891,10 @@ var specs = map[string]spec{ "from_unreachable": {fields: []string{"from", "host"}}, "gc_assets": {plural: true, fields: []string{"count"}}, "gc_bad_age": {fields: []string{"age"}}, + "gc_cache": {plural: true, fields: []string{"backend", "count", "size"}}, + "gc_cache_confirm": {fields: []string{"backend"}}, + "gc_cache_entry": {fields: []string{"size", "what"}}, + "gc_caches_need_terminal": {}, "gc_confirm": {}, "gc_export": {fields: []string{"date", "size", "vm"}}, "gc_exports": {plural: true, fields: []string{"count", "size"}}, diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index 6c472df3..f0eca5d9 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -25,9 +25,9 @@ func devvm() rules { // its methods do, as vm's Launch, Lifecycle, Settings and Net. maxMethods: 24, largeTypes: map[string]large{ - "internal/backend/lima.Lima": {72, "a backend: backend.Backend's 28 methods, KeyFiles, DiskDirs, Floors, Usage, Location, Forget, Strays and Lima's own"}, - "internal/backend/smolvm.Smolvm": {77, "a backend: backend.Backend's 28 methods, DiskDirs, Floors, Usage, Location, Forget, Strays and smolvm's own"}, - "internal/backend/docker.Docker": {84, "a backend: backend.Backend's 28 methods, the optional ones it implements and Docker's own, its ssh, ports, agent and docker layer emulations among them; its docker commands are its client's"}, + "internal/backend/lima.Lima": {75, "a backend: backend.Backend's 28 methods, KeyFiles, DiskDirs, Floors, Usage, Location, Forget, Strays, DevvmCache, DeleteCache and Lima's own"}, + "internal/backend/smolvm.Smolvm": {79, "a backend: backend.Backend's 28 methods, DiskDirs, Floors, Usage, Location, Forget, Strays, DevvmCache, DeleteCache and smolvm's own"}, + "internal/backend/docker.Docker": {86, "a backend: backend.Backend's 28 methods, the optional ones it implements and Docker's own, its ssh, ports, agent and docker layer emulations among them; its docker commands are its client's"}, "internal/backend/backendtest.Fake": {35, "backend.Backend's 28 methods and what tests ask of it"}, "internal/paths.Dirs": {38, "one method per folder or file devvm uses: a list"}, "internal/ui.UI": {41, "the one terminal: messages, prompts, status line, run log, cleanups, signals"}, diff --git a/locales/en.toml b/locales/en.toml index e45810f8..40962c8b 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -760,6 +760,23 @@ other = "{{.vm}} was made in another Lima home, HOME or Docker engine than this [gc_orphan_recent] other = "{{.vm}}'s state changed in the last hour, so it stays in case the VM is still being made." +[gc_caches_need_terminal] +other = "--caches asks before it frees each backend's cache, so it runs only in a terminal. Run devvm gc --caches in one." + +[gc_cache] +one = "{{.count}} entry of {{.backend}}'s own cache that devvm's builds put there and nothing of devvm's needs ({{.size}}):" +other = "{{.count}} entries of {{.backend}}'s own cache that devvm's builds put there and nothing of devvm's needs ({{.size}}):" + +[gc_cache_entry] +other = " {{.what}} ({{.size}})" + +[gc_cache_confirm] +other = "Your own entries in {{.backend}}'s cache stay. Delete these?" + +[deleted_cache] +one = "deleted {{.count}} entry of {{.backend}}'s cache" +other = "deleted {{.count}} entries of {{.backend}}'s cache" + [gc_mise] one = "{{.count}} older version of the mise devvm runs on this machine is left ({{.size}})." other = "{{.count}} older versions of the mise devvm runs on this machine are left ({{.size}})." diff --git a/testdata/script/gc_caches.txtar b/testdata/script/gc_caches.txtar new file mode 100644 index 00000000..583ef689 --- /dev/null +++ b/testdata/script/gc_caches.txtar @@ -0,0 +1,19 @@ +# gc --caches asks for each backend before it frees anything of the +# backends' own caches, so without a terminal it refuses, before gc +# deletes anything else. The default run never touches the caches. +env DEVVM_MESSAGES=names + +[darwin] mkdir $HOME/Library/Caches/lima/download/by-url-sha256/0123 +[darwin] exec sh -c 'echo x > "$HOME/Library/Caches/lima/download/by-url-sha256/0123/data"' +mkdir $XDG_DATA_HOME/devvm/mise/2020.1.1 +exec touch -t 202001010000 $XDG_DATA_HOME/devvm/mise/2020.1.1 + +! exec devvm gc --caches +stderr '^devvm: gc_caches_need_terminal$' +! stdout . +exists $XDG_DATA_HOME/devvm/mise/2020.1.1 +[darwin] exists $HOME/Library/Caches/lima/download/by-url-sha256/0123/data + +exec devvm gc +stdout '^==> deleted_mise count=1$' +[darwin] exists $HOME/Library/Caches/lima/download/by-url-sha256/0123/data