-
Notifications
You must be signed in to change notification settings - Fork 3
/
vm.go
682 lines (587 loc) · 20 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
// Copyright (c) 2019 The virnsnap authors. See file "AUTHORS".
// Licensed under the MIT License. You have obtained a copy of the License at
// the "LICENSE" file in this repository.
// Package virt implements high-level functions for handling virtual machines
// (VMS) that use the more low-level libvirt functions internally.
package virt
import (
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/joroec/virsnap/pkg/instrument/log"
"github.com/libvirt/libvirt-go"
libvirtxml "github.com/libvirt/libvirt-go-xml"
)
// -----------------------------------------------------------------------------
// VM is a simple wrapper type for a libvirt.Domain with its corresponding
// XML descriptor unmarshalled as data type.
type VM struct {
Instance libvirt.Domain
Descriptor libvirtxml.Domain
Logger log.Logger
}
// Free ist just a convenience function to free the associated libvirt.Domain
// instance.
func (vm *VM) Free() error {
return vm.Instance.Free()
}
// Transition implements state transitions of the given VM. This method can
// be seen as implementation of an finite state machine (FSM). "to" specifies
// the target state of the VM. "forceShutdown" determines whether the VM should
// be forced to shutoff (plug the cable) after several tries of graceful
// shutdown before returning an error. "timeout" specifies the timeout in
// minutes a VM is allowed to take before forcing shutdown.
func (vm *VM) Transition(to libvirt.DomainState, forceShutdown bool,
timeout int) (libvirt.DomainState, error) {
// check argument validity
if to != libvirt.DOMAIN_RUNNING && to != libvirt.DOMAIN_SHUTOFF &&
to != libvirt.DOMAIN_PMSUSPENDED && to != libvirt.DOMAIN_PAUSED {
err := fmt.Errorf("unable to start transition of VM '%s' to state "+
"'%s': target state not allowed", vm.Descriptor.Name,
GetStateString(to))
return libvirt.DOMAIN_NOSTATE, err
}
// get current state of virtual machine
state, _, err := vm.Instance.GetState()
if err != nil {
err = fmt.Errorf("unable to retrieve state of VM '%s': %s ",
vm.Descriptor.Name,
err,
)
return libvirt.DOMAIN_NOSTATE, err
}
// outer switch: current state of VM, inner switch: target state of VM
switch state {
// HANDLE RUNNING VM ---------------------------------------------------------
case libvirt.DOMAIN_RUNNING:
switch to {
case libvirt.DOMAIN_RUNNING:
vm.Logger.Debugf("Domain '%s' is already running.", vm.Descriptor.Name)
return state, nil
case libvirt.DOMAIN_PAUSED:
vm.Logger.Debugf("Suspending domain '%s'.", vm.Descriptor.Name)
err = vm.Instance.Suspend()
if err != nil {
err = fmt.Errorf("unable to suspend VM '%s': %s",
vm.Descriptor.Name,
err,
)
return state, err
}
return state, nil
case libvirt.DOMAIN_PMSUSPENDED:
vm.Logger.Debugf("PMSuspending domain '%s'.", vm.Descriptor.Name)
err = vm.Instance.PMSuspendForDuration(libvirt.NODE_SUSPEND_TARGET_MEM,
0, 0)
if err != nil {
err = fmt.Errorf("unable to pmsuspend VM '%s': %s",
vm.Descriptor.Name,
err,
)
return state, err
}
return state, nil
case libvirt.DOMAIN_SHUTOFF:
vm.Logger.Debugf("Trying to shutdown domain '%s' gracefully.",
vm.Descriptor.Name)
roundSeconds := 0.33 * float64(timeout*60)
newState := libvirt.DOMAIN_RUNNING
// if the virtual machine seems to not react to the first shutdown
// request, repeatedly send further requests to gracefully shutdown
for i := 0; i < 3; i++ {
before := time.Now()
vm.Logger.Debugf("Sending shutdown request to VM '%s'.",
vm.Descriptor.Name)
err = vm.Instance.Shutdown() // returns instantly
if err != nil {
// we need to cast to specific libvirt error, since the VM might
// be in a shutoff state since last check. If this is the case, we
// do not want to return an error!
lverr, ok := err.(libvirt.Error)
if ok && (lverr.Code == libvirt.ERR_OPERATION_INVALID ||
strings.Contains(lverr.Message, "domain is not running")) {
vm.Logger.Debugf("VM '%s' was shutdown in the meantime.",
vm.Descriptor.Name)
return libvirt.DOMAIN_RUNNING, nil
}
err = fmt.Errorf("unable to initiate the shutdown request for VM '%s': %s",
vm.Descriptor.Name,
err,
)
return libvirt.DOMAIN_RUNNING, err
}
vm.Logger.Debugf("Waiting for VM '%s' to shutdown.",
vm.Descriptor.Name)
for true {
time.Sleep(5 * time.Second)
newState, _, err = vm.Instance.GetState()
if err != nil {
err = fmt.Errorf("unable to re-retrieve state of VM "+
"'%s': %s", vm.Descriptor.Name, err)
vm.Logger.Warnf("%s, Retrying...", err)
}
if newState == libvirt.DOMAIN_SHUTOFF {
return libvirt.DOMAIN_RUNNING, nil
}
// if we waited longer since 33% of the timeout, try sending the
// shutdown request again
after := time.Now()
duration := after.Sub(before) // int64 nanosecods
maxRoundDuration := time.Duration(roundSeconds) * time.Second
if duration > maxRoundDuration {
vm.Logger.Debugf("Beginning next graceful shutdown round for VM '%s'",
vm.Descriptor.Name,
)
break
}
}
}
// could not shutdown the VM gracefully, force?
if forceShutdown {
vm.Logger.Debugf("Destroying VM '%s' since it could not be "+
"shutdown gracefully.",
vm.Descriptor.Name,
)
err = vm.Instance.Destroy()
if err != nil {
err = fmt.Errorf("unable to destroy VM '%s': %s",
vm.Descriptor.Name,
err,
)
return libvirt.DOMAIN_RUNNING, err
}
return libvirt.DOMAIN_RUNNING, nil
}
err = fmt.Errorf("unable to shutdown VM '%s', state is now: '%s'",
vm.Descriptor.Name,
GetStateString(newState),
)
return libvirt.DOMAIN_RUNNING, err
default:
err = fmt.Errorf("unable to start transition of VM '%s' to state "+
"'%s': target state not allowed",
vm.Descriptor.Name,
GetStateString(to),
)
return state, err
}
// HANDLE CRASHED VM ---------------------------------------------------------
case libvirt.DOMAIN_CRASHED:
// treat a crashed like a VM that is shutoff
fallthrough
// HANDLE SHUTOFF VM ---------------------------------------------------------
case libvirt.DOMAIN_SHUTOFF:
// we only need three cases here: Either the VM is already shutdown or
// the VM should be started. In any other case, the VM needs to be
// booted up, before the follow-up transition can occur.
if to == libvirt.DOMAIN_SHUTOFF {
vm.Logger.Debugf("Domain '%s' is already shutoff.", vm.Descriptor.Name)
return state, nil
} else if to == libvirt.DOMAIN_RUNNING {
err := vm.Instance.Create()
if err != nil {
vm.Logger.Errorf("unable to boot VM '%s': %s",
vm.Descriptor.Name,
err,
)
return state, err
}
return state, nil
} else {
// First Transition: Wait for the VM to be running
prev, err := vm.Transition(libvirt.DOMAIN_RUNNING, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != state {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// Second Transition: Transition to the acutal target state
prev, err = vm.Transition(to, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != libvirt.DOMAIN_RUNNING {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
return state, nil
}
// HANDLE SHUTDOWNING VM -----------------------------------------------------
case libvirt.DOMAIN_SHUTDOWN:
// we only need two cases here: Wait for the VM to shutdown and anything
// else because in any other case than waiting for the VM to shutdown we
// would need wait nevertheless and then execute the follow-up transition.
if to == libvirt.DOMAIN_SHUTOFF {
vm.Logger.Debugf("Waiting for VM '%s' to shutdown.",
vm.Descriptor.Name)
before := time.Now()
for true {
time.Sleep(5 * time.Second)
newState, _, err := vm.Instance.GetState()
if err != nil {
err = fmt.Errorf("unable to re-retrieve state of VM "+
"'%s': %s", vm.Descriptor.Name, err)
vm.Logger.Warnf("%s, Retrying...", err)
}
if newState == libvirt.DOMAIN_SHUTOFF {
// returning shutoff, since this will be the future state of the VM.
// A caller should assume this as previous state, since the VM would
// have entered the shutoff state without any further intervention.
return libvirt.DOMAIN_SHUTOFF, nil
}
after := time.Now()
duration := after.Sub(before) // int64 nanosecods
if duration > time.Duration(timeout)*time.Minute {
vm.Logger.Debugf("Beginning next graceful shutdown round for VM "+
"'%s'", vm.Descriptor.Name)
break
}
}
// returning shutoff, since this will be the future state of the VM.
// A caller should assume this as previous state, since the VM would
// have entered the shutoff state without any further intervention.
return libvirt.DOMAIN_SHUTOFF, nil
}
// In any other case: First Transition: Wait for the VM to be shutoff
prev, err := vm.Transition(libvirt.DOMAIN_SHUTOFF, forceShutdown, timeout)
if err != nil {
// return shutoff, since the VM reaches this state without any further
// intervention.
return libvirt.DOMAIN_SHUTOFF, err
}
if prev != state && prev != libvirt.DOMAIN_SHUTOFF {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// Second Transition: Transition to the acutal target state
prev, err = vm.Transition(to, forceShutdown, timeout)
if err != nil {
// return shutoff, since the VM reaches this state without any further
// intervention.
return libvirt.DOMAIN_SHUTOFF, err
}
if prev != libvirt.DOMAIN_SHUTOFF {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// return shutoff, since the VM reaches this state without any further
// intervention.
return libvirt.DOMAIN_SHUTOFF, nil
// HANDLE PAUSED VM ----------------------------------------------------------
case libvirt.DOMAIN_PAUSED:
// we only need three cases here: Either the VM is already paused or
// the VM should be woken up. In any other case, the VM needs to be
// woken up, before the follow-up transition can occur.
if to == libvirt.DOMAIN_PAUSED {
vm.Logger.Debugf("Domain '%s' is already paused.", vm.Descriptor.Name)
return state, nil
} else if to == libvirt.DOMAIN_RUNNING {
vm.Logger.Debugf("Resuming domain '%s'.", vm.Descriptor.Name)
err = vm.Instance.Resume()
if err != nil {
err = fmt.Errorf("unable to resume VM '%s': %s",
vm.Descriptor.Name,
err,
)
return state, err
}
return state, nil
} else {
// First Transition: Wait for the VM to be resumed
prev, err := vm.Transition(libvirt.DOMAIN_RUNNING, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != state {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// Second Transition: Transition to the acutal target state
prev, err = vm.Transition(to, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != libvirt.DOMAIN_RUNNING {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
return state, nil
}
// HANDLE PMSUSPENDED VM -----------------------------------------------------
case libvirt.DOMAIN_PMSUSPENDED:
// we only need three cases here: Either the VM is already pmsuspended or
// the VM should be resumed. In any other case, the VM needs to be
// resumed, before the follow-up transition can occur.
if to == libvirt.DOMAIN_PMSUSPENDED {
vm.Logger.Debugf("Domain '%s' is already pmsuspended.", vm.Descriptor.Name)
return state, nil
} else if to == libvirt.DOMAIN_RUNNING {
vm.Logger.Debugf("Wake up domain '%s'.", vm.Descriptor.Name)
err = vm.Instance.PMWakeup(0)
if err != nil {
err = fmt.Errorf("unable to wake up VM '%s': %s",
vm.Descriptor.Name,
err,
)
return state, err
}
return state, nil
} else {
// First Transition: Wait for the VM to be woken up
prev, err := vm.Transition(libvirt.DOMAIN_RUNNING, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != state {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// Second Transition: Transition to the acutal target state
prev, err = vm.Transition(to, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != libvirt.DOMAIN_RUNNING {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
return state, nil
}
// HANDLE BLOCKED VM ---------------------------------------------------------
case libvirt.DOMAIN_BLOCKED:
// TODO: What exactly is a blocked VM? Cannot find any documentation. Tell
// me, if you find some...
// Wait for the VM to not be blocked anymore and then execute the given
// transition.
vm.Logger.Debugf("Waiting vor the VM '%s' to not be blocked anymore.",
vm.Descriptor.Name)
before := time.Now()
for true {
time.Sleep(5 * time.Second)
newState, _, err := vm.Instance.GetState()
if err != nil {
err = fmt.Errorf("unable to re-retrieve state of VM "+
"'%s': %s", vm.Descriptor.Name, err)
vm.Logger.Warnf("%s, Retrying...", err)
}
if newState != libvirt.DOMAIN_BLOCKED {
// Execute Transition to the acutal target state
prev, err := vm.Transition(to, forceShutdown, timeout)
if err != nil {
return state, err
}
if prev != newState {
vm.Logger.Warnf("State of VM '%s' has changed from '%s' to '%s'",
vm.Descriptor.Name,
GetStateString(state),
GetStateString(prev),
)
}
// return running, since this is the future state if the VM is not
// blocked any longer
return libvirt.DOMAIN_RUNNING, nil
}
after := time.Now()
duration := after.Sub(before) // int64 nanosecods
if duration > time.Duration(timeout)*time.Minute {
vm.Logger.Debugf("Beginning next graceful shutdown round for VM "+
"'%s'.", vm.Descriptor.Name)
break
}
}
// return running, since this is the future state if the VM is not
// blocked any longer
err = fmt.Errorf("timeout while waiting for unblock of VM '%s'",
vm.Descriptor.Name,
)
return libvirt.DOMAIN_RUNNING, err
// HANDLE ANY OTHER CASE -----------------------------------------------------
default:
err = fmt.Errorf("illegal state of VM '%s': '%s'", vm.Descriptor.Name,
GetStateString(state),
)
return state, err
}
}
// -----------------------------------------------------------------------------
// ListMatchingVMs is a method that allows to retrieve information about
// virtual machines that can be accessed via libvirt. The first parameter
// specifies the logger to be used to output warnings. The second parameter
// specifies a slice of regular expressions. Only virtual machines whose name
// matches at least one of the regular expressions are returned. The third
// parameter is the libvirt/qemu socket URL to connect to.
// The caller is responsible for calling FreeVMs on the returned slice to free any
// buffer in libvirt. The returned VMs are sorted lexically by name.
func ListMatchingVMs(log log.Logger, regexes []string, socketURL string) ([]VM, error) {
// argument validity checking
exprs := make([]*regexp.Regexp, 0, len(regexes))
for _, arg := range regexes {
regex, err := regexp.Compile(arg)
if err != nil {
err = fmt.Errorf("unable to compile regular expression %s: %s", arg,
err)
return nil, err
}
exprs = append(exprs, regex)
}
if len(exprs) == 0 {
return nil, fmt.Errorf("bo regular expression was specified")
}
// trying to connect to QEMU socket...
conn, err := libvirt.NewConnect(socketURL)
if err != nil {
err = fmt.Errorf("unable to connect to QEMU socket: %s", err)
return nil, err
}
defer conn.Close()
// retrieving all virtual machines
// the parameter for ListAllDomains is a bitmask that is used for filtering
// the results. Since we do not want to restrict the usage to any strict type,
// we use 0 which returns all of the found virtual machines.
instances, err := conn.ListAllDomains(0)
if err != nil {
err = fmt.Errorf("unable to retrieve list of VMs from QEMU: %s",
err)
return nil, err
}
// loop over the virtual machines and check for a match with the given
// regular expressions
matchedVMs := make([]VM, 0, len(instances))
for _, instance := range instances {
// retrieve and unmarshal the descriptor of the VM
xml, err := instance.GetXMLDesc(0)
if err != nil {
err = fmt.Errorf("unable to get XML descriptor of VM: %s", err)
log.Warnf("Skipping VM: %s", err)
continue
}
descriptor := libvirtxml.Domain{}
err = descriptor.Unmarshal(xml)
if err != nil {
err = fmt.Errorf("unable to unmarshal XML descriptor of VM: %s", err)
log.Warnf("Skipping VM: %s", err)
continue
}
// checking for a matching regular expression
found := false
for _, regex := range exprs {
if regex.Find([]byte(descriptor.Name)) != nil {
found = true
break
}
}
if found {
// the caller is responsible for calling domain.Free() on the returned
// domains
matchedVM := VM{
Instance: instance,
Descriptor: descriptor,
Logger: log,
}
matchedVMs = append(matchedVMs, matchedVM)
} else {
// we do not need the instance here anymore
err = instance.Free()
if err != nil {
err = fmt.Errorf("unable to free VM '%s': %s", descriptor.Name, err)
log.Warn(err)
}
}
}
// sort the VMs according to the name increasingly
sorter := VMSorter{
VMs: &matchedVMs,
}
sort.Sort(&sorter)
return matchedVMs, nil
}
// -----------------------------------------------------------------------------
// VMSorter is a sorter for sorting snapshots by name lexically.
type VMSorter struct {
VMs *[]VM
}
func (s *VMSorter) Len() int {
return len(*s.VMs)
}
func (s *VMSorter) Less(i int, j int) bool {
return (*s.VMs)[i].Descriptor.Name < (*s.VMs)[j].Descriptor.Name
}
func (s *VMSorter) Swap(i int, j int) {
(*s.VMs)[i], (*s.VMs)[j] = (*s.VMs)[j], (*s.VMs)[i]
}
// -----------------------------------------------------------------------------
// FreeVMs is a function that takes a slice of VMs and frees any associated
// libvirt.Domain. Usually, this is called after ListMatchingVMs with a
// "defer" statement.
func FreeVMs(log log.Logger, vms []VM) {
for _, vm := range vms {
err := vm.Instance.Free()
if err != nil {
err = fmt.Errorf("unable to free vm %s: %s", vm.Descriptor.Name, err)
log.Warn(err)
}
}
}
// GetCurrentStateString is a helper method that retrieves the current
// state of the VM and returns this state as human readable representation.
func (vm *VM) GetCurrentStateString() (string, error) {
state, _, err := vm.Instance.GetState()
if err != nil {
err = fmt.Errorf("unable to retrieve state of VM '%s': %s",
vm.Descriptor.Name,
err,
)
return GetStateString(libvirt.DOMAIN_NOSTATE), err
}
return GetStateString(state), nil
}
// GetStateString is a helper function that takes a VM state and returns this
// state as human readable representation.
func GetStateString(state libvirt.DomainState) string {
switch state {
case libvirt.DOMAIN_RUNNING:
return "DOMAIN_RUNNING"
case libvirt.DOMAIN_BLOCKED:
return "DOMAIN_BLOCKED"
case libvirt.DOMAIN_PAUSED:
return "DOMAIN_PAUSED"
case libvirt.DOMAIN_SHUTDOWN:
return "DOMAIN_SHUTDOWN"
case libvirt.DOMAIN_CRASHED:
return "DOMAIN_CRASHED"
case libvirt.DOMAIN_PMSUSPENDED:
return "DOMAIN_PMSUSPENDED"
case libvirt.DOMAIN_SHUTOFF:
return "DOMAIN_SHUTOFF"
default:
return "DOMAIN_NOSTATE"
}
}