-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
731 lines (607 loc) · 17.9 KB
/
client.go
File metadata and controls
731 lines (607 loc) · 17.9 KB
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
package vcon
import (
"context"
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
// Version is the version of the application and API
const Version = "0.7.0"
// PowerState describes whether a VM is on, off, or suspended
type PowerState string
const (
// PoweredOff indicates that the VM is turned off
PoweredOff PowerState = "powered_off"
// PoweredOn indicates that the VM is running
PoweredOn PowerState = "powered_on"
// Suspended indicates that the VM is on but not running
Suspended PowerState = "suspended"
// Unknown indicates that the power state was not determined
Unknown PowerState = "unknown"
)
// Client represents a connection to vSphere
type Client struct {
Client *govmomi.Client
Finder *find.Finder
datacenter *object.Datacenter
datastore *object.Datastore
timeout time.Duration
Verbose bool
}
// NewClient creates a connection to a vSphere instance
func NewClient(url, username, password, datacenter, datastore string, timeout int) (*Client, error) {
connectionURL, err := buildConnectionString(url, username, password)
if err != nil {
return nil, err
}
c := &Client{
timeout: time.Duration(timeout) * time.Second,
}
err = func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
// Connect and log in to ESX or vCenter
c.Client, err = govmomi.NewClient(ctx, connectionURL, true)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "Failed to connect to vSphere at '%s' with user '%s'", url, username)
}
c.Finder = find.NewFinder(c.Client.Client, false)
c.datacenter, err = c.Finder.Datacenter(ctx, datacenter)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "Failed to find data center with name '%s'", datacenter)
}
c.Finder.SetDatacenter(c.datacenter)
c.datastore, err = c.Finder.Datastore(ctx, datastore)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "Failed to find data store with name '%s'", datastore)
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return nil, fmt.Errorf("Timeout while attempting to establish connection to vSphere")
default:
// unknown error
return nil, errors.Wrap(err, "Got error while attempting to establish connection to vSphere")
}
}
return c, nil
}
// AssignNote adds a note to the VM, or overwrites the notes entirely
func (c *Client) AssignNote(vm *VirtualMachine, note string, overwrite bool) error {
if c.Verbose {
fmt.Printf("Assigning note to VM...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
if !overwrite {
originalNote := vm.MO.Config.Annotation
if len(originalNote) != 0 {
note = fmt.Sprintf("%s\n\n%s", originalNote, note)
}
}
config := types.VirtualMachineConfigSpec{
Annotation: note,
}
task, err := vm.VM.Reconfigure(ctx, config)
_, err = c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "Error while assigning note")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to assign note to VM")
default:
// unknown error
return errors.Wrap(err, "Got error while assigning note to VM")
}
}
return nil
}
// Clone clones the specified VM
func (c *Client) Clone(vm *VirtualMachine, name, destination, resourcePool string) (*VirtualMachine, error) {
if c.Verbose {
fmt.Printf("Cloning VM...\n")
}
var newVM *object.VirtualMachine
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
objPool, err := c.Finder.ResourcePoolOrDefault(ctx, resourcePool)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While getting resource pool named '%s'", resourcePool)
}
// makeInventoryPath transforms a path to an inventory path by prepending
inventoryDestination := c.makeInventoryPath(destination)
objFolder, err := c.Finder.Folder(ctx, inventoryDestination)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While getting folder named '%s'", destination)
}
objDsRef := c.datastore.Reference()
objFolderRef := objFolder.Reference()
objPoolRef := objPool.Reference()
config := types.VirtualMachineCloneSpec{
Location: types.VirtualMachineRelocateSpec{
Datastore: &objDsRef,
Folder: &objFolderRef,
Pool: &objPoolRef,
},
Template: false,
}
task, err := vm.VM.Clone(ctx, objFolder, name, config)
res, err := c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "Error while cloning")
}
newVM = object.NewVirtualMachine(c.Client.Client, res.(types.ManagedObjectReference))
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return nil, fmt.Errorf("Timeout while attempting to clone VM")
default:
// unknown error
return nil, errors.Wrap(err, "Got error while cloning a VM")
}
}
result := &VirtualMachine{
Ref: newVM.Reference(),
VM: newVM,
}
return result, nil
}
// Configure will change some of the virtual hardware that the specified VM
// uses
func (c *Client) Configure(vm *VirtualMachine, vmc *VirtualMachineConfiguration) error {
if c.Verbose {
fmt.Printf("Configuring VM...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
cspec := types.VirtualMachineConfigSpec{}
reconfigure := false
if vmc.CPUs != nil {
cspec.NumCPUs = int32(*vmc.CPUs)
reconfigure = true
}
if vmc.Memory != nil {
cspec.MemoryMB = int64(*vmc.Memory)
reconfigure = true
}
if reconfigure == true {
task, err := vm.VM.Reconfigure(ctx, cspec)
_, err = c.finishTask(ctx, task, err)
if err = c.checkErr(ctx, err); err != nil {
return err
}
}
if vmc.Network != nil {
devices, err := vm.VM.Device(ctx)
if err = c.checkErr(ctx, err); err != nil {
return err
}
dest := []mo.Network{}
pc := property.DefaultCollector(c.Client.Client)
err = pc.Retrieve(ctx, vm.MO.Network, []string{"name"}, &dest)
if err = c.checkErr(ctx, err); err != nil {
return err
}
network := dest[0]
if network.Name == *vmc.Network {
// There's nothing to change; exit early.
return nil
}
backing := &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: network.Name,
},
}
matchingDevices := devices.SelectByBackingInfo(backing)
requestedNetwork, err := c.Finder.Network(ctx, *vmc.Network)
if err = c.checkErr(ctx, err); err != nil {
return err
}
if requestedNetwork == nil {
return fmt.Errorf("Failed to find requested network")
}
requestedBacking, err := requestedNetwork.EthernetCardBackingInfo(ctx)
if err = c.checkErr(ctx, err); err != nil {
return err
}
matchingDevices.Select(func(device types.BaseVirtualDevice) bool {
device.GetVirtualDevice().Backing = requestedBacking
err = vm.VM.EditDevice(ctx, device)
if err = c.checkErr(ctx, err); err != nil {
// Unclear what to do here; we will continue looping regardless.
}
// We are not collecting the results, so return false
return false
})
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to reconfigure VM")
default:
// unknown error
return errors.Wrap(err, "Got error while reconfiguring a VM")
}
}
return nil
}
// Destroy will remove a VM from vSphere
func (c *Client) Destroy(vm *VirtualMachine) error {
if c.Verbose {
fmt.Printf("Destroying VM...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
powerState, err := vm.VM.PowerState(ctx)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While getting getting power state")
}
if powerState != types.VirtualMachinePowerStatePoweredOff {
return fmt.Errorf("Cannot destroy a Vm that is running")
}
task, err := vm.VM.Destroy(ctx)
_, err = c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "While destroying VM")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to destroy VM")
default:
// unknown error
return errors.Wrap(err, "Got error while destroy a VM")
}
}
return nil
}
// EnsureOff makes certain that the VM is off (not on or suspended)
func (c *Client) EnsureOff(vm *VirtualMachine) error {
if c.Verbose {
fmt.Printf("Ensuring off power state...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
vmps, err := vm.VM.PowerState(ctx)
if err != nil {
return errors.Wrapf(err, "While checking current power state")
}
if vmps == types.VirtualMachinePowerStatePoweredOff {
return nil
}
task, err := vm.VM.PowerOff(ctx)
_, err = c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "While powering off")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to power off VM")
default:
// unknown error
return errors.Wrap(err, "Got error while power off VM")
}
}
return nil
}
// EnsureOn makes certain that the VM is on
func (c *Client) EnsureOn(vm *VirtualMachine) error {
if c.Verbose {
fmt.Printf("Ensuring on power state...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
vmps, err := vm.VM.PowerState(ctx)
if err != nil {
return errors.Wrapf(err, "While checking current power state")
}
if vmps == types.VirtualMachinePowerStatePoweredOn {
return nil
}
task, err := vm.VM.PowerOn(ctx)
_, err = c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "While powering on")
}
_, err = vm.VM.WaitForIP(ctx)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While waiting for IP address")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to power on VM")
default:
// unknown error
return errors.Wrap(err, "Got error while power on VM")
}
}
return nil
}
// GetPowerState returns the current power state of the provided VM
func (c *Client) GetPowerState(vm *VirtualMachine) (PowerState, error) {
ps := Unknown
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
s, err := vm.VM.PowerState(ctx)
if err = c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While getting getting power state")
}
switch s {
case types.VirtualMachinePowerStatePoweredOff:
ps = PoweredOff
case types.VirtualMachinePowerStatePoweredOn:
ps = PoweredOn
case types.VirtualMachinePowerStateSuspended:
ps = Suspended
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return ps, fmt.Errorf("Timeout while getting power state of VM")
default:
// unknown error
return ps, errors.Wrapf(err, "Got error while getting power state of VM")
}
}
return ps, nil
}
// Relocate will move the VM into a new destination folder, and/or change its
// name
func (c *Client) Relocate(vm *VirtualMachine, name, destination string) error {
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
if name != "" {
task, err := vm.VM.Rename(ctx, name)
_, err = c.finishTask(ctx, task, err)
if err = c.checkErr(ctx, err); err != nil {
return err
}
}
if destination != "" {
fmt.Printf("Have destination '%s'\n", destination)
inventoryDestination := c.makeInventoryPath(destination)
fmt.Printf("inventoryDestination: '%s'\n", inventoryDestination)
objFolder, err := c.Finder.Folder(ctx, inventoryDestination)
if err := c.checkErr(ctx, err); err != nil {
return errors.Wrapf(err, "While getting folder named '%s'", destination)
}
task, err := objFolder.MoveInto(ctx, []types.ManagedObjectReference{vm.Ref})
_, err = c.finishTask(ctx, task, err)
if err = c.checkErr(ctx, err); err != nil {
return err
}
fmt.Printf("Relocate complete\n")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to rename and/or move VM")
default:
// unknown error
return errors.Wrap(err, "Got error while attempting to rename and/or move VM")
}
}
return err
}
func (c *Client) ReportSnapshot(mo *types.ManagedObjectReference) *Snapshot {
s := &Snapshot{
Ref: mo.Reference().Value,
}
return s
}
// ReportVM writes descriptive JSON data to the console
func (c *Client) ReportVM(vm *VirtualMachine) *VirtualMachineInfo {
d := &VirtualMachineInfo{
Configuration: &VirtualMachineConfiguration{},
}
func() {
pc := property.DefaultCollector(c.Client.Client)
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
d.Ref = vm.VM.Reference().Value
powerState, err := vm.VM.PowerState(ctx)
select {
case <-ctx.Done():
return
default:
if err != nil {
return
}
d.IsRunning = powerState != types.VirtualMachinePowerStatePoweredOff
}
d.IPs = []string{}
if d.IsRunning {
macs, err := vm.VM.WaitForNetIP(ctx, true)
select {
case <-ctx.Done():
return
default:
if err != nil {
return
}
for _, addrs := range macs {
d.IPs = append(d.IPs, addrs...)
}
}
}
elements, err := c.Finder.Element(ctx, vm.VM.Reference())
select {
case <-ctx.Done():
return
default:
if err != nil {
return
}
d.Path = c.makePath(elements.Path)
}
if vm.MO == nil {
refs := []types.ManagedObjectReference{vm.VM.Reference()}
res := []mo.VirtualMachine{}
err = pc.Retrieve(ctx, refs, []string{"network", "summary"}, &res)
select {
case <-ctx.Done():
return
default:
if err != nil {
return
}
vm.MO = &res[0]
}
}
cpuCount := int(vm.MO.Summary.Config.NumCpu)
memorySize := int(vm.MO.Summary.Config.MemorySizeMB)
d.Configuration.CPUs = &cpuCount
d.Configuration.Memory = &memorySize
dest := []interface{}{}
err = pc.Retrieve(ctx, vm.MO.Network, []string{"name"}, &dest)
err = c.checkErr(ctx, err)
if err != nil {
return
}
network := dest[0].(mo.Network)
d.Configuration.Network = &network.Name
}()
return d
}
// Suspend makes certain that the VM is suspended
func (c *Client) Suspend(vm *VirtualMachine) error {
if c.Verbose {
fmt.Printf("Ensuring on suspended state...\n")
}
err := func() error {
ctx, cancelFn := context.WithTimeout(context.Background(), c.timeout)
defer cancelFn()
vmps, err := vm.VM.PowerState(ctx)
if err != nil {
return errors.Wrapf(err, "While checking current power state")
}
if vmps == types.VirtualMachinePowerStateSuspended {
return nil
}
task, err := vm.VM.Suspend(ctx)
_, err = c.finishTask(ctx, task, err)
if err != nil {
return errors.Wrapf(err, "While suspending")
}
return nil
}()
if err != nil {
switch err := errors.Cause(err).(type) {
case *TimeoutExceededError:
// handle specifically
return fmt.Errorf("Timeout while attempting to suspend VM")
default:
// unknown error
return errors.Wrap(err, "Got error while attempting to suspend VM")
}
}
return err
}
func buildConnectionString(vsphere, name, password string) (*url.URL, error) {
if name == "" || password == "" {
return nil, fmt.Errorf("Missing username or password")
}
connectionString := fmt.Sprintf("https://%s:%s@%s/sdk", name, password, vsphere)
url, err := soap.ParseURL(connectionString)
if err != nil {
return nil, fmt.Errorf("Failed to form URL")
}
return url, nil
}
func (c *Client) checkErr(ctx context.Context, err error) error {
select {
case <-ctx.Done():
return TimeoutExceededError{
timeout: c.timeout,
}
default:
if err != nil {
return err
}
}
return nil
}
func (c *Client) finishTask(ctx context.Context, task *object.Task, err error) (types.AnyType, error) {
if err := c.checkErr(ctx, err); err != nil {
return nil, errors.Wrapf(err, "While suspend")
}
ti, err := task.WaitForResult(ctx, nil)
if err := c.checkErr(ctx, err); err != nil {
return nil, errors.Wrapf(err, "While waiting for task to finish")
}
if ti.State != types.TaskInfoStateSuccess {
return nil, fmt.Errorf(ti.Error.LocalizedMessage)
}
return ti.Result, nil
}
// makeInventoryPath transforms a path to an inventory path by prepending
// the datacenter name and "vm" path segments
func (c *Client) makeInventoryPath(path string) string {
if strings.HasPrefix(path, "/") {
path = path[1:]
}
datacenterName := c.datacenter.Name()
completePath := fmt.Sprintf("/%s/vm/%s", datacenterName, path)
return completePath
}
// makePath transforms an inventory path to a path by removing the datacenter
// name and "vm" path prefix segments
func (c *Client) makePath(inventoryPath string) string {
path := inventoryPath
datacenterNameSegment := fmt.Sprintf("/%s", c.datacenter.Name())
if strings.HasPrefix(path, datacenterNameSegment) {
path = path[len(datacenterNameSegment):]
if strings.HasPrefix(path, "/vm/") {
path = path[4:]
}
}
return path
}