This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 262
/
Copy pathvsphereTasks.go
473 lines (389 loc) · 14.7 KB
/
vsphereTasks.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
package vsphere // import "github.com/docker/infrakit/pkg/provider/vsphere"
import (
"context"
"errors"
"fmt"
"strings"
"github.com/docker/infrakit/pkg/spi/group"
"github.com/docker/infrakit/pkg/spi/instance"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
func cloneNewInstance(p *plugin, vm *vmInstance, vmSpec instance.Spec) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(p.vCenterInternals.client.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *p.vC.dcName)
if err != nil {
return fmt.Errorf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// Use finder for VM template
vmTemplate, err := f.VirtualMachine(ctx, vm.vmTemplate)
if err != nil {
return err
}
pool := p.vCenterInternals.resourcePool.Reference()
host := p.vCenterInternals.hostSystem.Reference()
ds := p.vCenterInternals.datastore.Reference()
// TODO - Allow modifiable relocateSpec for other DataStores
relocateSpec := types.VirtualMachineRelocateSpec{
Pool: &pool,
Host: &host,
Datastore: &ds,
}
// The only change we make to the Template Spec, is the config sha and group name
spec := types.VirtualMachineConfigSpec{
Annotation: vmSpec.Tags[group.GroupTag] + "\n" + vmSpec.Tags[group.ConfigSHATag] + "\n" + vm.annotation,
}
// Changes can be to spec or relocateSpec
cisp := types.VirtualMachineCloneSpec{
Config: &spec,
Location: relocateSpec,
Template: false,
PowerOn: vm.poweron,
}
vmObj := object.NewVirtualMachine(p.vCenterInternals.client.Client, vmTemplate.Reference())
var vmFolder *object.Folder
// Check that a group has been submitted
if vmSpec.Tags[group.GroupTag] == "" {
vmFolder, err = f.DefaultFolder(ctx)
} else {
groupFolder, err := f.Folder(ctx, vmSpec.Tags[group.GroupTag])
if err != nil {
log.Warn("Issues finding a group folder", "err", err)
groupFolder, err = p.vCenterInternals.dcFolders.VmFolder.CreateFolder(ctx, vmSpec.Tags[group.GroupTag])
if err != nil {
if err.Error() == "ServerFaultCode: The operation is not supported on the object." {
baseFolder, _ := dc.Folders(ctx)
groupFolder = baseFolder.VmFolder
} else {
if err.Error() == "ServerFaultCode: The name '"+vmSpec.Tags[group.GroupTag]+"' already exists." {
return errors.New("A Virtual Machine exists with the same name as the InfraKit group")
}
log.Warn("Issues setting the group folder", "err", err)
}
}
}
vmFolder = groupFolder
}
task, err := vmObj.Clone(ctx, vmFolder, vm.vmName, cisp)
if err != nil {
return errors.New("Creating new VM failed, more detail can be found in vCenter tasks")
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
return fmt.Errorf("Creating new VM failed\n%v", err)
}
if info.Error != nil {
return fmt.Errorf("Clone task finished with error: %s", info.Error)
}
return nil
}
func createNewVMInstance(p *plugin, vm *vmInstance, vmSpec instance.Spec) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(p.vCenterInternals.client.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *p.vC.dcName)
if err != nil {
return fmt.Errorf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
spec := types.VirtualMachineConfigSpec{
Name: vm.vmName,
GuestId: "otherLinux64Guest",
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", p.vCenterInternals.datastore.Name())},
NumCPUs: int32(vm.vCpus),
MemoryMB: int64(vm.mem),
Annotation: vmSpec.Tags[group.GroupTag] + "\n" + vmSpec.Tags[group.ConfigSHATag] + "\n" + vm.annotation,
}
scsi, err := object.SCSIControllerTypes().CreateSCSIController("pvscsi")
if err != nil {
return errors.New("Error creating pvscsi controller as part of new VM")
}
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
Operation: types.VirtualDeviceConfigSpecOperationAdd,
Device: scsi,
})
groupFolder, err := f.Folder(ctx, vmSpec.Tags[group.GroupTag])
if err != nil {
log.Warn("Issues finding a group folder", "err", err)
groupFolder, err = p.vCenterInternals.dcFolders.VmFolder.CreateFolder(ctx, vmSpec.Tags[group.GroupTag])
if err != nil {
if err.Error() == "ServerFaultCode: The operation is not supported on the object." {
baseFolder, _ := dc.Folders(ctx)
groupFolder = baseFolder.VmFolder
} else {
if err.Error() == "ServerFaultCode: The name '"+vmSpec.Tags[group.GroupTag]+"' already exists." {
return errors.New("A Virtual Machine exists with the same name as the InfraKit group")
}
log.Warn("Issues setting the group folder", "err", err)
}
}
}
task, err := groupFolder.CreateVM(ctx, spec, p.vCenterInternals.resourcePool, p.vCenterInternals.hostSystem)
if err != nil {
return errors.New("Creating new VM failed, more detail can be found in vCenter tasks")
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
return fmt.Errorf("Creating new VM failed\n%v", err)
}
// Retrieve the new VM
newVM := object.NewVirtualMachine(p.vCenterInternals.client.Client, info.Result.(types.ManagedObjectReference))
err = addISO(p, *vm, newVM)
if err != nil {
log.Warn(err.Error())
}
if *p.vC.networkName != "" {
err = findNetwork(p.vC, p.vCenterInternals)
if err != nil {
log.Warn(err.Error())
} else {
err = addNIC(newVM, p.vCenterInternals.network)
if err != nil {
log.Warn(err.Error())
}
}
}
if vm.persistentSz > 0 {
err = addVMDK(p, newVM, *vm)
if err != nil {
log.Warn(err.Error())
}
}
if vm.poweron == true {
log.Info("Powering on new Virtual Machine instance")
return setVMPowerOn(true, newVM)
}
return nil
}
func deleteVM(p *plugin, vm string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(p.vCenterInternals.client.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *p.vC.dcName)
if err != nil {
return fmt.Errorf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// Try and find the virtual machine
foundVM, err := f.VirtualMachine(ctx, vm)
if err != nil {
return fmt.Errorf("Error finding Virtual Machine\nClient Error => %v", err)
}
// Attempt to power off the VM regardless of power state
_ = setVMPowerOn(false, foundVM)
// If the Virtual Machine is found then we call Destroy against it.
task, err := foundVM.Destroy(ctx)
if err != nil {
return errors.New("Delete operation has failed, more detail can be found in vCenter tasks")
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return errors.New("Delete Task has failed, more detail can be found in vCenter tasks")
}
return nil
}
func ignoreVM(p *plugin, vm string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(p.vCenterInternals.client.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *p.vC.dcName)
if err != nil {
return fmt.Errorf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// Try and find the virtual machine
foundVM, err := f.VirtualMachine(ctx, vm)
if err != nil {
return fmt.Errorf("Error finding Virtual Machine\nClient Error => %v", err)
}
configSpec := types.VirtualMachineConfigSpec{
Annotation: "Deleted by InfraKit",
}
task, err := foundVM.Reconfigure(ctx, configSpec)
if err != nil {
return errors.New("Delete operation has failed, more detail can be found in vCenter tasks")
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return errors.New("Delete Task has failed, more detail can be found in vCenter tasks")
}
return nil
}
func setVMPowerOn(state bool, vm *object.VirtualMachine) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var task *object.Task
var err error
if state == true {
task, err = vm.PowerOn(ctx)
if err != nil {
return errors.New("Power On operation has failed, more detail can be found in vCenter tasks")
}
} else {
task, err = vm.PowerOff(ctx)
if err != nil {
return errors.New("Power Off operation has failed, more detail can be found in vCenter tasks")
}
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return errors.New("Power On Task has failed, more detail can be found in vCenter tasks")
}
return nil
}
func addNIC(vm *object.VirtualMachine, net object.NetworkReference) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
backing, err := net.EthernetCardBackingInfo(ctx)
if err != nil {
return fmt.Errorf("Unable to determine vCenter network backend\n%v", err)
}
netdev, err := object.EthernetCardTypes().CreateEthernetCard("vmxnet3", backing)
if err != nil {
return fmt.Errorf("Unable to create vmxnet3 network interface\n%v", err)
}
log.Info("Adding VM Networking")
var add []types.BaseVirtualDevice
add = append(add, netdev)
if vm.AddDevice(ctx, add...); err != nil {
return fmt.Errorf("Unable to add new networking device to VM configuration\n%v", err)
}
return nil
}
func addVMDK(p *plugin, vm *object.VirtualMachine, newVM vmInstance) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
devices, err := vm.Device(ctx)
if err != nil {
return fmt.Errorf("Unable to read devices from VM configuration\n%v", err)
}
controller, err := devices.FindDiskController("scsi")
if err != nil {
return fmt.Errorf("Unable to find SCSI device from VM configuration\n%v", err)
}
// The default is to have all persistent disks named linuxkit.vmdk
disk := devices.CreateDisk(controller, p.vCenterInternals.datastore.Reference(), p.vCenterInternals.datastore.Path(fmt.Sprintf("%s/%s", newVM.vmName, newVM.vmName+".vmdk")))
disk.CapacityInKB = int64(newVM.persistentSz * 1024)
var add []types.BaseVirtualDevice
add = append(add, disk)
log.Info("Adding a persistent disk to the Virtual Machine")
if vm.AddDevice(ctx, add...); err != nil {
return fmt.Errorf("Unable to add new storage device to VM configuration\n%v", err)
}
return nil
}
func addISO(p *plugin, newInstance vmInstance, vm *object.VirtualMachine) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
devices, err := vm.Device(ctx)
if err != nil {
return fmt.Errorf("Unable to read devices from VM configuration\n%v", err)
}
ide, err := devices.FindIDEController("")
if err != nil {
return fmt.Errorf("Unable to find IDE device from VM configuration\n%v", err)
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
return fmt.Errorf("Unable to create new CDROM device\n%v", err)
}
var add []types.BaseVirtualDevice
add = append(add, devices.InsertIso(cdrom, p.vCenterInternals.datastore.Path(fmt.Sprintf("%s", newInstance.isoPath))))
log.Debug("Adding ISO to the Virtual Machine")
if vm.AddDevice(ctx, add...); err != nil {
return fmt.Errorf("Unable to add new CD-ROM device to VM configuration\n%v", err)
}
return nil
}
func findGroupInstances(p *plugin, groupName string) ([]*object.VirtualMachine, error) { // Without a groupName we have nothing to search for
if groupName == "" {
return nil, fmt.Errorf("The tag %s was blank", group.GroupTag)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(p.vCenterInternals.client.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *p.vC.dcName)
if err != nil {
return nil, fmt.Errorf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// This will either hold all of the virtual machines in a folder, or ALL VMs
var vmList []*object.VirtualMachine
// Try to find virtual machines in the groupName folder (doesn't exist on ESXi)
vmList, err = f.VirtualMachineList(ctx, groupName+"/*")
// If there is an error, it should indicate that there is no folder
if err != nil {
// Resort to inspecting ALL VM Instances for group tags
vmList, err = f.VirtualMachineList(ctx, "*")
if err != nil {
return vmList, err
}
}
// Go through the VMs and find the correct ones from the groupname
return findInstancesFromAnnotation(ctx, vmList, groupName)
}
func findInstancesFromAnnotation(ctx context.Context, vmList []*object.VirtualMachine, groupName string) ([]*object.VirtualMachine, error) {
var foundVMS []*object.VirtualMachine
// Find ALL Virtual Machines
// Create new array of Virtual Machines that will hold all VMs that have the groupName
for _, vmInstance := range vmList {
instanceGroup := returnDataFromVM(ctx, vmInstance, "group")
if instanceGroup == groupName {
foundVMS = append(foundVMS, vmInstance)
}
}
return foundVMS, nil
}
func returnDataFromVM(ctx context.Context, vmInstance *object.VirtualMachine, dataType string) string {
var machineConfig mo.VirtualMachine
if dataType == "guestIP" {
err := vmInstance.Properties(ctx, vmInstance.Reference(), []string{"guest.ipAddress"}, &machineConfig)
if err != nil {
log.Error(err.Error())
} else {
// Ensure that we're pointing to a Guest Config struct
if machineConfig.Guest != nil {
//log.Printf("%v\n%s", vmInstance, machineConfig.Guest.IpAddress)
return machineConfig.Guest.IpAddress
}
}
} else {
err := vmInstance.Properties(ctx, vmInstance.Reference(), []string{"config.annotation"}, &machineConfig)
if err != nil {
log.Error(err.Error())
}
// Ensure that we're pointing to a Configuration struct
if machineConfig.Config != nil {
annotationData := strings.Split(machineConfig.Config.Annotation, "\n")
if len(annotationData) > 1 {
switch dataType {
case "group":
return annotationData[0]
case "sha":
return annotationData[1]
}
}
}
}
return ""
}