/
step_create_domain.go
124 lines (109 loc) · 2.57 KB
/
step_create_domain.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
package libvirt
import (
"bytes"
"fmt"
"html/template"
"net"
"net/url"
"strings"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"github.com/vtolstov/libvirt-go"
)
type stepCreateDomain struct{}
func (s *stepCreateDomain) Run(state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
ui := state.Get("ui").(packer.Ui)
sshHostPort := state.Get("sshHostPort").(uint)
lv, err := libvirt.NewVirConnection(config.LibvirtUrl)
if err != nil {
err := fmt.Errorf("Error connecting to libvirt: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
defer lv.CloseConnection()
if lvd, err := lv.LookupDomainByName(config.VMName); err == nil {
err = lvd.Destroy()
if err != nil {
err := fmt.Errorf("Error domain already running")
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
domainXml := bytes.NewBuffer(nil)
tmpl, err := template.New("domain").Parse(config.DomainXml)
if err != nil {
err := fmt.Errorf("Error creating domain template: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
u, err := url.Parse(config.ISOUrl)
if err != nil {
err := fmt.Errorf("Error parse iso_url: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
var h string
var p string
if strings.Index(u.Host, ":") == -1 {
h = u.Host
} else {
h, p, _ = net.SplitHostPort(u.Host)
}
if p == "" {
switch u.Scheme {
case "https":
p = "443"
case "http":
p = "80"
}
}
data := struct {
VMName string
DiskName string
DiskType string
PoolName string
MemorySize uint
ISOUrlProto string
ISOUrlPath string
ISOUrlHost string
ISOUrlPort string
SSHHostPort string
SSHGuestport string
}{
config.VMName,
config.DiskName,
"raw",
config.PoolName,
config.MemorySize,
u.Scheme,
u.Path,
h,
p,
sshHostPort,
config.Comm.Port(),
}
err = tmpl.Execute(domainXml, data)
if err != nil {
err := fmt.Errorf("Error running domain template: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// ui.Say(fmt.Sprintf("domain config: %s", string(domainXml.Bytes())))
lvd, err := lv.DomainDefineXML(string(domainXml.Bytes()))
if err != nil {
err := fmt.Errorf("Error defining domain: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
defer lvd.Free()
return multistep.ActionContinue
}
func (s *stepCreateDomain) Cleanup(state multistep.StateBag) {
}