forked from vmware/go-vcloud-director
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvapp.go
1596 lines (1333 loc) · 55.4 KB
/
vapp.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 2023 VMware, Inc. All rights reserved. Licensed under the Apache v2 License.
*/
package govcd
import (
"encoding/xml"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/vmware/go-vcloud-director/v2/types/v56"
"github.com/vmware/go-vcloud-director/v2/util"
)
type VApp struct {
VApp *types.VApp
client *Client
}
func NewVApp(cli *Client) *VApp {
return &VApp{
VApp: new(types.VApp),
client: cli,
}
}
func (vcdClient *VCDClient) NewVApp(client *Client) VApp {
newvapp := NewVApp(client)
return *newvapp
}
// struct type used to pass information for vApp network creation
type VappNetworkSettings struct {
ID string
Name string
Description string
Gateway string
NetMask string
SubnetPrefixLength string
DNS1 string
DNS2 string
DNSSuffix string
GuestVLANAllowed *bool
StaticIPRanges []*types.IPRange
DhcpSettings *DhcpSettings
RetainIpMacEnabled *bool
VappFenceEnabled *bool
}
// struct type used to pass information for vApp network DHCP
type DhcpSettings struct {
IsEnabled bool
MaxLeaseTime int
DefaultLeaseTime int
IPRange *types.IPRange
}
// Returns the vdc where the vapp resides in.
func (vapp *VApp) getParentVDC() (Vdc, error) {
for _, link := range vapp.VApp.Link {
if (link.Type == types.MimeVDC || link.Type == types.MimeAdminVDC) && link.Rel == "up" {
vdc := NewVdc(vapp.client)
_, err := vapp.client.ExecuteRequest(link.HREF, http.MethodGet,
"", "error retrieving parent vdc: %s", nil, vdc.Vdc)
if err != nil {
return Vdc{}, err
}
parent, err := vdc.getParentOrg()
if err != nil {
return Vdc{}, err
}
vdc.parent = parent
return *vdc, nil
}
}
return Vdc{}, fmt.Errorf("could not find a parent Vdc")
}
func (vapp *VApp) Refresh() error {
if vapp.VApp.HREF == "" {
return fmt.Errorf("cannot refresh, Object is empty")
}
url := vapp.VApp.HREF
// Empty struct before a new unmarshal, otherwise we end up with duplicate
// elements in slices.
vapp.VApp = &types.VApp{}
_, err := vapp.client.ExecuteRequest(url, http.MethodGet,
"", "error refreshing vApp: %s", nil, vapp.VApp)
// The request was successful
return err
}
// AddVM create vm in vApp using vApp template
// orgVdcNetworks - adds org VDC networks to be available for vApp. Can be empty.
// vappNetworkName - adds vApp network to be available for vApp. Can be empty.
// vappTemplate - vApp Template which will be used for VM creation.
// name - name for VM.
// acceptAllEulas - setting allows to automatically accept or not Eulas.
//
// Deprecated: Use vapp.AddNewVM instead for more sophisticated network handling
func (vapp *VApp) AddVM(orgVdcNetworks []*types.OrgVDCNetwork, vappNetworkName string, vappTemplate VAppTemplate, name string, acceptAllEulas bool) (Task, error) {
util.Logger.Printf("[INFO] vapp.AddVM() is deprecated in favor of vapp.AddNewVM()")
if vappTemplate == (VAppTemplate{}) || vappTemplate.VAppTemplate == nil {
return Task{}, fmt.Errorf("vApp Template can not be empty")
}
// primaryNetworkConnectionIndex will be inherited from template or defaulted to 0
// if the template does not have any NICs assigned.
primaryNetworkConnectionIndex := 0
if vappTemplate.VAppTemplate.Children != nil && len(vappTemplate.VAppTemplate.Children.VM) > 0 &&
vappTemplate.VAppTemplate.Children.VM[0].NetworkConnectionSection != nil {
primaryNetworkConnectionIndex = vappTemplate.VAppTemplate.Children.VM[0].NetworkConnectionSection.PrimaryNetworkConnectionIndex
}
networkConnectionSection := types.NetworkConnectionSection{
Info: "Network config for sourced item",
PrimaryNetworkConnectionIndex: primaryNetworkConnectionIndex,
}
for index, orgVdcNetwork := range orgVdcNetworks {
networkConnectionSection.NetworkConnection = append(networkConnectionSection.NetworkConnection,
&types.NetworkConnection{
Network: orgVdcNetwork.Name,
NetworkConnectionIndex: index,
IsConnected: true,
IPAddressAllocationMode: types.IPAllocationModePool,
},
)
}
if vappNetworkName != "" {
networkConnectionSection.NetworkConnection = append(networkConnectionSection.NetworkConnection,
&types.NetworkConnection{
Network: vappNetworkName,
NetworkConnectionIndex: len(orgVdcNetworks),
IsConnected: true,
IPAddressAllocationMode: types.IPAllocationModePool,
},
)
}
return vapp.AddNewVM(name, vappTemplate, &networkConnectionSection, acceptAllEulas)
}
// AddRawVM accepts raw types.ReComposeVAppParams which contains all information for VM creation
func (vapp *VApp) AddRawVM(vAppComposition *types.ReComposeVAppParams) (*VM, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/recomposeVApp"
// Return the task
task, err := vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost, types.MimeRecomposeVappParams, "error instantiating a new VM: %s", vAppComposition)
if err != nil {
return nil, fmt.Errorf("error instantiating a new VM: %s", err)
}
err = task.WaitTaskCompletion()
if err != nil {
return nil, fmt.Errorf("VM creation task failed: %s", err)
}
// VM task does not return any reference to VM therefore it must be looked up by name after
// creation
var vmName string
if vAppComposition.SourcedItem != nil && vAppComposition.SourcedItem.Source != nil {
vmName = vAppComposition.SourcedItem.Source.Name
}
vm, err := vapp.GetVMByName(vmName, true)
if err != nil {
return nil, fmt.Errorf("error finding VM %s in vApp %s after creation: %s", vAppComposition.Name, vapp.VApp.Name, err)
}
return vm, nil
}
// AddNewVM adds VM from vApp template with custom NetworkConnectionSection
func (vapp *VApp) AddNewVM(name string, vappTemplate VAppTemplate, network *types.NetworkConnectionSection, acceptAllEulas bool) (Task, error) {
return vapp.AddNewVMWithStorageProfile(name, vappTemplate, network, nil, acceptAllEulas)
}
// AddNewVMWithStorageProfile adds VM from vApp template with custom NetworkConnectionSection and optional storage profile
func (vapp *VApp) AddNewVMWithStorageProfile(name string, vappTemplate VAppTemplate,
network *types.NetworkConnectionSection,
storageProfileRef *types.Reference, acceptAllEulas bool) (Task, error) {
return addNewVMW(vapp, name, vappTemplate, network, storageProfileRef, nil, acceptAllEulas)
}
// AddNewVMWithComputePolicy adds VM from vApp template with custom NetworkConnectionSection and optional storage profile
// and compute policy
func (vapp *VApp) AddNewVMWithComputePolicy(name string, vappTemplate VAppTemplate,
network *types.NetworkConnectionSection,
storageProfileRef *types.Reference, computePolicy *types.VdcComputePolicy, acceptAllEulas bool) (Task, error) {
return addNewVMW(vapp, name, vappTemplate, network, storageProfileRef, computePolicy, acceptAllEulas)
}
// addNewVMW adds VM from vApp template with custom NetworkConnectionSection and optional storage profile
// and optional compute policy
func addNewVMW(vapp *VApp, name string, vappTemplate VAppTemplate,
network *types.NetworkConnectionSection,
storageProfileRef *types.Reference, computePolicy *types.VdcComputePolicy, acceptAllEulas bool) (Task, error) {
if vappTemplate == (VAppTemplate{}) || vappTemplate.VAppTemplate == nil {
return Task{}, fmt.Errorf("vApp Template can not be empty")
}
templateHref := vappTemplate.VAppTemplate.HREF
if vappTemplate.VAppTemplate.Children != nil && len(vappTemplate.VAppTemplate.Children.VM) != 0 {
templateHref = vappTemplate.VAppTemplate.Children.VM[0].HREF
}
// Status 8 means The object is resolved and powered off.
// https://vdc-repo.vmware.com/vmwb-repository/dcr-public/94b8bd8d-74ff-4fe3-b7a4-41ae31516ed7/1b42f3b5-8b31-4279-8b3f-547f6c7c5aa8/doc/GUID-843BE3AD-5EF6-4442-B864-BCAE44A51867.html
if vappTemplate.VAppTemplate.Status != 8 {
return Task{}, fmt.Errorf("vApp Template shape is not ok (status: %d)", vappTemplate.VAppTemplate.Status)
}
// Validate network config only if it was supplied
if network != nil && network.NetworkConnection != nil {
for _, nic := range network.NetworkConnection {
if nic.Network == "" {
return Task{}, fmt.Errorf("missing mandatory attribute Network: %s", nic.Network)
}
if nic.IPAddressAllocationMode == "" {
return Task{}, fmt.Errorf("missing mandatory attribute IPAddressAllocationMode: %s", nic.IPAddressAllocationMode)
}
}
}
vAppComposition := &types.ReComposeVAppParams{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
Deploy: false,
Name: vapp.VApp.Name,
PowerOn: false,
Description: vapp.VApp.Description,
SourcedItem: &types.SourcedCompositionItemParam{
Source: &types.Reference{
HREF: templateHref,
Name: name,
},
InstantiationParams: &types.InstantiationParams{}, // network config is injected below
},
AllEULAsAccepted: acceptAllEulas,
}
// Add storage profile
if storageProfileRef != nil && storageProfileRef.HREF != "" {
vAppComposition.SourcedItem.StorageProfile = storageProfileRef
}
// Add compute policy
if computePolicy != nil && computePolicy.ID != "" {
vdcComputePolicyHref, err := vapp.client.OpenApiBuildEndpoint(types.OpenApiPathVersion1_0_0, types.OpenApiEndpointVdcComputePolicies, computePolicy.ID)
if err != nil {
return Task{}, fmt.Errorf("error constructing HREF for compute policy")
}
vAppComposition.SourcedItem.ComputePolicy = &types.ComputePolicy{VmSizingPolicy: &types.Reference{HREF: vdcComputePolicyHref.String()}}
}
// Inject network config
vAppComposition.SourcedItem.InstantiationParams.NetworkConnectionSection = network
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/recomposeVApp"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
types.MimeRecomposeVappParams, "error instantiating a new VM: %s", vAppComposition)
}
// ========================= issue#252 ==================================
// TODO: To be refactored, handling networks better. See issue#252 for details
// https://github.com/vmware/go-vcloud-director/issues/252
// ======================================================================
func (vapp *VApp) RemoveVM(vm VM) error {
err := vapp.Refresh()
if err != nil {
return fmt.Errorf("error refreshing vApp before removing VM: %s", err)
}
task := NewTask(vapp.client)
if vapp.VApp.Tasks != nil {
for _, taskItem := range vapp.VApp.Tasks.Task {
task.Task = taskItem
// Leftover tasks may have unhandled errors that can be dismissed at this stage
// we complete any incomplete tasks at this stage, to finish the refresh.
if task.Task.Status != "error" && task.Task.Status != "success" {
err := task.WaitTaskCompletion()
if err != nil {
return fmt.Errorf("error performing task: %s", err)
}
}
}
}
vcomp := &types.ReComposeVAppParams{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
DeleteItem: &types.DeleteItem{
HREF: vm.VM.HREF,
},
}
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/recomposeVApp"
deleteTask, err := vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
types.MimeRecomposeVappParams, "error removing VM: %s", vcomp)
if err != nil {
return err
}
err = deleteTask.WaitTaskCompletion()
if err != nil {
return fmt.Errorf("error performing removing VM task: %s", err)
}
return nil
}
func (vapp *VApp) PowerOn() (Task, error) {
err := vapp.BlockWhileStatus("UNRESOLVED", vapp.client.MaxRetryTimeout)
if err != nil {
return Task{}, fmt.Errorf("error powering on vApp: %s", err)
}
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/powerOn"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error powering on vApp: %s", nil)
}
func (vapp *VApp) PowerOff() (Task, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/powerOff"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error powering off vApp: %s", nil)
}
func (vapp *VApp) Reboot() (Task, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/reboot"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error rebooting vApp: %s", nil)
}
func (vapp *VApp) Reset() (Task, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/reset"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error resetting vApp: %s", nil)
}
// Suspend suspends a vApp
func (vapp *VApp) Suspend() (Task, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/suspend"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error suspending vApp: %s", nil)
}
// DiscardSuspendedState takes back a vApp from suspension
func (vapp *VApp) DiscardSuspendedState() error {
// Status 3 means that the vApp is suspended
if vapp.VApp.Status != 3 {
return nil
}
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/discardSuspendedState"
// Return the task
task, err := vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error discarding suspended state for vApp: %s", nil)
if err != nil {
return err
}
return task.WaitTaskCompletion()
}
func (vapp *VApp) Shutdown() (Task, error) {
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/power/action/shutdown"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
"", "error shutting down vApp: %s", nil)
}
func (vapp *VApp) Undeploy() (Task, error) {
vu := &types.UndeployVAppParams{
Xmlns: types.XMLNamespaceVCloud,
UndeployPowerAction: "powerOff",
}
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/undeploy"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
types.MimeUndeployVappParams, "error undeploy vApp: %s", vu)
}
func (vapp *VApp) Deploy() (Task, error) {
vu := &types.DeployVAppParams{
Xmlns: types.XMLNamespaceVCloud,
PowerOn: false,
}
apiEndpoint := urlParseRequestURI(vapp.VApp.HREF)
apiEndpoint.Path += "/action/deploy"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPost,
types.MimeDeployVappParams, "error deploy vApp: %s", vu)
}
func (vapp *VApp) Delete() (Task, error) {
// Return the task
return vapp.client.ExecuteTaskRequest(vapp.VApp.HREF, http.MethodDelete,
"", "error deleting vApp: %s", nil)
}
func (vapp *VApp) RunCustomizationScript(computername, script string) (Task, error) {
return vapp.Customize(computername, script, false)
}
// Customize applies customization to first child VM
//
// Deprecated: Use vm.SetGuestCustomizationSection()
func (vapp *VApp) Customize(computername, script string, changeSid bool) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
// Check if VApp Children is populated
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
vu := &types.GuestCustomizationSection{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
HREF: vapp.VApp.Children.VM[0].HREF,
Type: types.MimeGuestCustomizationSection,
Info: "Specifies Guest OS Customization Settings",
Enabled: addrOf(true),
ComputerName: computername,
CustomizationScript: script,
ChangeSid: &changeSid,
}
apiEndpoint := urlParseRequestURI(vapp.VApp.Children.VM[0].HREF)
apiEndpoint.Path += "/guestCustomizationSection/"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPut,
types.MimeGuestCustomizationSection, "error customizing VM: %s", vu)
}
func (vapp *VApp) GetStatus() (string, error) {
err := vapp.Refresh()
if err != nil {
return "", fmt.Errorf("error refreshing vApp: %s", err)
}
// Trying to make this function future-proof:
// If a new status is added to a future vCD API and the status map in types.go
// is not updated, we may get a panic.
// Using the ", ok" construct we take control of the data lookup and are able to fail
// gracefully.
statusText, ok := types.VAppStatuses[vapp.VApp.Status]
if ok {
return statusText, nil
}
return "", fmt.Errorf("status %d does not have a description in types.VappStatuses", vapp.VApp.Status)
}
// BlockWhileStatus blocks until the status of vApp exits unwantedStatus.
// It sleeps 200 milliseconds between iterations and times out after timeOutAfterSeconds
// of seconds.
func (vapp *VApp) BlockWhileStatus(unwantedStatus string, timeOutAfterSeconds int) error {
timeoutAfter := time.After(time.Duration(timeOutAfterSeconds) * time.Second)
tick := time.NewTicker(200 * time.Millisecond)
for {
select {
case <-timeoutAfter:
return fmt.Errorf("timed out waiting for vApp to exit state %s after %d seconds",
unwantedStatus, timeOutAfterSeconds)
case <-tick.C:
currentStatus, err := vapp.GetStatus()
if err != nil {
return fmt.Errorf("could not get vApp status %s", err)
}
if currentStatus != unwantedStatus {
return nil
}
}
}
}
func (vapp *VApp) GetNetworkConnectionSection() (*types.NetworkConnectionSection, error) {
networkConnectionSection := &types.NetworkConnectionSection{}
if vapp.VApp.Children.VM[0].HREF == "" {
return networkConnectionSection, fmt.Errorf("cannot refresh, Object is empty")
}
_, err := vapp.client.ExecuteRequest(vapp.VApp.Children.VM[0].HREF+"/networkConnectionSection/", http.MethodGet,
types.MimeNetworkConnectionSection, "error retrieving network connection: %s", nil, networkConnectionSection)
// The request was successful
return networkConnectionSection, err
}
// Sets number of available virtual logical processors
// (i.e. CPUs x cores per socket)
// https://communities.vmware.com/thread/576209
// Deprecated: Use vm.ChangeCPUcount()
func (vapp *VApp) ChangeCPUCount(virtualCpuCount int) (Task, error) {
return vapp.ChangeCPUCountWithCore(virtualCpuCount, nil)
}
// Sets number of available virtual logical processors
// (i.e. CPUs x cores per socket) and cores per socket.
// Socket count is a result of: virtual logical processors/cores per socket
// https://communities.vmware.com/thread/576209
// Deprecated: Use vm.ChangeCPUCountWithCore()
func (vapp *VApp) ChangeCPUCountWithCore(virtualCpuCount int, coresPerSocket *int) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
// Check if VApp Children is populated
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
newcpu := &types.OVFItem{
XmlnsRasd: types.XMLNamespaceRASD,
XmlnsVCloud: types.XMLNamespaceVCloud,
XmlnsXsi: types.XMLNamespaceXSI,
XmlnsVmw: types.XMLNamespaceVMW,
VCloudHREF: vapp.VApp.Children.VM[0].HREF + "/virtualHardwareSection/cpu",
VCloudType: types.MimeRasdItem,
AllocationUnits: "hertz * 10^6",
Description: "Number of Virtual CPUs",
ElementName: strconv.Itoa(virtualCpuCount) + " virtual CPU(s)",
InstanceID: 4,
Reservation: 0,
ResourceType: types.ResourceTypeProcessor,
VirtualQuantity: int64(virtualCpuCount),
Weight: 0,
CoresPerSocket: coresPerSocket,
Link: &types.Link{
HREF: vapp.VApp.Children.VM[0].HREF + "/virtualHardwareSection/cpu",
Rel: "edit",
Type: types.MimeRasdItem,
},
}
apiEndpoint := urlParseRequestURI(vapp.VApp.Children.VM[0].HREF)
apiEndpoint.Path += "/virtualHardwareSection/cpu"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPut,
types.MimeRasdItem, "error changing CPU count: %s", newcpu)
}
func (vapp *VApp) ChangeStorageProfile(name string) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
if vapp.VApp.Children == nil || len(vapp.VApp.Children.VM) == 0 {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
vdc, err := vapp.getParentVDC()
if err != nil {
return Task{}, fmt.Errorf("error retrieving parent VDC for vApp %s", vapp.VApp.Name)
}
storageProfileRef, err := vdc.FindStorageProfileReference(name)
if err != nil {
return Task{}, fmt.Errorf("error retrieving storage profile %s for vApp %s", name, vapp.VApp.Name)
}
newProfile := &types.Vm{
Name: vapp.VApp.Children.VM[0].Name,
StorageProfile: &storageProfileRef,
Xmlns: types.XMLNamespaceVCloud,
}
// Return the task
return vapp.client.ExecuteTaskRequest(vapp.VApp.Children.VM[0].HREF, http.MethodPut,
types.MimeVM, "error changing CPU count: %s", newProfile)
}
// Deprecated as it changes only first VM's name
func (vapp *VApp) ChangeVMName(name string) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
newName := &types.Vm{
Name: name,
Xmlns: types.XMLNamespaceVCloud,
}
// Return the task
return vapp.client.ExecuteTaskRequest(vapp.VApp.Children.VM[0].HREF, http.MethodPut,
types.MimeVM, "error changing VM name: %s", newName)
}
// SetOvf sets guest properties for the first child VM in vApp
//
// Deprecated: Use vm.SetProductSectionList()
func (vapp *VApp) SetOvf(parameters map[string]string) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
if vapp.VApp.Children.VM[0].ProductSection == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children with ProductSection, interrupting customization")
}
for key, value := range parameters {
for _, ovf_value := range vapp.VApp.Children.VM[0].ProductSection.Property {
if ovf_value.Key == key {
ovf_value.Value = &types.Value{Value: value}
break
}
}
}
ovf := &types.ProductSectionList{
Xmlns: types.XMLNamespaceVCloud,
Ovf: types.XMLNamespaceOVF,
ProductSection: vapp.VApp.Children.VM[0].ProductSection,
}
apiEndpoint := urlParseRequestURI(vapp.VApp.Children.VM[0].HREF)
apiEndpoint.Path += "/productSections"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPut,
types.MimeProductSection, "error setting ovf: %s", ovf)
}
func (vapp *VApp) ChangeNetworkConfig(networks []map[string]interface{}, ip string) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing VM before running customization: %s", err)
}
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
networksection, err := vapp.GetNetworkConnectionSection()
if err != nil {
return Task{}, err
}
for index, network := range networks {
// Determine what type of address is requested for the vApp
ipAllocationMode := types.IPAllocationModeNone
ipAddress := "Any"
// TODO: Review current behaviour of using DHCP when left blank
if ip == "" || ip == "dhcp" || network["ip"] == "dhcp" {
ipAllocationMode = types.IPAllocationModeDHCP
} else if ip == "allocated" || network["ip"] == "allocated" {
ipAllocationMode = types.IPAllocationModePool
} else if ip == "none" || network["ip"] == "none" {
ipAllocationMode = types.IPAllocationModeNone
} else if ip != "" || network["ip"] != "" {
ipAllocationMode = types.IPAllocationModeManual
// TODO: Check a valid IP has been given
ipAddress = ip
}
util.Logger.Printf("[DEBUG] Function ChangeNetworkConfig() for %s invoked", network["orgnetwork"])
networksection.Xmlns = types.XMLNamespaceVCloud
networksection.Ovf = types.XMLNamespaceOVF
networksection.Info = "Specifies the available VM network connections"
networksection.NetworkConnection[index].NeedsCustomization = true
networksection.NetworkConnection[index].IPAddress = ipAddress
networksection.NetworkConnection[index].IPAddressAllocationMode = ipAllocationMode
networksection.NetworkConnection[index].MACAddress = ""
if network["is_primary"] == true {
networksection.PrimaryNetworkConnectionIndex = index
}
}
apiEndpoint := urlParseRequestURI(vapp.VApp.Children.VM[0].HREF)
apiEndpoint.Path += "/networkConnectionSection/"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPut,
types.MimeNetworkConnectionSection, "error changing network config: %s", networksection)
}
// Deprecated as it changes only first VM's memory
func (vapp *VApp) ChangeMemorySize(size int) (Task, error) {
err := vapp.Refresh()
if err != nil {
return Task{}, fmt.Errorf("error refreshing vApp before running customization: %s", err)
}
// Check if VApp Children is populated
if vapp.VApp.Children == nil {
return Task{}, fmt.Errorf("vApp doesn't contain any children, interrupting customization")
}
newMem := &types.OVFItem{
XmlnsRasd: types.XMLNamespaceRASD,
XmlnsVCloud: types.XMLNamespaceVCloud,
XmlnsXsi: types.XMLNamespaceXSI,
VCloudHREF: vapp.VApp.Children.VM[0].HREF + "/virtualHardwareSection/memory",
VCloudType: types.MimeRasdItem,
AllocationUnits: "byte * 2^20",
Description: "Memory Size",
ElementName: strconv.Itoa(size) + " MB of memory",
InstanceID: 5,
Reservation: 0,
ResourceType: types.ResourceTypeMemory,
VirtualQuantity: int64(size),
Weight: 0,
Link: &types.Link{
HREF: vapp.VApp.Children.VM[0].HREF + "/virtualHardwareSection/memory",
Rel: "edit",
Type: types.MimeRasdItem,
},
}
apiEndpoint := urlParseRequestURI(vapp.VApp.Children.VM[0].HREF)
apiEndpoint.Path += "/virtualHardwareSection/memory"
// Return the task
return vapp.client.ExecuteTaskRequest(apiEndpoint.String(), http.MethodPut,
types.MimeRasdItem, "error changing memory size: %s", newMem)
}
func (vapp *VApp) GetNetworkConfig() (*types.NetworkConfigSection, error) {
networkConfig := &types.NetworkConfigSection{}
if vapp.VApp.HREF == "" {
return networkConfig, fmt.Errorf("cannot refresh, Object is empty")
}
_, err := vapp.client.ExecuteRequest(vapp.VApp.HREF+"/networkConfigSection/", http.MethodGet,
types.MimeNetworkConfigSection, "error retrieving network config: %s", nil, networkConfig)
// The request was successful
return networkConfig, err
}
// AddRAWNetworkConfig adds existing VDC network to vApp
// Deprecated: in favor of vapp.AddOrgNetwork
func (vapp *VApp) AddRAWNetworkConfig(orgvdcnetworks []*types.OrgVDCNetwork) (Task, error) {
vAppNetworkConfig, err := vapp.GetNetworkConfig()
if err != nil {
return Task{}, fmt.Errorf("error getting vApp networks: %s", err)
}
networkConfigurations := vAppNetworkConfig.NetworkConfig
for _, network := range orgvdcnetworks {
networkConfigurations = append(networkConfigurations,
types.VAppNetworkConfiguration{
NetworkName: network.Name,
Configuration: &types.NetworkConfiguration{
ParentNetwork: &types.Reference{
HREF: network.HREF,
},
FenceMode: types.FenceModeBridged,
},
},
)
}
return updateNetworkConfigurations(vapp, networkConfigurations)
}
// Function allows to create isolated network for vApp. This is equivalent to vCD UI function - vApp network creation.
// Deprecated: in favor of vapp.CreateVappNetwork
func (vapp *VApp) AddIsolatedNetwork(newIsolatedNetworkSettings *VappNetworkSettings) (Task, error) {
err := validateNetworkConfigSettings(newIsolatedNetworkSettings)
if err != nil {
return Task{}, err
}
// for case when range is one ip address
if newIsolatedNetworkSettings.DhcpSettings != nil && newIsolatedNetworkSettings.DhcpSettings.IPRange != nil && newIsolatedNetworkSettings.DhcpSettings.IPRange.EndAddress == "" {
newIsolatedNetworkSettings.DhcpSettings.IPRange.EndAddress = newIsolatedNetworkSettings.DhcpSettings.IPRange.StartAddress
}
// only add values if available. Won't be send to API if not provided
var networkFeatures *types.NetworkFeatures
if newIsolatedNetworkSettings.DhcpSettings != nil {
networkFeatures = &types.NetworkFeatures{DhcpService: &types.DhcpService{
IsEnabled: newIsolatedNetworkSettings.DhcpSettings.IsEnabled,
DefaultLeaseTime: newIsolatedNetworkSettings.DhcpSettings.DefaultLeaseTime,
MaxLeaseTime: newIsolatedNetworkSettings.DhcpSettings.MaxLeaseTime,
IPRange: newIsolatedNetworkSettings.DhcpSettings.IPRange}}
}
networkConfigurations := vapp.VApp.NetworkConfigSection.NetworkConfig
networkConfigurations = append(networkConfigurations,
types.VAppNetworkConfiguration{
NetworkName: newIsolatedNetworkSettings.Name,
Description: newIsolatedNetworkSettings.Description,
Configuration: &types.NetworkConfiguration{
FenceMode: types.FenceModeIsolated,
GuestVlanAllowed: newIsolatedNetworkSettings.GuestVLANAllowed,
Features: networkFeatures,
IPScopes: &types.IPScopes{IPScope: []*types.IPScope{&types.IPScope{IsInherited: false, Gateway: newIsolatedNetworkSettings.Gateway,
Netmask: newIsolatedNetworkSettings.NetMask, DNS1: newIsolatedNetworkSettings.DNS1,
DNS2: newIsolatedNetworkSettings.DNS2, DNSSuffix: newIsolatedNetworkSettings.DNSSuffix, IsEnabled: true,
IPRanges: &types.IPRanges{IPRange: newIsolatedNetworkSettings.StaticIPRanges}}}},
},
IsDeployed: false,
})
return updateNetworkConfigurations(vapp, networkConfigurations)
}
// CreateVappNetwork creates isolated or nat routed(connected to Org VDC network) network for vApp.
// Returns pointer to types.NetworkConfigSection or error
// If orgNetwork is nil, then isolated network created.
func (vapp *VApp) CreateVappNetwork(newNetworkSettings *VappNetworkSettings, orgNetwork *types.OrgVDCNetwork) (*types.NetworkConfigSection, error) {
task, err := vapp.CreateVappNetworkAsync(newNetworkSettings, orgNetwork)
if err != nil {
return nil, err
}
err = task.WaitTaskCompletion()
if err != nil {
return nil, fmt.Errorf("%s", combinedTaskErrorMessage(task.Task, err))
}
vAppNetworkConfig, err := vapp.GetNetworkConfig()
if err != nil {
return nil, fmt.Errorf("error getting vApp networks: %#v", err)
}
return vAppNetworkConfig, nil
}
// CreateVappNetworkAsync creates asynchronously isolated or nat routed network for vApp. Returns Task or error
// If orgNetwork is nil, then isolated network created.
func (vapp *VApp) CreateVappNetworkAsync(newNetworkSettings *VappNetworkSettings, orgNetwork *types.OrgVDCNetwork) (Task, error) {
err := validateNetworkConfigSettings(newNetworkSettings)
if err != nil {
return Task{}, err
}
// for case when range is one ip address
if newNetworkSettings.DhcpSettings != nil && newNetworkSettings.DhcpSettings.IPRange != nil && newNetworkSettings.DhcpSettings.IPRange.EndAddress == "" {
newNetworkSettings.DhcpSettings.IPRange.EndAddress = newNetworkSettings.DhcpSettings.IPRange.StartAddress
}
// only add values if available. Won't be send to API if not provided
var networkFeatures *types.NetworkFeatures
if newNetworkSettings.DhcpSettings != nil {
networkFeatures = &types.NetworkFeatures{DhcpService: &types.DhcpService{
IsEnabled: newNetworkSettings.DhcpSettings.IsEnabled,
DefaultLeaseTime: newNetworkSettings.DhcpSettings.DefaultLeaseTime,
MaxLeaseTime: newNetworkSettings.DhcpSettings.MaxLeaseTime,
IPRange: newNetworkSettings.DhcpSettings.IPRange},
}
}
networkConfigurations := vapp.VApp.NetworkConfigSection.NetworkConfig
vappConfiguration := types.VAppNetworkConfiguration{
NetworkName: newNetworkSettings.Name,
Description: newNetworkSettings.Description,
Configuration: &types.NetworkConfiguration{
FenceMode: types.FenceModeIsolated,
GuestVlanAllowed: newNetworkSettings.GuestVLANAllowed,
Features: networkFeatures,
IPScopes: &types.IPScopes{
IPScope: []*types.IPScope{{
IsInherited: false,
Gateway: newNetworkSettings.Gateway,
Netmask: newNetworkSettings.NetMask,
SubnetPrefixLength: newNetworkSettings.SubnetPrefixLength,
DNS1: newNetworkSettings.DNS1,
DNS2: newNetworkSettings.DNS2,
DNSSuffix: newNetworkSettings.DNSSuffix,
IsEnabled: true,
IPRanges: &types.IPRanges{IPRange: newNetworkSettings.StaticIPRanges}}}},
RetainNetInfoAcrossDeployments: newNetworkSettings.RetainIpMacEnabled,
},
IsDeployed: false,
}
if orgNetwork != nil {
vappConfiguration.Configuration.ParentNetwork = &types.Reference{
HREF: orgNetwork.HREF,
}
vappConfiguration.Configuration.FenceMode = types.FenceModeNAT
}
networkConfigurations = append(networkConfigurations,
vappConfiguration)
return updateNetworkConfigurations(vapp, networkConfigurations)
}
// AddOrgNetwork adds Org VDC network as vApp network.
// Returns pointer to types.NetworkConfigSection or error
func (vapp *VApp) AddOrgNetwork(newNetworkSettings *VappNetworkSettings, orgNetwork *types.OrgVDCNetwork, isFenced bool) (*types.NetworkConfigSection, error) {
task, err := vapp.AddOrgNetworkAsync(newNetworkSettings, orgNetwork, isFenced)
if err != nil {
return nil, err
}
err = task.WaitTaskCompletion()
if err != nil {
return nil, fmt.Errorf("%s", combinedTaskErrorMessage(task.Task, err))
}
vAppNetworkConfig, err := vapp.GetNetworkConfig()
if err != nil {
return nil, fmt.Errorf("error getting vApp networks: %#v", err)
}
return vAppNetworkConfig, nil
}
// AddOrgNetworkAsync adds asynchronously Org VDC network as vApp network. Returns Task or error
func (vapp *VApp) AddOrgNetworkAsync(newNetworkSettings *VappNetworkSettings, orgNetwork *types.OrgVDCNetwork, isFenced bool) (Task, error) {
if orgNetwork == nil {
return Task{}, errors.New("org VDC network is missing")
}
fenceMode := types.FenceModeBridged
if isFenced {