-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.go
365 lines (328 loc) · 10.1 KB
/
main.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"runtime"
"time"
"github.com/Code-Hex/vz/v3"
)
var install bool
var nbdURL string
func init() {
flag.BoolVar(&install, "install", false, "run command as install mode")
flag.StringVar(&nbdURL, "nbd-url", "", "nbd url (e.g. nbd+unix:///export?socket=nbd.sock)")
}
func main() {
flag.Parse()
if err := run(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "failed to run: %v", err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
if install {
return installMacOS(ctx)
}
return runVM(ctx)
}
func runVM(ctx context.Context) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
platformConfig, err := createMacPlatformConfiguration()
if err != nil {
return err
}
config, err := setupVMConfiguration(platformConfig)
if err != nil {
return err
}
vm, err := vz.NewVirtualMachine(config)
if err != nil {
return err
}
if err := vm.Start(); err != nil {
return err
}
errCh := make(chan error, 1)
go func() {
for {
select {
case newState := <-vm.StateChangedNotify():
if newState == vz.VirtualMachineStateRunning {
log.Println("start VM is running")
}
if newState == vz.VirtualMachineStateStopped || newState == vz.VirtualMachineStateStopping {
log.Println("stopped state")
errCh <- nil
return
}
case err := <-errCh:
errCh <- fmt.Errorf("failed to start vm: %w", err)
return
}
}
}()
// it start listening to the NBD server, if any
nbdAttachment := retrieveNetworkBlockDeviceStorageDeviceAttachment(config.StorageDevices())
if nbdAttachment != nil {
go func() {
for {
select {
case err := <-nbdAttachment.DidEncounterError():
log.Printf("NBD client has been encountered error: %v\n", err)
case <-nbdAttachment.Connected():
log.Println("NBD client connected with the server")
}
}
}()
}
// cleanup is this function is useful when finished graphic application.
cleanup := func() {
for i := 1; vm.CanRequestStop(); i++ {
result, err := vm.RequestStop()
log.Printf("sent stop request(%d): %t, %v", i, result, err)
time.Sleep(time.Second * 3)
if i > 3 {
log.Println("call stop")
if err := vm.Stop(); err != nil {
log.Println("stop with error", err)
return
}
// if err := vm.Pause(); err != nil {
// log.Println("pause with error", err)
// return
// }
// if err := vm.SaveMachineStateToPath("savestate"); err != nil {
// log.Println("save state with error", err)
// }
}
}
log.Println("finished cleanup")
}
vm.StartGraphicApplication(960, 600, vz.WithWindowTitle("macOS"), vz.WithController(true))
cleanup()
return <-errCh
}
func computeCPUCount() uint {
totalAvailableCPUs := runtime.NumCPU()
virtualCPUCount := uint(totalAvailableCPUs - 1)
if virtualCPUCount <= 1 {
virtualCPUCount = 1
}
// TODO(codehex): use generics function when deprecated Go 1.17
maxAllowed := vz.VirtualMachineConfigurationMaximumAllowedCPUCount()
if virtualCPUCount > maxAllowed {
virtualCPUCount = maxAllowed
}
minAllowed := vz.VirtualMachineConfigurationMinimumAllowedCPUCount()
if virtualCPUCount < minAllowed {
virtualCPUCount = minAllowed
}
return virtualCPUCount
}
func computeMemorySize() uint64 {
// We arbitrarily choose 4GB.
memorySize := uint64(4 * 1024 * 1024 * 1024)
maxAllowed := vz.VirtualMachineConfigurationMaximumAllowedMemorySize()
if memorySize > maxAllowed {
memorySize = maxAllowed
}
minAllowed := vz.VirtualMachineConfigurationMinimumAllowedMemorySize()
if memorySize < minAllowed {
memorySize = minAllowed
}
return memorySize
}
func createBlockDeviceConfiguration(diskPath string) (*vz.VirtioBlockDeviceConfiguration, error) {
// create disk image with 64 GiB
if err := vz.CreateDiskImage(diskPath, 64*1024*1024*1024); err != nil {
if !os.IsExist(err) {
return nil, fmt.Errorf("failed to create disk image: %w", err)
}
}
attachment, err := vz.NewDiskImageStorageDeviceAttachment(
diskPath,
false,
)
if err != nil {
return nil, err
}
return vz.NewVirtioBlockDeviceConfiguration(attachment)
}
func createNetworkBlockDeviceConfiguration(nbdURL string) (*vz.VirtioBlockDeviceConfiguration, error) {
attachment, err := vz.NewNetworkBlockDeviceStorageDeviceAttachment(
nbdURL,
10*time.Second,
false,
vz.DiskSynchronizationModeFull,
)
if err != nil {
return nil, err
}
return vz.NewVirtioBlockDeviceConfiguration(attachment)
}
func createGraphicsDeviceConfiguration() (*vz.MacGraphicsDeviceConfiguration, error) {
graphicDeviceConfig, err := vz.NewMacGraphicsDeviceConfiguration()
if err != nil {
return nil, err
}
graphicsDisplayConfig, err := vz.NewMacGraphicsDisplayConfiguration(1920, 1200, 80)
if err != nil {
return nil, err
}
graphicDeviceConfig.SetDisplays(
graphicsDisplayConfig,
)
return graphicDeviceConfig, nil
}
func createNetworkDeviceConfiguration() (*vz.VirtioNetworkDeviceConfiguration, error) {
natAttachment, err := vz.NewNATNetworkDeviceAttachment()
if err != nil {
return nil, err
}
return vz.NewVirtioNetworkDeviceConfiguration(natAttachment)
}
func createKeyboardConfiguration() (vz.KeyboardConfiguration, error) {
config, err := vz.NewMacKeyboardConfiguration()
if err != nil {
if errors.Is(err, vz.ErrUnsupportedOSVersion) {
return vz.NewUSBKeyboardConfiguration()
}
return nil, err
}
return config, nil
}
func createAudioDeviceConfiguration() (*vz.VirtioSoundDeviceConfiguration, error) {
audioConfig, err := vz.NewVirtioSoundDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create sound device configuration: %w", err)
}
inputStream, err := vz.NewVirtioSoundDeviceHostInputStreamConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create input stream configuration: %w", err)
}
outputStream, err := vz.NewVirtioSoundDeviceHostOutputStreamConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create output stream configuration: %w", err)
}
audioConfig.SetStreams(
inputStream,
outputStream,
)
return audioConfig, nil
}
func createMacPlatformConfiguration() (*vz.MacPlatformConfiguration, error) {
auxiliaryStorage, err := vz.NewMacAuxiliaryStorage(GetAuxiliaryStoragePath())
if err != nil {
return nil, fmt.Errorf("failed to create a new mac auxiliary storage: %w", err)
}
hardwareModel, err := vz.NewMacHardwareModelWithDataPath(
GetHardwareModelPath(),
)
if err != nil {
return nil, fmt.Errorf("failed to create a new hardware model: %w", err)
}
machineIdentifier, err := vz.NewMacMachineIdentifierWithDataPath(
GetMachineIdentifierPath(),
)
if err != nil {
return nil, fmt.Errorf("failed to create a new machine identifier: %w", err)
}
return vz.NewMacPlatformConfiguration(
vz.WithMacAuxiliaryStorage(auxiliaryStorage),
vz.WithMacHardwareModel(hardwareModel),
vz.WithMacMachineIdentifier(machineIdentifier),
)
}
func setupVMConfiguration(platformConfig vz.PlatformConfiguration) (*vz.VirtualMachineConfiguration, error) {
bootloader, err := vz.NewMacOSBootLoader()
if err != nil {
return nil, err
}
config, err := vz.NewVirtualMachineConfiguration(
bootloader,
computeCPUCount(),
computeMemorySize(),
)
if err != nil {
return nil, err
}
config.SetPlatformVirtualMachineConfiguration(platformConfig)
graphicsDeviceConfig, err := createGraphicsDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create graphics device configuration: %w", err)
}
config.SetGraphicsDevicesVirtualMachineConfiguration([]vz.GraphicsDeviceConfiguration{
graphicsDeviceConfig,
})
blockDeviceConfig, err := createBlockDeviceConfiguration(GetDiskImagePath())
if err != nil {
return nil, fmt.Errorf("failed to create block device configuration: %w", err)
}
sdconfigs := []vz.StorageDeviceConfiguration{blockDeviceConfig}
if nbdURL != "" {
ndbConfig, err := createNetworkBlockDeviceConfiguration(nbdURL)
if err != nil {
return nil, fmt.Errorf("failed to create network block device configuration: %w", err)
}
sdconfigs = append(sdconfigs, ndbConfig)
}
config.SetStorageDevicesVirtualMachineConfiguration(sdconfigs)
networkDeviceConfig, err := createNetworkDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create network device configuration: %w", err)
}
config.SetNetworkDevicesVirtualMachineConfiguration([]*vz.VirtioNetworkDeviceConfiguration{
networkDeviceConfig,
})
usbScreenPointingDevice, err := vz.NewUSBScreenCoordinatePointingDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create pointing device configuration: %w", err)
}
pointingDevices := []vz.PointingDeviceConfiguration{usbScreenPointingDevice}
trackpad, err := vz.NewMacTrackpadConfiguration()
if err == nil {
pointingDevices = append(pointingDevices, trackpad)
}
config.SetPointingDevicesVirtualMachineConfiguration(pointingDevices)
keyboardDeviceConfig, err := createKeyboardConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create keyboard device configuration: %w", err)
}
config.SetKeyboardsVirtualMachineConfiguration([]vz.KeyboardConfiguration{
keyboardDeviceConfig,
})
audioDeviceConfig, err := createAudioDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create audio device configuration: %w", err)
}
config.SetAudioDevicesVirtualMachineConfiguration([]vz.AudioDeviceConfiguration{
audioDeviceConfig,
})
validated, err := config.Validate()
if err != nil {
return nil, fmt.Errorf("failed to validate configuration: %w", err)
}
if !validated {
return nil, fmt.Errorf("invalid configuration")
}
// If you want to try this one, you need to comment out a few of configs.
//
// if _, err := config.ValidateSaveRestoreSupport(); err != nil {
// return nil, fmt.Errorf("failed to validate save restore configuration: %w", err)
// }
return config, nil
}
func retrieveNetworkBlockDeviceStorageDeviceAttachment(storages []vz.StorageDeviceConfiguration) *vz.NetworkBlockDeviceStorageDeviceAttachment {
for _, storage := range storages {
attachment := storage.Attachment()
if nbdAttachment, ok := attachment.(*vz.NetworkBlockDeviceStorageDeviceAttachment); ok {
return nbdAttachment
}
}
return nil
}