/
vm.go
121 lines (100 loc) · 2.48 KB
/
vm.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
package vm
import (
"encoding/json"
"fmt"
"strconv"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
apiv1 "github.com/cppforlife/bosh-cpi-go/apiv1"
"github.com/cppforlife/bosh-virtualbox-cpi/driver"
bpds "github.com/cppforlife/bosh-virtualbox-cpi/vm/portdevices"
)
type VMImpl struct {
cid apiv1.VMCID
portDevices bpds.PortDevices
store Store
stemcellAPIVersion apiv1.StemcellAPIVersion
driver driver.Driver
logger boshlog.Logger
}
func NewVMImpl(
cid apiv1.VMCID,
portDevices bpds.PortDevices,
store Store,
stemcellAPIVersion apiv1.StemcellAPIVersion,
driver driver.Driver,
logger boshlog.Logger,
) VMImpl {
return VMImpl{
cid: cid,
portDevices: portDevices,
store: store,
stemcellAPIVersion: stemcellAPIVersion,
driver: driver,
logger: logger,
}
}
func (vm VMImpl) ID() apiv1.VMCID { return vm.cid }
func (vm VMImpl) SetProps(props VMProps) error {
_, err := vm.driver.Execute(
"modifyvm", vm.cid.AsString(),
"--name", vm.cid.AsString(),
"--memory", strconv.Itoa(props.Memory),
"--cpus", strconv.Itoa(props.CPUs),
"--paravirtprovider", props.ParavirtProvider,
"--audio", props.Audio,
)
if err != nil {
return err
}
for index, folder := range props.SharedFolders {
name := fmt.Sprintf("folder-%d", index)
_, err := vm.driver.Execute(
"setextradata", vm.cid.AsString(),
"VBoxInternal2/SharedFoldersEnableSymlinksCreate/"+name, "1",
)
if err != nil {
return err
}
_, err = vm.driver.Execute(
"sharedfolder", "add", vm.cid.AsString(),
"--name", name,
"--hostpath", folder.HostPath,
)
if err != nil {
return err
}
}
return nil
}
func (vm VMImpl) SetMetadata(meta apiv1.VMMeta) error {
// todo can we do better?
bytes, err := json.Marshal(meta)
if err != nil {
return bosherr.WrapError(err, "Marshaling VM metadata")
}
err = vm.store.Put("metadata.json", bytes)
if err != nil {
return bosherr.WrapError(err, "Saving VM metadata")
}
return nil
}
func (vm VMImpl) ConfigureNICs(nets Networks, host Host) error {
return NICs{vm.driver, vm.ID()}.Configure(nets, host)
}
func (vm VMImpl) Delete() error {
err := vm.HaltIfRunning()
if err != nil {
return err
}
// todo is this necessary?
err = vm.detachPersistentDisks()
if err != nil {
return err
}
_, err = vm.driver.Execute("unregistervm", vm.cid.AsString(), "--delete")
if err != nil {
return err
}
return vm.store.Delete()
}