-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.go
435 lines (384 loc) · 12.7 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
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
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"runtime"
"time"
"github.com/Code-Hex/vz/v3"
)
var install bool
func init() {
flag.BoolVar(&install, "install", false, "run command as install mode")
}
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 {
installerISOPath := os.Getenv("INSTALLER_ISO_PATH")
if install {
if installerISOPath == "" {
return fmt.Errorf("must be specified INSTALLER_ISO_PATH env")
}
if err := CreateVMBundle(); err != nil {
return err
}
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
config, err := createVirtualMachineConfig(installerISOPath, install)
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
}
}
}()
// 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)
}
}
}
log.Println("finished cleanup")
}
runtime.LockOSThread()
vm.StartGraphicApplication(960, 600, vz.WithWindowTitle("Linux"), vz.WithController(true))
runtime.UnlockOSThread()
cleanup()
return <-errCh
}
// Create an empty disk image for the virtual machine.
func createMainDiskImage(diskPath string) error {
// create disk image with 64 GiB
if err := vz.CreateDiskImage(diskPath, 64*1024*1024*1024); err != nil {
if !os.IsExist(err) {
return fmt.Errorf("failed to create disk image: %w", err)
}
}
return nil
}
func createBlockDeviceConfiguration(diskPath string) (*vz.VirtioBlockDeviceConfiguration, error) {
attachment, err := vz.NewDiskImageStorageDeviceAttachmentWithCacheAndSync(diskPath, false, vz.DiskImageCachingModeAutomatic, vz.DiskImageSynchronizationModeFsync)
if err != nil {
return nil, fmt.Errorf("failed to create a new disk image storage device attachment: %w", err)
}
mainDisk, err := vz.NewVirtioBlockDeviceConfiguration(attachment)
if err != nil {
return nil, fmt.Errorf("failed to create a new block deveice config: %w", err)
}
return mainDisk, nil
}
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 createAndSaveMachineIdentifier(identifierPath string) (*vz.GenericMachineIdentifier, error) {
machineIdentifier, err := vz.NewGenericMachineIdentifier()
if err != nil {
return nil, fmt.Errorf("failed to create a new machine identifier: %w", err)
}
err = CreateFileAndWriteTo(machineIdentifier.DataRepresentation(), identifierPath)
if err != nil {
return nil, fmt.Errorf("failed to save machine identifier data: %w", err)
}
return machineIdentifier, nil
}
func createEFIVariableStore(efiVariableStorePath string) (*vz.EFIVariableStore, error) {
variableStore, err := vz.NewEFIVariableStore(
efiVariableStorePath,
vz.WithCreatingEFIVariableStore(),
)
if err != nil {
return nil, fmt.Errorf("failed to create EFI variable store: %w", err)
}
return variableStore, nil
}
func createUSBMassStorageDeviceConfiguration(installerISOPath string) (*vz.USBMassStorageDeviceConfiguration, error) {
installerDiskAttachment, err := vz.NewDiskImageStorageDeviceAttachment(
installerISOPath,
true,
)
if err != nil {
return nil, fmt.Errorf("failed to create a new disk attachment for USBMassConfiguration: %w", err)
}
config, err := vz.NewUSBMassStorageDeviceConfiguration(installerDiskAttachment)
if err != nil {
return nil, fmt.Errorf("failed to create a new USB storage device: %w", err)
}
return config, nil
}
func createNetworkDeviceConfiguration() (*vz.VirtioNetworkDeviceConfiguration, error) {
natAttachment, err := vz.NewNATNetworkDeviceAttachment()
if err != nil {
return nil, fmt.Errorf("nat attachment initialization failed: %w", err)
}
netConfig, err := vz.NewVirtioNetworkDeviceConfiguration(natAttachment)
if err != nil {
return nil, fmt.Errorf("failed to create a network device: %w", err)
}
return netConfig, nil
}
func createGraphicsDeviceConfiguration() (*vz.VirtioGraphicsDeviceConfiguration, error) {
graphicDeviceConfig, err := vz.NewVirtioGraphicsDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to initialize virtio graphic device: %w", err)
}
graphicsScanoutConfig, err := vz.NewVirtioGraphicsScanoutConfiguration(1920, 1200)
if err != nil {
return nil, fmt.Errorf("failed to create graphics scanout: %w", err)
}
graphicDeviceConfig.SetScanouts(
graphicsScanoutConfig,
)
return graphicDeviceConfig, nil
}
func createInputAudioDeviceConfiguration() (*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)
}
audioConfig.SetStreams(
inputStream,
)
return audioConfig, nil
}
func createOutputAudioDeviceConfiguration() (*vz.VirtioSoundDeviceConfiguration, error) {
audioConfig, err := vz.NewVirtioSoundDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create sound device configuration: %w", err)
}
outputStream, err := vz.NewVirtioSoundDeviceHostOutputStreamConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create output stream configuration: %w", err)
}
audioConfig.SetStreams(
outputStream,
)
return audioConfig, nil
}
func createSpiceAgentConsoleDeviceConfiguration() (*vz.VirtioConsoleDeviceConfiguration, error) {
consoleDevice, err := vz.NewVirtioConsoleDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create a new console device: %w", err)
}
spiceAgentAttachment, err := vz.NewSpiceAgentPortAttachment()
if err != nil {
return nil, fmt.Errorf("failed to create a new spice agent attachment: %w", err)
}
spiceAgentName, err := vz.SpiceAgentPortAttachmentName()
if err != nil {
return nil, fmt.Errorf("failed to get spice agent name: %w", err)
}
spiceAgentPort, err := vz.NewVirtioConsolePortConfiguration(
vz.WithVirtioConsolePortConfigurationAttachment(spiceAgentAttachment),
vz.WithVirtioConsolePortConfigurationName(spiceAgentName),
)
if err != nil {
return nil, fmt.Errorf("failed to create a new console port for spice agent: %w", err)
}
consoleDevice.SetVirtioConsolePortConfiguration(0, spiceAgentPort)
return consoleDevice, nil
}
func getMachineIdentifier(needsInstall bool) (*vz.GenericMachineIdentifier, error) {
path := GetMachineIdentifierPath()
if needsInstall {
return createAndSaveMachineIdentifier(path)
}
return vz.NewGenericMachineIdentifierWithDataPath(path)
}
func getEFIVariableStore(needsInstall bool) (*vz.EFIVariableStore, error) {
path := GetEFIVariableStorePath()
if needsInstall {
return createEFIVariableStore(path)
}
return vz.NewEFIVariableStore(path)
}
func createVirtualMachineConfig(installerISOPath string, needsInstall bool) (*vz.VirtualMachineConfiguration, error) {
machineIdentifier, err := getMachineIdentifier(needsInstall)
if err != nil {
return nil, err
}
platformConfig, err := vz.NewGenericPlatformConfiguration(
vz.WithGenericMachineIdentifier(machineIdentifier),
)
if err != nil {
return nil, fmt.Errorf("failed to create a new platform config: %w", err)
}
efiVariableStore, err := getEFIVariableStore(needsInstall)
if err != nil {
return nil, err
}
bootLoader, err := vz.NewEFIBootLoader(
vz.WithEFIVariableStore(efiVariableStore),
)
if err != nil {
return nil, fmt.Errorf("failed to create a new EFI boot loader: %w", err)
}
disks := make([]vz.StorageDeviceConfiguration, 0)
if needsInstall {
usbConfig, err := createUSBMassStorageDeviceConfiguration(installerISOPath)
if err != nil {
return nil, err
}
disks = append(disks, usbConfig)
}
config, err := vz.NewVirtualMachineConfiguration(
bootLoader,
computeCPUCount(),
computeMemorySize(),
)
if err != nil {
return nil, fmt.Errorf("failed to create vm config: %w", err)
}
config.SetPlatformVirtualMachineConfiguration(platformConfig)
// Set graphic device
graphicsDeviceConfig, err := createGraphicsDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create graphics device configuration: %w", err)
}
config.SetGraphicsDevicesVirtualMachineConfiguration([]vz.GraphicsDeviceConfiguration{
graphicsDeviceConfig,
})
// Set storage device
mainDiskPath := GetMainDiskImagePath()
if needsInstall {
if err := createMainDiskImage(mainDiskPath); err != nil {
return nil, fmt.Errorf("failed to create a main disk image: %w", err)
}
}
mainDisk, err := createBlockDeviceConfiguration(mainDiskPath)
if err != nil {
return nil, err
}
disks = append(disks, mainDisk)
config.SetStorageDevicesVirtualMachineConfiguration(disks)
consoleDeviceConfig, err := createSpiceAgentConsoleDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create console device configuration: %w", err)
}
config.SetConsoleDevicesVirtualMachineConfiguration([]vz.ConsoleDeviceConfiguration{
consoleDeviceConfig,
})
// Set network device
networkDeviceConfig, err := createNetworkDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create network device configuration: %w", err)
}
config.SetNetworkDevicesVirtualMachineConfiguration([]*vz.VirtioNetworkDeviceConfiguration{
networkDeviceConfig,
})
// Set audio device
inputAudioDeviceConfig, err := createInputAudioDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create input audio device configuration: %w", err)
}
outputAudioDeviceConfig, err := createOutputAudioDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create output audio device configuration: %w", err)
}
config.SetAudioDevicesVirtualMachineConfiguration([]vz.AudioDeviceConfiguration{
inputAudioDeviceConfig,
outputAudioDeviceConfig,
})
// Set pointing device
pointingDeviceConfig, err := vz.NewUSBScreenCoordinatePointingDeviceConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create pointing device configuration: %w", err)
}
config.SetPointingDevicesVirtualMachineConfiguration([]vz.PointingDeviceConfiguration{
pointingDeviceConfig,
})
// Set keyboard device
keyboardDeviceConfig, err := vz.NewUSBKeyboardConfiguration()
if err != nil {
return nil, fmt.Errorf("failed to create keyboard device configuration: %w", err)
}
config.SetKeyboardsVirtualMachineConfiguration([]vz.KeyboardConfiguration{
keyboardDeviceConfig,
})
// Set rosetta directory share
directorySharingConfigs := make([]vz.DirectorySharingDeviceConfiguration, 0)
directorySharingDeviceConfig, err := createRosettaDirectoryShareConfiguration()
if err != nil && !errors.Is(err, errIgnoreInstall) {
return nil, err
}
if directorySharingDeviceConfig != nil {
directorySharingConfigs = append(directorySharingConfigs, directorySharingDeviceConfig)
}
config.SetDirectorySharingDevicesVirtualMachineConfiguration(directorySharingConfigs)
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")
}
return config, nil
}