/
machine.go
1210 lines (1049 loc) · 31 KB
/
machine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build darwin
// +build darwin
package applehv
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/containers/common/pkg/config"
gvproxy "github.com/containers/gvisor-tap-vsock/pkg/types"
"github.com/containers/podman/v4/pkg/machine"
"github.com/containers/podman/v4/pkg/machine/define"
"github.com/containers/podman/v4/pkg/strongunits"
"github.com/containers/podman/v4/pkg/util"
"github.com/containers/podman/v4/utils"
"github.com/containers/storage/pkg/lockfile"
vfConfig "github.com/crc-org/vfkit/pkg/config"
vfRest "github.com/crc-org/vfkit/pkg/rest"
"github.com/docker/go-units"
"github.com/sirupsen/logrus"
)
var (
// vmtype refers to qemu (vs libvirt, krun, etc).
vmtype = machine.AppleHvVirt
)
const (
dockerSock = "/var/run/docker.sock"
dockerConnectTimeout = 5 * time.Second
apiUpTimeout = 20 * time.Second
)
// VfkitHelper describes the use of vfkit: cmdline and endpoint
type VfkitHelper struct {
LogLevel logrus.Level
Endpoint string
VfkitBinaryPath *define.VMFile
VirtualMachine *vfConfig.VirtualMachine
}
// appleHVReadyUnit is a unit file that sets up the virtual serial device
// where when the VM is done configuring, it will send an ack
// so a listening host knows it can begin interacting with it
const appleHVReadyUnit = `[Unit]
Requires=dev-virtio\\x2dports-%s.device
After=remove-moby.service sshd.socket sshd.service
OnFailure=emergency.target
OnFailureJobMode=isolate
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh -c '/usr/bin/echo Ready | socat - VSOCK-CONNECT:2:1025'
[Install]
RequiredBy=default.target
`
type MacMachine struct {
// ConfigPath is the fully qualified path to the configuration file
ConfigPath define.VMFile
// HostUser contains info about host user
machine.HostUser
// ImageConfig describes the bootable image
machine.ImageConfig
// Mounts is the list of remote filesystems to mount
Mounts []machine.Mount
// Name of VM
Name string
// ReadySocket tells host when vm is booted
ReadySocket define.VMFile
// ResourceConfig is physical attrs of the VM
machine.ResourceConfig
// SSHConfig for accessing the remote vm
machine.SSHConfig
// Starting tells us whether the machine is running or if we have just dialed it to start it
Starting bool
// Created contains the original created time instead of querying the file mod time
Created time.Time
// LastUp contains the last recorded uptime
LastUp time.Time
// The VFKit endpoint where we can interact with the VM
Vfkit VfkitHelper
LogPath define.VMFile
GvProxyPid define.VMFile
GvProxySock define.VMFile
// Used at runtime for serializing write operations
lock *lockfile.LockFile
}
// setGVProxyInfo sets the VM's gvproxy pid and socket files
func (m *MacMachine) setGVProxyInfo(runtimeDir string) error {
gvProxyPid, err := define.NewMachineFile(filepath.Join(runtimeDir, "gvproxy.pid"), nil)
if err != nil {
return err
}
m.GvProxyPid = *gvProxyPid
return machine.SetSocket(&m.GvProxySock, filepath.Join(runtimeDir, "gvproxy.sock"), nil)
}
// setVfkitInfo stores the default devices, sets the vfkit endpoint, and
// locates/stores the path to the binary
func (m *MacMachine) setVfkitInfo(cfg *config.Config, readySocket define.VMFile) error {
defaultDevices, err := getDefaultDevices(m.ImagePath.GetPath(), m.LogPath.GetPath(), readySocket.GetPath())
if err != nil {
return err
}
// Store VFKit stuffs
vfkitPath, err := cfg.FindHelperBinary("vfkit", false)
if err != nil {
return err
}
vfkitBinaryPath, err := define.NewMachineFile(vfkitPath, nil)
if err != nil {
return err
}
m.Vfkit.VirtualMachine.Devices = defaultDevices
randPort, err := utils.GetRandomPort()
if err != nil {
return err
}
m.Vfkit.Endpoint = localhostURI + ":" + strconv.Itoa(randPort)
m.Vfkit.VfkitBinaryPath = vfkitBinaryPath
return nil
}
// addMountsToVM converts the volumes passed through the CLI to virtio-fs mounts
// and adds them to the machine
func (m *MacMachine) addMountsToVM(opts machine.InitOptions, virtiofsMnts *[]machine.VirtIoFs) error {
var mounts []machine.Mount
for _, volume := range opts.Volumes {
source, target, _, readOnly, err := machine.ParseVolumeFromPath(volume)
if err != nil {
return err
}
mnt := machine.NewVirtIoFsMount(source, target, readOnly)
*virtiofsMnts = append(*virtiofsMnts, mnt)
mounts = append(mounts, mnt.ToMount())
}
m.Mounts = mounts
return nil
}
func (m *MacMachine) Init(opts machine.InitOptions) (bool, error) {
var (
key string
virtiofsMnts []machine.VirtIoFs
err error
)
// cleanup half-baked files if init fails at any point
callbackFuncs := machine.InitCleanup()
defer callbackFuncs.CleanIfErr(&err)
go callbackFuncs.CleanOnSignal()
callbackFuncs.Add(m.ConfigPath.Delete)
dataDir, err := machine.GetDataDir(machine.AppleHvVirt)
if err != nil {
return false, err
}
cfg, err := config.Default()
if err != nil {
return false, err
}
dl, err := VirtualizationProvider().NewDownload(m.Name)
if err != nil {
return false, err
}
imagePath, strm, err := dl.AcquireVMImage(opts.ImagePath)
if err != nil {
return false, err
}
callbackFuncs.Add(imagePath.Delete)
// Set the values for imagePath and strm
m.ImagePath = *imagePath
m.ImageStream = strm.String()
logPath, err := define.NewMachineFile(filepath.Join(dataDir, fmt.Sprintf("%s.log", m.Name)), nil)
if err != nil {
return false, err
}
callbackFuncs.Add(logPath.Delete)
m.LogPath = *logPath
runtimeDir, err := m.getRuntimeDir()
if err != nil {
return false, err
}
if err := machine.SetSocket(&m.ReadySocket, machine.ReadySocketPath(runtimeDir, m.Name), nil); err != nil {
return false, err
}
if err = m.setGVProxyInfo(runtimeDir); err != nil {
return false, err
}
if err = m.setVfkitInfo(cfg, m.ReadySocket); err != nil {
return false, err
}
m.IdentityPath = util.GetIdentityPath(m.Name)
m.Rootful = opts.Rootful
m.RemoteUsername = opts.Username
m.UID = os.Getuid()
sshPort, err := utils.GetRandomPort()
if err != nil {
return false, err
}
m.Port = sshPort
if err = m.addMountsToVM(opts, &virtiofsMnts); err != nil {
return false, err
}
err = machine.AddSSHConnectionsToPodmanSocket(
m.UID,
m.Port,
m.IdentityPath,
m.Name,
m.RemoteUsername,
opts,
)
if err != nil {
return false, err
}
callbackFuncs.Add(m.removeSystemConnections)
logrus.Debugf("resizing disk to %d GiB", opts.DiskSize)
if err = m.resizeDisk(strongunits.GiB(opts.DiskSize)); err != nil {
return false, err
}
if err = m.writeConfig(); err != nil {
return false, err
}
if len(opts.IgnitionPath) < 1 {
key, err = machine.CreateSSHKeys(m.IdentityPath)
if err != nil {
return false, err
}
callbackFuncs.Add(m.removeSSHKeys)
}
builder := machine.NewIgnitionBuilder(machine.DynamicIgnition{
Name: opts.Username,
Key: key,
VMName: m.Name,
VMType: machine.AppleHvVirt,
TimeZone: opts.TimeZone,
WritePath: m.IgnitionFile.GetPath(),
UID: m.UID,
Rootful: m.Rootful,
})
if len(opts.IgnitionPath) > 0 {
return false, builder.BuildWithIgnitionFile(opts.IgnitionPath)
}
if err := builder.GenerateIgnitionConfig(); err != nil {
return false, err
}
builder.WithUnit(machine.Unit{
Enabled: machine.BoolToPtr(true),
Name: "ready.service",
Contents: machine.StrToPtr(fmt.Sprintf(appleHVReadyUnit, "vsock")),
})
builder.WithUnit(generateSystemDFilesForVirtiofsMounts(virtiofsMnts)...)
// TODO Ignition stuff goes here
err = builder.Build()
callbackFuncs.Add(m.IgnitionFile.Delete)
return err == nil, err
}
func (m *MacMachine) removeSSHKeys() error {
if err := os.Remove(fmt.Sprintf("%s.pub", m.IdentityPath)); err != nil {
logrus.Error(err)
}
return os.Remove(m.IdentityPath)
}
func (m *MacMachine) removeSystemConnections() error {
return machine.RemoveConnections(m.Name, fmt.Sprintf("%s-root", m.Name))
}
func (m *MacMachine) Inspect() (*machine.InspectInfo, error) {
vmState, err := m.Vfkit.state()
if err != nil {
return nil, err
}
podmanSocket, err := m.forwardSocketPath()
if err != nil {
return nil, err
}
ii := machine.InspectInfo{
ConfigPath: m.ConfigPath,
ConnectionInfo: machine.ConnectionConfig{
PodmanSocket: podmanSocket,
PodmanPipe: nil,
},
Created: m.Created,
Image: machine.ImageConfig{
IgnitionFile: m.IgnitionFile,
ImageStream: m.ImageStream,
ImagePath: m.ImagePath,
},
LastUp: m.LastUp,
Name: m.Name,
Resources: machine.ResourceConfig{
CPUs: m.CPUs,
DiskSize: m.DiskSize,
Memory: m.Memory,
},
SSHConfig: m.SSHConfig,
State: vmState,
Rootful: m.Rootful,
}
return &ii, nil
}
// collectFilesToDestroy retrieves the files that will be destroyed by `Remove`
func (m *MacMachine) collectFilesToDestroy(opts machine.RemoveOptions) []string {
files := []string{}
if !opts.SaveKeys {
files = append(files, m.IdentityPath, m.IdentityPath+".pub")
}
if !opts.SaveIgnition {
files = append(files, m.IgnitionFile.GetPath())
}
if !opts.SaveImage {
files = append(files, m.ImagePath.GetPath())
}
files = append(files, m.ConfigPath.GetPath())
return files
}
func (m *MacMachine) Remove(name string, opts machine.RemoveOptions) (string, func() error, error) {
var (
files []string
)
m.lock.Lock()
defer m.lock.Unlock()
vmState, err := m.Vfkit.state()
if err != nil {
return "", nil, err
}
if vmState == machine.Running {
if !opts.Force {
return "", nil, &machine.ErrVMRunningCannotDestroyed{Name: m.Name}
}
if err := m.Vfkit.stop(true, true); err != nil {
return "", nil, err
}
defer func() {
if err := machine.CleanupGVProxy(m.GvProxyPid); err != nil {
logrus.Error(err)
}
}()
}
files = m.collectFilesToDestroy(opts)
confirmationMessage := "\nThe following files will be deleted:\n\n"
for _, msg := range files {
confirmationMessage += msg + "\n"
}
confirmationMessage += "\n"
return confirmationMessage, func() error {
machine.RemoveFilesAndConnections(files, m.Name, m.Name+"-root")
// TODO We will need something like this for applehv too i think
/*
// Remove the HVSOCK for networking
if err := m.NetworkHVSock.Remove(); err != nil {
logrus.Errorf("unable to remove registry entry for %s: %q", m.NetworkHVSock.KeyName, err)
}
// Remove the HVSOCK for events
if err := m.ReadyHVSock.Remove(); err != nil {
logrus.Errorf("unable to remove registry entry for %s: %q", m.NetworkHVSock.KeyName, err)
}
*/
return nil
}, nil
}
func (m *MacMachine) writeConfig() error {
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
return os.WriteFile(m.ConfigPath.Path, b, 0644)
}
func (m *MacMachine) setRootful(rootful bool) error {
if err := machine.SetRootful(rootful, m.Name, m.Name+"-root"); err != nil {
return err
}
m.HostUser.Modified = true
return nil
}
func (m *MacMachine) Set(name string, opts machine.SetOptions) ([]error, error) {
var setErrors []error
m.lock.Lock()
defer m.lock.Unlock()
vmState, err := m.State(false)
if err != nil {
return nil, err
}
if vmState != machine.Stopped {
return nil, machine.ErrWrongState
}
if cpus := opts.CPUs; cpus != nil {
m.CPUs = *cpus
}
if mem := opts.Memory; mem != nil {
m.Memory = *mem
}
if newSize := opts.DiskSize; newSize != nil {
if *newSize < m.DiskSize {
setErrors = append(setErrors, errors.New("new disk size smaller than existing disk size: cannot shrink disk size"))
} else {
m.DiskSize = *newSize
if err := m.resizeDisk(strongunits.GiB(*opts.DiskSize)); err != nil {
setErrors = append(setErrors, err)
}
}
}
if opts.USBs != nil {
setErrors = append(setErrors, errors.New("changing USBs not supported for applehv machines"))
}
if opts.Rootful != nil && m.Rootful != *opts.Rootful {
if err := m.setRootful(*opts.Rootful); err != nil {
setErrors = append(setErrors, fmt.Errorf("failed to set rootful option: %w", err))
} else {
m.Rootful = *opts.Rootful
}
}
// Write the machine config to the filesystem
err = m.writeConfig()
setErrors = append(setErrors, err)
switch len(setErrors) {
case 0:
return setErrors, nil
case 1:
return nil, setErrors[0]
default:
// Number of errors is 2 or more
lastErr := setErrors[len(setErrors)-1]
return setErrors[:len(setErrors)-1], lastErr
}
}
func (m *MacMachine) SSH(name string, opts machine.SSHOptions) error {
st, err := m.State(false)
if err != nil {
return err
}
if st != machine.Running {
return fmt.Errorf("vm %q is not running", m.Name)
}
username := opts.Username
if username == "" {
username = m.RemoteUsername
}
return machine.CommonSSH(username, m.IdentityPath, m.Name, m.Port, opts.Args)
}
// deleteIgnitionSocket retrieves the ignition socket, deletes it, and returns a
// pointer to the `VMFile`
func (m *MacMachine) deleteIgnitionSocket() (*define.VMFile, error) {
ignitionSocket, err := m.getIgnitionSock()
if err != nil {
return nil, err
}
if err := ignitionSocket.Delete(); err != nil {
return nil, err
}
return ignitionSocket, nil
}
// getIgnitionVsockDeviceAsCLI retrieves the ignition vsock device and converts
// it to a cmdline format
func getIgnitionVsockDeviceAsCLI(ignitionSocketPath string) ([]string, error) {
ignitionVsockDevice, err := getIgnitionVsockDevice(ignitionSocketPath)
if err != nil {
return nil, err
}
// Convert the device into cli args
ignitionVsockDeviceCLI, err := ignitionVsockDevice.ToCmdLine()
if err != nil {
return nil, err
}
return ignitionVsockDeviceCLI, nil
}
// getDebugDevicesCMDArgs retrieves the debug devices and converts them to a
// cmdline format
func getDebugDevicesCMDArgs() ([]string, error) {
args := []string{}
debugDevices, err := getDebugDevices()
if err != nil {
return nil, err
}
for _, debugDevice := range debugDevices {
debugCli, err := debugDevice.ToCmdLine()
if err != nil {
return nil, err
}
args = append(args, debugCli...)
}
return args, nil
}
// getVfKitEndpointCMDArgs converts the vfkit endpoint to a cmdline format
func getVfKitEndpointCMDArgs(endpoint string) ([]string, error) {
restEndpoint, err := vfRest.NewEndpoint(endpoint)
if err != nil {
return nil, err
}
return restEndpoint.ToCmdLine()
}
// addVolumesToVfKit adds the VM's mounts to vfkit's devices
func (m *MacMachine) addVolumesToVfKit() error {
for _, vol := range m.Mounts {
virtfsDevice, err := vfConfig.VirtioFsNew(vol.Source, vol.Tag)
if err != nil {
return err
}
m.Vfkit.VirtualMachine.Devices = append(m.Vfkit.VirtualMachine.Devices, virtfsDevice)
}
return nil
}
func (m *MacMachine) Start(name string, opts machine.StartOptions) error {
var ignitionSocket *define.VMFile
m.lock.Lock()
defer m.lock.Unlock()
st, err := m.State(false)
if err != nil {
return err
}
if st == machine.Running {
return machine.ErrVMAlreadyRunning
}
// TODO handle returns from startHostNetworking
forwardSock, forwardState, err := m.startHostNetworking()
if err != nil {
return err
}
// Add networking
netDevice, err := vfConfig.VirtioNetNew("5a:94:ef:e4:0c:ee")
if err != nil {
return err
}
// Set user networking with gvproxy
netDevice.SetUnixSocketPath(m.GvProxySock.GetPath())
m.Vfkit.VirtualMachine.Devices = append(m.Vfkit.VirtualMachine.Devices, netDevice)
if err := m.addVolumesToVfKit(); err != nil {
return err
}
// To start the VM, we need to call vfkit
logrus.Debugf("vfkit path is: %s", m.Vfkit.VfkitBinaryPath.Path)
cmd, err := m.Vfkit.VirtualMachine.Cmd(m.Vfkit.VfkitBinaryPath.Path)
if err != nil {
return err
}
vfkitEndpointArgs, err := getVfKitEndpointCMDArgs(m.Vfkit.Endpoint)
if err != nil {
return err
}
cmd.Args = append(cmd.Args, vfkitEndpointArgs...)
firstBoot, err := m.isFirstBoot()
if err != nil {
return err
}
if firstBoot {
// If this is the first boot of the vm, we need to add the vsock
// device to vfkit so we can inject the ignition file
ignitionSocket, err = m.deleteIgnitionSocket()
if err != nil {
return err
}
ignitionVsockDeviceCLI, err := getIgnitionVsockDeviceAsCLI(ignitionSocket.GetPath())
if err != nil {
return err
}
cmd.Args = append(cmd.Args, ignitionVsockDeviceCLI...)
}
if logrus.IsLevelEnabled(logrus.DebugLevel) {
debugDevArgs, err := getDebugDevicesCMDArgs()
if err != nil {
return err
}
cmd.Args = append(cmd.Args, debugDevArgs...)
cmd.Args = append(cmd.Args, "--gui") // add command line switch to pop the gui open
}
readSocketBaseDir := filepath.Dir(m.ReadySocket.GetPath())
if err := os.MkdirAll(readSocketBaseDir, 0755); err != nil {
return err
}
if firstBoot {
logrus.Debug("first boot detected")
logrus.Debugf("serving ignition file over %s", ignitionSocket.GetPath())
go func() {
if err := m.serveIgnitionOverSock(ignitionSocket); err != nil {
logrus.Error(err)
}
logrus.Debug("ignition vsock server exited")
}()
}
if err := m.ReadySocket.Delete(); err != nil {
return err
}
logrus.Debugf("listening for ready on: %s", m.ReadySocket.GetPath())
readyListen, err := net.Listen("unix", m.ReadySocket.GetPath())
if err != nil {
return err
}
logrus.Debug("waiting for ready notification")
readyChan := make(chan error)
go machine.ListenAndWaitOnSocket(readyChan, readyListen)
if err := cmd.Start(); err != nil {
return err
}
processErrChan := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
defer close(processErrChan)
for {
select {
case <-ctx.Done():
return
default:
}
if err := checkProcessRunning("vfkit", cmd.Process.Pid); err != nil {
processErrChan <- err
return
}
// lets poll status every half second
time.Sleep(500 * time.Millisecond)
}
}()
// wait for either socket or to be ready or process to have exited
select {
case err := <-processErrChan:
if err != nil {
return err
}
case err := <-readyChan:
if err != nil {
return err
}
}
logrus.Debug("ready notification received")
machine.WaitAPIAndPrintInfo(
forwardState,
m.Name,
findClaimHelper(),
forwardSock,
opts.NoInfo,
m.isIncompatible(),
m.Rootful,
)
// update the podman/docker socket service if the host user has been modified at all (UID or Rootful)
if m.HostUser.Modified {
if machine.UpdatePodmanDockerSockService(m, name, m.UID, m.Rootful) == nil {
// Reset modification state if there are no errors, otherwise ignore errors
// which are already logged
m.HostUser.Modified = false
_ = m.writeConfig()
}
}
return nil
}
func (m *MacMachine) State(_ bool) (machine.Status, error) {
vmStatus, err := m.Vfkit.state()
if err != nil {
return "", err
}
return vmStatus, nil
}
func (m *MacMachine) Stop(name string, opts machine.StopOptions) error {
m.lock.Lock()
defer m.lock.Unlock()
vmState, err := m.State(false)
if err != nil {
return err
}
if vmState != machine.Running {
return nil
}
defer func() {
if err := machine.CleanupGVProxy(m.GvProxyPid); err != nil {
logrus.Error(err)
}
}()
if err := m.Vfkit.stop(false, true); err != nil {
return err
}
// keep track of last up
m.LastUp = time.Now()
return m.writeConfig()
}
// getVMConfigPath is a simple wrapper for getting the fully-qualified
// path of the vm json config file. It should be used to get conformity
func getVMConfigPath(configDir, vmName string) string {
return filepath.Join(configDir, fmt.Sprintf("%s.json", vmName))
}
func (m *MacMachine) loadFromFile() (*MacMachine, error) {
if len(m.Name) < 1 {
return nil, errors.New("encountered machine with no name")
}
jsonPath, err := m.jsonConfigPath()
if err != nil {
return nil, err
}
mm, err := loadMacMachineFromJSON(jsonPath)
if err != nil {
return nil, err
}
lock, err := machine.GetLock(mm.Name, vmtype)
if err != nil {
return nil, err
}
mm.lock = lock
return mm, nil
}
func loadMacMachineFromJSON(fqConfigPath string) (*MacMachine, error) {
b, err := os.ReadFile(fqConfigPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
name := strings.TrimSuffix(filepath.Base(fqConfigPath), ".json")
return nil, fmt.Errorf("%s: %w", name, machine.ErrNoSuchVM)
}
return nil, err
}
mm := new(MacMachine)
if err := json.Unmarshal(b, mm); err != nil {
return nil, err
}
return mm, nil
}
func (m *MacMachine) jsonConfigPath() (string, error) {
configDir, err := machine.GetConfDir(machine.AppleHvVirt)
if err != nil {
return "", err
}
return getVMConfigPath(configDir, m.Name), nil
}
func getVMInfos() ([]*machine.ListResponse, error) {
vmConfigDir, err := machine.GetConfDir(vmtype)
if err != nil {
return nil, err
}
var listed []*machine.ListResponse
if err = filepath.WalkDir(vmConfigDir, func(path string, d fs.DirEntry, err error) error {
vm := new(MacMachine)
if strings.HasSuffix(d.Name(), ".json") {
fullPath := filepath.Join(vmConfigDir, d.Name())
b, err := os.ReadFile(fullPath)
if err != nil {
return err
}
err = json.Unmarshal(b, vm)
if err != nil {
return err
}
listEntry := new(machine.ListResponse)
listEntry.Name = vm.Name
listEntry.Stream = vm.ImageStream
listEntry.VMType = machine.AppleHvVirt.String()
listEntry.CPUs = vm.CPUs
listEntry.Memory = vm.Memory * units.MiB
listEntry.DiskSize = vm.DiskSize * units.GiB
listEntry.Port = vm.Port
listEntry.RemoteUsername = vm.RemoteUsername
listEntry.IdentityPath = vm.IdentityPath
listEntry.CreatedAt = vm.Created
listEntry.Starting = vm.Starting
if listEntry.CreatedAt.IsZero() {
listEntry.CreatedAt = time.Now()
vm.Created = time.Now()
if err := vm.writeConfig(); err != nil {
return err
}
}
vmState, err := vm.State(false)
if err != nil {
return err
}
listEntry.Running = vmState == machine.Running
listEntry.LastUp = vm.LastUp
listed = append(listed, listEntry)
}
return nil
}); err != nil {
return nil, err
}
return listed, err
}
// setupStartHostNetworkingCmd generates the cmd that will be used to start the
// host networking. Includes the ssh port, gvproxy pid file, gvproxy socket, and
// a debug flag depending on the logrus log level
func (m *MacMachine) setupStartHostNetworkingCmd() (gvproxy.GvproxyCommand, string, machine.APIForwardingState) {
cmd := gvproxy.NewGvproxyCommand()
cmd.SSHPort = m.Port
cmd.PidFile = m.GvProxyPid.GetPath()
cmd.AddVfkitSocket(fmt.Sprintf("unixgram://%s", m.GvProxySock.GetPath()))
cmd.Debug = logrus.IsLevelEnabled(logrus.DebugLevel)
cmd, forwardSock, state := m.setupAPIForwarding(cmd)
if cmd.Debug {
logrus.Debug(cmd.ToCmdline())
}
return cmd, forwardSock, state
}
func (m *MacMachine) startHostNetworking() (string, machine.APIForwardingState, error) {
var (
forwardSock string
state machine.APIForwardingState
)
// TODO This should probably be added to startHostNetworking everywhere
// GvProxy does not clean up after itself
if err := m.GvProxySock.Delete(); err != nil {
b, err := m.GvProxyPid.Read()
if err != nil {
return "", machine.NoForwarding, err
}
pid, err := strconv.Atoi(string(b))
if err != nil {
return "", 0, err
}
gvProcess, err := os.FindProcess(pid)
if err != nil {
return "", 0, err
}
// shoot it with a signal 0 and see if it is active
err = gvProcess.Signal(syscall.Signal(0))
if err == nil {
return "", 0, fmt.Errorf("gvproxy process %s already running", string(b))
}
if err := m.GvProxySock.Delete(); err != nil {
return "", 0, err
}
}
cfg, err := config.Default()
if err != nil {
return "", machine.NoForwarding, err
}
gvproxyBinary, err := cfg.FindHelperBinary("gvproxy", false)
if err != nil {
return "", 0, err
}
logrus.Debugf("gvproxy binary being used: %s", gvproxyBinary)
cmd, forwardSock, state := m.setupStartHostNetworkingCmd()
c := cmd.Cmd(gvproxyBinary)
if err := c.Start(); err != nil {
return "", 0, fmt.Errorf("unable to execute: %q: %w", cmd.ToCmdline(), err)
}
// We need to wait and make sure gvproxy is in fact running
// before continuing
for i := 0; i < 10; i++ {
_, err := os.Stat(m.GvProxySock.GetPath())
if err == nil {
break
}
if err := checkProcessRunning("gvproxy", c.Process.Pid); err != nil {
// gvproxy is no longer running
return "", 0, err
}
logrus.Debugf("gvproxy unixgram socket %q not found: %v", m.GvProxySock.GetPath(), err)
// Sleep for 1/2 second
time.Sleep(500 * time.Millisecond)
}
if err != nil {
// I guess we would also check the pidfile and look to see if it is running
// to?
return "", 0, fmt.Errorf("unable to verify gvproxy is running")
}
return forwardSock, state, nil
}
// checkProcessRunning checks non blocking if the pid exited
// returns nil if process is running otherwise an error if not
func checkProcessRunning(processName string, pid int) error {
var status syscall.WaitStatus
pid, err := syscall.Wait4(pid, &status, syscall.WNOHANG, nil)
if err != nil {
return fmt.Errorf("failed to read %s process status: %w", processName, err)
}
if pid > 0 {
// child exited
return fmt.Errorf("%s exited unexpectedly with exit code %d", processName, status.ExitStatus())
}
return nil
}
func (m *MacMachine) setupAPIForwarding(cmd gvproxy.GvproxyCommand) (gvproxy.GvproxyCommand, string, machine.APIForwardingState) {
socket, err := m.forwardSocketPath()
if err != nil {
return cmd, "", machine.NoForwarding
}
destSock := fmt.Sprintf("/run/user/%d/podman/podman.sock", m.UID)