forked from vmware/go-vcloud-director
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvdc.go
1344 lines (1142 loc) · 42.7 KB
/
vdc.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 (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/vmware/go-vcloud-director/v2/types/v56"
"github.com/vmware/go-vcloud-director/v2/util"
)
type Vdc struct {
Vdc *types.Vdc
client *Client
parent organization
}
func NewVdc(cli *Client) *Vdc {
return &Vdc{
Vdc: new(types.Vdc),
client: cli,
}
}
// Gets a vapp with a specific url vappHREF
func (vdc *Vdc) getVdcVAppbyHREF(vappHREF *url.URL) (*VApp, error) {
vapp := NewVApp(vdc.client)
_, err := vdc.client.ExecuteRequest(vappHREF.String(), http.MethodGet,
"", "error retrieving VApp: %s", nil, vapp.VApp)
return vapp, err
}
// Undeploys every vapp in the vdc
func (vdc *Vdc) undeployAllVdcVApps() error {
err := vdc.Refresh()
if err != nil {
return fmt.Errorf("error refreshing vdc: %s", err)
}
for _, resents := range vdc.Vdc.ResourceEntities {
for _, resent := range resents.ResourceEntity {
if resent.Type == "application/vnd.vmware.vcloud.vApp+xml" {
vappHREF, err := url.Parse(resent.HREF)
if err != nil {
return err
}
vapp, err := vdc.getVdcVAppbyHREF(vappHREF)
if err != nil {
return fmt.Errorf("error retrieving vapp with url: %s and with error %s", vappHREF.Path, err)
}
task, err := vapp.Undeploy()
if err != nil {
return err
}
if task == (Task{}) {
continue
}
err = task.WaitTaskCompletion()
if err != nil {
return err
}
}
}
}
return nil
}
// Removes all vapps in the vdc
func (vdc *Vdc) removeAllVdcVApps() error {
err := vdc.Refresh()
if err != nil {
return fmt.Errorf("error refreshing vdc: %s", err)
}
for _, resents := range vdc.Vdc.ResourceEntities {
for _, resent := range resents.ResourceEntity {
if resent.Type == "application/vnd.vmware.vcloud.vApp+xml" {
vappHREF, err := url.Parse(resent.HREF)
if err != nil {
return err
}
vapp, err := vdc.getVdcVAppbyHREF(vappHREF)
if err != nil {
return fmt.Errorf("error retrieving vapp with url: %s and with error %s", vappHREF.Path, err)
}
task, err := vapp.Delete()
if err != nil {
return fmt.Errorf("error deleting vapp: %s", err)
}
err = task.WaitTaskCompletion()
if err != nil {
return fmt.Errorf("couldn't finish removing vapp %s", err)
}
}
}
}
return nil
}
func (vdc *Vdc) Refresh() error {
if vdc.Vdc.HREF == "" {
return fmt.Errorf("cannot refresh, Object is empty")
}
// Empty struct before a new unmarshal, otherwise we end up with duplicate
// elements in slices.
unmarshalledVdc := &types.Vdc{}
_, err := vdc.client.ExecuteRequest(vdc.Vdc.HREF, http.MethodGet,
"", "error refreshing vDC: %s", nil, unmarshalledVdc)
if err != nil {
return err
}
vdc.Vdc = unmarshalledVdc
// The request was successful
return nil
}
// Deletes the vdc, returning an error of the vCD call fails.
// API Documentation: https://code.vmware.com/apis/220/vcloud#/doc/doc/operations/DELETE-Vdc.html
func (vdc *Vdc) Delete(force bool, recursive bool) (Task, error) {
util.Logger.Printf("[TRACE] Vdc.Delete - deleting VDC with force: %t, recursive: %t", force, recursive)
if vdc.Vdc.HREF == "" {
return Task{}, fmt.Errorf("cannot delete, Object is empty")
}
vdcUrl, err := url.ParseRequestURI(vdc.Vdc.HREF)
if err != nil {
return Task{}, fmt.Errorf("error parsing vdc url: %s", err)
}
req := vdc.client.NewRequest(map[string]string{
"force": strconv.FormatBool(force),
"recursive": strconv.FormatBool(recursive),
}, http.MethodDelete, *vdcUrl, nil)
resp, err := checkResp(vdc.client.Http.Do(req))
if err != nil {
return Task{}, fmt.Errorf("error deleting vdc: %s", err)
}
task := NewTask(vdc.client)
if err = decodeBody(types.BodyTypeXML, resp, task.Task); err != nil {
return Task{}, fmt.Errorf("error decoding task response: %s", err)
}
if task.Task.Status == "error" {
return Task{}, fmt.Errorf("vdc not properly destroyed")
}
return *task, nil
}
// Deletes the vdc and waits for the asynchronous task to complete.
func (vdc *Vdc) DeleteWait(force bool, recursive bool) error {
task, err := vdc.Delete(force, recursive)
if err != nil {
return err
}
err = task.WaitTaskCompletion()
if err != nil {
return fmt.Errorf("couldn't finish removing vdc %s", err)
}
return nil
}
// Deprecated: use GetOrgVdcNetworkByName
func (vdc *Vdc) FindVDCNetwork(network string) (OrgVDCNetwork, error) {
err := vdc.Refresh()
if err != nil {
return OrgVDCNetwork{}, fmt.Errorf("error refreshing vdc: %s", err)
}
for _, an := range vdc.Vdc.AvailableNetworks {
for _, reference := range an.Network {
if reference.Name == network {
orgNet := NewOrgVDCNetwork(vdc.client)
_, err := vdc.client.ExecuteRequest(reference.HREF, http.MethodGet,
"", "error retrieving org vdc network: %s", nil, orgNet.OrgVDCNetwork)
// The request was successful
return *orgNet, err
}
}
}
return OrgVDCNetwork{}, fmt.Errorf("can't find VDC Network: %s", network)
}
// GetOrgVdcNetworkByHref returns an Org VDC Network reference if the network HREF matches an existing one.
// If no valid external network is found, it returns a nil Network reference and an error
func (vdc *Vdc) GetOrgVdcNetworkByHref(href string) (*OrgVDCNetwork, error) {
orgNet := NewOrgVDCNetwork(vdc.client)
_, err := vdc.client.ExecuteRequest(href, http.MethodGet,
"", "error retrieving org vdc network: %s", nil, orgNet.OrgVDCNetwork)
// The request was successful
return orgNet, err
}
// GetOrgVdcNetworkByName returns an Org VDC Network reference if the network name matches an existing one.
// If no valid external network is found, it returns a nil Network reference and an error
func (vdc *Vdc) GetOrgVdcNetworkByName(name string, refresh bool) (*OrgVDCNetwork, error) {
if refresh {
err := vdc.Refresh()
if err != nil {
return nil, fmt.Errorf("error refreshing vdc: %s", err)
}
}
for _, an := range vdc.Vdc.AvailableNetworks {
for _, reference := range an.Network {
if reference.Name == name {
return vdc.GetOrgVdcNetworkByHref(reference.HREF)
}
}
}
return nil, ErrorEntityNotFound
}
// GetOrgVdcNetworkById returns an Org VDC Network reference if the network ID matches an existing one.
// If no valid external network is found, it returns a nil Network reference and an error
func (vdc *Vdc) GetOrgVdcNetworkById(id string, refresh bool) (*OrgVDCNetwork, error) {
if refresh {
err := vdc.Refresh()
if err != nil {
return nil, fmt.Errorf("error refreshing vdc: %s", err)
}
}
for _, an := range vdc.Vdc.AvailableNetworks {
for _, reference := range an.Network {
// Some versions of vCD do not return an ID in the network reference
// We use equalIds to overcome this issue
if equalIds(id, reference.ID, reference.HREF) {
return vdc.GetOrgVdcNetworkByHref(reference.HREF)
}
}
}
return nil, ErrorEntityNotFound
}
// GetOrgVdcNetworkByNameOrId returns a VDC Network reference if either the network name or ID matches an existing one.
// If no valid external network is found, it returns a nil ExternalNetwork reference and an error
func (vdc *Vdc) GetOrgVdcNetworkByNameOrId(identifier string, refresh bool) (*OrgVDCNetwork, error) {
getByName := func(name string, refresh bool) (interface{}, error) { return vdc.GetOrgVdcNetworkByName(name, refresh) }
getById := func(id string, refresh bool) (interface{}, error) { return vdc.GetOrgVdcNetworkById(id, refresh) }
entity, err := getEntityByNameOrId(getByName, getById, identifier, false)
if entity == nil {
return nil, err
}
return entity.(*OrgVDCNetwork), err
}
func (vdc *Vdc) FindStorageProfileReference(name string) (types.Reference, error) {
err := vdc.Refresh()
if err != nil {
return types.Reference{}, fmt.Errorf("error refreshing vdc: %s", err)
}
for _, sp := range vdc.Vdc.VdcStorageProfiles.VdcStorageProfile {
if sp.Name == name {
return types.Reference{HREF: sp.HREF, Name: sp.Name, ID: sp.ID}, nil
}
}
return types.Reference{}, fmt.Errorf("can't find any VDC Storage_profiles")
}
// GetDefaultStorageProfileReference should find the default storage profile for a VDC
// Deprecated: unused and implemented in the wrong way. Use adminVdc.GetDefaultStorageProfileReference instead
func (vdc *Vdc) GetDefaultStorageProfileReference(storageprofiles *types.QueryResultRecordsType) (types.Reference, error) {
err := vdc.Refresh()
if err != nil {
return types.Reference{}, fmt.Errorf("error refreshing vdc: %s", err)
}
for _, spr := range storageprofiles.OrgVdcStorageProfileRecord {
if spr.IsDefaultStorageProfile {
return types.Reference{HREF: spr.HREF, Name: spr.Name}, nil
}
}
return types.Reference{}, fmt.Errorf("can't find Default VDC Storage_profile")
}
// Deprecated: use GetEdgeGatewayByName
func (vdc *Vdc) FindEdgeGateway(edgegateway string) (EdgeGateway, error) {
err := vdc.Refresh()
if err != nil {
return EdgeGateway{}, fmt.Errorf("error refreshing vdc: %s", err)
}
for _, av := range vdc.Vdc.Link {
if av.Rel == "edgeGateways" && av.Type == types.MimeQueryRecords {
query := new(types.QueryResultEdgeGatewayRecordsType)
_, err := vdc.client.ExecuteRequest(av.HREF, http.MethodGet,
"", "error querying edge gateways: %s", nil, query)
if err != nil {
return EdgeGateway{}, err
}
var href string
for _, edge := range query.EdgeGatewayRecord {
if edge.Name == edgegateway {
href = edge.HREF
}
}
if href == "" {
return EdgeGateway{}, fmt.Errorf("can't find edge gateway with name: %s", edgegateway)
}
edge := NewEdgeGateway(vdc.client)
_, err = vdc.client.ExecuteRequest(href, http.MethodGet,
"", "error retrieving edge gateway: %s", nil, edge.EdgeGateway)
// TODO - remove this if a solution is found or once 9.7 is deprecated
// vCD 9.7 has a bug and sometimes it fails to retrieve edge gateway with weird error.
// At this point in time the solution is to retry a few times as it does not fail to
// retrieve when retried.
//
// GitHUB issue - https://github.com/vmware/go-vcloud-director/issues/218
if err != nil {
util.Logger.Printf("[DEBUG] vCD 9.7 is known to sometimes respond with error on edge gateway (%s) "+
"retrieval. As a workaround this is done a few times before failing. Retrying: ", edgegateway)
for i := 1; i < 4 && err != nil; i++ {
time.Sleep(200 * time.Millisecond)
util.Logger.Printf("%d ", i)
_, err = vdc.client.ExecuteRequest(href, http.MethodGet,
"", "error retrieving edge gateway: %s", nil, edge.EdgeGateway)
}
util.Logger.Printf("\n")
}
return *edge, err
}
}
return EdgeGateway{}, fmt.Errorf("can't find Edge Gateway")
}
// GetEdgeGatewayByHref retrieves an edge gateway from VDC
// by querying directly its HREF.
// The name passed as parameter is only used for error reporting
func (vdc *Vdc) GetEdgeGatewayByHref(href string) (*EdgeGateway, error) {
if href == "" {
return nil, fmt.Errorf("empty edge gateway HREF")
}
edge := NewEdgeGateway(vdc.client)
_, err := vdc.client.ExecuteRequest(href, http.MethodGet,
"", "error retrieving edge gateway: %s", nil, edge.EdgeGateway)
// TODO - remove this if a solution is found or once 9.7 is deprecated
// vCD 9.7 has a bug and sometimes it fails to retrieve edge gateway with weird error.
// At this point in time the solution is to retry a few times as it does not fail to
// retrieve when retried.
//
// GitHUB issue - https://github.com/vmware/go-vcloud-director/issues/218
if err != nil {
util.Logger.Printf("[DEBUG] vCD 9.7 is known to sometimes respond with error on edge gateway " +
"retrieval. As a workaround this is done a few times before failing. Retrying:")
for i := 1; i < 4 && err != nil; i++ {
time.Sleep(200 * time.Millisecond)
util.Logger.Printf("%d ", i)
_, err = vdc.client.ExecuteRequest(href, http.MethodGet,
"", "error retrieving edge gateway: %s", nil, edge.EdgeGateway)
}
util.Logger.Printf("\n")
}
if err != nil {
return nil, err
}
return edge, nil
}
// QueryEdgeGatewayList returns a list of all the edge gateways in a VDC
func (vdc *Vdc) QueryEdgeGatewayList() ([]*types.QueryResultEdgeGatewayRecordType, error) {
results, err := vdc.client.cumulativeQuery(types.QtEdgeGateway, nil, map[string]string{
"type": types.QtEdgeGateway,
"filter": fmt.Sprintf("orgVdcName==%s", url.QueryEscape(vdc.Vdc.Name)),
"filterEncoded": "true",
})
if err != nil {
return nil, err
}
return results.Results.EdgeGatewayRecord, nil
}
// GetEdgeGatewayRecordsType retrieves a list of edge gateways from VDC
// Deprecated: use QueryEdgeGatewayList instead
func (vdc *Vdc) GetEdgeGatewayRecordsType(refresh bool) (*types.QueryResultEdgeGatewayRecordsType, error) {
items, err := vdc.QueryEdgeGatewayList()
if err != nil {
return nil, fmt.Errorf("error retrieving edge gateway list: %s", err)
}
return &types.QueryResultEdgeGatewayRecordsType{
Total: float64(len(items)),
EdgeGatewayRecord: items,
}, nil
}
// GetEdgeGatewayByName search the VDC list of edge gateways for a given name.
// If the name matches, it returns a pointer to an edge gateway object.
// On failure, it returns a nil object and an error
func (vdc *Vdc) GetEdgeGatewayByName(name string, refresh bool) (*EdgeGateway, error) {
edgeGatewayList, err := vdc.QueryEdgeGatewayList()
if err != nil {
return nil, fmt.Errorf("error retrieving edge gateways list: %s", err)
}
for _, edge := range edgeGatewayList {
if edge.Name == name {
return vdc.GetEdgeGatewayByHref(edge.HREF)
}
}
return nil, ErrorEntityNotFound
}
// GetEdgeGatewayById search VDC list of edge gateways for a given ID.
// If the id matches, it returns a pointer to an edge gateway object.
// On failure, it returns a nil object and an error
func (vdc *Vdc) GetEdgeGatewayById(id string, refresh bool) (*EdgeGateway, error) {
edgeGatewayList, err := vdc.QueryEdgeGatewayList()
if err != nil {
return nil, fmt.Errorf("error retrieving edge gateways list: %s", err)
}
for _, edge := range edgeGatewayList {
if equalIds(id, "", edge.HREF) {
return vdc.GetEdgeGatewayByHref(edge.HREF)
}
}
return nil, ErrorEntityNotFound
}
// GetEdgeGatewayByNameOrId search the VDC list of edge gateways for a given name or ID.
// If the name or the ID match, it returns a pointer to an edge gateway object.
// On failure, it returns a nil object and an error
func (vdc *Vdc) GetEdgeGatewayByNameOrId(identifier string, refresh bool) (*EdgeGateway, error) {
getByName := func(name string, refresh bool) (interface{}, error) { return vdc.GetEdgeGatewayByName(name, refresh) }
getById := func(id string, refresh bool) (interface{}, error) { return vdc.GetEdgeGatewayById(id, refresh) }
entity, err := getEntityByNameOrId(getByName, getById, identifier, false)
if entity == nil {
return nil, err
}
return entity.(*EdgeGateway), err
}
// ComposeRawVApp creates an empty vApp
// Deprecated: use CreateRawVApp instead
func (vdc *Vdc) ComposeRawVApp(name string, description string) error {
vcomp := &types.ComposeVAppParams{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
Deploy: false,
Name: name,
PowerOn: false,
Description: description,
}
vdcHref, err := url.ParseRequestURI(vdc.Vdc.HREF)
if err != nil {
return fmt.Errorf("error getting vdc href: %s", err)
}
vdcHref.Path += "/action/composeVApp"
// This call is wrong: /action/composeVApp returns a vApp, not a task
task, err := vdc.client.ExecuteTaskRequest(vdcHref.String(), http.MethodPost,
types.MimeComposeVappParams, "error instantiating a new vApp:: %s", vcomp)
if err != nil {
return fmt.Errorf("error executing task request: %s", err)
}
err = task.WaitTaskCompletion()
if err != nil {
return fmt.Errorf("error performing task: %s", err)
}
return nil
}
// CreateRawVApp creates an empty vApp
func (vdc *Vdc) CreateRawVApp(name string, description string) (*VApp, error) {
vcomp := &types.ComposeVAppParams{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
Deploy: false,
Name: name,
PowerOn: false,
Description: description,
}
vdcHref, err := url.ParseRequestURI(vdc.Vdc.HREF)
if err != nil {
return nil, fmt.Errorf("error getting vdc href: %s", err)
}
vdcHref.Path += "/action/composeVApp"
var vAppContents types.VApp
_, err = vdc.client.ExecuteRequest(vdcHref.String(), http.MethodPost,
types.MimeComposeVappParams, "error instantiating a new vApp:: %s", vcomp, &vAppContents)
if err != nil {
return nil, fmt.Errorf("error executing task request: %s", err)
}
if vAppContents.Tasks != nil {
for _, innerTask := range vAppContents.Tasks.Task {
if innerTask != nil {
task := NewTask(vdc.client)
task.Task = innerTask
err = task.WaitTaskCompletion()
if err != nil {
return nil, fmt.Errorf("error performing task: %s", err)
}
}
}
}
vapp := NewVApp(vdc.client)
vapp.VApp = &vAppContents
err = vapp.Refresh()
if err != nil {
return nil, err
}
err = vdc.Refresh()
if err != nil {
return nil, err
}
return vapp, nil
}
// ComposeVApp creates a vapp with the given template, name, and description
// that uses the storageprofile and networks given. If you want all eulas
// to be accepted set acceptalleulas to true. Returns a successful task
// if completed successfully, otherwise returns an error and an empty task.
// Deprecated: bad implementation
func (vdc *Vdc) ComposeVApp(orgvdcnetworks []*types.OrgVDCNetwork, vapptemplate VAppTemplate, storageprofileref types.Reference, name string, description string, acceptalleulas bool) (Task, error) {
if vapptemplate.VAppTemplate.Children == nil || orgvdcnetworks == nil {
return Task{}, fmt.Errorf("can't compose a new vApp, objects passed are not valid")
}
// Determine primary network connection index number. We normally depend on it being inherited from vApp template
// but in the case when vApp template does not have network card it would fail on the index being undefined. We
// set the value to 0 (first NIC instead)
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
}
// Build request XML
vcomp := &types.ComposeVAppParams{
Ovf: types.XMLNamespaceOVF,
Xsi: types.XMLNamespaceXSI,
Xmlns: types.XMLNamespaceVCloud,
Deploy: false,
Name: name,
PowerOn: false,
Description: description,
InstantiationParams: &types.InstantiationParams{
NetworkConfigSection: &types.NetworkConfigSection{
Info: "Configuration parameters for logical networks",
},
},
AllEULAsAccepted: acceptalleulas,
SourcedItem: &types.SourcedCompositionItemParam{
Source: &types.Reference{
HREF: vapptemplate.VAppTemplate.Children.VM[0].HREF,
Name: vapptemplate.VAppTemplate.Children.VM[0].Name,
},
InstantiationParams: &types.InstantiationParams{
NetworkConnectionSection: &types.NetworkConnectionSection{
Info: "Network config for sourced item",
PrimaryNetworkConnectionIndex: primaryNetworkConnectionIndex,
},
},
},
}
for index, orgvdcnetwork := range orgvdcnetworks {
vcomp.InstantiationParams.NetworkConfigSection.NetworkConfig = append(vcomp.InstantiationParams.NetworkConfigSection.NetworkConfig,
types.VAppNetworkConfiguration{
NetworkName: orgvdcnetwork.Name,
Configuration: &types.NetworkConfiguration{
FenceMode: types.FenceModeBridged,
ParentNetwork: &types.Reference{
HREF: orgvdcnetwork.HREF,
Name: orgvdcnetwork.Name,
Type: orgvdcnetwork.Type,
},
},
},
)
vcomp.SourcedItem.InstantiationParams.NetworkConnectionSection.NetworkConnection = append(vcomp.SourcedItem.InstantiationParams.NetworkConnectionSection.NetworkConnection,
&types.NetworkConnection{
Network: orgvdcnetwork.Name,
NetworkConnectionIndex: index,
IsConnected: true,
IPAddressAllocationMode: types.IPAllocationModePool,
},
)
vcomp.SourcedItem.NetworkAssignment = append(vcomp.SourcedItem.NetworkAssignment,
&types.NetworkAssignment{
InnerNetwork: orgvdcnetwork.Name,
ContainerNetwork: orgvdcnetwork.Name,
},
)
}
if storageprofileref.HREF != "" {
vcomp.SourcedItem.StorageProfile = &storageprofileref
}
vdcHref, err := url.ParseRequestURI(vdc.Vdc.HREF)
if err != nil {
return Task{}, fmt.Errorf("error getting vdc href: %s", err)
}
vdcHref.Path += "/action/composeVApp"
// Like ComposeRawVApp, this function returns a task, while it should be returning a vApp
// Since we don't use this function in terraform-provider-vcd, we are not going to
// replace it.
return vdc.client.ExecuteTaskRequest(vdcHref.String(), http.MethodPost,
types.MimeComposeVappParams, "error instantiating a new vApp: %s", vcomp)
}
// Deprecated: use vdc.GetVAppByName instead
func (vdc *Vdc) FindVAppByName(vapp string) (VApp, error) {
err := vdc.Refresh()
if err != nil {
return VApp{}, fmt.Errorf("error refreshing vdc: %s", err)
}
for _, resents := range vdc.Vdc.ResourceEntities {
for _, resent := range resents.ResourceEntity {
if resent.Name == vapp && resent.Type == "application/vnd.vmware.vcloud.vApp+xml" {
newVapp := NewVApp(vdc.client)
_, err := vdc.client.ExecuteRequest(resent.HREF, http.MethodGet,
"", "error retrieving vApp: %s", nil, newVapp.VApp)
return *newVapp, err
}
}
}
return VApp{}, fmt.Errorf("can't find vApp: %s", vapp)
}
// Deprecated: use vapp.GetVMByName instead
func (vdc *Vdc) FindVMByName(vapp VApp, vm string) (VM, error) {
err := vdc.Refresh()
if err != nil {
return VM{}, fmt.Errorf("error refreshing vdc: %s", err)
}
err = vapp.Refresh()
if err != nil {
return VM{}, fmt.Errorf("error refreshing vApp: %s", err)
}
//vApp Might Not Have Any VMs
if vapp.VApp.Children == nil {
return VM{}, fmt.Errorf("VApp Has No VMs")
}
util.Logger.Printf("[TRACE] Looking for VM: %s", vm)
for _, child := range vapp.VApp.Children.VM {
util.Logger.Printf("[TRACE] Found: %s", child.Name)
if child.Name == vm {
newVm := NewVM(vdc.client)
_, err := vdc.client.ExecuteRequest(child.HREF, http.MethodGet,
"", "error retrieving vm: %s", nil, newVm.VM)
return *newVm, err
}
}
util.Logger.Printf("[TRACE] Couldn't find VM: %s", vm)
return VM{}, fmt.Errorf("can't find vm: %s", vm)
}
// Find vm using vApp name and VM name. Returns VMRecord query return type
func (vdc *Vdc) QueryVM(vappName, vmName string) (VMRecord, error) {
if vmName == "" {
return VMRecord{}, errors.New("error querying vm name is empty")
}
if vappName == "" {
return VMRecord{}, errors.New("error querying vapp name is empty")
}
typeMedia := "vm"
if vdc.client.IsSysAdmin {
typeMedia = "adminVM"
}
results, err := vdc.QueryWithNotEncodedParams(nil, map[string]string{"type": typeMedia,
"filter": "name==" + url.QueryEscape(vmName) + ";containerName==" + url.QueryEscape(vappName),
"filterEncoded": "true"})
if err != nil {
return VMRecord{}, fmt.Errorf("error querying vm %s", err)
}
vmResults := results.Results.VMRecord
if vdc.client.IsSysAdmin {
vmResults = results.Results.AdminVMRecord
}
newVM := NewVMRecord(vdc.client)
if len(vmResults) == 1 {
newVM.VM = vmResults[0]
} else {
return VMRecord{}, fmt.Errorf("found results %d", len(vmResults))
}
return *newVM, nil
}
// Deprecated: use vdc.GetVAppById instead
func (vdc *Vdc) FindVAppByID(vappid string) (VApp, error) {
// Horrible hack to fetch a vapp with its id.
// urn:vcloud:vapp:00000000-0000-0000-0000-000000000000
err := vdc.Refresh()
if err != nil {
return VApp{}, fmt.Errorf("error refreshing vdc: %s", err)
}
urnslice := strings.SplitAfter(vappid, ":")
urnid := urnslice[len(urnslice)-1]
for _, resents := range vdc.Vdc.ResourceEntities {
for _, resent := range resents.ResourceEntity {
hrefslice := strings.SplitAfter(resent.HREF, "/")
hrefslice = strings.SplitAfter(hrefslice[len(hrefslice)-1], "-")
res := strings.Join(hrefslice[1:], "")
if res == urnid && resent.Type == "application/vnd.vmware.vcloud.vApp+xml" {
newVapp := NewVApp(vdc.client)
_, err := vdc.client.ExecuteRequest(resent.HREF, http.MethodGet,
"", "error retrieving vApp: %s", nil, newVapp.VApp)
return *newVapp, err
}
}
}
return VApp{}, fmt.Errorf("can't find vApp")
}
// FindMediaImage returns media image found in system using `name` as query.
// Can find a few of them if media with same name exist in different catalogs.
// Deprecated: Use catalog.GetMediaByName()
func (vdc *Vdc) FindMediaImage(mediaName string) (MediaItem, error) {
util.Logger.Printf("[TRACE] Querying medias by name\n")
mediaResults, err := queryMediaWithFilter(vdc,
fmt.Sprintf("name==%s", url.QueryEscape(mediaName)))
if err != nil {
return MediaItem{}, err
}
newMediaItem := NewMediaItem(vdc)
if len(mediaResults) == 1 {
newMediaItem.MediaItem = mediaResults[0]
}
if len(mediaResults) == 0 {
return MediaItem{}, nil
}
if len(mediaResults) > 1 {
return MediaItem{}, errors.New("found more than result")
}
util.Logger.Printf("[TRACE] Found media record by name: %#v \n", mediaResults[0])
return *newMediaItem, nil
}
// GetVappByHref returns a vApp reference by running a vCD API call
// If no valid vApp is found, it returns a nil VApp reference and an error
func (vdc *Vdc) GetVAppByHref(vappHref string) (*VApp, error) {
newVapp := NewVApp(vdc.client)
_, err := vdc.client.ExecuteRequest(vappHref, http.MethodGet,
"", "error retrieving vApp: %s", nil, newVapp.VApp)
if err != nil {
return nil, err
}
return newVapp, nil
}
// GetVappByName returns a vApp reference if the vApp Name matches an existing one.
// If no valid vApp is found, it returns a nil VApp reference and an error
func (vdc *Vdc) GetVAppByName(vappName string, refresh bool) (*VApp, error) {
if refresh {
err := vdc.Refresh()
if err != nil {
return nil, fmt.Errorf("error refreshing VDC: %s", err)
}
}
for _, resourceEntities := range vdc.Vdc.ResourceEntities {
for _, resourceReference := range resourceEntities.ResourceEntity {
if resourceReference.Name == vappName && resourceReference.Type == "application/vnd.vmware.vcloud.vApp+xml" {
return vdc.GetVAppByHref(resourceReference.HREF)
}
}
}
return nil, ErrorEntityNotFound
}
// GetVappById returns a vApp reference if the vApp ID matches an existing one.
// If no valid vApp is found, it returns a nil VApp reference and an error
func (vdc *Vdc) GetVAppById(id string, refresh bool) (*VApp, error) {
if refresh {
err := vdc.Refresh()
if err != nil {
return nil, fmt.Errorf("error refreshing VDC: %s", err)
}
}
for _, resourceEntities := range vdc.Vdc.ResourceEntities {
for _, resourceReference := range resourceEntities.ResourceEntity {
if equalIds(id, resourceReference.ID, resourceReference.HREF) {
return vdc.GetVAppByHref(resourceReference.HREF)
}
}
}
return nil, ErrorEntityNotFound
}
// GetVappByNameOrId returns a vApp reference if either the vApp name or ID matches an existing one.
// If no valid vApp is found, it returns a nil VApp reference and an error
func (vdc *Vdc) GetVAppByNameOrId(identifier string, refresh bool) (*VApp, error) {
getByName := func(name string, refresh bool) (interface{}, error) { return vdc.GetVAppByName(name, refresh) }
getById := func(id string, refresh bool) (interface{}, error) { return vdc.GetVAppById(id, refresh) }
entity, err := getEntityByNameOrId(getByName, getById, identifier, false)
if entity == nil {
return nil, err
}
return entity.(*VApp), err
}
// buildNsxvNetworkServiceEndpointURL uses vDC HREF as a base to derive NSX-V based "network
// services" endpoint (eg: https://_hostname_or_ip_/network/services + optionalSuffix)
func (vdc *Vdc) buildNsxvNetworkServiceEndpointURL(optionalSuffix string) (string, error) {
apiEndpoint, err := url.ParseRequestURI(vdc.Vdc.HREF)
if err != nil {
return "", fmt.Errorf("unable to process vDC URL: %s", err)
}
hostname := apiEndpoint.Scheme + "://" + apiEndpoint.Host + "/network/services"
if optionalSuffix != "" {
return hostname + optionalSuffix, nil
}
return hostname, nil
}
// QueryMediaList retrieves a list of media items for the VDC
func (vdc *Vdc) QueryMediaList() ([]*types.MediaRecordType, error) {
return getExistingMedia(vdc)
}
// QueryVappVmTemplate Finds VM template using catalog name, vApp template name, VN name in template.
// Returns types.QueryResultVMRecordType if it finds the VM. Returns ErrorEntityNotFound
// if it's not found. Returns other error if it finds more than one or the search fails.
func (vdc *Vdc) QueryVappVmTemplate(catalogName, vappTemplateName, vmNameInTemplate string) (*types.QueryResultVMRecordType, error) {
queryType := "vm"
if vdc.client.IsSysAdmin {
queryType = "adminVM"
}
// this allows to query deployed and not deployed templates
results, err := vdc.QueryWithNotEncodedParams(nil, map[string]string{"type": queryType,
"filter": "catalogName==" + url.QueryEscape(catalogName) + ";containerName==" + url.QueryEscape(vappTemplateName) + ";name==" + url.QueryEscape(vmNameInTemplate) +
";isVAppTemplate==true;status!=FAILED_CREATION;status!=UNKNOWN;status!=UNRECOGNIZED;status!=UNRESOLVED&links=true;",
"filterEncoded": "true"})
if err != nil {
return nil, fmt.Errorf("error quering all vApp templates: %s", err)
}
vmResults := results.Results.VMRecord
if vdc.client.IsSysAdmin {
vmResults = results.Results.AdminVMRecord
}
if len(vmResults) == 0 {
return nil, fmt.Errorf("[QueryVappVmTemplate] did not find any result with catalog name: %s, "+
"vApp template name: %s, VM name: %s", catalogName, vappTemplateName, vmNameInTemplate)
}
if len(vmResults) > 1 {
return nil, fmt.Errorf("[QueryVappVmTemplate] found more than 1 result: %d with with catalog name: %s, "+
"vApp template name: %s, VM name: %s", len(vmResults), catalogName, vappTemplateName, vmNameInTemplate)
}
return vmResults[0], nil
}
// QueryVappSynchronizedVmTemplate Finds a catalog-synchronized VM inside a vApp Template using catalog name, vApp template name, VN name in template.
// Returns types.QueryResultVMRecordType if it finds the VM and it's synchronized in the catalog. Returns ErrorEntityNotFound
// if it's not found. Returns other error if it finds more than one or the search fails.
func (vdc *Vdc) QueryVappSynchronizedVmTemplate(catalogName, vappTemplateName, vmNameInTemplate string) (*types.QueryResultVMRecordType, error) {
vmRecord, err := vdc.QueryVappVmTemplate(catalogName, vappTemplateName, vmNameInTemplate)
if err != nil {
return nil, err
}
if vmRecord.Status == "LOCAL_COPY_UNAVAILABLE" {
return nil, ErrorEntityNotFound
}
return vmRecord, nil
}
// GetVAppTemplateByName finds a VAppTemplate by Name
// On success, returns a pointer to the VAppTemplate structure and a nil error
// On failure, returns a nil pointer and an error
func (vdc *Vdc) GetVAppTemplateByName(vAppTemplateName string) (*VAppTemplate, error) {
vAppTemplateQueryResult, err := vdc.QueryVappTemplateWithName(vAppTemplateName)
if err != nil {
return nil, err
}
return getVAppTemplateByHref(vdc.client, vAppTemplateQueryResult.HREF)
}
// GetVAppTemplateByNameOrId finds a vApp Template by Name or ID.
// On success, returns a pointer to the VAppTemplate structure and a nil error
// On failure, returns a nil pointer and an error
func (vdc *Vdc) GetVAppTemplateByNameOrId(identifier string, refresh bool) (*VAppTemplate, error) {
getByName := func(name string, refresh bool) (interface{}, error) { return vdc.GetVAppTemplateByName(name) }
getById := func(id string, refresh bool) (interface{}, error) { return getVAppTemplateById(vdc.client, id) }
entity, err := getEntityByNameOrIdSkipNonId(getByName, getById, identifier, refresh)
if entity == nil {
return nil, err
}
return entity.(*VAppTemplate), err
}
// getLinkHref returns a link HREF for a wanted combination of rel and type
func (vdc *Vdc) getLinkHref(rel, linkType string) string {
for _, link := range vdc.Vdc.Link {
if link.Rel == rel && link.Type == linkType {
return link.HREF
}
}
return ""
}
// GetVappList returns the list of vApps for a VDC
func (vdc *Vdc) GetVappList() []*types.ResourceReference {
var list []*types.ResourceReference
for _, resourceEntities := range vdc.Vdc.ResourceEntities {