-
Notifications
You must be signed in to change notification settings - Fork 2
/
destroy.go
71 lines (59 loc) · 1.23 KB
/
destroy.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
package vm
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/libvirt/libvirt-go"
)
// Destroy stops and undefines a domain by name. If force is true, the
// domain is destroyed without prompting for confirmation.
func Destroy(uri, name string, force bool) error {
conn, err := libvirt.NewConnect(uri)
if err != nil {
return err
}
instancesDir, err := getInstancesDir()
if err != nil {
return err
}
dom, err := conn.LookupDomainByName(name)
if err != nil {
return err
}
defer dom.Free()
name, err = dom.GetName()
if err != nil {
return err
}
if !force {
fmt.Printf("Are you sure you wish to destroy %v? (y/N) ", name)
var response string
fmt.Scan(&response)
response = strings.ToLower(strings.TrimSpace(response))
if response != "y" {
return nil
}
}
state, _, err := dom.GetState()
if err != nil {
return err
}
if state == libvirt.DOMAIN_RUNNING {
err = dom.Destroy()
if err != nil {
return err
}
}
UUID, err := dom.GetUUIDString()
if err != nil {
return err
}
os.Remove(filepath.Join(instancesDir, UUID+".qcow2"))
os.RemoveAll(filepath.Join(instancesDir, UUID))
err = dom.UndefineFlags(libvirt.DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)
if err != nil {
return err
}
return nil
}