forked from terra-farm/go-virtualbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine.go
401 lines (364 loc) · 9.11 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
package virtualbox
import (
"bufio"
"fmt"
"path/filepath"
"strconv"
"strings"
"time"
)
type MachineState string
const (
Poweroff = MachineState("poweroff")
Running = MachineState("running")
Paused = MachineState("paused")
Saved = MachineState("saved")
Aborted = MachineState("aborted")
)
type Flag int
// Flag names in lowercases to be consistent with VBoxManage options.
const (
F_acpi Flag = 1 << iota
F_ioapic
F_rtcuseutc
F_cpuhotplug
F_pae
F_longmode
F_synthcpu
F_hpet
F_hwvirtex
F_triplefaultreset
F_nestedpaging
F_largepages
F_vtxvpid
F_vtxux
F_accelerate3d
)
// Convert bool to "on"/"off"
func bool2string(b bool) string {
if b {
return "on"
}
return "off"
}
// Test if flag is set. Return "on" or "off".
func (f Flag) Get(o Flag) string {
return bool2string(f&o == o)
}
// Machine information.
type Machine struct {
Name string
UUID string
State MachineState
CPUs uint
Memory uint // main memory (in MB)
VRAM uint // video memory (in MB)
CfgFile string
BaseFolder string
OSType string
Flag Flag
BootOrder []string // max 4 slots, each in {none|floppy|dvd|disk|net}
}
// Refresh reloads the machine information.
func (m *Machine) Refresh() error {
id := m.Name
if id == "" {
id = m.UUID
}
mm, err := GetMachine(id)
if err != nil {
return err
}
*m = *mm
return nil
}
// Start starts the machine.
func (m *Machine) Start() error {
switch m.State {
case Paused:
return vbm("controlvm", m.Name, "resume")
case Poweroff, Saved, Aborted:
return vbm("startvm", m.Name, "--type", "headless")
}
return nil
}
// Suspend suspends the machine and saves its state to disk.
func (m *Machine) Save() error {
switch m.State {
case Paused:
if err := m.Start(); err != nil {
return err
}
case Poweroff, Aborted, Saved:
return nil
}
return vbm("controlvm", m.Name, "savestate")
}
// Pause pauses the execution of the machine.
func (m *Machine) Pause() error {
switch m.State {
case Paused, Poweroff, Aborted, Saved:
return nil
}
return vbm("controlvm", m.Name, "pause")
}
// Stop gracefully stops the machine.
func (m *Machine) Stop() error {
switch m.State {
case Poweroff, Aborted, Saved:
return nil
case Paused:
if err := m.Start(); err != nil {
return err
}
}
for m.State != Poweroff { // busy wait until the machine is stopped
if err := vbm("controlvm", m.Name, "acpipowerbutton"); err != nil {
return err
}
time.Sleep(1 * time.Second)
if err := m.Refresh(); err != nil {
return err
}
}
return nil
}
// Poweroff forcefully stops the machine. State is lost and might corrupt the disk image.
func (m *Machine) Poweroff() error {
switch m.State {
case Poweroff, Aborted, Saved:
return nil
}
return vbm("controlvm", m.Name, "poweroff")
}
// Restart gracefully restarts the machine.
func (m *Machine) Restart() error {
switch m.State {
case Paused, Saved:
if err := m.Start(); err != nil {
return err
}
}
if err := m.Stop(); err != nil {
return err
}
return m.Start()
}
// Reset forcefully restarts the machine. State is lost and might corrupt the disk image.
func (m *Machine) Reset() error {
switch m.State {
case Paused, Saved:
if err := m.Start(); err != nil {
return err
}
}
return vbm("controlvm", m.Name, "reset")
}
// Delete deletes the machine and associated disk images.
func (m *Machine) Delete() error {
if err := m.Poweroff(); err != nil {
return err
}
return vbm("unregistervm", m.Name, "--delete")
}
// GetMachine finds a machine by its name or UUID.
func GetMachine(id string) (*Machine, error) {
stdout, stderr, err := vbmOutErr("showvminfo", id, "--machinereadable")
if err != nil {
if reMachineNotFound.FindString(stderr) != "" {
return nil, ErrMachineNotExist
}
return nil, err
}
s := bufio.NewScanner(strings.NewReader(stdout))
m := &Machine{}
for s.Scan() {
res := reVMInfoLine.FindStringSubmatch(s.Text())
if res == nil {
continue
}
key := res[1]
if key == "" {
key = res[2]
}
val := res[3]
if val == "" {
val = res[4]
}
switch key {
case "name":
m.Name = val
case "UUID":
m.UUID = val
case "VMState":
m.State = MachineState(val)
case "memory":
n, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return nil, err
}
m.Memory = uint(n)
case "cpus":
n, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return nil, err
}
m.CPUs = uint(n)
case "vram":
n, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return nil, err
}
m.VRAM = uint(n)
case "CfgFile":
m.CfgFile = val
m.BaseFolder = filepath.Dir(val)
}
}
if err := s.Err(); err != nil {
return nil, err
}
return m, nil
}
// ListMachines lists all registered machines.
func ListMachines() ([]*Machine, error) {
out, err := vbmOut("list", "vms")
if err != nil {
return nil, err
}
ms := []*Machine{}
s := bufio.NewScanner(strings.NewReader(out))
for s.Scan() {
res := reVMNameUUID.FindStringSubmatch(s.Text())
if res == nil {
continue
}
m, err := GetMachine(res[1])
if err != nil {
return nil, err
}
ms = append(ms, m)
}
if err := s.Err(); err != nil {
return nil, err
}
return ms, nil
}
// CreateMachine creates a new machine. If basefolder is empty, use default.
func CreateMachine(name, basefolder string) (*Machine, error) {
if name == "" {
return nil, fmt.Errorf("machine name is empty")
}
// Check if a machine with the given name already exists.
ms, err := ListMachines()
if err != nil {
return nil, err
}
for _, m := range ms {
if m.Name == name {
return nil, ErrMachineExist
}
}
// Create and register the machine.
args := []string{"createvm", "--name", name, "--register"}
if basefolder != "" {
args = append(args, "--basefolder", basefolder)
}
if err := vbm(args...); err != nil {
return nil, err
}
m, err := GetMachine(name)
if err != nil {
return nil, err
}
return m, nil
}
// Modify changes the settings of the machine.
func (m *Machine) Modify() error {
args := []string{"modifyvm", m.Name,
"--firmware", "bios",
"--bioslogofadein", "off",
"--bioslogofadeout", "off",
"--bioslogodisplaytime", "0",
"--biosbootmenu", "disabled",
"--ostype", m.OSType,
"--cpus", fmt.Sprintf("%d", m.CPUs),
"--memory", fmt.Sprintf("%d", m.Memory),
"--vram", fmt.Sprintf("%d", m.VRAM),
"--acpi", m.Flag.Get(F_acpi),
"--ioapic", m.Flag.Get(F_ioapic),
"--rtcuseutc", m.Flag.Get(F_rtcuseutc),
"--cpuhotplug", m.Flag.Get(F_cpuhotplug),
"--pae", m.Flag.Get(F_pae),
"--longmode", m.Flag.Get(F_longmode),
"--synthcpu", m.Flag.Get(F_synthcpu),
"--hpet", m.Flag.Get(F_hpet),
"--hwvirtex", m.Flag.Get(F_hwvirtex),
"--triplefaultreset", m.Flag.Get(F_triplefaultreset),
"--nestedpaging", m.Flag.Get(F_nestedpaging),
"--largepages", m.Flag.Get(F_largepages),
"--vtxvpid", m.Flag.Get(F_vtxvpid),
"--vtxux", m.Flag.Get(F_vtxux),
"--accelerate3d", m.Flag.Get(F_accelerate3d),
}
for i, dev := range m.BootOrder {
if i > 3 {
break // Only four slots `--boot{1,2,3,4}`. Ignore the rest.
}
args = append(args, fmt.Sprintf("--boot%d", i+1), dev)
}
if err := vbm(args...); err != nil {
return err
}
return m.Refresh()
}
// AddNATPF adds a NAT port forarding rule to the n-th NIC with the given name.
func (m *Machine) AddNATPF(n int, name string, rule PFRule) error {
return vbm("controlvm", m.Name, fmt.Sprintf("natpf%d", n),
fmt.Sprintf("%s,%s", name, rule.Format()))
}
// DelNATPF deletes the NAT port forwarding rule with the given name from the n-th NIC.
func (m *Machine) DelNATPF(n int, name string) error {
return vbm("controlvm", m.Name, fmt.Sprintf("natpf%d", n), "delete", name)
}
// SetNIC set the n-th NIC.
func (m *Machine) SetNIC(n int, nic NIC) error {
args := []string{"modifyvm", m.Name,
fmt.Sprintf("--nic%d", n), string(nic.Network),
fmt.Sprintf("--nictype%d", n), string(nic.Hardware),
fmt.Sprintf("--cableconnected%d", n), "on",
}
if nic.Network == "hostonly" {
args = append(args, fmt.Sprintf("--hostonlyadapter%d", n), nic.HostonlyAdapter)
}
return vbm(args...)
}
// AddStorageCtl adds a storage controller with the given name.
func (m *Machine) AddStorageCtl(name string, ctl StorageController) error {
args := []string{"storagectl", m.Name, "--name", name}
if ctl.SysBus != "" {
args = append(args, "--add", string(ctl.SysBus))
}
if ctl.Ports > 0 {
args = append(args, "--portcount", fmt.Sprintf("%d", ctl.Ports))
}
if ctl.Chipset != "" {
args = append(args, "--controller", string(ctl.Chipset))
}
args = append(args, "--hostiocache", bool2string(ctl.HostIOCache))
args = append(args, "--bootable", bool2string(ctl.Bootable))
return vbm(args...)
}
// DelStorageCtl deletes the storage controller with the given name.
func (m *Machine) DelStorageCtl(name string) error {
return vbm("storagectl", m.Name, "--name", name, "--remove")
}
// AttachStorage attaches a storage medium to the named storage controller.
func (m *Machine) AttachStorage(ctlName string, medium StorageMedium) error {
return vbm("storageattach", m.Name, "--storagectl", ctlName,
"--port", fmt.Sprintf("%d", medium.Port),
"--device", fmt.Sprintf("%d", medium.Device),
"--type", string(medium.DriveType),
"--medium", medium.Medium,
)
}