跳到主要内容

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

浏览文件

qemu_driver.go

1134 行 · 31.5 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package qemu
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "image/png"
13 "io"
14 "io/fs"
15 "net"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "slices"
21 "strconv"
22 "strings"
23 "syscall"
24 "text/template"
25 "time"
26
27 "github.com/coreos/go-semver/semver"
28 "github.com/digitalocean/go-qemu/qmp"
29 "github.com/digitalocean/go-qemu/qmp/raw"
30 "github.com/lima-vm/go-qcow2reader/image/qcow2"
31 rawImage "github.com/lima-vm/go-qcow2reader/image/raw"
32 "github.com/lima-vm/go-qcow2reader/image/vhdx"
33 "github.com/lima-vm/go-qcow2reader/image/vmdk"
34 "github.com/sirupsen/logrus"
35 "github.com/spakin/netpbm"
36 "golang.org/x/image/bmp"
37
38 "github.com/lima-vm/lima/v2/pkg/driver"
39 "github.com/lima-vm/lima/v2/pkg/driver/qemu/entitlementutil"
40 "github.com/lima-vm/lima/v2/pkg/executil"
41 "github.com/lima-vm/lima/v2/pkg/limatype"
42 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
43 "github.com/lima-vm/lima/v2/pkg/limayaml"
44 "github.com/lima-vm/lima/v2/pkg/networks"
45 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
46 "github.com/lima-vm/lima/v2/pkg/osutil"
47 "github.com/lima-vm/lima/v2/pkg/reflectutil"
48 "github.com/lima-vm/lima/v2/pkg/version/versionutil"
49)
50
51type LimaQemuDriver struct {
52 Instance *limatype.Instance
53 SSHLocalPort int
54 vSockPort int
55 virtioPort string
56
57 qCmd *exec.Cmd
58 qWaitCh chan error
59
60 vhostCmds []*exec.Cmd
61
62 swtpmCmd *exec.Cmd
63 swtpmWaitCh chan error
64
65 // The instance's own gvisor netstack (startUsernet), as with vz.
66 usernetClient *usernet.Client
67 usernetStop context.CancelFunc
68}
69
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.
74type 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
84func newUsernetSockets(inst *limatype.Instance) (*usernetSockets, error) {
85 endpoint, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
86 if err != nil {
87 return nil, err
88 }
89 qemu, err := usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock)
90 if err != nil {
91 return nil, err
92 }
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.
104func (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.
113func 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,
118 DefaultLeases: map[string]string{
119 networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir),
120 },
121 Subnet: networks.SlirpNetwork,
122 }
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 }
130 }
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
145}
146
147var _ driver.Driver = (*LimaQemuDriver)(nil)
148
149func New() *LimaQemuDriver {
150 // virtserialport doesn't seem to work reliably: https://github.com/lima-vm/lima/issues/2064
151 // but on Windows default Unix socket forwarding is not available
152 var virtioPort string
153 virtioPort = filenames.VirtioPort
154 if runtime.GOOS != "windows" {
155 virtioPort = ""
156 }
157 return &LimaQemuDriver{
158 vSockPort: 0,
159 virtioPort: virtioPort,
160 }
161}
162
163func (l *LimaQemuDriver) Configure(_ context.Context, inst *limatype.Instance) (*driver.ConfiguredDriver, error) {
164 if err := fillConfig(inst.Config, inst.Dir); err != nil {
165 return nil, err
166 }
167
168 l.Instance = inst
169 l.SSHLocalPort = inst.SSHLocalPort
170
171 return &driver.ConfiguredDriver{
172 Driver: l,
173 }, nil
174}
175
176func (l *LimaQemuDriver) Validate(ctx context.Context) error {
177 if err := validateArch(ctx, l.Instance.Config); err != nil {
178 return err
179 }
180 return validateConfig(l.Instance.Config)
181}
182
183func validateConfig(cfg *limatype.LimaYAML) error {
184 if cfg == nil {
185 return errors.New("configuration is nil")
186 }
187 if err := validateMountType(cfg); err != nil {
188 return err
189 }
190
191 for i, nw := range cfg.Networks {
192 if unknown := reflectutil.UnknownNonEmptyFields(nw,
193 "Lima",
194 "Socket",
195 "MACAddress",
196 "Metric",
197 "Interface",
198 ); len(unknown) > 0 {
199 logrus.Warnf("vmType %s: ignoring networks[%d]: %+v", *cfg.VMType, i, unknown)
200 }
201 }
202
203 audio := cfg.Audio
204 if audio.Microphone != nil && !*audio.Microphone {
205 audio.Microphone = nil
206 }
207 if unknown := reflectutil.UnknownNonEmptyFields(audio,
208 "Device",
209 "Interface",
210 ); len(unknown) > 0 {
211 logrus.Warnf("vmType %s: ignoring audio: %+v", *cfg.VMType, unknown)
212 }
213
214 var qemuOpts limatype.QEMUOpts
215 if err := limayaml.Convert(cfg.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil {
216 return err
217 }
218 if qemuOpts.MinimumVersion != nil {
219 if _, err := semver.NewVersion(*qemuOpts.MinimumVersion); err != nil {
220 return fmt.Errorf("field `vmOpts.qemu.minimumVersion` must be a semvar value, got %#q: %w", *qemuOpts.MinimumVersion, err)
221 }
222 }
223
224 if cfg.NestedVirtualization != nil && *cfg.NestedVirtualization {
225 if runtime.GOOS == "darwin" {
226 macOSProductVersion, err := osutil.ProductVersion()
227 if err != nil {
228 return err
229 }
230 if macOSProductVersion.LessThan(*semver.New("15.0.0")) {
231 return errors.New("nested virtualization requires macOS 15 or newer")
232 }
233 }
234 }
235
236 return nil
237}
238
239// Helper method for checking the binary signature on macOS.
240func validateArch(ctx context.Context, cfg *limatype.LimaYAML) error {
241 if runtime.GOOS == "darwin" {
242 var vmArch string
243 if cfg.Arch != nil {
244 vmArch = *cfg.Arch
245 }
246 if err := checkBinarySignature(ctx, vmArch); err != nil {
247 return err
248 }
249 }
250 return nil
251}
252
253// Helper method for mount type validation.
254func validateMountType(cfg *limatype.LimaYAML) error {
255 // 1. First, check if the user explicitly blocked this mount type in their config.
256 if cfg.MountTypesUnsupported != nil && cfg.MountType != nil && slices.Contains(cfg.MountTypesUnsupported, *cfg.MountType) {
257 return fmt.Errorf("mount type %#q is explicitly unsupported", *cfg.MountType)
258 }
259
260 // 2. Then, check if the mount type is valid for the current Operating System.
261 if cfg.MountType != nil {
262 switch runtime.GOOS {
263 case "linux":
264 switch *cfg.MountType {
265 case limatype.REVSSHFS, limatype.NINEP, limatype.VIRTIOFS:
266 return nil
267 default:
268 return fmt.Errorf("field `mountType` must be one of %v for QEMU driver on Linux, got %#q", []string{limatype.REVSSHFS, limatype.NINEP, limatype.VIRTIOFS}, *cfg.MountType)
269 }
270 case "darwin":
271 switch *cfg.MountType {
272 case limatype.REVSSHFS, limatype.NINEP:
273 return nil
274 default:
275 return fmt.Errorf("field `mountType` must be %#q or %#q for QEMU driver on macOS, got %#q", limatype.REVSSHFS, limatype.NINEP, *cfg.MountType)
276 }
277 case "windows":
278 // Windows version of QEMU does not support 9p yet, so we should not suggest it.
279 // https://gitlab.com/qemu-project/qemu/-/work_items/974
280 switch *cfg.MountType {
281 case limatype.REVSSHFS:
282 return nil
283 default:
284 return fmt.Errorf("field `mountType` must be %#q for QEMU driver on Windows, got %#q", limatype.REVSSHFS, *cfg.MountType)
285 }
286 default:
287 switch *cfg.MountType {
288 case limatype.REVSSHFS, limatype.NINEP:
289 return nil
290 default:
291 return fmt.Errorf("field `mountType` must be %#q or %#q for QEMU driver on %s, got %#q", limatype.REVSSHFS, limatype.NINEP, runtime.GOOS, *cfg.MountType)
292 }
293 }
294 }
295
296 return nil
297}
298
299func fillConfig(cfg *limatype.LimaYAML, instDir string) error {
300 if cfg.VMType == nil {
301 cfg.VMType = new(limatype.QEMU)
302 }
303
304 if cfg.Video.VNC.Display == nil || *cfg.Video.VNC.Display == "" {
305 cfg.Video.VNC.Display = new("127.0.0.1:0,to=9")
306 }
307
308 var qemuOpts limatype.QEMUOpts
309 if err := limayaml.Convert(cfg.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil {
310 logrus.WithError(err).Warnf("Couldn't convert %#q", cfg.VMOpts[limatype.QEMU])
311 }
312 if qemuOpts.CPUType == nil {
313 qemuOpts.CPUType = limatype.CPUType{}
314 }
315
316 //nolint:staticcheck // Migration of top-level CPUTYPE if specified
317 if len(cfg.CPUType) > 0 {
318 logrus.Warn("The top-level `cpuType` field is deprecated and will be removed in a future release. Please migrate to `vmOpts.qemu.cpuType`.")
319 for arch, v := range cfg.CPUType {
320 if v == "" {
321 continue
322 }
323 if existing, ok := qemuOpts.CPUType[arch]; ok && existing != "" && existing != v {
324 logrus.Warnf("Conflicting cpuType for arch %#q: top-level=%#q, vmOpts.qemu=%#q; using vmOpts.qemu value", arch, v, existing)
325 continue
326 }
327 qemuOpts.CPUType[arch] = v
328 }
329 cfg.CPUType = nil
330
331 var opts any
332 if err := limayaml.Convert(qemuOpts, &opts, ""); err != nil {
333 logrus.WithError(err).Warnf("Couldn't convert %+v", qemuOpts)
334 }
335 if cfg.VMOpts == nil {
336 cfg.VMOpts = limatype.VMOpts{}
337 }
338 cfg.VMOpts[limatype.QEMU] = opts
339 }
340
341 mountTypesUnsupported := make(map[string]struct{})
342 for _, f := range cfg.MountTypesUnsupported {
343 mountTypesUnsupported[f] = struct{}{}
344 }
345
346 if runtime.GOOS == "windows" {
347 // QEMU for Windows does not support 9p
348 mountTypesUnsupported[limatype.NINEP] = struct{}{}
349 }
350
351 if cfg.MountType == nil || *cfg.MountType == "" || *cfg.MountType == "default" {
352 cfg.MountType = new(limatype.NINEP)
353 if _, ok := mountTypesUnsupported[limatype.NINEP]; ok {
354 // Use REVSSHFS if the instance does not support 9p
355 cfg.MountType = new(limatype.REVSSHFS)
356 } else if limayaml.IsExistingInstanceDir(instDir) && !versionutil.GreaterEqual(limayaml.ExistingLimaVersion(instDir), "1.0.0") {
357 // Use REVSSHFS if the instance was created with Lima prior to v1.0
358 cfg.MountType = new(limatype.REVSSHFS)
359 }
360 }
361
362 for i := range cfg.Mounts {
363 mount := &cfg.Mounts[i]
364 if mount.Virtiofs.QueueSize == nil && *cfg.MountType == limatype.VIRTIOFS {
365 cfg.Mounts[i].Virtiofs.QueueSize = new(limayaml.DefaultVirtiofsQueueSize)
366 }
367 }
368
369 if _, ok := mountTypesUnsupported[*cfg.MountType]; ok {
370 return fmt.Errorf("mount type %#q is explicitly unsupported", *cfg.MountType)
371 }
372
373 return validateConfig(cfg)
374}
375
376func (l *LimaQemuDriver) BootScripts(_ context.Context) (map[string][]byte, error) {
377 return nil, nil
378}
379
380func (l *LimaQemuDriver) CreateDisk(ctx context.Context) error {
381 qCfg := Config{
382 Name: l.Instance.Name,
383 InstanceDir: l.Instance.Dir,
384 LimaYAML: l.Instance.Config,
385 }
386 return EnsureDisk(ctx, qCfg)
387}
388
389func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
390 ctx, cancel := context.WithCancel(ctx)
391 defer func() {
392 if l.qCmd == nil {
393 cancel()
394 }
395 }()
396
397 if l.Instance.Config.SSH.OverVsock != nil && *l.Instance.Config.SSH.OverVsock {
398 logrus.Warn(".ssh.overVsock is not implemented yet for QEMU driver")
399 }
400
401 qCfg := Config{
402 Name: l.Instance.Name,
403 InstanceDir: l.Instance.Dir,
404 LimaYAML: l.Instance.Config,
405 SSHLocalPort: l.SSHLocalPort,
406 SSHAddress: l.Instance.SSHAddress,
407 VirtioGA: l.virtioPort != "",
408 }
409 // The netstack starts once Cmdline has chosen how QEMU reaches it.
410 var socks *usernetSockets
411 if limayaml.FirstUsernetIndex(l.Instance.Config) == -1 {
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 var workingDir string
426 qExe, qArgs, err := cmdline(ctx, qCfg, &workingDir)
427 if err != nil {
428 return nil, err
429 }
430 if socks != nil {
431 viaDgram := slices.ContainsFunc(qArgs, func(a string) bool { return strings.HasPrefix(a, "dgram,id=net0,") })
432 client, stop, err := startUsernet(ctx, l.Instance, socks, viaDgram)
433 if err != nil {
434 return nil, err
435 }
436 netstackStarted = true
437 l.usernetClient, l.usernetStop = client, stop
438 defer func() {
439 if l.qCmd == nil {
440 stop()
441 }
442 }()
443 }
444
445 var vhostCmds []*exec.Cmd
446 if *l.Instance.Config.MountType == limatype.VIRTIOFS {
447 vhostExe, err := FindVirtiofsd(ctx, qExe)
448 if err != nil {
449 return nil, err
450 }
451
452 for i := range l.Instance.Config.Mounts {
453 args, err := VirtiofsdCmdline(qCfg, i)
454 if err != nil {
455 return nil, err
456 }
457
458 vhostCmds = append(vhostCmds, exec.CommandContext(ctx, vhostExe, args...))
459 }
460 }
461
462 var qArgsFinal []string
463 applier := &qArgTemplateApplier{dgram: qCfg.UsernetDgram}
464 for _, unapplied := range qArgs {
465 applied, err := applier.applyTemplate(unapplied)
466 if err != nil {
467 return nil, err
468 }
469 qArgsFinal = append(qArgsFinal, applied)
470 }
471 qCmd := exec.CommandContext(ctx, qExe, qArgsFinal...)
472 qCmd.Dir = workingDir
473 qCmd.ExtraFiles = append(qCmd.ExtraFiles, applier.files...)
474 qCmd.SysProcAttr = executil.BackgroundSysProcAttr
475 qStdout, err := qCmd.StdoutPipe()
476 if err != nil {
477 return nil, err
478 }
479 go logPipeRoutine(qStdout, "qemu[stdout]")
480 qStderr, err := qCmd.StderrPipe()
481 if err != nil {
482 return nil, err
483 }
484 go logPipeRoutine(qStderr, "qemu[stderr]")
485
486 for i, vhostCmd := range vhostCmds {
487 vhostStdout, err := vhostCmd.StdoutPipe()
488 if err != nil {
489 return nil, err
490 }
491 go logPipeRoutine(vhostStdout, fmt.Sprintf("virtiofsd-%d[stdout]", i))
492 vhostStderr, err := vhostCmd.StderrPipe()
493 if err != nil {
494 return nil, err
495 }
496 go logPipeRoutine(vhostStderr, fmt.Sprintf("virtiofsd-%d[stderr]", i))
497 }
498
499 for i, vhostCmd := range vhostCmds {
500 logrus.Debugf("vhostCmd[%d].Args: %v", i, vhostCmd.Args)
501 if err := vhostCmd.Start(); err != nil {
502 return nil, err
503 }
504
505 vhostWaitCh := make(chan error)
506 go func() {
507 vhostWaitCh <- vhostCmd.Wait()
508 }()
509
510 vhostSock := filepath.Join(l.Instance.Dir, fmt.Sprintf(filenames.VhostSock, i))
511 vhostSockExists := false
512 for attempt := range 5 {
513 logrus.Debugf("Try waiting for %s to appear (attempt %d)", vhostSock, attempt)
514
515 if _, err := os.Stat(vhostSock); err != nil {
516 if !errors.Is(err, fs.ErrNotExist) {
517 logrus.Warnf("Failed to check for vhost socket: %v", err)
518 }
519 } else {
520 vhostSockExists = true
521 break
522 }
523
524 retry := time.NewTimer(200 * time.Millisecond)
525 select {
526 case err = <-vhostWaitCh:
527 return nil, fmt.Errorf("virtiofsd never created vhost socket: %w", err)
528 case <-retry.C:
529 }
530 }
531
532 if !vhostSockExists {
533 return nil, fmt.Errorf("vhost socket %s never appeared", vhostSock)
534 }
535
536 go func() {
537 if err := <-vhostWaitCh; err != nil {
538 logrus.Errorf("Error from virtiofsd instance #%d: %v", i, err)
539 }
540 }()
541 }
542
543 // Start swtpm for TPM emulation.
544 if *l.Instance.Config.TPM {
545 if err := l.runSwtpm(ctx, qCfg); err != nil {
546 return nil, err
547 }
548 }
549
550 logrus.Infof("Starting QEMU (hint: to watch the boot progress, see %#q)", filepath.Join(qCfg.InstanceDir, "serial*.log"))
551 logrus.Debugf("qCmd.Args: %v", qCmd.Args)
552 if err := qCmd.Start(); err != nil {
553 return nil, err
554 }
555 l.qCmd = qCmd
556 l.vhostCmds = vhostCmds
557 l.qWaitCh = watchQEMU(qCmd.Wait, func() error {
558 client := l.usernetClient
559 if usernetIndex := limayaml.FirstUsernetIndex(l.Instance.Config); usernetIndex != -1 {
560 client = usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima)
561 }
562 if client != nil {
563 return client.ConfigureDriver(ctx, l.Instance, l.SSHLocalPort)
564 }
565 return nil
566 }, func() {
567 cancel()
568 if l.usernetStop != nil {
569 l.usernetStop()
570 }
571 })
572
573 // QEMU's UEFI boot order doesn't work well for Windows guest OS.
574 // We send a key periodically to proceed from "Press any key to boot from CD or DVD...".
575 if *qCfg.LimaYAML.OS == limatype.WINDOWS && !*qCfg.LimaYAML.Firmware.LegacyBIOS {
576 logrus.Debug("send a key to QEMU to boot Windows ISO...")
577 if err := l.sendEnter(); err != nil {
578 logrus.WithError(err).Error("failed to send a keypress event")
579 }
580 }
581
582 return l.qWaitCh, nil
583}
584
585func (l *LimaQemuDriver) Stop(ctx context.Context) error {
586 return l.shutdownQEMU(ctx, 3*time.Minute, l.qCmd, l.qWaitCh)
587}
588
589func (l *LimaQemuDriver) ChangeDisplayPassword(_ context.Context, password string) error {
590 return l.changeVNCPassword(password)
591}
592
593func (l *LimaQemuDriver) DisplayConnection(_ context.Context) (string, error) {
594 return l.getVNCDisplayPort()
595}
596
597func (l *LimaQemuDriver) runSwtpm(ctx context.Context, qCfg Config) error {
598 var swtpmCmd *exec.Cmd
599 swtpmExe, swtpmArgs, err := SwtpmCmdline(qCfg)
600 if err != nil {
601 return err
602 }
603
604 swtpmCmd = exec.CommandContext(ctx, swtpmExe, swtpmArgs...)
605 swtpmCmd.SysProcAttr = executil.BackgroundSysProcAttr
606
607 swtpmStdout, err := swtpmCmd.StdoutPipe()
608 if err != nil {
609 return err
610 }
611 go logPipeRoutine(swtpmStdout, "swtpm[stdout]")
612
613 swtpmStderr, err := swtpmCmd.StderrPipe()
614 if err != nil {
615 return err
616 }
617 go logPipeRoutine(swtpmStderr, "swtpm[stderr]")
618
619 logrus.Info("Starting swtpm for TPM emulation")
620 logrus.Debugf("swtpmCmd.Args: %v", swtpmCmd.Args)
621 if err := swtpmCmd.Start(); err != nil {
622 return fmt.Errorf("failed to start swtpm: %w", err)
623 }
624
625 swtpmSock := filepath.Join(l.Instance.Dir, filenames.SwtpmSock)
626 l.swtpmWaitCh = make(chan error, 1)
627 go func() {
628 l.swtpmWaitCh <- swtpmCmd.Wait()
629 close(l.swtpmWaitCh)
630 }()
631
632 var swtpmSockExists bool
633 for attempt := range 5 {
634 logrus.Debugf("Waiting for swtpm socket %s (attempt %d)", swtpmSock, attempt)
635 if _, err := os.Stat(swtpmSock); err == nil {
636 swtpmSockExists = true
637 break
638 }
639 retry := time.NewTimer(200 * time.Millisecond)
640 select {
641 case err = <-l.swtpmWaitCh:
642 retry.Stop()
643 return fmt.Errorf("swtpm exited before creating socket: %w", err)
644 case <-retry.C:
645 }
646 }
647
648 if !swtpmSockExists {
649 _ = swtpmCmd.Process.Kill()
650 return fmt.Errorf("swtpm socket %s never appeared", swtpmSock)
651 }
652
653 l.swtpmCmd = swtpmCmd
654
655 return nil
656}
657
658func waitFileExists(path string, timeout time.Duration) error {
659 startWaiting := time.Now()
660 for {
661 _, err := os.Stat(path)
662 if err == nil {
663 break
664 }
665 if !errors.Is(err, os.ErrNotExist) {
666 return err
667 }
668 if time.Since(startWaiting) > timeout {
669 return fmt.Errorf("timeout waiting for %s", path)
670 }
671 time.Sleep(500 * time.Millisecond)
672 }
673 return nil
674}
675
676// Ask the user to sign the qemu binary with the "com.apple.security.hypervisor" if needed.
677// Workaround for https://github.com/lima-vm/lima/issues/1742
678func checkBinarySignature(ctx context.Context, vmArch string) error {
679 macOSProductVersion, err := osutil.ProductVersion()
680 if err != nil {
681 return err
682 }
683 // The codesign --xml option is only available on macOS Monterey and later
684 if !macOSProductVersion.LessThan(*semver.New("12.0.0")) && vmArch != "" {
685 qExe, _, err := Exe(vmArch)
686 if err != nil {
687 return fmt.Errorf("failed to find the QEMU binary for the architecture %#q: %w", vmArch, err)
688 }
689 if accel := Accel(vmArch); accel == "hvf" {
690 entitlementutil.AskToSignIfNotSignedProperly(ctx, qExe)
691 }
692 }
693
694 return nil
695}
696
697// sendEnter sends a Return (Enter) key to QEMU through QMP.
698// This method is for proceeding UEFI boot forcefully.
699func (l *LimaQemuDriver) sendEnter() error {
700 qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
701 err := waitFileExists(qmpSockPath, 30*time.Second)
702 if err != nil {
703 return err
704 }
705 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
706 if err != nil {
707 return err
708 }
709 if err := qmpClient.Connect(); err != nil {
710 return err
711 }
712 defer func() { _ = qmpClient.Disconnect() }()
713 rawClient := raw.NewMonitor(qmpClient)
714
715 inputs := []raw.InputEvent{
716 raw.InputEventKey{Key: raw.KeyValueQcode(raw.QKeyCodeRet), Down: true},
717 raw.InputEventKey{Key: raw.KeyValueQcode(raw.QKeyCodeRet), Down: false},
718 }
719
720 // TODO: Ideally, we should check the boot status and break earlier.
721 for range 5 {
722 err = rawClient.InputSendEvent(nil, nil, inputs)
723 if err != nil {
724 return err
725 }
726 time.Sleep(time.Second)
727 }
728
729 return nil
730}
731
732func (l *LimaQemuDriver) changeVNCPassword(password string) error {
733 qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
734 err := waitFileExists(qmpSockPath, 30*time.Second)
735 if err != nil {
736 return err
737 }
738 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
739 if err != nil {
740 return err
741 }
742 if err := qmpClient.Connect(); err != nil {
743 return err
744 }
745 defer func() { _ = qmpClient.Disconnect() }()
746 rawClient := raw.NewMonitor(qmpClient)
747 err = rawClient.ChangeVNCPassword(password)
748 if err != nil {
749 return err
750 }
751 return nil
752}
753
754func (l *LimaQemuDriver) getVNCDisplayPort() (string, error) {
755 qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
756 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
757 if err != nil {
758 return "", err
759 }
760 if err := qmpClient.Connect(); err != nil {
761 return "", err
762 }
763 defer func() { _ = qmpClient.Disconnect() }()
764 rawClient := raw.NewMonitor(qmpClient)
765 info, err := rawClient.QueryVNC()
766 if err != nil {
767 return "", err
768 }
769 return *info.Service, nil
770}
771
772func (l *LimaQemuDriver) removeVNCFiles() error {
773 vncfile := filepath.Join(l.Instance.Dir, filenames.VNCDisplayFile)
774 err := os.RemoveAll(vncfile)
775 if err != nil {
776 return err
777 }
778 vncpwdfile := filepath.Join(l.Instance.Dir, filenames.VNCPasswordFile)
779 err = os.RemoveAll(vncpwdfile)
780 if err != nil {
781 return err
782 }
783 return nil
784}
785
786func (l *LimaQemuDriver) killVhosts() error {
787 var errs []error
788 for i, vhost := range l.vhostCmds {
789 if err := vhost.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
790 errs = append(errs, fmt.Errorf("failed to kill virtiofsd instance #%d: %w", i, err))
791 }
792 }
793
794 return errors.Join(errs...)
795}
796
797func (l *LimaQemuDriver) killSwtpm() error {
798 if l.swtpmCmd == nil || l.swtpmCmd.Process == nil {
799 return nil
800 }
801
802 logrus.Debug("shutting down swtpm process")
803 if err := l.swtpmCmd.Process.Signal(syscall.SIGTERM); err != nil {
804 if errors.Is(err, os.ErrProcessDone) {
805 logrus.Debug("swtpm process was already done")
806 return nil
807 }
808 }
809
810 select {
811 case err, ok := <-l.swtpmWaitCh:
812 if !ok {
813 logrus.Debug("swtpm wait channel was closed")
814 }
815 if err != nil {
816 logrus.Errorf("swtpm exited with error: %v", err)
817 return err
818 }
819 return nil
820 case <-time.After(5 * time.Second):
821 }
822
823 if err := l.swtpmCmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
824 return fmt.Errorf("failed to kill swtpm: %w", err)
825 }
826
827 return nil
828}
829
830func (l *LimaQemuDriver) shutdownQEMU(ctx context.Context, timeout time.Duration, qCmd *exec.Cmd, qWaitCh chan error) error {
831 // "power button" refers to ACPI on the most archs, except RISC-V
832 logrus.Info("Shutting down QEMU with the power button")
833 client := l.usernetClient
834 if usernetIndex := limayaml.FirstUsernetIndex(l.Instance.Config); usernetIndex != -1 {
835 client = usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima)
836 }
837 if client != nil {
838 err := client.UnExposeSSH(l.SSHLocalPort)
839 if err != nil {
840 logrus.Warnf("Failed to remove SSH binding for port %d", l.SSHLocalPort)
841 }
842 }
843 qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
844 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
845 if err != nil {
846 logrus.WithError(err).Warnf("failed to open the QMP socket %#q, forcibly killing QEMU", qmpSockPath)
847 return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
848 }
849 if err := qmpClient.Connect(); err != nil {
850 logrus.WithError(err).Warnf("failed to connect to the QMP socket %#q, forcibly killing QEMU", qmpSockPath)
851 return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
852 }
853 defer func() { _ = qmpClient.Disconnect() }()
854 rawClient := raw.NewMonitor(qmpClient)
855 logrus.Info("Sending QMP system_powerdown command")
856 if err := rawClient.SystemPowerdown(); err != nil {
857 logrus.WithError(err).Warnf("failed to send system_powerdown command via the QMP socket %#q, forcibly killing QEMU", qmpSockPath)
858 return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
859 }
860 timeoutCtx, timeoutCancel := context.WithTimeout(ctx, timeout)
861 defer timeoutCancel()
862
863 select {
864 case qWaitErr, ok := <-qWaitCh:
865 if !ok {
866 logrus.Info("QEMU wait channel was closed")
867 _ = l.removeVNCFiles()
868 return errors.Join(l.killVhosts(), l.killSwtpm())
869 }
870 entry := logrus.NewEntry(logrus.StandardLogger())
871 if qWaitErr != nil {
872 entry = entry.WithError(qWaitErr)
873 }
874 entry.Info("QEMU has exited")
875 _ = l.removeVNCFiles()
876 return errors.Join(qWaitErr, l.killVhosts(), l.killSwtpm())
877 case <-timeoutCtx.Done():
878 if qCmd.ProcessState != nil {
879 logrus.Info("QEMU has already exited")
880 _ = l.removeVNCFiles()
881 return errors.Join(l.killVhosts(), l.killSwtpm())
882 }
883 logrus.Warnf("QEMU did not exit in %v, forcibly killing QEMU", timeout)
884 return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
885 }
886}
887
888func (l *LimaQemuDriver) killQEMU(_ context.Context, _ time.Duration, qCmd *exec.Cmd, qWaitCh chan error) error {
889 var qWaitErr error
890 if qCmd.ProcessState == nil {
891 if killErr := qCmd.Process.Kill(); killErr != nil {
892 logrus.WithError(killErr).Warn("failed to kill QEMU")
893 }
894 qWaitErr = <-qWaitCh
895 logrus.WithError(qWaitErr).Info("QEMU has exited, after killing forcibly")
896 } else {
897 logrus.Info("QEMU has already exited")
898 }
899 qemuPIDPath := filepath.Join(l.Instance.Dir, filenames.PIDFile(*l.Instance.Config.VMType))
900 _ = os.RemoveAll(qemuPIDPath)
901 _ = l.removeVNCFiles()
902 return errors.Join(qWaitErr, l.killVhosts(), l.killSwtpm())
903}
904
905func logPipeRoutine(r io.Reader, header string) {
906 scanner := bufio.NewScanner(r)
907 for scanner.Scan() {
908 line := scanner.Text()
909 logrus.Debugf("%s: %s", header, line)
910 }
911}
912
913func (l *LimaQemuDriver) DeleteSnapshot(ctx context.Context, tag string) error {
914 qCfg := Config{
915 Name: l.Instance.Name,
916 InstanceDir: l.Instance.Dir,
917 LimaYAML: l.Instance.Config,
918 }
919 return Del(ctx, qCfg, l.Instance.Status == limatype.StatusRunning, tag)
920}
921
922func (l *LimaQemuDriver) CreateSnapshot(ctx context.Context, tag string) error {
923 qCfg := Config{
924 Name: l.Instance.Name,
925 InstanceDir: l.Instance.Dir,
926 LimaYAML: l.Instance.Config,
927 }
928 return Save(ctx, qCfg, l.Instance.Status == limatype.StatusRunning, tag)
929}
930
931func (l *LimaQemuDriver) ApplySnapshot(ctx context.Context, tag string) error {
932 qCfg := Config{
933 Name: l.Instance.Name,
934 InstanceDir: l.Instance.Dir,
935 LimaYAML: l.Instance.Config,
936 }
937 return Load(ctx, qCfg, l.Instance.Status == limatype.StatusRunning, tag)
938}
939
940func (l *LimaQemuDriver) ListSnapshots(ctx context.Context) (string, error) {
941 qCfg := Config{
942 Name: l.Instance.Name,
943 InstanceDir: l.Instance.Dir,
944 LimaYAML: l.Instance.Config,
945 }
946 return List(ctx, qCfg, l.Instance.Status == limatype.StatusRunning)
947}
948
949func (l *LimaQemuDriver) GuestAgentConn(ctx context.Context) (net.Conn, string, error) {
950 var d net.Dialer
951 dialContext, err := d.DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.GuestAgentSock))
952 return dialContext, "unix", err
953}
954
955type qArgTemplateApplier struct {
956 files []*os.File
957 // dgram is the file fd_dgram passes to QEMU.
958 dgram *os.File
959}
960
961func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
962 if !strings.Contains(qArg, "{{") {
963 return qArg, nil
964 }
965 funcMap := template.FuncMap{
966 "fd_connect": func(v any) string {
967 fn := func(v any) (string, error) {
968 s, ok := v.(string)
969 if !ok {
970 return "", fmt.Errorf("non-string argument %+v", v)
971 }
972 addr, err := net.ResolveUnixAddr("unix", s)
973 if err != nil {
974 return "", err
975 }
976 conn, err := net.DialUnix("unix", nil, addr)
977 if err != nil {
978 return "", err
979 }
980 f, err := conn.File()
981 if err != nil {
982 return "", err
983 }
984 if err := conn.Close(); err != nil {
985 return "", err
986 }
987 a.files = append(a.files, f)
988 fd := len(a.files) + 2 // the first FD is 3
989 return strconv.Itoa(fd), nil
990 }
991 res, err := fn(v)
992 if err != nil {
993 panic(fmt.Errorf("fd_connect: %w", err))
994 }
995 return res
996 },
997 "fd_dgram": func() (string, error) {
998 if a.dgram == nil {
999 return "", errors.New("fd_dgram: no datagram socket")
1000 }
1001 a.files = append(a.files, a.dgram)
1002 return strconv.Itoa(len(a.files) + 2), nil
1003 },
1004 }
1005 tmpl, err := template.New("").Funcs(funcMap).Parse(qArg)
1006 if err != nil {
1007 return "", err
1008 }
1009 var b bytes.Buffer
1010 if err := tmpl.Execute(&b, nil); err != nil {
1011 return "", err
1012 }
1013 return b.String(), nil
1014}
1015
1016func (l *LimaQemuDriver) Info(_ context.Context) driver.Info {
1017 var info driver.Info
1018 info.Name = "qemu"
1019 if l.Instance != nil && l.Instance.Dir != "" {
1020 info.InstanceDir = l.Instance.Dir
1021 }
1022 info.VirtioPort = l.virtioPort
1023 info.VsockPort = l.vSockPort
1024
1025 info.Features = driver.DriverFeatures{
1026 DynamicSSHAddress: false,
1027 SkipSocketForwarding: false,
1028 CanRunGUI: false,
1029 SupportedImageFormats: []string{string(qcow2.Type), string(rawImage.Type), string(vmdk.Type), string(vhdx.Type)}, // Not a comprehensive list of supported formats
1030 }
1031 return info
1032}
1033
1034func (l *LimaQemuDriver) SSHAddress(_ context.Context) (string, error) {
1035 return "127.0.0.1", nil
1036}
1037
1038func (l *LimaQemuDriver) InspectStatus(_ context.Context, _ *limatype.Instance) string {
1039 return ""
1040}
1041
1042func (l *LimaQemuDriver) Create(_ context.Context) error {
1043 return nil
1044}
1045
1046func (l *LimaQemuDriver) Delete(_ context.Context) error {
1047 return nil
1048}
1049
1050func (l *LimaQemuDriver) RunGUI(_ context.Context) error {
1051 return nil
1052}
1053
1054func (l *LimaQemuDriver) Register(_ context.Context) error {
1055 return nil
1056}
1057
1058func (l *LimaQemuDriver) Unregister(_ context.Context) error {
1059 return nil
1060}
1061
1062func (l *LimaQemuDriver) ForwardGuestAgent(_ context.Context) bool {
1063 // if driver is not providing, use host agent
1064 return l.vSockPort == 0 && l.virtioPort == ""
1065}
1066
1067func (l *LimaQemuDriver) AdditionalSetupForSSH(_ context.Context) error {
1068 return nil
1069}
1070
1071func (l *LimaQemuDriver) CaptureScreenshot(format string) ([]byte, error) {
1072 if format == "" {
1073 format = "png"
1074 }
1075 if format != "png" && format != "bmp" {
1076 return nil, fmt.Errorf("unsupported format %q: must be png or bmp", format)
1077 }
1078
1079 if l.Instance.Config.Video.Display != nil && *l.Instance.Config.Video.Display == "none" {
1080 return nil, fmt.Errorf("%w (set video.display to \"default\" or a VNC display to enable screenshots)", driver.ErrNoDisplay)
1081 }
1082
1083 qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
1084 err := waitFileExists(qmpSockPath, 30*time.Second)
1085 if err != nil {
1086 return nil, err
1087 }
1088
1089 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
1090 if err != nil {
1091 return nil, err
1092 }
1093 if err := qmpClient.Connect(); err != nil {
1094 return nil, err
1095 }
1096 defer func() { _ = qmpClient.Disconnect() }()
1097
1098 rawClient := raw.NewMonitor(qmpClient)
1099
1100 tmpFile, err := os.CreateTemp("", "screendump-*.ppm")
1101 if err != nil {
1102 return nil, fmt.Errorf("failed to create temporary file: %w", err)
1103 }
1104 tmpPath := tmpFile.Name()
1105 defer os.Remove(tmpPath)
1106 tmpFile.Close()
1107
1108 if err := rawClient.Screendump(tmpPath); err != nil {
1109 return nil, fmt.Errorf("screendump failed: %w", err)
1110 }
1111
1112 data, err := os.ReadFile(tmpPath)
1113 if err != nil {
1114 return nil, fmt.Errorf("failed to read screendump: %w", err)
1115 }
1116
1117 img, err := netpbm.Decode(bytes.NewReader(data), nil)
1118 if err != nil {
1119 return nil, fmt.Errorf("failed to decode PPM screendump: %w", err)
1120 }
1121
1122 var buf bytes.Buffer
1123 if format == "bmp" {
1124 if err := bmp.Encode(&buf, img); err != nil {
1125 return nil, fmt.Errorf("failed to encode BMP: %w", err)
1126 }
1127 } else {
1128 if err := png.Encode(&buf, img); err != nil {
1129 return nil, fmt.Errorf("failed to encode PNG: %w", err)
1130 }
1131 }
1132
1133 return buf.Bytes(), nil
1134}