/
run_vcenter.go
335 lines (283 loc) · 10.3 KB
/
run_vcenter.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
package main
import (
"context"
"errors"
"fmt"
"math/rand"
"net/url"
"os"
"path"
"strings"
"github.com/spf13/cobra"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
log "github.com/sirupsen/logrus"
)
type vmConfig struct {
vCenterURL *string
dcName *string
dsName *string
networkName *string
vSphereHost *string
vmFolder *string
path *string
persistent *string
persistentSz int
vCpus *int
mem *int64
poweron *bool
guestIP *bool
}
func runVCenterCmd() *cobra.Command {
var (
vCenterURL string
dcName string
dsName string
networkName string
vSphereHost string
vmFolder string
vmPath string
persistent string
poweron bool
guestIP bool
)
cmd := &cobra.Command{
Use: "vcenter",
Short: "launch a VCenter instance using an existing image",
Long: `Launch a VCenter instance using an existing image.
'path' specifies the full path of an image to run.
`,
Args: cobra.ExactArgs(1),
Example: "linuxkit run vcenter [options] path",
RunE: func(cmd *cobra.Command, args []string) error {
imagePath := args[0]
if guestIP && !poweron {
return errors.New("The waitForIP flag can not be used without the powerOn flag")
}
// Ensure an iso has been passed to the vCenter run Command
if strings.HasSuffix(vmPath, ".iso") {
// Allow alternative names for new virtual machines being created in vCenter
if vmFolder == "" {
vmFolder = strings.TrimSuffix(path.Base(vmPath), ".iso")
}
} else {
return fmt.Errorf("Please pass an \".iso\" file as the path")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mem64 := int64(mem)
newVM := vmConfig{
vCenterURL: &vCenterURL,
dcName: &dcName,
dsName: &dsName,
networkName: &networkName,
vSphereHost: &vSphereHost,
vmFolder: &vmFolder,
path: &vmPath,
persistent: &persistent,
mem: &mem64,
vCpus: &cpus,
poweron: &poweron,
guestIP: &guestIP,
}
newVM.path = &imagePath
// Connect to VMware vCenter and return the default and found values needed for a new VM
c, dss, folders, hs, net, rp := vCenterConnect(ctx, newVM)
log.Infof("Creating new LinuxKit Virtual Machine")
spec := types.VirtualMachineConfigSpec{
Name: *newVM.vmFolder,
GuestId: "otherLinux64Guest",
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", dss.Name())},
NumCPUs: int32(*newVM.vCpus),
MemoryMB: *newVM.mem,
}
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,
})
task, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs)
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%w", err)
}
// Retrieve the new VM
vm := object.NewVirtualMachine(c.Client, info.Result.(types.ManagedObjectReference))
addISO(ctx, newVM, vm, dss)
if *newVM.persistent != "" {
newVM.persistentSz, err = getDiskSizeMB(*newVM.persistent)
if err != nil {
return fmt.Errorf("Couldn't parse disk-size %s: %v", *newVM.persistent, err)
}
addVMDK(ctx, vm, dss, newVM)
}
if *newVM.networkName != "" {
addNIC(ctx, vm, net)
}
if *newVM.poweron {
log.Infoln("Powering on LinuxKit VM")
powerOnVM(ctx, vm)
}
if *newVM.guestIP {
log.Infof("Waiting for OpenVM Tools to come online")
guestIP, err := getVMToolsIP(ctx, vm)
if err != nil {
log.Errorf("%v", err)
}
log.Infof("Guest IP Address: %s", guestIP)
}
return nil
},
}
cmd.Flags().StringVar(&vCenterURL, "url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
cmd.Flags().StringVar(&dcName, "datacenter", os.Getenv("VCDATACENTER"), "The name of the Datacenter to host the VM")
cmd.Flags().StringVar(&dsName, "datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the VM")
cmd.Flags().StringVar(&networkName, "network", os.Getenv("VCNETWORK"), "The network label the VM will use")
cmd.Flags().StringVar(&vSphereHost, "hostname", os.Getenv("VCHOST"), "The server that will run the VM")
cmd.Flags().StringVar(&vmFolder, "vmfolder", "", "Specify a name/folder for the virtual machine to reside in")
cmd.Flags().StringVar(&vmPath, "path", "", "Path to a specific image")
cmd.Flags().StringVar(&persistent, "persistentSize", "", "Size in MB of persistent storage to allocate to the VM")
cmd.Flags().BoolVar(&poweron, "powerOn", false, "Power On the new VM once it has been created")
cmd.Flags().BoolVar(&guestIP, "waitForIP", false, "LinuxKit will wait for the VM to power on and return the guest IP, requires open-vm-tools and the -powerOn flag to be set")
return cmd
}
func getVMToolsIP(ctx context.Context, vm *object.VirtualMachine) (string, error) {
guestIP, err := vm.WaitForIP(ctx)
if err != nil {
return "", err
}
return guestIP, err
}
func vCenterConnect(ctx context.Context, newVM vmConfig) (*govmomi.Client, *object.Datastore, *object.DatacenterFolders, *object.HostSystem, object.NetworkReference, *object.ResourcePool) {
// Parse URL from string
u, err := url.Parse(*newVM.vCenterURL)
if err != nil {
log.Fatalf("URL can't be parsed, ensure it is https://username:password/<address>/sdk %v", err)
}
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, true)
if err != nil {
log.Fatalf("Error logging into vCenter, check address and credentials %v", err)
}
// Create a new finder that will discover the defaults and are looked for Networks/Datastores
f := find.NewFinder(c.Client, true)
// Find one and only datacenter, not sure how VMware linked mode will work
dc, err := f.DatacenterOrDefault(ctx, *newVM.dcName)
if err != nil {
log.Fatalf("No Datacenter instance could be found inside of vCenter %v", err)
}
// Make future calls local to this datacenter
f.SetDatacenter(dc)
// Find Datastore/Network
dss, err := f.DatastoreOrDefault(ctx, *newVM.dsName)
if err != nil {
log.Fatalf("Datastore [%s], could not be found", *newVM.dsName)
}
folders, err := dc.Folders(ctx)
if err != nil {
log.Fatalln("Error locating default datacenter folder")
}
// This code is shared between Push/Run, a network isn't needed for Pushing an image
var net object.NetworkReference
if newVM.networkName != nil && *newVM.networkName != "" {
net, err = f.NetworkOrDefault(ctx, *newVM.networkName)
if err != nil {
log.Fatalf("Network [%s], could not be found", *newVM.networkName)
}
}
// Check to see if a host has been specified
var hs *object.HostSystem
if *newVM.vSphereHost != "" {
// Find the selected host
hs, err = f.HostSystem(ctx, *newVM.vSphereHost)
if err != nil {
log.Fatalf("vSphere host [%s], could not be found", *newVM.vSphereHost)
}
} else {
allHosts, err := f.HostSystemList(ctx, "*/*")
if err != nil || len(allHosts) == 0 {
log.Fatalf("No vSphere hosts could be found on vCenter server")
}
// Select a host from the list off all available hosts at random
hs = allHosts[rand.Int()%len(allHosts)]
}
var rp *object.ResourcePool
rp, err = hs.ResourcePool(ctx)
if err != nil {
log.Fatalln("Error locating default resource pool")
}
return c, dss, folders, hs, net, rp
}
func powerOnVM(ctx context.Context, vm *object.VirtualMachine) {
task, err := vm.PowerOn(ctx)
if err != nil {
log.Errorln("Power On operation has failed, more detail can be found in vCenter tasks")
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
log.Errorln("Power On Task has failed, more detail can be found in vCenter tasks")
}
}
func addNIC(ctx context.Context, vm *object.VirtualMachine, net object.NetworkReference) {
backing, err := net.EthernetCardBackingInfo(ctx)
if err != nil {
log.Fatalf("Unable to determine vCenter network backend\n%v", err)
}
netdev, err := object.EthernetCardTypes().CreateEthernetCard("vmxnet3", backing)
if err != nil {
log.Fatalf("Unable to create vmxnet3 network interface\n%v", err)
}
log.Infof("Adding VM Networking")
var add []types.BaseVirtualDevice
add = append(add, netdev)
if err := vm.AddDevice(ctx, add...); err != nil {
log.Fatalf("Unable to add new networking device to VM configuration\n%v", err)
}
}
func addVMDK(ctx context.Context, vm *object.VirtualMachine, dss *object.Datastore, newVM vmConfig) {
devices, err := vm.Device(ctx)
if err != nil {
log.Fatalf("Unable to read devices from VM configuration\n%v", err)
}
controller, err := devices.FindDiskController("scsi")
if err != nil {
log.Fatalf("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, dss.Reference(), dss.Path(fmt.Sprintf("%s/%s", *newVM.vmFolder, "linuxkit.vmdk")))
disk.CapacityInKB = int64(newVM.persistentSz * 1024)
var add []types.BaseVirtualDevice
add = append(add, disk)
log.Infof("Adding a persistent disk to the Virtual Machine")
if err := vm.AddDevice(ctx, add...); err != nil {
log.Fatalf("Unable to add new storage device to VM configuration\n%v", err)
}
}
func addISO(ctx context.Context, newVM vmConfig, vm *object.VirtualMachine, dss *object.Datastore) {
devices, err := vm.Device(ctx)
if err != nil {
log.Fatalf("Unable to read devices from VM configuration\n%v", err)
}
ide, err := devices.FindIDEController("")
if err != nil {
log.Fatalf("Unable to find IDE device from VM configuration\n%v", err)
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
log.Fatalf("Unable to create new CDROM device\n%v", err)
}
var add []types.BaseVirtualDevice
add = append(add, devices.InsertIso(cdrom, dss.Path(fmt.Sprintf("%s/%s", *newVM.vmFolder, path.Base(*newVM.path)))))
log.Infof("Adding ISO to the Virtual Machine")
if err := vm.AddDevice(ctx, add...); err != nil {
log.Fatalf("Unable to add new CD-ROM device to VM configuration\n%v", err)
}
}