跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录

Release 0.3.1: Packaging & QEMU fix (#39)

Added Linux .deb and .rpm packages for supported architectures. Added Nix flake support for Linux installations. Improved installation guidance and update instructions for Nix, Homebrew, and system packages. Improved recovery and cleanup for orphaned, broken, and failed-start virtual machines. Improved QEMU process safety, prerequisite guidance, and Linux networking reliability. Prevented host-agent shutdown when startup operations complete.

作者
Sylvain Zimmer
时间
2026/10/30 06:13
提交
3de7a9d
上一个
e3e7848
这个版本的全部文件
修改CHANGELOG.md+34 −1看文件
@@ -1,6 +1,39 @@
11# Changelog
22
3删除:## Unreleased
3新增:## 0.3.1
4新增:
5新增:### Added
6新增:
7新增:- Releases have a `.deb` and an `.rpm` for Linux (amd64, arm64): the binary in
8新增: `/usr/bin` and the docs, with QEMU and ssh recommended. Not in a package
9新增: repository yet: install the file with `apt install ./agent-vm_X.Y.Z_arm64.deb`
10新增: or `dnf install ./agent-vm-X.Y.Z-1.aarch64.rpm`.
11新增:- A Nix flake (Linux): `nix run github:sylvinus/agent-vm`. QEMU comes with it,
12新增: ssh is the system's.
13新增:
14新增:### Fixed
15新增:
16新增:- Linux: VMs turned Broken seconds to minutes after a start. The end of the
17新增: agent-vm command that started a VM (closing its terminal, a kill, and at
18新增: random a plain exit) killed Lima's host agent, which left QEMU running
19新增: without it, cut off, and failing every later start. The host agent now
20新增: outlives that command. On macOS, the same killed the VM.
21新增:- A VM left in that state is stopped by force, then started again, on the
22新增: next run; `agent-vm stop` stops it too. `stop` no longer says "VM stopped."
23新增: for a Broken VM it did not stop.
24新增:- A start that fails (the VM never came up) now stops the VM, which Lima's
25新增: host agent would otherwise keep running. The force-stop of a VM left without
26新增: its host agent checks that the process is QEMU first: the PID file of a QEMU
27新增: that aborted may name another program's process by now.
28新增:- The missing-QEMU hint no longer says `apt-get` where there is neither apt
29新增: nor dnf (NixOS): it points to the distribution's package, or the Nix flake.
30新增:- Linux: a VM could lose its network and stop in the middle of `agent-vm
31新增: setup` or any download (`exit status 255`, the VM Stopped), with QEMU
32新增: 10.2 and a KVM host. QEMU aborted on `net_fill_rstate: Assertion 'size ==
33新增: 0' failed`, a bug of its `socket` network backend, which handled a failed
34新增: read of the stream badly. The VMs' network now goes through QEMU's `dgram`
35新增: backend (QEMU 7.2 or later): no stream, nothing to lose. An older QEMU keeps
36新增: the former backend, and so does Windows (it has no unix datagram sockets).
437
538## 0.3.0
639
修改README.md+1 −1看文件
@@ -12,7 +12,7 @@ One binary with [Lima](https://lima-vm.io/) built in. Ships dev tools, Docker, h
1212curl -fsSL https://www.agent-vm.org/install.sh | sh
1313```
1414
15删除:Or `brew install sylvinus/tap/agent-vm`. From a clone, with Go (and on macOS the Xcode command line tools): `./agent-vm.sh install` builds it and links it onto your `PATH`; after a `git pull`, run it again. See [Install](https://www.agent-vm.org/#install) for prerequisites.
15新增:Or `brew install sylvinus/tap/agent-vm`; on Linux, the `.deb` or `.rpm` of the [latest release](https://github.com/sylvinus/agent-vm/releases/latest), or `nix run github:sylvinus/agent-vm` (QEMU included). From a clone, with Go (and on macOS the Xcode command line tools): `./agent-vm.sh install` builds it and links it onto your `PATH`; after a `git pull`, run it again. See [Install](https://www.agent-vm.org/#install) for prerequisites.
1616
1717## Use
1818
修改RELEASING.md+9 −0看文件
@@ -23,6 +23,9 @@ binaries `osslsigncode` (`brew install osslsigncode`).
2323 `AGENT_VM_WINDOWS_PFX_PASS=<its password>`. Without, they go out unsigned, with a warning.
2424 - Homebrew: `AGENT_VM_TAP=<clone of the tap>` updates `Formula/agent-vm.rb` there (each
2525 platform's url and sha256) and prints the commands to commit it.
26新增: - The Linux `.deb` and `.rpm` (`packaging/nfpm.yaml`) are made with nfpm, built with Go at the
27新增: version pinned in `release.sh` (`NFPM_VERSION`; `AGENT_VM_NFPM=<binary>` uses another). They
28新增: are release assets and in `SHA256SUMS`, after the tarballs.
2629 - A run that tagged and then failed is resumed by running it again.
27303. In a commit after it: `NEXT_VERSION` to the next version, and a new `## Unreleased` section.
2831
@@ -34,5 +37,11 @@ binaries `osslsigncode` (`brew install osslsigncode`).
3437 `on_arm`/`on_intel`), installing the tarball's `agent-vm`: that is the shape `AGENT_VM_TAP` updates.
3538 Then, in the tap: `brew audit --strict sylvinus/tap/agent-vm`, `brew reinstall` and `brew test`
3639 before pushing.
40新增:- `flake.nix` builds from source, with its `vendorHash` for the Go dependencies. When go.mod or
41新增: go.sum change, `release.sh` stops until it is updated: on a machine with Nix, set
42新增: `pkgs.lib.fakeHash`, run `nix build .#agent-vm` (Linux), put the hash it prints back, and update
43新增: the `go.mod+go.sum:` checksum line next to it (the error gives the value). The hash is of the
44新增: downloaded modules only (`proxyVendor`), so patches to `third_party/` leave it as it is. Do the
45新增: same after `nix flake update`: `flake.lock` pins nixpkgs, and with it the Go that downloads them.
3746- `--not-latest` publishes a release without making it GitHub's latest: the installer's default
3847 stays the previous release, and the Homebrew formula is left alone, `AGENT_VM_TAP` or not.
修改cmd/agent-vm/main.go+9 −0看文件
@@ -4,12 +4,21 @@ package main
44
55import (
66 "os"
7新增: "strings"
78
89 "github.com/sylvinus/agent-vm/internal/cli"
910 "github.com/sylvinus/agent-vm/internal/limaembed"
1011)
1112
13新增:// extraPath goes first on PATH, for this process and what it starts (the
14新增:// hostagent, QEMU): set at build time (-ldflags -X) by a build that ships
15新增:// QEMU with agent-vm (flake.nix). Empty otherwise.
16新增:var extraPath string
17新增:
1218func main() {
19新增: if p := os.Getenv("PATH"); extraPath != "" && !strings.HasPrefix(p, extraPath+string(os.PathListSeparator)) {
20新增: os.Setenv("PATH", extraPath+string(os.PathListSeparator)+p)
21新增: }
1322 // Lima's libraries start this executable again for its hostagent.
1423 if limaembed.Run(os.Args[1:]) {
1524 return
新增flake.lock+27 −0看文件
@@ -0,0 +1,27 @@
1新增:{
2新增: "nodes": {
3新增: "nixpkgs": {
4新增: "locked": {
5新增: "lastModified": 1792094642,
6新增: "narHash": "sha256-zp8ToDMnqZcu4o4IH9pdwXFXGp7yLm/M0dEnNWnyd7I=",
7新增: "owner": "NixOS",
8新增: "repo": "nixpkgs",
9新增: "rev": "fe13242281a67641c0102cdb1087f0ebe586c7df",
10新增: "type": "github"
11新增: },
12新增: "original": {
13新增: "owner": "NixOS",
14新增: "ref": "nixos-unstable",
15新增: "repo": "nixpkgs",
16新增: "type": "github"
17新增: }
18新增: },
19新增: "root": {
20新增: "inputs": {
21新增: "nixpkgs": "nixpkgs"
22新增: }
23新增: }
24新增: },
25新增: "root": "root",
26新增: "version": 7
27新增:}
新增flake.nix+122 −0看文件
@@ -0,0 +1,122 @@
1新增:{
2新增: description = "agent-vm: AI coding agents in a disposable Linux VM per project";
3新增:
4新增: inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
5新增:
6新增: outputs =
7新增: { self, nixpkgs }:
8新增: let
9新增: # Linux only for now: on macOS the binary needs cgo, the SDK and the
10新增: # virtualization entitlement (nixpkgs' lima signs it with
11新增: # darwin.sigtool), none of which this build sets up.
12新增: systems = [
13新增: "x86_64-linux"
14新增: "aarch64-linux"
15新增: ];
16新增: forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
17新增:
18新增: # The version, the build tags and Lima's version are the Makefile's and
19新增: # third_party/SOURCES's: there is one place to change each.
20新增: linesOf = file: builtins.filter builtins.isString (builtins.split "\n" (builtins.readFile file));
21新增: lineWith =
22新增: file: prefix:
23新增: builtins.head (
24新增: builtins.filter (l: builtins.substring 0 (builtins.stringLength prefix) l == prefix) (linesOf file)
25新增: );
26新增: makeVar =
27新增: name:
28新增: let
29新增: prefix = "${name} := ";
30新增: in
31新增: builtins.substring (builtins.stringLength prefix) (-1) (lineWith ./Makefile prefix);
32新增: # lima <upstream> <commit> <version> <left out>
33新增: limaVersion = builtins.elemAt (builtins.filter (s: builtins.isString s && s != "") (
34新增: builtins.split " +" (lineWith ./third_party/SOURCES "lima ")
35新增: )) 3;
36新增: in
37新增: {
38新增: packages = forAllSystems (pkgs: rec {
39新增: agent-vm = pkgs.buildGoModule {
40新增: pname = "agent-vm";
41新增: version = makeVar "NEXT_VERSION";
42新增: src = self;
43新增:
44新增: # The downloaded modules only: a vendor folder would hold
45新增: # third_party/ too (go.mod's replaces), and change with each patch.
46新增: proxyVendor = true;
47新增: # Changes with go.mod and go.sum: set pkgs.lib.fakeHash here, build,
48新增: # and nix prints the new one. release.sh refuses a release when
49新增: # this checksum of `cat go.mod go.sum` is not the current one:
50新增: # update it with the hash.
51新增: # go.mod+go.sum: d2f7908dea2c14beea6faa181d7a4cf4c709f35b94f0cc30392d4d2044f645ba
52新增: vendorHash = "sha256-zfAasYQEKqcrGi4OI3UKJyq3VoUCmNE5lU4JKPtJDmc=";
53新增:
54新增: subPackages = [ "cmd/agent-vm" ];
55新增: tags = pkgs.lib.splitString "," (makeVar "TAGS");
56新增: env.CGO_ENABLED = "0";
57新增: ldflags = [
58新增: "-s"
59新增: "-w"
60新增: "-X github.com/sylvinus/agent-vm/internal/version.Version=${makeVar "NEXT_VERSION"}"
61新增: "-X github.com/lima-vm/lima/v2/pkg/version.Version=${limaVersion}"
62新增: # QEMU comes with it, first on its PATH (cmd/agent-vm/main.go), as
63新增: # nixpkgs' lima does with a wrapper: a wrapped binary would make
64新增: # `agent-vm install` link past the wrapper. qemu_kvm, this host's
65新增: # architecture only, is a third smaller than qemu. ssh is the
66新增: # system's.
67新增: "-X main.extraPath=${pkgs.lib.makeBinPath [ pkgs.qemu_kvm ]}"
68新增: ];
69新增:
70新增: nativeBuildInputs = [ pkgs.gzip ];
71新增:
72新增: # go.mod names the Go the project is developed with, and nixpkgs
73新增: # has it a few days after a release: the build uses nixpkgs' (the
74新增: # sandbox cannot download a toolchain).
75新增: postPatch = ''
76新增: sed -i 's/^go [0-9.]*$/go ${pkgs.go.version}/' go.mod
77新增: '';
78新增:
79新增: # What the Makefile's `assets` target does: the guest agent runs in
80新增: # the Linux guest, of this machine's architecture, and is embedded
81新增: # in the binary with Lima's templates.
82新增: preBuild =
83新增: let
84新增: guestArch = if pkgs.stdenv.hostPlatform.isAarch64 then "aarch64" else "x86_64";
85新增: assets = "internal/limaembed/assets";
86新增: in
87新增: ''
88新增: go build -trimpath -ldflags "-s -w -X github.com/lima-vm/lima/v2/pkg/version.Version=${limaVersion}" \
89新增: -o ${assets}/lima-guestagent.Linux-${guestArch} github.com/lima-vm/lima/v2/cmd/lima-guestagent
90新增: gzip -9 -n -f ${assets}/lima-guestagent.Linux-${guestArch}
91新增: rm -rf ${assets}/templates
92新增: cp -R third_party/lima/templates ${assets}/templates
93新增: '';
94新增:
95新增: # The module download shares preBuild with the build, and has no
96新增: # modules to build the guest agent from yet.
97新增: overrideModAttrs = _: {
98新增: preBuild = "";
99新增: };
100新增:
101新增: # The tests run in CI, on the three platforms.
102新增: doCheck = false;
103新增:
104新增: meta = {
105新增: description = "Run AI coding agents in a disposable Linux VM per project";
106新增: homepage = "https://www.agent-vm.org/";
107新增: license = pkgs.lib.licenses.mit;
108新增: mainProgram = "agent-vm";
109新增: platforms = systems;
110新增: };
111新增: };
112新增: default = agent-vm;
113新增: });
114新增:
115新增: apps = forAllSystems (pkgs: {
116新增: default = {
117新增: type = "app";
118新增: program = "${self.packages.${pkgs.stdenv.hostPlatform.system}.agent-vm}/bin/agent-vm";
119新增: };
120新增: });
121新增: };
122新增:}
修改go.mod+1 −1看文件
@@ -1,6 +1,6 @@
11module github.com/sylvinus/agent-vm
22
3删除:go 1.26.9
3新增:go 1.26.10
44
55// Lima, sshocker and pkg/sftp are built from third_party/: upstream plus
66// patches/ (see scripts/third-party-sync). These replaces only apply when
修改internal/cli/cli.go+19 −1看文件
@@ -171,8 +171,26 @@ func versionCmd(args []string, io IO) int {
171171 return 1
172172}
173173
174删除:// updateCommand is how this copy of agent-vm is updated.
174新增:// updateCommand is how this copy of agent-vm is updated: by what installed
175新增:// it. The installer's copy would otherwise land in ~/.local/bin, ahead of a
176新增:// package's on the PATH, and hide its updates.
175177func updateCommand() string {
178新增: exe, err := self()
179新增: if err != nil {
180新增: exe = ""
181新增: }
182新增: return updateCommandFor(exe)
183新增:}
184新增:
185新增:func updateCommandFor(exe string) string {
186新增: switch {
187新增: case strings.HasPrefix(exe, "/nix/store/"):
188新增: return "with Nix, as installed (nix profile upgrade agent-vm, or the flake input)"
189新增: case strings.Contains(exe, "/Cellar/agent-vm/"):
190新增: return "brew upgrade agent-vm"
191新增: case exe == "/usr/bin/agent-vm":
192新增: return "install the .deb or .rpm of https://github.com/sylvinus/agent-vm/releases/latest"
193新增: }
176194 return "curl -fsSL https://www.agent-vm.org/install.sh | sh"
177195}
178196
修改internal/cli/cli_test.go+17 −0看文件
@@ -114,6 +114,23 @@ func TestHelp(t *testing.T) {
114114 }
115115}
116116
117新增:// A copy a package manager installed is updated by it: the installer's
118新增:// would land ahead of it on the PATH.
119新增:func TestUpdateCommand(t *testing.T) {
120新增: for exe, want := range map[string]string{
121新增: "/nix/store/abc-agent-vm-0.3.1/bin/agent-vm": "nix profile upgrade",
122新增: "/opt/homebrew/Cellar/agent-vm/0.3.1/bin/agent-vm": "brew upgrade agent-vm",
123新增: "/usr/bin/agent-vm": ".deb or .rpm",
124新增: "/home/u/.local/share/agent-vm/0.3.1/agent-vm": "install.sh | sh",
125新增: "/usr/local/bin/agent-vm": "install.sh | sh",
126新增: "": "install.sh | sh",
127新增: } {
128新增: if got := updateCommandFor(exe); !strings.Contains(got, want) {
129新增: t.Errorf("%q: %q", exe, got)
130新增: }
131新增: }
132新增:}
133新增:
117134func TestSplit(t *testing.T) {
118135 for _, c := range []struct {
119136 in []string
修改internal/cli/doctor.go+4 −0看文件
@@ -301,6 +301,10 @@ func (d *doctor) directory(ctx context.Context, dir string, protects bool, getVM
301301 case inst.Status == vm.Running:
302302 d.line("warn", "running with a share the host does not confine: "+confined.Error(),
303303 "The next start (after 'agent-vm stop') sets its shares back.")
304新增: case inst.Orphaned:
305新增: d.line("warn", "running without Lima's host agent, cut off", "'agent-vm stop' stops it, and so does the next agent-vm command here that starts a VM.")
306新增: case inst.Status == vm.Broken:
307新增: d.line("warn", "Broken: Lima cannot say whether it runs")
304308 default:
305309 d.line("info", "stopped")
306310 }
修改internal/cli/doctor_test.go+11 −0看文件
@@ -11,6 +11,7 @@ import (
1111
1212 "github.com/sylvinus/agent-vm/internal/paths"
1313 "github.com/sylvinus/agent-vm/internal/state"
14新增: "github.com/sylvinus/agent-vm/internal/vm"
1415 "github.com/sylvinus/agent-vm/internal/vmname"
1516)
1617
@@ -83,6 +84,16 @@ func TestDoctor(t *testing.T) {
8384 if o = out(); !strings.Contains(o, " warn running with a share the host does not confine: ") || !strings.Contains(o, `the mount type is "9p"`) {
8485 t.Errorf("9p:\n%s", o)
8586 }
87新增: // Broken, orphaned or not: never "stopped".
88新增: v.Status = vm.Broken
89新增: if o = out(); !strings.Contains(o, " warn Broken: Lima cannot say whether it runs") {
90新增: t.Errorf("Broken:\n%s", o)
91新增: }
92新增: v.Orphaned = true
93新增: if o = out(); !strings.Contains(o, " warn running without Lima's host agent, cut off") {
94新增: t.Errorf("orphaned:\n%s", o)
95新增: }
96新增: v.Status, v.Orphaned = vm.Running, false
8697 if strings.Contains(se.fake.CallLog(), "edit") || strings.Contains(se.fake.CallLog(), "start") || strings.Contains(se.fake.CallLog(), "stop") {
8798 t.Errorf("doctor changed the VM:\n%s", se.fake.CallLog())
8899 }
修改internal/cli/e2e_test.go+60 −1看文件
@@ -1,4 +1,4 @@
1删除://go:build e2e
1新增://go:build e2e && !windows
22
33package cli
44
@@ -9,11 +9,17 @@ import (
99 "os"
1010 "os/exec"
1111 "path/filepath"
12新增: "strconv"
1213 "strings"
14新增: "syscall"
1315 "testing"
1416 "time"
1517
1618 "github.com/lima-vm/lima/v2/pkg/instance"
19新增:
20新增: "github.com/sylvinus/agent-vm/internal/state"
21新增: "github.com/sylvinus/agent-vm/internal/vm"
22新增: "github.com/sylvinus/agent-vm/internal/vmname"
1723)
1824
1925// agent-vm as a user runs it, on real VMs: setup, then a command in a
@@ -93,6 +99,9 @@ func TestE2E(t *testing.T) {
9399 if b, _ := os.ReadFile(filepath.Join(proj, "from-vm")); string(b) != "hi\na\n" {
94100 t.Errorf("on the host: %q", b)
95101 }
102新增: // The run that started the VM is over and its context cancelled: the VM
103新增: // runs on (Lima once killed its hostagent then).
104新增: time.Sleep(2 * time.Second)
96105 if code, out := run(proj, "info"); code != 0 || !strings.Contains(out, "vm_running=1") || !strings.Contains(out, "git_protected=1") {
97106 t.Errorf("info: %s", out)
98107 }
@@ -113,7 +122,57 @@ func TestE2E(t *testing.T) {
113122 if code != 0 || !strings.Contains(out, "the project share is not mounted") || !strings.Contains(out, "v2, longer") {
114123 t.Errorf("lost share: %d %s", code, out)
115124 }
125新增: // The hostagent killed under the VM: with QEMU, the VM runs on, cut off.
126新增: // The next run stops it and starts it again; so does stop. With vz, the
127新增: // VM goes with the hostagent.
128新增: st := state.Dir(filepath.Join(home, ".agent-vm"))
129新增: b, err := vm.NewLima(LimaHome(st), string(st))
130新增: if err != nil {
131新增: t.Fatal(err)
132新增: }
133新增: name := vmname.Name(proj)
134新增: orphan := func() (driver int) {
135新增: t.Helper()
136新增: inst, err := b.Get(ctx, name)
137新增: if err != nil || inst.Status != vm.Running {
138新增: t.Fatalf("before the kill: %+v %v", inst, err)
139新增: }
140新增: pid := func(f string) int {
141新增: b, _ := os.ReadFile(filepath.Join(inst.Dir, f))
142新增: n, _ := strconv.Atoi(strings.TrimSpace(string(b)))
143新增: return n
144新增: }
145新增: driver = pid(inst.VMType + ".pid")
146新增: if err := syscall.Kill(pid("ha.pid"), syscall.SIGKILL); err != nil {
147新增: t.Fatal(err)
148新增: }
149新增: // Broken without more until the hostagent is reaped.
150新增: for range 100 {
151新增: if inst, err = b.Get(ctx, name); err == nil && (inst.Orphaned || inst.Status == vm.Stopped) {
152新增: break
153新增: }
154新增: time.Sleep(100 * time.Millisecond)
155新增: }
156新增: if !inst.Orphaned {
157新增: t.Logf("not orphaned by the kill: %s", inst.Status)
158新增: return 0
159新增: }
160新增: return driver
161新增: }
162新增: orphaned := orphan() != 0
163新增: if code, out := run(proj, "run", "true"); code != 0 || orphaned != strings.Contains(out, "left running without Lima's host agent") {
164新增: t.Errorf("run on an orphaned VM: %d %s", code, out)
165新增: }
166新增: driver := orphan()
116167 if code, out := run(proj, "stop"); code != 0 || !strings.Contains(out, "VM stopped.") {
117168 t.Errorf("stop: %s", out)
118169 }
170新增: // Killed, then reaped by init.
171新增: for i := 0; driver != 0 && syscall.Kill(driver, 0) == nil; i++ {
172新增: if i == 50 {
173新增: t.Errorf("the orphaned driver %d still runs", driver)
174新增: break
175新增: }
176新增: time.Sleep(100 * time.Millisecond)
177新增: }
119178}
修改internal/cli/setup.go+1 −1看文件
@@ -446,7 +446,7 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
446446 (&start{app: e, ctx: ctx, name: building}).printResources()
447447
448448 fmt.Fprintln(e.io.Stdout, "Starting base VM (the first run downloads a Debian image)...")
449删除: if !windowed(func(w io.Writer) error { return b.Start(ctx, building, w) }) {
449新增: if !windowed(func(w io.Writer) error { return e.startVM(ctx, b, building, w) }) {
450450 ha := filepath.Join(LimaHome(e.state), building, "ha.stderr.log")
451451 fmt.Fprintf(e.io.Stderr, "Error: Failed to start base VM. Full log: %s\nLima's own log: %s\n", logPath, ha)
452452 host.WindowsStartHint(e.io.Stderr, logPath, ha)
修改internal/cli/start.go+15 −2看文件
@@ -416,6 +416,19 @@ func (s *start) ensureRunningLocked() error {
416416 if !o.Reset && s.configErr(inst) {
417417 return errStop
418418 }
419新增: // Lima's hostagent died under it: the VM is cut off, and blocks its next
420新增: // start.
421新增: if inst != nil && inst.Orphaned {
422新增: s.warnf("Warning: VM '%s' was left running without Lima's host agent, cut off: stopping it.", s.name)
423新增: if !s.stopVM(s.ctx, s.name) {
424新增: s.warnf("Error: could not stop VM '%s'. See 'agent-vm list'.", s.name)
425新增: return errStop
426新增: }
427新增: if inst, err = s.get(s.name); err != nil {
428新增: s.warnf("Error: could not query Lima: %v", err)
429新增: return errStop
430新增: }
431新增: }
419432 if o.Reset && inst != nil {
420433 fmt.Fprintf(s.io.Stdout, "Resetting VM '%s'...\n", s.name)
421434 if !s.deleteVM(s.ctx, s.name) {
@@ -618,7 +631,7 @@ func (s *start) boot() error {
618631 fmt.Fprintf(s.io.Stdout, "Starting VM '%s'...\n", s.name)
619632 b, _ := s.backend()
620633 var log bytes.Buffer
621删除: if err := b.Start(s.ctx, s.name, &log); err != nil {
634新增: if err := s.startVM(s.ctx, b, s.name, &log); err != nil {
622635 ha := paths.Host(filepath.Join(LimaHome(s.state), s.name, "ha.stderr.log"))
623636 s.warnf("Error: Failed to start VM '%s'.\n--- Lima's output ---\n%s%v\nFull log: %s", s.name, log.String(), err, ha)
624637 host.WindowsStartHint(s.io.Stderr, ha)
@@ -698,7 +711,7 @@ func (s *start) afterBoot(isNew, wasRunning, wantWritable bool) error {
698711 return err
699712 }
700713 b, _ := s.backend()
701删除: if err := b.Start(s.ctx, s.name, io.Discard); err != nil {
714新增: if err := s.startVM(s.ctx, b, s.name, io.Discard); err != nil {
702715 s.warnf("Error: VM '%s' did not come back up after changing the project mount.", s.name)
703716 return errStop
704717 }
修改internal/cli/start_test.go+45 −0看文件
@@ -143,6 +143,29 @@ func TestStartNewVM(t *testing.T) {
143143 }
144144}
145145
146新增:// A VM left running without Lima's hostagent is stopped by force, then
147新增:// started again.
148新增:func TestStartOrphaned(t *testing.T) {
149新增: se := newStartEnv(t)
150新增: se.base()
151新增: name := vmname.Name(se.proj)
152新增: if code := se.run("run", "true"); code != 0 {
153新增: t.Fatalf("run: %d %s", code, se.out())
154新增: }
155新增: v := se.fake.VMs[name]
156新增: v.Status, v.Orphaned = vm.Broken, true
157新增: if se.run("run", "true") != 0 || !strings.Contains(se.out(), "left running without Lima's host agent") ||
158新增: !strings.HasPrefix(se.fake.CallLog(), "stop "+name) || !strings.Contains(se.fake.CallLog(), "start "+name) || v.Status != vm.Running {
159新增: t.Errorf("orphaned: %s\n%s", se.out(), se.fake.CallLog())
160新增: }
161新增: // One that does not stop: no start.
162新增: v.Status, v.Orphaned = vm.Broken, true
163新增: se.fake.Sticky[name] = true
164新增: if se.run("run", "true") != 1 || !strings.Contains(se.out(), "could not stop VM") || strings.Contains(se.fake.CallLog(), "start") {
165新增: t.Errorf("orphaned, stop failed: %s\n%s", se.out(), se.fake.CallLog())
166新增: }
167新增:}
168新增:
146169// The resources asked against the VM's: in bytes, the disk one way (it
147170// only grows), a VM that cannot be read counts as a change.
148171func TestResourcesDiffer(t *testing.T) {
@@ -211,6 +234,28 @@ func TestStartSSHPort(t *testing.T) {
211234 }
212235}
213236
237新增:// A start that fails stops the VM: the hostagent would outlive the command.
238新增:// An interrupted one is left to finish in the background.
239新增:func TestStartFailedStops(t *testing.T) {
240新增: se := newStartEnv(t)
241新增: se.base()
242新增: name := vmname.Name(se.proj)
243新增: se.fake.FailOn = map[string]error{"start": errors.New("boom")}
244新增: if se.run("run", "true") != 1 || !strings.HasSuffix(se.fake.CallLog(), "start "+name+"\nstop "+name) {
245新增: t.Errorf("start fails: %s\n%s", se.out(), se.fake.CallLog())
246新增: }
247新增: e, err := newApp(IO{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: io.Discard})
248新增: if err != nil {
249新增: t.Fatal(err)
250新增: }
251新增: ctx, cancel := context.WithCancel(context.Background())
252新增: cancel()
253新增: n := len(se.fake.Calls)
254新增: if err := e.startVM(ctx, se.fake, name, io.Discard); err == nil || strings.Contains(strings.Join(se.fake.Calls[n:], "\n"), "stop") {
255新增: t.Errorf("interrupted: %v\n%s", err, se.fake.CallLog())
256新增: }
257新增:}
258新增:
214259// A new VM that cannot be configured is deleted, never started, nothing
215260// recorded; --reset that cannot delete changes nothing.
216261func TestStartFailures(t *testing.T) {
修改internal/cli/vms.go+16 −1看文件
@@ -4,6 +4,7 @@ import (
44 "context"
55 "errors"
66 "fmt"
7新增: "io"
78 "strings"
89 "text/tabwriter"
910
@@ -67,6 +68,20 @@ func (e *app) stopCmd(ctx context.Context, args []string) int {
6768 return 0
6869}
6970
71新增:// startVM starts name on b. Lima's hostagent outlives the command, so a start
72新增:// that fails (the VM never came up) would leave it running, cut off: it is
73新增:// stopped. Not after an interrupt: that start goes on in the background, as
74新增:// limactl's does, and the next command finds the VM up.
75新增:func (e *app) startVM(ctx context.Context, b vm.Backend, name string, log io.Writer) error {
76新增: err := b.Start(ctx, name, log)
77新增: if err != nil && ctx.Err() == nil {
78新增: if stopErr := b.Stop(ctx, name); stopErr != nil {
79新增: err = errors.Join(err, fmt.Errorf("stopping VM '%s' failed, it may still be running: %w", name, stopErr))
80新增: }
81新增: }
82新增: return err
83新增:}
84新增:
7085// stopVM stops name, and reports whether it is known to be stopped.
7186func (e *app) stopVM(ctx context.Context, name string) bool {
7287 b, err := e.backend()
@@ -75,7 +90,7 @@ func (e *app) stopVM(ctx context.Context, name string) bool {
7590 }
7691 _ = b.Stop(ctx, name)
7792 inst, err := b.Get(ctx, name)
78删除: return err == nil && inst.Status != vm.Running
93新增: return err == nil && inst.Status == vm.Stopped
7994}
8095
8196func (e *app) rmCmd(ctx context.Context, args []string) int {
修改internal/cli/vms_test.go+12 −0看文件
@@ -92,6 +92,18 @@ func TestStopRm(t *testing.T) {
9292 if te.run("stop", "proj-deadbeef") != 1 || !strings.Contains(te.out(), "is still running") {
9393 t.Errorf("stop that did not take: %s", te.out())
9494 }
95新增: // A Broken VM is not stopped: said so. An orphaned one is stopped by force.
96新增: te.fake.Sticky = map[string]bool{}
97新增: te.fake.VMs["proj-deadbeef"].Status = vm.Broken
98新增: if te.run("stop", "proj-deadbeef") != 1 || !strings.Contains(te.out(), "is still running") {
99新增: t.Errorf("stop of a Broken VM: %s", te.out())
100新增: }
101新增: te.fake.VMs["proj-deadbeef"].Orphaned = true
102新增: if te.run("stop", "proj-deadbeef") != 0 || !strings.HasSuffix(te.out(), "VM stopped.\n") || te.fake.VMs["proj-deadbeef"].Status != vm.Stopped {
103新增: t.Errorf("stop of an orphaned VM: %s", te.out())
104新增: }
105新增: te.fake.VMs["proj-deadbeef"].Status = vm.Running
106新增: te.fake.Sticky["proj-deadbeef"] = true
95107 // Nor a delete that did not take.
96108 os.WriteFile(te.state.Marker(state.VersionOf, "proj-deadbeef"), []byte("1\n"), 0o644)
97109 if te.run("rm", "proj-deadbeef") != 1 || !strings.Contains(te.out(), "could not delete VM 'proj-deadbeef'") ||
修改internal/host/host_test.go+19 −0看文件
@@ -47,3 +47,22 @@ func TestCapBash(t *testing.T) {
4747 t.Error("an unknown host clamped")
4848 }
4949}
50新增:
51新增:// QEMU's package by the host's package manager, as the .deb and .rpm
52新增:// recommend it.
53新增:func TestQemuBinaryFor(t *testing.T) {
54新增: for _, c := range []struct {
55新增: goarch, manager string
56新增: bin, cmd string
57新增: }{
58新增: {"amd64", "apt-get", "qemu-system-x86_64", "sudo apt-get install qemu-system-x86 qemu-utils"},
59新增: {"arm64", "apt-get", "qemu-system-aarch64", "sudo apt-get install qemu-system-arm qemu-utils"},
60新增: {"amd64", "dnf", "qemu-system-x86_64", "sudo dnf install qemu-system-x86-core qemu-img"},
61新增: {"arm64", "dnf", "qemu-system-aarch64", "sudo dnf install qemu-system-aarch64-core qemu-img"},
62新增: {"amd64", "", "qemu-system-x86_64", "your distribution's QEMU package (with Nix, 'nix run github:sylvinus/agent-vm' brings its own)"},
63新增: } {
64新增: if bin, cmd := qemuBinaryFor(c.goarch, c.manager); bin != c.bin || cmd != c.cmd {
65新增: t.Errorf("%s %q: %s %q", c.goarch, c.manager, bin, cmd)
66新增: }
67新增: }
68新增:}
修改internal/host/prereqs.go+32 −10看文件
@@ -13,15 +13,33 @@ import (
1313)
1414
1515// qemuBinary is QEMU's emulator for this host's architecture, and the
16删除:// Debian package that has it.
17删除:func qemuBinary() (bin, pkg string) {
18删除: switch runtime.GOARCH {
16新增:// way to install it: the command with apt-get's package, or dnf's where there
17新增:// is dnf and no apt-get; a general hint where there is neither (NixOS, Arch).
18新增:func qemuBinary() (bin, install string) {
19新增: manager := ""
20新增: if _, err := exec.LookPath("apt-get"); err == nil {
21新增: manager = "apt-get"
22新增: } else if _, err := exec.LookPath("dnf"); err == nil {
23新增: manager = "dnf"
24新增: }
25新增: return qemuBinaryFor(runtime.GOARCH, manager)
26新增:}
27新增:
28新增:func qemuBinaryFor(goarch, manager string) (bin, install string) {
29新增: bin, deb, rpm := "qemu-system-"+goarch, "qemu-system", "qemu-system-"+goarch+"-core"
30新增: switch goarch {
1931 case "amd64":
20删除: return "qemu-system-x86_64", "qemu-system-x86"
32新增: bin, deb, rpm = "qemu-system-x86_64", "qemu-system-x86", "qemu-system-x86-core"
2133 case "arm64":
22删除: return "qemu-system-aarch64", "qemu-system-arm"
34新增: bin, deb, rpm = "qemu-system-aarch64", "qemu-system-arm", "qemu-system-aarch64-core"
2335 }
24删除: return "qemu-system-" + runtime.GOARCH, "qemu-system"
36新增: switch manager {
37新增: case "dnf":
38新增: return bin, "sudo dnf install " + rpm + " qemu-img"
39新增: case "apt-get":
40新增: return bin, "sudo apt-get install " + deb + " qemu-utils"
41新增: }
42新增: return bin, "your distribution's QEMU package (with Nix, 'nix run github:sylvinus/agent-vm' brings its own)"
2543}
2644
2745// WSLVersion is 2 or 1 under WSL, from the kernel release, 0 elsewhere.
@@ -47,10 +65,14 @@ func LinuxPrereqs(w io.Writer) bool {
4765 return true
4866 }
4967 ok := true
50删除: bin, pkg := qemuBinary()
51删除: if _, err := exec.LookPath(bin); err != nil {
52删除: fmt.Fprintf(w, "Error: Lima needs '%s' on PATH (not found).\n Install with: sudo apt-get install %s\n", bin, pkg)
53删除: ok = false
68新增: bin, install := qemuBinary()
69新增: // Fedora packages qemu-img apart from the emulator, and Lima runs it on
70新增: // the disk image.
71新增: for _, b := range []string{bin, "qemu-img"} {
72新增: if _, err := exec.LookPath(b); err != nil {
73新增: fmt.Fprintf(w, "Error: Lima needs '%s' on PATH (not found).\n Install with: %s\n", b, install)
74新增: ok = false
75新增: }
5476 }
5577 _, err := os.Stat("/dev/kvm")
5678 switch {
修改internal/vm/lima.go+18 −5看文件
@@ -222,6 +222,13 @@ func fromLima(inst *limatype.Instance) *Instance {
222222 out.Status = Broken
223223 out.ConfigErr = errors.Join(inst.Errors...)
224224 }
225新增: // "driver is running but host agent is not". Not the other way around: a
226新增: // hostagent without its driver is also one booting the VM. Only QEMU
227新增: // outlives the hostagent (vz and the others run in it), and the PID file
228新增: // of one that aborted may name another program's process now: Stop kills
229新增: // this one.
230新增: out.Orphaned = out.Status == Broken && inst.Config != nil && inst.HostAgentPID == 0 && inst.DriverPID > 0 &&
231新增: inst.VMType == limatype.QEMU && isQEMU(inst.DriverPID, inst.Dir, inst.Name)
225232 if c := inst.Config; c != nil {
226233 if c.SSH.LocalPort != nil {
227234 out.SSHPortConfig = *c.SSH.LocalPort
@@ -505,12 +512,18 @@ func (l *Lima) Stop(ctx context.Context, name string) error {
505512 if err != nil {
506513 return err
507514 }
508删除: if inst.Status != limatype.StatusRunning {
509删除: return nil
515新增: switch {
516新增: case inst.Status == limatype.StatusRunning:
517新增: return withLog(io.Discard, func() error {
518新增: return errors.Join(instance.StopGracefully(ctx, inst, false), reconcile.Reconcile(ctx, ""))
519新增: })
520新增: case fromLima(inst).Orphaned:
521新增: return withLog(io.Discard, func() error {
522新增: instance.StopForcibly(inst)
523新增: return reconcile.Reconcile(ctx, "")
524新增: })
510525 }
511删除: return withLog(io.Discard, func() error {
512删除: return errors.Join(instance.StopGracefully(ctx, inst, false), reconcile.Reconcile(ctx, ""))
513删除: })
526新增: return nil
514527}
515528
516529func (l *Lima) Delete(ctx context.Context, name string) error {
修改internal/vm/lima_test.go+95 −0看文件
@@ -5,15 +5,20 @@ import (
55 "errors"
66 "io"
77 "os"
8新增: "os/exec"
89 "path/filepath"
910 "reflect"
11新增: "runtime"
12新增: "strconv"
1013 "strings"
1114 "sync"
1215 "testing"
16新增: "time"
1317
1418 "github.com/lima-vm/lima/v2/pkg/guestagent/api"
1519 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
1620 "github.com/lima-vm/lima/v2/pkg/limatype"
21新增: "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
1722 "github.com/lima-vm/lima/v2/pkg/limayaml"
1823 "github.com/lima-vm/lima/v2/pkg/portfwd"
1924
@@ -291,6 +296,96 @@ func TestSharesKeptWindows(t *testing.T) {
291296 }
292297}
293298
299新增:// A driver running without its hostagent: orphaned, and Stop kills it. A
300新增:// hostagent without its driver is not: it may be booting the VM.
301新增:func TestLimaStopOrphaned(t *testing.T) {
302新增: if runtime.GOOS == "windows" {
303新增: t.Skip("no sleep to stand for the driver")
304新增: }
305新增: ctx := context.Background()
306新增: l := newTestLima(t)
307新增: none := []Mount{}
308新增: if err := l.Create(ctx, "o", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
309新增: t.Fatal(err)
310新增: }
311新增: inst, err := l.Get(ctx, "o")
312新增: if err != nil {
313新增: t.Fatal(err)
314新增: }
315新增: if inst.VMType != "qemu" {
316新增: t.Skip("only QEMU outlives the hostagent")
317新增: }
318新增: // A shell idling, under the name of a program and with the options of a
319新增: // QEMU: of this VM's, or any other.
320新增: spawn := func(name, vmName string) ([]byte, chan struct{}) {
321新增: sh, err := exec.LookPath("sh")
322新增: if err != nil {
323新增: t.Skip(err)
324新增: }
325新增: exe := filepath.Join(t.TempDir(), name)
326新增: if err := os.Symlink(sh, exe); err != nil {
327新增: t.Fatal(err)
328新增: }
329新增: cmd := exec.Command(exe, "-c", "while :; do sleep 1; done", "-name", "lima-"+vmName,
330新增: "-pidfile", filepath.Join(inst.Dir, filenames.PIDFile(inst.VMType)))
331新增: if err := cmd.Start(); err != nil {
332新增: t.Fatal(err)
333新增: }
334新增: done := make(chan struct{})
335新增: go func() { cmd.Wait(); close(done) }()
336新增: t.Cleanup(func() { cmd.Process.Kill(); <-done })
337新增: return []byte(strconv.Itoa(cmd.Process.Pid)), done
338新增: }
339新增: pid, exited := spawn("qemu-system-fake", "o")
340新增:
341新增: ha := filepath.Join(inst.Dir, filenames.HostAgentPID)
342新增: os.WriteFile(ha, pid, 0o644)
343新增: if got, _ := l.Get(ctx, "o"); got.Status != Broken || got.Orphaned {
344新增: t.Fatalf("a hostagent without its driver: %+v", got)
345新增: }
346新增: l.Stop(ctx, "o")
347新增: select {
348新增: case <-exited:
349新增: t.Fatal("Stop killed a hostagent without its driver")
350新增: case <-time.After(200 * time.Millisecond):
351新增: }
352新增: os.Remove(ha)
353新增:
354新增: // A PID file left by a QEMU that aborted, its number another program's
355新增: // now: not orphaned, and Stop leaves it alone.
356新增: driverPID := filepath.Join(inst.Dir, filenames.PIDFile(inst.VMType))
357新增: // Or another VM's QEMU.
358新增: for _, c := range []struct{ prog, vm string }{{"not-a-vm", "o"}, {"qemu-system-fake", "other"}} {
359新增: other, otherExited := spawn(c.prog, c.vm)
360新增: os.WriteFile(driverPID, other, 0o644)
361新增: if got, _ := l.Get(ctx, "o"); got.Orphaned {
362新增: t.Fatalf("%s of %s: %+v", c.prog, c.vm, got)
363新增: }
364新增: l.Stop(ctx, "o")
365新增: select {
366新增: case <-otherExited:
367新增: t.Fatalf("Stop killed %s of %s", c.prog, c.vm)
368新增: case <-time.After(200 * time.Millisecond):
369新增: }
370新增: }
371新增:
372新增: os.WriteFile(driverPID, pid, 0o644)
373新增: if got, _ := l.Get(ctx, "o"); got.Status != Broken || !got.Orphaned {
374新增: t.Fatalf("a driver without its hostagent: %+v", got)
375新增: }
376新增: if err := l.Stop(ctx, "o"); err != nil {
377新增: t.Fatal(err)
378新增: }
379新增: select {
380新增: case <-exited:
381新增: case <-time.After(10 * time.Second):
382新增: t.Fatal("the driver still runs")
383新增: }
384新增: if got, _ := l.Get(ctx, "o"); got.Status != Stopped || got.Orphaned {
385新增: t.Errorf("after Stop: %+v", got)
386新增: }
387新增:}
388新增:
294389func TestConfined(t *testing.T) {
295390 b := &SSHFS{SFTPDriver: "builtin"}
296391 for _, c := range []struct {
新增internal/vm/procname.go+48 −0看文件
@@ -0,0 +1,48 @@
1新增:package vm
2新增:
3新增:import (
4新增: "os"
5新增: "os/exec"
6新增: "path/filepath"
7新增: "runtime"
8新增: "strconv"
9新增: "strings"
10新增:
11新增: "github.com/lima-vm/lima/v2/pkg/limatype"
12新增: "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
13新增:)
14新增:
15新增:// isQEMU reports whether pid is the QEMU of the VM name, whose files are in
16新增:// dir: its command line has the -name and -pidfile Lima gave it. A PID file
17新增:// outlives a QEMU that aborted, and its number may belong to another program
18新增:// or another VM by now: that one must not be killed.
19新增:func isQEMU(pid int, dir, name string) bool {
20新增: var args string
21新增: switch runtime.GOOS {
22新增: case "linux":
23新增: b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline")
24新增: if err != nil {
25新增: return false
26新增: }
27新增: args = strings.ReplaceAll(string(b), "\x00", " ")
28新增: case "windows":
29新增: out, err := exec.Command("powershell", "-NoProfile", "-Command",
30新增: "(Get-CimInstance Win32_Process -Filter 'ProcessId="+strconv.Itoa(pid)+"').CommandLine").Output()
31新增: if err != nil {
32新增: return false
33新增: }
34新增: args = string(out)
35新增: default:
36新增: out, err := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "args=").Output()
37新增: if err != nil {
38新增: return false
39新增: }
40新增: args = string(out)
41新增: }
42新增: // Padded, so that an option is matched whole.
43新增: args = " " + strings.TrimSpace(args) + " "
44新增: pidfile := filepath.Join(dir, filenames.PIDFile(string(limatype.QEMU)))
45新增: prog, _, found := strings.Cut(args, " -name lima-"+name+" ")
46新增: return found && strings.Contains(strings.ToLower(prog), "qemu") &&
47新增: strings.Contains(args, " -pidfile "+pidfile+" ")
48新增:}
修改internal/vm/vm.go+6 −1看文件
@@ -61,6 +61,10 @@ type Instance struct {
6161 Mounts []Mount
6262 // ConfigErr is why the backend cannot read the VM's config (Broken).
6363 ConfigErr error
64新增: // Orphaned: Broken, the VM still running without the backend's process
65新增: // that serves it (Lima's hostagent). Nothing reaches it; Stop ends it by
66新增: // force.
67新增: Orphaned bool
6468}
6569
6670// Mount is a host folder shared with the guest.
@@ -140,7 +144,8 @@ type Backend interface {
140144 // gets the backend's progress. It refuses a VM whose shares are not
141145 // confined to their folders (see Confined).
142146 Start(ctx context.Context, name string, log io.Writer) error
143删除: // Stop shuts down the running VM name.
147新增: // Stop shuts down the running VM name, and kills an orphaned one. Any
148新增: // other VM is left as it is.
144149 Stop(ctx context.Context, name string) error
145150 // Delete removes the VM name, running or not.
146151 Delete(ctx context.Context, name string) error
修改internal/vm/vmtest/fake.go+2 −2看文件
@@ -177,8 +177,8 @@ func (f *Fake) Stop(_ context.Context, name string) error {
177177 if err := f.call("stop %s", name); err != nil {
178178 return err
179179 }
180删除: if v, ok := f.VMs[name]; ok && !f.Sticky[name] {
181删除: v.Status = vm.Stopped
180新增: if v, ok := f.VMs[name]; ok && !f.Sticky[name] && (v.Status == vm.Running || v.Orphaned) {
181新增: v.Status, v.Orphaned = vm.Stopped, false
182182 }
183183 return nil
184184}
新增packaging/nfpm.yaml+53 −0看文件
@@ -0,0 +1,53 @@
1新增:# The .deb and .rpm of a Linux build, made by release.sh (linux_packages) with
2新增:# nfpm, run in the folder of that build's tarball. The variables come from
3新增:# release.sh. QEMU and ssh are recommended, not required: apt and dnf install
4新增:# recommends by default; RHEL and its rebuilds name QEMU qemu-kvm, and a QEMU
5新增:# from elsewhere on the PATH does too. `agent-vm setup` says what is missing.
6新增:name: agent-vm
7新增:arch: ${GOARCH}
8新增:platform: linux
9新增:version: ${VERSION}
10新增:release: "1"
11新增:section: utils
12新增:priority: optional
13新增:maintainer: Sylvain Zimmer <[email protected]>
14新增:description: |
15新增: Run AI coding agents in a disposable Linux VM per project.
16新增: The VM gets the project directory and nothing else of the host's.
17新增:homepage: https://www.agent-vm.org/
18新增:license: MIT
19新增:
20新增:contents:
21新增: - src: agent-vm
22新增: dst: /usr/bin/agent-vm
23新增: file_info:
24新增: mode: 0755
25新增: - src: README.md
26新增: dst: /usr/share/doc/agent-vm/README.md
27新增: - src: CHANGELOG.md
28新增: dst: /usr/share/doc/agent-vm/CHANGELOG.md
29新增: - src: LICENSE
30新增: dst: /usr/share/doc/agent-vm/LICENSE
31新增: - src: NOTICE
32新增: dst: /usr/share/doc/agent-vm/NOTICE
33新增: - src: THIRD_PARTY_LICENSES
34新增: dst: /usr/share/doc/agent-vm/THIRD_PARTY_LICENSES
35新增: - src: runtime.example.sh
36新增: dst: /usr/share/doc/agent-vm/runtime.example.sh
37新增:
38新增:# The RPM records the build host's name: fixed, so that the same commit gives
39新增:# the same RPM on any machine.
40新增:rpm:
41新增: buildhost: agent-vm
42新增:
43新增:overrides:
44新增: deb:
45新增: recommends:
46新增: - ${QEMU_DEB}
47新增: - qemu-utils
48新增: - openssh-client
49新增: rpm:
50新增: recommends:
51新增: - ${QEMU_RPM}
52新增: - qemu-img
53新增: - openssh-clients
修改patches/README.md+7 −0看文件
@@ -34,6 +34,8 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there
3434| 18 | When the first sshfs mount fails, Lima retries with `-o nonempty` in place of the share's options. | The share is mounted again without `cache=no` (sshfs's attribute cache back on). | lima 0003 |
3535| 19 | The host's event for a removal the guest asked for is relayed back as a host deletion. | The guest's next removal of a file it created again is taken for the relayed one and not done: the file stays on the host. | sshocker 0009 |
3636| 20 | The client sets any mode bit, setuid, setgid and sticky included. | A file the host runs carries the privileges of its owner. | sshocker 0006 |
37新增:| 21 | `instance.StartWithPaths` starts the hostagent with `exec.CommandContext`: os/exec kills it when the caller's context ends, also after Start returned. | The end of the agent-vm command that started a VM kills its hostagent: QEMU runs on without it (Broken, every later start fails), vz VMs die. | lima 0006 |
38新增:| 22 | QEMU's `socket` and `stream` netdevs fall through to `net_fill_rstate` with `size == -1` when `recv()` returns EAGAIN (QEMU 10.2.4 at least). | QEMU aborts (`Assertion 'size == 0' failed`) under sustained traffic on Linux with KVM: the instance stops, mid-setup. Windows keeps the `stream` netdev and so the risk. | lima 0008 |
3739
3840## The patches
3941
@@ -44,6 +46,10 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there
4446| `lima/0003-hostagent-keep-sshfs-options-on-retry` | lima-vm/lima | not sent | Bug 18: the retry adds `nonempty` to the options. No test: it needs a guest whose first mount fails. |
4547| `lima/0004-portfwd-not-next-to-a-host-program` | lima-vm/lima | not sent | A guest port is forwarded only when no host program uses it: with `SO_REUSEADDR`, a listener on 127.0.0.1:P is allowed next to a host program's 0.0.0.0:P on macOS and BSD, and takes its local connections. The port is tried on 127.0.0.1, ::1, 0.0.0.0 and :: first (with `SO_EXCLUSIVEADDRUSE` on Windows); one in use gives a `failed` port-forward event. Tests `TestForwardNotNextToHostProgram`, `TestForwardFreePort`. |
4648| `lima/0005-network-isolation-hooks` | lima-vm/lima | not sent | Hooks for agent-vm's network policy: `usernet.Outbound` and `usernet.AllowHostService` (the hostagent's DNS ports), `dns.Names`/`dns.Answered` (a name refused is NXDOMAIN, never looked up). QEMU gets its own netstack per instance, as vz has, so the policy applies to both, and its guest's DNS is the gateway's. QEMU is handed the connected socket, or on Windows, which cannot pass it, connects itself (`stream` netdev, QEMU 7.2 or later). `usernet.Names` and `usernet.Answered` reach the gateway's DNS server through gvisor-tap-vsock 0002, and a host service is allowed for its network and port on 127.0.0.1 only. Tests `TestNamesAnswered`, `TestOutboundHostServices`; the rest is covered by agent-vm's e2e (`internal/vm/lima_e2e_test.go`). |
49新增:| `lima/0006-instance-hostagent-outlives-start-context` | lima-vm/lima | not sent; the issue to open is the patch's header | Bug 21: `exec.Command`. No Lima test (its unit tests start no hostagent): agent-vm's e2e (`internal/cli/e2e_test.go`) fails without it. The header also reports the QEMU driver's "send on closed channel" panic that follows, not fixed here. |
50新增:| `lima/0007-qemu-features-own-outputs` | lima-vm/lima | not sent | `inspectFeatures` ran its four help requests into the same buffers: each feature text held the earlier ones'. One buffer per request (`qemuHelp`). Test `TestInspectFeaturesOwnOutputs`. |
51新增:| `lima/0008-qemu-dgram-netdev` | lima-vm/lima | not sent; the issue to open at QEMU is the patch's header | Bug 22: QEMU gets the netstack through a datagram socketpair (`-netdev dgram`, `GVisorNetstackOpts.DgramConn`), as vz does; the `socket` netdev, and its unix socket listener, only for a QEMU older than 7.2, and Windows (the `stream` netdev has the bug too). Tests `TestDgramConn`, `TestDgramPair`, `TestFdDgramTemplate`; the netdev choice is covered by agent-vm's e2e. |
52新增:| `lima/0009-start-channels-buffered` | lima-vm/lima | not sent | `StartWithPaths` left the losing goroutine of its race blocked on an unbuffered send, for as long as the program lives. No test: it starts a hostagent. |
4753| `sshocker/0001-rooted-server-readonly-names` | lima-vm/sshocker | fork branch `readonly-names` | The builtin server serves only the mounted directory, and `ReadonlyNames`. |
4854| `sshocker/0002-expect-remove` | lima-vm/sshocker | fork branch `expect-remove` | `ExpectRemove`, for 0002 of Lima. |
4955| `sshocker/0003-append-fix` | lima-vm/sshocker | not sent | Bug 1. Tests `TestRootedOpenAppend`, `TestRootedOpenMode`. No pkg/sftp dependency: send first. |
@@ -60,6 +66,7 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there
6066| `sftp/0005-fuzz-request-server` | pkg/sftp | not sent | `FuzzRequestServer`: any bytes after INIT, to a server set as sshocker sets it; it never panics nor hangs. Its seed is a WRITE at a huge offset, which made `InMemHandler` allocate it. |
6167| `gvisor-tap-vsock/0001-outbound-policy` | containers/gvisor-tap-vsock | not sent | `Configuration.Outbound`: the TCP and UDP forwarders refuse a destination it denies, checked after NAT (the gateway's address is the host's loopback by then). No test of its own: agent-vm's e2e connects to denied and allowed addresses. |
6268| `gvisor-tap-vsock/0002-dns-policy` | containers/gvisor-tap-vsock | not sent | `Configuration.DNSNames` and `DNSAnswered`: the gateway's DNS server answers NXDOMAIN, over UDP and TCP, for a name `DNSNames` refuses, without asking the host's resolver, and tells `DNSAnswered` the IPv4 addresses it gave, so that `Outbound` can allow those only. Test `TestPolicy`. |
69新增:| `gvisor-tap-vsock/0003-accept-ended-by-context` | containers/gvisor-tap-vsock | not sent | `Switch.Accept` returns nil, and logs nothing, when its connection ends after the program cancelled the context. Test `TestAcceptEndedByContext`. |
6370
6471Lima's `0b63ae0` of the fork (`replace` of sshocker) is gone: agent-vm's `go.mod` replaces all
6572three modules. FSETSTAT through a read handle keeps the path checks (0004): a read handle can be
新增patches/gvisor-tap-vsock/0003-accept-ended-by-context.patch+80 −0看文件
@@ -0,0 +1,80 @@
1新增:Subject: [PATCH] tap: a connection closed by the program's cancel is not an error
2新增:
3新增:Switch.Accept logs "cannot receive packets from X, disconnecting" at error
4新增:level, and returns the error, when the connection's read fails. A program
5新增:that stops its switch by cancelling the context and closing the connection
6新增:gets that error each time, though it asked for it. Accept returns nil then,
7新增:and says nothing.
8新增:
9新增:Test: TestAcceptEndedByContext (a read failing by itself is still an error).
10新增:
11新增:---
12新增:diff --git a/pkg/tap/switch.go b/pkg/tap/switch.go
13新增:index 944b618f..e96a0fd9 100644
14新增:--- a/pkg/tap/switch.go
15新增:+++ b/pkg/tap/switch.go
16新增:@@ -96,6 +96,10 @@ func (e *Switch) Accept(ctx context.Context, rawConn net.Conn, protocol types.Pr
17新增: e.disconnect(id, conn)
18新增: }()
19新增: if err := e.rx(ctx, id, conn); err != nil {
20新增:+ if ctx.Err() != nil {
21新增:+ // Closing the connection is how a program ends the switch.
22新增:+ return nil
23新增:+ }
24新增: err := fmt.Errorf("cannot receive packets from %s, disconnecting: %w", conn.RemoteAddr().String(), err)
25新增: log.Error(err)
26新增: return err
27新增:diff --git a/pkg/tap/switch_test.go b/pkg/tap/switch_test.go
28新增:new file mode 100644
29新增:index 00000000..4039fe9b
30新增:--- /dev/null
31新增:+++ b/pkg/tap/switch_test.go
32新增:@@ -0,0 +1,48 @@
33新增:+package tap
34新增:+
35新增:+import (
36新增:+ "context"
37新增:+ "net"
38新增:+ "sync"
39新增:+ "testing"
40新增:+
41新增:+ "github.com/containers/gvisor-tap-vsock/pkg/types"
42新增:+ "github.com/stretchr/testify/require"
43新增:+)
44新增:+
45新增:+// readingConn says when it is first read.
46新增:+type readingConn struct {
47新增:+ net.Conn
48新增:+ reading chan struct{}
49新增:+ once sync.Once
50新增:+}
51新增:+
52新增:+func (c *readingConn) Read(b []byte) (int, error) {
53新增:+ c.once.Do(func() { close(c.reading) })
54新增:+ return c.Conn.Read(b)
55新增:+}
56新增:+
57新增:+// A connection that ends because the program cancelled the context is not an
58新增:+// error; one that ends by itself is.
59新增:+func TestAcceptEndedByContext(t *testing.T) {
60新增:+ for _, cancelled := range []bool{true, false} {
61新增:+ s := NewSwitch(false)
62新增:+ ours, theirs := net.Pipe()
63新增:+ conn := &readingConn{Conn: ours, reading: make(chan struct{})}
64新增:+ ctx, cancel := context.WithCancel(context.Background())
65新增:+ done := make(chan error, 1)
66新增:+ go func() { done <- s.Accept(ctx, conn, types.VfkitProtocol) }()
67新增:+ <-conn.reading
68新增:+ if cancelled {
69新增:+ cancel()
70新增:+ }
71新增:+ theirs.Close()
72新增:+ err := <-done
73新增:+ cancel()
74新增:+ if cancelled {
75新增:+ require.NoError(t, err)
76新增:+ } else {
77新增:+ require.Error(t, err)
78新增:+ }
79新增:+ }
80新增:+}
新增patches/lima/0006-instance-hostagent-outlives-start-context.patch+76 −0看文件
@@ -0,0 +1,76 @@
1新增:Subject: [PATCH] instance: do not kill the hostagent when Start's context ends
2新增:
3新增:StartWithPaths starts the hostagent with exec.CommandContext(ctx, ...).
4新增:The hostagent is meant to outlive the call ("leave the hostagent process
5新增:running" when Start returns), but os/exec kills it as soon as ctx is
6新增:done, also long after Start returned.
7新增:
8新增:limactl does not show it: its process exits right after Start, before
9新增:anything cancels the context, and a Ctrl-C kills limactl without
10新增:cancelling it. A Go program that uses pkg/instance does: it cancels the
11新增:context it passed (a deferred cancel, a signal handler, a request scope)
12新增:while it keeps running, and the hostagent is killed then. When the
13新增:cancel comes just before the program exits, os/exec's watcher races the
14新增:exit: the instance breaks sometimes, depending on the machine.
15新增:
16新增:What follows depends on the driver:
17新增:
18新增:- qemu: QEMU is a child of the hostagent, not killed with it. It keeps
19新增: running, reparented to init, unreachable (no hostagent, so no SSH
20新增: forward or usernet), and holds the lock on its PID file. The instance
21新增: is Broken: "qemu driver is running but host agent is not". The next
22新增: start fails: QEMU exits at once ("cannot create PID file: Cannot lock
23新增: pid file"), the QEMU driver panics (below), and limactl reports "host
24新增: agent process has exited: exit status 2". `limactl stop -f` recovers.
25新增:- vz: the VM runs in the hostagent, so it is killed with it, without a
26新增: shutdown (not tested).
27新增:
28新增:Reproduce, from a Go program, on Linux with the qemu driver:
29新增:
30新增: ctx, cancel := context.WithCancel(context.Background())
31新增: err := instance.Start(ctx, inst, false, false) // nil, instance Running
32新增: cancel()
33新增: time.Sleep(time.Second)
34新增: // store.Inspect: Broken; `ps -o ppid= -C qemu-system-x86_64`: 1
35新增:
36新增:Found in agent-vm, which embeds Lima: on Linux hosts its VMs became
37新增:Broken a few seconds to minutes after a start, when the command that
38新增:started them ended (closed terminal, SIGTERM, or a plain exit losing the
39新增:race). Tested there: with this patch the VM stays Running after the
40新增:starting program ends, cancelled context included, and the next start
41新增:works.
42新增:
43新增:The fix: exec.Command. ctx still bounds the wait for the hostagent to
44新增:come up (waitHostAgentStart, watchHostAgentEvents). A start cancelled
45新增:during that wait leaves the hostagent running, as an interrupted limactl
46新增:start does (the hostagent has its own process group,
47新增:BackgroundSysProcAttr, and the terminal's Ctrl-C does not reach it).
48新增:
49新增:No unit test: Lima's unit tests never start a hostagent. agent-vm's e2e
50新增:test (internal/cli/e2e_test.go) fails without it.
51新增:
52新增:Separate bug, to report on its own: the panic of the QEMU driver,
53新增:"panic: send on closed channel" in LimaQemuDriver.Start.func5
54新增:(pkg/driver/qemu/qemu_driver.go). When QEMU exits early, the goroutine
55新增:waiting on it closes qWaitCh and cancels the driver's context; the
56新增:ConfigureDriver goroutine then fails on that context and sends its
57新增:error on the closed qWaitCh. Already seen in #4645 (closed on its
58新增:Colima-specific part, the panic itself left unfixed). Sending with a
59新增:select on a done channel, or one closer for both goroutines, fixes it.
60新增:
61新增:Assisted-by: Claude Opus 5.5 <[email protected]>
62新增:---
63新增:diff --git a/pkg/instance/start.go b/pkg/instance/start.go
64新增:--- a/pkg/instance/start.go
65新增:+++ b/pkg/instance/start.go
66新增:@@ -291,7 +291,9 @@
67新增: args = append(args, "--progress")
68新增: }
69新增: args = append(args, inst.Name)
70新增:- haCmd = exec.CommandContext(ctx, limactl, args...)
71新增:+ // Not exec.CommandContext: the hostagent outlives this call, and os/exec
72新增:+ // would kill it whenever ctx ends, even after Start returned.
73新增:+ haCmd = exec.Command(limactl, args...)
74新增:
75新增: haCmd.SysProcAttr = executil.BackgroundSysProcAttr
76新增:
新增patches/lima/0007-qemu-features-own-outputs.patch+147 −0看文件
@@ -0,0 +1,147 @@
1新增:Subject: [PATCH] qemu: give each help request its own output
2新增:
3新增:inspectFeatures runs `qemu -accel help`, `-netdev help`, `-machine help` and
4新增:`-cpu help` into the same two buffers, and keeps each output as the buffer's
5新增:Bytes() after its run. NetdevHelp is the accelerators' text followed by the
6新增:netdevs', MachineHelp has both and its own, CPUHelp all four. The features
7新增:are searched as text (strings.Contains): a word of an earlier help can match
8新增:a later one's feature.
9新增:
10新增:Each request has its own buffers now (qemuHelp).
11新增:
12新增:Test: TestInspectFeaturesOwnOutputs.
13新增:
14新增:---
15新增:diff --git a/pkg/driver/qemu/features_test.go b/pkg/driver/qemu/features_test.go
16新增:new file mode 100644
17新增:index 00000000..16228077
18新增:--- /dev/null
19新增:+++ b/pkg/driver/qemu/features_test.go
20新增:@@ -0,0 +1,36 @@
21新增:+//go:build !windows
22新增:+
23新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors
24新增:+// SPDX-License-Identifier: Apache-2.0
25新增:+
26新增:+package qemu
27新增:+
28新增:+import (
29新增:+ "context"
30新增:+ "os"
31新增:+ "path/filepath"
32新增:+ "testing"
33新增:+
34新增:+ "gotest.tools/v3/assert"
35新增:+)
36新增:+
37新增:+// Each help text is its own: the features are searched as text, and a netdev
38新增:+// list holding the accelerators' words would match them.
39新增:+func TestInspectFeaturesOwnOutputs(t *testing.T) {
40新增:+ exe := filepath.Join(t.TempDir(), "qemu-fake")
41新增:+ script := `#!/bin/sh
42新增:+case "$*" in
43新增:+ *-cpu*) echo "cpus: max" ;;
44新增:+ *-accel*) echo "accels: tcg" ;;
45新增:+ *-netdev*) echo "netdevs: dgram" ;;
46新增:+ *-machine*) echo "machines: virt" ;;
47新增:+esac
48新增:+`
49新增:+ assert.NilError(t, os.WriteFile(exe, []byte(script), 0o755))
50新增:+ f, err := inspectFeatures(context.Background(), exe, "virt")
51新增:+ assert.NilError(t, err)
52新增:+ assert.Equal(t, string(f.AccelHelp), "accels: tcg\n")
53新增:+ assert.Equal(t, string(f.NetdevHelp), "netdevs: dgram\n")
54新增:+ assert.Equal(t, string(f.MachineHelp), "machines: virt\n")
55新增:+ assert.Equal(t, string(f.CPUHelp), "cpus: max\n")
56新增:+}
57新增:diff --git a/pkg/driver/qemu/qemu.go b/pkg/driver/qemu/qemu.go
58新增:index 1bb7bccf..79318857 100644
59新增:--- a/pkg/driver/qemu/qemu.go
60新增:+++ b/pkg/driver/qemu/qemu.go
61新增:@@ -310,61 +310,40 @@ type features struct {
62新增: }
63新增:
64新增: func inspectFeatures(ctx context.Context, exe, machine string) (*features, error) {
65新增:- var (
66新增:- f features
67新增:- stdout bytes.Buffer
68新增:- stderr bytes.Buffer
69新增:- )
70新增:- cmd := exec.CommandContext(ctx, exe, "-M", "none", "-accel", "help")
71新增:- cmd.Stdout = &stdout
72新增:- cmd.Stderr = &stderr
73新增:- if err := cmd.Run(); err != nil {
74新增:- return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
75新增:+ var f features
76新增:+ var err error
77新增:+ if f.AccelHelp, err = qemuHelp(ctx, exe, "-M", "none", "-accel", "help"); err != nil {
78新增:+ return nil, err
79新增: }
80新增:- f.AccelHelp = stdout.Bytes()
81新增:- // on older versions qemu will write "help" output to stderr
82新增:- if len(f.AccelHelp) == 0 {
83新增:- f.AccelHelp = stderr.Bytes()
84新增:+ if f.NetdevHelp, err = qemuHelp(ctx, exe, "-M", "none", "-netdev", "help"); err != nil {
85新增:+ logrus.Warn(err)
86新增: }
87新增:-
88新增:- cmd = exec.CommandContext(ctx, exe, "-M", "none", "-netdev", "help")
89新增:- cmd.Stdout = &stdout
90新增:- cmd.Stderr = &stderr
91新增:- if err := cmd.Run(); err != nil {
92新增:- logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
93新增:- } else {
94新增:- f.NetdevHelp = stdout.Bytes()
95新增:- if len(f.NetdevHelp) == 0 {
96新增:- f.NetdevHelp = stderr.Bytes()
97新增:- }
98新增:+ if f.MachineHelp, err = qemuHelp(ctx, exe, "-machine", "help"); err != nil {
99新增:+ logrus.Warn(err)
100新增: }
101新增:-
102新增:- cmd = exec.CommandContext(ctx, exe, "-machine", "help")
103新增:- cmd.Stdout = &stdout
104新增:- cmd.Stderr = &stderr
105新增:- if err := cmd.Run(); err != nil {
106新增:- logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
107新增:- } else {
108新增:- f.MachineHelp = stdout.Bytes()
109新增:- if len(f.MachineHelp) == 0 {
110新增:- f.MachineHelp = stderr.Bytes()
111新增:- }
112新增:+ // Avoid error: "No machine specified, and there is no default"
113新增:+ if f.CPUHelp, err = qemuHelp(ctx, exe, "-cpu", "help", "-machine", machine); err != nil {
114新增:+ logrus.Warn(err)
115新增: }
116新增:+ return &f, nil
117新增:+}
118新增:
119新增:- // Avoid error: "No machine specified, and there is no default"
120新增:- cmd = exec.CommandContext(ctx, exe, "-cpu", "help", "-machine", machine)
121新增:+// qemuHelp is what exe prints for args, a help request. Each one has its own
122新增:+// buffers: the features are searched as text, and one holding another's
123新增:+// output would match words that are not its own.
124新增:+func qemuHelp(ctx context.Context, exe string, args ...string) ([]byte, error) {
125新增:+ var stdout, stderr bytes.Buffer
126新增:+ cmd := exec.CommandContext(ctx, exe, args...)
127新增: cmd.Stdout = &stdout
128新增: cmd.Stderr = &stderr
129新增: if err := cmd.Run(); err != nil {
130新增:- logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
131新增:- } else {
132新增:- f.CPUHelp = stdout.Bytes()
133新增:- if len(f.CPUHelp) == 0 {
134新增:- f.CPUHelp = stderr.Bytes()
135新增:- }
136新增:+ return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
137新增: }
138新增:-
139新增:- return &f, nil
140新增:+ // on older versions qemu will write "help" output to stderr
141新增:+ if stdout.Len() == 0 {
142新增:+ return stderr.Bytes(), nil
143新增:+ }
144新增:+ return stdout.Bytes(), nil
145新增: }
146新增:
147新增: // adjustMemBytesDarwinARM64HVF adjusts the memory to be <= 3 GiB, only when the following conditions are met:
新增patches/lima/0008-qemu-dgram-netdev.patch+541 −0看文件
@@ -0,0 +1,541 @@
1新增:Subject: [PATCH] qemu: connect the instance's netstack through the dgram netdev
2新增:
3新增:startUsernet gives QEMU its own gvisor-tap-vsock netstack through the
4新增:`socket` netdev (a length-prefixed stream on a unix socket). That netdev,
5新增:like `stream`, aborts QEMU in this case: net_socket_send() and
6新增:net_stream_data_send() ignore a recv() that fails with EWOULDBLOCK, but
7新增:then fall through to net_fill_rstate(rs, buf, size) with size == -1,
8新增:which skips its loop and fails `assert(size == 0)`:
9新增:
10新增: qemu-system-x86_64: ../net/net.c:2172: net_fill_rstate: Assertion
11新增: `size == 0' failed.
12新增:
13新增:QEMU exits with SIGABRT, the hostagent stops the instance, and the guest
14新增:loses its network in the middle of what it was doing (an apt install, in
15新增:agent-vm). It happens on Linux hosts with KVM, under sustained traffic,
16新增:with QEMU 10.2.x, to everyone whose guest goes through that netstack
17新增:(Lima's user-v2 network, Colima: qemu-project/qemu#3285,
18新增:estuary/flow#3267). What makes recv() return EAGAIN after poll() said
19新增:readable is not known. The fault is QEMU's: a unix stream socket whose
20新增:only pending data is an out-of-band byte does the same, with no netstack
21新增:(`-netdev socket,fd=N` or `-netdev stream`, the peer sends one MSG_OOB
22新增:byte).
23新增:
24新增:The dgram netdev (QEMU 7.2 or later) returns on any failed recv() and has
25新增:no framing to lose. With it, the netstack is served on a datagram
26新增:socketpair, as vz does for its network (createSockPair, AcceptBess): one
27新增:end is passed to QEMU (-netdev dgram,local.type=fd), the other is
28新增:served by usernet.GVisorNetstackOpts.DgramConn. A unix datagram socket
29新增:keeps frame boundaries and loses nothing: a full buffer blocks the
30新增:sender, and QEMU stops reading until it can write.
31新增:
32新增:Which one QEMU gets is decided by Cmdline, from the netdevs it lists, and
33新增:the netstack starts after it: it listens on the unix socket only for the
34新增:socket netdev, of a QEMU without dgram. Windows has no unix datagram
35新增:sockets and no file descriptor passing: it keeps the stream netdev, so the
36新增:abort remains possible there.
37新增:
38新增:Tests: TestDgramConn (a frame sent as a datagram is answered by the
39新增:netstack; it times out without DgramConn being served), TestDgramPair,
40新增:TestFdDgramTemplate. The netdev choice in Cmdline needs a QEMU binary:
41新增:checked by agent-vm's e2e (internal/vm/lima_e2e_test.go), whose guest
42新增:boots and installs packages through it.
43新增:
44新增:---
45新增:diff --git a/pkg/driver/qemu/dgram_unix.go b/pkg/driver/qemu/dgram_unix.go
46新增:new file mode 100644
47新增:index 00000000..e1be774c
48新增:--- /dev/null
49新增:+++ b/pkg/driver/qemu/dgram_unix.go
50新增:@@ -0,0 +1,45 @@
51新增:+//go:build !windows
52新增:+
53新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors
54新增:+// SPDX-License-Identifier: Apache-2.0
55新增:+
56新增:+package qemu
57新增:+
58新增:+import (
59新增:+ "net"
60新增:+ "os"
61新增:+ "syscall"
62新增:+)
63新增:+
64新增:+// dgramPair returns the two ends of a connected datagram socket, as vz does
65新增:+// for its network: ours as a net.Conn for the netstack, and QEMU's as a file
66新增:+// to pass to it (-netdev dgram,local.type=fd). A datagram is a frame, and
67新增:+// unix datagram sockets neither lose nor reorder them: a full buffer blocks
68新增:+// the sender.
69新增:+func dgramPair() (ours net.Conn, qemu *os.File, err error) {
70新增:+ // The descriptors must not leak into the processes started meanwhile:
71新增:+ // QEMU gets its end through ExtraFiles.
72新增:+ syscall.ForkLock.RLock()
73新增:+ fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
74新增:+ if err == nil {
75新增:+ syscall.CloseOnExec(fds[0])
76新增:+ syscall.CloseOnExec(fds[1])
77新增:+ }
78新增:+ syscall.ForkLock.RUnlock()
79新增:+ if err != nil {
80新增:+ return nil, nil, err
81新增:+ }
82新增:+ for _, fd := range fds {
83新增:+ // Best effort: the kernel caps these (net.core.wmem_max, rmem_max).
84新增:+ _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 1<<20)
85新增:+ _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 4<<20)
86新增:+ }
87新增:+ f := os.NewFile(uintptr(fds[0]), "usernet-dgram")
88新增:+ defer f.Close()
89新增:+ ours, err = net.FileConn(f)
90新增:+ if err != nil {
91新增:+ syscall.Close(fds[1])
92新增:+ return nil, nil, err
93新增:+ }
94新增:+ return ours, os.NewFile(uintptr(fds[1]), "qemu-dgram"), nil
95新增:+}
96新增:diff --git a/pkg/driver/qemu/dgram_unix_test.go b/pkg/driver/qemu/dgram_unix_test.go
97新增:new file mode 100644
98新增:index 00000000..c6b1fb04
99新增:--- /dev/null
100新增:+++ b/pkg/driver/qemu/dgram_unix_test.go
101新增:@@ -0,0 +1,56 @@
102新增:+//go:build !windows
103新增:+
104新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors
105新增:+// SPDX-License-Identifier: Apache-2.0
106新增:+
107新增:+package qemu
108新增:+
109新增:+import (
110新增:+ "net"
111新增:+ "testing"
112新增:+
113新增:+ "gotest.tools/v3/assert"
114新增:+)
115新增:+
116新增:+// Each write is one datagram, both ways, and QEMU's end is a file that stays
117新增:+// usable once ours is a net.Conn.
118新增:+func TestDgramPair(t *testing.T) {
119新增:+ ours, qemu, err := dgramPair()
120新增:+ assert.NilError(t, err)
121新增:+ t.Cleanup(func() { ours.Close(); qemu.Close() })
122新增:+ theirs, err := net.FileConn(qemu)
123新增:+ assert.NilError(t, err)
124新增:+ t.Cleanup(func() { theirs.Close() })
125新增:+
126新增:+ for _, c := range []struct{ from, to net.Conn }{{ours, theirs}, {theirs, ours}} {
127新增:+ _, err = c.from.Write([]byte("abc"))
128新增:+ assert.NilError(t, err)
129新增:+ _, err = c.from.Write([]byte("defgh"))
130新增:+ assert.NilError(t, err)
131新增:+ buf := make([]byte, 64)
132新增:+ n, err := c.to.Read(buf)
133新增:+ assert.NilError(t, err)
134新增:+ assert.Equal(t, string(buf[:n]), "abc")
135新增:+ n, err = c.to.Read(buf)
136新增:+ assert.NilError(t, err)
137新增:+ assert.Equal(t, string(buf[:n]), "defgh")
138新增:+ }
139新增:+}
140新增:+
141新增:+// fd_dgram hands QEMU the datagram socket as the next file descriptor, after
142新增:+// those fd_connect made.
143新增:+func TestFdDgramTemplate(t *testing.T) {
144新增:+ _, qemu, err := dgramPair()
145新增:+ assert.NilError(t, err)
146新增:+ t.Cleanup(func() { qemu.Close() })
147新增:+
148新增:+ a := &qArgTemplateApplier{dgram: qemu}
149新增:+ got, err := a.applyTemplate("dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}")
150新增:+ assert.NilError(t, err)
151新增:+ assert.Equal(t, got, "dgram,id=net0,local.type=fd,local.str=3")
152新增:+ assert.DeepEqual(t, len(a.files), 1)
153新增:+ assert.Equal(t, a.files[0], qemu)
154新增:+
155新增:+ _, err = (&qArgTemplateApplier{}).applyTemplate("{{ fd_dgram }}")
156新增:+ assert.ErrorContains(t, err, "no datagram socket")
157新增:+}
158新增:diff --git a/pkg/driver/qemu/dgram_windows.go b/pkg/driver/qemu/dgram_windows.go
159新增:new file mode 100644
160新增:index 00000000..2f11d288
161新增:--- /dev/null
162新增:+++ b/pkg/driver/qemu/dgram_windows.go
163新增:@@ -0,0 +1,16 @@
164新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors
165新增:+// SPDX-License-Identifier: Apache-2.0
166新增:+
167新增:+package qemu
168新增:+
169新增:+import (
170新增:+ "errors"
171新增:+ "net"
172新增:+ "os"
173新增:+)
174新增:+
175新增:+// dgramPair: Windows has no unix datagram sockets, and cannot pass a file
176新增:+// descriptor to QEMU.
177新增:+func dgramPair() (net.Conn, *os.File, error) {
178新增:+ return nil, nil, errors.ErrUnsupported
179新增:+}
180新增:diff --git a/pkg/driver/qemu/qemu.go b/pkg/driver/qemu/qemu.go
181新增:index 79318857..bf55ddb3 100644
182新增:--- a/pkg/driver/qemu/qemu.go
183新增:+++ b/pkg/driver/qemu/qemu.go
184新增:@@ -50,6 +50,10 @@ type Config struct {
185新增: // UsernetQEMUSock is the QEMU socket of the instance's own gvisor
186新增: // netstack, used instead of slirp when set (see startUsernet).
187新增: UsernetQEMUSock string
188新增:+ // UsernetDgram is QEMU's end of a datagram socketpair whose other end the
189新增:+ // netstack serves, preferred to UsernetQEMUSock when QEMU has the dgram
190新增:+ // netdev (see dgramPair). Nil on Windows.
191新增:+ UsernetDgram *os.File
192新增: }
193新增:
194新增: // minimumQemuVersion returns hardMin and softMin.
195新增:@@ -788,11 +792,22 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er
196新增: case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows":
197新增: // No file descriptor passing there (fd_connect): QEMU connects to the
198新增: // socket itself, which QEMU 7.2 or later can on Windows. The same
199新增:- // stream as the socket netdev's.
200新增:+ // stream as the socket netdev's, so the same abort on EAGAIN (see the
201新增:+ // dgram netdev below): Windows has no datagram unix sockets.
202新增: if !strings.Contains(string(features.NetdevHelp), "stream") {
203新增: return "", nil, errors.New("QEMU 7.2 or later is needed (its stream netdev)")
204新增: }
205新增: args = append(args, "-netdev", fmt.Sprintf("stream,id=net0,server=off,addr.type=unix,addr.path=%s", cfg.UsernetQEMUSock))
206新增:+ case firstUsernetIndex == -1 && cfg.UsernetDgram != nil && strings.Contains(string(features.NetdevHelp), "dgram"):
207新增:+ // Not the socket netdev below: it reads a length-prefixed stream, and
208新增:+ // QEMU (10.2.4 at least) aborts with `net_fill_rstate: Assertion
209新增:+ // 'size == 0' failed` when its recv() returns EAGAIN, which it
210新增:+ // meant to ignore (net_socket_send, and net_stream_data_send for the
211新增:+ // stream netdev, fall through to net_fill_rstate with size -1).
212新增:+ // Seen on Linux hosts, under sustained guest traffic. The dgram
213新增:+ // netdev ignores a failed recv() and has no framing to lose. It
214新增:+ // needs QEMU 7.2 or later.
215新增:+ args = append(args, "-netdev", "dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}")
216新增: case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "":
217新增: args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", cfg.UsernetQEMUSock))
218新增: case firstUsernetIndex == -1:
219新增:diff --git a/pkg/driver/qemu/qemu_driver.go b/pkg/driver/qemu/qemu_driver.go
220新增:index 5a68db80..dba82218 100644
221新增:--- a/pkg/driver/qemu/qemu_driver.go
222新增:+++ b/pkg/driver/qemu/qemu_driver.go
223新增:@@ -67,40 +67,81 @@ type LimaQemuDriver struct {
224新增: usernetStop context.CancelFunc
225新增: }
226新增:
227新增:-// startUsernet starts the instance's own gvisor netstack, as vz does: one
228新增:-// network per instance, in the hostagent, where usernet.Outbound applies.
229新增:-func startUsernet(ctx context.Context, inst *limatype.Instance) (client *usernet.Client, qemuSock string, stop context.CancelFunc, err error) {
230新增:- endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
231新增:+// usernetSockets are what connects QEMU to the instance's own gvisor netstack
232新增:+// (see startUsernet). QEMU gets the dgram end, or the socket path when its
233新增:+// netdevs have no dgram (see Cmdline): the netstack listens on the path only
234新增:+// then, as nothing else should be able to connect to it.
235新增:+type usernetSockets struct {
236新增:+ endpoint string
237新增:+ // qemu is the path of the socket netdev's listener.
238新增:+ qemu string
239新增:+ // dgramConn is the netstack's end of a datagram socketpair, qemuDgram
240新增:+ // QEMU's. Both are nil on Windows.
241新增:+ dgramConn net.Conn
242新增:+ qemuDgram *os.File
243新增:+}
244新增:+
245新增:+func newUsernetSockets(inst *limatype.Instance) (*usernetSockets, error) {
246新增:+ endpoint, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
247新增: if err != nil {
248新增:- return nil, "", nil, err
249新增:+ return nil, err
250新增: }
251新增:- qemuSock, err = usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock)
252新增:+ qemu, err := usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock)
253新增: if err != nil {
254新增:- return nil, "", nil, err
255新增:+ return nil, err
256新增: }
257新增:- os.RemoveAll(endpointSock)
258新增:- os.RemoveAll(qemuSock)
259新增:- ctx, stop = context.WithCancel(ctx)
260新增:- err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{
261新增:- MTU: 1500,
262新增:- Endpoint: endpointSock,
263新增:- QemuSocket: qemuSock,
264新增:- Async: true,
265新增:+ os.RemoveAll(endpoint)
266新增:+ os.RemoveAll(qemu)
267新增:+ s := &usernetSockets{endpoint: endpoint, qemu: qemu}
268新增:+ s.dgramConn, s.qemuDgram, err = dgramPair()
269新增:+ if err != nil && !errors.Is(err, errors.ErrUnsupported) {
270新增:+ return nil, err
271新增:+ }
272新增:+ return s, nil
273新增:+}
274新增:+
275新增:+// closeQEMUEnd closes the file given to QEMU: it has its own copy once started.
276新增:+func (s *usernetSockets) closeQEMUEnd() {
277新增:+ if s.qemuDgram != nil {
278新增:+ s.qemuDgram.Close()
279新增:+ }
280新增:+}
281新增:+
282新增:+// startUsernet starts the instance's own gvisor netstack, as vz does: one
283新增:+// network per instance, in the hostagent, where usernet.Outbound applies.
284新增:+// viaDgram says which end QEMU was given.
285新增:+func startUsernet(ctx context.Context, inst *limatype.Instance, s *usernetSockets, viaDgram bool) (client *usernet.Client, stop context.CancelFunc, err error) {
286新增:+ opts := &usernet.GVisorNetstackOpts{
287新增:+ MTU: 1500,
288新增:+ Endpoint: s.endpoint,
289新增:+ Async: true,
290新增: DefaultLeases: map[string]string{
291新增: networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir),
292新增: },
293新增: Subnet: networks.SlirpNetwork,
294新增:- })
295新增:- if err != nil {
296新增:- stop()
297新增:- return nil, "", nil, err
298新增: }
299新增:- subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork)
300新增:- if err != nil {
301新增:- stop()
302新增:- return nil, "", nil, err
303新增:+ if viaDgram {
304新增:+ opts.DgramConn = s.dgramConn
305新增:+ } else {
306新增:+ opts.QemuSocket = s.qemu
307新增:+ if s.dgramConn != nil {
308新增:+ s.dgramConn.Close()
309新增:+ }
310新增: }
311新增:- return usernet.NewClient(endpointSock, subnetIP), qemuSock, stop, nil
312新增:+ ctx, stop = context.WithCancel(ctx)
313新增:+ err = usernet.StartGVisorNetstack(ctx, opts)
314新增:+ if err == nil {
315新增:+ var subnetIP net.IP
316新增:+ subnetIP, _, err = net.ParseCIDR(networks.SlirpNetwork)
317新增:+ if err == nil {
318新增:+ return usernet.NewClient(s.endpoint, subnetIP), stop, nil
319新增:+ }
320新增:+ }
321新增:+ stop()
322新增:+ if viaDgram {
323新增:+ s.dgramConn.Close()
324新增:+ }
325新增:+ return nil, nil, err
326新增: }
327新增:
328新增: var _ driver.Driver = (*LimaQemuDriver)(nil)
329新增:@@ -365,22 +406,40 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
330新增: SSHAddress: l.Instance.SSHAddress,
331新增: VirtioGA: l.virtioPort != "",
332新增: }
333新增:+ // The netstack starts once Cmdline has chosen how QEMU reaches it.
334新增:+ var socks *usernetSockets
335新增: if limayaml.FirstUsernetIndex(l.Instance.Config) == -1 {
336新增:- client, sock, stop, err := startUsernet(ctx, l.Instance)
337新增:+ var err error
338新增:+ if socks, err = newUsernetSockets(l.Instance); err != nil {
339新增:+ return nil, err
340新增:+ }
341新增:+ qCfg.UsernetQEMUSock, qCfg.UsernetDgram = socks.qemu, socks.qemuDgram
342新增:+ defer socks.closeQEMUEnd()
343新增:+ }
344新增:+ netstackStarted := false
345新增:+ defer func() {
346新增:+ if socks != nil && socks.dgramConn != nil && !netstackStarted {
347新增:+ socks.dgramConn.Close()
348新增:+ }
349新增:+ }()
350新增:+ qExe, qArgs, err := Cmdline(ctx, qCfg)
351新增:+ if err != nil {
352新增:+ return nil, err
353新增:+ }
354新增:+ if socks != nil {
355新增:+ viaDgram := slices.ContainsFunc(qArgs, func(a string) bool { return strings.HasPrefix(a, "dgram,id=net0,") })
356新增:+ client, stop, err := startUsernet(ctx, l.Instance, socks, viaDgram)
357新增: if err != nil {
358新增: return nil, err
359新增: }
360新增:- l.usernetClient, l.usernetStop, qCfg.UsernetQEMUSock = client, stop, sock
361新增:+ netstackStarted = true
362新增:+ l.usernetClient, l.usernetStop = client, stop
363新增: defer func() {
364新增: if l.qCmd == nil {
365新增: stop()
366新增: }
367新增: }()
368新增: }
369新增:- qExe, qArgs, err := Cmdline(ctx, qCfg)
370新增:- if err != nil {
371新增:- return nil, err
372新增:- }
373新增:
374新增: var vhostCmds []*exec.Cmd
375新增: if *l.Instance.Config.MountType == limatype.VIRTIOFS {
376新增:@@ -400,7 +459,7 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
377新增: }
378新增:
379新增: var qArgsFinal []string
380新增:- applier := &qArgTemplateApplier{}
381新增:+ applier := &qArgTemplateApplier{dgram: qCfg.UsernetDgram}
382新增: for _, unapplied := range qArgs {
383新增: applied, err := applier.applyTemplate(unapplied)
384新增: if err != nil {
385新增:@@ -900,6 +959,8 @@ func (l *LimaQemuDriver) GuestAgentConn(ctx context.Context) (net.Conn, string,
386新增:
387新增: type qArgTemplateApplier struct {
388新增: files []*os.File
389新增:+ // dgram is the file fd_dgram passes to QEMU.
390新增:+ dgram *os.File
391新增: }
392新增:
393新增: func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
394新增:@@ -938,6 +999,13 @@ func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
395新增: }
396新增: return res
397新增: },
398新增:+ "fd_dgram": func() (string, error) {
399新增:+ if a.dgram == nil {
400新增:+ return "", errors.New("fd_dgram: no datagram socket")
401新增:+ }
402新增:+ a.files = append(a.files, a.dgram)
403新增:+ return strconv.Itoa(len(a.files) + 2), nil
404新增:+ },
405新增: }
406新增: tmpl, err := template.New("").Funcs(funcMap).Parse(qArg)
407新增: if err != nil {
408新增:diff --git a/pkg/networks/usernet/dgram_test.go b/pkg/networks/usernet/dgram_test.go
409新增:new file mode 100644
410新增:index 00000000..01782a14
411新增:--- /dev/null
412新增:+++ b/pkg/networks/usernet/dgram_test.go
413新增:@@ -0,0 +1,82 @@
414新增:+//go:build !windows
415新增:+
416新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors
417新增:+// SPDX-License-Identifier: Apache-2.0
418新增:+
419新增:+package usernet
420新增:+
421新增:+import (
422新增:+ "bytes"
423新增:+ "context"
424新增:+ "net"
425新增:+ "os"
426新增:+ "path/filepath"
427新增:+ "syscall"
428新增:+ "testing"
429新增:+ "time"
430新增:+
431新增:+ "gotest.tools/v3/assert"
432新增:+)
433新增:+
434新增:+// A frame sent as a datagram is served by the netstack, and the answer comes
435新增:+// back as one: an ARP request for the gateway gets its reply.
436新增:+func TestDgramConn(t *testing.T) {
437新增:+ dir, err := os.MkdirTemp("", "usernet")
438新增:+ assert.NilError(t, err)
439新增:+ t.Cleanup(func() { os.RemoveAll(dir) })
440新增:+
441新增:+ fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
442新增:+ assert.NilError(t, err)
443新增:+ serverFile, peerFile := os.NewFile(uintptr(fds[0]), "server"), os.NewFile(uintptr(fds[1]), "peer")
444新增:+ server, err := net.FileConn(serverFile)
445新增:+ assert.NilError(t, err)
446新增:+ peer, err := net.FileConn(peerFile)
447新增:+ assert.NilError(t, err)
448新增:+ serverFile.Close()
449新增:+ peerFile.Close()
450新增:+ t.Cleanup(func() { peer.Close() })
451新增:+
452新增:+ ctx, cancel := context.WithCancel(context.Background())
453新增:+ t.Cleanup(cancel)
454新增:+ err = StartGVisorNetstack(ctx, &GVisorNetstackOpts{
455新增:+ MTU: 1500,
456新增:+ Endpoint: filepath.Join(dir, "ep.sock"),
457新增:+ DgramConn: server,
458新增:+ Async: true,
459新增:+ Subnet: "192.168.5.0/24",
460新增:+ })
461新增:+ assert.NilError(t, err)
462新增:+
463新增:+ guestMAC := net.HardwareAddr{0x52, 0x54, 0x00, 0x00, 0x00, 0x01}
464新增:+ gatewayMAC, err := net.ParseMAC(gatewayMacAddr)
465新增:+ assert.NilError(t, err)
466新增:+ arp := bytes.Join([][]byte{
467新增:+ {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, guestMAC, {0x08, 0x06}, // Ethernet: broadcast, ARP
468新增:+ {0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01}, // Ethernet, IPv4, request
469新增:+ guestMAC, {192, 168, 5, 15},
470新增:+ make([]byte, 6), {192, 168, 5, 2}, // who has the gateway
471新增:+ }, nil)
472新增:+ _, err = peer.Write(arp)
473新增:+ assert.NilError(t, err)
474新增:+
475新增:+ buf := make([]byte, 2048)
476新增:+ assert.NilError(t, peer.SetReadDeadline(time.Now().Add(10*time.Second)))
477新增:+ n, err := peer.Read(buf)
478新增:+ assert.NilError(t, err)
479新增:+ reply := buf[:n]
480新增:+ assert.Assert(t, n >= 42, "frame of %d bytes", n)
481新增:+ assert.DeepEqual(t, reply[0:6], []byte(guestMAC))
482新增:+ assert.DeepEqual(t, reply[6:12], []byte(gatewayMAC))
483新增:+ assert.DeepEqual(t, reply[12:14], []byte{0x08, 0x06})
484新增:+ assert.DeepEqual(t, reply[20:22], []byte{0x00, 0x02}) // ARP reply
485新增:+
486新增:+ // The connection ends with the netstack's context.
487新增:+ cancel()
488新增:+ assert.NilError(t, peer.SetWriteDeadline(time.Now().Add(10*time.Second)))
489新增:+ _, err = peer.Write(arp)
490新增:+ for i := 0; err == nil && i < 100; i++ {
491新增:+ time.Sleep(50 * time.Millisecond)
492新增:+ _, err = peer.Write(arp)
493新增:+ }
494新增:+ assert.ErrorContains(t, err, "")
495新增:+}
496新增:diff --git a/pkg/networks/usernet/gvproxy.go b/pkg/networks/usernet/gvproxy.go
497新增:index 05c30cad..1ce63e30 100644
498新增:--- a/pkg/networks/usernet/gvproxy.go
499新增:+++ b/pkg/networks/usernet/gvproxy.go
500新增:@@ -33,6 +33,11 @@ type GVisorNetstackOpts struct {
501新增: FdSocket string
502新增: Endpoint string
503新增:
504新增:+ // DgramConn is one end of a datagram socketpair, whose other end is
505新增:+ // QEMU's dgram netdev: one raw Ethernet frame per datagram. The netstack
506新增:+ // closes it when its context ends.
507新增:+ DgramConn net.Conn
508新增:+
509新增: Subnet string
510新增:
511新增: Async bool
512新增:@@ -160,9 +165,29 @@ func run(ctx context.Context, g *errgroup.Group, configuration *types.Configurat
513新增: return err
514新增: }
515新增: }
516新增:+ if opts.DgramConn != nil {
517新增:+ serveDgram(ctx, vn, opts.DgramConn)
518新增:+ }
519新增: return nil
520新增: }
521新增:
522新增:+// serveDgram serves the netstack on conn, until ctx ends. Frames are the
523新增:+// datagrams: there is no length prefix to lose track of, as with QEMU's
524新增:+// socket and stream netdevs.
525新增:+func serveDgram(ctx context.Context, vn *virtualnetwork.VirtualNetwork, conn net.Conn) {
526新增:+ ctx, cancel := context.WithCancel(ctx)
527新增:+ go func() {
528新增:+ <-ctx.Done()
529新增:+ conn.Close()
530新增:+ }()
531新增:+ go func() {
532新增:+ defer cancel()
533新增:+ if err := vn.AcceptBess(ctx, &UDPFileConn{Conn: conn}); err != nil && ctx.Err() == nil {
534新增:+ logrus.Error("QEMU datagram connection closed with error: ", err)
535新增:+ }
536新增:+ }()
537新增:+}
538新增:+
539新增: func listenQEMU(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error {
540新增: var lc net.ListenConfig
541新增: listener, err := lc.Listen(ctx, "unix", opts.QemuSocket)
新增patches/lima/0009-start-channels-buffered.patch+34 −0看文件
@@ -0,0 +1,34 @@
1新增:Subject: [PATCH] instance: do not leave goroutines blocked after Start returns
2新增:
3新增:StartWithPaths races two goroutines (the hostagent's events and its exit)
4新增:on unbuffered channels and returns on the first. The loser blocks on its
5新增:send for as long as the program lives: one goroutine per start in a program
6新增:that outlives the call (limactl exits, so it does not show there). The
7新增:channels hold one value, so the sends complete; the exit goroutine also
8新增:finishes its Wait, which reaps the hostagent when it ends.
9新增:
10新增:No test: StartWithPaths starts a hostagent, which Lima's unit tests do not.
11新增:
12新增:---
13新增:diff --git a/pkg/instance/start.go b/pkg/instance/start.go
14新增:index 0c70232a..489df5f9 100644
15新增:--- a/pkg/instance/start.go
16新增:+++ b/pkg/instance/start.go
17新增:@@ -319,12 +319,15 @@ func StartWithPaths(ctx context.Context, inst *limatype.Instance, launchHostAgen
18新增: return err
19新增: }
20新增:
21新增:- watchErrCh := make(chan error)
22新增:+ // Buffered: the goroutine that loses the race below must not block on its
23新增:+ // send for as long as the program lives (it would, once StartWithPaths
24新增:+ // has returned).
25新增:+ watchErrCh := make(chan error, 1)
26新增: go func() {
27新增: watchErrCh <- watchHostAgentEvents(ctx, inst, haStdoutPath, haStderrPath, begin, showProgress)
28新增: close(watchErrCh)
29新增: }()
30新增:- waitErrCh := make(chan error)
31新增:+ waitErrCh := make(chan error, 1)
32新增: if haCmd != nil {
33新增: go func() {
34新增: waitErrCh <- haCmd.Wait()
修改release.sh+62 −2看文件
@@ -30,7 +30,11 @@
3030# SHA256SUMS. Each tarball holds that platform's binary, agent-vm, built
3131# here from the tag, agent-vm.sh, and LICENSE, NOTICE and
3232# THIRD_PARTY_LICENSES: the curl installer takes the one of the
33删除:# machine, unpacks it and runs `agent-vm.sh install`. The release is
33新增:# machine, unpacks it and runs `agent-vm.sh install`. The Linux builds
34新增:# also come as agent-vm_X.Y.Z_<arch>.deb and agent-vm-X.Y.Z-1.<arch>.rpm
35新增:# (packaging/nfpm.yaml; nfpm is built with Go at a pinned version, or
36新增:# AGENT_VM_NFPM names a binary), listed in SHA256SUMS after the tarballs.
37新增:# The release is
3438# created as a draft, its assets are downloaded back and compared with
3539# the local ones, and only then is it published; then the published
3640# assets are downloaded once more and checked against SHA256SUMS (and
@@ -153,9 +157,45 @@ package() {
153157 "$src/README.md" "$src/CHANGELOG.md" "$src/runtime.example.sh" "$stage/"
154158 [ "$os" != windows ] || [ -z "${AGENT_VM_WINDOWS_PFX:-}" ] || sign_windows "$stage/$bin" "$out"
155159 make_tarball "$out/agent-vm-$version-$p.tar.gz" "$out/stage-$p" "agent-vm-$version"
160新增: [ "$os" != linux ] || linux_packages "$ref" "$version" "$out" "$arch" "$stage"
156161 done
157162}
158163
164新增:# nfpm, which makes the .deb and .rpm: AGENT_VM_NFPM names a binary, else the
165新增:# pinned version is built with Go (once, into $WORK/bin).
166新增:NFPM_VERSION=v2.48.0
167新增:nfpm_bin() {
168新增: if [ -n "${AGENT_VM_NFPM:-}" ]; then echo "$AGENT_VM_NFPM"; return; fi
169新增: local bin="$WORK/bin/nfpm"
170新增: if [ ! -x "$bin" ]; then
171新增: ( cd "$WORK" && GOWORK=off GOBIN="$WORK/bin" go install "github.com/goreleaser/nfpm/v2/cmd/nfpm@$NFPM_VERSION" ) >"$WORK/nfpm-build.log" 2>&1 \
172新增: || { tail -n 20 "$WORK/nfpm-build.log" >&2; die "could not build nfpm $NFPM_VERSION (or set AGENT_VM_NFPM)"; }
173新增: fi
174新增: echo "$bin"
175新增:}
176新增:
177新增:# linux_packages <ref> <version> <outdir> <goarch> <stagedir>: in outdir,
178新增:# agent-vm_<version>_<goarch>.deb and agent-vm-<version>-1.<arch>.rpm, from
179新增:# packaging/nfpm.yaml and the files of the tarball's folder. The dates inside
180新增:# are the commit's, so the same commit gives the same packages.
181新增:linux_packages() {
182新增: local ref="$1" version="$2" out="$3" goarch="$4" stage="$5" nfpm rpmarch qdeb qrpm
183新增: case "$goarch" in
184新增: amd64) rpmarch=x86_64; qdeb=qemu-system-x86; qrpm=qemu-system-x86-core ;;
185新增: arm64) rpmarch=aarch64; qdeb=qemu-system-arm; qrpm=qemu-system-aarch64-core ;;
186新增: *) die "no .deb or .rpm for $goarch" ;;
187新增: esac
188新增: nfpm="$(nfpm_bin)"
189新增: echo " packaging linux-$goarch (.deb, .rpm)"
190新增: local vars=(GOARCH="$goarch" VERSION="$version" QEMU_DEB="$qdeb" QEMU_RPM="$qrpm"
191新增: SOURCE_DATE_EPOCH="$(git -C "$REPO_DIR" log -1 --format=%ct "$ref")")
192新增: ( cd "$stage" \
193新增: && env "${vars[@]}" "$nfpm" package -f "$out/src/packaging/nfpm.yaml" -p deb -t "$out/agent-vm_${version}_${goarch}.deb" \
194新增: && env "${vars[@]}" "$nfpm" package -f "$out/src/packaging/nfpm.yaml" -p rpm -t "$out/agent-vm-${version}-1.${rpmarch}.rpm" ) \
195新增: >"$out/nfpm-$goarch.log" 2>&1 || { tail -n 20 "$out/nfpm-$goarch.log" >&2; die "packaging linux-$goarch failed: $out/nfpm-$goarch.log"; }
196新增: printf '%s\n' "agent-vm_${version}_${goarch}.deb" "agent-vm-${version}-1.${rpmarch}.rpm" >> "$out/packages.list"
197新增:}
198新增:
159199# make_tarball <tarball> <dir> <name>: <name> of <dir> as a tarball owned by
160200# root (numeric ids), with no extended attributes and no AppleDouble files
161201# (macOS's bsdtar adds both), and a gzip header without a date. GNU tar and
@@ -412,6 +452,15 @@ for f in LICENSE NOTICE THIRD_PARTY_LICENSES; do
412452done
413453ok "LICENSE, NOTICE and THIRD_PARTY_LICENSES are there"
414454
455新增:# flake.nix's vendorHash is of the Go dependencies: it notes the checksum of
456新增:# go.mod and go.sum it was made for.
457新增:if [ -f flake.nix ]; then
458新增: mods="$(cat go.mod go.sum | sha256_of /dev/stdin)"
459新增: grep -q "go.mod+go.sum: $mods\$" flake.nix \
460新增: || die "flake.nix's vendorHash is not for this go.mod and go.sum: update it and its 'go.mod+go.sum: $mods' line (see the comment there)"
461新增: ok "flake.nix's vendorHash is for this go.mod and go.sum"
462新增:fi
463新增:
415464# --- 3. tests ------------------------------------------------------------------
416465# CI is the authority: it runs on Linux, macOS and Windows.
417466# --bypass-checks skips the workflow only: the checks above decide what the
@@ -490,6 +539,16 @@ for p in $PLATFORMS; do
490539 assets+=("$WORK/$f")
491540 ok "$f: $(du -h "$WORK/$f" | cut -f1), sha256 $sha"
492541done
542新增:# The Linux packages, after the tarballs: the installer reads only the
543新增:# tarballs' lines of SHA256SUMS.
544新增:if [ -f "$WORK/packages.list" ]; then
545新增: while read -r f; do
546新增: sha="$(sha256_of "$WORK/$f")"
547新增: printf '%s %s\n' "$sha" "$f" >> "$WORK/SHA256SUMS"
548新增: assets+=("$WORK/$f")
549新增: ok "$f: $(du -h "$WORK/$f" | cut -f1), sha256 $sha"
550新增: done < "$WORK/packages.list"
551新增:fi
493552if [ -n "${AGENT_VM_MINISIGN_KEY:-}" ]; then
494553 # Prompts for the key's password, on the terminal.
495554 if [ -z "$DRY_RUN" ]; then
@@ -529,6 +588,7 @@ SMOKE_FAILED=""
529588echo
530589echo "Homebrew formula, per platform (each tarball's agent-vm is the binary):"
531590while read -r sha f; do
591新增: case "$f" in *.tar.gz) ;; *) continue ;; esac
532592 echo " url \"$BASE/$f\""
533593 echo " sha256 \"$sha\""
534594done < "$WORK/SHA256SUMS"
@@ -545,7 +605,7 @@ if [ -n "${AGENT_VM_TAP:-}" ]; then
545605 # sha256 after it that tarball's. A `bottle do` block has sha256 lines
546606 # of its own, after no url: left alone.
547607 awk -v base="$BASE" -v version="$VERSION" -v sums="$WORK/SHA256SUMS" '
548删除: BEGIN { while ((getline l < sums) > 0) { split(l, a, " "); p = a[2]; sub(/^agent-vm-[0-9.]+-/, "", p); sub(/\.tar\.gz$/, "", p); sha[p] = a[1] } }
608新增: BEGIN { while ((getline l < sums) > 0) { split(l, a, " "); p = a[2]; if (p !~ /\.tar\.gz$/) continue; sub(/^agent-vm-[0-9.]+-/, "", p); sub(/\.tar\.gz$/, "", p); sha[p] = a[1] } }
549609 /^[[:space:]]*url / {
550610 for (p in sha) if (index($0, "-" p ".tar.gz")) {
551611 sub(/url .*/, "url \"" base "/agent-vm-" version "-" p ".tar.gz\""); want = p
修改tests/fuzz/go.work+1 −1看文件
@@ -1,7 +1,7 @@
11// `go test -fuzz` only fuzzes the main modules: this workspace makes the
22// vendored sshocker and pkg/sftp ones too (make fuzz). Not Lima: as a main
33// module, its own requirements (its MCP server's) would take part in the build.
4删除:go 1.26.9
4新增:go 1.26.10
55
66use (
77 ../..
修改tests/release.sh+33 −5看文件
@@ -75,7 +75,7 @@ RR="$SB/repo"; RO="$SB/origin.git"; RB="$SB/bin"
7575mkdir -p "$RR/www/public" "$RB"
7676cp -R "$SELF_DIR/release.sh" "$SELF_DIR/agent-vm.sh" "$SELF_DIR/agent-vm.setup.sh" "$SELF_DIR/runtime.example.sh" \
7777 "$SELF_DIR/LICENSE" "$SELF_DIR/NOTICE" "$SELF_DIR/THIRD_PARTY_LICENSES" "$SELF_DIR/README.md" \
78删除: "$SELF_DIR/tests" "$SELF_DIR/scripts" "$RR/"
78新增: "$SELF_DIR/tests" "$SELF_DIR/scripts" "$SELF_DIR/packaging" "$RR/"
7979cp "$SELF_DIR/www/public/install.sh" "$RR/www/public/"
8080printf 'NEXT_VERSION := %s\n' "$V" > "$RR/Makefile"
8181printf '# Changelog\n\n## %s\n\n- notes\n' "$V" > "$RR/CHANGELOG.md"
@@ -95,7 +95,7 @@ case "\$1 \$2" in
9595 "release create")
9696 echo "\$*" > "$SB/gh-create.log"
9797 mkdir -p "$SB/assets"
98删除: for a in "\$@"; do case "\$a" in *.tar.gz|*SHA256SUMS|*.minisig) cp "\$a" "$SB/assets/" ;; esac; done
98新增: for a in "\$@"; do case "\$a" in *.tar.gz|*.deb|*.rpm|*SHA256SUMS|*.minisig) cp "\$a" "$SB/assets/" ;; esac; done
9999 touch "$SB/draft" ;;
100100 "release download")
101101 dir=""
@@ -156,7 +156,17 @@ case "\$*" in
156156 else echo "\$os-\$arch" > "\$2/_output/bin/agent-vm.exe"; fi ;;
157157esac
158158STUB
159删除:chmod +x "$RB/gh" "$RB/make" "$RB/curl"
159新增:# nfpm writes what it was told to (-t), holding the variables release.sh sets
160新增:# and the files it was run next to.
161新增:cat > "$RB/nfpm" <<STUB
162新增:#!/bin/sh
163新增:while [ \$# -gt 0 ]; do case "\$1" in -t) out="\$2" ;; -p) fmt="\$2" ;; -f) cfg="\$2" ;; esac; shift; done
164新增:[ -f "\$cfg" ] || { echo "nfpm stub: no config at \$cfg" >&2; exit 1; }
165新增:[ -f agent-vm ] || { echo "nfpm stub: no agent-vm in \$(pwd)" >&2; exit 1; }
166新增:echo "\$fmt \$GOARCH \$VERSION \$QEMU_DEB \$QEMU_RPM \$SOURCE_DATE_EPOCH" > "\$out"
167新增:STUB
168新增:chmod +x "$RB/gh" "$RB/make" "$RB/curl" "$RB/nfpm"
169新增:export AGENT_VM_NFPM="$RB/nfpm"
160170( cd "$RR" && git init -q -b main && git add -A && git commit -qm r \
161171 && git init -q --bare "$RO" && git remote add origin "$RO" && git push -q origin main ) >/dev/null 2>&1
162172
@@ -188,6 +198,18 @@ out="$(relrun)"; rc=$?
188198case "$rc:$out" in 1:*"NEXT_VERSION is '9.9.8'"*) pass "a Makefile on another version is refused" ;; *) fail "other version: $out" ;; esac
189199( cd "$RR" && printf 'NEXT_VERSION := %s\n' "$V" > Makefile && git commit -qam v && git push -q origin main ) >/dev/null 2>&1
190200
201新增:# flake.nix names the checksum of go.mod and go.sum its vendorHash is for.
202新增:mods="$(cat "$SELF_DIR/go.mod" "$SELF_DIR/go.sum" | sha256_of /dev/stdin)"
203新增:check "flake.nix: its note is the checksum release.sh computes" "$(grep -c "go.mod+go.sum: $mods\$" "$SELF_DIR/flake.nix")" "1"
204新增:( cd "$RR" && cp "$SELF_DIR/go.mod" "$SELF_DIR/go.sum" . && printf '# go.mod+go.sum: %s\n' "$mods" > flake.nix \
205新增: && git add -A && git commit -qm n && git push -q origin main ) >/dev/null 2>&1
206新增:out="$(relrun)"; rc=$?
207新增:case "$rc:$out" in 0:*"vendorHash is for this go.mod and go.sum"*) pass "a flake.nix for these Go dependencies passes" ;; *) fail "flake.nix: $out" ;; esac
208新增:( cd "$RR" && printf '\n// changed\n' >> go.mod && git commit -qam d && git push -q origin main ) >/dev/null 2>&1
209新增:out="$(relrun)"; rc=$?
210新增:case "$rc:$out" in 1:*"flake.nix's vendorHash is not for this go.mod and go.sum"*) pass "a flake.nix for other Go dependencies is refused" ;; *) fail "stale flake.nix: $out" ;; esac
211新增:( cd "$RR" && cp "$SELF_DIR/go.mod" go.mod && git commit -qam r && git push -q origin main ) >/dev/null 2>&1
212新增:
191213# A missing formula stops the run before it tags or publishes anything.
192214out="$(AGENT_VM_TAP="$SB/no-tap" relrun)"; rc=$?
193215case "$rc:$out" in
@@ -284,8 +306,14 @@ check "real run: the tag is on origin" "$(git -C "$RO" tag)" "v$V"
284306check "real run: the latest release (no --latest=false)" "$(grep -c -- '--latest=false' "$SB/gh-edit.log")" "0"
285307check "real run: published as the latest release" "$(grep -c -- '--draft=false --latest$' "$SB/gh-edit.log")" "1"
286308# Byte order (LC_ALL=C): macOS sorts these differently in its locale.
287删除:check "real run: one tarball per platform, and their sums" "$(LC_ALL=C ls "$SB/assets" | tr '\n' ' ')" \
288删除: "SHA256SUMS agent-vm-$V-linux-amd64.tar.gz agent-vm-$V-linux-arm64.tar.gz agent-vm-$V-windows-amd64.tar.gz agent-vm-$V-windows-arm64.tar.gz "
309新增:check "real run: one tarball per platform, a .deb and .rpm per Linux one, and their sums" "$(LC_ALL=C ls "$SB/assets" | tr '\n' ' ')" \
310新增: "SHA256SUMS agent-vm-$V-1.aarch64.rpm agent-vm-$V-1.x86_64.rpm agent-vm-$V-linux-amd64.tar.gz agent-vm-$V-linux-arm64.tar.gz agent-vm-$V-windows-amd64.tar.gz agent-vm-$V-windows-arm64.tar.gz agent-vm_${V}_amd64.deb agent-vm_${V}_arm64.deb "
311新增:check "real run: the tarballs come first in SHA256SUMS" "$(awk '{ print $2 }' "$SB/assets/SHA256SUMS" | tr '\n' ' ' | sed 's/agent-vm-[^ ]*-[a-z]*-[a-z0-9]*\.tar\.gz/T/g')" \
312新增: "T T T T agent-vm_${V}_arm64.deb agent-vm-$V-1.aarch64.rpm agent-vm_${V}_amd64.deb agent-vm-$V-1.x86_64.rpm "
313新增:check "real run: the arm64 .deb is made from that build" "$(cat "$SB/assets/agent-vm_${V}_arm64.deb")" \
314新增: "deb arm64 $V qemu-system-arm qemu-system-aarch64-core $(git -C "$RR" log -1 --format=%ct)"
315新增:check "real run: the x86_64 .rpm is made from that build" "$(cat "$SB/assets/agent-vm-$V-1.x86_64.rpm")" \
316新增: "rpm amd64 $V qemu-system-x86 qemu-system-x86-core $(git -C "$RR" log -1 --format=%ct)"
289317check "real run: Windows's is agent-vm.exe" \
290318 "$(tar -tzf "$SB/assets/agent-vm-$V-windows-arm64.tar.gz" | grep -c "^agent-vm-$V/agent-vm.exe$")" "1"
291319if [ -n "$SIGN" ]; then
修改third_party/gvisor-tap-vsock/pkg/tap/switch.go+4 −0看文件
@@ -96,6 +96,10 @@ func (e *Switch) Accept(ctx context.Context, rawConn net.Conn, protocol types.Pr
9696 e.disconnect(id, conn)
9797 }()
9898 if err := e.rx(ctx, id, conn); err != nil {
99新增: if ctx.Err() != nil {
100新增: // Closing the connection is how a program ends the switch.
101新增: return nil
102新增: }
99103 err := fmt.Errorf("cannot receive packets from %s, disconnecting: %w", conn.RemoteAddr().String(), err)
100104 log.Error(err)
101105 return err
新增third_party/gvisor-tap-vsock/pkg/tap/switch_test.go+48 −0看文件
@@ -0,0 +1,48 @@
1新增:package tap
2新增:
3新增:import (
4新增: "context"
5新增: "net"
6新增: "sync"
7新增: "testing"
8新增:
9新增: "github.com/containers/gvisor-tap-vsock/pkg/types"
10新增: "github.com/stretchr/testify/require"
11新增:)
12新增:
13新增:// readingConn says when it is first read.
14新增:type readingConn struct {
15新增: net.Conn
16新增: reading chan struct{}
17新增: once sync.Once
18新增:}
19新增:
20新增:func (c *readingConn) Read(b []byte) (int, error) {
21新增: c.once.Do(func() { close(c.reading) })
22新增: return c.Conn.Read(b)
23新增:}
24新增:
25新增:// A connection that ends because the program cancelled the context is not an
26新增:// error; one that ends by itself is.
27新增:func TestAcceptEndedByContext(t *testing.T) {
28新增: for _, cancelled := range []bool{true, false} {
29新增: s := NewSwitch(false)
30新增: ours, theirs := net.Pipe()
31新增: conn := &readingConn{Conn: ours, reading: make(chan struct{})}
32新增: ctx, cancel := context.WithCancel(context.Background())
33新增: done := make(chan error, 1)
34新增: go func() { done <- s.Accept(ctx, conn, types.VfkitProtocol) }()
35新增: <-conn.reading
36新增: if cancelled {
37新增: cancel()
38新增: }
39新增: theirs.Close()
40新增: err := <-done
41新增: cancel()
42新增: if cancelled {
43新增: require.NoError(t, err)
44新增: } else {
45新增: require.Error(t, err)
46新增: }
47新增: }
48新增:}
新增third_party/lima/pkg/driver/qemu/dgram_unix.go+45 −0看文件
@@ -0,0 +1,45 @@
1新增://go:build !windows
2新增:
3新增:// SPDX-FileCopyrightText: Copyright The Lima Authors
4新增:// SPDX-License-Identifier: Apache-2.0
5新增:
6新增:package qemu
7新增:
8新增:import (
9新增: "net"
10新增: "os"
11新增: "syscall"
12新增:)
13新增:
14新增:// dgramPair returns the two ends of a connected datagram socket, as vz does
15新增:// for its network: ours as a net.Conn for the netstack, and QEMU's as a file
16新增:// to pass to it (-netdev dgram,local.type=fd). A datagram is a frame, and
17新增:// unix datagram sockets neither lose nor reorder them: a full buffer blocks
18新增:// the sender.
19新增:func dgramPair() (ours net.Conn, qemu *os.File, err error) {
20新增: // The descriptors must not leak into the processes started meanwhile:
21新增: // QEMU gets its end through ExtraFiles.
22新增: syscall.ForkLock.RLock()
23新增: fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
24新增: if err == nil {
25新增: syscall.CloseOnExec(fds[0])
26新增: syscall.CloseOnExec(fds[1])
27新增: }
28新增: syscall.ForkLock.RUnlock()
29新增: if err != nil {
30新增: return nil, nil, err
31新增: }
32新增: for _, fd := range fds {
33新增: // Best effort: the kernel caps these (net.core.wmem_max, rmem_max).
34新增: _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 1<<20)
35新增: _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 4<<20)
36新增: }
37新增: f := os.NewFile(uintptr(fds[0]), "usernet-dgram")
38新增: defer f.Close()
39新增: ours, err = net.FileConn(f)
40新增: if err != nil {
41新增: syscall.Close(fds[1])
42新增: return nil, nil, err
43新增: }
44新增: return ours, os.NewFile(uintptr(fds[1]), "qemu-dgram"), nil
45新增:}
新增third_party/lima/pkg/driver/qemu/dgram_unix_test.go+56 −0看文件
@@ -0,0 +1,56 @@
1新增://go:build !windows
2新增:
3新增:// SPDX-FileCopyrightText: Copyright The Lima Authors
4新增:// SPDX-License-Identifier: Apache-2.0
5新增:
6新增:package qemu
7新增:
8新增:import (
9新增: "net"
10新增: "testing"
11新增:
12新增: "gotest.tools/v3/assert"
13新增:)
14新增:
15新增:// Each write is one datagram, both ways, and QEMU's end is a file that stays
16新增:// usable once ours is a net.Conn.
17新增:func TestDgramPair(t *testing.T) {
18新增: ours, qemu, err := dgramPair()
19新增: assert.NilError(t, err)
20新增: t.Cleanup(func() { ours.Close(); qemu.Close() })
21新增: theirs, err := net.FileConn(qemu)
22新增: assert.NilError(t, err)
23新增: t.Cleanup(func() { theirs.Close() })
24新增:
25新增: for _, c := range []struct{ from, to net.Conn }{{ours, theirs}, {theirs, ours}} {
26新增: _, err = c.from.Write([]byte("abc"))
27新增: assert.NilError(t, err)
28新增: _, err = c.from.Write([]byte("defgh"))
29新增: assert.NilError(t, err)
30新增: buf := make([]byte, 64)
31新增: n, err := c.to.Read(buf)
32新增: assert.NilError(t, err)
33新增: assert.Equal(t, string(buf[:n]), "abc")
34新增: n, err = c.to.Read(buf)
35新增: assert.NilError(t, err)
36新增: assert.Equal(t, string(buf[:n]), "defgh")
37新增: }
38新增:}
39新增:
40新增:// fd_dgram hands QEMU the datagram socket as the next file descriptor, after
41新增:// those fd_connect made.
42新增:func TestFdDgramTemplate(t *testing.T) {
43新增: _, qemu, err := dgramPair()
44新增: assert.NilError(t, err)
45新增: t.Cleanup(func() { qemu.Close() })
46新增:
47新增: a := &qArgTemplateApplier{dgram: qemu}
48新增: got, err := a.applyTemplate("dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}")
49新增: assert.NilError(t, err)
50新增: assert.Equal(t, got, "dgram,id=net0,local.type=fd,local.str=3")
51新增: assert.DeepEqual(t, len(a.files), 1)
52新增: assert.Equal(t, a.files[0], qemu)
53新增:
54新增: _, err = (&qArgTemplateApplier{}).applyTemplate("{{ fd_dgram }}")
55新增: assert.ErrorContains(t, err, "no datagram socket")
56新增:}
新增third_party/lima/pkg/driver/qemu/dgram_windows.go+16 −0看文件
@@ -0,0 +1,16 @@
1新增:// SPDX-FileCopyrightText: Copyright The Lima Authors
2新增:// SPDX-License-Identifier: Apache-2.0
3新增:
4新增:package qemu
5新增:
6新增:import (
7新增: "errors"
8新增: "net"
9新增: "os"
10新增:)
11新增:
12新增:// dgramPair: Windows has no unix datagram sockets, and cannot pass a file
13新增:// descriptor to QEMU.
14新增:func dgramPair() (net.Conn, *os.File, error) {
15新增: return nil, nil, errors.ErrUnsupported
16新增:}
新增third_party/lima/pkg/driver/qemu/features_test.go+36 −0看文件
@@ -0,0 +1,36 @@
1新增://go:build !windows
2新增:
3新增:// SPDX-FileCopyrightText: Copyright The Lima Authors
4新增:// SPDX-License-Identifier: Apache-2.0
5新增:
6新增:package qemu
7新增:
8新增:import (
9新增: "context"
10新增: "os"
11新增: "path/filepath"
12新增: "testing"
13新增:
14新增: "gotest.tools/v3/assert"
15新增:)
16新增:
17新增:// Each help text is its own: the features are searched as text, and a netdev
18新增:// list holding the accelerators' words would match them.
19新增:func TestInspectFeaturesOwnOutputs(t *testing.T) {
20新增: exe := filepath.Join(t.TempDir(), "qemu-fake")
21新增: script := `#!/bin/sh
22新增:case "$*" in
23新增: *-cpu*) echo "cpus: max" ;;
24新增: *-accel*) echo "accels: tcg" ;;
25新增: *-netdev*) echo "netdevs: dgram" ;;
26新增: *-machine*) echo "machines: virt" ;;
27新增:esac
28新增:`
29新增: assert.NilError(t, os.WriteFile(exe, []byte(script), 0o755))
30新增: f, err := inspectFeatures(context.Background(), exe, "virt")
31新增: assert.NilError(t, err)
32新增: assert.Equal(t, string(f.AccelHelp), "accels: tcg\n")
33新增: assert.Equal(t, string(f.NetdevHelp), "netdevs: dgram\n")
34新增: assert.Equal(t, string(f.MachineHelp), "machines: virt\n")
35新增: assert.Equal(t, string(f.CPUHelp), "cpus: max\n")
36新增:}
修改third_party/lima/pkg/driver/qemu/qemu.go+41 −47看文件
@@ -50,6 +50,10 @@ type Config struct {
5050 // UsernetQEMUSock is the QEMU socket of the instance's own gvisor
5151 // netstack, used instead of slirp when set (see startUsernet).
5252 UsernetQEMUSock string
53新增: // UsernetDgram is QEMU's end of a datagram socketpair whose other end the
54新增: // netstack serves, preferred to UsernetQEMUSock when QEMU has the dgram
55新增: // netdev (see dgramPair). Nil on Windows.
56新增: UsernetDgram *os.File
5357}
5458
5559// minimumQemuVersion returns hardMin and softMin.
@@ -310,61 +314,40 @@ type features struct {
310314}
311315
312316func inspectFeatures(ctx context.Context, exe, machine string) (*features, error) {
313删除: var (
314删除: f features
315删除: stdout bytes.Buffer
316删除: stderr bytes.Buffer
317删除: )
318删除: cmd := exec.CommandContext(ctx, exe, "-M", "none", "-accel", "help")
319删除: cmd.Stdout = &stdout
320删除: cmd.Stderr = &stderr
321删除: if err := cmd.Run(); err != nil {
322删除: return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
317新增: var f features
318新增: var err error
319新增: if f.AccelHelp, err = qemuHelp(ctx, exe, "-M", "none", "-accel", "help"); err != nil {
320新增: return nil, err
323321 }
324删除: f.AccelHelp = stdout.Bytes()
325删除: // on older versions qemu will write "help" output to stderr
326删除: if len(f.AccelHelp) == 0 {
327删除: f.AccelHelp = stderr.Bytes()
322新增: if f.NetdevHelp, err = qemuHelp(ctx, exe, "-M", "none", "-netdev", "help"); err != nil {
323新增: logrus.Warn(err)
328324 }
329删除:
330删除: cmd = exec.CommandContext(ctx, exe, "-M", "none", "-netdev", "help")
331删除: cmd.Stdout = &stdout
332删除: cmd.Stderr = &stderr
333删除: if err := cmd.Run(); err != nil {
334删除: logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
335删除: } else {
336删除: f.NetdevHelp = stdout.Bytes()
337删除: if len(f.NetdevHelp) == 0 {
338删除: f.NetdevHelp = stderr.Bytes()
339删除: }
325新增: if f.MachineHelp, err = qemuHelp(ctx, exe, "-machine", "help"); err != nil {
326新增: logrus.Warn(err)
340327 }
341删除:
342删除: cmd = exec.CommandContext(ctx, exe, "-machine", "help")
343删除: cmd.Stdout = &stdout
344删除: cmd.Stderr = &stderr
345删除: if err := cmd.Run(); err != nil {
346删除: logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
347删除: } else {
348删除: f.MachineHelp = stdout.Bytes()
349删除: if len(f.MachineHelp) == 0 {
350删除: f.MachineHelp = stderr.Bytes()
351删除: }
328新增: // Avoid error: "No machine specified, and there is no default"
329新增: if f.CPUHelp, err = qemuHelp(ctx, exe, "-cpu", "help", "-machine", machine); err != nil {
330新增: logrus.Warn(err)
352331 }
332新增: return &f, nil
333新增:}
353334
354删除: // Avoid error: "No machine specified, and there is no default"
355删除: cmd = exec.CommandContext(ctx, exe, "-cpu", "help", "-machine", machine)
335新增:// qemuHelp is what exe prints for args, a help request. Each one has its own
336新增:// buffers: the features are searched as text, and one holding another's
337新增:// output would match words that are not its own.
338新增:func qemuHelp(ctx context.Context, exe string, args ...string) ([]byte, error) {
339新增: var stdout, stderr bytes.Buffer
340新增: cmd := exec.CommandContext(ctx, exe, args...)
356341 cmd.Stdout = &stdout
357342 cmd.Stderr = &stderr
358343 if err := cmd.Run(); err != nil {
359删除: logrus.Warnf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
360删除: } else {
361删除: f.CPUHelp = stdout.Bytes()
362删除: if len(f.CPUHelp) == 0 {
363删除: f.CPUHelp = stderr.Bytes()
364删除: }
344新增: return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
365345 }
366删除:
367删除: return &f, nil
346新增: // on older versions qemu will write "help" output to stderr
347新增: if stdout.Len() == 0 {
348新增: return stderr.Bytes(), nil
349新增: }
350新增: return stdout.Bytes(), nil
368351}
369352
370353// adjustMemBytesDarwinARM64HVF adjusts the memory to be <= 3 GiB, only when the following conditions are met:
@@ -809,11 +792,22 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er
809792 case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows":
810793 // No file descriptor passing there (fd_connect): QEMU connects to the
811794 // socket itself, which QEMU 7.2 or later can on Windows. The same
812删除: // stream as the socket netdev's.
795新增: // stream as the socket netdev's, so the same abort on EAGAIN (see the
796新增: // dgram netdev below): Windows has no datagram unix sockets.
813797 if !strings.Contains(string(features.NetdevHelp), "stream") {
814798 return "", nil, errors.New("QEMU 7.2 or later is needed (its stream netdev)")
815799 }
816800 args = append(args, "-netdev", fmt.Sprintf("stream,id=net0,server=off,addr.type=unix,addr.path=%s", cfg.UsernetQEMUSock))
801新增: case firstUsernetIndex == -1 && cfg.UsernetDgram != nil && strings.Contains(string(features.NetdevHelp), "dgram"):
802新增: // Not the socket netdev below: it reads a length-prefixed stream, and
803新增: // QEMU (10.2.4 at least) aborts with `net_fill_rstate: Assertion
804新增: // 'size == 0' failed` when its recv() returns EAGAIN, which it
805新增: // meant to ignore (net_socket_send, and net_stream_data_send for the
806新增: // stream netdev, fall through to net_fill_rstate with size -1).
807新增: // Seen on Linux hosts, under sustained guest traffic. The dgram
808新增: // netdev ignores a failed recv() and has no framing to lose. It
809新增: // needs QEMU 7.2 or later.
810新增: args = append(args, "-netdev", "dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}")
817811 case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "":
818812 args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", cfg.UsernetQEMUSock))
819813 case firstUsernetIndex == -1:
修改third_party/lima/pkg/driver/qemu/qemu_driver.go+99 −31看文件
@@ -67,40 +67,81 @@ type LimaQemuDriver struct {
6767 usernetStop context.CancelFunc
6868}
6969
70删除:// startUsernet starts the instance's own gvisor netstack, as vz does: one
71删除:// network per instance, in the hostagent, where usernet.Outbound applies.
72删除:func startUsernet(ctx context.Context, inst *limatype.Instance) (client *usernet.Client, qemuSock string, stop context.CancelFunc, err error) {
73删除: endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
70新增:// usernetSockets are what connects QEMU to the instance's own gvisor netstack
71新增:// (see startUsernet). QEMU gets the dgram end, or the socket path when its
72新增:// netdevs have no dgram (see Cmdline): the netstack listens on the path only
73新增:// then, as nothing else should be able to connect to it.
74新增:type usernetSockets struct {
75新增: endpoint string
76新增: // qemu is the path of the socket netdev's listener.
77新增: qemu string
78新增: // dgramConn is the netstack's end of a datagram socketpair, qemuDgram
79新增: // QEMU's. Both are nil on Windows.
80新增: dgramConn net.Conn
81新增: qemuDgram *os.File
82新增:}
83新增:
84新增:func newUsernetSockets(inst *limatype.Instance) (*usernetSockets, error) {
85新增: endpoint, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
7486 if err != nil {
75删除: return nil, "", nil, err
87新增: return nil, err
7688 }
77删除: qemuSock, err = usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock)
89新增: qemu, err := usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock)
7890 if err != nil {
79删除: return nil, "", nil, err
91新增: return nil, err
8092 }
81删除: os.RemoveAll(endpointSock)
82删除: os.RemoveAll(qemuSock)
83删除: ctx, stop = context.WithCancel(ctx)
84删除: err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{
85删除: MTU: 1500,
86删除: Endpoint: endpointSock,
87删除: QemuSocket: qemuSock,
88删除: Async: true,
93新增: os.RemoveAll(endpoint)
94新增: os.RemoveAll(qemu)
95新增: s := &usernetSockets{endpoint: endpoint, qemu: qemu}
96新增: s.dgramConn, s.qemuDgram, err = dgramPair()
97新增: if err != nil && !errors.Is(err, errors.ErrUnsupported) {
98新增: return nil, err
99新增: }
100新增: return s, nil
101新增:}
102新增:
103新增:// closeQEMUEnd closes the file given to QEMU: it has its own copy once started.
104新增:func (s *usernetSockets) closeQEMUEnd() {
105新增: if s.qemuDgram != nil {
106新增: s.qemuDgram.Close()
107新增: }
108新增:}
109新增:
110新增:// startUsernet starts the instance's own gvisor netstack, as vz does: one
111新增:// network per instance, in the hostagent, where usernet.Outbound applies.
112新增:// viaDgram says which end QEMU was given.
113新增:func startUsernet(ctx context.Context, inst *limatype.Instance, s *usernetSockets, viaDgram bool) (client *usernet.Client, stop context.CancelFunc, err error) {
114新增: opts := &usernet.GVisorNetstackOpts{
115新增: MTU: 1500,
116新增: Endpoint: s.endpoint,
117新增: Async: true,
89118 DefaultLeases: map[string]string{
90119 networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir),
91120 },
92121 Subnet: networks.SlirpNetwork,
93删除: })
94删除: if err != nil {
95删除: stop()
96删除: return nil, "", nil, err
97122 }
98删除: subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork)
99删除: if err != nil {
100删除: stop()
101删除: return nil, "", nil, err
123新增: if viaDgram {
124新增: opts.DgramConn = s.dgramConn
125新增: } else {
126新增: opts.QemuSocket = s.qemu
127新增: if s.dgramConn != nil {
128新增: s.dgramConn.Close()
129新增: }
102130 }
103删除: return usernet.NewClient(endpointSock, subnetIP), qemuSock, stop, nil
131新增: ctx, stop = context.WithCancel(ctx)
132新增: err = usernet.StartGVisorNetstack(ctx, opts)
133新增: if err == nil {
134新增: var subnetIP net.IP
135新增: subnetIP, _, err = net.ParseCIDR(networks.SlirpNetwork)
136新增: if err == nil {
137新增: return usernet.NewClient(s.endpoint, subnetIP), stop, nil
138新增: }
139新增: }
140新增: stop()
141新增: if viaDgram {
142新增: s.dgramConn.Close()
143新增: }
144新增: return nil, nil, err
104145}
105146
106147var _ driver.Driver = (*LimaQemuDriver)(nil)
@@ -365,22 +406,40 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
365406 SSHAddress: l.Instance.SSHAddress,
366407 VirtioGA: l.virtioPort != "",
367408 }
409新增: // The netstack starts once Cmdline has chosen how QEMU reaches it.
410新增: var socks *usernetSockets
368411 if limayaml.FirstUsernetIndex(l.Instance.Config) == -1 {
369删除: client, sock, stop, err := startUsernet(ctx, l.Instance)
412新增: var err error
413新增: if socks, err = newUsernetSockets(l.Instance); err != nil {
414新增: return nil, err
415新增: }
416新增: qCfg.UsernetQEMUSock, qCfg.UsernetDgram = socks.qemu, socks.qemuDgram
417新增: defer socks.closeQEMUEnd()
418新增: }
419新增: netstackStarted := false
420新增: defer func() {
421新增: if socks != nil && socks.dgramConn != nil && !netstackStarted {
422新增: socks.dgramConn.Close()
423新增: }
424新增: }()
425新增: qExe, qArgs, err := Cmdline(ctx, qCfg)
426新增: if err != nil {
427新增: return nil, err
428新增: }
429新增: if socks != nil {
430新增: viaDgram := slices.ContainsFunc(qArgs, func(a string) bool { return strings.HasPrefix(a, "dgram,id=net0,") })
431新增: client, stop, err := startUsernet(ctx, l.Instance, socks, viaDgram)
370432 if err != nil {
371433 return nil, err
372434 }
373删除: l.usernetClient, l.usernetStop, qCfg.UsernetQEMUSock = client, stop, sock
435新增: netstackStarted = true
436新增: l.usernetClient, l.usernetStop = client, stop
374437 defer func() {
375438 if l.qCmd == nil {
376439 stop()
377440 }
378441 }()
379442 }
380删除: qExe, qArgs, err := Cmdline(ctx, qCfg)
381删除: if err != nil {
382删除: return nil, err
383删除: }
384443
385444 var vhostCmds []*exec.Cmd
386445 if *l.Instance.Config.MountType == limatype.VIRTIOFS {
@@ -400,7 +459,7 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
400459 }
401460
402461 var qArgsFinal []string
403删除: applier := &qArgTemplateApplier{}
462新增: applier := &qArgTemplateApplier{dgram: qCfg.UsernetDgram}
404463 for _, unapplied := range qArgs {
405464 applied, err := applier.applyTemplate(unapplied)
406465 if err != nil {
@@ -900,6 +959,8 @@ func (l *LimaQemuDriver) GuestAgentConn(ctx context.Context) (net.Conn, string,
900959
901960type qArgTemplateApplier struct {
902961 files []*os.File
962新增: // dgram is the file fd_dgram passes to QEMU.
963新增: dgram *os.File
903964}
904965
905966func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
@@ -938,6 +999,13 @@ func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
938999 }
9391000 return res
9401001 },
1002新增: "fd_dgram": func() (string, error) {
1003新增: if a.dgram == nil {
1004新增: return "", errors.New("fd_dgram: no datagram socket")
1005新增: }
1006新增: a.files = append(a.files, a.dgram)
1007新增: return strconv.Itoa(len(a.files) + 2), nil
1008新增: },
9411009 }
9421010 tmpl, err := template.New("").Funcs(funcMap).Parse(qArg)
9431011 if err != nil {
修改third_party/lima/pkg/instance/start.go+8 −3看文件
@@ -291,7 +291,9 @@ func StartWithPaths(ctx context.Context, inst *limatype.Instance, launchHostAgen
291291 args = append(args, "--progress")
292292 }
293293 args = append(args, inst.Name)
294删除: haCmd = exec.CommandContext(ctx, limactl, args...)
294新增: // Not exec.CommandContext: the hostagent outlives this call, and os/exec
295新增: // would kill it whenever ctx ends, even after Start returned.
296新增: haCmd = exec.Command(limactl, args...)
295297
296298 haCmd.SysProcAttr = executil.BackgroundSysProcAttr
297299
@@ -317,12 +319,15 @@ func StartWithPaths(ctx context.Context, inst *limatype.Instance, launchHostAgen
317319 return err
318320 }
319321
320删除: watchErrCh := make(chan error)
322新增: // Buffered: the goroutine that loses the race below must not block on its
323新增: // send for as long as the program lives (it would, once StartWithPaths
324新增: // has returned).
325新增: watchErrCh := make(chan error, 1)
321326 go func() {
322327 watchErrCh <- watchHostAgentEvents(ctx, inst, haStdoutPath, haStderrPath, begin, showProgress)
323328 close(watchErrCh)
324329 }()
325删除: waitErrCh := make(chan error)
330新增: waitErrCh := make(chan error, 1)
326331 if haCmd != nil {
327332 go func() {
328333 waitErrCh <- haCmd.Wait()
新增third_party/lima/pkg/networks/usernet/dgram_test.go+82 −0看文件
@@ -0,0 +1,82 @@
1新增://go:build !windows
2新增:
3新增:// SPDX-FileCopyrightText: Copyright The Lima Authors
4新增:// SPDX-License-Identifier: Apache-2.0
5新增:
6新增:package usernet
7新增:
8新增:import (
9新增: "bytes"
10新增: "context"
11新增: "net"
12新增: "os"
13新增: "path/filepath"
14新增: "syscall"
15新增: "testing"
16新增: "time"
17新增:
18新增: "gotest.tools/v3/assert"
19新增:)
20新增:
21新增:// A frame sent as a datagram is served by the netstack, and the answer comes
22新增:// back as one: an ARP request for the gateway gets its reply.
23新增:func TestDgramConn(t *testing.T) {
24新增: dir, err := os.MkdirTemp("", "usernet")
25新增: assert.NilError(t, err)
26新增: t.Cleanup(func() { os.RemoveAll(dir) })
27新增:
28新增: fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
29新增: assert.NilError(t, err)
30新增: serverFile, peerFile := os.NewFile(uintptr(fds[0]), "server"), os.NewFile(uintptr(fds[1]), "peer")
31新增: server, err := net.FileConn(serverFile)
32新增: assert.NilError(t, err)
33新增: peer, err := net.FileConn(peerFile)
34新增: assert.NilError(t, err)
35新增: serverFile.Close()
36新增: peerFile.Close()
37新增: t.Cleanup(func() { peer.Close() })
38新增:
39新增: ctx, cancel := context.WithCancel(context.Background())
40新增: t.Cleanup(cancel)
41新增: err = StartGVisorNetstack(ctx, &GVisorNetstackOpts{
42新增: MTU: 1500,
43新增: Endpoint: filepath.Join(dir, "ep.sock"),
44新增: DgramConn: server,
45新增: Async: true,
46新增: Subnet: "192.168.5.0/24",
47新增: })
48新增: assert.NilError(t, err)
49新增:
50新增: guestMAC := net.HardwareAddr{0x52, 0x54, 0x00, 0x00, 0x00, 0x01}
51新增: gatewayMAC, err := net.ParseMAC(gatewayMacAddr)
52新增: assert.NilError(t, err)
53新增: arp := bytes.Join([][]byte{
54新增: {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, guestMAC, {0x08, 0x06}, // Ethernet: broadcast, ARP
55新增: {0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01}, // Ethernet, IPv4, request
56新增: guestMAC, {192, 168, 5, 15},
57新增: make([]byte, 6), {192, 168, 5, 2}, // who has the gateway
58新增: }, nil)
59新增: _, err = peer.Write(arp)
60新增: assert.NilError(t, err)
61新增:
62新增: buf := make([]byte, 2048)
63新增: assert.NilError(t, peer.SetReadDeadline(time.Now().Add(10*time.Second)))
64新增: n, err := peer.Read(buf)
65新增: assert.NilError(t, err)
66新增: reply := buf[:n]
67新增: assert.Assert(t, n >= 42, "frame of %d bytes", n)
68新增: assert.DeepEqual(t, reply[0:6], []byte(guestMAC))
69新增: assert.DeepEqual(t, reply[6:12], []byte(gatewayMAC))
70新增: assert.DeepEqual(t, reply[12:14], []byte{0x08, 0x06})
71新增: assert.DeepEqual(t, reply[20:22], []byte{0x00, 0x02}) // ARP reply
72新增:
73新增: // The connection ends with the netstack's context.
74新增: cancel()
75新增: assert.NilError(t, peer.SetWriteDeadline(time.Now().Add(10*time.Second)))
76新增: _, err = peer.Write(arp)
77新增: for i := 0; err == nil && i < 100; i++ {
78新增: time.Sleep(50 * time.Millisecond)
79新增: _, err = peer.Write(arp)
80新增: }
81新增: assert.ErrorContains(t, err, "")
82新增:}
修改third_party/lima/pkg/networks/usernet/gvproxy.go+25 −0看文件
@@ -33,6 +33,11 @@ type GVisorNetstackOpts struct {
3333 FdSocket string
3434 Endpoint string
3535
36新增: // DgramConn is one end of a datagram socketpair, whose other end is
37新增: // QEMU's dgram netdev: one raw Ethernet frame per datagram. The netstack
38新增: // closes it when its context ends.
39新增: DgramConn net.Conn
40新增:
3641 Subnet string
3742
3843 Async bool
@@ -160,9 +165,29 @@ func run(ctx context.Context, g *errgroup.Group, configuration *types.Configurat
160165 return err
161166 }
162167 }
168新增: if opts.DgramConn != nil {
169新增: serveDgram(ctx, vn, opts.DgramConn)
170新增: }
163171 return nil
164172}
165173
174新增:// serveDgram serves the netstack on conn, until ctx ends. Frames are the
175新增:// datagrams: there is no length prefix to lose track of, as with QEMU's
176新增:// socket and stream netdevs.
177新增:func serveDgram(ctx context.Context, vn *virtualnetwork.VirtualNetwork, conn net.Conn) {
178新增: ctx, cancel := context.WithCancel(ctx)
179新增: go func() {
180新增: <-ctx.Done()
181新增: conn.Close()
182新增: }()
183新增: go func() {
184新增: defer cancel()
185新增: if err := vn.AcceptBess(ctx, &UDPFileConn{Conn: conn}); err != nil && ctx.Err() == nil {
186新增: logrus.Error("QEMU datagram connection closed with error: ", err)
187新增: }
188新增: }()
189新增:}
190新增:
166191func listenQEMU(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error {
167192 var lc net.ListenConfig
168193 listener, err := lc.Listen(ctx, "unix", opts.QemuSocket)
修改www/src/i18n/en.ts+13 −1看文件
@@ -107,7 +107,7 @@ export const en = {
107107 },
108108 ],
109109 methodsTitle: 'Install the command',
110删除: methodsBody: 'Pick one. Each puts `agent-vm` on your `PATH` without root.',
110新增: methodsBody: 'Pick one. Each puts `agent-vm` on your `PATH`; only the Linux packages need root.',
111111 methodsLabel: 'Install method',
112112 methods: [
113113 {
@@ -122,6 +122,18 @@ export const en = {
122122 code: 'brew install sylvinus/tap/agent-vm',
123123 note: 'macOS, or Linux with Homebrew. `brew upgrade agent-vm` updates it.',
124124 },
125新增: {
126新增: id: 'linux',
127新增: label: 'Linux package',
128新增: code: 'sudo apt install ./agent-vm_X.Y.Z_amd64.deb\nsudo dnf install ./agent-vm-X.Y.Z-1.x86_64.rpm',
129新增: note: 'Download the `.deb` or `.rpm` of your architecture (`amd64`, `arm64`; `x86_64`, `aarch64`) from the GitHub releases. It installs `agent-vm` in `/usr/bin` and recommends QEMU and ssh. Not in a package repository yet: install the new file to update.',
130新增: },
131新增: {
132新增: id: 'nix',
133新增: label: 'Nix',
134新增: code: 'nix run github:sylvinus/agent-vm\nnix profile install github:sylvinus/agent-vm',
135新增: note: 'Linux, NixOS included. QEMU comes with it; ssh is the system’s. `nix profile upgrade agent-vm` updates it.',
136新增: },
125137 {
126138 id: 'git',
127139 label: 'git',
修改www/src/i18n/fr.ts+13 −1看文件
@@ -109,7 +109,7 @@ export const fr: Dictionary = {
109109 },
110110 ],
111111 methodsTitle: 'Installer la commande',
112删除: methodsBody: 'Au choix. Chacune met `agent-vm` dans ton `PATH`, sans root.',
112新增: methodsBody: 'Au choix. Chacune met `agent-vm` dans ton `PATH` ; seuls les paquets Linux demandent root.',
113113 methodsLabel: 'Méthode d\'installation',
114114 methods: [
115115 {
@@ -124,6 +124,18 @@ export const fr: Dictionary = {
124124 code: 'brew install sylvinus/tap/agent-vm',
125125 note: 'macOS, ou Linux avec Homebrew. `brew upgrade agent-vm` le met à jour.',
126126 },
127新增: {
128新增: id: 'linux',
129新增: label: 'Paquet Linux',
130新增: code: 'sudo apt install ./agent-vm_X.Y.Z_amd64.deb\nsudo dnf install ./agent-vm-X.Y.Z-1.x86_64.rpm',
131新增: note: 'Télécharge le `.deb` ou le `.rpm` de ton architecture (`amd64`, `arm64` ; `x86_64`, `aarch64`) depuis les versions publiées sur GitHub. Il installe `agent-vm` dans `/usr/bin` et recommande QEMU et ssh. Pas encore dans un dépôt de paquets : installe le nouveau fichier pour mettre à jour.',
132新增: },
133新增: {
134新增: id: 'nix',
135新增: label: 'Nix',
136新增: code: 'nix run github:sylvinus/agent-vm\nnix profile install github:sylvinus/agent-vm',
137新增: note: 'Linux, NixOS compris. QEMU est fourni ; ssh est celui du système. `nix profile upgrade agent-vm` le met à jour.',
138新增: },
127139 {
128140 id: 'git',
129141 label: 'git',