github.com/vmware/go-vcloud-director/v2@v2.24.0/govcd/system_test.go (about)

     1  //go:build system || functional || ALL
     2  
     3  /*
     4   * Copyright 2019 VMware, Inc.  All rights reserved.  Licensed under the Apache v2 License.
     5   */
     6  
     7  package govcd
     8  
     9  import (
    10  	"fmt"
    11  	"strings"
    12  
    13  	. "gopkg.in/check.v1"
    14  
    15  	"github.com/vmware/go-vcloud-director/v2/types/v56"
    16  	"github.com/vmware/go-vcloud-director/v2/util"
    17  )
    18  
    19  // Tests Org retrieval by name, by ID, and by a combination of name and ID
    20  func (vcd *TestVCD) Test_SystemGetOrg(check *C) {
    21  
    22  	if vcd.config.VCD.Org == "" {
    23  		check.Skip("Test_SystemGetOrg: Org name not given")
    24  		return
    25  	}
    26  
    27  	getByName := func(name string, refresh bool) (genericEntity, error) { return vcd.client.GetOrgByName(name) }
    28  	getById := func(id string, refresh bool) (genericEntity, error) { return vcd.client.GetOrgById(id) }
    29  	getByNameOrId := func(id string, refresh bool) (genericEntity, error) { return vcd.client.GetOrgByNameOrId(id) }
    30  
    31  	var def = getterTestDefinition{
    32  		parentType:    "VCDClient",
    33  		parentName:    "System",
    34  		entityType:    "Org",
    35  		entityName:    vcd.config.VCD.Org,
    36  		getByName:     getByName,
    37  		getById:       getById,
    38  		getByNameOrId: getByNameOrId,
    39  	}
    40  	vcd.testFinderGetGenericEntity(def, check)
    41  }
    42  
    43  // Tests AdminOrg retrieval by name, by ID, and by a combination of name and ID
    44  func (vcd *TestVCD) Test_SystemGetAdminOrg(check *C) {
    45  
    46  	if vcd.config.VCD.Org == "" {
    47  		check.Skip("Test_SystemGetAdminOrg: Org name not given.")
    48  		return
    49  	}
    50  
    51  	getByName := func(name string, refresh bool) (genericEntity, error) { return vcd.client.GetAdminOrgByName(name) }
    52  	getById := func(id string, refresh bool) (genericEntity, error) { return vcd.client.GetAdminOrgById(id) }
    53  	getByNameOrId := func(id string, refresh bool) (genericEntity, error) { return vcd.client.GetAdminOrgByNameOrId(id) }
    54  
    55  	var def = getterTestDefinition{
    56  		parentType:    "VCDClient",
    57  		parentName:    "System",
    58  		entityType:    "AdminOrg",
    59  		entityName:    vcd.config.VCD.Org,
    60  		getByName:     getByName,
    61  		getById:       getById,
    62  		getByNameOrId: getByNameOrId,
    63  	}
    64  	vcd.testFinderGetGenericEntity(def, check)
    65  }
    66  
    67  // Tests the creation of an org with general settings,
    68  // org vapp template settings, and orgldapsettings. Asserts an
    69  // error if the task, fetching the org, or deleting the org fails
    70  func (vcd *TestVCD) Test_CreateOrg(check *C) {
    71  	if vcd.skipAdminTests {
    72  		check.Skip(fmt.Sprintf(TestRequiresSysAdminPrivileges, check.TestName()))
    73  	}
    74  
    75  	type testOrgData struct {
    76  		name                     string
    77  		enabled                  bool
    78  		canPublishCatalogs       bool
    79  		deployedVmQuota          int
    80  		storedVmQuota            int
    81  		delayAfterPowerOnSeconds int
    82  		fullData                 bool
    83  	}
    84  	var orgList = []testOrgData{
    85  		{"org1", true, false, 0, 0, 0, true},
    86  		{"org2", true, true, 0, 0, 1, false},
    87  		{"org3", false, false, 1, 1, 3, true},
    88  		{"org4", true, true, 10, 10, 10, false},
    89  		{"org5", false, true, 100, 100, 100, false},
    90  	}
    91  
    92  	storageLeaseSeconds := 10
    93  	deploymentLeaseSeconds := 1000000
    94  	trueVal := true
    95  	fullSettings := &types.OrgSettings{
    96  		OrgGeneralSettings: &types.OrgGeneralSettings{},
    97  		OrgVAppTemplateSettings: &types.VAppTemplateLeaseSettings{
    98  			DeleteOnStorageLeaseExpiration: &trueVal,
    99  			StorageLeaseSeconds:            &storageLeaseSeconds,
   100  		},
   101  		OrgVAppLeaseSettings: &types.VAppLeaseSettings{
   102  			PowerOffOnRuntimeLeaseExpiration: &trueVal,
   103  			DeploymentLeaseSeconds:           &deploymentLeaseSeconds,
   104  			DeleteOnStorageLeaseExpiration:   &trueVal,
   105  			StorageLeaseSeconds:              &storageLeaseSeconds,
   106  		},
   107  		OrgLdapSettings: &types.OrgLdapSettingsType{
   108  			OrgLdapMode: "NONE",
   109  		},
   110  	}
   111  	for _, od := range orgList {
   112  		var settings *types.OrgSettings
   113  		if od.fullData {
   114  			settings = fullSettings
   115  		} else {
   116  			settings = &types.OrgSettings{
   117  				OrgGeneralSettings: &types.OrgGeneralSettings{},
   118  			}
   119  		}
   120  		orgName := TestCreateOrg + "_" + od.name
   121  
   122  		if vcd.client.Client.APIVCDMaxVersionIs("= 37.2") && !od.enabled {
   123  			// TODO revisit once bug is fixed in VCD
   124  			fmt.Println("[INFO] VCD 10.4.2 has a bug that prevents creating a disabled Org - Changing 'enabled' parameter to 'true'")
   125  			od.enabled = true
   126  		}
   127  		fmt.Printf("# org %s (enabled: %v - catalogs: %v [%d %d])\n", orgName, od.enabled, od.canPublishCatalogs, od.storedVmQuota, od.deployedVmQuota)
   128  		settings.OrgGeneralSettings.CanPublishCatalogs = od.canPublishCatalogs
   129  		settings.OrgGeneralSettings.DeployedVMQuota = od.deployedVmQuota
   130  		settings.OrgGeneralSettings.StoredVMQuota = od.storedVmQuota
   131  		settings.OrgGeneralSettings.DelayAfterPowerOnSeconds = od.delayAfterPowerOnSeconds
   132  		task, err := CreateOrg(vcd.client, orgName, TestCreateOrg, TestCreateOrg, settings, od.enabled)
   133  		check.Assert(err, IsNil)
   134  		// After a successful creation, the entity is added to the cleanup list.
   135  		// If something fails after this point, the entity will be removed
   136  		AddToCleanupList(orgName, "org", "", "TestCreateOrg")
   137  		err = task.WaitTaskCompletion()
   138  		check.Assert(err, IsNil)
   139  		// fetch newly created org
   140  		adminOrg, err := vcd.client.GetAdminOrgByName(orgName)
   141  		check.Assert(err, IsNil)
   142  		check.Assert(adminOrg, NotNil)
   143  		check.Assert(adminOrg.AdminOrg.Name, Equals, orgName)
   144  		check.Assert(adminOrg.AdminOrg.Description, Equals, TestCreateOrg)
   145  		check.Assert(adminOrg.AdminOrg.IsEnabled, Equals, od.enabled)
   146  
   147  		check.Assert(adminOrg.AdminOrg.OrgSettings.OrgGeneralSettings.CanPublishCatalogs, Equals, od.canPublishCatalogs)
   148  		check.Assert(adminOrg.AdminOrg.OrgSettings.OrgGeneralSettings.DeployedVMQuota, Equals, od.deployedVmQuota)
   149  		check.Assert(adminOrg.AdminOrg.OrgSettings.OrgGeneralSettings.StoredVMQuota, Equals, od.storedVmQuota)
   150  		check.Assert(adminOrg.AdminOrg.OrgSettings.OrgGeneralSettings.DelayAfterPowerOnSeconds, Equals, od.delayAfterPowerOnSeconds)
   151  		// Delete, with force and recursive true
   152  		err = adminOrg.Delete(true, true)
   153  		check.Assert(err, IsNil)
   154  		doesOrgExist(check, vcd)
   155  	}
   156  }
   157  
   158  func (vcd *TestVCD) Test_CreateDeleteEdgeGateway(check *C) {
   159  	vcd.skipIfNotSysAdmin(check)
   160  	if vcd.config.VCD.ExternalNetwork == "" {
   161  		check.Skip("No external network provided")
   162  	}
   163  
   164  	newEgwName := "CreateDeleteEdgeGateway"
   165  	orgName := vcd.config.VCD.Org
   166  	vdcName := vcd.config.VCD.Vdc
   167  	egc := EdgeGatewayCreation{
   168  		ExternalNetworks:          []string{vcd.config.VCD.ExternalNetwork},
   169  		DefaultGateway:            vcd.config.VCD.ExternalNetwork,
   170  		OrgName:                   orgName,
   171  		VdcName:                   vdcName,
   172  		AdvancedNetworkingEnabled: true,
   173  	}
   174  
   175  	testingRange := []string{"compact", "full"}
   176  	for _, backingConf := range testingRange {
   177  		egc.BackingConfiguration = backingConf
   178  		egc.Name = newEgwName + "_" + backingConf
   179  		egc.Description = egc.Name
   180  
   181  		var edge EdgeGateway
   182  		var task Task
   183  		var err error
   184  		builtWithDefaultGateway := true
   185  		// Tests one edge gateway with default gateway, and one without
   186  		// Also tests two different functions to create the gateway
   187  		if backingConf == "full" {
   188  			egc.DefaultGateway = vcd.config.VCD.ExternalNetwork
   189  			edge, err = CreateEdgeGateway(vcd.client, egc)
   190  			check.Assert(err, IsNil)
   191  		} else {
   192  			// The "compact" edge gateway is created without default gateway
   193  			egc.DefaultGateway = ""
   194  			builtWithDefaultGateway = false
   195  			task, err = CreateEdgeGatewayAsync(vcd.client, egc)
   196  			check.Assert(err, IsNil)
   197  			err = task.WaitTaskCompletion()
   198  			check.Assert(err, IsNil)
   199  			newEdge, err := vcd.vdc.GetEdgeGatewayByName(egc.Name, true)
   200  			check.Assert(err, IsNil)
   201  			check.Assert(newEdge, NotNil)
   202  			edge = *newEdge
   203  		}
   204  
   205  		AddToCleanupList(egc.Name, "edgegateway", orgName+"|"+vdcName, "Test_CreateDeleteEdgeGateway")
   206  
   207  		check.Assert(edge.EdgeGateway.Name, Equals, egc.Name)
   208  		// Edge gateway status:
   209  		//  0 : being created
   210  		//  1 : ready
   211  		// -1 : creation error
   212  		check.Assert(edge.EdgeGateway.Status, Equals, 1)
   213  
   214  		check.Assert(edge.EdgeGateway.Configuration.AdvancedNetworkingEnabled, NotNil)
   215  		check.Assert(*edge.EdgeGateway.Configuration.AdvancedNetworkingEnabled, Equals, true)
   216  		util.Logger.Printf("Edge Gateway:\n%s\n", prettyEdgeGateway(*edge.EdgeGateway))
   217  
   218  		check.Assert(edge.HasDefaultGateway(), Equals, builtWithDefaultGateway)
   219  		check.Assert(edge.HasAdvancedNetworking(), Equals, egc.AdvancedNetworkingEnabled)
   220  
   221  		// testing both delete methods
   222  		if backingConf == "full" {
   223  			err = edge.Delete(true, true)
   224  			check.Assert(err, IsNil)
   225  		} else {
   226  			task, err := edge.DeleteAsync(true, true)
   227  			check.Assert(err, IsNil)
   228  			err = task.WaitTaskCompletion()
   229  			check.Assert(err, IsNil)
   230  		}
   231  
   232  		// Once deleted, look for the edge gateway again. It should return an error
   233  		newEdge, err := vcd.vdc.GetEdgeGatewayByName(egc.Name, true)
   234  		check.Assert(err, Equals, ErrorEntityNotFound)
   235  		check.Assert(newEdge, IsNil)
   236  	}
   237  }
   238  
   239  // Test_CreateDeleteEdgeGatewayAdvanced sets up external network which has multiple IP scopes and IP
   240  // ranges defined. This helps to test edge gateway capabilities for multiple networks and scopes
   241  func (vcd *TestVCD) Test_CreateDeleteEdgeGatewayAdvanced(check *C) {
   242  	// Setup external network with multiple IP scopes and multiple ranges
   243  	dnsSuffix := "some.net"
   244  	skippingReason, externalNetwork, task, err := vcd.testCreateExternalNetwork(check.TestName(), check.TestName(), dnsSuffix)
   245  	if skippingReason != "" {
   246  		check.Skip(skippingReason)
   247  	}
   248  
   249  	check.Assert(err, IsNil)
   250  	check.Assert(task.Task, Not(Equals), types.Task{})
   251  
   252  	AddToCleanupList(externalNetwork.Name, "externalNetwork", "", check.TestName())
   253  	err = task.WaitTaskCompletion()
   254  	check.Assert(err, IsNil)
   255  
   256  	// "Refresh" external network to fill in all fields (like HREF)
   257  	extNet, err := vcd.client.GetExternalNetworkByName(externalNetwork.Name)
   258  	check.Assert(err, IsNil)
   259  	externalNetwork = extNet.ExternalNetwork
   260  
   261  	edgeName := "Test-Multi-Scope-Gw"
   262  	// Initialize edge gateway structure
   263  	edgeGatewayConfig := &types.EdgeGateway{
   264  		Name:        edgeName,
   265  		Description: edgeName,
   266  		Configuration: &types.GatewayConfiguration{
   267  			HaEnabled:            addrOf(false),
   268  			GatewayBackingConfig: "compact",
   269  			GatewayInterfaces: &types.GatewayInterfaces{
   270  				GatewayInterface: []*types.GatewayInterface{},
   271  			},
   272  			AdvancedNetworkingEnabled:  addrOf(true),
   273  			DistributedRoutingEnabled:  addrOf(false),
   274  			UseDefaultRouteForDNSRelay: addrOf(true),
   275  		},
   276  	}
   277  
   278  	edgeGatewayConfig.Configuration.FipsModeEnabled = addrOf(false)
   279  
   280  	// Create subnet participation structure
   281  	subnetParticipation := make([]*types.SubnetParticipation, len(externalNetwork.Configuration.IPScopes.IPScope))
   282  	// Loop over IP scopes
   283  	for ipScopeIndex, ipScope := range externalNetwork.Configuration.IPScopes.IPScope {
   284  		subnetParticipation[ipScopeIndex] = &types.SubnetParticipation{
   285  			Gateway: ipScope.Gateway,
   286  			Netmask: ipScope.Netmask,
   287  			// IPAddress: string,			// Can be set to specify IP address of edge gateway
   288  			// UseForDefaultRoute: bool,	// Can be specified to use subnet as default gateway
   289  			IPRanges: &types.IPRanges{},
   290  		}
   291  	}
   292  
   293  	// Setup network interface config
   294  	networkConf := &types.GatewayInterface{
   295  		Name:          externalNetwork.Name,
   296  		DisplayName:   externalNetwork.Name,
   297  		InterfaceType: "uplink",
   298  		Network: &types.Reference{
   299  			HREF: externalNetwork.HREF,
   300  			ID:   externalNetwork.ID,
   301  			Type: "application/vnd.vmware.admin.network+xml",
   302  			Name: externalNetwork.Name,
   303  		},
   304  		UseForDefaultRoute:  true,
   305  		SubnetParticipation: subnetParticipation,
   306  	}
   307  
   308  	// Sort by subnet participation gateway so that below injected variables are not being added to
   309  	// incorrect network
   310  	networkConf.SortBySubnetParticipationGateway()
   311  	// Set static IP assignment
   312  	networkConf.SubnetParticipation[0].IPAddress = "192.168.201.100"
   313  	// Set default gateway subnet
   314  	networkConf.SubnetParticipation[1].UseForDefaultRoute = true
   315  	// Inject an IP range (in UI it is called "sub-allocated pools" in separate tab)
   316  	networkConf.SubnetParticipation[0].IPRanges = &types.IPRanges{
   317  		IPRange: []*types.IPRange{
   318  			&types.IPRange{
   319  				StartAddress: "192.168.201.120",
   320  				EndAddress:   "192.168.201.130",
   321  			},
   322  		},
   323  	}
   324  
   325  	edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface =
   326  		append(edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface, networkConf)
   327  
   328  	orgName := vcd.config.VCD.Org
   329  	vdcName := vcd.config.VCD.Vdc
   330  
   331  	edge, err := CreateAndConfigureEdgeGateway(vcd.client, orgName, vdcName, edgeName, edgeGatewayConfig)
   332  	check.Assert(err, IsNil)
   333  	PrependToCleanupList(edge.EdgeGateway.Name, "edgegateway", orgName+"|"+vdcName, "Test_CreateDeleteEdgeGateway")
   334  
   335  	// Patch known differences for comparison deep comparison
   336  	edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0].SubnetParticipation[1].IPAddress = "192.168.231.3"
   337  	edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0].Network.HREF =
   338  		edge.EdgeGateway.Configuration.GatewayInterfaces.GatewayInterface[0].Network.HREF
   339  
   340  	edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0].Network.HREF =
   341  		edge.EdgeGateway.Configuration.GatewayInterfaces.GatewayInterface[0].Network.HREF
   342  
   343  	//edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0].Network.ID = ""
   344  
   345  	// Sort gateway interfaces so that comparison is easier
   346  	edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0].SortBySubnetParticipationGateway()
   347  	edge.EdgeGateway.Configuration.GatewayInterfaces.GatewayInterface[0].SortBySubnetParticipationGateway()
   348  
   349  	check.Assert(edge.EdgeGateway.Configuration.GatewayInterfaces.GatewayInterface[0], DeepEquals,
   350  		edgeGatewayConfig.Configuration.GatewayInterfaces.GatewayInterface[0])
   351  	check.Assert(edge.EdgeGateway.Configuration.DistributedRoutingEnabled, NotNil)
   352  	check.Assert(*edge.EdgeGateway.Configuration.DistributedRoutingEnabled, Equals, false)
   353  
   354  	// FIPS mode is not being returned from API (neither when it is enabled, nor when disabled), but
   355  	// does allow to turn it on.
   356  	// check.Assert(edge.EdgeGateway.Configuration.FipsModeEnabled, NotNil)
   357  	// check.Assert(*edge.EdgeGateway.Configuration.FipsModeEnabled, Equals, true)
   358  
   359  	check.Assert(edge.EdgeGateway.Configuration.AdvancedNetworkingEnabled, NotNil)
   360  	check.Assert(*edge.EdgeGateway.Configuration.AdvancedNetworkingEnabled, Equals, true)
   361  	check.Assert(edge.EdgeGateway.Configuration.UseDefaultRouteForDNSRelay, NotNil)
   362  	check.Assert(*edge.EdgeGateway.Configuration.UseDefaultRouteForDNSRelay, Equals, true)
   363  	check.Assert(edge.EdgeGateway.Configuration.HaEnabled, NotNil)
   364  	check.Assert(*edge.EdgeGateway.Configuration.HaEnabled, Equals, false)
   365  
   366  	// Remove created objects to free them up
   367  	err = edge.Delete(true, false)
   368  	check.Assert(err, IsNil)
   369  
   370  	err = extNet.DeleteWait()
   371  	check.Assert(err, IsNil)
   372  }
   373  
   374  func (vcd *TestVCD) Test_FindBadlyNamedStorageProfile(check *C) {
   375  	reNotFound := `can't find any VDC Storage_profiles`
   376  	_, err := vcd.vdc.FindStorageProfileReference("name with spaces")
   377  	check.Assert(err, NotNil)
   378  	check.Assert(err.Error(), Matches, reNotFound)
   379  }
   380  
   381  // Test getting network pool by href and vdc client
   382  func (vcd *TestVCD) Test_GetNetworkPoolByHREF(check *C) {
   383  	vcd.skipIfNotSysAdmin(check)
   384  	if vcd.config.VCD.ProviderVdc.NetworkPool == "" {
   385  		check.Skip("Skipping test because network pool is not configured")
   386  	}
   387  
   388  	fmt.Printf("Running: %s\n", check.TestName())
   389  
   390  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.config.VCD.Org)
   391  	check.Assert(err, IsNil)
   392  	check.Assert(adminOrg, NotNil)
   393  
   394  	adminVdc, err := adminOrg.GetAdminVDCByName(vcd.config.VCD.Vdc, false)
   395  	check.Assert(err, IsNil)
   396  	check.Assert(adminVdc, NotNil)
   397  
   398  	// Get network pool by href
   399  	foundNetworkPool, err := GetNetworkPoolByHREF(vcd.client, adminVdc.AdminVdc.NetworkPoolReference.HREF)
   400  	check.Assert(err, IsNil)
   401  	check.Assert(foundNetworkPool, Not(Equals), types.VMWNetworkPool{})
   402  }
   403  
   404  func init() {
   405  	testingTags["system"] = "system_test.go"
   406  }
   407  
   408  func (vcd *TestVCD) Test_QueryOrgVdcNetworkByName(check *C) {
   409  	fmt.Printf("Running: %s\n", check.TestName())
   410  
   411  	if vcd.config.VCD.Network.Net1 == "" {
   412  		check.Skip("Skipping test because no network was given")
   413  	}
   414  
   415  	orgVdcNetwork, err := QueryOrgVdcNetworkByName(vcd.client, vcd.config.VCD.Network.Net1)
   416  	check.Assert(err, IsNil)
   417  	check.Assert(len(orgVdcNetwork), Not(Equals), 0)
   418  	check.Assert(orgVdcNetwork[0].Name, Equals, vcd.config.VCD.Network.Net1)
   419  	check.Assert(orgVdcNetwork[0].ConnectedTo, Equals, vcd.config.VCD.EdgeGateway)
   420  }
   421  
   422  func (vcd *TestVCD) Test_QueryOrgVdcNetworkByNameWithSpace(check *C) {
   423  	fmt.Printf("Running: %s\n", check.TestName())
   424  	networkName := "Test_QueryOrgVdcNetworkByNameWith Space"
   425  
   426  	if vcd.skipAdminTests {
   427  		check.Skip(fmt.Sprintf(TestRequiresSysAdminPrivileges, check.TestName()))
   428  	}
   429  
   430  	if vcd.config.VCD.ExternalNetwork == "" {
   431  		check.Skip("[Test_CreateOrgVdcNetworkDirect] external network not provided")
   432  	}
   433  	externalNetwork, err := vcd.client.GetExternalNetworkByName(vcd.config.VCD.ExternalNetwork)
   434  	if err != nil {
   435  		check.Skip("[Test_CreateOrgVdcNetworkDirect] parent external network not found")
   436  	}
   437  	// Note that there is no IPScope for this type of network
   438  	var networkConfig = types.OrgVDCNetwork{
   439  		Name: networkName,
   440  		Configuration: &types.NetworkConfiguration{
   441  			FenceMode: types.FenceModeBridged,
   442  			ParentNetwork: &types.Reference{
   443  				HREF: externalNetwork.ExternalNetwork.HREF,
   444  				Name: externalNetwork.ExternalNetwork.Name,
   445  				Type: externalNetwork.ExternalNetwork.Type,
   446  			},
   447  			BackwardCompatibilityMode: true,
   448  		},
   449  		IsShared: false,
   450  	}
   451  	LogNetwork(networkConfig)
   452  
   453  	task, err := vcd.vdc.CreateOrgVDCNetwork(&networkConfig)
   454  	if err != nil {
   455  		fmt.Printf("error creating the network: %s", err)
   456  	}
   457  	check.Assert(err, IsNil)
   458  	if task == (Task{}) {
   459  		fmt.Printf("NULL task retrieved after network creation")
   460  	}
   461  	check.Assert(task.Task.HREF, Not(Equals), "")
   462  
   463  	AddToCleanupList(networkName, "network", vcd.org.Org.Name+"|"+vcd.vdc.Vdc.Name, check.TestName())
   464  
   465  	// err = task.WaitTaskCompletion()
   466  	err = task.WaitInspectTaskCompletion(LogTask, 10)
   467  	if err != nil {
   468  		fmt.Printf("error performing task: %s", err)
   469  	}
   470  	check.Assert(err, IsNil)
   471  
   472  	orgVdcNetwork, err := QueryOrgVdcNetworkByName(vcd.client, networkName)
   473  	check.Assert(err, IsNil)
   474  	check.Assert(len(orgVdcNetwork), Not(Equals), 0)
   475  	check.Assert(orgVdcNetwork[0].Name, Equals, networkName)
   476  	check.Assert(orgVdcNetwork[0].ConnectedTo, Equals, externalNetwork.ExternalNetwork.Name)
   477  	network, err := vcd.vdc.GetOrgVdcNetworkByName(networkName, true)
   478  	check.Assert(err, IsNil)
   479  	task, err = network.Delete()
   480  	check.Assert(err, IsNil)
   481  	err = task.WaitTaskCompletion()
   482  	check.Assert(err, IsNil)
   483  }
   484  
   485  func (vcd *TestVCD) Test_QueryProviderVdcEntities(check *C) {
   486  	vcd.skipIfNotSysAdmin(check)
   487  	providerVdcName := vcd.config.VCD.ProviderVdc.Name
   488  	networkPoolName := vcd.config.VCD.ProviderVdc.NetworkPool
   489  	storageProfileName := vcd.config.VCD.ProviderVdc.StorageProfile
   490  	if providerVdcName == "" {
   491  		check.Skip("Skipping Provider VDC query: no provider VDC was given")
   492  	}
   493  	providerVdcs, err := vcd.client.QueryProviderVdcs()
   494  	check.Assert(err, IsNil)
   495  	check.Assert(len(providerVdcName) > 0, Equals, true)
   496  
   497  	providerFound := false
   498  	for _, providerVdc := range providerVdcs {
   499  		if providerVdcName == providerVdc.Name {
   500  			providerFound = true
   501  		}
   502  
   503  		if testVerbose {
   504  			fmt.Printf("PVDC %s\n", providerVdc.Name)
   505  			fmt.Printf("\t href    %s\n", providerVdc.HREF)
   506  			fmt.Printf("\t status  %s\n", providerVdc.Status)
   507  			fmt.Printf("\t enabled %v\n", providerVdc.IsEnabled)
   508  			fmt.Println("")
   509  		}
   510  	}
   511  	check.Assert(providerFound, Equals, true)
   512  
   513  	if networkPoolName == "" {
   514  		check.Skip("Skipping Network pool query: no network pool was given")
   515  	}
   516  	netPools, err := vcd.client.QueryNetworkPools()
   517  	check.Assert(err, IsNil)
   518  	check.Assert(len(netPools) > 0, Equals, true)
   519  	networkPoolFound := false
   520  	for _, networkPool := range netPools {
   521  		if networkPoolName == networkPool.Name {
   522  			networkPoolFound = true
   523  		}
   524  		if testVerbose {
   525  			fmt.Printf("NP %s\n", networkPool.Name)
   526  			fmt.Printf("\t href %s\n", networkPool.HREF)
   527  			fmt.Printf("\t type %v\n", networkPool.NetworkPoolType)
   528  			fmt.Println("")
   529  		}
   530  	}
   531  	check.Assert(networkPoolFound, Equals, true)
   532  
   533  	if storageProfileName == "" {
   534  		check.Skip("Skipping storage profile query: no storage profile was given")
   535  	}
   536  	storageProfiles, err := vcd.client.Client.QueryAllProviderVdcStorageProfiles()
   537  	check.Assert(err, IsNil)
   538  	check.Assert(len(storageProfiles) > 0, Equals, true)
   539  	storageProfileFound := false
   540  	for _, sp := range storageProfiles {
   541  		if storageProfileName == sp.Name {
   542  			storageProfileFound = true
   543  		}
   544  		if testVerbose {
   545  			fmt.Printf("SP %s\n", sp.Name)
   546  			fmt.Printf("\t enabled     %12v\n", sp.IsEnabled)
   547  			fmt.Printf("\t storage     %12d\n", sp.StorageTotalMB)
   548  			fmt.Printf("\t provisioned %12d\n", sp.StorageProvisionedMB)
   549  			fmt.Printf("\t requested   %12d\n", sp.StorageRequestedMB)
   550  			fmt.Printf("\t used        %12d\n", sp.StorageUsedMB)
   551  			fmt.Println("")
   552  		}
   553  	}
   554  	check.Assert(storageProfileFound, Equals, true)
   555  
   556  }
   557  
   558  func (vcd *TestVCD) Test_QueryProviderVdcByName(check *C) {
   559  	vcd.skipIfNotSysAdmin(check)
   560  	if vcd.config.VCD.ProviderVdc.Name == "" {
   561  		check.Skip("Skipping Provider VDC query: no provider VDC was given")
   562  	}
   563  	providerVdcs, err := QueryProviderVdcByName(vcd.client, vcd.config.VCD.ProviderVdc.Name)
   564  	check.Assert(err, IsNil)
   565  	check.Assert(len(providerVdcs) > 0, Equals, true)
   566  
   567  	providerFound := false
   568  	for _, providerVdc := range providerVdcs {
   569  		if vcd.config.VCD.ProviderVdc.Name == providerVdc.Name {
   570  			providerFound = true
   571  		}
   572  
   573  		if testVerbose {
   574  			fmt.Printf("PVDC %s\n", providerVdc.Name)
   575  			fmt.Printf("\t href    %s\n", providerVdc.HREF)
   576  			fmt.Printf("\t status  %s\n", providerVdc.Status)
   577  			fmt.Printf("\t enabled %v\n", providerVdc.IsEnabled)
   578  			fmt.Println("")
   579  		}
   580  	}
   581  	check.Assert(providerFound, Equals, true)
   582  
   583  }
   584  
   585  func (vcd *TestVCD) Test_QueryAdminOrgVdcStorageProfileByID(check *C) {
   586  	if !vcd.client.Client.IsSysAdmin {
   587  		check.Skip("Skipping Admin VDC StorageProfile query: can't query as tenant user")
   588  	}
   589  	if vcd.config.VCD.StorageProfile.SP1 == "" {
   590  		check.Skip("Skipping VDC StorageProfile query: no StorageProfile ID was given")
   591  	}
   592  	ref, err := vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
   593  	check.Assert(err, IsNil)
   594  	expectedStorageProfileID, err := GetUuidFromHref(ref.HREF, true)
   595  	check.Assert(err, IsNil)
   596  	vdcStorageProfile, err := QueryAdminOrgVdcStorageProfileByID(vcd.client, ref.ID)
   597  	check.Assert(err, IsNil)
   598  
   599  	storageProfileFound := false
   600  
   601  	storageProfileID, err := GetUuidFromHref(vdcStorageProfile.HREF, true)
   602  	check.Assert(err, IsNil)
   603  	if storageProfileID == expectedStorageProfileID {
   604  		storageProfileFound = true
   605  	}
   606  
   607  	if testVerbose {
   608  		fmt.Printf("StorageProfile %s\n", vdcStorageProfile.Name)
   609  		fmt.Printf("\t href    %s\n", vdcStorageProfile.HREF)
   610  		fmt.Printf("\t enabled %v\n", vdcStorageProfile.IsEnabled)
   611  		fmt.Println("")
   612  	}
   613  
   614  	check.Assert(storageProfileFound, Equals, true)
   615  }
   616  
   617  func (vcd *TestVCD) Test_QueryOrgVdcStorageProfileByID(check *C) {
   618  	if vcd.config.VCD.StorageProfile.SP1 == "" {
   619  		check.Skip("Skipping VDC StorageProfile query: no StorageProfile ID was given")
   620  	}
   621  
   622  	// Setup Org user and connection
   623  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.config.VCD.Org)
   624  	check.Assert(err, IsNil)
   625  
   626  	orgUserVcdClient, _, err := newOrgUserConnection(adminOrg, "query-org-vdc-storage-profile-by-id", "CHANGE-ME", vcd.config.Provider.Url, true)
   627  	check.Assert(err, IsNil)
   628  
   629  	ref, err := vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
   630  	check.Assert(err, IsNil)
   631  	expectedStorageProfileID, err := GetUuidFromHref(ref.HREF, true)
   632  	check.Assert(err, IsNil)
   633  	vdcStorageProfile, err := QueryOrgVdcStorageProfileByID(orgUserVcdClient, ref.ID)
   634  	check.Assert(err, IsNil)
   635  
   636  	storageProfileFound := false
   637  
   638  	storageProfileID, err := GetUuidFromHref(vdcStorageProfile.HREF, true)
   639  	check.Assert(err, IsNil)
   640  	if storageProfileID == expectedStorageProfileID {
   641  		storageProfileFound = true
   642  	}
   643  
   644  	if testVerbose {
   645  		fmt.Printf("StorageProfile %s\n", vdcStorageProfile.Name)
   646  		fmt.Printf("\t href    %s\n", vdcStorageProfile.HREF)
   647  		fmt.Printf("\t enabled %v\n", vdcStorageProfile.IsEnabled)
   648  		fmt.Println("")
   649  	}
   650  
   651  	check.Assert(storageProfileFound, Equals, true)
   652  }
   653  
   654  func (vcd *TestVCD) Test_QueryNetworkPoolByName(check *C) {
   655  	vcd.skipIfNotSysAdmin(check)
   656  	if vcd.config.VCD.ProviderVdc.NetworkPool == "" {
   657  		check.Skip("Skipping Provider VDC network pool query: no provider VDC network pool was given")
   658  	}
   659  	netPools, err := QueryNetworkPoolByName(vcd.client, vcd.config.VCD.ProviderVdc.NetworkPool)
   660  	check.Assert(err, IsNil)
   661  	check.Assert(len(netPools) > 0, Equals, true)
   662  
   663  	networkPoolFound := false
   664  	for _, networkPool := range netPools {
   665  		if vcd.config.VCD.ProviderVdc.NetworkPool == networkPool.Name {
   666  			networkPoolFound = true
   667  		}
   668  		if testVerbose {
   669  			fmt.Printf("NP %s\n", networkPool.Name)
   670  			fmt.Printf("\t href %s\n", networkPool.HREF)
   671  			fmt.Printf("\t type %v\n", networkPool.NetworkPoolType)
   672  			fmt.Println("")
   673  		}
   674  	}
   675  	check.Assert(networkPoolFound, Equals, true)
   676  
   677  }
   678  
   679  // Test_GetStorageProfile tests all the getters of Storage Profile
   680  func (vcd *TestVCD) Test_GetStorageProfile(check *C) {
   681  	if vcd.config.VCD.ProviderVdc.StorageProfile == "" {
   682  		check.Skip("Skipping test because storage profile is not configured")
   683  	}
   684  
   685  	fmt.Printf("Running: %s\n", check.TestName())
   686  
   687  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.config.VCD.Org)
   688  	check.Assert(err, IsNil)
   689  	check.Assert(adminOrg, NotNil)
   690  
   691  	adminVdc, err := adminOrg.GetAdminVDCByName(vcd.config.VCD.Vdc, false)
   692  	check.Assert(err, IsNil)
   693  	check.Assert(adminVdc, NotNil)
   694  
   695  	// Get storage profile by href
   696  	foundStorageProfile, err := vcd.client.Client.GetStorageProfileByHref(adminVdc.AdminVdc.VdcStorageProfiles.VdcStorageProfile[0].HREF)
   697  	check.Assert(err, IsNil)
   698  	check.Assert(foundStorageProfile, NotNil)
   699  	check.Assert(foundStorageProfile.IopsSettings, NotNil)
   700  	check.Assert(foundStorageProfile, Not(Equals), types.VdcStorageProfile{})
   701  	check.Assert(foundStorageProfile.IopsSettings, Not(Equals), types.VdcStorageProfileIopsSettings{})
   702  
   703  	// Get storage profile by ID
   704  	foundStorageProfile2, err := vcd.client.GetStorageProfileById(foundStorageProfile.ID)
   705  	check.Assert(err, IsNil)
   706  	check.Assert(foundStorageProfile, DeepEquals, foundStorageProfile2)
   707  }
   708  
   709  func (vcd *TestVCD) Test_GetOrgList(check *C) {
   710  
   711  	orgs, err := vcd.client.GetOrgList()
   712  	check.Assert(err, IsNil)
   713  	check.Assert(orgs, NotNil)
   714  
   715  	if vcd.config.VCD.Org != "" {
   716  		foundOrg := false
   717  		for _, org := range orgs.Org {
   718  			if org.Name == vcd.config.VCD.Org {
   719  				foundOrg = true
   720  			}
   721  		}
   722  		check.Assert(foundOrg, Equals, true)
   723  	}
   724  }
   725  
   726  func (vcd *TestVCD) TestQueryAllVdcs(check *C) {
   727  	if vcd.skipAdminTests {
   728  		check.Skip(fmt.Sprintf(TestRequiresSysAdminPrivileges, check.TestName()))
   729  	}
   730  
   731  	allVdcs, err := vcd.client.Client.QueryAllVdcs()
   732  	check.Assert(err, IsNil)
   733  
   734  	// Check for at least that many VDCs in VCD
   735  	// expectedVdcCountInSystem = 1 NSX-V VDC
   736  	expectedVdcCountInSystem := 1
   737  	// If an NSX-T VDC exists - then expected count of VDCs is at least 2
   738  	if vcd.config.VCD.Nsxt.Vdc != "" {
   739  		expectedVdcCountInSystem++
   740  	}
   741  
   742  	if testVerbose {
   743  		fmt.Printf("# List contains at least %d VDCs.", expectedVdcCountInSystem)
   744  	}
   745  	check.Assert(len(allVdcs) >= expectedVdcCountInSystem, Equals, true)
   746  	// Check that known VDCs are inside the list
   747  
   748  	knownVdcs := []string{vcd.config.VCD.Vdc}
   749  	if vcd.config.VCD.Nsxt.Vdc != "" {
   750  		knownVdcs = append(knownVdcs, vcd.config.VCD.Nsxt.Vdc)
   751  	}
   752  
   753  	foundVdcNames := make([]string, len(allVdcs))
   754  	for vdcIndex, vdc := range allVdcs {
   755  		foundVdcNames[vdcIndex] = vdc.Name
   756  	}
   757  
   758  	if testVerbose {
   759  		fmt.Printf("# Checking result contains all known VDCs (%s).", strings.Join((knownVdcs), ", "))
   760  	}
   761  	for _, knownVdcName := range knownVdcs {
   762  		check.Assert(contains(knownVdcName, foundVdcNames), Equals, true)
   763  	}
   764  }
   765  
   766  func (vcd *TestVCD) Test_NsxtGlobalDefaultSegmentProfileTemplate(check *C) {
   767  	skipNoNsxtConfiguration(vcd, check)
   768  	vcd.skipIfNotSysAdmin(check)
   769  
   770  	nsxtManager, err := vcd.client.GetNsxtManagerByName(vcd.config.VCD.Nsxt.Manager)
   771  	check.Assert(err, IsNil)
   772  	check.Assert(nsxtManager, NotNil)
   773  	nsxtManagerUrn, err := nsxtManager.Urn()
   774  	check.Assert(err, IsNil)
   775  
   776  	// Filter by NSX-T Manager
   777  	queryParams := copyOrNewUrlValues(nil)
   778  	queryParams = queryParameterFilterAnd(fmt.Sprintf("nsxTManagerRef.id==%s", nsxtManagerUrn), queryParams)
   779  
   780  	// Lookup prerequisite profiles for Segment Profile template creation
   781  	ipDiscoveryProfile, err := vcd.client.GetIpDiscoveryProfileByName(vcd.config.VCD.Nsxt.IpDiscoveryProfile, queryParams)
   782  	check.Assert(err, IsNil)
   783  	macDiscoveryProfile, err := vcd.client.GetMacDiscoveryProfileByName(vcd.config.VCD.Nsxt.MacDiscoveryProfile, queryParams)
   784  	check.Assert(err, IsNil)
   785  	spoofGuardProfile, err := vcd.client.GetSpoofGuardProfileByName(vcd.config.VCD.Nsxt.SpoofGuardProfile, queryParams)
   786  	check.Assert(err, IsNil)
   787  	qosProfile, err := vcd.client.GetQoSProfileByName(vcd.config.VCD.Nsxt.QosProfile, queryParams)
   788  	check.Assert(err, IsNil)
   789  	segmentSecurityProfile, err := vcd.client.GetSegmentSecurityProfileByName(vcd.config.VCD.Nsxt.SegmentSecurityProfile, queryParams)
   790  	check.Assert(err, IsNil)
   791  
   792  	config := &types.NsxtSegmentProfileTemplate{
   793  		Name:                   check.TestName(),
   794  		Description:            check.TestName() + "-description",
   795  		IPDiscoveryProfile:     &types.Reference{ID: ipDiscoveryProfile.ID},
   796  		MacDiscoveryProfile:    &types.Reference{ID: macDiscoveryProfile.ID},
   797  		QosProfile:             &types.Reference{ID: qosProfile.ID},
   798  		SegmentSecurityProfile: &types.Reference{ID: segmentSecurityProfile.ID},
   799  		SpoofGuardProfile:      &types.Reference{ID: spoofGuardProfile.ID},
   800  		SourceNsxTManagerRef:   &types.OpenApiReference{ID: nsxtManager.NsxtManager.ID},
   801  	}
   802  
   803  	createdSegmentProfileTemplate, err := vcd.client.CreateSegmentProfileTemplate(config)
   804  	check.Assert(err, IsNil)
   805  	check.Assert(createdSegmentProfileTemplate, NotNil)
   806  
   807  	// Add to cleanup list
   808  	openApiEndpoint := types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointNsxtSegmentProfileTemplates + createdSegmentProfileTemplate.NsxtSegmentProfileTemplate.ID
   809  	AddToCleanupListOpenApi(config.Name, check.TestName(), openApiEndpoint)
   810  
   811  	// Set global profile template
   812  	globalDefaultSegmentProfileConfig := &types.NsxtGlobalDefaultSegmentProfileTemplate{
   813  		VappNetworkSegmentProfileTemplateRef: &types.OpenApiReference{ID: createdSegmentProfileTemplate.NsxtSegmentProfileTemplate.ID},
   814  		VdcNetworkSegmentProfileTemplateRef:  &types.OpenApiReference{ID: createdSegmentProfileTemplate.NsxtSegmentProfileTemplate.ID},
   815  	}
   816  
   817  	updatedDefaults, err := vcd.client.UpdateGlobalDefaultSegmentProfileTemplates(globalDefaultSegmentProfileConfig)
   818  	check.Assert(err, IsNil)
   819  	check.Assert(updatedDefaults, NotNil)
   820  	check.Assert(updatedDefaults.VappNetworkSegmentProfileTemplateRef.ID, Equals, createdSegmentProfileTemplate.NsxtSegmentProfileTemplate.ID)
   821  	check.Assert(updatedDefaults.VdcNetworkSegmentProfileTemplateRef.ID, Equals, createdSegmentProfileTemplate.NsxtSegmentProfileTemplate.ID)
   822  
   823  	openApiEndpoint = types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointNsxtGlobalDefaultSegmentProfileTemplates
   824  	PrependToCleanupList(openApiEndpoint, "OpenApiEntityGlobalDefaultSegmentProfileTemplate", "", check.TestName())
   825  
   826  	// Cleanup
   827  	resetDefaults, err := vcd.client.UpdateGlobalDefaultSegmentProfileTemplates(&types.NsxtGlobalDefaultSegmentProfileTemplate{})
   828  	check.Assert(err, IsNil)
   829  	check.Assert(resetDefaults, NotNil)
   830  	check.Assert(resetDefaults.VappNetworkSegmentProfileTemplateRef, IsNil)
   831  	check.Assert(resetDefaults.VdcNetworkSegmentProfileTemplateRef, IsNil)
   832  
   833  	err = createdSegmentProfileTemplate.Delete()
   834  	check.Assert(err, IsNil)
   835  }