forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_esx5.go
497 lines (412 loc) · 11 KB
/
driver_esx5.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
package iso
import (
"bufio"
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/communicator/ssh"
"github.com/mitchellh/packer/packer"
gossh "golang.org/x/crypto/ssh"
)
// ESX5 driver talks to an ESXi5 hypervisor remotely over SSH to build
// virtual machines. This driver can only manage one machine at a time.
type ESX5Driver struct {
Host string
Port uint
Username string
Password string
Datastore string
CacheDatastore string
CacheDirectory string
comm packer.Communicator
outputDir string
vmId string
}
func (d *ESX5Driver) Clone(dst, src string) error {
return errors.New("Cloning is not supported with the ESX driver.")
}
func (d *ESX5Driver) CompactDisk(diskPathLocal string) error {
return nil
}
func (d *ESX5Driver) CreateDisk(diskPathLocal string, size string, typeId string) error {
diskPath := d.datastorePath(diskPathLocal)
return d.sh("vmkfstools", "-c", size, "-d", typeId, "-a", "lsilogic", diskPath)
}
func (d *ESX5Driver) IsRunning(string) (bool, error) {
state, err := d.run(nil, "vim-cmd", "vmsvc/power.getstate", d.vmId)
if err != nil {
return false, err
}
return strings.Contains(state, "Powered on"), nil
}
func (d *ESX5Driver) ReloadVM() error {
return d.sh("vim-cmd", "vmsvc/reload", d.vmId)
}
func (d *ESX5Driver) Start(vmxPathLocal string, headless bool) error {
for i := 0; i < 20; i++ {
err := d.sh("vim-cmd", "vmsvc/power.on", d.vmId)
if err != nil {
return err
}
time.Sleep((time.Duration(i) * time.Second) + 1)
running, err := d.IsRunning(vmxPathLocal)
if err != nil {
return err
}
if running {
return nil
}
}
return errors.New("Retry limit exceeded")
}
func (d *ESX5Driver) Stop(vmxPathLocal string) error {
return d.sh("vim-cmd", "vmsvc/power.off", d.vmId)
}
func (d *ESX5Driver) Register(vmxPathLocal string) error {
vmxPath := filepath.ToSlash(filepath.Join(d.outputDir, filepath.Base(vmxPathLocal)))
if err := d.upload(vmxPath, vmxPathLocal); err != nil {
return err
}
r, err := d.run(nil, "vim-cmd", "solo/registervm", vmxPath)
if err != nil {
return err
}
d.vmId = strings.TrimRight(r, "\n")
return nil
}
func (d *ESX5Driver) SuppressMessages(vmxPath string) error {
return nil
}
func (d *ESX5Driver) Unregister(vmxPathLocal string) error {
return d.sh("vim-cmd", "vmsvc/unregister", d.vmId)
}
func (d *ESX5Driver) UploadISO(localPath string, checksum string, checksumType string) (string, error) {
finalPath := d.cachePath(localPath)
if err := d.mkdir(filepath.ToSlash(filepath.Dir(finalPath))); err != nil {
return "", err
}
log.Printf("Verifying checksum of %s", finalPath)
if d.verifyChecksum(checksumType, checksum, finalPath) {
log.Println("Initial checksum matched, no upload needed.")
return finalPath, nil
}
if err := d.upload(finalPath, localPath); err != nil {
return "", err
}
return finalPath, nil
}
func (d *ESX5Driver) ToolsIsoPath(string) string {
return ""
}
func (d *ESX5Driver) ToolsInstall() error {
return d.sh("vim-cmd", "vmsvc/tools.install", d.vmId)
}
func (d *ESX5Driver) DhcpLeasesPath(string) string {
return ""
}
func (d *ESX5Driver) Verify() error {
checks := []func() error{
d.connect,
d.checkSystemVersion,
d.checkGuestIPHackEnabled,
}
for _, check := range checks {
if err := check(); err != nil {
return err
}
}
return nil
}
func (d *ESX5Driver) HostIP() (string, error) {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", d.Host, d.Port))
defer conn.Close()
if err != nil {
return "", err
}
host, _, err := net.SplitHostPort(conn.LocalAddr().String())
return host, err
}
func (d *ESX5Driver) VNCAddress(portMin, portMax uint) (string, uint, error) {
var vncPort uint
//Process ports ESXi is listening on to determine which are available
//This process does best effort to detect ports that are unavailable,
//it will ignore any ports listened to by only localhost
r, err := d.esxcli("network", "ip", "connection", "list")
if err != nil {
err = fmt.Errorf("Could not retrieve network information for ESXi: %v", err)
return "", 0, err
}
listenPorts := make(map[string]bool)
for record, err := r.read(); record != nil && err == nil; record, err = r.read() {
if record["State"] == "LISTEN" {
splitAddress := strings.Split(record["LocalAddress"], ":")
if splitAddress[0] != "127.0.0.1" {
port := splitAddress[len(splitAddress)-1]
log.Printf("ESXi listening on address %s, port %s unavailable for VNC", record["LocalAddress"], port)
listenPorts[port] = true
}
}
}
for port := portMin; port <= portMax; port++ {
if _, ok := listenPorts[fmt.Sprintf("%d", port)]; ok {
log.Printf("Port %d in use", port)
continue
}
address := fmt.Sprintf("%s:%d", d.Host, port)
log.Printf("Trying address: %s...", address)
l, err := net.DialTimeout("tcp", address, 1*time.Second)
if err != nil {
if e, ok := err.(*net.OpError); ok {
if e.Timeout() {
log.Printf("Timeout connecting to: %s (check firewall rules)", address)
} else {
vncPort = port
break
}
}
} else {
defer l.Close()
}
}
if vncPort == 0 {
err := fmt.Errorf("Unable to find available VNC port between %d and %d",
portMin, portMax)
return d.Host, vncPort, err
}
return d.Host, vncPort, nil
}
func (d *ESX5Driver) CommHost(state multistep.StateBag) (string, error) {
config := state.Get("config").(*Config)
if address, ok := state.GetOk("vm_address"); ok {
return address.(string), nil
}
r, err := d.esxcli("network", "vm", "list")
if err != nil {
return "", err
}
record, err := r.find("Name", config.VMName)
if err != nil {
return "", err
}
wid := record["WorldID"]
if wid == "" {
return "", errors.New("VM WorldID not found")
}
r, err = d.esxcli("network", "vm", "port", "list", "-w", wid)
if err != nil {
return "", err
}
record, err = r.read()
if err != nil {
return "", err
}
if record["IPAddress"] == "0.0.0.0" {
return "", errors.New("VM network port found, but no IP address")
}
address := record["IPAddress"]
state.Put("vm_address", address)
return address, nil
}
//-------------------------------------------------------------------
// OutputDir implementation
//-------------------------------------------------------------------
func (d *ESX5Driver) DirExists() (bool, error) {
err := d.sh("test", "-e", d.outputDir)
return err == nil, nil
}
func (d *ESX5Driver) ListFiles() ([]string, error) {
stdout, err := d.ssh("ls -1p "+d.outputDir, nil)
if err != nil {
return nil, err
}
files := make([]string, 0, 10)
reader := bufio.NewReader(stdout)
for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
if line[len(line)-1] == '/' {
continue
}
files = append(files, filepath.ToSlash(filepath.Join(d.outputDir, string(line))))
}
return files, nil
}
func (d *ESX5Driver) MkdirAll() error {
return d.mkdir(d.outputDir)
}
func (d *ESX5Driver) Remove(path string) error {
return d.sh("rm", path)
}
func (d *ESX5Driver) RemoveAll() error {
return d.sh("rm", "-rf", d.outputDir)
}
func (d *ESX5Driver) SetOutputDir(path string) {
d.outputDir = d.datastorePath(path)
}
func (d *ESX5Driver) String() string {
return d.outputDir
}
func (d *ESX5Driver) datastorePath(path string) string {
dirPath := filepath.Dir(path)
return filepath.ToSlash(filepath.Join("/vmfs/volumes", d.Datastore, dirPath, filepath.Base(path)))
}
func (d *ESX5Driver) cachePath(path string) string {
return filepath.ToSlash(filepath.Join("/vmfs/volumes", d.CacheDatastore, d.CacheDirectory, filepath.Base(path)))
}
func (d *ESX5Driver) connect() error {
address := fmt.Sprintf("%s:%d", d.Host, d.Port)
auth := []gossh.AuthMethod{
gossh.Password(d.Password),
gossh.KeyboardInteractive(
ssh.PasswordKeyboardInteractive(d.Password)),
}
// TODO(dougm) KeyPath support
sshConfig := &ssh.Config{
Connection: ssh.ConnectFunc("tcp", address),
SSHConfig: &gossh.ClientConfig{
User: d.Username,
Auth: auth,
},
}
comm, err := ssh.New(address, sshConfig)
if err != nil {
return err
}
d.comm = comm
return nil
}
func (d *ESX5Driver) checkSystemVersion() error {
r, err := d.esxcli("system", "version", "get")
if err != nil {
return err
}
record, err := r.read()
if err != nil {
return err
}
log.Printf("Connected to %s %s %s", record["Product"],
record["Version"], record["Build"])
return nil
}
func (d *ESX5Driver) checkGuestIPHackEnabled() error {
r, err := d.esxcli("system", "settings", "advanced", "list", "-o", "/Net/GuestIPHack")
if err != nil {
return err
}
record, err := r.read()
if err != nil {
return err
}
if record["IntValue"] != "1" {
return errors.New(
"GuestIPHack is required, enable by running this on the ESX machine:\n" +
"esxcli system settings advanced set -o /Net/GuestIPHack -i 1")
}
return nil
}
func (d *ESX5Driver) mkdir(path string) error {
return d.sh("mkdir", "-p", path)
}
func (d *ESX5Driver) upload(dst, src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
return d.comm.Upload(dst, f, nil)
}
func (d *ESX5Driver) verifyChecksum(ctype string, hash string, file string) bool {
if ctype == "none" {
if err := d.sh("stat", file); err != nil {
return false
}
} else {
stdin := bytes.NewBufferString(fmt.Sprintf("%s %s", hash, file))
_, err := d.run(stdin, fmt.Sprintf("%ssum", ctype), "-c")
if err != nil {
return false
}
}
return true
}
func (d *ESX5Driver) ssh(command string, stdin io.Reader) (*bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: command,
Stdout: &stdout,
Stderr: &stderr,
Stdin: stdin,
}
err := d.comm.Start(cmd)
if err != nil {
return nil, err
}
cmd.Wait()
if cmd.ExitStatus != 0 {
err = fmt.Errorf("'%s'\n\nStdout: %s\n\nStderr: %s",
cmd.Command, stdout.String(), stderr.String())
return nil, err
}
return &stdout, nil
}
func (d *ESX5Driver) run(stdin io.Reader, args ...string) (string, error) {
stdout, err := d.ssh(strings.Join(args, " "), stdin)
if err != nil {
return "", err
}
return stdout.String(), nil
}
func (d *ESX5Driver) sh(args ...string) error {
_, err := d.run(nil, args...)
return err
}
func (d *ESX5Driver) esxcli(args ...string) (*esxcliReader, error) {
stdout, err := d.ssh("esxcli --formatter csv "+strings.Join(args, " "), nil)
if err != nil {
return nil, err
}
r := csv.NewReader(bytes.NewReader(stdout.Bytes()))
r.TrailingComma = true
header, err := r.Read()
if err != nil {
return nil, err
}
return &esxcliReader{r, header}, nil
}
type esxcliReader struct {
cr *csv.Reader
header []string
}
func (r *esxcliReader) read() (map[string]string, error) {
fields, err := r.cr.Read()
if err != nil {
return nil, err
}
record := map[string]string{}
for i, v := range fields {
record[r.header[i]] = v
}
return record, nil
}
func (r *esxcliReader) find(key, val string) (map[string]string, error) {
for {
record, err := r.read()
if err != nil {
return nil, err
}
if record[key] == val {
return record, nil
}
}
}