跳到主要内容

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

浏览文件

lima_test.go

565 行 · 19.5 KB历史下载
1package vm
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "reflect"
12 "runtime"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "github.com/lima-vm/lima/v2/pkg/driverutil"
20 "github.com/lima-vm/lima/v2/pkg/guestagent/api"
21 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
22 "github.com/lima-vm/lima/v2/pkg/limatype"
23 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
24 "github.com/lima-vm/lima/v2/pkg/limayaml"
25 "github.com/lima-vm/lima/v2/pkg/portfwd"
26 "github.com/lima-vm/lima/v2/pkg/registry"
27
28 "github.com/sylvinus/agent-vm/internal/cage"
29 "github.com/sylvinus/agent-vm/internal/limaembed"
30 "github.com/sylvinus/agent-vm/internal/paths"
31)
32
33func newTestLima(t *testing.T) *Lima {
34 t.Helper()
35 home := t.TempDir()
36 t.Setenv("LIMA_HOME", home)
37 t.Setenv("LIMA_TEMPLATES_PATH", "")
38 l, err := NewLima(home, t.TempDir())
39 if err != nil {
40 t.Fatal(err)
41 }
42 if _, err := l.prepare(); errors.Is(err, limaembed.ErrNoAssets) {
43 t.Skip("built without the guest agent: make assets")
44 } else if err != nil {
45 t.Fatal(err)
46 }
47 return l
48}
49
50func TestCageDebianMirrors(t *testing.T) {
51 l := newTestLima(t)
52 config := filepath.Join(t.TempDir(), "config.json")
53 data, err := json.Marshal(cage.DefaultConfig())
54 if err != nil {
55 t.Fatal(err)
56 }
57 if err := os.WriteFile(config, data, 0600); err != nil {
58 t.Fatal(err)
59 }
60 t.Setenv(cage.ConfigEnv, config)
61 none := []Mount{}
62 ctx := context.Background()
63 if err := l.Create(ctx, "base", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
64 t.Fatal(err)
65 }
66 instance, err := l.inspect(ctx, "base")
67 if err != nil {
68 t.Fatal(err)
69 }
70 earlyAPT := false
71 for _, step := range instance.Config.Provision {
72 if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianPrepareScript {
73 earlyAPT = true
74 }
75 }
76 if !earlyAPT {
77 t.Fatal("cloud-init could fetch packages before Debian mirrors are set")
78 }
79 for _, arch := range []limatype.Arch{"x86_64", "aarch64"} {
80 var images []limatype.Image
81 for _, image := range instance.Config.Images {
82 if image.Arch == arch {
83 images = append(images, image)
84 }
85 }
86 if len(images) != 3 {
87 t.Fatalf("%s: expected two mirrors and one upstream, got %+v", arch, images)
88 }
89 for i, base := range []string{"https://cloud.debian.org/images/cloud/", "https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/"} {
90 if !strings.HasPrefix(images[i].Location, base) || images[i].Digest != images[2].Digest || images[i].Digest.Validate() != nil {
91 t.Fatalf("unexpected image or missing pin: %+v", images[i])
92 }
93 }
94 }
95}
96
97// What agent-vm does to a VM without booting it: create, edit its shares,
98// clone, delete.
99func TestLimaLifecycle(t *testing.T) {
100 ctx := context.Background()
101 l := newTestLima(t)
102 none := []Mount{}
103 err := l.Create(ctx, "base", "template:debian-13", Settings{CPUs: 1, MemoryGiB: 2, DiskGiB: 10, Mounts: &none, NoContainerd: true}, io.Discard)
104 if err != nil {
105 t.Fatal(err)
106 }
107 base, err := l.Get(ctx, "base")
108 if err != nil {
109 t.Fatal(err)
110 }
111 if base.Status != Stopped || base.CPUs != 1 || base.Memory != 2<<30 || base.Disk != 10<<30 || len(base.Mounts) != 0 {
112 t.Fatalf("created: %+v", base)
113 }
114 // Lima's containerd stays out: Docker brings its own when chosen.
115 if y, _ := os.ReadFile(filepath.Join(os.Getenv("LIMA_HOME"), "base", "lima.yaml")); !strings.Contains(string(y), "containerd:\n user: false\n system: false") {
116 t.Errorf("containerd in lima.yaml:\n%s", y)
117 }
118
119 if err := l.Clone(ctx, "base", "p-12345678"); err != nil {
120 t.Fatal(err)
121 }
122 // A name whose sockets would not fit here, or longer than Lima's 76
123 // characters: said so, nothing made.
124 long := "agent-vm-" + strings.Repeat("x", 50) + "-12345678"
125 if err := l.Clone(ctx, "base", long); !errors.Is(err, ErrNameTooLong) {
126 t.Errorf("long name: %v", err)
127 }
128 if _, err := l.Get(ctx, long); !errors.Is(err, ErrNotFound) {
129 t.Errorf("a long name was made: %v", err)
130 }
131 if err := l.Clone(ctx, "base", long+strings.Repeat("y", 20)); !errors.Is(err, ErrNameTooLong) {
132 t.Errorf("name over 76: %v", err)
133 }
134 // MaxName is exactly what fits here.
135 if m := MaxName(os.Getenv("LIMA_HOME")); m < 76 {
136 fits := strings.Repeat("n", m-9) + "-12345678"
137 if err := l.Clone(ctx, "base", fits); err != nil {
138 t.Errorf("a name of MaxName (%d): %v", m, err)
139 }
140 l.Delete(ctx, fits)
141 if err := l.Clone(ctx, "base", "n"+fits); !errors.Is(err, ErrNameTooLong) {
142 t.Errorf("a name of MaxName+1: %v", err)
143 }
144 } else {
145 t.Errorf("MaxName = %d: the test's Lima home is long, it should be less than 76", m)
146 }
147
148 proj := t.TempDir()
149 off := false
150 mounts := []Mount{{Location: proj, MountPoint: proj, Writable: true,
151 SSHFS: &SSHFS{SFTPDriver: "builtin", Cache: &off, ReadonlyNames: []string{".git", ".hg"}}}}
152 rev := ReverseSSHFS
153 port := 23456
154 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &mounts, MountType: &rev, SSHLocalPort: &port, CPUs: 2}); err != nil {
155 t.Fatal(err)
156 }
157 p, err := l.Get(ctx, "p-12345678")
158 if err != nil {
159 t.Fatal(err)
160 }
161 if p.MountType != ReverseSSHFS || p.SSHLocalPort != 23456 || p.CPUs != 2 || !reflect.DeepEqual(p.Mounts, mounts) {
162 t.Fatalf("edited: %+v %+v", p, p.Mounts)
163 }
164
165 // A path Lima reads as written; those it would read as another (a Go
166 // template, what JSON escapes) refused, nothing written.
167 amp := filepath.Join(t.TempDir(), "R&D <x>")
168 os.MkdirAll(amp, 0o755)
169 withAmp := []Mount{{Location: amp, MountPoint: amp, Writable: true, SSHFS: &SSHFS{SFTPDriver: "builtin", ReadonlyNames: []string{".git", "a&b"}}}}
170 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &withAmp}); err != nil {
171 t.Fatal(err)
172 }
173 if p, _ := l.Get(ctx, "p-12345678"); len(p.Mounts) != 1 || p.Mounts[0].Location != amp || p.Mounts[0].SSHFS.ReadonlyNames[1] != "a&b" {
174 t.Errorf("& and <>: %+v", p.Mounts)
175 }
176 before0, _ := os.ReadFile(filepath.Join(p.Dir, "lima.yaml"))
177 for _, name := range []string{"t{{.Home}}", "q{{.Foo}}", "bad\xffbyte", "line\u2028sep"} {
178 odd := []Mount{{Location: "/tmp/" + name, MountPoint: "/tmp/x", Writable: true, SSHFS: &SSHFS{SFTPDriver: "builtin", ReadonlyNames: []string{".git"}}}}
179 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &odd}); !errors.Is(err, ErrUnmountable) {
180 t.Errorf("%q: %v", name, err)
181 }
182 }
183 if after, _ := os.ReadFile(filepath.Join(p.Dir, "lima.yaml")); string(after) != string(before0) {
184 t.Error("a refused share was written")
185 }
186 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &mounts}); err != nil {
187 t.Fatal(err)
188 }
189
190 // Lima refuses a name with a slash: nothing is written.
191 yaml := filepath.Join(p.Dir, "lima.yaml")
192 before, _ := os.ReadFile(yaml)
193 bad := []Mount{{Location: proj, Writable: true, SSHFS: &SSHFS{SFTPDriver: "builtin", ReadonlyNames: []string{"a/b"}}}}
194 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &bad}); err == nil {
195 t.Error("a name with a slash was accepted")
196 }
197 if after, _ := os.ReadFile(yaml); string(after) != string(before) {
198 t.Error("a refused edit changed lima.yaml")
199 }
200
201 // Lima's override.yaml, with a share lacking the builtin SFTP server the
202 // read-only names need: Lima refuses the config, and says why.
203 cfg := filepath.Join(os.Getenv("LIMA_HOME"), "_config")
204 os.MkdirAll(cfg, 0o755)
205 os.WriteFile(filepath.Join(cfg, "override.yaml"), []byte("mounts:\n- location: "+t.TempDir()+"\n writable: true\n"), 0o644)
206 if p, err := l.Get(ctx, "p-12345678"); err != nil || p.Status != Broken || p.ConfigErr == nil || !strings.Contains(p.ConfigErr.Error(), "sftpDriver") {
207 t.Errorf("get, refused: %v %+v", err, p)
208 }
209 // No VM made or started while it is there.
210 if err := l.Create(ctx, "q-12345678", "template:debian-13", Settings{Mounts: &none}, io.Discard); !errors.Is(err, ErrLimaOverrides) {
211 t.Errorf("create with an override: %v", err)
212 }
213 if err := l.Start(ctx, "p-12345678", io.Discard); !errors.Is(err, ErrLimaOverrides) {
214 t.Errorf("start with an override: %v", err)
215 }
216 os.Remove(filepath.Join(cfg, "override.yaml"))
217
218 // Back to Lima's default mount type, and no shares.
219 def := ""
220 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &none, MountType: &def}); err != nil {
221 t.Fatal(err)
222 }
223 if p, _ := l.Get(ctx, "p-12345678"); len(p.Mounts) != 0 || p.MountType == ReverseSSHFS {
224 t.Errorf("reset: %+v", p)
225 }
226
227 // Never started with a share not confined to its folder.
228 plain := []Mount{{Location: proj, Writable: true}}
229 builtin := []Mount{{Location: proj, Writable: true, SSHFS: &SSHFS{SFTPDriver: "builtin"}}}
230 for _, set := range []Settings{{Mounts: &plain, MountType: &rev}, {Mounts: &builtin, MountType: &def}} {
231 if err := l.Edit(ctx, "p-12345678", set); err != nil {
232 t.Fatal(err)
233 }
234 if err := l.Start(ctx, "p-12345678", io.Discard); !errors.Is(err, ErrUnconfined) {
235 t.Errorf("start, %+v: %v", set, err)
236 }
237 }
238 if err := l.Edit(ctx, "p-12345678", Settings{Mounts: &none, MountType: &def}); err != nil {
239 t.Fatal(err)
240 }
241
242 // _config/base.yaml is not mixed into a new VM.
243 cfgDir := filepath.Join(os.Getenv("LIMA_HOME"), "_config")
244 os.MkdirAll(cfgDir, 0o755)
245 os.WriteFile(filepath.Join(cfgDir, "base.yaml"), []byte("cpus: 7\n"), 0o644)
246 if err := l.Create(ctx, "b-12345678", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
247 t.Fatal(err)
248 }
249 if b, _ := l.Get(ctx, "b-12345678"); b == nil || b.CPUs == 7 {
250 t.Errorf("base.yaml mixed in: %+v", b)
251 }
252 os.Remove(filepath.Join(cfgDir, "base.yaml"))
253 l.Delete(ctx, "b-12345678")
254
255 list, err := l.List(ctx)
256 if err != nil || len(list) != 2 || list[0].Name != "base" || list[1].Name != "p-12345678" {
257 t.Fatalf("list: %v %v", list, err)
258 }
259 for _, name := range []string{"base", "p-12345678"} {
260 if err := l.Delete(ctx, name); err != nil {
261 t.Fatal(err)
262 }
263 if _, err := l.Get(ctx, name); !errors.Is(err, ErrNotFound) {
264 t.Errorf("%s after delete: %v", name, err)
265 }
266 }
267}
268
269// Start gives a VM, made before or not, the rule leaving the guest's
270// ephemeral ports unforwarded: on 127.0.0.1, 0.0.0.0, ::, TCP or UDP, as
271// Lima's forwarder reads it. Other ports are forwarded still.
272func TestLimaEphemeralPorts(t *testing.T) {
273 ctx := context.Background()
274 l := newTestLima(t)
275 // Unconfined: Start edits it, then refuses to boot it.
276 plain := []Mount{{Location: t.TempDir(), Writable: true}}
277 rev := ReverseSSHFS
278 if err := l.Create(ctx, "p-12345678", "template:debian-13", Settings{Mounts: &plain, MountType: &rev}, io.Discard); err != nil {
279 t.Fatal(err)
280 }
281 // A forward of the VM's own, which Start keeps.
282 yamlPath := filepath.Join(os.Getenv("LIMA_HOME"), "p-12345678", "lima.yaml")
283 orig, _ := os.ReadFile(yamlPath)
284 custom := "\nportForwards:\n- guestPort: 40000\n hostPort: 40001\n"
285 if err := os.WriteFile(yamlPath, append(orig, custom...), 0o644); err != nil {
286 t.Fatal(err)
287 }
288 if err := l.Start(ctx, "p-12345678", io.Discard); !errors.Is(err, ErrUnconfined) {
289 t.Fatalf("start: %v", err)
290 }
291 inst, err := l.inspect(ctx, "p-12345678")
292 if err != nil || inst.Config == nil {
293 t.Fatalf("inspect: %v %v", err, inst.Errors)
294 }
295 if n := len(inst.Config.PortForwards); n != 2 || inst.Config.PortForwards[0].GuestPort != 40000 {
296 t.Errorf("port forwards: %+v", inst.Config.PortForwards)
297 }
298 def := limatype.PortForward{}
299 limayaml.FillPortForwardDefaults(&def, inst.Dir, inst.Config.User, inst.Param)
300 var got []events.PortForwardEvent
301 fw := portfwd.NewPortForwarder(append(inst.Config.PortForwards, def), false, false, func(ev *events.PortForwardEvent) { got = append(got, *ev) })
302 defer fw.Close()
303 cctx, cancel := context.WithCancel(ctx)
304 defer cancel()
305 for _, p := range []*api.IPPort{
306 {Protocol: "tcp", Ip: "127.0.0.1", Port: 32768},
307 {Protocol: "tcp", Ip: "0.0.0.0", Port: 45000},
308 {Protocol: "tcp", Ip: "::", Port: 60999},
309 {Protocol: "udp", Ip: "0.0.0.0", Port: 50000},
310 } {
311 got = nil
312 fw.OnEvent(cctx, nil, &api.Event{AddedLocalPorts: []*api.IPPort{p}})
313 if len(got) != 1 || got[0].Type != events.PortForwardEventNotForwarding {
314 t.Errorf("%s %s:%d: %+v", p.Protocol, p.Ip, p.Port, got)
315 }
316 }
317 // Forwarded, or not because the host uses it: not ignored either way.
318 got = nil
319 fw.OnEvent(cctx, nil, &api.Event{AddedLocalPorts: []*api.IPPort{{Protocol: "tcp", Ip: "0.0.0.0", Port: 32767}}})
320 if len(got) != 1 || got[0].Type == events.PortForwardEventNotForwarding {
321 t.Errorf("32767: %+v", got)
322 }
323
324 // Once there, not written again.
325 y := filepath.Join(inst.Dir, "lima.yaml")
326 before, _ := os.ReadFile(y)
327 l.Start(ctx, "p-12345678", io.Discard)
328 if after, _ := os.ReadFile(y); string(after) != string(before) || strings.Count(string(after), "ignore: true") != 1 {
329 t.Errorf("rewritten:\n%s", after)
330 }
331}
332
333// Only the builtin SFTP server over reverse-sshfs is confined.
334// Lima reads a location back through filepath.Abs, C:\p on Windows: the
335// share asked as C:/p, kept.
336func TestSharesKeptWindows(t *testing.T) {
337 old := paths.Windows
338 paths.Windows = func() bool { return true }
339 t.Cleanup(func() { paths.Windows = old })
340 mp := "/c/p"
341 want := []Mount{{Location: "C:/p", MountPoint: mp}}
342 if err := sharesKept(want, []limatype.Mount{{Location: `C:\p`, MountPoint: &mp}}); err != nil {
343 t.Errorf("C:\\p: %v", err)
344 }
345 if err := sharesKept(want, []limatype.Mount{{Location: `C:\q`, MountPoint: &mp}}); !errors.Is(err, ErrUnmountable) {
346 t.Errorf("C:\\q: %v", err)
347 }
348}
349
350// A driver running without its hostagent: orphaned, and Stop kills it. A
351// hostagent without its driver is not: it may be booting the VM.
352func TestLimaStopOrphaned(t *testing.T) {
353 if runtime.GOOS == "windows" {
354 t.Skip("no sleep to stand for the driver")
355 }
356 ctx := context.Background()
357 l := newTestLima(t)
358 none := []Mount{}
359 if err := l.Create(ctx, "o", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
360 t.Fatal(err)
361 }
362 inst, err := l.Get(ctx, "o")
363 if err != nil {
364 t.Fatal(err)
365 }
366 if inst.VMType != "qemu" {
367 t.Skip("only QEMU outlives the hostagent")
368 }
369 // A shell idling, under the name of a program and with the options of a
370 // QEMU: of this VM's, or any other.
371 spawn := func(name, vmName string) ([]byte, chan struct{}) {
372 sh, err := exec.LookPath("sh")
373 if err != nil {
374 t.Skip(err)
375 }
376 exe := filepath.Join(t.TempDir(), name)
377 if err := os.Symlink(sh, exe); err != nil {
378 t.Fatal(err)
379 }
380 cmd := exec.Command(exe, "-c", "while :; do sleep 1; done", "-name", "lima-"+vmName,
381 "-pidfile", filepath.Join(inst.Dir, filenames.PIDFile(inst.VMType)))
382 if err := cmd.Start(); err != nil {
383 t.Fatal(err)
384 }
385 done := make(chan struct{})
386 go func() { cmd.Wait(); close(done) }()
387 t.Cleanup(func() { cmd.Process.Kill(); <-done })
388 return []byte(strconv.Itoa(cmd.Process.Pid)), done
389 }
390 pid, exited := spawn("qemu-system-fake", "o")
391
392 ha := filepath.Join(inst.Dir, filenames.HostAgentPID)
393 os.WriteFile(ha, pid, 0o644)
394 if got, _ := l.Get(ctx, "o"); got.Status != Broken || got.Orphaned {
395 t.Fatalf("a hostagent without its driver: %+v", got)
396 }
397 l.Stop(ctx, "o")
398 select {
399 case <-exited:
400 t.Fatal("Stop killed a hostagent without its driver")
401 case <-time.After(200 * time.Millisecond):
402 }
403 os.Remove(ha)
404
405 // A PID file left by a QEMU that aborted, its number another program's
406 // now: not orphaned, and Stop leaves it alone.
407 driverPID := filepath.Join(inst.Dir, filenames.PIDFile(inst.VMType))
408 // Or another VM's QEMU.
409 for _, c := range []struct{ prog, vm string }{{"not-a-vm", "o"}, {"qemu-system-fake", "other"}} {
410 other, otherExited := spawn(c.prog, c.vm)
411 os.WriteFile(driverPID, other, 0o644)
412 if got, _ := l.Get(ctx, "o"); got.Orphaned {
413 t.Fatalf("%s of %s: %+v", c.prog, c.vm, got)
414 }
415 l.Stop(ctx, "o")
416 select {
417 case <-otherExited:
418 t.Fatalf("Stop killed %s of %s", c.prog, c.vm)
419 case <-time.After(200 * time.Millisecond):
420 }
421 }
422
423 os.WriteFile(driverPID, pid, 0o644)
424 if got, _ := l.Get(ctx, "o"); got.Status != Broken || !got.Orphaned {
425 t.Fatalf("a driver without its hostagent: %+v", got)
426 }
427 if err := l.Stop(ctx, "o"); err != nil {
428 t.Fatal(err)
429 }
430 select {
431 case <-exited:
432 case <-time.After(10 * time.Second):
433 t.Fatal("the driver still runs")
434 }
435 if got, _ := l.Get(ctx, "o"); got.Status != Stopped || got.Orphaned {
436 t.Errorf("after Stop: %+v", got)
437 }
438}
439
440func TestConfined(t *testing.T) {
441 b := &SSHFS{SFTPDriver: "builtin"}
442 for _, c := range []struct {
443 inst *Instance
444 ok bool
445 }{
446 {&Instance{}, true},
447 {&Instance{MountType: ReverseSSHFS, Mounts: []Mount{{Location: "/p", SSHFS: b}}}, true},
448 {&Instance{MountType: ReverseSSHFS, Mounts: []Mount{{Location: "/p", SSHFS: b}, {Location: "/q"}}}, false},
449 {&Instance{MountType: ReverseSSHFS, Mounts: []Mount{{Location: "/p", SSHFS: &SSHFS{SFTPDriver: "openssh-sftp-server"}}}}, false},
450 {&Instance{MountType: "9p", Mounts: []Mount{{Location: "/p", SSHFS: b}}}, false},
451 {&Instance{Mounts: []Mount{{Location: "/p", SSHFS: b}}}, false},
452 } {
453 if err := Confined(c.inst); (err == nil) != c.ok || err != nil && !errors.Is(err, ErrUnconfined) {
454 t.Errorf("%+v: %v", c.inst, err)
455 }
456 }
457}
458
459// The user's own LIMA_HOME is what NewLima found, not the one it sets.
460func TestUserLimaHome(t *testing.T) {
461 oldSet, oldUser := limaHomeSet, userLimaHome
462 t.Cleanup(func() { limaHomeSet, userLimaHome = oldSet, oldUser })
463 limaHomeSet, userLimaHome = "", ""
464 user := t.TempDir()
465 t.Setenv("LIMA_HOME", user)
466 if got := UserLimaHome(); got != user {
467 t.Errorf("before NewLima: %q", got)
468 }
469 ours := t.TempDir()
470 if _, err := NewLima(ours, t.TempDir()); err != nil {
471 t.Fatal(err)
472 }
473 if got := UserLimaHome(); got != user {
474 t.Errorf("after NewLima: %q, want %q", got, user)
475 }
476 // A second one, as tests and migrations make, keeps it.
477 if _, err := NewLima(ours, t.TempDir()); err != nil {
478 t.Fatal(err)
479 }
480 if got := UserLimaHome(); got != user {
481 t.Errorf("after two: %q, want %q", got, user)
482 }
483
484 limaHomeSet, userLimaHome = "", ""
485 os.Unsetenv("LIMA_HOME")
486 if _, err := NewLima(ours, t.TempDir()); err != nil {
487 t.Fatal(err)
488 }
489 if got := UserLimaHome(); got != "" {
490 t.Errorf("unset: %q", got)
491 }
492}
493
494func TestLimaDrivers(t *testing.T) {
495 l := newTestLima(t)
496 ctx := t.Context()
497 none := []Mount{}
498 if err := l.Create(ctx, "base", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
499 t.Fatal(err)
500 }
501 for _, kind := range []string{limatype.QEMU, limatype.VZ} {
502 if registry.CheckInternalOrExternal(kind) != registry.Internal {
503 continue
504 }
505 t.Run(kind, func(t *testing.T) {
506 first, err := l.inspect(ctx, "base")
507 if err != nil {
508 t.Fatal(err)
509 }
510 second, err := l.inspect(ctx, "base")
511 if err != nil {
512 t.Fatal(err)
513 }
514 first.Dir = filepath.Join(first.Dir, "first")
515 second.Dir = filepath.Join(second.Dir, "second")
516 first.Config.VMType = &kind
517 second.Config.VMType = &kind
518 firstDriver, err := driverutil.CreateConfiguredDriver(ctx, first, 0)
519 if err != nil {
520 t.Fatal(err)
521 }
522 secondDriver, err := driverutil.CreateConfiguredDriver(ctx, second, 0)
523 if err != nil {
524 t.Fatal(err)
525 }
526 if firstDriver.Driver == secondDriver.Driver || firstDriver.Info(ctx).InstanceDir != first.Dir {
527 t.Fatal("configuring another VM changed the first VM's driver")
528 }
529 if secondDriver.Info(ctx).InstanceDir != second.Dir {
530 t.Fatal("the second driver lost its instance")
531 }
532 })
533 }
534}
535
536// Edits at once each write a whole lima.yaml, and leave nothing behind.
537func TestLimaEditConcurrent(t *testing.T) {
538 ctx := context.Background()
539 l := newTestLima(t)
540 none := []Mount{}
541 if err := l.Create(ctx, "p-12345678", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil {
542 t.Fatal(err)
543 }
544 var wg sync.WaitGroup
545 for i := 1; i <= 8; i++ {
546 wg.Add(1)
547 go func() {
548 defer wg.Done()
549 if err := l.Edit(ctx, "p-12345678", Settings{CPUs: i}); err != nil {
550 t.Error(err)
551 }
552 }()
553 }
554 wg.Wait()
555 p, err := l.Get(ctx, "p-12345678")
556 if err != nil || p.Status == Broken {
557 t.Fatalf("after: %v %+v", err, p)
558 }
559 ents, _ := os.ReadDir(p.Dir)
560 for _, e := range ents {
561 if strings.HasSuffix(e.Name(), ".tmp") {
562 t.Errorf("left behind: %s", e.Name())
563 }
564 }
565}