forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vsphere.go
988 lines (840 loc) · 22.1 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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
/*
* Copyright 2014 VMware, Inc. All rights reserved. Licensed under the Apache v2 License.
*/
package vmwarevsphere
import (
"archive/tar"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"errors"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/guest"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
const (
// dockerBridgeIP is the default IP address of the docker0 bridge.
dockerBridgeIP = "172.17.0.1"
isoFilename = "boot2docker.iso"
// B2DUser is the guest User for tools login
B2DUser = "docker"
// B2DPass is the guest Pass for tools login
B2DPass = "tcuser"
)
type Driver struct {
*drivers.BaseDriver
Memory int
DiskSize int
CPU int
ISO string
Boot2DockerURL string
CPUS int
IP string
Port int
Username string
Password string
Network string
Datastore string
Datacenter string
Pool string
HostSystem string
CfgParams []string
CloudInit string
SSHPassword string
}
const (
defaultSSHUser = B2DUser
defaultSSHPass = B2DPass
defaultCpus = 2
defaultMemory = 2048
defaultDiskSize = 20480
defaultSDKPort = 443
)
// GetCreateFlags registers the flags this driver adds to
// "docker-machine create"
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.IntFlag{
EnvVar: "VSPHERE_CPU_COUNT",
Name: "vmwarevsphere-cpu-count",
Usage: "vSphere CPU number for docker VM",
Value: defaultCpus,
},
mcnflag.IntFlag{
EnvVar: "VSPHERE_MEMORY_SIZE",
Name: "vmwarevsphere-memory-size",
Usage: "vSphere size of memory for docker VM (in MB)",
Value: defaultMemory,
},
mcnflag.IntFlag{
EnvVar: "VSPHERE_DISK_SIZE",
Name: "vmwarevsphere-disk-size",
Usage: "vSphere size of disk for docker VM (in MB)",
Value: defaultDiskSize,
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_BOOT2DOCKER_URL",
Name: "vmwarevsphere-boot2docker-url",
Usage: "vSphere URL for boot2docker image",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_VCENTER",
Name: "vmwarevsphere-vcenter",
Usage: "vSphere IP/hostname for vCenter",
},
mcnflag.IntFlag{
EnvVar: "VSPHERE_VCENTER_PORT",
Name: "vmwarevsphere-vcenter-port",
Usage: "vSphere Port for vCenter",
Value: defaultSDKPort,
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_USERNAME",
Name: "vmwarevsphere-username",
Usage: "vSphere username",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_PASSWORD",
Name: "vmwarevsphere-password",
Usage: "vSphere password",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_NETWORK",
Name: "vmwarevsphere-network",
Usage: "vSphere network where the docker VM will be attached",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_DATASTORE",
Name: "vmwarevsphere-datastore",
Usage: "vSphere datastore for docker VM",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_DATACENTER",
Name: "vmwarevsphere-datacenter",
Usage: "vSphere datacenter for docker VM",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_POOL",
Name: "vmwarevsphere-pool",
Usage: "vSphere resource pool for docker VM",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_HOSTSYSTEM",
Name: "vmwarevsphere-hostsystem",
Usage: "vSphere compute resource where the docker VM will be instantiated. This can be omitted if using a cluster with DRS.",
},
mcnflag.StringSliceFlag{
EnvVar: "VSPHERE_CFGPARAM",
Name: "vmwarevsphere-cfgparam",
Usage: "vSphere vm configuration parameters (used for guestinfo)",
},
mcnflag.StringFlag{
EnvVar: "VSPHERE_CLOUDINIT",
Name: "vmwarevsphere-cloudinit",
Usage: "vSphere cloud-init file or url to set in the guestinfo",
},
}
}
func NewDriver(hostName, storePath string) drivers.Driver {
return &Driver{
CPUS: defaultCpus,
Memory: defaultMemory,
DiskSize: defaultDiskSize,
SSHPassword: defaultSSHPass,
Port: defaultSDKPort,
BaseDriver: &drivers.BaseDriver{
SSHUser: defaultSSHUser,
MachineName: hostName,
StorePath: storePath,
},
}
}
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
func (d *Driver) GetSSHUsername() string {
if d.SSHUser == "" {
d.SSHUser = "docker"
}
return d.SSHUser
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return "vmwarevsphere"
}
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.SSHUser = "docker"
d.SSHPort = 22
d.CPU = flags.Int("vmwarevsphere-cpu-count")
d.Memory = flags.Int("vmwarevsphere-memory-size")
d.DiskSize = flags.Int("vmwarevsphere-disk-size")
d.Boot2DockerURL = flags.String("vmwarevsphere-boot2docker-url")
d.IP = flags.String("vmwarevsphere-vcenter")
d.Port = flags.Int("vmwarevsphere-vcenter-port")
d.Username = flags.String("vmwarevsphere-username")
d.Password = flags.String("vmwarevsphere-password")
d.Network = flags.String("vmwarevsphere-network")
d.Datastore = flags.String("vmwarevsphere-datastore")
d.Datacenter = flags.String("vmwarevsphere-datacenter")
d.Pool = flags.String("vmwarevsphere-pool")
d.HostSystem = flags.String("vmwarevsphere-hostsystem")
d.CfgParams = flags.StringSlice("vmwarevsphere-cfgparam")
d.CloudInit = flags.String("vmwarevsphere-cloudinit")
d.SetSwarmConfigFromFlags(flags)
d.ISO = d.ResolveStorePath(isoFilename)
return nil
}
func (d *Driver) GetURL() (string, error) {
ip, err := d.GetIP()
if err != nil {
return "", err
}
if ip == "" {
return "", nil
}
return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil
}
func (d *Driver) GetIP() (string, error) {
status, err := d.GetState()
if status != state.Running {
return "", drivers.ErrHostIsNotRunning
}
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return "", err
}
defer c.Logout(ctx)
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return "", err
}
configuredMacIPs, err := vm.WaitForNetIP(ctx, false)
if err != nil {
return "", err
}
for _, ips := range configuredMacIPs {
if len(ips) >= 0 {
// Prefer IPv4 address, but fall back to first/IPv6
preferredIP := ips[0]
for _, ip := range ips {
// In addition to non IPv4 addresses, try to filter
// out link local addresses and the default address of
// the Docker0 bridge
netIP := net.ParseIP(ip)
if netIP.To4() != nil && netIP.IsGlobalUnicast() && !netIP.Equal(net.ParseIP(dockerBridgeIP)) {
preferredIP = ip
break
}
}
return preferredIP, nil
}
}
return "", errors.New("No IP despite waiting for one - check DHCP status")
}
func (d *Driver) GetState() (state.State, error) {
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return state.None, err
}
defer c.Logout(ctx)
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return state.None, err
}
var mvm mo.VirtualMachine
err = c.RetrieveOne(ctx, vm.Reference(), nil, &mvm)
if err != nil {
return state.None, nil
}
s := mvm.Summary
if strings.Contains(string(s.Runtime.PowerState), "poweredOn") {
return state.Running, nil
} else if strings.Contains(string(s.Runtime.PowerState), "poweredOff") {
return state.Stopped, nil
}
return state.None, nil
}
// PreCreateCheck checks that the machine creation process can be started safely.
func (d *Driver) PreCreateCheck() error {
log.Debug("Connecting to vSphere for pre-create checks...")
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
// Create a new finder
f := find.NewFinder(c.Client, true)
dc, err := f.DatacenterOrDefault(ctx, d.Datacenter)
if err != nil {
return err
}
f.SetDatacenter(dc)
if _, err := f.DatastoreOrDefault(ctx, d.Datastore); err != nil {
return err
}
if _, err := f.NetworkOrDefault(ctx, d.Network); err != nil {
return err
}
var hs *object.HostSystem
if d.HostSystem != "" {
var err error
hs, err = f.HostSystemOrDefault(ctx, d.HostSystem)
if err != nil {
return err
}
}
// ResourcePool
if d.Pool != "" {
// Find specified Resource Pool
if _, err := f.ResourcePool(ctx, d.Pool); err != nil {
return err
}
} else if hs != nil {
// Pick default Resource Pool for Host System
if _, err := hs.ResourcePool(ctx); err != nil {
return err
}
} else {
// Pick the default Resource Pool for the Datacenter.
if _, err := f.DefaultResourcePool(ctx); err != nil {
return err
}
}
return nil
}
// Create has the following implementation:
// 1. check whether the docker directory contains the boot2docker ISO
// 2. generate an SSH keypair and bundle it in a tar.
// 3. create a virtual machine with the boot2docker ISO mounted;
// 4. reconfigure the virtual machine network and disk size;
func (d *Driver) Create() error {
b2dutils := mcnutils.NewB2dUtils(d.StorePath)
if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
return err
}
log.Infof("Generating SSH Keypair...")
if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
return err
}
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
// Create a new finder
f := find.NewFinder(c.Client, true)
dc, err := f.DatacenterOrDefault(ctx, d.Datacenter)
if err != nil {
return err
}
f.SetDatacenter(dc)
dss, err := f.DatastoreOrDefault(ctx, d.Datastore)
if err != nil {
return err
}
net, err := f.NetworkOrDefault(ctx, d.Network)
if err != nil {
return err
}
var hs *object.HostSystem
if d.HostSystem != "" {
var err error
hs, err = f.HostSystemOrDefault(ctx, d.HostSystem)
if err != nil {
return err
}
}
var rp *object.ResourcePool
if d.Pool != "" {
// Find specified Resource Pool
rp, err = f.ResourcePool(ctx, d.Pool)
if err != nil {
return err
}
} else if d.HostSystem != "" {
// Pick default Resource Pool for Host System
rp, err = hs.ResourcePool(ctx)
if err != nil {
return err
}
} else {
// Pick the default Resource Pool for the Datacenter.
rp, err = f.DefaultResourcePool(ctx)
if err != nil {
return err
}
}
spec := types.VirtualMachineConfigSpec{
Name: d.MachineName,
GuestId: "otherLinux64Guest",
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", dss.Name())},
NumCPUs: int32(d.CPU),
MemoryMB: int64(d.Memory),
}
scsi, err := object.SCSIControllerTypes().CreateSCSIController("pvscsi")
if err != nil {
return err
}
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
Operation: types.VirtualDeviceConfigSpecOperationAdd,
Device: scsi,
})
log.Infof("Creating VM...")
folders, err := dc.Folders(ctx)
task, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs)
if err != nil {
return err
}
info, err := task.WaitForResult(ctx, nil)
if err != nil {
return err
}
log.Infof("Uploading Boot2docker ISO ...")
dsurl, err := dss.URL(ctx, dc, fmt.Sprintf("%s/%s", d.MachineName, isoFilename))
if err != nil {
return err
}
p := soap.DefaultUpload
if err = c.Client.UploadFile(d.ISO, dsurl, &p); err != nil {
return err
}
// Retrieve the new VM
vm := object.NewVirtualMachine(c.Client, info.Result.(types.ManagedObjectReference))
devices, err := vm.Device(ctx)
if err != nil {
return err
}
var add []types.BaseVirtualDevice
controller, err := devices.FindDiskController("scsi")
if err != nil {
return err
}
disk := devices.CreateDisk(controller, dss.Reference(),
dss.Path(fmt.Sprintf("%s/%s.vmdk", d.MachineName, d.MachineName)))
// Convert MB to KB
disk.CapacityInKB = int64(d.DiskSize) * 1024
add = append(add, disk)
ide, err := devices.FindIDEController("")
if err != nil {
return err
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
return err
}
add = append(add, devices.InsertIso(cdrom, dss.Path(fmt.Sprintf("%s/%s", d.MachineName, isoFilename))))
backing, err := net.EthernetCardBackingInfo(ctx)
if err != nil {
return err
}
netdev, err := object.EthernetCardTypes().CreateEthernetCard("vmxnet3", backing)
if err != nil {
return err
}
log.Infof("Reconfiguring VM...")
add = append(add, netdev)
if vm.AddDevice(ctx, add...); err != nil {
return err
}
// Adding some guestinfo data
var opts []types.BaseOptionValue
for _, param := range d.CfgParams {
v := strings.SplitN(param, "=", 2)
key := v[0]
value := ""
if len(v) > 1 {
value = v[1]
}
fmt.Printf("Setting %s to %s\n", key, value)
opts = append(opts, &types.OptionValue{
Key: key,
Value: value,
})
}
if d.CloudInit != "" {
if _, err := url.ParseRequestURI(d.CloudInit); err == nil {
log.Infof("setting guestinfo.cloud-init.data.url to %s\n", d.CloudInit)
opts = append(opts, &types.OptionValue{
Key: "guestinfo.cloud-init.config.url",
Value: d.CloudInit,
})
} else {
if _, err := os.Stat(d.CloudInit); err == nil {
if value, err := ioutil.ReadFile(d.CloudInit); err == nil {
log.Infof("setting guestinfo.cloud-init.data to encoded content of %s\n", d.CloudInit)
encoded := base64.StdEncoding.EncodeToString(value)
opts = append(opts, &types.OptionValue{
Key: "guestinfo.cloud-init.config.data",
Value: encoded,
})
opts = append(opts, &types.OptionValue{
Key: "guestinfo.cloud-init.data.encoding",
Value: "base64",
})
}
}
}
}
task, err = vm.Reconfigure(ctx, types.VirtualMachineConfigSpec{
ExtraConfig: opts,
})
if err != nil {
return err
}
task.Wait(ctx)
if err := d.Start(); err != nil {
return err
}
log.Infof("Provisioning certs and ssh keys...")
// Generate a tar keys bundle
if err := d.generateKeyBundle(); err != nil {
return err
}
opman := guest.NewOperationsManager(c.Client, vm.Reference())
fileman, err := opman.FileManager(ctx)
if err != nil {
return err
}
src := d.ResolveStorePath("userdata.tar")
s, err := os.Stat(src)
if err != nil {
return err
}
auth := AuthFlag{}
flag := FileAttrFlag{}
auth.auth.Username = B2DUser
auth.auth.Password = B2DPass
flag.SetPerms(0, 0, 660)
url, err := fileman.InitiateFileTransferToGuest(ctx, auth.Auth(), "/home/docker/userdata.tar", flag.Attr(), s.Size(), true)
if err != nil {
return err
}
u, err := c.Client.ParseURL(url)
if err != nil {
return err
}
if err = c.Client.UploadFile(src, u, nil); err != nil {
return err
}
procman, err := opman.ProcessManager(ctx)
if err != nil {
return err
}
// first, untar - only boot2docker has /var/lib/boot2docker
// TODO: don't hard-code to docker & staff - they are also just b2d
var env []string
guestspec := types.GuestProgramSpec{
ProgramPath: "/usr/bin/sudo",
Arguments: "/usr/bin/sudo /bin/sh -c \"tar xvf /home/docker/userdata.tar -C /home/docker > /var/log/userdata.log 2>&1 && chown -R docker:staff /home/docker\"",
WorkingDirectory: "",
EnvVariables: env,
}
_, err = procman.StartProgram(ctx, auth.Auth(), &guestspec)
if err != nil {
return err
}
// now move to /var/lib/boot2docker if its there
guestspec = types.GuestProgramSpec{
ProgramPath: "/usr/bin/sudo",
Arguments: "/bin/mv /home/docker/userdata.tar /var/lib/boot2docker/userdata.tar",
WorkingDirectory: "",
EnvVariables: env,
}
_, err = procman.StartProgram(ctx, auth.Auth(), &guestspec)
if err != nil {
return err
}
return nil
}
func (d *Driver) Start() error {
machineState, err := d.GetState()
if err != nil {
return err
}
switch machineState {
case state.Running:
log.Infof("VM %s has already been started", d.MachineName)
return nil
case state.Stopped:
// TODO add transactional or error handling in the following steps
// Create context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return err
}
task, err := vm.PowerOn(ctx)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
log.Infof("Waiting for VMware Tools to come online...")
if d.IPAddress, err = d.GetIP(); err != nil {
return err
}
}
return nil
}
func (d *Driver) Stop() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return err
}
if err := vm.ShutdownGuest(ctx); err != nil {
return err
}
d.IPAddress = ""
return nil
}
func (d *Driver) Restart() error {
if err := d.Stop(); err != nil {
return err
}
// Check for 120 seconds for the machine to stop
for i := 1; i <= 60; i++ {
machineState, err := d.GetState()
if err != nil {
return err
}
if machineState == state.Running {
log.Debugf("Not there yet %d/%d", i, 60)
time.Sleep(2 * time.Second)
continue
}
if machineState == state.Stopped {
break
}
}
machineState, err := d.GetState()
// If the VM is still running after 120 seconds just kill it.
if machineState == state.Running {
if err = d.Kill(); err != nil {
return fmt.Errorf("can't stop VM: %s", err)
}
}
return d.Start()
}
func (d *Driver) Kill() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return err
}
task, err := vm.PowerOff(ctx)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
d.IPAddress = ""
return nil
}
func (d *Driver) Remove() error {
machineState, err := d.GetState()
if err != nil {
return err
}
if machineState == state.Running {
if err = d.Kill(); err != nil {
return fmt.Errorf("can't stop VM: %s", err)
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, err := d.vsphereLogin(ctx)
if err != nil {
return err
}
defer c.Logout(ctx)
// Create a new finder
f := find.NewFinder(c.Client, true)
dc, err := f.DatacenterOrDefault(ctx, d.Datacenter)
if err != nil {
return err
}
f.SetDatacenter(dc)
dss, err := f.DatastoreOrDefault(ctx, d.Datastore)
if err != nil {
return err
}
// Remove B2D Iso from VM folder
m := object.NewFileManager(c.Client)
task, err := m.DeleteDatastoreFile(ctx, dss.Path(fmt.Sprintf("%s/%s", d.MachineName, isoFilename)), dc)
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
if types.IsFileNotFound(err) {
// Ignore error
return nil
}
}
vm, err := d.fetchVM(ctx, c, d.MachineName)
if err != nil {
return err
}
task, err = vm.Destroy(ctx)
if err != nil {
return err
}
_, err = task.WaitForResult(ctx, nil)
if err != nil {
return err
}
return nil
}
func (d *Driver) Upgrade() error {
return fmt.Errorf("upgrade is not supported for vsphere driver at this moment")
}
func (d *Driver) publicSSHKeyPath() string {
return d.GetSSHKeyPath() + ".pub"
}
// Make a boot2docker userdata.tar key bundle
func (d *Driver) generateKeyBundle() error {
log.Debugf("Creating Tar key bundle...")
magicString := "boot2docker, this is vmware speaking"
tf, err := os.Create(d.ResolveStorePath("userdata.tar"))
if err != nil {
return err
}
defer tf.Close()
var fileWriter = tf
tw := tar.NewWriter(fileWriter)
defer tw.Close()
// magicString first so we can figure out who originally wrote the tar.
file := &tar.Header{Name: magicString, Size: int64(len(magicString))}
if err := tw.WriteHeader(file); err != nil {
return err
}
if _, err := tw.Write([]byte(magicString)); err != nil {
return err
}
// .ssh/key.pub => authorized_keys
file = &tar.Header{Name: ".ssh", Typeflag: tar.TypeDir, Mode: 0700}
if err := tw.WriteHeader(file); err != nil {
return err
}
pubKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
if err != nil {
return err
}
file = &tar.Header{Name: ".ssh/authorized_keys", Size: int64(len(pubKey)), Mode: 0644}
if err := tw.WriteHeader(file); err != nil {
return err
}
if _, err := tw.Write([]byte(pubKey)); err != nil {
return err
}
file = &tar.Header{Name: ".ssh/authorized_keys2", Size: int64(len(pubKey)), Mode: 0644}
if err := tw.WriteHeader(file); err != nil {
return err
}
if _, err := tw.Write([]byte(pubKey)); err != nil {
return err
}
if err := tw.Close(); err != nil {
return err
}
return nil
}
func (d *Driver) vsphereLogin(ctx context.Context) (*govmomi.Client, error) {
// Parse URL from string
u, err := url.Parse(fmt.Sprintf("https://%s:%d/sdk", d.IP, d.Port))
if err != nil {
return nil, err
}
// set username and password for the URL
u.User = url.UserPassword(d.Username, d.Password)
// Connect and log in to ESX or vCenter
c, err := govmomi.NewClient(ctx, u, true)
if err != nil {
return nil, err
}
return c, nil
}
func (d *Driver) fetchVM(ctx context.Context, c *govmomi.Client, vmname string) (*object.VirtualMachine, error) {
// Create a new finder
f := find.NewFinder(c.Client, true)
var vm *object.VirtualMachine
var err error
dc, err := f.DatacenterOrDefault(ctx, d.Datacenter)
if err != nil {
return vm, err
}
f.SetDatacenter(dc)
vm, err = f.VirtualMachine(ctx, vmname)
if err != nil {
return vm, err
}
return vm, nil
}
type AuthFlag struct {
auth types.NamePasswordAuthentication
}
func (f *AuthFlag) Auth() types.BaseGuestAuthentication {
return &f.auth
}
type FileAttrFlag struct {
types.GuestPosixFileAttributes
}
func (f *FileAttrFlag) SetPerms(owner, group, perms int) {
f.OwnerId = int32(owner)
f.GroupId = int32(group)
f.Permissions = int64(perms)
}
func (f *FileAttrFlag) Attr() types.BaseGuestFileAttributes {
return &f.GuestPosixFileAttributes
}