forked from vmware/go-vcloud-director
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_vcd_test.go
2119 lines (1906 loc) · 73.4 KB
/
api_vcd_test.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
//go:build api || openapi || functional || catalog || vapp || gateway || network || org || query || extnetwork || task || vm || vdc || system || disk || lb || lbAppRule || lbAppProfile || lbServerPool || lbServiceMonitor || lbVirtualServer || user || search || nsxv || nsxt || auth || affinity || role || alb || certificate || vdcGroup || metadata || providervdc || rde || vsphere || uiPlugin || cse || ALL
/*
* Copyright 2022 VMware, Inc. All rights reserved. Licensed under the Apache v2 License.
*/
package govcd
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"gopkg.in/yaml.v2"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"testing"
"time"
. "gopkg.in/check.v1"
"github.com/vmware/go-vcloud-director/v2/types/v56"
"github.com/vmware/go-vcloud-director/v2/util"
)
func init() {
testingTags["api"] = "api_vcd_test.go"
// To list the flags when we run "go test -tags functional -vcd-help", the flag name must start with "vcd"
// They will all appear alongside the native flags when we use an invalid one
setBoolFlag(&vcdHelp, "vcd-help", "VCD_HELP", "Show vcd flags")
setBoolFlag(&enableDebug, "vcd-debug", "GOVCD_DEBUG", "enables debug output")
setBoolFlag(&testVerbose, "vcd-verbose", "GOVCD_TEST_VERBOSE", "enables verbose output")
setBoolFlag(&skipVappCreation, "vcd-skip-vapp-creation", "GOVCD_SKIP_VAPP_CREATION", "Skips vApp creation")
setBoolFlag(&ignoreCleanupFile, "vcd-ignore-cleanup-file", "GOVCD_IGNORE_CLEANUP_FILE", "Does not process previous cleanup file")
setBoolFlag(&debugShowRequestEnabled, "vcd-show-request", "GOVCD_SHOW_REQ", "Shows API request")
setBoolFlag(&debugShowResponseEnabled, "vcd-show-response", "GOVCD_SHOW_RESP", "Shows API response")
setBoolFlag(&connectAsOrgUser, "vcd-as-org-user", "VCD_TEST_ORG_USER", "Connect as Org user")
setBoolFlag(&connectAsOrgUser, "vcd-test-org-user", "VCD_TEST_ORG_USER", "Connect as Org user")
flag.IntVar(&connectTenantNum, "vcd-connect-tenant", connectTenantNum, "change index of tenant to use (0=first)")
}
const (
// Names for entities created by the tests
TestCreateOrg = "TestCreateOrg"
TestDeleteOrg = "TestDeleteOrg"
TestUpdateOrg = "TestUpdateOrg"
TestCreateCatalog = "TestCreateCatalog"
TestCreateCatalogDesc = "Catalog created by tests"
TestRefreshOrgFullName = "TestRefreshOrgFullName"
TestUpdateCatalog = "TestUpdateCatalog"
TestDeleteCatalog = "TestDeleteCatalog"
TestRefreshOrg = "TestRefreshOrg"
TestComposeVapp = "TestComposeVapp"
TestComposeVappDesc = "vApp created by tests"
TestSetUpSuite = "TestSetUpSuite"
TestUploadOvf = "TestUploadOvf"
TestDeleteCatalogItem = "TestDeleteCatalogItem"
TestCreateOrgVdc = "TestCreateOrgVdc"
TestRefreshOrgVdc = "TestRefreshOrgVdc"
TestCreateOrgVdcNetworkRouted = "TestCreateOrgVdcNetworkRouted"
TestCreateOrgVdcNetworkDhcp = "TestCreateOrgVdcNetworkDhcp"
TestCreateOrgVdcNetworkIso = "TestCreateOrgVdcNetworkIso"
TestCreateOrgVdcNetworkDirect = "TestCreateOrgVdcNetworkDirect"
TestUploadMedia = "TestUploadMedia"
TestCatalogUploadMedia = "TestCatalogUploadMedia"
TestCreateDisk = "TestCreateDisk"
TestUpdateDisk = "TestUpdateDisk"
TestDeleteDisk = "TestDeleteDisk"
TestRefreshDisk = "TestRefreshDisk"
TestAttachedVMDisk = "TestAttachedVMDisk"
TestVdcFindDiskByHREF = "TestVdcFindDiskByHREF"
TestFindDiskByHREF = "TestFindDiskByHREF"
TestDisk = "TestDisk"
// #nosec G101 -- Not a credential
TestVMAttachOrDetachDisk = "TestVMAttachOrDetachDisk"
TestVMAttachDisk = "TestVMAttachDisk"
TestVMDetachDisk = "TestVMDetachDisk"
TestCreateExternalNetwork = "TestCreateExternalNetwork"
TestDeleteExternalNetwork = "TestDeleteExternalNetwork"
TestLbServiceMonitor = "TestLbServiceMonitor"
TestLbServerPool = "TestLbServerPool"
TestLbAppProfile = "TestLbAppProfile"
TestLbAppRule = "TestLbAppRule"
TestLbVirtualServer = "TestLbVirtualServer"
TestLb = "TestLb"
TestNsxvSnatRule = "TestNsxvSnatRule"
TestNsxvDnatRule = "TestNsxvDnatRule"
)
const (
TestRequiresSysAdminPrivileges = "Test %s requires system administrator privileges"
)
type Tenant struct {
User string `yaml:"user,omitempty"`
Password string `yaml:"password,omitempty"`
Token string `yaml:"token,omitempty"`
ApiToken string `yaml:"api_token,omitempty"`
SysOrg string `yaml:"sysOrg,omitempty"`
}
// Struct to get info from a config yaml file that the user
// specifies
type TestConfig struct {
Provider struct {
User string `yaml:"user"`
Password string `yaml:"password"`
Token string `yaml:"token"`
ApiToken string `yaml:"api_token"`
VcdVersion string `yaml:"vcdVersion,omitempty"`
ApiVersion string `yaml:"apiVersion,omitempty"`
// UseSamlAdfs specifies if SAML auth is used for authenticating vCD instead of local login.
// The above `User` and `Password` will be used to authenticate against ADFS IdP when true.
UseSamlAdfs bool `yaml:"useSamlAdfs"`
// CustomAdfsRptId allows to set custom Relaying Party Trust identifier if needed. Only has
// effect if `UseSamlAdfs` is true.
CustomAdfsRptId string `yaml:"customAdfsRptId"`
// The variables `SamlUser`, `SamlPassword` and `SamlCustomRptId` are optional and are
// related to an additional test run specifically with SAML user/password. It is useful in
// case local user is used for test run (defined by above 'User', 'Password' variables).
// SamlUser takes ADFS friendly format ('contoso.com\username' or 'username@contoso.com')
SamlUser string `yaml:"samlUser,omitempty"`
SamlPassword string `yaml:"samlPassword,omitempty"`
SamlCustomRptId string `yaml:"samlCustomRptId,omitempty"`
Url string `yaml:"url"`
SysOrg string `yaml:"sysOrg"`
MaxRetryTimeout int `yaml:"maxRetryTimeout,omitempty"`
HttpTimeout int64 `yaml:"httpTimeout,omitempty"`
}
Tenants []Tenant `yaml:"tenants,omitempty"`
VCD struct {
Org string `yaml:"org"`
Vdc string `yaml:"vdc"`
ProviderVdc struct {
Name string `yaml:"name"`
StorageProfile string `yaml:"storage_profile"`
NetworkPool string `yaml:"network_pool"`
} `yaml:"provider_vdc"`
NsxtProviderVdc struct {
Name string `yaml:"name"`
StorageProfile string `yaml:"storage_profile"`
StorageProfile2 string `yaml:"storage_profile_2"`
NetworkPool string `yaml:"network_pool"`
PlacementPolicyVmGroup string `yaml:"placementPolicyVmGroup,omitempty"`
} `yaml:"nsxt_provider_vdc"`
Catalog struct {
Name string `yaml:"name,omitempty"`
NsxtBackedCatalogName string `yaml:"nsxtBackedCatalogName,omitempty"`
Description string `yaml:"description,omitempty"`
CatalogItem string `yaml:"catalogItem,omitempty"`
CatalogItemWithEfiSupport string `yaml:"catalogItemWithEfiSupport,omitempty"`
NsxtCatalogItem string `yaml:"nsxtCatalogItem,omitempty"`
CatalogItemDescription string `yaml:"catalogItemDescription,omitempty"`
CatalogItemWithMultiVms string `yaml:"catalogItemWithMultiVms,omitempty"`
VmNameInMultiVmItem string `yaml:"vmNameInMultiVmItem,omitempty"`
} `yaml:"catalog"`
Network struct {
Net1 string `yaml:"network1"`
Net2 string `yaml:"network2,omitempty"`
} `yaml:"network"`
StorageProfile struct {
SP1 string `yaml:"storageProfile1"`
SP2 string `yaml:"storageProfile2,omitempty"`
} `yaml:"storageProfile"`
ExternalIp string `yaml:"externalIp,omitempty"`
ExternalNetmask string `yaml:"externalNetmask,omitempty"`
InternalIp string `yaml:"internalIp,omitempty"`
InternalNetmask string `yaml:"internalNetmask,omitempty"`
EdgeGateway string `yaml:"edgeGateway,omitempty"`
ExternalNetwork string `yaml:"externalNetwork,omitempty"`
ExternalNetworkPortGroup string `yaml:"externalNetworkPortGroup,omitempty"`
ExternalNetworkPortGroupType string `yaml:"externalNetworkPortGroupType,omitempty"`
VimServer string `yaml:"vimServer,omitempty"`
LdapServer string `yaml:"ldapServer,omitempty"`
Nsxt struct {
Manager string `yaml:"manager"`
Tier0router string `yaml:"tier0router"`
Tier0routerVrf string `yaml:"tier0routerVrf"`
NsxtDvpg string `yaml:"nsxtDvpg"`
GatewayQosProfile string `yaml:"gatewayQosProfile"`
Vdc string `yaml:"vdc"`
ExternalNetwork string `yaml:"externalNetwork"`
EdgeGateway string `yaml:"edgeGateway"`
NsxtImportSegment string `yaml:"nsxtImportSegment"`
NsxtImportSegment2 string `yaml:"nsxtImportSegment2"`
VdcGroup string `yaml:"vdcGroup"`
VdcGroupEdgeGateway string `yaml:"vdcGroupEdgeGateway"`
NsxtEdgeCluster string `yaml:"nsxtEdgeCluster"`
RoutedNetwork string `yaml:"routedNetwork"`
NsxtAlbControllerUrl string `yaml:"nsxtAlbControllerUrl"`
NsxtAlbControllerUser string `yaml:"nsxtAlbControllerUser"`
NsxtAlbControllerPassword string `yaml:"nsxtAlbControllerPassword"`
NsxtAlbImportableCloud string `yaml:"nsxtAlbImportableCloud"`
NsxtAlbServiceEngineGroup string `yaml:"nsxtAlbServiceEngineGroup"`
IpDiscoveryProfile string `yaml:"ipDiscoveryProfile"`
MacDiscoveryProfile string `yaml:"macDiscoveryProfile"`
SpoofGuardProfile string `yaml:"spoofGuardProfile"`
QosProfile string `yaml:"qosProfile"`
SegmentSecurityProfile string `yaml:"segmentSecurityProfile"`
} `yaml:"nsxt"`
} `yaml:"vcd"`
Vsphere struct {
ResourcePoolForVcd1 string `yaml:"resourcePoolForVcd1,omitempty"`
ResourcePoolForVcd2 string `yaml:"resourcePoolForVcd2,omitempty"`
} `yaml:"vsphere,omitempty"`
Logging struct {
Enabled bool `yaml:"enabled,omitempty"`
LogFileName string `yaml:"logFileName,omitempty"`
LogHttpRequest bool `yaml:"logHttpRequest,omitempty"`
LogHttpResponse bool `yaml:"logHttpResponse,omitempty"`
SkipResponseTags string `yaml:"skipResponseTags,omitempty"`
ApiLogFunctions string `yaml:"apiLogFunctions,omitempty"`
VerboseCleanup bool `yaml:"verboseCleanup,omitempty"`
} `yaml:"logging"`
OVA struct {
OvaPath string `yaml:"ovaPath,omitempty"`
OvaChunkedPath string `yaml:"ovaChunkedPath,omitempty"`
OvaMultiVmPath string `yaml:"ovaMultiVmPath,omitempty"`
OvaWithoutSizePath string `yaml:"ovaWithoutSizePath,omitempty"`
OvfPath string `yaml:"ovfPath,omitempty"`
OvfUrl string `yaml:"ovfUrl,omitempty"`
} `yaml:"ova"`
Media struct {
MediaPath string `yaml:"mediaPath,omitempty"`
Media string `yaml:"mediaName,omitempty"`
NsxtMedia string `yaml:"nsxtBackedMediaName,omitempty"`
PhotonOsOvaPath string `yaml:"photonOsOvaPath,omitempty"`
MediaUdfTypePath string `yaml:"mediaUdfTypePath,omitempty"`
UiPluginPath string `yaml:"uiPluginPath,omitempty"`
} `yaml:"media"`
Cse struct {
Version string `yaml:"version,omitempty"`
SolutionsOrg string `yaml:"solutionsOrg,omitempty"`
TenantOrg string `yaml:"tenantOrg,omitempty"`
TenantVdc string `yaml:"tenantVdc,omitempty"`
RoutedNetwork string `yaml:"routedNetwork,omitempty"`
EdgeGateway string `yaml:"edgeGateway,omitempty"`
StorageProfile string `yaml:"storageProfile,omitempty"`
OvaCatalog string `yaml:"ovaCatalog,omitempty"`
OvaName string `yaml:"ovaName,omitempty"`
} `yaml:"cse,omitempty"`
}
// Test struct for vcloud-director.
// Test functions use the struct to get
// an org, vdc, vapp, and client to run
// tests on
type TestVCD struct {
client *VCDClient
org *Org
vdc *Vdc
nsxtVdc *Vdc
vapp *VApp
config TestConfig
skipVappTests bool
skipAdminTests bool
}
// Cleanup entity structure used by the tear-down procedure
// at the end of the tests to remove leftover entities
type CleanupEntity struct {
Name string
EntityType string
Parent string
CreatedBy string
OpenApiEndpoint string
}
// CleanupInfo is the data used to persist an entity list in a file
type CleanupInfo struct {
VcdIp string // IP of the vCD where the test runs
Info string // Information about this file
EntityList []CleanupEntity // List of entities to remove
}
// Internally used by the test suite to run tests based on TestVCD structures
var _ = Suite(&TestVCD{})
// The list holding the entities to be examined and eventually removed
// at the end of the tests
var cleanupEntityList []CleanupEntity
// Lock for of cleanup entities persistent file
var persistentCleanupListLock sync.Mutex
// IP of the vCD being tested. It is initialized at the first client authentication
var persistentCleanupIp string
// Use this value to run a specific test that does not need a pre-created vApp.
var skipVappCreation bool = os.Getenv("GOVCD_SKIP_VAPP_CREATION") != ""
// vcdHelp shows command line options
var vcdHelp bool
// enableDebug enables debug output
var enableDebug bool
// ignoreCleanupFile prevents processing a previous cleanup file
var ignoreCleanupFile bool
// connectAsOrgUser connects as Org user instead of System administrator
var connectAsOrgUser bool
var connectTenantNum int
// Makes the name for the cleanup entities persistent file
// Using a name for each vCD allows us to run tests with different servers
// and persist the cleanup list for all.
func makePersistentCleanupFileName() string {
var persistentCleanupListMask = "test_cleanup_list-%s.%s"
if persistentCleanupIp == "" {
fmt.Printf("######## Persistent Cleanup IP was not set ########\n")
os.Exit(1)
}
reForbiddenChars := regexp.MustCompile(`[/]`)
fileName := fmt.Sprintf(persistentCleanupListMask,
reForbiddenChars.ReplaceAllString(persistentCleanupIp, ""), "json")
return fileName
}
// Removes the list of cleanup entities
// To be called only after the list has been processed
func removePersistentCleanupList() {
persistentCleanupListFile := makePersistentCleanupFileName()
persistentCleanupListLock.Lock()
defer persistentCleanupListLock.Unlock()
_, err := os.Stat(persistentCleanupListFile)
if os.IsNotExist(err) {
return
}
_ = os.Remove(persistentCleanupListFile)
}
// Reads a cleanup list from file
func readCleanupList() ([]CleanupEntity, error) {
persistentCleanupListFile := makePersistentCleanupFileName()
persistentCleanupListLock.Lock()
defer persistentCleanupListLock.Unlock()
var cleanupInfo CleanupInfo
_, err := os.Stat(persistentCleanupListFile)
if os.IsNotExist(err) {
return nil, err
}
listText, err := os.ReadFile(filepath.Clean(persistentCleanupListFile))
if err != nil {
return nil, err
}
err = json.Unmarshal(listText, &cleanupInfo)
return cleanupInfo.EntityList, err
}
// Writes a cleanup list to file.
// If the test suite terminates without having a chance to
// clean up properly, the next run of the test suite will try to
// remove the leftovers
func writeCleanupList(cleanupList []CleanupEntity) error {
persistentCleanupListFile := makePersistentCleanupFileName()
persistentCleanupListLock.Lock()
defer persistentCleanupListLock.Unlock()
cleanupInfo := CleanupInfo{
VcdIp: persistentCleanupIp,
Info: "Persistent list of entities to be destroyed. " +
" If this file is found when starting the tests, its entities will be " +
" processed for removal before any other operation.",
EntityList: cleanupList,
}
listText, err := json.MarshalIndent(cleanupInfo, " ", " ")
if err != nil {
return err
}
file, err := os.Create(filepath.Clean(persistentCleanupListFile))
if err != nil {
return err
}
writer := bufio.NewWriter(file)
count, err := writer.Write(listText)
if err != nil || count == 0 {
return err
}
err = writer.Flush()
if err != nil {
return err
}
return file.Close()
}
// AddToCleanupList adds an entity to the cleanup list.
// To be called by all tests when a new entity has been created, before
// running any other operation.
// Items in the list will be deleted at the end of the tests if they still exist.
func AddToCleanupList(name, entityType, parent, createdBy string) {
for _, item := range cleanupEntityList {
// avoid adding the same item twice
if item.Name == name && item.EntityType == entityType {
return
}
}
cleanupEntityList = append(cleanupEntityList, CleanupEntity{Name: name, EntityType: entityType, Parent: parent, CreatedBy: createdBy})
err := writeCleanupList(cleanupEntityList)
if err != nil {
fmt.Printf("################ error writing cleanup list %s\n", err)
}
}
// PrependToCleanupList prepends an entity to the cleanup list.
// To be called by all tests when a new entity has been created, before
// running any other operation.
// Items in the list will be deleted at the end of the tests if they still exist.
func PrependToCleanupList(name, entityType, parent, createdBy string) {
for _, item := range cleanupEntityList {
// avoid adding the same item twice
if item.Name == name && item.EntityType == entityType {
return
}
}
cleanupEntityList = append([]CleanupEntity{{Name: name, EntityType: entityType, Parent: parent, CreatedBy: createdBy}}, cleanupEntityList...)
err := writeCleanupList(cleanupEntityList)
if err != nil {
fmt.Printf("################ error writing cleanup list %s\n", err)
}
}
// AddToCleanupListOpenApi adds an OpenAPI entity OpenApi objects `entityType=OpenApiEntity` and `openApiEndpoint`should
// be set in format "types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointOrgVdcNetworks + ID"
func AddToCleanupListOpenApi(name, createdBy, openApiEndpoint string) {
for _, item := range cleanupEntityList {
// avoid adding the same item twice
if item.OpenApiEndpoint == openApiEndpoint {
return
}
}
cleanupEntityList = append(cleanupEntityList, CleanupEntity{Name: name, EntityType: "OpenApiEntity", CreatedBy: createdBy, OpenApiEndpoint: openApiEndpoint})
err := writeCleanupList(cleanupEntityList)
if err != nil {
fmt.Printf("################ error writing cleanup list %s\n", err)
}
}
// PrependToCleanupListOpenApi prepends an OpenAPI entity OpenApi objects `entityType=OpenApiEntity` and
// `openApiEndpoint`should be set in format "types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointOrgVdcNetworks + ID"
func PrependToCleanupListOpenApi(name, createdBy, openApiEndpoint string) {
for _, item := range cleanupEntityList {
// avoid adding the same item twice
if item.OpenApiEndpoint == openApiEndpoint {
return
}
}
cleanupEntityList = append([]CleanupEntity{{Name: name, EntityType: "OpenApiEntity", CreatedBy: createdBy, OpenApiEndpoint: openApiEndpoint}}, cleanupEntityList...)
err := writeCleanupList(cleanupEntityList)
if err != nil {
fmt.Printf("################ error writing cleanup list %s\n", err)
}
}
// Users use the environmental variable GOVCD_CONFIG as
// a config file for testing. Otherwise the default is govcd_test_config.yaml
// in the current directory. Throws an error if it cannot find your
// yaml file or if it cannot read it.
func GetConfigStruct() (TestConfig, error) {
config := os.Getenv("GOVCD_CONFIG")
var configStruct TestConfig
if config == "" {
// Finds the current directory, through the path of this running test
_, currentFilename, _, _ := runtime.Caller(0)
currentDirectory := filepath.Dir(currentFilename)
config = currentDirectory + "/govcd_test_config.yaml"
}
// Looks if the configuration file exists before attempting to read it
_, err := os.Stat(config)
if os.IsNotExist(err) {
return TestConfig{}, fmt.Errorf("Configuration file %s not found: %s", config, err)
}
yamlFile, err := os.ReadFile(filepath.Clean(config))
if err != nil {
return TestConfig{}, fmt.Errorf("could not read config file %s: %s", config, err)
}
err = yaml.Unmarshal(yamlFile, &configStruct)
if err != nil {
return TestConfig{}, fmt.Errorf("could not unmarshal yaml file: %s", err)
}
if connectAsOrgUser {
if len(configStruct.Tenants) == 0 {
return TestConfig{}, fmt.Errorf("org user connection required, but 'tenants[%d]' is empty", connectTenantNum)
}
if connectTenantNum > len(configStruct.Tenants)-1 {
return TestConfig{}, fmt.Errorf("org user connection required, but tenant number %d is higher than the number of tenants ", connectTenantNum)
}
// Change configStruct.Provider, to reuse the global fields, such as URL
configStruct.Provider.User = configStruct.Tenants[connectTenantNum].User
configStruct.Provider.Password = configStruct.Tenants[connectTenantNum].Password
configStruct.Provider.SysOrg = configStruct.Tenants[connectTenantNum].SysOrg
configStruct.Provider.Token = configStruct.Tenants[connectTenantNum].Token
configStruct.Provider.ApiToken = configStruct.Tenants[connectTenantNum].ApiToken
}
return configStruct, nil
}
// Creates a VCDClient based on the endpoint given in the TestConfig argument.
// TestConfig struct can be obtained by calling GetConfigStruct. Throws an error
// if endpoint given is not a valid url.
func GetTestVCDFromYaml(testConfig TestConfig, options ...VCDClientOption) (*VCDClient, error) {
configUrl, err := url.ParseRequestURI(testConfig.Provider.Url)
if err != nil {
return &VCDClient{}, fmt.Errorf("could not parse Url: %s", err)
}
if testConfig.Provider.MaxRetryTimeout != 0 {
options = append(options, WithMaxRetryTimeout(testConfig.Provider.MaxRetryTimeout))
}
if testConfig.Provider.HttpTimeout != 0 {
options = append(options, WithHttpTimeout(testConfig.Provider.HttpTimeout))
}
if testConfig.Provider.UseSamlAdfs {
options = append(options, WithSamlAdfs(true, testConfig.Provider.CustomAdfsRptId))
}
return NewVCDClient(*configUrl, true, options...), nil
}
// Necessary to enable the suite tests with TestVCD
func Test(t *testing.T) { TestingT(t) }
// Sets the org, vdc, vapp, and vcdClient for a
// TestVCD struct. An error is thrown if something goes wrong
// getting config file, creating vcd, during authentication, or
// when creating a new vapp. If this method panics, no test
// case that uses the TestVCD struct is run.
func (vcd *TestVCD) SetUpSuite(check *C) {
flag.Parse()
setTestEnv()
if vcdHelp {
fmt.Println("vcd flags:")
fmt.Println()
// Prints only the flags defined in this package
flag.CommandLine.VisitAll(func(f *flag.Flag) {
if strings.HasPrefix(f.Name, "vcd-") {
fmt.Printf(" -%-40s %s (%v)\n", f.Name, f.Usage, f.Value)
}
})
fmt.Println()
// This will skip the whole suite.
// Instead, running os.Exit(0) will panic
check.Skip("--- showing help ---")
}
config, err := GetConfigStruct()
if config.Provider.Url == "" || err != nil {
panic(err)
}
vcd.config = config
// This library sets HTTP User-Agent to be `go-vcloud-director` by default and all HTTP calls
// expected to contain this header. An explicit test cannot capture future HTTP requests, but
// of them should use logging so this should be a good 'gate' to ensure ALL HTTP calls going out
// of this library do include HTTP User-Agent.
util.TogglePanicEmptyUserAgent(true)
if vcd.config.Logging.Enabled {
util.EnableLogging = true
if vcd.config.Logging.LogFileName != "" {
util.ApiLogFileName = vcd.config.Logging.LogFileName
}
if vcd.config.Logging.LogHttpRequest {
util.LogHttpRequest = true
}
if vcd.config.Logging.LogHttpResponse {
util.LogHttpResponse = true
}
if vcd.config.Logging.SkipResponseTags != "" {
util.SetSkipTags(vcd.config.Logging.SkipResponseTags)
}
if vcd.config.Logging.ApiLogFunctions != "" {
util.SetApiLogFunctions(vcd.config.Logging.ApiLogFunctions)
}
} else {
util.EnableLogging = false
}
util.SetLog()
vcdClient, err := GetTestVCDFromYaml(config)
if vcdClient == nil || err != nil {
panic(err)
}
vcd.client = vcdClient
token := os.Getenv("VCD_TOKEN")
if token == "" {
token = config.Provider.Token
}
apiToken := os.Getenv("VCD_API_TOKEN")
if apiToken == "" {
apiToken = config.Provider.ApiToken
}
authenticationMode := "password"
if apiToken != "" {
authenticationMode = "API-token"
err = vcd.client.SetToken(config.Provider.SysOrg, ApiTokenHeader, apiToken)
} else {
if token != "" {
authenticationMode = "token"
err = vcd.client.SetToken(config.Provider.SysOrg, AuthorizationHeader, token)
} else {
err = vcd.client.Authenticate(config.Provider.User, config.Provider.Password, config.Provider.SysOrg)
}
}
if config.Provider.UseSamlAdfs {
authenticationMode = "SAML password"
}
if err != nil {
panic(err)
}
versionInfo := ""
version, versionTime, err := vcd.client.Client.GetVcdVersion()
if err == nil {
versionInfo = fmt.Sprintf("version %s built at %s", version, versionTime)
}
fmt.Printf("Running on VCD %s (%s)\nas user %s@%s (using %s)\n", vcd.config.Provider.Url, versionInfo,
vcd.config.Provider.User, vcd.config.Provider.SysOrg, authenticationMode)
if !vcd.client.Client.IsSysAdmin {
vcd.skipAdminTests = true
}
// Sets the vCD IP value, removing the elements that would
// not be appropriate in a file name
reHttp := regexp.MustCompile(`^https?://`)
reApi := regexp.MustCompile(`/api/?`)
persistentCleanupIp = vcd.config.Provider.Url
persistentCleanupIp = reHttp.ReplaceAllString(persistentCleanupIp, "")
persistentCleanupIp = reApi.ReplaceAllString(persistentCleanupIp, "")
// set org
vcd.org, err = vcd.client.GetOrgByName(config.VCD.Org)
if err != nil {
fmt.Printf("error retrieving org %s: %s\n", config.VCD.Org, err)
os.Exit(1)
}
// set vdc
vcd.vdc, err = vcd.org.GetVDCByName(config.VCD.Vdc, false)
if err != nil || vcd.vdc == nil {
panic(err)
}
// configure NSX-T VDC for convenience if it is specified in configuration
if config.VCD.Nsxt.Vdc != "" {
vcd.nsxtVdc, err = vcd.org.GetVDCByName(config.VCD.Nsxt.Vdc, false)
if err != nil {
panic(fmt.Errorf("error geting NSX-T VDC '%s': %s", config.VCD.Nsxt.Vdc, err))
}
}
// If neither the vApp or VM tags are set, we also skip the
// creation of the default vApp
if !isTagSet("vapp") && !isTagSet("vm") {
// vcd.skipVappTests = true
skipVappCreation = true
}
// Gets the persistent cleanup list from file, if exists.
cleanupList, err := readCleanupList()
if len(cleanupList) > 0 && err == nil {
if !ignoreCleanupFile {
// If we found a cleanup file and we want to process it (default)
// We proceed to cleanup the leftovers before any other operation
fmt.Printf("*** Found cleanup file %s\n", makePersistentCleanupFileName())
for i, cleanupEntity := range cleanupList {
fmt.Printf("# %d ", i+1)
vcd.removeLeftoverEntities(cleanupEntity)
}
}
removePersistentCleanupList()
}
// creates a new VApp for vapp tests
if !skipVappCreation && config.VCD.Network.Net1 != "" && config.VCD.StorageProfile.SP1 != "" &&
config.VCD.Catalog.Name != "" && config.VCD.Catalog.CatalogItem != "" {
// deployVappForTest replaces the old createTestVapp() because it was using bad implemented method vdc.ComposeVApp
vcd.vapp, err = deployVappForTest(vcd, TestSetUpSuite)
// If no vApp is created, we skip all vApp tests
if err != nil {
fmt.Printf("%s\n", err)
panic("Creation failed - Bailing out")
}
if vcd.vapp == nil {
fmt.Printf("Creation of vApp %s failed unexpectedly. No error was reported, but vApp is empty\n", TestSetUpSuite)
panic("initial vApp is empty - bailing out")
}
} else {
vcd.skipVappTests = true
fmt.Println("Skipping all vapp tests because one of the following wasn't given: Network, StorageProfile, Catalog, Catalogitem")
}
}
// Shows the detail of cleanup operations only if the relevant verbosity
// has been enabled
func (vcd *TestVCD) infoCleanup(format string, args ...interface{}) {
if vcd.config.Logging.VerboseCleanup {
fmt.Printf(format, args...)
}
}
func getOrgVdcByNames(vcd *TestVCD, orgName, vdcName string) (*Org, *Vdc, error) {
if orgName == "" || vdcName == "" {
return nil, nil, fmt.Errorf("orgName, vdcName cant be empty")
}
org, _ := vcd.client.GetOrgByName(orgName)
if org == nil {
vcd.infoCleanup("could not find org '%s'", orgName)
return nil, nil, fmt.Errorf("can't find org")
}
vdc, err := org.GetVDCByName(vdcName, false)
if err != nil {
vcd.infoCleanup("could not find vdc '%s'", vdcName)
return nil, nil, fmt.Errorf("can't find vdc")
}
return org, vdc, nil
}
func getOrgVdcEdgeByNames(vcd *TestVCD, orgName, vdcName, edgeName string) (*Org, *Vdc, *EdgeGateway, error) {
if orgName == "" || vdcName == "" || edgeName == "" {
return nil, nil, nil, fmt.Errorf("orgName, vdcName, edgeName cant be empty")
}
org, vdc, err := getOrgVdcByNames(vcd, orgName, vdcName)
if err != nil {
return nil, nil, nil, err
}
edge, err := vdc.GetEdgeGatewayByName(edgeName, false)
if err != nil {
vcd.infoCleanup("could not find edge '%s': %s", edgeName, err)
}
return org, vdc, edge, nil
}
var splitParentNotFound string = "removeLeftoverEntries: [ERROR] missing parent info (%s). The parent fields must be defined with a separator '|'\n"
var notFoundMsg string = "removeLeftoverEntries: [INFO] No action for %s '%s'\n"
func (vcd *TestVCD) getAdminOrgAndVdcFromCleanupEntity(entity CleanupEntity) (org *AdminOrg, vdc *Vdc, err error) {
orgName, vdcName, _ := splitParent(entity.Parent, "|")
if orgName == "" || vdcName == "" {
vcd.infoCleanup(splitParentNotFound, entity.Parent)
return nil, nil, fmt.Errorf("can't find parents names")
}
org, err = vcd.client.GetAdminOrgByName(orgName)
if err != nil {
vcd.infoCleanup(notFoundMsg, "org", orgName)
return nil, nil, fmt.Errorf("can't find org")
}
vdc, err = org.GetVDCByName(vdcName, false)
if vdc == nil || err != nil {
vcd.infoCleanup(notFoundMsg, "vdc", vdcName)
return nil, nil, fmt.Errorf("can't find vdc")
}
return org, vdc, nil
}
// Removes leftover entities that may still exist after failed tests
// or the ones that were explicitly created for several tests and
// were relying on this procedure to clean up at the end.
func (vcd *TestVCD) removeLeftoverEntities(entity CleanupEntity) {
var introMsg string = "removeLeftoverEntries: [INFO] Attempting cleanup of %s '%s' instantiated by %s\n"
var removedMsg string = "removeLeftoverEntries: [INFO] Removed %s '%s' created by %s\n"
var notDeletedMsg string = "removeLeftoverEntries: [ERROR] Error deleting %s '%s': %s\n"
// NOTE: this is a cleanup function that should continue even if errors are found.
// For this reason, the [ERROR] messages won't be followed by a program termination
vcd.infoCleanup(introMsg, entity.EntityType, entity.Name, entity.CreatedBy)
switch entity.EntityType {
// openApiEntity can be used to delete any OpenAPI entity due to the API being uniform and allowing the same
// low level OpenApiDeleteItem()
case "OpenApiEntity":
// entity.OpenApiEndpoint contains "endpoint/{ID}"
// (in format types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointOrgVdcNetworks + ID) but
// to lookup used API version this ID must not be present therefore below we remove suffix ID.
// This is done by splitting whole path by "/" and rebuilding path again without last element in slice (which is
// expected to be the ID)
// Sometimes API endpoint path might contain URNs in the middle (e.g. OpenApiEndpointNsxtNatRules). They are
// replaced back to string placeholder %s to match original definitions
endpointSlice := strings.Split(entity.OpenApiEndpoint, "/")
endpointWithUuid := strings.Join(endpointSlice[:len(endpointSlice)-1], "/") + "/"
// replace any "urns" (e.g. 'urn:vcloud:gateway:64966c36-e805-44e2-980b-c1077ab54956') with '%s' to match API definitions
re := regexp.MustCompile(`urn[^\/]+`) // Regexp matches from 'urn' up to next '/' in the path
endpointRemovedUuids := re.ReplaceAllString(endpointWithUuid, "%s")
apiVersion, _ := vcd.client.Client.checkOpenApiEndpointCompatibility(endpointRemovedUuids)
// Build UP complete endpoint address
urlRef, err := vcd.client.Client.OpenApiBuildEndpoint(entity.OpenApiEndpoint)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
// Validate if the resource still exists
err = vcd.client.Client.OpenApiGetItem(apiVersion, urlRef, nil, nil, nil)
// RDE Framework has a bug in VCD 10.3.0 that causes "not found" errors to return as "400 bad request",
// so we need to amend them
if strings.Contains(entity.OpenApiEndpoint, types.OpenApiEndpointRdeInterfaces) {
err = amendRdeApiError(&vcd.client.Client, err)
}
// UI Plugin has a bug in VCD 10.4.x that causes "not found" errors to return a NullPointerException,
// so we need to amend them
if strings.Contains(entity.OpenApiEndpoint, types.OpenApiEndpointExtensionsUi) {
err = amendUIPluginGetByIdError(entity.Name, err)
}
if ContainsNotFound(err) {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
// Attempt to use supplied path in entity.Parent for element deletion
err = vcd.client.Client.OpenApiDeleteItem(apiVersion, urlRef, nil, nil)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
// OpenApiEntityFirewall has different API structure therefore generic `OpenApiEntity` case does not fit cleanup
case "OpenApiEntityFirewall":
apiVersion, err := vcd.client.Client.checkOpenApiEndpointCompatibility(types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointNsxtFirewallRules)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
urlRef, err := vcd.client.Client.OpenApiBuildEndpoint(entity.Name)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
// Attempt to use supplied path in entity.Parent for element deletion
err = vcd.client.Client.OpenApiDeleteItem(apiVersion, urlRef, nil, nil)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
case "OpenApiEntityGlobalDefaultSegmentProfileTemplate":
// Check if any default settings are applied
gdSpt, err := vcd.client.GetGlobalDefaultSegmentProfileTemplates()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
if gdSpt.VappNetworkSegmentProfileTemplateRef == nil && gdSpt.VdcNetworkSegmentProfileTemplateRef == nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
_, err = vcd.client.UpdateGlobalDefaultSegmentProfileTemplates(&types.NsxtGlobalDefaultSegmentProfileTemplate{})
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
// OpenApiEntityAlbSettingsDisable has different API structure therefore generic `OpenApiEntity` case does not fit cleanup
case "OpenApiEntityAlbSettingsDisable":
edge, err := vcd.nsxtVdc.GetNsxtEdgeGatewayByName(entity.Parent)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
edgeAlbSettingsConfig, err := edge.GetAlbSettings()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
if edgeAlbSettingsConfig.Enabled == false {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
err = edge.DisableAlb()
if err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
case "vapp":
vdc := vcd.vdc
var err error
// Check if parent VDC was specified. If not - use the default NSX-V VDC
if entity.Parent != "" {
vdc, err = vcd.org.GetVDCByName(entity.Parent, true)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
}
vapp, err := vdc.GetVAppByName(entity.Name, true)
if err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
task, _ := vapp.Undeploy()
_ = task.WaitTaskCompletion()
// Detach all Org networks during vApp removal because network removal errors if it happens
// very quickly (as the next task) after vApp removal
task, _ = vapp.RemoveAllNetworks()
_ = task.WaitTaskCompletion()
task, err = vapp.Delete()
_ = task.WaitTaskCompletion()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
return
case "catalog":
if entity.Parent == "" {
vcd.infoCleanup("removeLeftoverEntries: [ERROR] No Org provided for catalog '%s'\n", entity.Name)
return
}
org, err := vcd.client.GetAdminOrgByName(entity.Parent)
if err != nil {
vcd.infoCleanup("removeLeftoverEntries: [INFO] organization '%s' not found\n", entity.Parent)
return
}
catalog, err := org.GetAdminCatalogByName(entity.Name, false)
if catalog == nil || err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
err = catalog.Delete(true, true)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
return
case "org":
org, err := vcd.client.GetAdminOrgByName(entity.Name)
if err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
err = org.Delete(true, true)
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
return
case "provider_vdc":
pvdc, err := vcd.client.GetProviderVdcExtendedByName(entity.Name)
if err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}
err = pvdc.Disable()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
task, err := pvdc.Delete()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)
return
}
err = task.WaitTaskCompletion()
if err != nil {
vcd.infoCleanup(notDeletedMsg, entity.EntityType, entity.Name, err)