-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.go
272 lines (240 loc) · 6.83 KB
/
control.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
package virtualbox
import (
"bytes"
"errors"
"fmt"
"net"
"os"
"os/exec"
"regexp"
"strings"
"time"
"github.com/sirupsen/logrus"
)
type StatusType string
const (
NotFound StatusType = "notfound"
PoweredOff StatusType = "poweroff"
Saved StatusType = "saved"
Teleported StatusType = "teleported"
Aborted StatusType = "aborted"
Running StatusType = "running"
Paused StatusType = "paused"
Stuck StatusType = "gurumeditation"
Teleporting StatusType = "teleporting"
LiveSnapshotting StatusType = "livesnapshotting"
Starting StatusType = "starting"
Stopping StatusType = "stopping"
Saving StatusType = "saving"
Restoring StatusType = "restoring"
TeleportingPausedVM StatusType = "teleportingpausedvm"
TeleportingIn StatusType = "teleportingin"
FaultTolerantSyncing StatusType = "faulttolerantsyncing"
DeletingSnapshotOnline StatusType = "deletingsnapshotlive"
DeletingSnapshotPaused StatusType = "deletingsnapshotlivepaused"
OnlineSnapshotting StatusType = "onlinesnapshotting"
RestoringSnapshot StatusType = "restoringsnapshot"
DeletingSnapshot StatusType = "deletingsnapshot"
SettingUp StatusType = "settingup"
Snapshotting StatusType = "snapshotting"
Unknown StatusType = "unknown"
// TODO: update as new VM states are added
)
func IsStatusOnlineOrTransient(vmStatus StatusType) bool {
switch vmStatus {
case Running,
Paused,
Stuck,
Teleporting,
LiveSnapshotting,
Starting,
Stopping,
Saving,
Restoring,
TeleportingPausedVM,
TeleportingIn,
FaultTolerantSyncing,
DeletingSnapshotOnline,
DeletingSnapshotPaused,
OnlineSnapshotting,
RestoringSnapshot,
DeletingSnapshot,
SettingUp,
Snapshotting:
return true
}
return false
}
func VboxManageOutput(exe string, args ...string) (string, error) {
var stdout, stderr bytes.Buffer
logrus.Debugf("Executing VBoxManageOutput: %#v", args)
cmd := exec.Command(exe, args...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
stderrString := strings.TrimSpace(stderr.String())
if _, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("VBoxManageOutput error: %s", stderrString)
}
return stdout.String(), err
}
func VBoxManage(args ...string) (string, error) {
return VboxManageOutput("vboxmanage", args...)
}
func Version() (string, error) {
version, err := VBoxManage("--version")
if err != nil {
return "", err
}
return strings.TrimSpace(version), nil
}
func FindSSHPort(vmName string) (port string, err error) {
info, err := VBoxManage("showvminfo", vmName)
if err != nil {
return
}
portRe := regexp.MustCompile(`guestssh.*host port = (\d+)`)
sshPort := portRe.FindStringSubmatch(info)
if len(sshPort) >= 2 {
port = sshPort[1]
} else {
err = errors.New("failed to find guestssh port")
}
return
}
func Exist(vmName string) bool {
_, err := VBoxManage("showvminfo", vmName)
if err != nil {
return false
}
return true
}
func CreateOsVM(vmName string, templateName string, templateSnapshot string) error {
args := []string{"clonevm", vmName, "--mode", "machine", "--name", templateName, "--register"}
if templateSnapshot != "" {
args = append(args, "--snapshot", templateSnapshot, "--options", "link")
}
_, err := VBoxManage(args...)
return err
}
func isPortUnassigned(testPort string, usedPorts [][]string) bool {
for _, port := range usedPorts {
if testPort == port[1] {
return false
}
}
return true
}
func getUsedVirtualBoxPorts() (usedPorts [][]string, err error) {
output, err := VBoxManage("list", "vms", "-l")
if err != nil {
return
}
allPortsRe := regexp.MustCompile(`host port = (\d+)`)
usedPorts = allPortsRe.FindAllStringSubmatch(output, -1)
return
}
func allocatePort(handler func(port string) error) (port string, err error) {
ln, err := net.Listen("tcp", ":0")
if err != nil {
logrus.Debugln("VirtualBox ConfigureSSH:", err)
return
}
defer ln.Close()
usedPorts, err := getUsedVirtualBoxPorts()
if err != nil {
logrus.Debugln("VirtualBox ConfigureSSH:", err)
return
}
addressElements := strings.Split(ln.Addr().String(), ":")
port = addressElements[len(addressElements)-1]
if isPortUnassigned(port, usedPorts) {
err = handler(port)
} else {
err = os.ErrExist
}
return
}
func ConfigureSSH(vmName string, vmSSHPort string) (port string, err error) {
for {
port, err = allocatePort(
func(port string) error {
rule := fmt.Sprintf("guestssh,tcp,127.0.0.1,%s,,%s", port, vmSSHPort)
_, err = VBoxManage("modifyvm", vmName, "--natpf1", rule)
return err
},
)
if err == nil || err != os.ErrExist {
return
}
}
}
func CreateSnapshot(vmName string, snapshotName string) error {
_, err := VBoxManage("snapshot", vmName, "take", snapshotName)
return err
}
func RevertToSnapshot(vmName string) error {
_, err := VBoxManage("snapshot", vmName, "restorecurrent")
return err
}
func HasSnapshot(vmName string, snapshotName string) bool {
output, err := VBoxManage("snapshot", vmName, "list", "--machinereadable")
if err != nil {
return false
}
snapshotRe := regexp.MustCompile(fmt.Sprintf(`(?m)^Snapshot(Name|UUID)[^=]*="%s"$`, regexp.QuoteMeta(snapshotName)))
snapshot := snapshotRe.FindStringSubmatch(output)
return snapshot != nil
}
func GetCurrentSnapshot(vmName string) (string, error) {
output, err := VBoxManage("snapshot", vmName, "list", "--machinereadable")
if err != nil {
return "", err
}
snapshotRe := regexp.MustCompile(`(?m)^CurrentSnapshotName="([^"]*)"$`)
snapshot := snapshotRe.FindStringSubmatch(output)
if snapshot == nil {
return "", errors.New("Failed to match current snapshot name")
}
return snapshot[1], nil
}
func Start(vmName string) error {
_, err := VBoxManage("startvm", vmName, "--type", "headless")
return err
}
func Kill(vmName string) error {
_, err := VBoxManage("controlvm", vmName, "poweroff")
return err
}
func Delete(vmName string) error {
_, err := VBoxManage("unregistervm", vmName, "--delete")
return err
}
func Status(vmName string) (StatusType, error) {
output, err := VBoxManage("showvminfo", vmName, "--machinereadable")
statusRe := regexp.MustCompile(`VMState="(\w+)"`)
status := statusRe.FindStringSubmatch(output)
if err != nil {
return NotFound, err
}
return StatusType(status[1]), nil
}
func WaitForStatus(vmName string, vmStatus StatusType, seconds int) error {
var status StatusType
var err error
for i := 0; i < seconds; i++ {
status, err = Status(vmName)
if err != nil {
return err
}
if status == vmStatus {
return nil
}
time.Sleep(time.Second)
}
return errors.New("VM " + vmName + " is in " + string(status) + " where it should be in " + string(vmStatus))
}
func Unregister(vmName string) error {
_, err := VBoxManage("unregistervm", vmName)
return err
}