-
Notifications
You must be signed in to change notification settings - Fork 16
/
vsphere.go
374 lines (316 loc) · 10.5 KB
/
vsphere.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
/*
Copyright © 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This piece of code was developed for RDM support mainly thanks to the project govmax on github.com
// This file in particular from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
package service
import (
"errors"
"fmt"
"net"
"net/url"
"reflect"
"strings"
log "github.com/sirupsen/logrus"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/akutz/goof"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// VMHost - structure to hold the VM host
type VMHost struct {
client *govmomi.Client
Ctx context.Context
mac string
VM *object.VirtualMachine
}
// NewVMHost connects to a ESXi or vCenter instance and returns a *VMHost
// This method is referenced from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func NewVMHost(insecure bool, hostURLparam, user, pass string) (*VMHost, error) {
ctx, _ := context.WithCancel(context.Background())
hostURL, err := url.Parse("https://" + hostURLparam + "/sdk")
hostURL.User = url.UserPassword(user, pass)
cli, err := govmomi.NewClient(ctx, hostURL, insecure)
if err != nil {
return nil, err
}
mac, err := getLocalMAC()
if err != nil {
return nil, err
}
vmh := &VMHost{
client: cli,
Ctx: ctx,
mac: mac,
}
vm, err := vmh.findVM(vmh.mac)
if err != nil {
return nil, err
}
vmh.VM = vm
return vmh, nil
}
////////////////////////////////////////////////////////////////////
// Returns if Eth0 MAC Address of VM //
////////////////////////////////////////////////////////////////////
func (vmh *VMHost) getMACAddressOfVM(vm *object.VirtualMachine) (string, error) {
vmDeviceList, err := vm.Device(context.TODO())
if err != nil {
return "", errors.New("Cannot read VM VirtualDevices")
}
return vmDeviceList.PrimaryMacAddress(), nil
}
func getLocalMAC() (string, error) {
ifs, err := net.Interfaces()
if err != nil {
return "", err
}
for _, v := range ifs {
if v.HardwareAddr.String() != "" {
return v.HardwareAddr.String(), nil
}
}
return "", errors.New("No network interface found")
}
///////////////////////////////////////////////////////////////////
// Find the target VM in Host with specified MAC Address //
// Using MAC address to identify VM since that is the only //
// property known to the VM that its host also knows //
// WITHOUT VMWARE tools installed. //
///////////////////////////////////////////////////////////////////
func (vmh *VMHost) findVM(targetMACAddress string) (vm *object.VirtualMachine, err error) {
targetMACAddress = strings.ToUpper(targetMACAddress)
f := find.NewFinder(vmh.client.Client, true)
allDatacenters, err := f.DatacenterList(vmh.Ctx, "*")
if err != nil {
return nil, errors.New("Could not get List of Datacenters")
}
for _, datacenter := range allDatacenters {
f.SetDatacenter(datacenter)
allVMs, err := f.VirtualMachineList(vmh.Ctx, "*")
if err != nil {
return nil, errors.New("Could not get List of VMs")
}
for _, vm := range allVMs {
VMMac, err := vmh.getMACAddressOfVM(vm)
VMMac = strings.ToUpper(VMMac)
if err != nil {
log.Debugf("Could not get MAC Address of VM (%v), datacenter (%v)", vm, datacenter)
}
if VMMac == targetMACAddress && err == nil {
log.Debugf("Found VM: %v , mac(%s)", vm, VMMac)
return vm, nil
}
}
}
return nil, errors.New("Could not find VM with specified MAC Address of " + targetMACAddress)
}
func (vmh *VMHost) getVMScsiDiskDeviceInfo(vm *object.VirtualMachine) ([]types.VirtualMachineScsiDiskDeviceInfo, error) {
var VMwithProp mo.VirtualMachine
err := vm.Properties(vmh.Ctx, vm.Reference(), []string{"environmentBrowser"}, &VMwithProp)
if err != nil {
return nil, fmt.Errorf("Error finding Environment Browser for VM - %S", err)
}
// Query VM To Find Devices avilable for attaching to VM
var queryConfigRequest types.QueryConfigTarget
queryConfigRequest.This = VMwithProp.EnvironmentBrowser
queryConfigResp, err := methods.QueryConfigTarget(vmh.Ctx, vmh.client.Client, &queryConfigRequest)
if err != nil {
return nil, fmt.Errorf("Error Obtaining Configuration Options of Host System that VM is On - %S", err)
}
vmConfigOptions := *queryConfigResp.Returnval
return vmConfigOptions.ScsiDisk, nil
}
func (vmh *VMHost) getAvailableSCSIController() (*types.VirtualSCSIController, error) {
scsiControllers, err := vmh.getSCSIControllers()
if err != nil {
return nil, err
}
for _, scsiDevice := range scsiControllers {
scsiDevice := scsiDevice.(types.BaseVirtualSCSIController).GetVirtualSCSIController()
if len(scsiDevice.VirtualController.Device) < 15 {
return scsiDevice, nil
}
}
return nil, nil
}
func (vmh *VMHost) getSCSIControllers() (object.VirtualDeviceList, error) {
virtualDeviceList, err := vmh.VM.Device(vmh.Ctx)
if err != nil {
return nil, fmt.Errorf("Error Obtaining List of Devices Attached to VM - %s", err)
}
var c types.VirtualSCSIController
return virtualDeviceList.SelectByType(&c), nil
}
// GetSCSILuns fetches all the SCSILuns discovered on the host
// This method is referenced from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func (vmh *VMHost) GetSCSILuns() ([]*types.ScsiLun, error) {
host, err := vmh.VM.HostSystem(vmh.Ctx)
if err != nil {
return nil, err
}
ss, err := host.ConfigManager().StorageSystem(vmh.Ctx)
if err != nil {
return nil, err
}
var hss mo.HostStorageSystem
err = ss.Properties(vmh.Ctx, ss.Reference(), nil, &hss)
if err != nil {
return nil, err
}
scsiLuns := make([]*types.ScsiLun, 0)
for _, sl := range hss.StorageDeviceInfo.ScsiLun {
scsiLuns = append(scsiLuns, sl.(types.BaseScsiLun).GetScsiLun())
}
return scsiLuns, nil
}
func (vmh *VMHost) createController(controller *types.BaseVirtualDevice) error {
devices, err := vmh.VM.Device(context.TODO())
if err != nil {
return err
}
d, err := devices.CreateSCSIController(reflect.TypeOf(*controller).Name())
if err != nil {
return err
}
err = vmh.VM.AddDevice(vmh.Ctx, d)
if err != nil {
return fmt.Errorf("Error creating new SCSI Controller for RDM - %s", err)
}
return nil
}
// AttachRDM adds the device to the VM as an RDM
// This method is referenced from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func (vmh *VMHost) AttachRDM(vm *object.VirtualMachine, deviceNAA string) (err error) {
vmScsiDiskDeviceInfo, err := vmh.getVMScsiDiskDeviceInfo(vm)
if err != nil {
return err
}
// var scsiCtlrUnitNumber int
// Build new Virtual Device to add to VM from list of avilable devices found from our query
for _, ScsiDisk := range vmScsiDiskDeviceInfo {
if !strings.Contains(ScsiDisk.Disk.CanonicalName, deviceNAA) {
continue
}
var rdmBacking types.VirtualDiskRawDiskMappingVer1BackingInfo
rdmBacking.FileName = ""
rdmBacking.DiskMode = "independent_persistent"
rdmBacking.CompatibilityMode = "physicalMode"
rdmBacking.DeviceName = ScsiDisk.Disk.DeviceName
for _, descriptor := range ScsiDisk.Disk.Descriptor {
if string([]rune(descriptor.Id)[:4]) == "vml." {
rdmBacking.LunUuid = descriptor.Id
break
}
}
var rdmDisk types.VirtualDisk
rdmDisk.Backing = &rdmBacking
rdmDisk.CapacityInKB = 1024
controller, err := vmh.getAvailableSCSIController()
if err != nil {
return err
}
if controller == nil {
controllers, err := vmh.getSCSIControllers()
if err != nil {
return err
}
if len(controllers) == 0 {
return errors.New("no SCSI controllers found")
}
if len(controllers) == 4 {
return errors.New("no more controllers can be added")
}
err = vmh.createController(&controllers[0])
if err != nil {
return err
}
controller, err = vmh.getAvailableSCSIController()
if err != nil {
return err
}
}
rdmDisk.ControllerKey = controller.VirtualController.Key
var x int32 = -1
rdmDisk.UnitNumber = &x
err = vm.AddDevice(vmh.Ctx, &rdmDisk)
if err != nil {
return fmt.Errorf("Error adding device %+v \n Logged Item: %s", rdmDisk, err)
}
return nil
}
scsiLuns, err := vmh.GetSCSILuns()
if err != nil {
return goof.WithError("error getting existing LUNs", err)
}
for _, sl := range scsiLuns {
if strings.Contains(sl.CanonicalName, deviceNAA) {
return nil
}
}
return errors.New("no device detected on VM host to add")
}
// DetachRDM removes the device from the VM
// This method is referenced from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func (vmh *VMHost) DetachRDM(vm *object.VirtualMachine, deviceNAA string) error {
scsiLuns, err := vmh.GetSCSILuns()
if err != nil {
return err
}
mapSDI := make(map[string]*types.ScsiLun)
for _, d := range scsiLuns {
mapSDI[d.Uuid] = d
}
devices, err := vm.Device(context.TODO())
if err != nil {
return err
}
for _, device := range devices {
device2 := device.(types.BaseVirtualDevice).GetVirtualDevice()
if device2.Backing != nil {
elem := reflect.ValueOf(device2.Backing).Elem()
lunUUID := elem.FieldByName("LunUuid")
if lunUUID.Kind() == reflect.Invalid {
continue
}
if sd, ok := mapSDI[lunUUID.String()]; ok && strings.Contains(sd.CanonicalName, deviceNAA) {
deviceName := devices.Name(device)
newDevice := devices.Find(deviceName)
if newDevice == nil {
return fmt.Errorf("device '%s' not found", deviceName)
}
if err = vm.RemoveDevice(context.TODO(), false, newDevice); err != nil {
return err
}
break
}
}
}
return nil
}
// RescanAllHba rediscovers new devices added to the ESX
// This method is referenced from https://github.com/codedellemc/govmax/blob/master/api/v1/vmomi.go
func (vmh *VMHost) RescanAllHba(hostSystem *object.HostSystem) error {
storageSystem, err := hostSystem.ConfigManager().StorageSystem(vmh.Ctx)
if err != nil {
return err
}
err = storageSystem.RescanAllHba(vmh.Ctx)
if err != nil {
return err
}
return nil
}