forked from vmware/vic
/
appliance.go
1279 lines (1095 loc) · 40 KB
/
appliance.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
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2018 VMware, Inc. 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.
package management
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"syscall"
"time"
dockertypes "github.com/docker/docker/api/types"
"github.com/docker/docker/opts"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
"github.com/vmware/vic/lib/config"
"github.com/vmware/vic/lib/config/executor"
"github.com/vmware/vic/lib/constants"
"github.com/vmware/vic/lib/install/data"
"github.com/vmware/vic/lib/spec"
"github.com/vmware/vic/lib/tether/shared"
"github.com/vmware/vic/pkg/errors"
"github.com/vmware/vic/pkg/ip"
"github.com/vmware/vic/pkg/retry"
"github.com/vmware/vic/pkg/trace"
"github.com/vmware/vic/pkg/vsphere/compute"
"github.com/vmware/vic/pkg/vsphere/diag"
"github.com/vmware/vic/pkg/vsphere/extraconfig"
"github.com/vmware/vic/pkg/vsphere/extraconfig/vmomi"
"github.com/vmware/vic/pkg/vsphere/tasks"
"github.com/vmware/vic/pkg/vsphere/vm"
)
const (
portLayerPort = constants.SerialOverLANPort
// this is generated in the crypto/tls.alert code
badTLSCertificate = "tls: bad certificate"
// This is a constant also used in the lib/apiservers/engine/backends/system.go to assign custom info the docker types.info struct
volumeStoresID = "VolumeStores"
)
var (
lastSeenProgressMessage string
unitNumber int32
)
func (d *Dispatcher) isVCH(vm *vm.VirtualMachine) (bool, error) {
if vm == nil {
return false, errors.New("nil parameter")
}
defer trace.End(trace.Begin(vm.InventoryPath))
info, err := vm.FetchExtraConfig(d.op)
if err != nil {
err = errors.Errorf("Failed to fetch guest info of appliance vm: %s", err)
return false, err
}
var remoteConf config.VirtualContainerHostConfigSpec
extraconfig.Decode(extraconfig.MapSource(info), &remoteConf)
// if the moref of the target matches where we expect to find it for a VCH, run with it
if remoteConf.ExecutorConfig.ID == vm.Reference().String() || remoteConf.IsCreating() {
return true, nil
}
return false, nil
}
func (d *Dispatcher) isContainerVM(vm *vm.VirtualMachine) (bool, error) {
if vm == nil {
return false, errors.New("nil parameter")
}
defer trace.End(trace.Begin(vm.InventoryPath))
var cspec executor.ExecutorConfig
info, err := vm.FetchExtraConfig(d.op)
if err != nil {
err = errors.Errorf("Failed to fetch guest info of appliance vm: %s", err)
return false, err
}
extraconfig.Decode(extraconfig.MapSource(info), &cspec)
if cspec.Version == nil {
return false, nil
}
return true, nil
}
func (d *Dispatcher) checkExistence(conf *config.VirtualContainerHostConfigSpec, settings *data.InstallerData) error {
defer trace.End(trace.Begin(""))
var err error
var orp *object.ResourcePool
if orp, err = d.findResourcePool(d.vchPoolPath); err != nil {
return err
}
if orp == nil {
return nil
}
rp := compute.NewResourcePool(d.op, d.session, orp.Reference())
vm, err := rp.GetChildVM(d.op, conf.Name)
if err != nil {
return err
}
if vm == nil {
return nil
}
d.op.Debug("Appliance is found")
if ok, verr := d.isVCH(vm); !ok {
verr = errors.Errorf("Found virtual machine %q, but it is not a VCH. Please choose a different virtual app.", conf.Name)
return verr
}
err = errors.Errorf("A VCH with the name %q already exists. Please choose a different name before attempting another install", conf.Name)
return err
}
func (d *Dispatcher) powerOffVM(vm *vm.VirtualMachine) error {
var err error
power, err := vm.PowerState(d.op)
if err == nil && power == types.VirtualMachinePowerStatePoweredOff {
d.op.Debugf("VM is already powered off: %s", vm.Reference())
return nil
}
if err != nil {
d.op.Warnf("Failed to get vm power status %q: %s", vm.Reference(), err)
}
// try guest shutdown first
tools, err := vm.IsToolsRunning(d.op)
if tools {
d.op.Debugf("Performing guest shutdown for %s", vm.Reference())
err = vm.ShutdownGuest(d.op)
if err == nil {
// just enough time for the endpoint to shutdown cleanly even having timed out internally
timeout, cancel := trace.WithTimeout(&d.op, shared.GuestShutdownTimeout+(5*time.Second), "Shut down endpointVM")
err = vm.WaitForPowerState(timeout, types.VirtualMachinePowerStatePoweredOff)
cancel()
if err == nil {
return nil
}
d.op.Warnf("Guest shutdown timed out, resorting to power off - sessions may be left open: %s", err)
}
// this may well be because of delay in reporting the VM powering off so the actual detail is recorded as debug
// if this is the case then we will catch it via the IsAlreadyPoweredOff call below
d.op.Debugf("Guest shutdown failed: %s", err)
} else {
d.op.Warnf("Guest tools unavailable, resorting to power off - sessions will be left open")
}
_, err = vm.WaitForResult(d.op, func(ctx context.Context) (tasks.Task, error) {
return vm.PowerOff(ctx)
})
if vm.IsAlreadyPoweredOffError(err) {
err = nil
}
return err
}
func (d *Dispatcher) deleteVM(vm *vm.VirtualMachine, force bool) error {
defer trace.End(trace.Begin(fmt.Sprintf("vm %q, force %t", vm.String(), force)))
var err error
power, err := vm.PowerState(d.op)
if err != nil || power != types.VirtualMachinePowerStatePoweredOff {
if err != nil {
d.op.Warnf("Failed to get vm power status %q: %s", vm.Reference(), err)
}
if !force {
if err != nil {
return err
}
name, _ := vm.ObjectName(d.op)
if name != "" {
err = errors.Errorf("VM %q is powered on", name)
} else {
err = errors.Errorf("VM %q is powered on", vm.Reference())
}
return err
}
err = d.powerOffVM(vm)
if err != nil {
d.op.Debugf("Failed to power off existing appliance for %s, try to remove anyway", err)
}
}
// get the actual folder name before we delete it
folder, err := vm.DatastoreFolderName(d.op)
if err != nil {
// failed to get folder name, might not be able to remove files for this VM
name, _ := vm.ObjectName(d.op)
if name == "" {
d.op.Errorf("Unable to automatically remove all files in datastore for VM %q", vm.Reference())
} else {
// try to use the vm name in place of folder
d.op.Infof("Delete will attempt to remove datastore files for VM %q", name)
folder = name
}
}
// Power off the VM if necessary
retryErrHandler := func(err error) bool {
if tasks.IsInvalidPowerStateError(err) {
_, terr := vm.WaitForResult(d.op, func(ctx context.Context) (tasks.Task, error) {
return vm.PowerOff(ctx)
})
if terr == nil || tasks.IsTransientError(d.op, terr) || tasks.IsInvalidPowerStateError(terr) {
return true
}
}
return tasks.IsTransientError(d.op, err) || tasks.IsConcurrentAccessError(err)
}
// Only retry VM destroy on ConcurrentAccess error
err = retry.Do(d.op, func() error {
_, err := vm.DeleteExceptDisks(d.op)
return err
}, retryErrHandler)
if err != nil {
d.op.Warnf("Destroy VM %s failed with %s, unregister the VM instead", vm.Reference(), err)
err = retry.Do(d.op, func() error {
return vm.Unregister(d.op)
}, retryErrHandler)
if err != nil {
d.op.Errorf("Unregister the VM failed: %s", err)
return err
}
}
if _, err = d.deleteDatastoreFiles(d.session.Datastore, folder, true); err != nil {
d.op.Warnf("Failed to remove datastore files for VM %s with folder path %s: %s", vm.Reference(), folder, err)
}
return nil
}
func (d *Dispatcher) addNetworkDevices(conf *config.VirtualContainerHostConfigSpec, cspec *spec.VirtualMachineConfigSpec, devices object.VirtualDeviceList) (object.VirtualDeviceList, error) {
defer trace.End(trace.Begin(""))
// network name:alias, to avoid create multiple devices for same network
slots := make(map[int32]bool)
nets := make(map[string]*executor.NetworkEndpoint)
for name, endpoint := range conf.ExecutorConfig.Networks {
if pnic, ok := nets[endpoint.Network.Common.ID]; ok {
// there's already a NIC on this network
endpoint.Common.ID = pnic.Common.ID
d.op.Infof("Network role %q is sharing NIC with %q", name, pnic.Network.Common.Name)
continue
}
moref := new(types.ManagedObjectReference)
if ok := moref.FromString(endpoint.Network.ID); !ok {
return nil, fmt.Errorf("serialized managed object reference in unexpected format: %q", endpoint.Network.ID)
}
obj, err := d.session.Finder.ObjectReference(d.op, *moref)
if err != nil {
return nil, fmt.Errorf("unable to reacquire reference for network %q from serialized form: %q", endpoint.Network.Name, endpoint.Network.ID)
}
network, ok := obj.(object.NetworkReference)
if !ok {
return nil, fmt.Errorf("reacquired reference for network %q, from serialized form %q, was not a network: %T", endpoint.Network.Name, endpoint.Network.ID, obj)
}
backing, err := network.EthernetCardBackingInfo(d.op)
if err != nil {
err = errors.Errorf("Failed to get network backing info for %q: %s", network, err)
return nil, err
}
nic, err := devices.CreateEthernetCard("vmxnet3", backing)
if err != nil {
err = errors.Errorf("Failed to create Ethernet Card spec for %s", err)
return nil, err
}
slot := cspec.AssignSlotNumber(nic, slots)
if slot == constants.NilSlot {
err = errors.Errorf("Failed to assign stable PCI slot for %q network card", name)
}
endpoint.Common.ID = strconv.Itoa(int(slot))
slots[slot] = true
d.op.Debugf("Setting %q to slot %d", name, slot)
devices = append(devices, nic)
nets[endpoint.Network.Common.ID] = endpoint
}
return devices, nil
}
func (d *Dispatcher) addIDEController(devices object.VirtualDeviceList) (object.VirtualDeviceList, error) {
defer trace.End(trace.Begin(""))
// IDE controller
scsi, err := devices.CreateIDEController()
if err != nil {
return nil, err
}
devices = append(devices, scsi)
return devices, nil
}
func (d *Dispatcher) addParaVirtualSCSIController(devices object.VirtualDeviceList) (object.VirtualDeviceList, error) {
defer trace.End(trace.Begin(""))
// para virtual SCSI controller
scsi, err := devices.CreateSCSIController("pvscsi")
if err != nil {
return nil, err
}
devices = append(devices, scsi)
return devices, nil
}
func (d *Dispatcher) createApplianceSpec(conf *config.VirtualContainerHostConfigSpec, vConf *data.InstallerData) (*types.VirtualMachineConfigSpec, error) {
defer trace.End(trace.Begin(""))
var devices object.VirtualDeviceList
var err error
var cpus int32 // appliance number of CPUs
var memory int64 // appliance memory in MB
// set to creating VCH
conf.SetIsCreating(true)
cfg, err := d.encodeConfig(conf)
if err != nil {
return nil, err
}
if vConf.ApplianceSize.CPU.Limit != nil {
cpus = int32(*vConf.ApplianceSize.CPU.Limit)
}
if vConf.ApplianceSize.Memory.Limit != nil {
memory = *vConf.ApplianceSize.Memory.Limit
}
spec := &spec.VirtualMachineConfigSpec{
VirtualMachineConfigSpec: &types.VirtualMachineConfigSpec{
Name: conf.Name,
GuestId: string(types.VirtualMachineGuestOsIdentifierOtherGuest64),
AlternateGuestName: constants.DefaultAltVCHGuestName(),
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", conf.ImageStores[0].Host)},
NumCPUs: cpus,
MemoryMB: memory,
// Encode the config both here and after the VMs created so that it can be identified as a VCH appliance as soon as
// creation is complete.
ExtraConfig: append(vmomi.OptionValueFromMap(cfg, true), &types.OptionValue{Key: "answer.msg.serial.file.open", Value: "Append"}),
},
}
if devices, err = d.addIDEController(devices); err != nil {
return nil, err
}
if devices, err = d.addParaVirtualSCSIController(devices); err != nil {
return nil, err
}
if devices, err = d.addNetworkDevices(conf, spec, devices); err != nil {
return nil, err
}
deviceChange, err := devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)
if err != nil {
return nil, err
}
spec.DeviceChange = deviceChange
return spec.VirtualMachineConfigSpec, nil
}
func isManagedObjectNotFoundError(err error) bool {
if soap.IsSoapFault(err) {
_, ok := soap.ToSoapFault(err).VimFault().(types.ManagedObjectNotFound)
return ok
}
return false
}
func (d *Dispatcher) findApplianceByID(conf *config.VirtualContainerHostConfigSpec) (*vm.VirtualMachine, error) {
defer trace.End(trace.Begin(""))
var err error
var vmm *vm.VirtualMachine
moref := new(types.ManagedObjectReference)
if ok := moref.FromString(conf.ID); !ok {
message := "Failed to get appliance VM mob reference"
d.op.Error(message)
return nil, errors.New(message)
}
ref, err := d.session.Finder.ObjectReference(d.op, *moref)
if err != nil {
if !isManagedObjectNotFoundError(err) {
err = errors.Errorf("Failed to query appliance (%q): %s", moref, err)
return nil, err
}
d.op.Debug("Appliance is not found")
return nil, nil
}
ovm, ok := ref.(*object.VirtualMachine)
if !ok {
d.op.Errorf("Failed to find VM %q: %s", moref, err)
return nil, err
}
vmm = vm.NewVirtualMachine(d.op, d.session, ovm.Reference())
element, err := d.session.Finder.Element(d.op, vmm.Reference())
if err != nil {
return nil, err
}
vmm.SetInventoryPath(element.Path)
return vmm, nil
}
func (d *Dispatcher) configIso(conf *config.VirtualContainerHostConfigSpec, vm *vm.VirtualMachine, settings *data.InstallerData) (object.VirtualDeviceList, error) {
defer trace.End(trace.Begin(""))
var devices object.VirtualDeviceList
var err error
vmDevices, err := vm.Device(d.op)
if err != nil {
d.op.Errorf("Failed to get vm devices for appliance: %s", err)
return nil, err
}
ide, err := vmDevices.FindIDEController("")
if err != nil {
d.op.Errorf("Failed to find IDE controller for appliance: %s", err)
return nil, err
}
cdrom, err := devices.CreateCdrom(ide)
if err != nil {
d.op.Errorf("Failed to create Cdrom device for appliance: %s", err)
return nil, err
}
cdrom = devices.InsertIso(cdrom, fmt.Sprintf("[%s] %s/%s", conf.ImageStores[0].Host, d.vmPathName, settings.ApplianceISO))
devices = append(devices, cdrom)
return devices, nil
}
func (d *Dispatcher) configLogging(conf *config.VirtualContainerHostConfigSpec, vm *vm.VirtualMachine, settings *data.InstallerData) (object.VirtualDeviceList, error) {
defer trace.End(trace.Begin(""))
devices, err := vm.Device(d.op)
if err != nil {
d.op.Errorf("Failed to get vm devices for appliance: %s", err)
return nil, err
}
p, err := devices.CreateSerialPort()
if err != nil {
return nil, err
}
err = vm.AddDevice(d.op, p)
if err != nil {
return nil, err
}
devices, err = vm.Device(d.op)
if err != nil {
d.op.Errorf("Failed to get vm devices for appliance: %s", err)
return nil, err
}
serial, err := devices.FindSerialPort("")
if err != nil {
d.op.Errorf("Failed to locate serial port for persistent log configuration: %s", err)
return nil, err
}
// TODO: we need to add an accessor for generating paths within the VM directory
vmx, err := vm.VMPathName(d.op)
if err != nil {
d.op.Errorf("Unable to determine path of appliance VM: %s", err)
return nil, err
}
// TODO: move this construction into the spec package and update portlayer/logging to use it as well
serial.Backing = &types.VirtualSerialPortFileBackingInfo{
VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
// name consistency with containerVM
FileName: fmt.Sprintf("%s/tether.debug", path.Dir(vmx)),
},
}
return []types.BaseVirtualDevice{serial}, nil
}
func (d *Dispatcher) setDockerPort(conf *config.VirtualContainerHostConfigSpec, settings *data.InstallerData) {
if conf.HostCertificate != nil {
d.DockerPort = fmt.Sprintf("%d", opts.DefaultTLSHTTPPort)
} else {
d.DockerPort = fmt.Sprintf("%d", opts.DefaultHTTPPort)
}
}
func (d *Dispatcher) createAppliance(conf *config.VirtualContainerHostConfigSpec, settings *data.InstallerData) error {
defer trace.End(trace.Begin(""))
d.op.Info("Creating appliance on target")
spec, err := d.createApplianceSpec(conf, settings)
if err != nil {
d.op.Errorf("Unable to create appliance spec: %s", err)
return err
}
// Create the VCH inventory folder
if d.isVC {
d.op.Info("Creating the VCH folder")
// update the session pointer with the VCH Folder
d.session.VCHFolder, err = d.session.VMFolder.CreateFolder(d.op, spec.Name)
if err != nil {
if soap.IsSoapFault(err) {
switch soap.ToSoapFault(err).VimFault().(type) {
case types.DuplicateName:
return fmt.Errorf("The specified VCH name (%s) is already in use", conf.Name)
}
}
return fmt.Errorf("Unable to create the VCH Folder(%s): %s", conf.Name, err)
}
}
d.op.Info("Creating the VCH VM")
info, err := tasks.WaitForResult(d.op, func(ctx context.Context) (tasks.Task, error) {
return d.session.VCHFolder.CreateVM(ctx, *spec, d.vchPool, d.session.Host)
})
if err != nil {
d.op.Errorf("Unable to create the appliance VM: %s", err)
return err
}
if info.Error != nil || info.State != types.TaskInfoStateSuccess {
d.op.Errorf("Create appliance reported: %s", info.Error.LocalizedMessage)
}
if err = d.createVolumeStores(conf); err != nil {
return errors.Errorf("Exiting because we could not create volume stores due to error: %s", err)
}
// get VM reference and save it
moref := info.Result.(types.ManagedObjectReference)
conf.SetMoref(&moref)
obj, err := d.session.Finder.ObjectReference(d.op, moref)
if err != nil {
d.op.Errorf("Failed to reacquire reference to appliance VM after creation: %s", err)
return err
}
gvm, ok := obj.(*object.VirtualMachine)
if !ok {
return fmt.Errorf("Required reference after appliance creation was not for a VM: %T", obj)
}
vm2 := vm.NewVirtualMachineFromVM(d.op, d.session, gvm)
vm2.DisableDestroy(d.op)
// update the displayname to the actual folder name used
if d.vmPathName, err = vm2.DatastoreFolderName(d.op); err != nil {
d.op.Errorf("Failed to get canonical name for appliance: %s", err)
return err
}
d.op.Debugf("vm folder name: %q", d.vmPathName)
d.op.Debugf("vm inventory path: %q", vm2.InventoryPath)
vicadmin := executor.Cmd{
Path: "/sbin/vicadmin",
Args: []string{
"/sbin/vicadmin",
"--dc=" + settings.DatacenterName,
"--pool=" + settings.ResourcePoolPath,
"--cluster=" + settings.ClusterPath,
},
Env: []string{
"PATH=/sbin:/bin",
"GOTRACEBACK=all",
},
Dir: "/home/vicadmin",
}
if settings.HTTPProxy != nil {
vicadmin.Env = append(vicadmin.Env, fmt.Sprintf("%s=%s", config.VICAdminHTTPProxy, settings.HTTPProxy.String()))
}
if settings.HTTPSProxy != nil {
vicadmin.Env = append(vicadmin.Env, fmt.Sprintf("%s=%s", config.VICAdminHTTPSProxy, settings.HTTPSProxy.String()))
}
if settings.NoProxy != nil {
vicadmin.Env = append(vicadmin.Env, fmt.Sprintf("%s=%s", config.VICAdminNoProxy, *settings.NoProxy))
}
conf.AddComponent(config.VicAdminService, &executor.SessionConfig{
User: "vicadmin",
Group: "vicadmin",
Cmd: vicadmin,
Restart: true,
Active: true,
},
)
d.setDockerPort(conf, settings)
personality := executor.Cmd{
Path: "/sbin/docker-engine-server",
Args: []string{
"/sbin/docker-engine-server",
//FIXME: hack during config migration
"-port=" + d.DockerPort,
fmt.Sprintf("-port-layer-port=%d", portLayerPort),
},
Env: []string{
"PATH=/sbin",
"GOTRACEBACK=all",
},
}
if settings.HTTPProxy != nil {
personality.Env = append(personality.Env, fmt.Sprintf("%s=%s", config.GeneralHTTPProxy, settings.HTTPProxy.String()))
}
if settings.HTTPSProxy != nil {
personality.Env = append(personality.Env, fmt.Sprintf("%s=%s", config.GeneralHTTPSProxy, settings.HTTPSProxy.String()))
}
if settings.NoProxy != nil {
personality.Env = append(personality.Env, fmt.Sprintf("%s=%s", config.GeneralNoProxy, *settings.NoProxy))
}
conf.AddComponent(config.PersonaService, &executor.SessionConfig{
// currently needed for iptables interaction
// User: "nobody",
// Group: "nobody",
Cmd: personality,
Restart: true,
Active: true,
},
)
cfg := &executor.SessionConfig{
Cmd: executor.Cmd{
Path: "/sbin/port-layer-server",
Args: []string{
"/sbin/port-layer-server",
"--host=localhost",
fmt.Sprintf("--port=%d", portLayerPort),
},
Env: []string{
//FIXME: hack during config migration
"VC_URL=" + conf.Target,
"DC_PATH=" + settings.DatacenterName,
"CS_PATH=" + settings.ClusterPath,
"POOL_PATH=" + settings.ResourcePoolPath,
"DS_PATH=" + conf.ImageStores[0].Host,
},
},
Restart: true,
Active: true,
}
conf.AddComponent(config.PortLayerService, cfg)
// fix up those parts of the config that depend on the final applianceVM folder name
conf.BootstrapImagePath = fmt.Sprintf("[%s] %s/%s", conf.ImageStores[0].Host, d.vmPathName, settings.BootstrapISO)
if len(conf.ImageStores[0].Path) == 0 {
conf.ImageStores[0].Path = d.vmPathName
}
// apply the fixed-up configuration
spec, err = d.reconfigureApplianceSpec(vm2, conf, settings)
if err != nil {
d.op.Errorf("Error while getting appliance reconfig spec: %s", err)
return err
}
// reconfig
info, err = vm2.WaitForResult(d.op, func(ctx context.Context) (tasks.Task, error) {
return vm2.Reconfigure(ctx, *spec)
})
if err != nil {
d.op.Errorf("Error while setting component parameters to appliance: %s", err)
return err
}
if info.State != types.TaskInfoStateSuccess {
d.op.Errorf("Setting parameters to appliance reported: %s", info.Error.LocalizedMessage)
return err
}
d.appliance = vm2
return nil
}
func (d *Dispatcher) encodeConfig(conf *config.VirtualContainerHostConfigSpec) (map[string]string, error) {
d.op.Debug("generating new config secret key")
s, err := extraconfig.NewSecretKey()
if err != nil {
return nil, err
}
d.secret = s
cfg := make(map[string]string)
extraconfig.Encode(d.secret.Sink(extraconfig.MapSink(cfg)), conf)
return cfg, nil
}
func (d *Dispatcher) decryptVCHConfig(vm *vm.VirtualMachine, cfg map[string]string) (*config.VirtualContainerHostConfigSpec, error) {
defer trace.End(trace.Begin(""))
if d.secret == nil {
name, err := vm.ObjectName(d.op)
if err != nil {
err = errors.Errorf("Failed to get vm name %q: %s", vm.Reference(), err)
return nil, err
}
// set session datastore to where the VM is running
ds, err := d.getImageDatastore(vm, nil, true)
if err != nil {
err = errors.Errorf("Failure finding image store from VCH VM %q: %s", name, err)
return nil, err
}
path, err := vm.DatastoreFolderName(d.op)
if err != nil {
err = errors.Errorf("Failed to get VM %q datastore path: %s", name, err)
return nil, err
}
s, err := d.GuestInfoSecret(name, path, ds)
if err != nil {
return nil, err
}
d.secret = s
}
conf := &config.VirtualContainerHostConfigSpec{}
extraconfig.Decode(d.secret.Source(extraconfig.MapSource(cfg)), conf)
return conf, nil
}
func (d *Dispatcher) reconfigureApplianceSpec(vm *vm.VirtualMachine, conf *config.VirtualContainerHostConfigSpec, settings *data.InstallerData) (*types.VirtualMachineConfigSpec, error) {
defer trace.End(trace.Begin(""))
var devices object.VirtualDeviceList
var err error
spec := &types.VirtualMachineConfigSpec{}
// create new devices
if devices, err = d.configIso(conf, vm, settings); err != nil {
return nil, err
}
newDevices, err := devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)
if err != nil {
d.op.Errorf("Failed to create config spec for appliance: %s", err)
return nil, err
}
spec.DeviceChange = newDevices
// update existing devices
if devices, err = d.configLogging(conf, vm, settings); err != nil {
return nil, err
}
updateDevices, err := devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationEdit)
if err != nil {
d.op.Errorf("Failed to create config spec for logging update: %s", err)
return nil, err
}
spec.DeviceChange = append(spec.DeviceChange, updateDevices...)
cfg, err := d.encodeConfig(conf)
if err != nil {
return nil, err
}
spec.ExtraConfig = append(spec.ExtraConfig, vmomi.OptionValueFromMap(cfg, true)...)
return spec, nil
}
// applianceConfiguration updates the configuration passed in with the latest from the appliance VM.
// there's no guarantee of consistency within the configuration at this time
func (d *Dispatcher) applianceConfiguration(conf *config.VirtualContainerHostConfigSpec) error {
defer trace.End(trace.Begin(""))
extraConfig, err := d.appliance.FetchExtraConfig(d.op)
if err != nil {
return err
}
extraconfig.Decode(extraconfig.MapSource(extraConfig), conf)
return nil
}
// waitForKey squashes the return values and simpy blocks until the key is updated or there is an error
func (d *Dispatcher) waitForKey(key string) {
defer trace.End(trace.Begin(key))
d.appliance.WaitForKeyInExtraConfig(d.op, key)
return
}
// isPortLayerRunning decodes the `docker info` response to check if the portlayer is running
func isPortLayerRunning(op trace.Operation, res *http.Response, conf *config.VirtualContainerHostConfigSpec) bool {
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
op.Debugf("error while reading res body: %s", err.Error())
return false
}
var sysInfo dockertypes.Info
if err = json.Unmarshal(resBody, &sysInfo); err != nil {
op.Debugf("error while unmarshalling res body: %s", err.Error())
return false
}
// At this point the portlayer is up successfully. However, we need to report the Volume Stores that were not created successfully.
volumeStoresLine := ""
for _, value := range sysInfo.SystemStatus {
if value[0] == volumeStoresID {
op.Debugf("Portlayer has established volume stores (%s)", value[1])
volumeStoresLine = value[1]
break
}
}
allVolumeStoresPresent := confirmVolumeStores(op, conf, volumeStoresLine)
if !allVolumeStoresPresent {
op.Error("Not all configured volume stores are online - check port layer log via vicadmin")
}
for _, status := range sysInfo.SystemStatus {
if status[0] == sysInfo.Driver {
return status[1] == "RUNNING"
}
}
return false
}
// confirmVolumeStores is a helper function that will log and warn the vic-machine user if some of their volumestores did not present in the portlayer
func confirmVolumeStores(op trace.Operation, conf *config.VirtualContainerHostConfigSpec, rawVolumeStores string) bool {
establishedVolumeStores := make(map[string]struct{})
splitStores := strings.Split(rawVolumeStores, " ")
for _, v := range splitStores {
establishedVolumeStores[v] = struct{}{}
}
result := true
for k := range conf.VolumeLocations {
if _, ok := establishedVolumeStores[k]; !ok {
op.Errorf("VolumeStore (%s) cannot be brought online - check network, nfs server, and --volume-store configurations", k)
result = false
}
}
return result
}
// CheckDockerAPI checks if the appliance components are initialized by issuing
// `docker info` to the appliance
func (d *Dispatcher) CheckDockerAPI(conf *config.VirtualContainerHostConfigSpec, clientCert *tls.Certificate) error {
defer trace.End(trace.Begin(""))
var (
proto string
client *http.Client
res *http.Response
err error
req *http.Request
tlsErrExpected bool
)
if conf.HostCertificate.IsNil() {
// TLS disabled
proto = "http"
client = &http.Client{}
} else {
// TLS enabled
proto = "https"
// #nosec: TLS InsecureSkipVerify set true
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
// appliance is configured for tlsverify, but we don't have a client certificate
if len(conf.CertificateAuthorities) > 0 {
// if tlsverify was configured at all then we must verify the remote
tr.TLSClientConfig.InsecureSkipVerify = false
func() {
d.op.Debug("Loading CAs for client auth")
pool, err := x509.SystemCertPool()
if err != nil {
d.op.Warn("Unable to load system root certificates - continuing with only the provided CA")
pool = x509.NewCertPool()
}
if !pool.AppendCertsFromPEM(conf.CertificateAuthorities) {
d.op.Warn("Unable add CAs from config to validation pool")
}
// tr.TLSClientConfig.ClientCAs = pool
tr.TLSClientConfig.RootCAs = pool
if clientCert == nil {
// we know this will fail, but we can try to distinguish the expected error vs
// unresponsive endpoint
tlsErrExpected = true
d.op.Debug("CA configured on appliance but no client certificate available")
return
}
cert, err := conf.HostCertificate.X509Certificate()
if err != nil {
d.op.Debug("Unable to extract host certificate: %s", err)
tlsErrExpected = true
return
}
cip := net.ParseIP(d.HostIP)
if err != nil {
d.op.Debug("Unable to process Docker API host address from %q: %s", d.HostIP, err)
tlsErrExpected = true
return
}
// find the name to use and override the IP if found
addr, err := addrToUse(d.op, []net.IP{cip}, cert, conf.CertificateAuthorities)
if err != nil {
d.op.Debug("Unable to determine address to use with remote certificate, checking SANs")
// #nosec: Errors unhandled .
addr, _ = viableHostAddress(d.op, []net.IP{cip}, cert, conf.CertificateAuthorities)
d.op.Debugf("Using host address: %s", addr)
}
if addr != "" {
d.HostIP = addr
} else {
d.op.Debug("Failed to find a viable address for Docker API from certificates")
// Server certificate won't validate since we don't have a hostname
tlsErrExpected = true
}
d.op.Debugf("Host address set to: %q", d.HostIP)
}()
}
if clientCert != nil {
d.op.Debug("Assigning certificates for client auth")
tr.TLSClientConfig.Certificates = []tls.Certificate{*clientCert}
}
client = &http.Client{Transport: tr}
}
dockerInfoURL := fmt.Sprintf("%s://%s:%s/info", proto, d.HostIP, d.DockerPort)
d.op.Debugf("Docker API endpoint: %s", dockerInfoURL)
req, err = http.NewRequest("GET", dockerInfoURL, nil)
if err != nil {