跳到主要内容

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

浏览文件

vz_driver_darwin.go

733 行 · 21.8 KB历史下载
1//go:build darwin && !no_vz
2
3// SPDX-FileCopyrightText: Copyright The Lima Authors
4// SPDX-License-Identifier: Apache-2.0
5
6package vz
7
8import (
9 "context"
10 "embed"
11 "errors"
12 "fmt"
13 "net"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "runtime"
18 "time"
19
20 "github.com/Code-Hex/vz/v3"
21 continuityfs "github.com/containerd/continuity/fs"
22 "github.com/coreos/go-semver/semver"
23 "github.com/docker/go-units"
24 "github.com/lima-vm/go-qcow2reader/image"
25 "github.com/lima-vm/go-qcow2reader/image/asif"
26 "github.com/lima-vm/go-qcow2reader/image/raw"
27 "github.com/opencontainers/go-digest"
28 "github.com/sirupsen/logrus"
29 "golang.org/x/sys/unix"
30
31 "github.com/lima-vm/lima/v2/pkg/driver"
32 "github.com/lima-vm/lima/v2/pkg/driverutil"
33 "github.com/lima-vm/lima/v2/pkg/fileutils"
34 "github.com/lima-vm/lima/v2/pkg/guestpatch/macos"
35 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
36 "github.com/lima-vm/lima/v2/pkg/imgutil/nativeimgutil"
37 "github.com/lima-vm/lima/v2/pkg/imgutil/nativeimgutil/asifutil"
38 "github.com/lima-vm/lima/v2/pkg/limatype"
39 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
40 "github.com/lima-vm/lima/v2/pkg/limayaml"
41 "github.com/lima-vm/lima/v2/pkg/lockutil"
42 "github.com/lima-vm/lima/v2/pkg/osutil"
43 "github.com/lima-vm/lima/v2/pkg/reflectutil"
44 "github.com/lima-vm/lima/v2/pkg/sshutil"
45)
46
47var knownYamlProperties = []string{
48 "AdditionalDisks",
49 "Arch",
50 "Audio",
51 "CACertificates",
52 "Containerd",
53 "CopyToHost",
54 "CPUs",
55 "CPUType",
56 "Disk",
57 "DNS",
58 "Env",
59 "Firmware",
60 "GuestInstallPrefix",
61 "HostResolver",
62 "Images",
63 "Memory",
64 "Message",
65 "MinimumLimaVersion",
66 "Mounts",
67 "MountType",
68 "MountTypesUnsupported",
69 "MountInotify",
70 "NestedVirtualization",
71 "Networks",
72 "OS",
73 "OsOpts",
74 "Param",
75 "Plain",
76 "PortForwards",
77 "Probes",
78 "PropagateProxyEnv",
79 "Provision",
80 "Rosetta",
81 "SSH",
82 "TimeZone",
83 "TPM",
84 "UpgradePackages",
85 "User",
86 "Video",
87 "VMType",
88 "VMOpts",
89}
90
91const Enabled = true
92
93type LimaVzDriver struct {
94 Instance *limatype.Instance
95
96 SSHLocalPort int
97 vSockPort int
98 virtioPort string
99 rosettaEnabled bool
100 rosettaBinFmt bool
101 diskImageFormat image.Type
102
103 machine *virtualMachineWrapper
104 waitSSHLocalPortAccessible <-chan any
105
106 onVsockEvent func(*events.VsockEvent)
107}
108
109var (
110 _ driver.Driver = (*LimaVzDriver)(nil)
111 _ driver.VsockEventEmitter = (*LimaVzDriver)(nil)
112)
113
114// SetVsockEventCallback implements driver.VsockEventEmitter.
115func (l *LimaVzDriver) SetVsockEventCallback(callback func(*events.VsockEvent)) {
116 l.onVsockEvent = callback
117}
118
119func New() *LimaVzDriver {
120 return &LimaVzDriver{
121 vSockPort: 2222,
122 virtioPort: "",
123 }
124}
125
126func (l *LimaVzDriver) Configure(_ context.Context, inst *limatype.Instance) (*driver.ConfiguredDriver, error) {
127 if err := fillConfig(inst.Config); err != nil {
128 return nil, err
129 }
130
131 l.Instance = inst
132 l.SSHLocalPort = inst.SSHLocalPort
133
134 if l.Instance.Config.MountType != nil {
135 mountTypesUnsupported := make(map[string]struct{})
136 for _, f := range l.Instance.Config.MountTypesUnsupported {
137 mountTypesUnsupported[f] = struct{}{}
138 }
139
140 if _, ok := mountTypesUnsupported[*l.Instance.Config.MountType]; ok {
141 // We cannot return an error here, but Validate() will return it.
142 logrus.Warnf("Unsupported mount type: %#q", *l.Instance.Config.MountType)
143 }
144 }
145
146 var vzOpts limatype.VZOpts
147 if l.Instance.Config.VMOpts[limatype.VZ] != nil {
148 if err := limayaml.Convert(l.Instance.Config.VMOpts[limatype.VZ], &vzOpts, "vmOpts.vz"); err != nil {
149 logrus.WithError(err).Warnf("Couldn't convert %#q", l.Instance.Config.VMOpts[limatype.VZ])
150 }
151 }
152
153 if runtime.GOOS == "darwin" && limatype.IsNativeArch(limatype.AARCH64) {
154 if vzOpts.Rosetta.Enabled != nil {
155 l.rosettaEnabled = *vzOpts.Rosetta.Enabled
156 }
157 }
158 if vzOpts.Rosetta.BinFmt != nil {
159 l.rosettaBinFmt = *vzOpts.Rosetta.BinFmt
160 }
161 if vzOpts.DiskImageFormat != nil {
162 l.diskImageFormat = *vzOpts.DiskImageFormat
163 } else {
164 l.diskImageFormat = raw.Type
165 }
166
167 return &driver.ConfiguredDriver{
168 Driver: l,
169 }, nil
170}
171
172func fillConfig(cfg *limatype.LimaYAML) error {
173 if cfg.VMType == nil {
174 cfg.VMType = new(limatype.VZ)
175 }
176
177 if cfg.MountType == nil {
178 cfg.MountType = new(limatype.VIRTIOFS)
179 }
180
181 if cfg.SSH.OverVsock == nil {
182 cfg.SSH.OverVsock = new(*cfg.OS == limatype.LINUX)
183 }
184
185 var vzOpts limatype.VZOpts
186 if err := limayaml.Convert(cfg.VMOpts[limatype.VZ], &vzOpts, "vmOpts.vz"); err != nil {
187 logrus.WithError(err).Warnf("Couldn't convert %#q", cfg.VMOpts[limatype.VZ])
188 }
189
190 //nolint:staticcheck // Migration of top-level Rosetta if specified
191 if (vzOpts.Rosetta.Enabled == nil && vzOpts.Rosetta.BinFmt == nil) && (!isEmpty(cfg.Rosetta)) {
192 logrus.Debug("Migrating top-level Rosetta configuration to vmOpts.vz.rosetta")
193 vzOpts.Rosetta = cfg.Rosetta
194 }
195 //nolint:staticcheck // Warning about both top-level and vmOpts.vz.Rosetta being set
196 if (vzOpts.Rosetta.Enabled != nil && vzOpts.Rosetta.BinFmt != nil) && (!isEmpty(cfg.Rosetta)) {
197 logrus.Warn("Both top-level 'rosetta' and 'vmOpts.vz.rosetta' are configured. Using vmOpts.vz.rosetta. Top-level 'rosetta' is deprecated.")
198 }
199
200 if vzOpts.Rosetta.Enabled == nil {
201 vzOpts.Rosetta.Enabled = new(false)
202 }
203 if vzOpts.Rosetta.BinFmt == nil {
204 vzOpts.Rosetta.BinFmt = new(false)
205 }
206 if vzOpts.DiskImageFormat == nil {
207 // Default to ASIF for macOS guests on macOS 26+, raw otherwise.
208 if cfg.OS != nil && *cfg.OS == limatype.DARWIN {
209 macOSProductVersion, err := osutil.ProductVersion()
210 if err == nil && !macOSProductVersion.LessThan(*semver.New("26.0.0")) {
211 vzOpts.DiskImageFormat = new(asif.Type)
212 } else {
213 vzOpts.DiskImageFormat = new(raw.Type)
214 }
215 } else {
216 vzOpts.DiskImageFormat = new(raw.Type)
217 }
218 }
219
220 var opts any
221 if err := limayaml.Convert(vzOpts, &opts, ""); err != nil {
222 logrus.WithError(err).Warnf("Couldn't convert %+v", vzOpts)
223 }
224 if cfg.VMOpts == nil {
225 cfg.VMOpts = limatype.VMOpts{}
226 }
227 cfg.VMOpts[limatype.VZ] = opts
228
229 return validateConfig(cfg)
230}
231
232func isEmpty(r limatype.Rosetta) bool {
233 return r.Enabled == nil && r.BinFmt == nil
234}
235
236//go:embed boot.Linux/*.sh
237var bootLinuxFS embed.FS
238
239func (l *LimaVzDriver) BootScripts(_ context.Context) (map[string][]byte, error) {
240 scripts := make(map[string][]byte)
241
242 entries, err := bootLinuxFS.ReadDir("boot.Linux")
243 if err == nil {
244 for _, entry := range entries {
245 if entry.IsDir() {
246 continue
247 }
248 entryPath := "boot.Linux/" + entry.Name()
249
250 content, err := bootLinuxFS.ReadFile(entryPath)
251 if err != nil {
252 return nil, err
253 }
254
255 scripts[entryPath] = content
256 }
257 }
258
259 return scripts, nil
260}
261
262func (l *LimaVzDriver) Validate(_ context.Context) error {
263 return validateConfig(l.Instance.Config)
264}
265
266func validateConfig(cfg *limatype.LimaYAML) error {
267 if cfg == nil {
268 return errors.New("configuration is nil")
269 }
270 macOSProductVersion, err := osutil.ProductVersion()
271 if err != nil {
272 return err
273 }
274 if macOSProductVersion.LessThan(*semver.New("13.0.0")) {
275 return errors.New("VZ driver requires macOS 13 or higher to run")
276 }
277 if runtime.GOARCH == "amd64" && macOSProductVersion.LessThan(*semver.New("15.5.0")) {
278 logrus.Warnf("vmType %s: On Intel Mac, macOS 15.5 or later is required to run Linux 6.12 or later. "+
279 "Update macOS, or change vmType to `qemu` if the VM does not start up. (https://github.com/lima-vm/lima/issues/3334)",
280 *cfg.VMType)
281 }
282 if cfg.MountType != nil && *cfg.MountType == limatype.NINEP {
283 return fmt.Errorf("field `mountType` must be %#q or %#q for VZ driver , got %#q", limatype.REVSSHFS, limatype.VIRTIOFS, *cfg.MountType)
284 }
285 if cfg.TPM != nil && *cfg.TPM {
286 return errors.New("field `tpm` is not supported on VZ driver")
287 }
288 if cfg.OS != nil && *cfg.OS == limatype.WINDOWS {
289 return errors.New("currently Windows guest OS is only supported on QEMU")
290 }
291 if *cfg.Firmware.LegacyBIOS {
292 logrus.Warnf("vmType %s: ignoring `firmware.legacyBIOS`", *cfg.VMType)
293 }
294 for _, f := range cfg.Firmware.Images {
295 switch f.VMType {
296 case "", limatype.VZ:
297 if f.Arch == *cfg.Arch {
298 return errors.New("`firmware.images` configuration is not supported for VZ driver")
299 }
300 }
301 }
302 if unknown := reflectutil.UnknownNonEmptyFields(cfg, knownYamlProperties...); cfg.VMType != nil && len(unknown) > 0 {
303 logrus.Warnf("vmType %s: ignoring %+v", *cfg.VMType, unknown)
304 }
305
306 if !limatype.IsNativeArch(*cfg.Arch) {
307 return fmt.Errorf("unsupported arch: %#q", *cfg.Arch)
308 }
309
310 for i, image := range cfg.Images {
311 if unknown := reflectutil.UnknownNonEmptyFields(image, "File", "Kernel", "Initrd", "Variant", "ArchVariant"); len(unknown) > 0 {
312 logrus.Warnf("vmType %s: ignoring images[%d]: %+v", *cfg.VMType, i, unknown)
313 }
314 }
315
316 for i, mount := range cfg.Mounts {
317 if unknown := reflectutil.UnknownNonEmptyFields(mount, "Location",
318 "MountPoint",
319 "Writable",
320 "SSHFS",
321 "NineP",
322 ); len(unknown) > 0 {
323 logrus.Warnf("vmType %s: ignoring mounts[%d]: %+v", *cfg.VMType, i, unknown)
324 }
325 }
326
327 for i, nw := range cfg.Networks {
328 if unknown := reflectutil.UnknownNonEmptyFields(nw, "VZNAT",
329 "Lima",
330 "Socket",
331 "MACAddress",
332 "Metric",
333 "Interface",
334 ); len(unknown) > 0 {
335 logrus.Warnf("vmType %s: ignoring networks[%d]: %+v", *cfg.VMType, i, unknown)
336 }
337 }
338
339 switch audioDevice := *cfg.Audio.Device; audioDevice {
340 case "":
341 case "vz", "default", "none":
342 default:
343 logrus.Warnf("field `audio.device` must be `vz`, `default`, or `none` for VZ driver, got %#q", audioDevice)
344 }
345
346 switch videoDisplay := *cfg.Video.Display; videoDisplay {
347 case "vz", "default", "none", "offscreen":
348 default:
349 logrus.Warnf("field `video.display` must be `vz`, `default`, `none`, or `offscreen` for VZ driver, got %#q", videoDisplay)
350 }
351 var vzOpts limatype.VZOpts
352 if err := limayaml.Convert(cfg.VMOpts[limatype.VZ], &vzOpts, "vmOpts.vz"); err != nil {
353 logrus.WithError(err).Warnf("Couldn't convert %#q", cfg.VMOpts[limatype.VZ])
354 }
355 switch *vzOpts.DiskImageFormat {
356 case raw.Type:
357 case asif.Type:
358 if macOSProductVersion.LessThan(*semver.New("26.0.0")) {
359 return fmt.Errorf("vmOpts.vz.diskImageFormat=%#q requires macOS 26 or higher to run, got %#q", asif.Type, macOSProductVersion)
360 }
361 default:
362 return fmt.Errorf("field `vmOpts.vz.diskImageFormat` must be %#q or %#q, got %#q", raw.Type, asif.Type, *vzOpts.DiskImageFormat)
363 }
364 return nil
365}
366
367func (l *LimaVzDriver) Create(_ context.Context) error {
368 identifierFile := filepath.Join(l.Instance.Dir, filenames.VzIdentifier)
369 if *l.Instance.Config.OS == limatype.DARWIN {
370 _, err := getMacMachineIdentifier(identifierFile)
371 return err
372 }
373 _, err := getGenericMachineIdentifier(identifierFile)
374 return err
375}
376
377func (l *LimaVzDriver) CreateDisk(ctx context.Context) error {
378 if *l.Instance.Config.OS != limatype.DARWIN {
379 return driverutil.EnsureDisk(ctx, l.Instance.Dir, *l.Instance.Config.Disk, l.diskImageFormat)
380 }
381 return lockutil.WithDirLock(l.Instance.Dir, func() error {
382 if err := ctx.Err(); err != nil {
383 return err
384 }
385 disk := filepath.Join(l.Instance.Dir, filenames.Disk)
386 if err := restoreMacOSDisk(disk, func(staging string) error { return l.createDiskMacOSGuest(ctx, staging) }); err != nil {
387 return err
388 }
389 patchedMarker := disk + ".patched"
390 if osutil.FileExists(patchedMarker) {
391 return nil
392 }
393 logrus.Infof("Patching macOS disk %#q", disk)
394 if err := macos.Patch(ctx, disk); err != nil {
395 return fmt.Errorf("preparing existing macOS disk %q: %w", disk, err)
396 }
397 return os.WriteFile(patchedMarker, nil, 0o644)
398 })
399}
400
401// restoreMacOSDisk is called with the instance lock held. Existing guest disks
402// are never replaced. A process that exits during restore leaves only staging.
403func restoreMacOSDisk(disk string, install func(string) error) error {
404 if _, err := os.Lstat(disk); err == nil || !errors.Is(err, os.ErrNotExist) {
405 return err
406 }
407 staging := disk + ".installing"
408 // diskutil can append .asif when creating a blank disk. A killed process
409 // can leave either name behind. A fresh install also needs a fresh patch.
410 for _, path := range []string{staging, staging + ".asif", disk + ".patched"} {
411 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
412 return err
413 }
414 }
415 defer os.Remove(staging)
416 defer os.Remove(staging + ".asif")
417 if err := install(staging); err != nil {
418 return err
419 }
420 if err := unix.RenamexNp(staging, disk, unix.RENAME_EXCL); err != nil {
421 return err
422 }
423 // Remove only the instance's installation media after the disk is ready.
424 for _, filename := range []string{filenames.ImageIPSW, filenames.Image} {
425 path := filepath.Join(filepath.Dir(disk), filename)
426 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
427 logrus.WithError(err).Warnf("Failed to remove %#q", path)
428 }
429 }
430 return nil
431}
432
433// verifiedMacOSIPSW runs under the instance's restore lock. It checks the
434// actual private installer input, including media left after an interruption.
435func verifiedMacOSIPSW(ctx context.Context, inst *limatype.Instance) (string, error) {
436 if err := ensureIPSW(inst.Dir); err != nil {
437 return "", err
438 }
439 ipsw := filepath.Join(inst.Dir, filenames.ImageIPSW)
440 images := inst.Config.Images
441 if len(images) != 1 || !filepath.IsAbs(images[0].Location) || images[0].Digest == "" {
442 return ipsw, nil
443 }
444 expected := images[0].Digest
445 if err := expected.Validate(); err != nil {
446 return "", err
447 }
448 if expected.Algorithm() != digest.SHA256 {
449 return ipsw, nil
450 }
451 actual, err := fileutils.RestoreImageDigest(ctx, ipsw, nil)
452 if err != nil {
453 return "", err
454 }
455 if actual == expected {
456 return ipsw, nil
457 }
458 // Recover a stale private copy if the selected source is available again.
459 // Copy-on-write on APFS freezes the bytes at clone time. Only a verified
460 // copy can replace the private input; the selected file stays untouched.
461 tmpDir, err := os.MkdirTemp(inst.Dir, ".ipsw-repair-")
462 if err != nil {
463 return "", err
464 }
465 defer os.Remove(tmpDir)
466 staging := filepath.Join(tmpDir, "restore.ipsw")
467 defer os.Remove(staging)
468 if err := continuityfs.CopyFile(staging, images[0].Location); err != nil {
469 return "", fmt.Errorf("private IPSW digest mismatch; cannot recover the selected source: %w", err)
470 }
471 actual, err = fileutils.RestoreImageDigest(ctx, staging, nil)
472 if err != nil {
473 return "", err
474 }
475 if actual != expected {
476 return "", fmt.Errorf("macOS restore image digest mismatch: expected %s, got %s", expected, actual)
477 }
478 if err := os.Rename(staging, ipsw); err != nil {
479 return "", err
480 }
481 return ipsw, nil
482}
483
484func (l *LimaVzDriver) createDiskMacOSGuest(ctx context.Context, disk string) error {
485 ipsw, err := verifiedMacOSIPSW(ctx, l.Instance)
486 if err != nil {
487 return err
488 }
489 diskSize, err := units.RAMInBytes(*l.Instance.Config.Disk)
490 if err != nil {
491 return fmt.Errorf("invalid disk size %#q: %w", *l.Instance.Config.Disk, err)
492 }
493
494 switch l.diskImageFormat {
495 case asif.Type:
496 if err := asifutil.NewASIF(disk, diskSize); err != nil {
497 return err
498 }
499 case raw.Type:
500 logrus.Debugf("Using %s disk image for macOS guest", l.diskImageFormat)
501 diskUtil := &nativeimgutil.NativeImageUtil{}
502 if err := diskUtil.CreateDisk(ctx, disk, diskSize); err != nil {
503 return fmt.Errorf("failed to create %s disk %#q: %w", l.diskImageFormat, disk, err)
504 }
505 default:
506 return fmt.Errorf("unsupported disk format for macOS guest: %s", l.diskImageFormat)
507 }
508
509 vm, err := createVMForMacInstaller(ctx, l.Instance, disk)
510 if err != nil {
511 return err
512 }
513
514 logrus.Info("Running macOS installer (takes a few minutes)")
515 // FIXME: do we need to run the installer for every new instance,
516 // or can we safely reuse the installed disk image?
517 if err := installMacOS(ctx, vm, ipsw); err != nil {
518 return fmt.Errorf("failed to install macOS: %w", err)
519 }
520
521 return nil
522}
523
524func (l *LimaVzDriver) Start(ctx context.Context) (chan error, error) {
525 logrus.Infof("Starting VZ (hint: to watch the boot progress, see %#q)", filepath.Join(l.Instance.Dir, "serial*.log"))
526 vm, waitSSHLocalPortAccessible, errCh, err := startVM(ctx, l.Instance, l.SSHLocalPort, l.onVsockEvent)
527 if err != nil {
528 if errors.Is(err, vz.ErrUnsupportedOSVersion) {
529 return nil, fmt.Errorf("vz driver requires macOS 13 or higher to run: %w", err)
530 }
531 return nil, err
532 }
533 l.machine = vm
534 l.waitSSHLocalPortAccessible = waitSSHLocalPortAccessible
535
536 return errCh, nil
537}
538
539// OffscreenView lets an embedding application service a user-authorized login
540// view without opening Lima's VM window. The application must bind the exact instance.
541var OffscreenView func(ctx context.Context, machine *vz.VirtualMachine, instanceDir string) error
542var OwnsOffscreenView func(instanceDir string) bool
543
544func (l *LimaVzDriver) canRunGUI() bool {
545 switch *l.Instance.Config.Video.Display {
546 case "offscreen":
547 return *l.Instance.Config.OS == limatype.DARWIN && OffscreenView != nil && OwnsOffscreenView != nil && OwnsOffscreenView(l.Instance.Dir)
548 case "vz", "default":
549 return true
550 default:
551 return false
552 }
553}
554
555func (l *LimaVzDriver) RunGUI(ctx context.Context) error {
556 if l.canRunGUI() {
557 if *l.Instance.Config.Video.Display == "offscreen" {
558 return OffscreenView(ctx, l.machine.VirtualMachine, l.Instance.Dir)
559 }
560 title := fmt.Sprintf("Lima: %s", l.Instance.Name)
561 return l.machine.StartGraphicApplication(1920, 1200, vz.WithWindowTitle(title))
562 }
563 return fmt.Errorf("RunGUI is not supported for the given driver '%s' and display '%s'", "vz", *l.Instance.Config.Video.Display)
564}
565
566func (l *LimaVzDriver) requestStopViaSSH(ctx context.Context) error {
567 sshExe, err := sshutil.NewSSHExe()
568 if err != nil {
569 return err
570 }
571 cmd := exec.CommandContext(ctx, sshExe.Exe,
572 append(sshExe.Args, "-F", l.Instance.SSHConfigFile, l.Instance.Hostname, "--",
573 "sudo", "/sbin/shutdown", "-h", "now")...)
574 logrus.Infof("Running shutdown command in the VM: %v", cmd.Args)
575 if out, err := cmd.CombinedOutput(); err != nil {
576 return fmt.Errorf("failed to run %v: %w (output=%s)", cmd.Args, err, string(out))
577 }
578 return nil
579}
580
581// gracefulStopTimeout is how long to wait for the guest to shut down by itself.
582// Most Linux machines shutdown within 5 seconds, but macOS machines can take longer.
583const gracefulStopTimeout = 30 * time.Second
584
585func (l *LimaVzDriver) Stop(ctx context.Context) error {
586 logrus.Info("Shutting down VZ")
587
588 requested := false
589 if l.machine.CanRequestStop() {
590 // The returned boolean tells whether the request was made, not whether the guest
591 // has already stopped.
592 var err error
593 if requested, err = l.machine.RequestStop(); err != nil {
594 logrus.WithError(err).Warn("vz: failed to request the guest to stop")
595 }
596 } else {
597 logrus.Warn("vz: CanRequestStop is not supported")
598 }
599
600 // macOS VM does not respond to l.machine.RequestStop(), and neither does a guest that
601 // could not be asked at all, so we need to run `shutdown -h now` in the VM via SSH for
602 // graceful shutdown.
603 if !requested || *l.Instance.Config.OS == limatype.DARWIN {
604 if err := l.requestStopViaSSH(ctx); err != nil {
605 logrus.WithError(err).Warn("Failed to request shutdown via SSH")
606 }
607 }
608
609 // The VM is never stopped forcibly with l.machine.Stop(): that does not give the guest
610 // a chance to stop cleanly, and may corrupt the disk.
611 if err := l.waitForStopped(gracefulStopTimeout); err != nil {
612 // Retain the owner record while the VM may still be running.
613 return err
614 }
615 l.removePIDFile()
616 return nil
617}
618
619func (l *LimaVzDriver) waitForStopped(timeout time.Duration) error {
620 timeoutCh := time.After(timeout)
621 ticker := time.NewTicker(500 * time.Millisecond)
622 defer ticker.Stop()
623 for {
624 select {
625 case <-timeoutCh:
626 return errors.New("vz timeout while waiting for stop status")
627 case <-ticker.C:
628 l.machine.mu.Lock()
629 stopped := l.machine.stopped
630 l.machine.mu.Unlock()
631 if stopped {
632 return nil
633 }
634 }
635 }
636}
637
638// removePIDFile removes the PID file of the driver, so that a PID file is never left
639// behind for a VM that is not running anymore.
640func (l *LimaVzDriver) removePIDFile() {
641 pidFile := filepath.Join(l.Instance.Dir, filenames.PIDFile(*l.Instance.Config.VMType))
642 if err := os.RemoveAll(pidFile); err != nil {
643 logrus.WithError(err).Warnf("Failed to remove %#q", pidFile)
644 }
645}
646
647func (l *LimaVzDriver) GuestAgentConn(_ context.Context) (net.Conn, string, error) {
648 for _, socket := range l.machine.SocketDevices() {
649 connect, err := socket.Connect(uint32(l.vSockPort))
650 return connect, "vsock", err
651 }
652
653 return nil, "", errors.New("unable to connect to guest agent via vsock port 2222")
654}
655
656func (l *LimaVzDriver) Info(_ context.Context) driver.Info {
657 var info driver.Info
658
659 info.Name = "vz"
660 info.VsockPort = l.vSockPort
661 info.VirtioPort = l.virtioPort
662 if l.Instance != nil {
663 info.InstanceDir = l.Instance.Dir
664 }
665
666 var guiFlag bool
667 if l.Instance != nil {
668 guiFlag = l.canRunGUI()
669 }
670 info.Features = driver.DriverFeatures{
671 DynamicSSHAddress: false,
672 SkipSocketForwarding: false,
673 CanRunGUI: guiFlag,
674 RosettaEnabled: l.rosettaEnabled,
675 RosettaBinFmt: l.rosettaBinFmt,
676 SupportedImageFormats: []string{string(raw.Type), string(asif.Type)},
677 }
678 return info
679}
680
681func (l *LimaVzDriver) SSHAddress(_ context.Context) (string, error) {
682 return "127.0.0.1", nil
683}
684
685func (l *LimaVzDriver) InspectStatus(_ context.Context, _ *limatype.Instance) string {
686 return ""
687}
688
689func (l *LimaVzDriver) Delete(_ context.Context) error {
690 return nil
691}
692
693func (l *LimaVzDriver) Register(_ context.Context) error {
694 return nil
695}
696
697func (l *LimaVzDriver) Unregister(_ context.Context) error {
698 return nil
699}
700
701func (l *LimaVzDriver) ChangeDisplayPassword(_ context.Context, _ string) error {
702 return nil
703}
704
705func (l *LimaVzDriver) DisplayConnection(_ context.Context) (string, error) {
706 return "", nil
707}
708
709func (l *LimaVzDriver) CreateSnapshot(_ context.Context, _ string) error {
710 return errUnimplemented
711}
712
713func (l *LimaVzDriver) ApplySnapshot(_ context.Context, _ string) error {
714 return errUnimplemented
715}
716
717func (l *LimaVzDriver) DeleteSnapshot(_ context.Context, _ string) error {
718 return errUnimplemented
719}
720
721func (l *LimaVzDriver) ListSnapshots(_ context.Context) (string, error) {
722 return "", errUnimplemented
723}
724
725func (l *LimaVzDriver) ForwardGuestAgent(_ context.Context) bool {
726 // If driver is not providing, use host agent
727 return l.vSockPort == 0 && l.virtioPort == ""
728}
729
730func (l *LimaVzDriver) AdditionalSetupForSSH(_ context.Context) error {
731 <-l.waitSSHLocalPortAccessible
732 return nil
733}