forked from Cloud-Foundations/Dominator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
importVirshVm.go
367 lines (343 loc) · 9.64 KB
/
importVirshVm.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
package main
import (
"encoding/xml"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/Cloud-Foundations/Dominator/lib/errors"
"github.com/Cloud-Foundations/Dominator/lib/json"
"github.com/Cloud-Foundations/Dominator/lib/log"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
proto "github.com/Cloud-Foundations/Dominator/proto/hypervisor"
)
type bridgeType struct {
Bridge string `xml:"bridge,attr"`
}
type cpuType struct {
Mode string `xml:"mode,attr"`
}
type devicesInfo struct {
Volumes []volumeType `xml:"disk"`
Interfaces []interfaceType `xml:"interface"`
SerialPorts []serialType `xml:"serial"`
}
type driverType struct {
Name string `xml:"name,attr"`
Type string `xml:"type,attr"`
Cache string `xml:"cache,attr"`
Io string `xml:"io,attr"`
}
type interfaceType struct {
Mac macType `xml:"mac"`
Model modelType `xml:"model"`
Source bridgeType `xml:"source"`
Type string `xml:"type,attr"`
}
type macType struct {
Address string `xml:"address,attr"`
}
type memoryInfo struct {
Value uint64 `xml:",chardata"`
Unit string `xml:"unit,attr"`
}
type modelType struct {
Type string `xml:"type,attr"`
}
type osInfo struct {
Type osTypeInfo `xml:"type"`
}
type osTypeInfo struct {
Arch string `xml:"arch,attr"`
Machine string `xml:"machine,attr"`
Value string `xml:",chardata"`
}
type serialType struct {
Source serialSourceType `xml:"source"`
Type string `xml:"type,attr"`
}
type serialSourceType struct {
Path string `xml:"path,attr"`
}
type sourceType struct {
File string `xml:"file,attr"`
}
type targetType struct {
Device string `xml:"dev,attr"`
Bus string `xml:"bus,attr"`
}
type vCpuInfo struct {
Num uint `xml:",chardata"`
Placement string `xml:"placement,attr"`
}
type virshInfoType struct {
XMLName xml.Name `xml:"domain"`
Cpu cpuType `xml:"cpu"`
Devices devicesInfo `xml:"devices"`
Memory memoryInfo `xml:"memory"`
Name string `xml:"name"`
Os osInfo `xml:"os"`
Type string `xml:"type,attr"`
VCpu vCpuInfo `xml:"vcpu"`
}
type volumeType struct {
Device string `xml:"device,attr"`
Driver driverType `xml:"driver"`
Source sourceType `xml:"source"`
Target targetType `xml:"target"`
Type string `xml:"type,attr"`
}
func importVirshVmSubcommand(args []string, logger log.DebugLogger) error {
macAddr := args[0]
domainName := args[1]
args = args[2:]
if len(args)%2 != 0 {
return fmt.Errorf("missing IP address for MAC: %s", args[len(args)-1])
}
sAddrs := make([]proto.Address, 0, len(args)/2)
for index := 0; index < len(args); index += 2 {
ipAddr := args[index+1]
ipList, err := net.LookupIP(ipAddr)
if err != nil {
return err
}
if len(ipList) != 1 {
return fmt.Errorf("number of IPs for %s: %d != 1",
ipAddr, len(ipList))
}
sAddrs = append(sAddrs, proto.Address{
IpAddress: ipList[0],
MacAddress: args[index],
})
}
if err := importVirshVm(macAddr, domainName, sAddrs, logger); err != nil {
return fmt.Errorf("error importing VM: %s", err)
}
return nil
}
func ensureDomainIsStopped(domainName string) error {
state, err := getDomainState(domainName)
if err != nil {
return err
}
if state == "shut off" {
return nil
}
if state != "running" {
return fmt.Errorf("domain is in unsupported state \"%s\"", state)
}
response, err := askForInputChoice("Cannot import running VM",
[]string{"shutdown", "quit"})
if err != nil {
return err
}
if response == "quit" {
return fmt.Errorf("domain must be shut off but is \"%s\"", state)
}
err = exec.Command("virsh", []string{"shutdown", domainName}...).Run()
if err != nil {
return fmt.Errorf("error shutting down VM: %s", err)
}
for ; ; time.Sleep(time.Second) {
state, err := getDomainState(domainName)
if err != nil {
if strings.Contains(err.Error(), "Domain not found") {
return nil
}
return err
}
if state == "shut off" {
return nil
}
}
}
func getDomainState(domainName string) (string, error) {
cmd := exec.Command("virsh", []string{"domstate", domainName}...)
stdout, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("error getting VM status: %s",
err.(*exec.ExitError).Stderr)
}
return strings.TrimSpace(string(stdout)), nil
}
func importVirshVm(macAddr, domainName string, sAddrs []proto.Address,
logger log.DebugLogger) error {
ipList, err := net.LookupIP(domainName)
if err != nil {
return err
}
if len(ipList) != 1 {
return fmt.Errorf("number of IPs %d != 1", len(ipList))
}
tags := vmTags.Copy()
if _, ok := tags["Name"]; !ok {
tags["Name"] = domainName
}
request := proto.ImportLocalVmRequest{VmInfo: proto.VmInfo{
ConsoleType: consoleType,
DisableVirtIO: *disableVirtIO,
Hostname: domainName,
OwnerGroups: ownerGroups,
OwnerUsers: ownerUsers,
Tags: tags,
}}
hypervisor := fmt.Sprintf(":%d", *hypervisorPortNum)
client, err := srpc.DialHTTP("tcp", hypervisor, 0)
if err != nil {
return err
}
defer client.Close()
verificationCookie, err := readRootCookie(client, logger)
if err != nil {
return err
}
directories, err := listVolumeDirectories(client)
if err != nil {
return err
}
volumeRoots := make(map[string]string, len(directories))
for _, dirname := range directories {
volumeRoots[filepath.Dir(dirname)] = dirname
}
cmd := exec.Command("virsh",
[]string{"dumpxml", "--inactive", domainName}...)
stdout, err := cmd.Output()
if err != nil {
return fmt.Errorf("error getting XML data: %s", err)
}
var virshInfo virshInfoType
if err := xml.Unmarshal(stdout, &virshInfo); err != nil {
return err
}
json.WriteWithIndent(os.Stdout, " ", virshInfo)
if numIf := len(virshInfo.Devices.Interfaces); numIf != len(sAddrs)+1 {
return fmt.Errorf("number of interfaces %d != %d",
numIf, len(sAddrs)+1)
}
if macAddr != virshInfo.Devices.Interfaces[0].Mac.Address {
return fmt.Errorf("MAC address specified: %s != virsh data: %s",
macAddr, virshInfo.Devices.Interfaces[0].Mac.Address)
}
request.VmInfo.Address = proto.Address{
IpAddress: ipList[0],
MacAddress: virshInfo.Devices.Interfaces[0].Mac.Address,
}
for index, sAddr := range sAddrs {
if sAddr.MacAddress !=
virshInfo.Devices.Interfaces[index+1].Mac.Address {
return fmt.Errorf("MAC address specified: %s != virsh data: %s",
sAddr.MacAddress,
virshInfo.Devices.Interfaces[index+1].Mac.Address)
}
request.SecondaryAddresses = append(request.SecondaryAddresses, sAddr)
}
switch virshInfo.Memory.Unit {
case "KiB":
request.VmInfo.MemoryInMiB = virshInfo.Memory.Value >> 10
case "MiB":
request.VmInfo.MemoryInMiB = virshInfo.Memory.Value
case "GiB":
request.VmInfo.MemoryInMiB = virshInfo.Memory.Value << 10
default:
return fmt.Errorf("unknown memory unit: %s", virshInfo.Memory.Unit)
}
request.VmInfo.MilliCPUs = virshInfo.VCpu.Num * 1000
myPidStr := strconv.Itoa(os.Getpid())
if err := ensureDomainIsStopped(domainName); err != nil {
return err
}
logger.Debugln(0, "finding volumes")
for index, inputVolume := range virshInfo.Devices.Volumes {
if inputVolume.Device != "disk" {
continue
}
var volumeFormat proto.VolumeFormat
err := volumeFormat.UnmarshalText([]byte(inputVolume.Driver.Type))
if err != nil {
return err
}
inputFilename := inputVolume.Source.File
var volumeRoot string
for dirname := filepath.Dir(inputFilename); ; {
if vr, ok := volumeRoots[dirname]; ok {
volumeRoot = vr
break
}
if dirname == "/" {
break
}
dirname = filepath.Dir(dirname)
}
if volumeRoot == "" {
return fmt.Errorf("no Hypervisor directory for: %s", inputFilename)
}
outputDirname := filepath.Join(volumeRoot, "import", myPidStr)
if err := os.MkdirAll(outputDirname, dirPerms); err != nil {
return err
}
defer os.RemoveAll(outputDirname)
outputFilename := filepath.Join(outputDirname,
fmt.Sprintf("volume-%d", index))
if err := os.Link(inputFilename, outputFilename); err != nil {
return err
}
request.VolumeFilenames = append(request.VolumeFilenames,
outputFilename)
request.VmInfo.Volumes = append(request.VmInfo.Volumes,
proto.Volume{Format: volumeFormat})
}
json.WriteWithIndent(os.Stdout, " ", request)
request.VerificationCookie = verificationCookie
var reply proto.GetVmInfoResponse
logger.Debugln(0, "issuing import RPC")
err = client.RequestReply("Hypervisor.ImportLocalVm", request, &reply)
if err != nil {
return fmt.Errorf("Hypervisor.ImportLocalVm RPC failed: %s", err)
}
if err := errors.New(reply.Error); err != nil {
return fmt.Errorf("Hypervisor failed to import: %s", err)
}
logger.Debugln(0, "imported VM")
for _, dirname := range directories {
os.RemoveAll(filepath.Join(dirname, "import", myPidStr))
}
if err := maybeWatchVm(client, hypervisor, ipList[0], logger); err != nil {
return err
}
if err := askForCommitDecision(client, ipList[0]); err != nil {
if err == errorCommitAbandoned {
response, _ := askForInputChoice(
"Do you want to restart the old VM", []string{"y", "n"})
if response != "y" {
return err
}
cmd = exec.Command("virsh", "start", domainName)
if output, err := cmd.CombinedOutput(); err != nil {
logger.Println(string(output))
return err
}
}
return err
}
defer virshInfo.deleteVolumes()
cmd = exec.Command("virsh",
[]string{"undefine", "--managed-save", "--snapshots-metadata",
"--remove-all-storage", domainName}...)
if output, err := cmd.CombinedOutput(); err != nil {
logger.Println(string(output))
return fmt.Errorf("error destroying old VM: %s", err)
}
return nil
}
func (virshInfo virshInfoType) deleteVolumes() {
for _, inputVolume := range virshInfo.Devices.Volumes {
if inputVolume.Device != "disk" {
continue
}
os.Remove(inputVolume.Source.File)
}
}