跳到主要内容

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

浏览文件

vm_darwin.go

1001 行 · 31.0 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 "errors"
11 "fmt"
12 "io/fs"
13 "net"
14 "os"
15 "path/filepath"
16 "runtime"
17 "slices"
18 "strconv"
19 "sync"
20 "syscall"
21
22 "github.com/Code-Hex/vz/v3"
23 "github.com/coreos/go-semver/semver"
24 "github.com/docker/go-units"
25 "github.com/lima-vm/go-qcow2reader"
26 "github.com/lima-vm/go-qcow2reader/image"
27 "github.com/lima-vm/go-qcow2reader/image/asif"
28 "github.com/lima-vm/go-qcow2reader/image/raw"
29 "github.com/sirupsen/logrus"
30
31 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
32 "github.com/lima-vm/lima/v2/pkg/imgutil/proxyimgutil"
33 "github.com/lima-vm/lima/v2/pkg/limatype"
34 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
35 "github.com/lima-vm/lima/v2/pkg/limayaml"
36 "github.com/lima-vm/lima/v2/pkg/networks"
37 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
38 "github.com/lima-vm/lima/v2/pkg/osutil"
39 "github.com/lima-vm/lima/v2/pkg/store"
40)
41
42// diskImageCachingMode is set to DiskImageCachingModeCached so as to avoid disk corruption on ARM:
43// - https://github.com/utmapp/UTM/issues/4840#issuecomment-1824340975
44// - https://github.com/utmapp/UTM/issues/4840#issuecomment-1824542732
45//
46// Eventually we may bring this back to DiskImageCachingModeAutomatic when the corruption issue is properly fixed.
47const diskImageCachingMode = vz.DiskImageCachingModeCached
48
49type virtualMachineWrapper struct {
50 *vz.VirtualMachine
51 mu sync.Mutex
52 stopped bool
53}
54
55// Hold all *os.File created via socketpair() so that they won't get garbage collected. f.FD() gets invalid if f gets garbage collected.
56var vmNetworkFiles = make([]*os.File, 1)
57
58func startVM(ctx context.Context, inst *limatype.Instance, sshLocalPort int, onVsockEvent func(*events.VsockEvent)) (vm *virtualMachineWrapper, waitSSHLocalPortAccessible <-chan any, errCh chan error, err error) {
59 usernetClient, stopUsernet, err := startUsernet(ctx, inst)
60 if err != nil {
61 return nil, nil, nil, err
62 }
63
64 machine, err := createVM(ctx, inst)
65 if err != nil {
66 return nil, nil, nil, err
67 }
68
69 err = machine.Start()
70 if err != nil {
71 return nil, nil, nil, err
72 }
73
74 wrapper := &virtualMachineWrapper{VirtualMachine: machine, stopped: false}
75 notifySSHLocalPortAccessible := make(chan any)
76 sendErrCh := make(chan error)
77
78 go func() {
79 // Handle errors via errCh and handle stop vm during context close
80 defer func() {
81 for i := range vmNetworkFiles {
82 vmNetworkFiles[i].Close()
83 }
84 }()
85 for {
86 select {
87 case <-ctx.Done():
88 logrus.Info("Context closed, stopping vm")
89 if machine.CanStop() {
90 _, err := machine.RequestStop()
91 logrus.Errorf("Error while stopping the VM %#q", err)
92 }
93 case newState := <-machine.StateChangedNotify():
94 switch newState {
95 case vz.VirtualMachineStateRunning:
96 pidFile := filepath.Join(inst.Dir, filenames.PIDFile(*inst.Config.VMType))
97 if _, err := os.Stat(pidFile); !errors.Is(err, os.ErrNotExist) {
98 logrus.Errorf("pidfile %#q already exists", pidFile)
99 sendErrCh <- err
100 }
101 if err := store.WritePIDFile(pidFile, os.Getpid()); err != nil {
102 logrus.Errorf("error writing to pid fil %#q", pidFile)
103 sendErrCh <- err
104 }
105 logrus.Info("[VZ] - vm state change: running")
106
107 go func() {
108 defer close(notifySSHLocalPortAccessible)
109 usernetSSHLocalPort := sshLocalPort
110 useSSHOverVsock := *inst.Config.OS == limatype.LINUX
111 if inst.Config.SSH.OverVsock != nil {
112 useSSHOverVsock = *inst.Config.SSH.OverVsock
113 }
114 if !useSSHOverVsock {
115 logrus.Info("ssh.overVsock is false, skipping detection of SSH server on vsock port")
116 if onVsockEvent != nil {
117 onVsockEvent(&events.VsockEvent{
118 Type: events.VsockEventSkipped,
119 Reason: "ssh.overVsock is false",
120 })
121 }
122 } else if err := usernetClient.WaitOpeningSSHPort(ctx, inst); err == nil {
123 hostAddress := net.JoinHostPort(inst.SSHAddress, strconv.Itoa(usernetSSHLocalPort))
124 if err := wrapper.startVsockForwarder(ctx, 22, hostAddress); err == nil {
125 logrus.Infof("Detected SSH server is listening on the vsock port; changed %s to proxy for the vsock port", hostAddress)
126 if onVsockEvent != nil {
127 onVsockEvent(&events.VsockEvent{
128 Type: events.VsockEventStarted,
129 HostAddr: hostAddress,
130 VsockPort: 22,
131 })
132 }
133 usernetSSHLocalPort = 0 // disable gvisor ssh port forwarding
134 } else {
135 logrus.WithError(err).WithField("hostAddress", hostAddress).
136 Debugf("Failed to start vsock forwarder (systemd is older than v256?)")
137 logrus.Info("SSH server does not seem to be running on vsock port, using usernet forwarder")
138 if onVsockEvent != nil {
139 onVsockEvent(&events.VsockEvent{
140 Type: events.VsockEventFailed,
141 Reason: "SSH server does not seem to be running on vsock port",
142 })
143 }
144 }
145 } else {
146 logrus.WithError(err).Warn("Failed to wait for the guest SSH server to become available, falling back to usernet forwarder")
147 if onVsockEvent != nil {
148 onVsockEvent(&events.VsockEvent{
149 Type: events.VsockEventFailed,
150 Reason: "Failed to wait for guest SSH server",
151 })
152 }
153 }
154 err := usernetClient.ConfigureDriver(ctx, inst, usernetSSHLocalPort)
155 if err != nil {
156 sendErrCh <- err
157 }
158 }()
159 case vz.VirtualMachineStateStopped:
160 logrus.Info("[VZ] - vm state change: stopped")
161 wrapper.mu.Lock()
162 wrapper.stopped = true
163 wrapper.mu.Unlock()
164 _ = usernetClient.UnExposeSSH(inst.SSHLocalPort)
165 if stopUsernet != nil {
166 stopUsernet()
167 }
168 sendErrCh <- errors.New("vz driver state stopped")
169 default:
170 logrus.Debugf("[VZ] - vm state change: %#q", newState)
171 }
172 }
173 }
174 }()
175 return wrapper, notifySSHLocalPortAccessible, sendErrCh, err
176}
177
178func startUsernet(ctx context.Context, inst *limatype.Instance) (*usernet.Client, context.CancelFunc, error) {
179 if firstUsernetIndex := limayaml.FirstUsernetIndex(inst.Config); firstUsernetIndex != -1 {
180 nwName := inst.Config.Networks[firstUsernetIndex].Lima
181 return usernet.NewClientByName(nwName), nil, nil
182 }
183 // Start a in-process gvisor-tap-vsock
184 endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
185 if err != nil {
186 return nil, nil, err
187 }
188 vzSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.FDSock)
189 if err != nil {
190 return nil, nil, err
191 }
192 os.RemoveAll(endpointSock)
193 os.RemoveAll(vzSock)
194 ctx, cancel := context.WithCancel(ctx)
195 err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{
196 MTU: 1500,
197 Endpoint: endpointSock,
198 FdSocket: vzSock,
199 Async: true,
200 DefaultLeases: map[string]string{
201 networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir),
202 },
203 Subnet: networks.SlirpNetwork,
204 })
205 if err != nil {
206 defer cancel()
207 return nil, nil, err
208 }
209 subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork)
210 return usernet.NewClient(endpointSock, subnetIP), cancel, err
211}
212
213func createVM(ctx context.Context, inst *limatype.Instance) (*vz.VirtualMachine, error) {
214 vmConfig, err := createInitialConfig(inst)
215 if err != nil {
216 return nil, err
217 }
218
219 if err = attachPlatformConfig(inst, vmConfig); err != nil {
220 return nil, err
221 }
222
223 if err = attachSerialPort(inst, vmConfig); err != nil {
224 return nil, err
225 }
226
227 if err = attachNetwork(ctx, inst, vmConfig); err != nil {
228 return nil, err
229 }
230
231 if err = attachDisks(ctx, inst, vmConfig); err != nil {
232 return nil, err
233 }
234
235 if err = attachDisplay(inst, vmConfig); err != nil {
236 return nil, err
237 }
238
239 if err = attachFolderMounts(inst, vmConfig); err != nil {
240 return nil, err
241 }
242
243 if err = attachAudio(inst, vmConfig); err != nil {
244 return nil, err
245 }
246
247 if err = attachOtherDevices(inst, vmConfig); err != nil {
248 return nil, err
249 }
250
251 validated, err := vmConfig.Validate()
252 if !validated || err != nil {
253 return nil, err
254 }
255
256 return vz.NewVirtualMachine(vmConfig)
257}
258
259// createVMForMacInstaller is similar to createVM but only used for VZMacOSInstaller.
260// - Only the primary disk is attached.
261// - No network.
262func createVMForMacInstaller(_ context.Context, inst *limatype.Instance, disk string) (*vz.VirtualMachine, error) {
263 vmConfig, err := createInitialConfig(inst)
264 if err != nil {
265 return nil, err
266 }
267
268 if err = attachPlatformConfig(inst, vmConfig); err != nil {
269 return nil, err
270 }
271
272 // Only attach the primary disk here. cidata.iso is not existent at this point.
273 diffDiskAttachment, err := vz.NewDiskImageStorageDeviceAttachmentWithCacheAndSync(disk, false, diskImageCachingMode, vz.DiskImageSynchronizationModeFsync)
274 if err != nil {
275 return nil, err
276 }
277 diskConfig, err := vz.NewVirtioBlockDeviceConfiguration(diffDiskAttachment)
278 if err != nil {
279 return nil, err
280 }
281 vmConfig.SetStorageDevicesVirtualMachineConfiguration([]vz.StorageDeviceConfiguration{diskConfig})
282
283 if err = attachDisplay(inst, vmConfig); err != nil {
284 return nil, err
285 }
286
287 if err = attachOtherDevices(inst, vmConfig); err != nil {
288 return nil, err
289 }
290
291 validated, err := vmConfig.Validate()
292 if !validated || err != nil {
293 return nil, err
294 }
295
296 return vz.NewVirtualMachine(vmConfig)
297}
298
299func createInitialConfig(inst *limatype.Instance) (*vz.VirtualMachineConfiguration, error) {
300 bootLoader, err := bootLoader(inst)
301 if err != nil {
302 return nil, err
303 }
304
305 bytes, err := units.RAMInBytes(*inst.Config.Memory)
306 if err != nil {
307 return nil, err
308 }
309
310 vmConfig, err := vz.NewVirtualMachineConfiguration(
311 bootLoader,
312 uint(*inst.Config.CPUs),
313 uint64(bytes),
314 )
315 if err != nil {
316 return nil, err
317 }
318 return vmConfig, nil
319}
320
321func newPlatformConfiguration(inst *limatype.Instance) (vz.PlatformConfiguration, error) {
322 if *inst.Config.OS == limatype.DARWIN {
323 return newMacPlatformConfiguration(inst)
324 }
325
326 identifierFile := filepath.Join(inst.Dir, filenames.VzIdentifier)
327
328 machineIdentifier, err := getGenericMachineIdentifier(identifierFile)
329 if err != nil {
330 return nil, err
331 }
332
333 platformConfig, err := vz.NewGenericPlatformConfiguration(vz.WithGenericMachineIdentifier(machineIdentifier))
334 if err != nil {
335 return nil, err
336 }
337 return platformConfig, nil
338}
339
340func attachPlatformConfig(inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
341 platformConfig, err := newPlatformConfiguration(inst)
342 if err != nil {
343 return err
344 }
345
346 // nested virt
347 if *inst.Config.NestedVirtualization {
348 macOSProductVersion, err := osutil.ProductVersion()
349 if err != nil {
350 return fmt.Errorf("failed to get macOS product version: %w", err)
351 }
352
353 if macOSProductVersion.LessThan(*semver.New("15.0.0")) {
354 return errors.New("nested virtualization requires macOS 15 or newer")
355 }
356
357 if !vz.IsNestedVirtualizationSupported() {
358 return errors.New("nested virtualization is not supported on this device")
359 }
360
361 genericPlatformConfig, ok := platformConfig.(*vz.GenericPlatformConfiguration)
362 if !ok {
363 return fmt.Errorf("nested virtualization is not supported on %T", platformConfig)
364 }
365
366 if err := genericPlatformConfig.SetNestedVirtualizationEnabled(true); err != nil {
367 return fmt.Errorf("cannot enable nested virtualization: %w", err)
368 }
369 }
370
371 vmConfig.SetPlatformVirtualMachineConfiguration(platformConfig)
372 return nil
373}
374
375func attachSerialPort(inst *limatype.Instance, config *vz.VirtualMachineConfiguration) error {
376 path := filepath.Join(inst.Dir, filenames.SerialVirtioLog)
377 serialPortAttachment, err := vz.NewFileSerialPortAttachment(path, false)
378 if err != nil {
379 return err
380 }
381 consoleConfig, err := vz.NewVirtioConsoleDeviceSerialPortConfiguration(serialPortAttachment)
382 config.SetSerialPortsVirtualMachineConfiguration([]*vz.VirtioConsoleDeviceSerialPortConfiguration{
383 consoleConfig,
384 })
385 return err
386}
387
388func newVirtioFileNetworkDeviceConfiguration(file *os.File, macStr string) (*vz.VirtioNetworkDeviceConfiguration, error) {
389 fileAttachment, err := vz.NewFileHandleNetworkDeviceAttachment(file)
390 if err != nil {
391 return nil, err
392 }
393 return newVirtioNetworkDeviceConfiguration(fileAttachment, macStr)
394}
395
396func newVirtioNetworkDeviceConfiguration(attachment vz.NetworkDeviceAttachment, macStr string) (*vz.VirtioNetworkDeviceConfiguration, error) {
397 networkConfig, err := vz.NewVirtioNetworkDeviceConfiguration(attachment)
398 if err != nil {
399 return nil, err
400 }
401 mac, err := net.ParseMAC(macStr)
402 if err != nil {
403 return nil, err
404 }
405 address, err := vz.NewMACAddress(mac)
406 if err != nil {
407 return nil, err
408 }
409 networkConfig.SetMACAddress(address)
410 return networkConfig, nil
411}
412
413func attachNetwork(ctx context.Context, inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
414 var configurations []*vz.VirtioNetworkDeviceConfiguration
415
416 // Configure default usernetwork with limayaml.MACAddress(inst.Dir) for eth0 interface
417 firstUsernetIndex := limayaml.FirstUsernetIndex(inst.Config)
418 if firstUsernetIndex == -1 {
419 // slirp network using gvisor netstack
420 vzSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.FDSock)
421 if err != nil {
422 return err
423 }
424 networkConn, err := PassFDToUnix(vzSock)
425 if err != nil {
426 return err
427 }
428 networkConfig, err := newVirtioFileNetworkDeviceConfiguration(networkConn, limayaml.MACAddress(inst.Dir))
429 if err != nil {
430 return err
431 }
432 configurations = append(configurations, networkConfig)
433 } else {
434 vzSock, err := usernet.Sock(inst.Config.Networks[firstUsernetIndex].Lima, usernet.FDSock)
435 if err != nil {
436 return err
437 }
438 networkConn, err := PassFDToUnix(vzSock)
439 if err != nil {
440 return err
441 }
442 networkConfig, err := newVirtioFileNetworkDeviceConfiguration(networkConn, limayaml.MACAddress(inst.Dir))
443 if err != nil {
444 return err
445 }
446 configurations = append(configurations, networkConfig)
447 }
448
449 for i, nw := range inst.Networks {
450 if nw.VZNAT != nil && *nw.VZNAT {
451 attachment, err := vz.NewNATNetworkDeviceAttachment()
452 if err != nil {
453 return err
454 }
455 networkConfig, err := newVirtioNetworkDeviceConfiguration(attachment, nw.MACAddress)
456 if err != nil {
457 return err
458 }
459 configurations = append(configurations, networkConfig)
460 } else if nw.Lima != "" {
461 nwCfg, err := networks.LoadConfig()
462 if err != nil {
463 return err
464 }
465 isUsernet, err := nwCfg.Usernet(nw.Lima)
466 if err != nil {
467 return err
468 }
469 if isUsernet {
470 if i == firstUsernetIndex {
471 continue
472 }
473 vzSock, err := usernet.Sock(nw.Lima, usernet.FDSock)
474 if err != nil {
475 return err
476 }
477 clientFile, err := PassFDToUnix(vzSock)
478 if err != nil {
479 return err
480 }
481 networkConfig, err := newVirtioFileNetworkDeviceConfiguration(clientFile, nw.MACAddress)
482 if err != nil {
483 return err
484 }
485 configurations = append(configurations, networkConfig)
486 } else {
487 if runtime.GOOS != "darwin" {
488 return fmt.Errorf("networks.yaml '%s' configuration is only supported on macOS right now", nw.Lima)
489 }
490 socketVMNetOk, err := nwCfg.IsDaemonInstalled(networks.SocketVMNet)
491 if err != nil {
492 return err
493 }
494 if socketVMNetOk {
495 logrus.Debugf("Using socketVMNet (%#q)", nwCfg.Paths.SocketVMNet)
496 sock, err := networks.Sock(nw.Lima)
497 if err != nil {
498 return err
499 }
500
501 clientFile, err := DialQemu(ctx, sock)
502 if err != nil {
503 return err
504 }
505 networkConfig, err := newVirtioFileNetworkDeviceConfiguration(clientFile, nw.MACAddress)
506 if err != nil {
507 return err
508 }
509 configurations = append(configurations, networkConfig)
510 }
511 }
512 } else if nw.Socket != "" {
513 clientFile, err := DialQemu(ctx, nw.Socket)
514 if err != nil {
515 return err
516 }
517 networkConfig, err := newVirtioFileNetworkDeviceConfiguration(clientFile, nw.MACAddress)
518 if err != nil {
519 return err
520 }
521 configurations = append(configurations, networkConfig)
522 }
523 }
524 vmConfig.SetNetworkDevicesVirtualMachineConfiguration(configurations)
525 return nil
526}
527
528func validateDiskFormat(diskPath string) error {
529 f, err := os.Open(diskPath)
530 if err != nil {
531 return err
532 }
533 defer f.Close()
534 img, err := qcow2reader.Open(f)
535 if err != nil {
536 return fmt.Errorf("failed to detect the format of %#q: %w", diskPath, err)
537 }
538 supportedDiskTypes := []image.Type{raw.Type, asif.Type}
539 if t := img.Type(); !slices.Contains(supportedDiskTypes, t) {
540 return fmt.Errorf("expected the format of %#q to be one of %v, got %#q", diskPath, supportedDiskTypes, t)
541 }
542 // TODO: ensure that the disk is formatted with GPT or ISO9660
543 return nil
544}
545
546func attachDisks(ctx context.Context, inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
547 diskPath := filepath.Join(inst.Dir, filenames.Disk)
548 isoPath := filepath.Join(inst.Dir, filenames.ISO)
549 ciDataPath := filepath.Join(inst.Dir, filenames.CIDataISO)
550 var configurations []vz.StorageDeviceConfiguration
551
552 if osutil.FileExists(diskPath) {
553 if err := validateDiskFormat(diskPath); err != nil {
554 return err
555 }
556 diskAttachment, err := vz.NewDiskImageStorageDeviceAttachmentWithCacheAndSync(diskPath, false, diskImageCachingMode, vz.DiskImageSynchronizationModeFsync)
557 if err != nil {
558 return err
559 }
560 diskDev, err := vz.NewVirtioBlockDeviceConfiguration(diskAttachment)
561 if err != nil {
562 return err
563 }
564 configurations = append(configurations, diskDev)
565 }
566 if osutil.FileExists(isoPath) {
567 if err := validateDiskFormat(isoPath); err != nil {
568 return err
569 }
570 isoAttachment, err := vz.NewDiskImageStorageDeviceAttachment(isoPath, true)
571 if err != nil {
572 return err
573 }
574 isoDev, err := vz.NewUSBMassStorageDeviceConfiguration(isoAttachment)
575 if err != nil {
576 return err
577 }
578 configurations = append(configurations, isoDev)
579 }
580
581 diskUtil := proxyimgutil.NewDiskUtil(ctx)
582
583 for _, d := range inst.Config.AdditionalDisks {
584 diskName := d.Name
585 disk, err := store.InspectDisk(diskName, d.FSType)
586 if err != nil {
587 return fmt.Errorf("failed to run load disk %#q: %w", diskName, err)
588 }
589
590 logrus.Infof("Mounting disk %#q on %#q", diskName, disk.MountPoint)
591 if err = disk.LockForInstance(inst.Dir); err != nil {
592 return fmt.Errorf("failed to attach disk %#q: %w", diskName, err)
593 }
594 extraDiskPath := filepath.Join(disk.Dir, filenames.DataDisk)
595 // ConvertToRaw is a NOP if no conversion is needed
596 logrus.Debugf("Converting extra disk %#q to a raw disk (if it is not a raw)", extraDiskPath)
597
598 if err = diskUtil.Convert(ctx, raw.Type, extraDiskPath, extraDiskPath, nil, true); err != nil {
599 return fmt.Errorf("failed to convert extra disk %#q to a raw disk: %w", extraDiskPath, err)
600 }
601 extraDiskPathAttachment, err := vz.NewDiskImageStorageDeviceAttachmentWithCacheAndSync(extraDiskPath, false, diskImageCachingMode, vz.DiskImageSynchronizationModeFsync)
602 if err != nil {
603 return fmt.Errorf("failed to create disk attachment for extra disk %#q: %w", extraDiskPath, err)
604 }
605 extraDisk, err := vz.NewVirtioBlockDeviceConfiguration(extraDiskPathAttachment)
606 if err != nil {
607 return fmt.Errorf("failed to create new virtio block device config for extra disk %#q: %w", extraDiskPath, err)
608 }
609 configurations = append(configurations, extraDisk)
610 }
611
612 if err := validateDiskFormat(ciDataPath); err != nil {
613 return err
614 }
615 ciDataAttachment, err := vz.NewDiskImageStorageDeviceAttachment(ciDataPath, true)
616 if err != nil {
617 return err
618 }
619 ciData, err := vz.NewVirtioBlockDeviceConfiguration(ciDataAttachment)
620 if err != nil {
621 return err
622 }
623 configurations = append(configurations, ciData)
624
625 vmConfig.SetStorageDevicesVirtualMachineConfiguration(configurations)
626 return nil
627}
628
629func attachDisplay(inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
630 switch *inst.Config.Video.Display {
631 case "vz", "default", "offscreen":
632 var graphicsDeviceConfiguration vz.GraphicsDeviceConfiguration
633 if *inst.Config.OS == limatype.DARWIN {
634 var err error
635 if *inst.Config.Video.Display == "offscreen" {
636 // macOS uses the display's physical density to select Retina backing.
637 // Keep a 1920 x 1200 point workspace for the embedded application.
638 graphicsDeviceConfiguration, err = newMacGraphicsDeviceConfiguration(3840, 2400, 220)
639 } else {
640 graphicsDeviceConfiguration, err = newMacGraphicsDeviceConfiguration(1920, 1200, 80)
641 }
642 if err != nil {
643 return err
644 }
645 } else {
646 var err error
647 graphicsDeviceConfiguration, err = vz.NewVirtioGraphicsDeviceConfiguration()
648 if err != nil {
649 return err
650 }
651 scanoutConfiguration, err := vz.NewVirtioGraphicsScanoutConfiguration(1920, 1200)
652 if err != nil {
653 return err
654 }
655 graphicsDeviceConfiguration.(*vz.VirtioGraphicsDeviceConfiguration).SetScanouts(scanoutConfiguration)
656 }
657
658 vmConfig.SetGraphicsDevicesVirtualMachineConfiguration([]vz.GraphicsDeviceConfiguration{
659 graphicsDeviceConfiguration,
660 })
661 return nil
662 case "none":
663 return nil
664 default:
665 return fmt.Errorf("unexpected video display %#q", *inst.Config.Video.Display)
666 }
667}
668
669func directorySharingDevicesGeneric(origMounts []limatype.Mount) ([]vz.DirectorySharingDeviceConfiguration, error) {
670 var mounts []vz.DirectorySharingDeviceConfiguration
671 for _, mount := range origMounts {
672 if _, err := os.Stat(mount.Location); errors.Is(err, os.ErrNotExist) {
673 err := os.MkdirAll(mount.Location, 0o750)
674 if err != nil {
675 return nil, err
676 }
677 }
678
679 directory, err := vz.NewSharedDirectory(mount.Location, !*mount.Writable)
680 if err != nil {
681 return nil, err
682 }
683 share, err := vz.NewSingleDirectoryShare(directory)
684 if err != nil {
685 return nil, err
686 }
687
688 tag := limayaml.MountTag(mount.Location, *mount.MountPoint)
689 config, err := vz.NewVirtioFileSystemDeviceConfiguration(tag)
690 if err != nil {
691 return nil, err
692 }
693 config.SetDirectoryShare(share)
694 mounts = append(mounts, config)
695 }
696 return mounts, nil
697}
698
699func directorySharingDevicesMacOS(origMounts []limatype.Mount) ([]vz.DirectorySharingDeviceConfiguration, error) {
700 directories := make(map[string]*vz.SharedDirectory)
701 for _, mount := range origMounts {
702 if _, err := os.Stat(mount.Location); errors.Is(err, os.ErrNotExist) {
703 err := os.MkdirAll(mount.Location, 0o750)
704 if err != nil {
705 return nil, err
706 }
707 }
708
709 directory, err := vz.NewSharedDirectory(mount.Location, !*mount.Writable)
710 if err != nil {
711 return nil, err
712 }
713 // The directory is mounted on `/Volumes/My Shared Files/<pseudoTag>`.
714 // The actual virtiofs tag is allocated by vz.MacOSGuestAutomountTag().
715 // https://developer.apple.com/documentation/virtualization/vzvirtiofilesystemdeviceconfiguration?language=objc#Automounting-shared-directories-in-macOS-VMs
716 pseudoTag := limayaml.MountTag(mount.Location, *mount.MountPoint)
717 directories[pseudoTag] = directory
718 }
719 share, err := vz.NewMultipleDirectoryShare(directories)
720 if err != nil {
721 return nil, err
722 }
723 tag, err := vz.MacOSGuestAutomountTag()
724 if err != nil {
725 return nil, err
726 }
727 config, err := vz.NewVirtioFileSystemDeviceConfiguration(tag)
728 if err != nil {
729 return nil, err
730 }
731 config.SetDirectoryShare(share)
732 return []vz.DirectorySharingDeviceConfiguration{config}, nil
733}
734
735func attachFolderMounts(inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
736 var mounts []vz.DirectorySharingDeviceConfiguration
737 if *inst.Config.MountType == limatype.VIRTIOFS {
738 var err error
739 // "generic" sharing devices are still mountable on macOS, but such mounts are
740 // not accessible due to Operation not permitted" errors.
741 if *inst.Config.OS == limatype.DARWIN {
742 mounts, err = directorySharingDevicesMacOS(inst.Config.Mounts)
743 } else {
744 mounts, err = directorySharingDevicesGeneric(inst.Config.Mounts)
745 }
746 if err != nil {
747 return err
748 }
749 }
750
751 var vzOpts limatype.VZOpts
752 if err := limayaml.Convert(inst.Config.VMOpts[limatype.VZ], &vzOpts, "vmOpts.vz"); err != nil {
753 logrus.WithError(err).Warnf("Couldn't convert %#q", inst.Config.VMOpts[limatype.VZ])
754 }
755
756 if vzOpts.Rosetta.Enabled != nil && *vzOpts.Rosetta.Enabled {
757 logrus.Info("Setting up Rosetta share")
758 directorySharingDeviceConfig, err := createRosettaDirectoryShareConfiguration()
759 if err != nil {
760 logrus.Warnf("Unable to configure Rosetta: %s", err)
761 } else {
762 mounts = append(mounts, directorySharingDeviceConfig)
763 }
764 }
765
766 if len(mounts) > 0 {
767 vmConfig.SetDirectorySharingDevicesVirtualMachineConfiguration(mounts)
768 }
769 return nil
770}
771
772func attachAudio(inst *limatype.Instance, config *vz.VirtualMachineConfiguration) error {
773 y := inst.Config
774
775 if y.Audio.Device == nil || y.Audio.Interface == nil {
776 return nil
777 }
778
779 audioDev := *y.Audio.Device
780 audioInterface := *y.Audio.Interface
781
782 // If the user explicitly asks for HDA, we gracefully ignore it.
783 if audioInterface == "hda" {
784 logrus.Warn("VZ driver natively uses virtio-sound. Ignoring 'hda' interface request.")
785 }
786
787 switch audioDev {
788 case "vz", "default":
789 outputStream, err := vz.NewVirtioSoundDeviceHostOutputStreamConfiguration()
790 if err != nil {
791 return fmt.Errorf("failed to create host audio output stream: %w", err)
792 }
793 streams := []vz.VirtioSoundDeviceStreamConfiguration{outputStream}
794
795 // Opt-in: an input stream makes macOS ask for microphone permission
796 // on behalf of the process running the VM.
797 if y.Audio.Microphone != nil && *y.Audio.Microphone {
798 inputStream, err := vz.NewVirtioSoundDeviceHostInputStreamConfiguration()
799 if err != nil {
800 return fmt.Errorf("failed to create host audio input stream: %w", err)
801 }
802 streams = append(streams, inputStream)
803 }
804
805 soundDeviceConfiguration, err := vz.NewVirtioSoundDeviceConfiguration()
806 if err != nil {
807 return fmt.Errorf("failed to create virtio sound device configuration: %w", err)
808 }
809 soundDeviceConfiguration.SetStreams(streams...)
810 config.SetAudioDevicesVirtualMachineConfiguration([]vz.AudioDeviceConfiguration{
811 soundDeviceConfiguration,
812 })
813 return nil
814 case "", "none":
815 if y.Audio.Microphone != nil && *y.Audio.Microphone {
816 logrus.Warn("`audio.microphone` requires `audio.device` to be set. Ignoring it.")
817 }
818 return nil
819 default:
820 return fmt.Errorf("unexpected audio device %#q", *inst.Config.Audio.Device)
821 }
822}
823
824func attachOtherDevices(inst *limatype.Instance, vmConfig *vz.VirtualMachineConfiguration) error {
825 entropyConfig, err := vz.NewVirtioEntropyDeviceConfiguration()
826 if err != nil {
827 return err
828 }
829 vmConfig.SetEntropyDevicesVirtualMachineConfiguration([]*vz.VirtioEntropyDeviceConfiguration{
830 entropyConfig,
831 })
832
833 configuration, err := vz.NewVirtioTraditionalMemoryBalloonDeviceConfiguration()
834 if err != nil {
835 return err
836 }
837 vmConfig.SetMemoryBalloonDevicesVirtualMachineConfiguration([]vz.MemoryBalloonDeviceConfiguration{
838 configuration,
839 })
840
841 deviceConfiguration, err := vz.NewVirtioSocketDeviceConfiguration()
842 vmConfig.SetSocketDevicesVirtualMachineConfiguration([]vz.SocketDeviceConfiguration{
843 deviceConfiguration,
844 })
845 if err != nil {
846 return err
847 }
848
849 // Set pointing device
850 var pointingDeviceConfig vz.PointingDeviceConfiguration
851 if *inst.Config.OS == limatype.DARWIN {
852 pointingDeviceConfig, err = newMacPointingDeviceConfiguration()
853 } else {
854 pointingDeviceConfig, err = vz.NewUSBScreenCoordinatePointingDeviceConfiguration()
855 }
856 if err != nil {
857 return err
858 }
859 vmConfig.SetPointingDevicesVirtualMachineConfiguration([]vz.PointingDeviceConfiguration{
860 pointingDeviceConfig,
861 })
862
863 // Set keyboard device
864 var keyboardDeviceConfig vz.KeyboardConfiguration
865 if *inst.Config.OS == limatype.DARWIN {
866 keyboardDeviceConfig, err = newMacKeyboardConfiguration()
867 } else {
868 keyboardDeviceConfig, err = vz.NewUSBKeyboardConfiguration()
869 }
870 if err != nil {
871 return err
872 }
873 vmConfig.SetKeyboardsVirtualMachineConfiguration([]vz.KeyboardConfiguration{
874 keyboardDeviceConfig,
875 })
876 return nil
877}
878
879type machineIdentifier interface {
880 DataRepresentation() []byte
881}
882
883func getGenericMachineIdentifier(identifier string) (*vz.GenericMachineIdentifier, error) {
884 // Empty VzIdentifier can be created on cloning an instance.
885 if st, err := os.Stat(identifier); err != nil || (st != nil && st.Size() == 0) {
886 if err != nil && !errors.Is(err, fs.ErrNotExist) {
887 return nil, err
888 }
889 machineIdentifier, err := vz.NewGenericMachineIdentifier()
890 if err != nil {
891 return nil, err
892 }
893 err = os.WriteFile(identifier, machineIdentifier.DataRepresentation(), 0o666)
894 if err != nil {
895 return nil, err
896 }
897 return machineIdentifier, nil
898 }
899 return vz.NewGenericMachineIdentifierWithDataPath(identifier)
900}
901
902func bootLoader(inst *limatype.Instance) (vz.BootLoader, error) {
903 if *inst.Config.OS == limatype.DARWIN {
904 return newMacOSBootLoader()
905 }
906 linuxBootLoader, err := linuxBootLoader(inst)
907 if linuxBootLoader != nil {
908 return linuxBootLoader, nil
909 } else if !errors.Is(err, os.ErrNotExist) {
910 return nil, err
911 }
912
913 efiVariableStore, err := getEFI(inst)
914 if err != nil {
915 return nil, err
916 }
917 logrus.Debugf("Using EFI Boot Loader")
918 return vz.NewEFIBootLoader(vz.WithEFIVariableStore(efiVariableStore))
919}
920
921func linuxBootLoader(inst *limatype.Instance) (*vz.LinuxBootLoader, error) {
922 kernel := filepath.Join(inst.Dir, filenames.Kernel)
923 kernelCmdline := filepath.Join(inst.Dir, filenames.KernelCmdline)
924 initrd := filepath.Join(inst.Dir, filenames.Initrd)
925 if _, err := os.Stat(kernel); err != nil {
926 if errors.Is(err, os.ErrNotExist) {
927 logrus.Debugf("Kernel file %#q not found", kernel)
928 } else {
929 logrus.WithError(err).Debugf("Error while checking kernel file %#q", kernel)
930 }
931 return nil, err
932 }
933 var opt []vz.LinuxBootLoaderOption
934 if b, err := os.ReadFile(kernelCmdline); err == nil {
935 logrus.Debugf("Using kernel command line %#q", string(b))
936 opt = append(opt, vz.WithCommandLine(string(b)))
937 }
938 if _, err := os.Stat(initrd); err == nil {
939 logrus.Debugf("Using initrd %#q", initrd)
940 opt = append(opt, vz.WithInitrd(initrd))
941 }
942 logrus.Debugf("Using Linux Boot Loader with kernel %#q", kernel)
943 return vz.NewLinuxBootLoader(kernel, opt...)
944}
945
946func getEFI(inst *limatype.Instance) (*vz.EFIVariableStore, error) {
947 efi := filepath.Join(inst.Dir, filenames.VzEfi)
948 if _, err := os.Stat(efi); os.IsNotExist(err) {
949 return vz.NewEFIVariableStore(efi, vz.WithCreatingEFIVariableStore())
950 }
951 return vz.NewEFIVariableStore(efi)
952}
953
954func createSockPair() (server, client *os.File, _ error) {
955 pairs, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
956 if err != nil {
957 return nil, nil, err
958 }
959 serverFD := pairs[0]
960 clientFD := pairs[1]
961
962 if err = syscall.SetsockoptInt(serverFD, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 1*1024*1024); err != nil {
963 return nil, nil, err
964 }
965 if err = syscall.SetsockoptInt(serverFD, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 4*1024*1024); err != nil {
966 return nil, nil, err
967 }
968 if err = syscall.SetsockoptInt(clientFD, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 1*1024*1024); err != nil {
969 return nil, nil, err
970 }
971 if err = syscall.SetsockoptInt(clientFD, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 4*1024*1024); err != nil {
972 return nil, nil, err
973 }
974 server = os.NewFile(uintptr(serverFD), "server")
975 client = os.NewFile(uintptr(clientFD), "client")
976 runtime.SetFinalizer(server, func(*os.File) {
977 logrus.Debugf("Server network file GC'ed")
978 })
979 runtime.SetFinalizer(client, func(*os.File) {
980 logrus.Debugf("Client network file GC'ed")
981 })
982 vmNetworkFiles = append(vmNetworkFiles, server, client)
983 return server, client, nil
984}
985
986func ensureIPSW(instDir string) error {
987 ipsw := filepath.Join(instDir, filenames.ImageIPSW)
988 if osutil.FileExists(ipsw) {
989 return nil
990 }
991 ipswBase := filepath.Join(instDir, filenames.Image)
992 if _, err := os.Stat(ipswBase); err != nil {
993 return err
994 }
995 // The installer wants the file to have ".ipsw" suffix.
996 // The link is created as a hard link, as the installer does not accept symlinks.
997 if err := os.Link(ipswBase, ipsw); err != nil {
998 return fmt.Errorf("failed to create hard link from %#q to %#q: %w", ipswBase, ipsw, err)
999 }
1000 return nil
1001}