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

     1  //go:build vm || functional || ALL
     2  
     3  /*
     4  * Copyright 2021 VMware, Inc.  All rights reserved.  Licensed under the Apache v2 License.
     5  * Copyright 2016 Skyscape Cloud Services.  All rights reserved.  Licensed under the Apache v2 License.
     6   */
     7  
     8  package govcd
     9  
    10  import (
    11  	"fmt"
    12  	"strings"
    13  	"time"
    14  
    15  	"github.com/kr/pretty"
    16  	. "gopkg.in/check.v1"
    17  
    18  	"github.com/vmware/go-vcloud-director/v2/types/v56"
    19  	"github.com/vmware/go-vcloud-director/v2/util"
    20  )
    21  
    22  func init() {
    23  	testingTags["vm"] = "vm_test.go"
    24  }
    25  
    26  func (vcd *TestVCD) Test_FindVMByHREF(check *C) {
    27  	if vcd.skipVappTests {
    28  		check.Skip("Skipping test because vApp wasn't properly created")
    29  	}
    30  
    31  	fmt.Printf("Running: %s\n", check.TestName())
    32  	vapp := vcd.findFirstVapp()
    33  	if vapp.VApp.Name == "" {
    34  		check.Skip("Disabled: No suitable vApp found in vDC")
    35  	}
    36  	vm, vmName := vcd.findFirstVm(vapp)
    37  	if vm.Name == "" {
    38  		check.Skip("Disabled: No suitable VM found in vDC")
    39  	}
    40  
    41  	newVM, err := vcd.client.Client.GetVMByHref(vm.HREF)
    42  	check.Assert(err, IsNil)
    43  	check.Assert(newVM.VM.Name, Equals, vmName)
    44  	check.Assert(newVM.VM.VirtualHardwareSection.Item, NotNil)
    45  }
    46  
    47  // Test attach disk to VM and detach disk from VM
    48  func (vcd *TestVCD) Test_VMAttachOrDetachDisk(check *C) {
    49  	// Find VM
    50  	if skipVappCreation {
    51  		check.Skip("Skipping test because vapp was not successfully created at setup")
    52  	}
    53  
    54  	vapp := vcd.findFirstVapp()
    55  	vmType, vmName := vcd.findFirstVm(vapp)
    56  	if vmName == "" {
    57  		check.Skip("skipping test because no VM is found")
    58  	}
    59  
    60  	fmt.Printf("Running: %s\n", check.TestName())
    61  
    62  	vm := NewVM(&vcd.client.Client)
    63  	vm.VM = &vmType
    64  
    65  	// Ensure vApp and VM are suitable for this test
    66  	// Disk attach and detach operations are not working if VM is suspended
    67  	err := vcd.ensureVappIsSuitableForVMTest(vapp)
    68  	check.Assert(err, IsNil)
    69  	err = vcd.ensureVMIsSuitableForVMTest(vm)
    70  	check.Assert(err, IsNil)
    71  
    72  	// Create disk
    73  	diskCreateParamsDisk := &types.Disk{
    74  		Name:        TestVMAttachOrDetachDisk,
    75  		SizeMb:      1,
    76  		Description: TestVMAttachOrDetachDisk,
    77  	}
    78  
    79  	diskCreateParams := &types.DiskCreateParams{
    80  		Disk: diskCreateParamsDisk,
    81  	}
    82  
    83  	task, err := vcd.vdc.CreateDisk(diskCreateParams)
    84  	check.Assert(err, IsNil)
    85  
    86  	check.Assert(task.Task.Owner.Type, Equals, types.MimeDisk)
    87  	diskHREF := task.Task.Owner.HREF
    88  
    89  	PrependToCleanupList(diskHREF, "disk", "", check.TestName())
    90  
    91  	// Wait for disk creation complete
    92  	err = task.WaitTaskCompletion()
    93  	check.Assert(err, IsNil)
    94  
    95  	// Verify created disk
    96  	check.Assert(diskHREF, Not(Equals), "")
    97  	disk, err := vcd.vdc.GetDiskByHref(diskHREF)
    98  	check.Assert(err, IsNil)
    99  	check.Assert(disk.Disk.Name, Equals, diskCreateParamsDisk.Name)
   100  	check.Assert(disk.Disk.SizeMb, Equals, diskCreateParamsDisk.SizeMb)
   101  	check.Assert(disk.Disk.Description, Equals, diskCreateParamsDisk.Description)
   102  
   103  	// Attach disk
   104  	attachDiskTask, err := vm.attachOrDetachDisk(&types.DiskAttachOrDetachParams{
   105  		Disk: &types.Reference{
   106  			HREF: disk.Disk.HREF,
   107  		},
   108  	}, types.RelDiskAttach)
   109  	check.Assert(err, IsNil)
   110  
   111  	err = attachDiskTask.WaitTaskCompletion()
   112  	check.Assert(err, IsNil)
   113  
   114  	// Get attached VM
   115  	vmRef, err := disk.AttachedVM()
   116  	check.Assert(err, IsNil)
   117  	check.Assert(vmRef, NotNil)
   118  	check.Assert(vmRef.Name, Equals, vm.VM.Name)
   119  
   120  	// Detach disk
   121  	detachDiskTask, err := vm.attachOrDetachDisk(&types.DiskAttachOrDetachParams{
   122  		Disk: &types.Reference{
   123  			HREF: disk.Disk.HREF,
   124  		},
   125  	}, types.RelDiskDetach)
   126  	check.Assert(err, IsNil)
   127  
   128  	err = detachDiskTask.WaitTaskCompletion()
   129  	check.Assert(err, IsNil)
   130  
   131  }
   132  
   133  // Test attach/detach disk from VM
   134  func (vcd *TestVCD) Test_VMAttachAndDetachDisk(check *C) {
   135  	if vcd.skipVappTests {
   136  		check.Skip("skipping test because vApp wasn't properly created")
   137  	}
   138  
   139  	// Find VM
   140  	vapp := vcd.findFirstVapp()
   141  	vmType, vmName := vcd.findFirstVm(vapp)
   142  	if vmName == "" {
   143  		check.Skip("skipping test because no VM is found")
   144  	}
   145  
   146  	fmt.Printf("Running: %s\n", check.TestName())
   147  
   148  	vm := NewVM(&vcd.client.Client)
   149  	vm.VM = &vmType
   150  
   151  	// Ensure vApp and VM are suitable for this test
   152  	// Disk attach and detach operations are not working if VM is suspended
   153  	err := vcd.ensureVappIsSuitableForVMTest(vapp)
   154  	check.Assert(err, IsNil)
   155  	err = vcd.ensureVMIsSuitableForVMTest(vm)
   156  	check.Assert(err, IsNil)
   157  
   158  	// Create disk
   159  	diskCreateParamsDisk := &types.Disk{
   160  		Name:        TestVMDetachDisk,
   161  		SizeMb:      1,
   162  		Description: TestVMDetachDisk,
   163  	}
   164  
   165  	diskCreateParams := &types.DiskCreateParams{
   166  		Disk: diskCreateParamsDisk,
   167  	}
   168  
   169  	task, err := vcd.vdc.CreateDisk(diskCreateParams)
   170  	check.Assert(err, IsNil)
   171  
   172  	check.Assert(task.Task.Owner.Type, Equals, types.MimeDisk)
   173  	diskHREF := task.Task.Owner.HREF
   174  
   175  	// Defer prepend the disk info to cleanup list until the function returns
   176  	PrependToCleanupList(diskHREF, "disk", "", check.TestName())
   177  
   178  	// Wait for disk creation complete
   179  	err = task.WaitTaskCompletion()
   180  	check.Assert(err, IsNil)
   181  
   182  	// Verify created disk
   183  	check.Assert(diskHREF, Not(Equals), "")
   184  	disk, err := vcd.vdc.GetDiskByHref(diskHREF)
   185  	check.Assert(err, IsNil)
   186  	check.Assert(disk.Disk.Name, Equals, diskCreateParamsDisk.Name)
   187  	check.Assert(disk.Disk.SizeMb, Equals, diskCreateParamsDisk.SizeMb)
   188  	check.Assert(disk.Disk.Description, Equals, diskCreateParamsDisk.Description)
   189  
   190  	// Attach disk
   191  	attachDiskTask, err := vm.AttachDisk(&types.DiskAttachOrDetachParams{
   192  		Disk: &types.Reference{
   193  			HREF: disk.Disk.HREF,
   194  		},
   195  	})
   196  	check.Assert(err, IsNil)
   197  
   198  	err = attachDiskTask.WaitTaskCompletion()
   199  	check.Assert(err, IsNil)
   200  
   201  	// Get attached VM
   202  	vmRef, err := disk.AttachedVM()
   203  	check.Assert(err, IsNil)
   204  	check.Assert(vmRef, NotNil)
   205  	check.Assert(vmRef.Name, Equals, vm.VM.Name)
   206  
   207  	// Detach disk
   208  	detachDiskTask, err := vm.DetachDisk(&types.DiskAttachOrDetachParams{
   209  		Disk: &types.Reference{
   210  			HREF: disk.Disk.HREF,
   211  		},
   212  	})
   213  	check.Assert(err, IsNil)
   214  
   215  	err = detachDiskTask.WaitTaskCompletion()
   216  	check.Assert(err, IsNil)
   217  
   218  }
   219  
   220  // Test Insert or Eject Media for VM
   221  func (vcd *TestVCD) Test_HandleInsertOrEjectMedia(check *C) {
   222  	fmt.Printf("Running: %s\n", check.TestName())
   223  
   224  	if vcd.skipVappTests {
   225  		check.Skip("Skipping test because vapp was not successfully created at setup")
   226  	}
   227  	itemName := check.TestName()
   228  
   229  	// Find VApp
   230  	if vcd.vapp != nil && vcd.vapp.VApp == nil {
   231  		check.Skip("skipping test because no vApp is found")
   232  	}
   233  
   234  	vapp := vcd.findFirstVapp()
   235  	vmType, vmName := vcd.findFirstVm(vapp)
   236  	if vmName == "" {
   237  		check.Skip("skipping test because no VM is found")
   238  	}
   239  
   240  	vm := NewVM(&vcd.client.Client)
   241  	vm.VM = &vmType
   242  
   243  	// Upload Media
   244  	catalog, err := vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.Name, false)
   245  	check.Assert(err, IsNil)
   246  	check.Assert(catalog, NotNil)
   247  
   248  	uploadTask, err := catalog.UploadMediaImage(itemName, "upload from test", vcd.config.Media.MediaPath, 1024)
   249  	check.Assert(err, IsNil)
   250  	err = uploadTask.WaitTaskCompletion()
   251  	check.Assert(err, IsNil)
   252  
   253  	AddToCleanupList(itemName, "mediaCatalogImage", vcd.org.Org.Name+"|"+vcd.config.VCD.Catalog.Name, "Test_HandleInsertOrEjectMedia")
   254  
   255  	catalog, err = vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.Name, true)
   256  	check.Assert(err, IsNil)
   257  	check.Assert(catalog, NotNil)
   258  
   259  	media, err := catalog.GetMediaByName(itemName, false)
   260  	check.Assert(err, IsNil)
   261  	check.Assert(media, NotNil)
   262  
   263  	insertMediaTask, err := vm.HandleInsertMedia(vcd.org, vcd.config.VCD.Catalog.Name, itemName)
   264  	check.Assert(err, IsNil)
   265  
   266  	err = insertMediaTask.WaitTaskCompletion()
   267  	check.Assert(err, IsNil)
   268  
   269  	//verify
   270  	err = vm.Refresh()
   271  	check.Assert(err, IsNil)
   272  	check.Assert(isMediaInjected(vm.VM.VirtualHardwareSection.Item), Equals, true)
   273  
   274  	vm, err = vm.HandleEjectMediaAndAnswer(vcd.org, vcd.config.VCD.Catalog.Name, itemName, true)
   275  	check.Assert(err, IsNil)
   276  
   277  	//verify
   278  	check.Assert(isMediaInjected(vm.VM.VirtualHardwareSection.Item), Equals, false)
   279  
   280  	insertMediaTask, err = vm.HandleInsertMedia(vcd.org, vcd.config.VCD.Catalog.Name, itemName)
   281  	check.Assert(err, IsNil)
   282  
   283  	err = insertMediaTask.WaitTaskCompletion()
   284  	check.Assert(err, IsNil)
   285  
   286  	//verify
   287  	err = vm.Refresh()
   288  	check.Assert(err, IsNil)
   289  	check.Assert(isMediaInjected(vm.VM.VirtualHardwareSection.Item), Equals, true)
   290  
   291  	ejectMediaTask, err := vm.HandleEjectMedia(vcd.org, vcd.config.VCD.Catalog.Name, itemName)
   292  	check.Assert(err, IsNil)
   293  
   294  	for i := 0; i < 10; i++ {
   295  		question, err := vm.GetQuestion()
   296  		check.Assert(err, IsNil)
   297  
   298  		if question.QuestionId != "" && strings.Contains(question.Question, "Disconnect anyway and override the lock?") {
   299  			err = vm.AnswerQuestion(question.QuestionId, 0)
   300  			check.Assert(err, IsNil)
   301  		}
   302  		time.Sleep(time.Second * 3)
   303  	}
   304  
   305  	err = ejectMediaTask.Task.WaitTaskCompletion()
   306  	check.Assert(err, IsNil)
   307  
   308  	//verify
   309  	err = vm.Refresh()
   310  	check.Assert(err, IsNil)
   311  	check.Assert(isMediaInjected(vm.VM.VirtualHardwareSection.Item), Equals, false)
   312  
   313  	// Remove catalog item so far other tests don't fail
   314  	task, err := media.Delete()
   315  	check.Assert(err, IsNil)
   316  	err = task.WaitTaskCompletion()
   317  	check.Assert(err, IsNil)
   318  }
   319  
   320  func (vcd *TestVCD) Test_VMChangeCPUCountWithCore(check *C) {
   321  	if vcd.skipVappTests {
   322  		check.Skip("Skipping test because vapp was not successfully created at setup")
   323  	}
   324  
   325  	vapp := vcd.findFirstVapp()
   326  	existingVm, vmName := vcd.findFirstVm(vapp)
   327  	if vmName == "" {
   328  		check.Skip("skipping test because no VM is found")
   329  	}
   330  
   331  	currentCpus := int64(0)
   332  	currentCores := 0
   333  
   334  	// save current values
   335  	if nil != vcd.vapp.VApp.Children.VM[0] && nil != vcd.vapp.VApp.Children.VM[0].VirtualHardwareSection && nil != vcd.vapp.VApp.Children.VM[0].VirtualHardwareSection.Item {
   336  		for _, item := range vcd.vapp.VApp.Children.VM[0].VirtualHardwareSection.Item {
   337  			if item.ResourceType == types.ResourceTypeProcessor {
   338  				currentCpus = item.VirtualQuantity
   339  				currentCores = item.CoresPerSocket
   340  				break
   341  			}
   342  		}
   343  	}
   344  
   345  	check.Assert(0, Not(Equals), currentCpus)
   346  	check.Assert(0, Not(Equals), currentCores)
   347  
   348  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
   349  	check.Assert(err, IsNil)
   350  
   351  	cores := 2
   352  	cpuCount := int64(4)
   353  
   354  	task, err := vm.ChangeCPUCountWithCore(int(cpuCount), &cores)
   355  	check.Assert(err, IsNil)
   356  	err = task.WaitTaskCompletion()
   357  	check.Assert(err, IsNil)
   358  	check.Assert(task.Task.Status, Equals, "success")
   359  
   360  	err = vm.Refresh()
   361  	check.Assert(err, IsNil)
   362  	foundItem := false
   363  	if nil != vm.VM.VirtualHardwareSection.Item {
   364  		for _, item := range vm.VM.VirtualHardwareSection.Item {
   365  			if item.ResourceType == types.ResourceTypeProcessor {
   366  				check.Assert(item.CoresPerSocket, Equals, cores)
   367  				check.Assert(item.VirtualQuantity, Equals, cpuCount)
   368  				foundItem = true
   369  				break
   370  			}
   371  		}
   372  		check.Assert(foundItem, Equals, true)
   373  	}
   374  
   375  	// return to previous value
   376  	task, err = vm.ChangeCPUCountWithCore(int(currentCpus), &currentCores)
   377  	check.Assert(err, IsNil)
   378  	err = task.WaitTaskCompletion()
   379  	check.Assert(err, IsNil)
   380  	check.Assert(task.Task.Status, Equals, "success")
   381  }
   382  
   383  func (vcd *TestVCD) Test_VMToggleHardwareVirtualization(check *C) {
   384  	if vcd.skipVappTests {
   385  		check.Skip("Skipping test because vapp was not successfully created at setup")
   386  	}
   387  
   388  	_, vm := createNsxtVAppAndVm(vcd, check)
   389  
   390  	nestingStatus := vm.VM.NestedHypervisorEnabled
   391  	check.Assert(nestingStatus, Equals, false)
   392  
   393  	// PowerOn
   394  	task, err := vm.PowerOn()
   395  	check.Assert(err, IsNil)
   396  	err = task.WaitTaskCompletion()
   397  	check.Assert(err, IsNil)
   398  	check.Assert(task.Task.Status, Equals, "success")
   399  
   400  	// Try to change the setting on powered on VM to fail
   401  	_, err = vm.ToggleHardwareVirtualization(true)
   402  	check.Assert(err, ErrorMatches, ".*hardware virtualization can be changed from powered off state.*")
   403  
   404  	// Undeploy, so the VM goes to POWERED_OFF state instead of PARTIALLY_POWERED_OFF
   405  	task, err = vm.Undeploy()
   406  	check.Assert(err, IsNil)
   407  	err = task.WaitTaskCompletion()
   408  	check.Assert(err, IsNil)
   409  	check.Assert(task.Task.Status, Equals, "success")
   410  
   411  	// Perform steps on powered off VM
   412  	task, err = vm.ToggleHardwareVirtualization(true)
   413  	check.Assert(err, IsNil)
   414  	err = task.WaitTaskCompletion()
   415  	check.Assert(err, IsNil)
   416  	check.Assert(task.Task.Status, Equals, "success")
   417  
   418  	err = vm.Refresh()
   419  	check.Assert(err, IsNil)
   420  	check.Assert(vm.VM.NestedHypervisorEnabled, Equals, true)
   421  
   422  	task, err = vm.ToggleHardwareVirtualization(false)
   423  	check.Assert(err, IsNil)
   424  	err = task.WaitTaskCompletion()
   425  	check.Assert(err, IsNil)
   426  	check.Assert(task.Task.Status, Equals, "success")
   427  
   428  	err = vm.Refresh()
   429  	check.Assert(err, IsNil)
   430  	check.Assert(vm.VM.NestedHypervisorEnabled, Equals, false)
   431  
   432  	err = deleteNsxtVapp(vcd, check.TestName())
   433  	check.Assert(err, IsNil)
   434  }
   435  
   436  func (vcd *TestVCD) Test_VMPowerOnPowerOff(check *C) {
   437  	_, vm := createNsxtVAppAndVm(vcd, check)
   438  
   439  	// Ensure VM is not powered on
   440  	vmStatus, err := vm.GetStatus()
   441  	check.Assert(err, IsNil)
   442  	if vmStatus != "POWERED_OFF" && vmStatus != "PARTIALLY_POWERED_OFF" {
   443  		fmt.Printf("VM status: %s, powering off", vmStatus)
   444  		task, err := vm.PowerOff()
   445  		check.Assert(err, IsNil)
   446  		err = task.WaitTaskCompletion()
   447  		check.Assert(err, IsNil)
   448  		check.Assert(task.Task.Status, Equals, "success")
   449  	}
   450  
   451  	task, err := vm.PowerOn()
   452  	check.Assert(err, IsNil)
   453  	err = task.WaitTaskCompletion()
   454  	check.Assert(err, IsNil)
   455  	check.Assert(task.Task.Status, Equals, "success")
   456  	err = vm.Refresh()
   457  	check.Assert(err, IsNil)
   458  	vmStatus, err = vm.GetStatus()
   459  	check.Assert(err, IsNil)
   460  	check.Assert(vmStatus, Equals, "POWERED_ON")
   461  
   462  	task, err = vm.PowerOff()
   463  	check.Assert(err, IsNil)
   464  	err = task.WaitTaskCompletion()
   465  	check.Assert(err, IsNil)
   466  	check.Assert(task.Task.Status, Equals, "success")
   467  	vmStatus, err = vm.GetStatus()
   468  	check.Assert(err, IsNil)
   469  	check.Assert(vmStatus == "POWERED_OFF" || vmStatus == "PARTIALLY_POWERED_OFF", Equals, true)
   470  
   471  	err = deleteNsxtVapp(vcd, check.TestName())
   472  	check.Assert(err, IsNil)
   473  }
   474  
   475  func (vcd *TestVCD) Test_VmShutdown(check *C) {
   476  	vapp, vm := createNsxtVAppAndVm(vcd, check)
   477  
   478  	vdc, err := vm.GetParentVdc()
   479  	check.Assert(err, IsNil)
   480  
   481  	// Ensure VM is not powered on
   482  	vmStatus, err := vm.GetStatus()
   483  	check.Assert(err, IsNil)
   484  	fmt.Println("VM status: ", vmStatus)
   485  
   486  	if vmStatus != "POWERED_ON" {
   487  		task, err := vm.PowerOn()
   488  		check.Assert(err, IsNil)
   489  		err = task.WaitTaskCompletion()
   490  		check.Assert(err, IsNil)
   491  		check.Assert(task.Task.Status, Equals, "success")
   492  		err = vm.Refresh()
   493  		check.Assert(err, IsNil)
   494  		vmStatus, err = vm.GetStatus()
   495  		check.Assert(err, IsNil)
   496  		fmt.Println("VM status: ", vmStatus)
   497  	}
   498  
   499  	timeout := time.Minute * 5 // Avoiding infinite loops
   500  	startTime := time.Now()
   501  	elapsed := time.Since(startTime)
   502  	gcStatus := ""
   503  	statusFound := false
   504  	// Wait until Guest Tools gets to `REBOOT_PENDING` or `GC_COMPLETE` as there is no real way to
   505  	// check if VM has Guest Tools operating
   506  	for elapsed < timeout {
   507  		err = vm.Refresh()
   508  		check.Assert(err, IsNil)
   509  
   510  		vmQuery, err := vdc.QueryVM(vapp.VApp.Name, vm.VM.Name)
   511  		check.Assert(err, IsNil)
   512  
   513  		gcStatus = vmQuery.VM.GcStatus
   514  		printVerbose("VM Tools Status: %s (%s)\n", vmQuery.VM.GcStatus, elapsed)
   515  		if vmQuery.VM.GcStatus == "GC_COMPLETE" || vmQuery.VM.GcStatus == "REBOOT_PENDING" {
   516  			statusFound = true
   517  			break
   518  		}
   519  
   520  		time.Sleep(5 * time.Second)
   521  		elapsed = time.Since(startTime)
   522  	}
   523  	fmt.Printf("VM Tools Status: %s (%s)\n", gcStatus, elapsed)
   524  	check.Assert(statusFound, Equals, true)
   525  
   526  	printVerbose("Shutting down VM:\n")
   527  
   528  	task, err := vm.Shutdown()
   529  	check.Assert(err, IsNil)
   530  	err = task.WaitTaskCompletion()
   531  	check.Assert(err, IsNil)
   532  	check.Assert(task.Task.Status, Equals, "success")
   533  
   534  	newStatus, err := vm.GetStatus()
   535  	check.Assert(err, IsNil)
   536  	printVerbose("New VM status: %s\n", newStatus)
   537  	check.Assert(newStatus, Equals, "POWERED_OFF")
   538  
   539  	err = deleteNsxtVapp(vcd, check.TestName())
   540  	check.Assert(err, IsNil)
   541  }
   542  
   543  func (vcd *TestVCD) Test_GetNetworkConnectionSection(check *C) {
   544  	if vcd.skipVappTests {
   545  		check.Skip("Skipping test because vapp was not successfully created at setup")
   546  	}
   547  
   548  	vapp := vcd.findFirstVapp()
   549  	existingVm, vmName := vcd.findFirstVm(vapp)
   550  	if vmName == "" {
   551  		check.Skip("skipping test because no VM is found")
   552  	}
   553  
   554  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
   555  	check.Assert(err, IsNil)
   556  
   557  	networkBefore, err := vm.GetNetworkConnectionSection()
   558  	check.Assert(err, IsNil)
   559  
   560  	err = vm.UpdateNetworkConnectionSection(networkBefore)
   561  	check.Assert(err, IsNil)
   562  
   563  	networkAfter, err := vm.GetNetworkConnectionSection()
   564  	check.Assert(err, IsNil)
   565  
   566  	// Filter out always differing fields and do deep comparison of objects
   567  	networkBefore.Link = &types.Link{}
   568  	networkAfter.Link = &types.Link{}
   569  	check.Assert(networkAfter, DeepEquals, networkBefore)
   570  
   571  }
   572  
   573  // Test_PowerOnAndForceCustomization uses the VM from TestSuite and forces guest customization
   574  // in addition to the one which is triggered on first boot. It waits until the initial guest
   575  // customization after first power on is finished because it is inherited from the template.
   576  // After this initial wait it Undeploys VM and triggers a second customization and again waits until guest
   577  // customization status exits "GC_PENDING" state to succeed the test.
   578  // This test relies on longer timeouts in BlockWhileGuestCustomizationStatus because VMs take a lengthy time
   579  // to boot up and report customization done.
   580  func (vcd *TestVCD) Test_PowerOnAndForceCustomization(check *C) {
   581  
   582  	fmt.Printf("Running: %s\n", check.TestName())
   583  
   584  	_, vm := createNsxtVAppAndVm(vcd, check)
   585  
   586  	// It may be that prebuilt VM was not booted before in the test vApp and it would still have
   587  	// a guest customization status 'GC_PENDING'. This is because initially VM has this flag set
   588  	// but while this flag is here the test cannot actually check if vm.PowerOnAndForceCustomization()
   589  	// gives any effect therefore we must "wait through" initial guest customization if it is in
   590  	// 'GC_PENDING' state.
   591  	custStatus, err := vm.GetGuestCustomizationStatus()
   592  	check.Assert(err, IsNil)
   593  
   594  	vmStatus, err := vm.GetStatus()
   595  	check.Assert(err, IsNil)
   596  	if custStatus == types.GuestCustStatusPending {
   597  		// If VM is POWERED OFF - let's power it on before waiting for its status to change
   598  		if vmStatus == "POWERED_OFF" {
   599  			task, err := vm.PowerOn()
   600  			check.Assert(err, IsNil)
   601  			err = task.WaitTaskCompletion()
   602  			check.Assert(err, IsNil)
   603  			check.Assert(task.Task.Status, Equals, "success")
   604  		}
   605  
   606  		err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, 300)
   607  		check.Assert(err, IsNil)
   608  	}
   609  
   610  	// Check that VM is deployed
   611  	vmIsDeployed, err := vm.IsDeployed()
   612  	check.Assert(err, IsNil)
   613  	check.Assert(vmIsDeployed, Equals, true)
   614  
   615  	// Try to force operation on deployed VM and expect an error
   616  	err = vm.PowerOnAndForceCustomization()
   617  	check.Assert(err, NotNil)
   618  
   619  	// VM _must_ be un-deployed because PowerOnAndForceCustomization task will never finish (and
   620  	// probably not triggered) if it is not un-deployed.
   621  	task, err := vm.Undeploy()
   622  	check.Assert(err, IsNil)
   623  	err = task.WaitTaskCompletion()
   624  	check.Assert(err, IsNil)
   625  
   626  	// Check that VM is un-deployed
   627  	vmIsDeployed, err = vm.IsDeployed()
   628  	check.Assert(err, IsNil)
   629  	check.Assert(vmIsDeployed, Equals, false)
   630  
   631  	err = vm.PowerOnAndForceCustomization()
   632  	check.Assert(err, IsNil)
   633  
   634  	// Ensure that VM has the status set to "GC_PENDING" after forced re-customization
   635  	recustomizedVmStatus, err := vm.GetGuestCustomizationStatus()
   636  	check.Assert(err, IsNil)
   637  	check.Assert(recustomizedVmStatus, Equals, types.GuestCustStatusPending)
   638  
   639  	// Check that VM is deployed
   640  	vmIsDeployed, err = vm.IsDeployed()
   641  	check.Assert(err, IsNil)
   642  	check.Assert(vmIsDeployed, Equals, true)
   643  
   644  	// Wait until the VM exists GC_PENDING status again. At the moment this is the only simple way
   645  	// to see that the customization really worked as there is no API in vCD to execute remote
   646  	// commands on guest VMs
   647  	err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, 300)
   648  	check.Assert(err, IsNil)
   649  
   650  	err = deleteNsxtVapp(vcd, check.TestName())
   651  	check.Assert(err, IsNil)
   652  }
   653  
   654  func (vcd *TestVCD) Test_BlockWhileGuestCustomizationStatus(check *C) {
   655  	if vcd.skipVappTests {
   656  		check.Skip("Skipping test because vApp wasn't properly created")
   657  	}
   658  
   659  	fmt.Printf("Running: %s\n", check.TestName())
   660  	vapp := vcd.findFirstVapp()
   661  	existingVm, vmName := vcd.findFirstVm(vapp)
   662  	if vmName == "" {
   663  		check.Skip("skipping test because no VM is found")
   664  	}
   665  
   666  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
   667  	check.Assert(err, IsNil)
   668  
   669  	// Attempt to set invalid timeout values and expect validation error
   670  	err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, 0)
   671  	check.Assert(err, ErrorMatches, "timeOutAfterSeconds must be in range 4<X<7200")
   672  	err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, 4)
   673  	check.Assert(err, ErrorMatches, "timeOutAfterSeconds must be in range 4<X<7200")
   674  	err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, -30)
   675  	check.Assert(err, ErrorMatches, "timeOutAfterSeconds must be in range 4<X<7200")
   676  	err = vm.BlockWhileGuestCustomizationStatus(types.GuestCustStatusPending, 7201)
   677  	check.Assert(err, ErrorMatches, "timeOutAfterSeconds must be in range 4<X<7200")
   678  
   679  	vmCustStatus, err := vm.GetGuestCustomizationStatus()
   680  	check.Assert(err, IsNil)
   681  
   682  	// Use current value to trigger timeout
   683  	err = vm.BlockWhileGuestCustomizationStatus(vmCustStatus, 5)
   684  	check.Assert(err, ErrorMatches, "timed out waiting for VM guest customization status to exit state GC_PENDING after 5 seconds")
   685  
   686  	// Use unreal value to trigger instant unblocking
   687  	err = vm.BlockWhileGuestCustomizationStatus("invalid_GC_STATUS", 5)
   688  	check.Assert(err, IsNil)
   689  }
   690  
   691  // Test_VMSetProductSectionList sets product section, retrieves it and deeply matches if properties
   692  // were properly set using a propertyTester helper.
   693  func (vcd *TestVCD) Test_VMSetProductSectionList(check *C) {
   694  	if vcd.skipVappTests {
   695  		check.Skip("Skipping test because vapp was not successfully created at setup")
   696  	}
   697  	vapp := vcd.findFirstVapp()
   698  	existingVm, vmName := vcd.findFirstVm(vapp)
   699  	if vmName == "" {
   700  		check.Skip("skipping test because no VM is found")
   701  	}
   702  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
   703  	check.Assert(err, IsNil)
   704  	propertyTester(vcd, check, vm)
   705  }
   706  
   707  // Test_VMSetGetGuestCustomizationSection sets and when retrieves guest customization and checks if properties are right.
   708  func (vcd *TestVCD) Test_VMSetGetGuestCustomizationSection(check *C) {
   709  	if vcd.skipVappTests {
   710  		check.Skip("Skipping test because vapp was not successfully created at setup")
   711  	}
   712  	vapp := vcd.findFirstVapp()
   713  	existingVm, vmName := vcd.findFirstVm(vapp)
   714  	if vmName == "" {
   715  		check.Skip("skipping test because no VM is found")
   716  	}
   717  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
   718  	check.Assert(err, IsNil)
   719  	guestCustomizationPropertyTester(vcd, check, vm)
   720  }
   721  
   722  // Test create/update/remove of Internal Disk
   723  func (vcd *TestVCD) Test_InternalDisk(check *C) {
   724  	fmt.Printf("Running: %s\n", check.TestName())
   725  
   726  	// In general VM internal disks works with Org users, but due we need change VDC fast provisioning value, we have to be sys admins
   727  	if vcd.skipAdminTests {
   728  		check.Skip(fmt.Sprintf(TestRequiresSysAdminPrivileges, check.TestName()))
   729  	}
   730  	vmName := check.TestName()
   731  	vm, storageProfile, diskSettings, diskId, previousProvisioningValue, err := vcd.createInternalDisk(check, vmName, 1)
   732  	check.Assert(err, IsNil)
   733  
   734  	description := check.TestName() + "_Description"
   735  	vm, err = vm.UpdateVmSpecSection(vm.VM.VmSpecSection, description)
   736  	check.Assert(err, IsNil)
   737  
   738  	//verify
   739  	disk, err := vm.GetInternalDiskById(diskId, true)
   740  	check.Assert(err, IsNil)
   741  	check.Assert(disk, NotNil)
   742  
   743  	check.Assert(disk.StorageProfile.HREF, Equals, storageProfile.HREF)
   744  	check.Assert(disk.StorageProfile.ID, Equals, storageProfile.ID)
   745  	check.Assert(disk.AdapterType, Equals, diskSettings.AdapterType)
   746  	check.Assert(*disk.ThinProvisioned, Equals, *diskSettings.ThinProvisioned)
   747  	check.Assert(disk.IopsAllocation, NotNil)
   748  	check.Assert(diskSettings.IopsAllocation, NotNil)
   749  	check.Assert(disk.IopsAllocation.Reservation, Equals, diskSettings.IopsAllocation.Reservation)
   750  	check.Assert(disk.SizeMb, Equals, diskSettings.SizeMb)
   751  	check.Assert(disk.UnitNumber, Equals, diskSettings.UnitNumber)
   752  	check.Assert(disk.BusNumber, Equals, diskSettings.BusNumber)
   753  	check.Assert(disk.AdapterType, Equals, diskSettings.AdapterType)
   754  
   755  	// increase new disk size
   756  	vmSpecSection := vm.VM.VmSpecSection
   757  	changeDiskSettings := vm.VM.VmSpecSection.DiskSection.DiskSettings
   758  	for _, diskSettings := range changeDiskSettings {
   759  		if diskSettings.DiskId == diskId {
   760  			diskSettings.SizeMb = 2048
   761  		}
   762  	}
   763  
   764  	vmSpecSection.DiskSection.DiskSettings = changeDiskSettings
   765  
   766  	vmSpecSection, err = vm.UpdateInternalDisks(vmSpecSection)
   767  	check.Assert(err, IsNil)
   768  	check.Assert(vmSpecSection, NotNil)
   769  
   770  	disk, err = vm.GetInternalDiskById(diskId, true)
   771  	check.Assert(err, IsNil)
   772  	check.Assert(disk, NotNil)
   773  
   774  	//verify
   775  	check.Assert(disk.StorageProfile.HREF, Equals, storageProfile.HREF)
   776  	check.Assert(disk.StorageProfile.ID, Equals, storageProfile.ID)
   777  	check.Assert(disk.AdapterType, Equals, diskSettings.AdapterType)
   778  	check.Assert(*disk.ThinProvisioned, Equals, *diskSettings.ThinProvisioned)
   779  	check.Assert(disk.IopsAllocation.Reservation, Equals, diskSettings.IopsAllocation.Reservation)
   780  	check.Assert(disk.SizeMb, Equals, int64(2048))
   781  	check.Assert(disk.UnitNumber, Equals, diskSettings.UnitNumber)
   782  	check.Assert(disk.BusNumber, Equals, diskSettings.BusNumber)
   783  	check.Assert(disk.AdapterType, Equals, diskSettings.AdapterType)
   784  
   785  	// verify that VM description is still available - test for bugfix #418
   786  	err = vm.Refresh()
   787  	check.Assert(err, IsNil)
   788  	check.Assert(vm.VM.Description, Equals, description)
   789  
   790  	// attach independent disk
   791  	independentDisk, err := attachIndependentDisk(vcd, check, vm)
   792  	check.Assert(err, IsNil)
   793  
   794  	//cleanup
   795  	err = vm.DeleteInternalDisk(diskId)
   796  	check.Assert(err, IsNil)
   797  	detachIndependentDisk(vcd, check, independentDisk)
   798  
   799  	// disable fast provisioning if needed
   800  	updateVdcFastProvisioning(vcd, check, previousProvisioningValue)
   801  
   802  	// delete Vapp early to avoid env capacity issue
   803  	err = deleteVapp(vcd, vmName)
   804  	check.Assert(err, IsNil)
   805  }
   806  
   807  // createInternalDisk Finds available VM and creates internal Disk in it.
   808  // returns VM, storage profile, disk settings, disk id and error.
   809  func (vcd *TestVCD) createInternalDisk(check *C, vmName string, busNumber int) (*VM, types.Reference, *types.DiskSettings, string, string, error) {
   810  	if vcd.config.VCD.StorageProfile.SP1 == "" {
   811  		check.Skip("No Storage Profile given for VDC tests")
   812  	}
   813  
   814  	if vcd.config.VCD.Catalog.Name == "" {
   815  		check.Skip("No Catalog name given for VDC tests")
   816  	}
   817  
   818  	if vcd.config.VCD.Catalog.CatalogItem == "" {
   819  		check.Skip("No Catalog item given for VDC tests")
   820  	}
   821  
   822  	// disables fast provisioning if needed
   823  	previousVdcFastProvisioningValue := updateVdcFastProvisioning(vcd, check, "disable")
   824  	AddToCleanupList(previousVdcFastProvisioningValue, "fastProvisioning", vcd.config.VCD.Org+"|"+vcd.config.VCD.Vdc, "createInternalDisk")
   825  
   826  	vdc, _, vappTemplate, vapp, desiredNetConfig, err := vcd.createAndGetResourcesForVmCreation(check, vmName)
   827  	check.Assert(err, IsNil)
   828  
   829  	vm, err := spawnVM("FirstNode", 512, *vdc, *vapp, desiredNetConfig, vappTemplate, check, "", false)
   830  	check.Assert(err, IsNil)
   831  
   832  	storageProfile, err := vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
   833  	check.Assert(err, IsNil)
   834  	isThinProvisioned := true
   835  	diskSettings := &types.DiskSettings{
   836  		SizeMb:            1024,
   837  		UnitNumber:        0,
   838  		BusNumber:         busNumber,
   839  		AdapterType:       "4",
   840  		ThinProvisioned:   &isThinProvisioned,
   841  		StorageProfile:    &storageProfile,
   842  		OverrideVmDefault: true,
   843  		IopsAllocation: &types.IopsResource{
   844  			Limit:       0,
   845  			Reservation: 0,
   846  			SharesLevel: "NORMAL",
   847  			Shares:      1000,
   848  		},
   849  	}
   850  
   851  	diskId, err := vm.AddInternalDisk(diskSettings)
   852  	check.Assert(err, IsNil)
   853  	check.Assert(diskId, NotNil)
   854  	return &vm, storageProfile, diskSettings, diskId, previousVdcFastProvisioningValue, err
   855  }
   856  
   857  // updateVdcFastProvisioning Enables or Disables fast provisioning if needed
   858  func updateVdcFastProvisioning(vcd *TestVCD, check *C, enable string) string {
   859  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.config.VCD.Org)
   860  	check.Assert(err, IsNil)
   861  	check.Assert(adminOrg, NotNil)
   862  
   863  	adminVdc, err := adminOrg.GetAdminVDCByName(vcd.config.VCD.Vdc, true)
   864  	check.Assert(err, IsNil)
   865  	check.Assert(adminVdc, NotNil)
   866  
   867  	vdcFastProvisioningValue := "disabled"
   868  	if *adminVdc.AdminVdc.UsesFastProvisioning {
   869  		vdcFastProvisioningValue = "enable"
   870  	}
   871  
   872  	if *adminVdc.AdminVdc.UsesFastProvisioning && enable == "enable" {
   873  		return vdcFastProvisioningValue
   874  	}
   875  
   876  	if !*adminVdc.AdminVdc.UsesFastProvisioning && enable != "enable" {
   877  		return vdcFastProvisioningValue
   878  	}
   879  	valuePt := false
   880  	if enable == "enable" {
   881  		valuePt = true
   882  	}
   883  	adminVdc.AdminVdc.UsesFastProvisioning = &valuePt
   884  	_, err = adminVdc.Update()
   885  	check.Assert(err, IsNil)
   886  	return vdcFastProvisioningValue
   887  }
   888  
   889  func attachIndependentDisk(vcd *TestVCD, check *C, vm *VM) (*Disk, error) {
   890  	// Disk attach and detach operations are not working if VM is suspended
   891  	err := vcd.ensureVMIsSuitableForVMTest(vm)
   892  	check.Assert(err, IsNil)
   893  
   894  	// Create disk
   895  	diskCreateParamsDisk := &types.Disk{
   896  		Name:        TestAttachedVMDisk,
   897  		SizeMb:      1,
   898  		Description: TestAttachedVMDisk,
   899  	}
   900  
   901  	diskCreateParams := &types.DiskCreateParams{
   902  		Disk: diskCreateParamsDisk,
   903  	}
   904  
   905  	task, err := vcd.vdc.CreateDisk(diskCreateParams)
   906  	check.Assert(err, IsNil)
   907  
   908  	check.Assert(task.Task.Owner.Type, Equals, types.MimeDisk)
   909  	diskHREF := task.Task.Owner.HREF
   910  
   911  	PrependToCleanupList(diskHREF, "disk", "", check.TestName())
   912  
   913  	// Wait for disk creation complete
   914  	err = task.WaitTaskCompletion()
   915  	check.Assert(err, IsNil)
   916  
   917  	// Verify created disk
   918  	check.Assert(diskHREF, Not(Equals), "")
   919  	disk, err := vcd.vdc.GetDiskByHref(diskHREF)
   920  	check.Assert(err, IsNil)
   921  	check.Assert(disk.Disk.Name, Equals, diskCreateParamsDisk.Name)
   922  	check.Assert(disk.Disk.SizeMb, Equals, diskCreateParamsDisk.SizeMb)
   923  	check.Assert(disk.Disk.Description, Equals, diskCreateParamsDisk.Description)
   924  
   925  	// Attach disk
   926  	attachDiskTask, err := vm.AttachDisk(&types.DiskAttachOrDetachParams{
   927  		Disk: &types.Reference{
   928  			HREF: disk.Disk.HREF,
   929  		},
   930  	})
   931  	check.Assert(err, IsNil)
   932  
   933  	err = attachDiskTask.WaitTaskCompletion()
   934  	check.Assert(err, IsNil)
   935  	return disk, err
   936  }
   937  
   938  func detachIndependentDisk(vcd *TestVCD, check *C, disk *Disk) {
   939  	err := vcd.detachIndependentDisk(Disk{disk.Disk, &vcd.client.Client})
   940  	check.Assert(err, IsNil)
   941  }
   942  
   943  func (vcd *TestVCD) Test_VmGetParentvAppAndVdc(check *C) {
   944  	if vcd.skipVappTests {
   945  		check.Skip("Skipping test because vapp wasn't properly created")
   946  	}
   947  
   948  	fmt.Printf("Running: %s\n", check.TestName())
   949  	vapp := vcd.findFirstVapp()
   950  	if vapp.VApp.Name == "" {
   951  		check.Skip("Disabled: No suitable vApp found in vDC")
   952  	}
   953  	vm, vmName := vcd.findFirstVm(vapp)
   954  	if vm.Name == "" {
   955  		check.Skip("Disabled: No suitable VM found in vDC")
   956  	}
   957  
   958  	newVM, err := vcd.client.Client.GetVMByHref(vm.HREF)
   959  	check.Assert(err, IsNil)
   960  	check.Assert(newVM.VM.Name, Equals, vmName)
   961  	check.Assert(newVM.VM.VirtualHardwareSection.Item, NotNil)
   962  
   963  	parentvApp, err := newVM.GetParentVApp()
   964  	check.Assert(err, IsNil)
   965  	check.Assert(parentvApp.VApp.HREF, Equals, vapp.VApp.HREF)
   966  
   967  	parentVdc, err := newVM.GetParentVdc()
   968  	check.Assert(err, IsNil)
   969  	check.Assert(parentVdc.Vdc.Name, Equals, vcd.config.VCD.Vdc)
   970  }
   971  
   972  func (vcd *TestVCD) Test_AddNewEmptyVMMultiNIC(check *C) {
   973  
   974  	config := vcd.config
   975  	if config.VCD.Network.Net1 == "" {
   976  		check.Skip("Skipping test because no network was given")
   977  	}
   978  
   979  	// Find VApp
   980  	if vcd.vapp != nil && vcd.vapp.VApp == nil {
   981  		check.Skip("skipping test because no vApp is found")
   982  	}
   983  
   984  	vapp, err := deployVappForTest(vcd, "Test_AddNewEmptyVMMultiNIC")
   985  	check.Assert(err, IsNil)
   986  	check.Assert(vapp, NotNil)
   987  
   988  	desiredNetConfig := &types.NetworkConnectionSection{}
   989  	desiredNetConfig.PrimaryNetworkConnectionIndex = 0
   990  	desiredNetConfig.NetworkConnection = append(desiredNetConfig.NetworkConnection,
   991  		&types.NetworkConnection{
   992  			IsConnected:             true,
   993  			IPAddressAllocationMode: types.IPAllocationModePool,
   994  			Network:                 config.VCD.Network.Net1,
   995  			NetworkConnectionIndex:  0,
   996  		},
   997  		&types.NetworkConnection{
   998  			IsConnected:             true,
   999  			IPAddressAllocationMode: types.IPAllocationModeNone,
  1000  			Network:                 types.NoneNetwork,
  1001  			NetworkConnectionIndex:  1,
  1002  		})
  1003  
  1004  	// Test with two different networks if we have them
  1005  	if config.VCD.Network.Net2 != "" {
  1006  		// Attach second vdc network to vApp
  1007  		vdcNetwork2, err := vcd.vdc.GetOrgVdcNetworkByName(vcd.config.VCD.Network.Net2, false)
  1008  		check.Assert(err, IsNil)
  1009  		_, err = vapp.AddOrgNetwork(&VappNetworkSettings{}, vdcNetwork2.OrgVDCNetwork, false)
  1010  		check.Assert(err, IsNil)
  1011  
  1012  		desiredNetConfig.NetworkConnection = append(desiredNetConfig.NetworkConnection,
  1013  			&types.NetworkConnection{
  1014  				IsConnected:             true,
  1015  				IPAddressAllocationMode: types.IPAllocationModePool,
  1016  				Network:                 config.VCD.Network.Net2,
  1017  				NetworkConnectionIndex:  2,
  1018  			},
  1019  		)
  1020  	} else {
  1021  		fmt.Println("Skipping adding another vdc network as network2 was not specified")
  1022  	}
  1023  
  1024  	cat, err := vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.Name, true)
  1025  	check.Assert(err, IsNil)
  1026  	check.Assert(cat, NotNil)
  1027  
  1028  	media, err := cat.GetMediaByName(vcd.config.Media.Media, false)
  1029  	check.Assert(err, IsNil)
  1030  	check.Assert(media, NotNil)
  1031  
  1032  	var task Task
  1033  	var sp types.Reference
  1034  	var customSP = false
  1035  
  1036  	if vcd.config.VCD.StorageProfile.SP1 != "" {
  1037  		sp, _ = vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
  1038  	}
  1039  
  1040  	newDisk := types.DiskSettings{
  1041  		AdapterType:       "5",
  1042  		SizeMb:            int64(16384),
  1043  		BusNumber:         0,
  1044  		UnitNumber:        0,
  1045  		ThinProvisioned:   addrOf(true),
  1046  		OverrideVmDefault: true}
  1047  
  1048  	requestDetails := &types.RecomposeVAppParamsForEmptyVm{
  1049  		CreateItem: &types.CreateItem{
  1050  			Name:                      "Test_AddNewEmptyVMMultiNIC",
  1051  			NetworkConnectionSection:  desiredNetConfig,
  1052  			Description:               "created by Test_AddNewEmptyVMMultiNIC",
  1053  			GuestCustomizationSection: nil,
  1054  			VmSpecSection: &types.VmSpecSection{
  1055  				Modified:          addrOf(true),
  1056  				Info:              "Virtual Machine specification",
  1057  				OsType:            "debian10Guest",
  1058  				NumCpus:           addrOf(2),
  1059  				NumCoresPerSocket: addrOf(1),
  1060  				CpuResourceMhz:    &types.CpuResourceMhz{Configured: 1},
  1061  				MemoryResourceMb:  &types.MemoryResourceMb{Configured: 1024},
  1062  				DiskSection:       &types.DiskSection{DiskSettings: []*types.DiskSettings{&newDisk}},
  1063  				HardwareVersion:   &types.HardwareVersion{Value: "vmx-13"}, // need support older version vCD
  1064  				VmToolsVersion:    "",
  1065  				VirtualCpuType:    "VM32",
  1066  				TimeSyncWithHost:  nil,
  1067  			},
  1068  			BootImage: &types.Media{HREF: media.Media.HREF, Name: media.Media.Name, ID: media.Media.ID},
  1069  		},
  1070  		AllEULAsAccepted: true,
  1071  	}
  1072  
  1073  	createdVm, err := vapp.AddEmptyVm(requestDetails)
  1074  	check.Assert(err, IsNil)
  1075  	check.Assert(createdVm, NotNil)
  1076  
  1077  	// Ensure network config was valid
  1078  	actualNetConfig, err := createdVm.GetNetworkConnectionSection()
  1079  	check.Assert(err, IsNil)
  1080  
  1081  	if customSP {
  1082  		check.Assert(createdVm.VM.StorageProfile.HREF, Equals, sp.HREF)
  1083  	}
  1084  
  1085  	verifyNetworkConnectionSection(check, actualNetConfig, desiredNetConfig)
  1086  
  1087  	// Cleanup
  1088  	err = vapp.RemoveVM(*createdVm)
  1089  	check.Assert(err, IsNil)
  1090  
  1091  	// Ensure network is detached from vApp to avoid conflicts in other tests
  1092  	task, err = vapp.RemoveAllNetworks()
  1093  	check.Assert(err, IsNil)
  1094  	err = task.WaitTaskCompletion()
  1095  	check.Assert(err, IsNil)
  1096  	task, err = vapp.Delete()
  1097  	check.Assert(err, IsNil)
  1098  	err = task.WaitTaskCompletion()
  1099  	check.Assert(err, IsNil)
  1100  	check.Assert(task.Task.Status, Equals, "success")
  1101  }
  1102  
  1103  // Test update of VM Spec section
  1104  func (vcd *TestVCD) Test_UpdateVmSpecSection(check *C) {
  1105  	fmt.Printf("Running: %s\n", check.TestName())
  1106  
  1107  	vmName := check.TestName()
  1108  	if vcd.skipVappTests {
  1109  		check.Skip("Skipping test because vApp wasn't properly created")
  1110  	}
  1111  
  1112  	vdc, _, vappTemplate, vapp, desiredNetConfig, err := vcd.createAndGetResourcesForVmCreation(check, vmName)
  1113  	check.Assert(err, IsNil)
  1114  
  1115  	vm, err := spawnVM("FirstNode", 512, *vdc, *vapp, desiredNetConfig, vappTemplate, check, "", false)
  1116  	check.Assert(err, IsNil)
  1117  
  1118  	vmSpecSection := vm.VM.VmSpecSection
  1119  	vmSpecSection.NumCpus = addrOf(4)
  1120  	vmSpecSection.NumCoresPerSocket = addrOf(2)
  1121  	vmSpecSection.MemoryResourceMb = &types.MemoryResourceMb{Configured: 768}
  1122  	if vcd.client.Client.APIVCDMaxVersionIs(">=37.1") {
  1123  		vmSpecSection.Firmware = "efi"
  1124  	}
  1125  
  1126  	updatedVm, err := vm.UpdateVmSpecSection(vmSpecSection, "updateDescription")
  1127  	check.Assert(err, IsNil)
  1128  	check.Assert(updatedVm, NotNil)
  1129  
  1130  	//verify
  1131  	check.Assert(*updatedVm.VM.VmSpecSection.NumCpus, Equals, 4)
  1132  	check.Assert(*updatedVm.VM.VmSpecSection.NumCoresPerSocket, Equals, 2)
  1133  	check.Assert(updatedVm.VM.VmSpecSection.MemoryResourceMb.Configured, Equals, int64(768))
  1134  	check.Assert(updatedVm.VM.Description, Equals, "updateDescription")
  1135  	if vcd.client.Client.APIVCDMaxVersionIs(">=37.1") {
  1136  		check.Assert(updatedVm.VM.VmSpecSection.Firmware, Equals, "efi")
  1137  	}
  1138  
  1139  	// delete Vapp early to avoid env capacity issue
  1140  	err = deleteVapp(vcd, vmName)
  1141  	check.Assert(err, IsNil)
  1142  }
  1143  
  1144  func (vcd *TestVCD) Test_VmBootOptions(check *C) {
  1145  	fmt.Printf("Running: %s\n", check.TestName())
  1146  
  1147  	vmName := check.TestName()
  1148  	org, err := vcd.client.GetAdminOrgByName(vcd.config.VCD.Org)
  1149  	check.Assert(err, IsNil)
  1150  	vdc, err := org.GetVDCByName(vcd.config.VCD.Vdc, false)
  1151  	check.Assert(err, IsNil)
  1152  	check.Assert(vdc, NotNil)
  1153  
  1154  	_, vm := createNsxtVAppAndVmWithEfiSupport(vcd, check)
  1155  	check.Assert(err, IsNil)
  1156  
  1157  	hardwareVersion, err := vdc.GetHardwareVersion(vm.VM.VmSpecSection.HardwareVersion.Value)
  1158  	check.Assert(err, IsNil)
  1159  	check.Assert(hardwareVersion, NotNil)
  1160  
  1161  	var updatedVm *VM
  1162  	vmSpecSection := vm.VM.VmSpecSection
  1163  	supportsExtendedBootOptions := vcd.client.Client.APIVCDMaxVersionIs(">=37.1")
  1164  	if supportsExtendedBootOptions {
  1165  		vmSpecSection.Firmware = "efi"
  1166  		updatedVm, err = vm.UpdateVmSpecSection(vmSpecSection, "updateDescription")
  1167  		check.Assert(err, IsNil)
  1168  		check.Assert(updatedVm.VM.VmSpecSection.Firmware, Equals, "efi")
  1169  		check.Assert(updatedVm, NotNil)
  1170  	}
  1171  
  1172  	bootOptions := &types.BootOptions{}
  1173  	bootOptions.EnterBiosSetup = addrOf(true)
  1174  	bootOptions.BootDelay = addrOf(1)
  1175  
  1176  	if supportsExtendedBootOptions {
  1177  		bootOptions.EfiSecureBootEnabled = addrOf(true)
  1178  		bootOptions.BootRetryEnabled = addrOf(true)
  1179  		bootOptions.BootRetryDelay = addrOf(200)
  1180  	}
  1181  
  1182  	updatedVm, err = vm.UpdateBootOptions(bootOptions)
  1183  	check.Assert(err, IsNil)
  1184  
  1185  	if supportsExtendedBootOptions {
  1186  		check.Assert(updatedVm.VM.BootOptions.BootRetryEnabled, DeepEquals, addrOf(true))
  1187  		check.Assert(updatedVm.VM.BootOptions.BootRetryDelay, DeepEquals, addrOf(200))
  1188  		check.Assert(updatedVm.VM.BootOptions.EfiSecureBootEnabled, DeepEquals, addrOf(true))
  1189  	}
  1190  	check.Assert(updatedVm.VM.BootOptions.EnterBiosSetup, DeepEquals, addrOf(true))
  1191  	check.Assert(updatedVm.VM.BootOptions.BootDelay, DeepEquals, addrOf(1))
  1192  
  1193  	task, err := updatedVm.PowerOn()
  1194  	check.Assert(err, IsNil)
  1195  
  1196  	err = task.WaitTaskCompletion()
  1197  	check.Assert(err, IsNil)
  1198  
  1199  	task, err = updatedVm.PowerOff()
  1200  	check.Assert(err, IsNil)
  1201  
  1202  	err = task.WaitTaskCompletion()
  1203  	check.Assert(err, IsNil)
  1204  
  1205  	err = updatedVm.Refresh()
  1206  	check.Assert(err, IsNil)
  1207  
  1208  	check.Assert(updatedVm.VM.BootOptions.EnterBiosSetup, DeepEquals, addrOf(false))
  1209  
  1210  	// delete Vapp early to avoid env capacity issue
  1211  	err = deleteNsxtVapp(vcd, vmName)
  1212  	check.Assert(err, IsNil)
  1213  }
  1214  
  1215  func (vcd *TestVCD) Test_QueryVmList(check *C) {
  1216  
  1217  	if vcd.skipVappTests {
  1218  		check.Skip("Test_QueryVmList needs an existing vApp to run")
  1219  		return
  1220  	}
  1221  
  1222  	// Get the setUp vApp using traditional methods
  1223  	vapp, err := vcd.vdc.GetVAppByName(TestSetUpSuite, true)
  1224  	check.Assert(err, IsNil)
  1225  	vmName := ""
  1226  	for _, vm := range vapp.VApp.Children.VM {
  1227  		vmName = vm.Name
  1228  		break
  1229  	}
  1230  	if vmName == "" {
  1231  		check.Skip("No VM names found")
  1232  		return
  1233  	}
  1234  
  1235  	for filter := range []types.VmQueryFilter{types.VmQueryFilterOnlyDeployed, types.VmQueryFilterAll} {
  1236  		list, err := vcd.vdc.QueryVmList(types.VmQueryFilter(filter))
  1237  		check.Assert(err, IsNil)
  1238  		check.Assert(list, NotNil)
  1239  		foundVm := false
  1240  
  1241  		// Check the VM list for a known VM name
  1242  		for _, vm := range list {
  1243  			if vm.Name == vmName {
  1244  				foundVm = true
  1245  				break
  1246  			}
  1247  		}
  1248  		check.Assert(foundVm, Equals, true)
  1249  	}
  1250  }
  1251  
  1252  // Test update of VM Capabilities
  1253  func (vcd *TestVCD) Test_UpdateVmCpuAndMemoryHotAdd(check *C) {
  1254  	fmt.Printf("Running: %s\n", check.TestName())
  1255  
  1256  	vmName := "Test_UpdateVmCpuAndMemoryHotAdd"
  1257  	if vcd.skipVappTests {
  1258  		check.Skip("Skipping test because vApp wasn't properly created")
  1259  	}
  1260  
  1261  	vdc, _, vappTemplate, vapp, desiredNetConfig, err := vcd.createAndGetResourcesForVmCreation(check, vmName)
  1262  	check.Assert(err, IsNil)
  1263  
  1264  	vm, err := spawnVM("FirstNode", 512, *vdc, *vapp, desiredNetConfig, vappTemplate, check, "", false)
  1265  	check.Assert(err, IsNil)
  1266  
  1267  	check.Assert(vm.VM.VMCapabilities.MemoryHotAddEnabled, Equals, false)
  1268  	check.Assert(vm.VM.VMCapabilities.CPUHotAddEnabled, Equals, false)
  1269  
  1270  	updatedVm, err := vm.UpdateVmCpuAndMemoryHotAdd(true, true)
  1271  	check.Assert(err, IsNil)
  1272  	check.Assert(updatedVm, NotNil)
  1273  
  1274  	//verify
  1275  	check.Assert(updatedVm.VM.VMCapabilities.MemoryHotAddEnabled, Equals, true)
  1276  	check.Assert(updatedVm.VM.VMCapabilities.CPUHotAddEnabled, Equals, true)
  1277  
  1278  	// delete Vapp early to avoid env capacity issue
  1279  	err = deleteVapp(vcd, vmName)
  1280  	check.Assert(err, IsNil)
  1281  }
  1282  
  1283  func (vcd *TestVCD) Test_AddNewEmptyVMWithVmComputePolicyAndUpdate(check *C) {
  1284  	vcd.skipIfNotSysAdmin(check)
  1285  	vapp, err := deployVappForTest(vcd, "Test_AddNewEmptyVMWithVmComputePolicy")
  1286  	check.Assert(err, IsNil)
  1287  	check.Assert(vapp, NotNil)
  1288  
  1289  	cat, err := vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.Name, true)
  1290  	check.Assert(err, IsNil)
  1291  	check.Assert(cat, NotNil)
  1292  
  1293  	newComputePolicy := &VdcComputePolicy{
  1294  		client: vcd.org.client,
  1295  		VdcComputePolicy: &types.VdcComputePolicy{
  1296  			Name:        check.TestName() + "_empty",
  1297  			Description: addrOf("Empty policy created by test"),
  1298  		},
  1299  	}
  1300  
  1301  	newComputePolicy2 := &VdcComputePolicy{
  1302  		client: vcd.org.client,
  1303  		VdcComputePolicy: &types.VdcComputePolicy{
  1304  			Name:        check.TestName() + "_memory",
  1305  			Description: addrOf("Empty policy created by test 2"),
  1306  			Memory:      addrOf(2048),
  1307  		},
  1308  	}
  1309  
  1310  	// Create and assign compute policy
  1311  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.org.Org.Name)
  1312  	check.Assert(err, IsNil)
  1313  	check.Assert(adminOrg, NotNil)
  1314  
  1315  	adminVdc, err := adminOrg.GetAdminVDCByName(vcd.vdc.Vdc.Name, false)
  1316  	if adminVdc == nil || err != nil {
  1317  		vcd.infoCleanup(notFoundMsg, "vdc", vcd.vdc.Vdc.Name)
  1318  	}
  1319  
  1320  	createdPolicy, err := adminOrg.client.CreateVdcComputePolicy(newComputePolicy.VdcComputePolicy)
  1321  	check.Assert(err, IsNil)
  1322  
  1323  	createdPolicy2, err := adminOrg.client.CreateVdcComputePolicy(newComputePolicy2.VdcComputePolicy)
  1324  	check.Assert(err, IsNil)
  1325  
  1326  	AddToCleanupList(createdPolicy.VdcComputePolicy.ID, "vdcComputePolicy", vcd.org.Org.Name, "Test_AddNewEmptyVMWithVmComputePolicyAndUpdate")
  1327  	AddToCleanupList(createdPolicy2.VdcComputePolicy.ID, "vdcComputePolicy", vcd.org.Org.Name, "Test_AddNewEmptyVMWithVmComputePolicyAndUpdate")
  1328  
  1329  	vdcComputePolicyHref, err := adminOrg.client.OpenApiBuildEndpoint(types.OpenApiPathVersion1_0_0, types.OpenApiEndpointVdcComputePolicies)
  1330  	check.Assert(err, IsNil)
  1331  
  1332  	// Get policy to existing ones (can be only default one)
  1333  	allAssignedComputePolicies, err := adminVdc.GetAllAssignedVdcComputePolicies(nil)
  1334  	check.Assert(err, IsNil)
  1335  	var policyReferences []*types.Reference
  1336  	for _, assignedPolicy := range allAssignedComputePolicies {
  1337  		policyReferences = append(policyReferences, &types.Reference{HREF: vdcComputePolicyHref.String() + assignedPolicy.VdcComputePolicy.ID})
  1338  	}
  1339  	policyReferences = append(policyReferences, &types.Reference{HREF: vdcComputePolicyHref.String() + createdPolicy.VdcComputePolicy.ID})
  1340  	policyReferences = append(policyReferences, &types.Reference{HREF: vdcComputePolicyHref.String() + createdPolicy2.VdcComputePolicy.ID})
  1341  
  1342  	assignedVdcComputePolicies, err := adminVdc.SetAssignedComputePolicies(types.VdcComputePolicyReferences{VdcComputePolicyReference: policyReferences})
  1343  	check.Assert(err, IsNil)
  1344  	check.Assert(len(allAssignedComputePolicies)+2, Equals, len(assignedVdcComputePolicies.VdcComputePolicyReference))
  1345  	// end
  1346  
  1347  	var task Task
  1348  	var sp types.Reference
  1349  	var customSP = false
  1350  
  1351  	if vcd.config.VCD.StorageProfile.SP1 != "" {
  1352  		sp, _ = vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
  1353  	}
  1354  
  1355  	newDisk := types.DiskSettings{
  1356  		AdapterType:       "5",
  1357  		SizeMb:            int64(16384),
  1358  		BusNumber:         0,
  1359  		UnitNumber:        0,
  1360  		ThinProvisioned:   addrOf(true),
  1361  		OverrideVmDefault: true}
  1362  
  1363  	requestDetails := &types.RecomposeVAppParamsForEmptyVm{
  1364  		CreateItem: &types.CreateItem{
  1365  			Name:                      "Test_AddNewEmptyVMWithVmComputePolicy",
  1366  			Description:               "created by Test_AddNewEmptyVMWithVmComputePolicy",
  1367  			GuestCustomizationSection: nil,
  1368  			VmSpecSection: &types.VmSpecSection{
  1369  				Modified:          addrOf(true),
  1370  				Info:              "Virtual Machine specification",
  1371  				OsType:            "debian10Guest",
  1372  				NumCpus:           addrOf(2),
  1373  				NumCoresPerSocket: addrOf(1),
  1374  				CpuResourceMhz:    &types.CpuResourceMhz{Configured: 1},
  1375  				MemoryResourceMb:  &types.MemoryResourceMb{Configured: 1024},
  1376  				MediaSection:      nil,
  1377  				DiskSection:       &types.DiskSection{DiskSettings: []*types.DiskSettings{&newDisk}},
  1378  				HardwareVersion:   &types.HardwareVersion{Value: "vmx-13"}, // need support older version vCD
  1379  				VmToolsVersion:    "",
  1380  				VirtualCpuType:    "VM32",
  1381  				TimeSyncWithHost:  nil,
  1382  			},
  1383  			ComputePolicy: &types.ComputePolicy{VmSizingPolicy: &types.Reference{HREF: vdcComputePolicyHref.String() + createdPolicy.VdcComputePolicy.ID}},
  1384  		},
  1385  		AllEULAsAccepted: true,
  1386  	}
  1387  
  1388  	createdVm, err := vapp.AddEmptyVm(requestDetails)
  1389  	check.Assert(err, IsNil)
  1390  	check.Assert(createdVm, NotNil)
  1391  	check.Assert(createdVm.VM.ComputePolicy, NotNil)
  1392  	check.Assert(createdVm.VM.ComputePolicy.VmSizingPolicy, NotNil)
  1393  	check.Assert(createdVm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, createdPolicy.VdcComputePolicy.ID)
  1394  
  1395  	if customSP {
  1396  		check.Assert(createdVm.VM.StorageProfile.HREF, Equals, sp.HREF)
  1397  	}
  1398  
  1399  	updatedVm, err := createdVm.UpdateComputePolicy(createdPolicy2.VdcComputePolicy)
  1400  	check.Assert(err, IsNil)
  1401  	check.Assert(updatedVm, NotNil)
  1402  	check.Assert(updatedVm.VM.ComputePolicy, NotNil)
  1403  	check.Assert(updatedVm.VM.ComputePolicy.VmSizingPolicy, NotNil)
  1404  	check.Assert(updatedVm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, createdPolicy2.VdcComputePolicy.ID)
  1405  	check.Assert(updatedVm.VM.VmSpecSection.MemoryResourceMb, NotNil)
  1406  	check.Assert(updatedVm.VM.VmSpecSection.MemoryResourceMb.Configured, Equals, int64(2048))
  1407  
  1408  	// Cleanup
  1409  	err = vapp.RemoveVM(*createdVm)
  1410  	check.Assert(err, IsNil)
  1411  
  1412  	// Ensure network is detached from vApp to avoid conflicts in other tests
  1413  	task, err = vapp.RemoveAllNetworks()
  1414  	check.Assert(err, IsNil)
  1415  	err = task.WaitTaskCompletion()
  1416  	check.Assert(err, IsNil)
  1417  	task, err = vapp.Delete()
  1418  	check.Assert(err, IsNil)
  1419  	err = task.WaitTaskCompletion()
  1420  	check.Assert(err, IsNil)
  1421  	check.Assert(task.Task.Status, Equals, "success")
  1422  
  1423  	// cleanup assigned compute policy
  1424  	var beforeTestPolicyReferences []*types.Reference
  1425  	for _, assignedPolicy := range allAssignedComputePolicies {
  1426  		beforeTestPolicyReferences = append(beforeTestPolicyReferences, &types.Reference{HREF: vdcComputePolicyHref.String() + assignedPolicy.VdcComputePolicy.ID})
  1427  	}
  1428  
  1429  	_, err = adminVdc.SetAssignedComputePolicies(types.VdcComputePolicyReferences{VdcComputePolicyReference: beforeTestPolicyReferences})
  1430  	check.Assert(err, IsNil)
  1431  }
  1432  
  1433  func (vcd *TestVCD) Test_VMUpdateStorageProfile(check *C) {
  1434  	config := vcd.config
  1435  	if config.VCD.StorageProfile.SP1 == "" || config.VCD.StorageProfile.SP2 == "" {
  1436  		check.Skip("Skipping test because both storage profiles have to be configured")
  1437  	}
  1438  
  1439  	vapp, err := deployVappForTest(vcd, "Test_VMUpdateStorageProfile")
  1440  	check.Assert(err, IsNil)
  1441  	check.Assert(vapp, NotNil)
  1442  
  1443  	cat, err := vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.Name, true)
  1444  	check.Assert(err, IsNil)
  1445  	check.Assert(cat, NotNil)
  1446  
  1447  	var storageProfile types.Reference
  1448  
  1449  	storageProfile, _ = vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP1)
  1450  
  1451  	createdVm, err := makeEmptyVm(vapp, "Test_VMUpdateStorageProfile")
  1452  	check.Assert(err, IsNil)
  1453  	check.Assert(createdVm, NotNil)
  1454  	check.Assert(createdVm.VM.StorageProfile.HREF, Equals, storageProfile.HREF)
  1455  
  1456  	storageProfile2, _ := vcd.vdc.FindStorageProfileReference(vcd.config.VCD.StorageProfile.SP2)
  1457  	updatedVm, err := createdVm.UpdateStorageProfile(storageProfile2.HREF)
  1458  	check.Assert(err, IsNil)
  1459  	check.Assert(updatedVm, NotNil)
  1460  	check.Assert(createdVm.VM.StorageProfile.HREF, Equals, storageProfile2.HREF)
  1461  
  1462  	// Cleanup
  1463  	var task Task
  1464  	err = vapp.RemoveVM(*createdVm)
  1465  	check.Assert(err, IsNil)
  1466  
  1467  	// Ensure network is detached from vApp to avoid conflicts in other tests
  1468  	task, err = vapp.RemoveAllNetworks()
  1469  	check.Assert(err, IsNil)
  1470  	err = task.WaitTaskCompletion()
  1471  	check.Assert(err, IsNil)
  1472  	task, err = vapp.Delete()
  1473  	check.Assert(err, IsNil)
  1474  	err = task.WaitTaskCompletion()
  1475  	check.Assert(err, IsNil)
  1476  	check.Assert(task.Task.Status, Equals, "success")
  1477  }
  1478  
  1479  func (vcd *TestVCD) Test_VMUpdateComputePolicies(check *C) {
  1480  	vcd.skipIfNotSysAdmin(check)
  1481  	providerVdc, err := vcd.client.GetProviderVdcByName(vcd.config.VCD.NsxtProviderVdc.Name)
  1482  	check.Assert(err, IsNil)
  1483  	check.Assert(providerVdc, NotNil)
  1484  
  1485  	vmGroup, err := vcd.client.GetVmGroupByNameAndProviderVdcUrn(vcd.config.VCD.NsxtProviderVdc.PlacementPolicyVmGroup, providerVdc.ProviderVdc.ID)
  1486  	check.Assert(err, IsNil)
  1487  	check.Assert(vmGroup, NotNil)
  1488  
  1489  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.org.Org.Name)
  1490  	check.Assert(err, IsNil)
  1491  	check.Assert(adminOrg, NotNil)
  1492  
  1493  	adminVdc, err := adminOrg.GetAdminVDCByName(vcd.nsxtVdc.Vdc.Name, false)
  1494  	if adminVdc == nil || err != nil {
  1495  		vcd.infoCleanup(notFoundMsg, "vdc", vcd.nsxtVdc.Vdc.Name)
  1496  	}
  1497  
  1498  	// Create some Compute Policies
  1499  	var placementPolicies []*VdcComputePolicyV2
  1500  	var sizingPolicies []*VdcComputePolicyV2
  1501  	numberOfPolicies := 2
  1502  	for i := 0; i < numberOfPolicies; i++ {
  1503  		sizingPolicyName := fmt.Sprintf("%s_Sizing%d", check.TestName(), i+1)
  1504  		placementPolicyName := fmt.Sprintf("%s_Placement%d", check.TestName(), i+1)
  1505  
  1506  		sizingPolicies = append(sizingPolicies, &VdcComputePolicyV2{
  1507  			VdcComputePolicyV2: &types.VdcComputePolicyV2{
  1508  				VdcComputePolicy: types.VdcComputePolicy{
  1509  					Name:         sizingPolicyName,
  1510  					Description:  addrOf("Empty sizing policy created by test"),
  1511  					IsSizingOnly: true,
  1512  				},
  1513  				PolicyType: "VdcVmPolicy",
  1514  			},
  1515  		})
  1516  
  1517  		placementPolicies = append(placementPolicies, &VdcComputePolicyV2{
  1518  			VdcComputePolicyV2: &types.VdcComputePolicyV2{
  1519  				VdcComputePolicy: types.VdcComputePolicy{
  1520  					Name:         placementPolicyName,
  1521  					Description:  addrOf("Empty placement policy created by test"),
  1522  					IsSizingOnly: false,
  1523  				},
  1524  				PolicyType: "VdcVmPolicy",
  1525  				PvdcNamedVmGroupsMap: []types.PvdcNamedVmGroupsMap{
  1526  					{
  1527  						NamedVmGroups: []types.OpenApiReferences{{
  1528  							{
  1529  								Name: vmGroup.VmGroup.Name,
  1530  								ID:   fmt.Sprintf("urn:vcloud:namedVmGroup:%s", vmGroup.VmGroup.NamedVmGroupId),
  1531  							},
  1532  						}},
  1533  						Pvdc: types.OpenApiReference{
  1534  							Name: providerVdc.ProviderVdc.Name,
  1535  							ID:   providerVdc.ProviderVdc.ID,
  1536  						},
  1537  					},
  1538  				},
  1539  			},
  1540  		})
  1541  
  1542  		sizingPolicies[i], err = vcd.client.CreateVdcComputePolicyV2(sizingPolicies[i].VdcComputePolicyV2)
  1543  		check.Assert(err, IsNil)
  1544  		AddToCleanupList(sizingPolicies[i].VdcComputePolicyV2.ID, "vdcComputePolicy", vcd.org.Org.Name, sizingPolicyName)
  1545  
  1546  		placementPolicies[i], err = vcd.client.CreateVdcComputePolicyV2(placementPolicies[i].VdcComputePolicyV2)
  1547  		check.Assert(err, IsNil)
  1548  		AddToCleanupList(placementPolicies[i].VdcComputePolicyV2.ID, "vdcComputePolicy", vcd.org.Org.Name, placementPolicyName)
  1549  	}
  1550  
  1551  	vdcComputePolicyHref, err := adminOrg.client.OpenApiBuildEndpoint(types.OpenApiPathVersion2_0_0, types.OpenApiEndpointVdcComputePolicies)
  1552  	check.Assert(err, IsNil)
  1553  
  1554  	// Add the created compute policies to the ones that the VDC has already assigned
  1555  	alreadyAssignedPolicies, err := adminVdc.GetAllAssignedVdcComputePoliciesV2(nil)
  1556  	check.Assert(err, IsNil)
  1557  	var allComputePoliciesToAssign []*types.Reference
  1558  	for _, alreadyAssignedPolicy := range alreadyAssignedPolicies {
  1559  		allComputePoliciesToAssign = append(allComputePoliciesToAssign, &types.Reference{HREF: vdcComputePolicyHref.String() + alreadyAssignedPolicy.VdcComputePolicyV2.ID})
  1560  	}
  1561  	for i := 0; i < numberOfPolicies; i++ {
  1562  		allComputePoliciesToAssign = append(allComputePoliciesToAssign, &types.Reference{HREF: vdcComputePolicyHref.String() + sizingPolicies[i].VdcComputePolicyV2.ID})
  1563  		allComputePoliciesToAssign = append(allComputePoliciesToAssign, &types.Reference{HREF: vdcComputePolicyHref.String() + placementPolicies[i].VdcComputePolicyV2.ID})
  1564  	}
  1565  
  1566  	assignedVdcComputePolicies, err := adminVdc.SetAssignedComputePolicies(types.VdcComputePolicyReferences{VdcComputePolicyReference: allComputePoliciesToAssign})
  1567  	check.Assert(err, IsNil)
  1568  	check.Assert(len(alreadyAssignedPolicies)+numberOfPolicies*2, Equals, len(assignedVdcComputePolicies.VdcComputePolicyReference))
  1569  
  1570  	vapp, vm := createNsxtVAppAndVm(vcd, check)
  1571  	check.Assert(vapp, NotNil)
  1572  	check.Assert(vm, NotNil)
  1573  
  1574  	// Update all Compute Policies: Sizing and Placement
  1575  	check.Assert(err, IsNil)
  1576  	vm, err = vm.UpdateComputePolicyV2(sizingPolicies[0].VdcComputePolicyV2.ID, placementPolicies[0].VdcComputePolicyV2.ID, "")
  1577  	check.Assert(err, IsNil)
  1578  	check.Assert(vm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, sizingPolicies[0].VdcComputePolicyV2.ID)
  1579  	check.Assert(vm.VM.ComputePolicy.VmPlacementPolicy.ID, Equals, placementPolicies[0].VdcComputePolicyV2.ID)
  1580  
  1581  	// Update Sizing policy only
  1582  	vm, err = vm.UpdateComputePolicyV2(sizingPolicies[0].VdcComputePolicyV2.ID, placementPolicies[1].VdcComputePolicyV2.ID, "")
  1583  	check.Assert(err, IsNil)
  1584  	check.Assert(vm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, sizingPolicies[0].VdcComputePolicyV2.ID)
  1585  	check.Assert(vm.VM.ComputePolicy.VmPlacementPolicy.ID, Equals, placementPolicies[1].VdcComputePolicyV2.ID)
  1586  
  1587  	// Update Placement policy only
  1588  	vm, err = vm.UpdateComputePolicyV2(sizingPolicies[1].VdcComputePolicyV2.ID, placementPolicies[1].VdcComputePolicyV2.ID, "")
  1589  	check.Assert(err, IsNil)
  1590  	check.Assert(vm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, sizingPolicies[1].VdcComputePolicyV2.ID)
  1591  	check.Assert(vm.VM.ComputePolicy.VmPlacementPolicy.ID, Equals, placementPolicies[1].VdcComputePolicyV2.ID)
  1592  
  1593  	// Remove Placement Policy
  1594  	vm, err = vm.UpdateComputePolicyV2(sizingPolicies[1].VdcComputePolicyV2.ID, "", "")
  1595  	check.Assert(err, IsNil)
  1596  	check.Assert(vm.VM.ComputePolicy.VmSizingPolicy.ID, Equals, sizingPolicies[1].VdcComputePolicyV2.ID)
  1597  	check.Assert(vm.VM.ComputePolicy.VmPlacementPolicy, IsNil)
  1598  
  1599  	// Remove Sizing Policy
  1600  	vm, err = vm.UpdateComputePolicyV2("", placementPolicies[1].VdcComputePolicyV2.ID, "")
  1601  	check.Assert(err, IsNil)
  1602  	check.Assert(vm.VM.ComputePolicy.VmSizingPolicy, IsNil)
  1603  	check.Assert(vm.VM.ComputePolicy.VmPlacementPolicy.ID, Equals, placementPolicies[1].VdcComputePolicyV2.ID)
  1604  
  1605  	// Try to remove both, it should fail
  1606  	_, err = vm.UpdateComputePolicyV2("", "", "")
  1607  	check.Assert(err, NotNil)
  1608  	check.Assert(true, Equals, strings.Contains(err.Error(), "either sizing policy ID or placement policy ID is needed"))
  1609  
  1610  	// Clean VM
  1611  	task, err := vapp.Undeploy()
  1612  	check.Assert(err, IsNil)
  1613  	check.Assert(task, Not(Equals), Task{})
  1614  
  1615  	err = task.WaitTaskCompletion()
  1616  	check.Assert(err, IsNil)
  1617  
  1618  	task, err = vapp.Delete()
  1619  	check.Assert(err, IsNil)
  1620  	check.Assert(task, Not(Equals), Task{})
  1621  
  1622  	err = task.WaitTaskCompletion()
  1623  	check.Assert(err, IsNil)
  1624  
  1625  	// Cleanup assigned compute policies
  1626  	var beforeTestPolicyReferences []*types.Reference
  1627  	for _, assignedPolicy := range alreadyAssignedPolicies {
  1628  		beforeTestPolicyReferences = append(beforeTestPolicyReferences, &types.Reference{HREF: vdcComputePolicyHref.String() + assignedPolicy.VdcComputePolicyV2.ID})
  1629  	}
  1630  
  1631  	_, err = adminVdc.SetAssignedComputePolicies(types.VdcComputePolicyReferences{VdcComputePolicyReference: beforeTestPolicyReferences})
  1632  	check.Assert(err, IsNil)
  1633  }
  1634  
  1635  func (vcd *TestVCD) getNetworkConnection() *types.NetworkConnectionSection {
  1636  
  1637  	if vcd.config.VCD.Network.Net1 == "" {
  1638  		return nil
  1639  	}
  1640  	return &types.NetworkConnectionSection{
  1641  		Info:                          "Network Configuration for VM",
  1642  		PrimaryNetworkConnectionIndex: 0,
  1643  		NetworkConnection: []*types.NetworkConnection{
  1644  			&types.NetworkConnection{
  1645  				Network:                 vcd.config.VCD.Network.Net1,
  1646  				NeedsCustomization:      false,
  1647  				NetworkConnectionIndex:  0,
  1648  				IPAddress:               "any",
  1649  				IsConnected:             true,
  1650  				IPAddressAllocationMode: "DHCP",
  1651  				NetworkAdapterType:      "VMXNET3",
  1652  			},
  1653  		},
  1654  		Link: nil,
  1655  	}
  1656  }
  1657  
  1658  func (vcd *TestVCD) Test_CreateStandaloneVM(check *C) {
  1659  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.org.Org.Name)
  1660  	check.Assert(err, IsNil)
  1661  	check.Assert(adminOrg, NotNil)
  1662  
  1663  	vdc, err := adminOrg.GetVDCByName(vcd.vdc.Vdc.Name, false)
  1664  	check.Assert(err, IsNil)
  1665  	check.Assert(vdc, NotNil)
  1666  	description := "created by " + check.TestName()
  1667  	params := &types.CreateVmParams{
  1668  		Name:        "testStandaloneVm",
  1669  		PowerOn:     false,
  1670  		Description: description,
  1671  		CreateVm: &types.Vm{
  1672  			Name:                     "testStandaloneVm",
  1673  			VirtualHardwareSection:   nil,
  1674  			NetworkConnectionSection: vcd.getNetworkConnection(),
  1675  			VmSpecSection: &types.VmSpecSection{
  1676  				Modified:          addrOf(true),
  1677  				Info:              "Virtual Machine specification",
  1678  				OsType:            "sles11_64Guest",
  1679  				NumCpus:           addrOf(1),
  1680  				NumCoresPerSocket: addrOf(1),
  1681  				CpuResourceMhz: &types.CpuResourceMhz{
  1682  					Configured: 0,
  1683  				},
  1684  				MemoryResourceMb: &types.MemoryResourceMb{
  1685  					Configured: 512,
  1686  				},
  1687  				DiskSection: &types.DiskSection{
  1688  					DiskSettings: []*types.DiskSettings{
  1689  						{
  1690  							SizeMb:            1024,
  1691  							UnitNumber:        0,
  1692  							BusNumber:         0,
  1693  							AdapterType:       "5",
  1694  							ThinProvisioned:   addrOf(true),
  1695  							OverrideVmDefault: false,
  1696  						},
  1697  					},
  1698  				},
  1699  
  1700  				HardwareVersion: &types.HardwareVersion{Value: "vmx-14"},
  1701  				VmToolsVersion:  "",
  1702  				VirtualCpuType:  "VM32",
  1703  			},
  1704  			GuestCustomizationSection: &types.GuestCustomizationSection{
  1705  				Info:         "Specifies Guest OS Customization Settings",
  1706  				ComputerName: "standalone1",
  1707  			},
  1708  			BootOptions: &types.BootOptions{
  1709  				BootDelay: addrOf(0),
  1710  			},
  1711  		},
  1712  		Xmlns: types.XMLNamespaceVCloud,
  1713  	}
  1714  
  1715  	supportsExtendedBootOptions := vcd.client.Client.APIVCDMaxVersionIs(">=37.1")
  1716  	if supportsExtendedBootOptions {
  1717  		params.CreateVm.VmSpecSection.Firmware = "efi"
  1718  		params.CreateVm.BootOptions.EfiSecureBootEnabled = addrOf(true)
  1719  		params.CreateVm.BootOptions.BootRetryEnabled = addrOf(true)
  1720  		params.CreateVm.BootOptions.BootRetryDelay = addrOf(1)
  1721  	}
  1722  
  1723  	vappList := vdc.GetVappList()
  1724  	vappNum := len(vappList)
  1725  	vm, err := vdc.CreateStandaloneVm(params)
  1726  	check.Assert(err, IsNil)
  1727  	check.Assert(vm, NotNil)
  1728  	err = vm.Refresh()
  1729  	check.Assert(err, IsNil)
  1730  	AddToCleanupList(vm.VM.ID, "standaloneVm", "", check.TestName())
  1731  
  1732  	check.Assert(vm.VM.Description, Equals, description)
  1733  	check.Assert(vm.VM.BootOptions.BootDelay, DeepEquals, addrOf(0))
  1734  	if supportsExtendedBootOptions {
  1735  		check.Assert(vm.VM.BootOptions.EfiSecureBootEnabled, DeepEquals, addrOf(true))
  1736  		check.Assert(vm.VM.BootOptions.BootRetryEnabled, DeepEquals, addrOf(true))
  1737  		check.Assert(vm.VM.BootOptions.BootRetryDelay, DeepEquals, addrOf(1))
  1738  	}
  1739  
  1740  	_ = vdc.Refresh()
  1741  	vappList = vdc.GetVappList()
  1742  	check.Assert(len(vappList), Equals, vappNum+1)
  1743  	for _, vapp := range vappList {
  1744  		printVerbose("vapp: %s\n", vapp.Name)
  1745  	}
  1746  	err = vm.Delete()
  1747  	check.Assert(err, IsNil)
  1748  	_ = vdc.Refresh()
  1749  	vappList = vdc.GetVappList()
  1750  	check.Assert(len(vappList), Equals, vappNum)
  1751  }
  1752  
  1753  func (vcd *TestVCD) Test_CreateStandaloneVMFromTemplate(check *C) {
  1754  
  1755  	if vcd.config.VCD.Catalog.Name == "" {
  1756  		check.Skip("no catalog was defined")
  1757  	}
  1758  	if vcd.config.VCD.Catalog.CatalogItem == "" {
  1759  		check.Skip("no catalog item was defined")
  1760  	}
  1761  	adminOrg, err := vcd.client.GetAdminOrgByName(vcd.org.Org.Name)
  1762  	check.Assert(err, IsNil)
  1763  	check.Assert(adminOrg, NotNil)
  1764  
  1765  	vdc, err := adminOrg.GetVDCByName(vcd.vdc.Vdc.Name, false)
  1766  	check.Assert(err, IsNil)
  1767  	check.Assert(vdc, NotNil)
  1768  
  1769  	catalog, err := adminOrg.GetCatalogByName(vcd.config.VCD.Catalog.Name, false)
  1770  	check.Assert(err, IsNil)
  1771  	check.Assert(catalog, NotNil)
  1772  
  1773  	catalogItem, err := catalog.GetCatalogItemByName(vcd.config.VCD.Catalog.CatalogItem, false)
  1774  	check.Assert(err, IsNil)
  1775  	check.Assert(catalogItem, NotNil)
  1776  
  1777  	vappTemplate, err := catalog.GetVappTemplateByHref(catalogItem.CatalogItem.Entity.HREF)
  1778  	check.Assert(err, IsNil)
  1779  	check.Assert(vappTemplate, NotNil)
  1780  	check.Assert(vappTemplate.VAppTemplate.Children, NotNil)
  1781  	check.Assert(len(vappTemplate.VAppTemplate.Children.VM), Not(Equals), 0)
  1782  
  1783  	vmTemplate := vappTemplate.VAppTemplate.Children.VM[0]
  1784  	check.Assert(vmTemplate.HREF, Not(Equals), "")
  1785  	check.Assert(vmTemplate.ID, Not(Equals), "")
  1786  	check.Assert(vmTemplate.Type, Not(Equals), "")
  1787  	check.Assert(vmTemplate.Name, Not(Equals), "")
  1788  
  1789  	vmName := "testStandaloneTemplate"
  1790  	vmDescription := "Standalone VM"
  1791  	params := types.InstantiateVmTemplateParams{
  1792  		Xmlns:            types.XMLNamespaceVCloud,
  1793  		Name:             vmName,
  1794  		PowerOn:          true,
  1795  		AllEULAsAccepted: true,
  1796  		SourcedVmTemplateItem: &types.SourcedVmTemplateParams{
  1797  			LocalityParams: nil,
  1798  			Source: &types.Reference{
  1799  				HREF: vmTemplate.HREF,
  1800  				ID:   vmTemplate.ID,
  1801  				Type: vmTemplate.Type,
  1802  				Name: vmTemplate.Name,
  1803  			},
  1804  			StorageProfile: nil,
  1805  			VmCapabilities: nil,
  1806  			VmGeneralParams: &types.VMGeneralParams{
  1807  				Name:               vmName,
  1808  				Description:        vmDescription,
  1809  				NeedsCustomization: false,
  1810  				RegenerateBiosUuid: false,
  1811  			},
  1812  			VmTemplateInstantiationParams: nil,
  1813  		},
  1814  	}
  1815  	vappList := vdc.GetVappList()
  1816  	vappNum := len(vappList)
  1817  	util.Logger.Printf("%# v", pretty.Formatter(params))
  1818  	vm, err := vdc.CreateStandaloneVMFromTemplate(&params)
  1819  	check.Assert(err, IsNil)
  1820  	check.Assert(vm, NotNil)
  1821  	AddToCleanupList(vm.VM.ID, "standaloneVm", "", check.TestName())
  1822  	check.Assert(vm.VM.Name, Equals, vmName)
  1823  	check.Assert(vm.VM.Description, Equals, vmDescription)
  1824  
  1825  	_ = vdc.Refresh()
  1826  	vappList = vdc.GetVappList()
  1827  	check.Assert(len(vappList), Equals, vappNum+1)
  1828  	for _, vapp := range vappList {
  1829  		printVerbose("vapp: %s\n", vapp.Name)
  1830  	}
  1831  
  1832  	err = vm.Delete()
  1833  	check.Assert(err, IsNil)
  1834  	_ = vdc.Refresh()
  1835  	vappList = vdc.GetVappList()
  1836  	check.Assert(len(vappList), Equals, vappNum)
  1837  }
  1838  
  1839  func (vcd *TestVCD) Test_VMChangeCPU(check *C) {
  1840  	if vcd.skipVappTests {
  1841  		check.Skip("Skipping test because vapp was not successfully created at setup")
  1842  	}
  1843  
  1844  	vapp := vcd.findFirstVapp()
  1845  	existingVm, vmName := vcd.findFirstVm(vapp)
  1846  	if vmName == "" {
  1847  		check.Skip("skipping test because no VM is found")
  1848  	}
  1849  
  1850  	currentCpus := existingVm.VmSpecSection.NumCpus
  1851  	currentCores := existingVm.VmSpecSection.NumCoresPerSocket
  1852  
  1853  	check.Assert(0, Not(Equals), currentCpus)
  1854  	check.Assert(0, Not(Equals), currentCores)
  1855  
  1856  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
  1857  	check.Assert(err, IsNil)
  1858  
  1859  	cores := 2
  1860  	cpuCount := 4
  1861  
  1862  	err = vm.ChangeCPU(cpuCount, cores)
  1863  	check.Assert(err, IsNil)
  1864  
  1865  	check.Assert(*vm.VM.VmSpecSection.NumCpus, Equals, cpuCount)
  1866  	check.Assert(*vm.VM.VmSpecSection.NumCoresPerSocket, Equals, cores)
  1867  
  1868  	// return to previous value
  1869  	err = vm.ChangeCPU(*currentCpus, *currentCores)
  1870  	check.Assert(err, IsNil)
  1871  }
  1872  
  1873  func (vcd *TestVCD) Test_VMChangeCPUAndCoreCount(check *C) {
  1874  	if vcd.skipVappTests {
  1875  		check.Skip("Skipping test because vApp was not successfully created at setup")
  1876  	}
  1877  
  1878  	vapp := vcd.findFirstVapp()
  1879  	existingVm, vmName := vcd.findFirstVm(vapp)
  1880  	if vmName == "" {
  1881  		check.Skip("skipping test because no VM is found")
  1882  	}
  1883  
  1884  	currentCpus := existingVm.VmSpecSection.NumCpus
  1885  	currentCores := existingVm.VmSpecSection.NumCoresPerSocket
  1886  
  1887  	check.Assert(0, Not(Equals), currentCpus)
  1888  	check.Assert(0, Not(Equals), currentCores)
  1889  
  1890  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
  1891  	check.Assert(err, IsNil)
  1892  
  1893  	cores := 2
  1894  	cpuCount := 4
  1895  
  1896  	err = vm.ChangeCPUAndCoreCount(&cpuCount, &cores)
  1897  	check.Assert(err, IsNil)
  1898  
  1899  	check.Assert(*vm.VM.VmSpecSection.NumCpus, Equals, cpuCount)
  1900  	check.Assert(*vm.VM.VmSpecSection.NumCoresPerSocket, Equals, cores)
  1901  
  1902  	// Try changing only CPU count and seeing if coreCount remains the same
  1903  	newCpuCount := 2
  1904  	err = vm.ChangeCPUAndCoreCount(&newCpuCount, nil)
  1905  	check.Assert(err, IsNil)
  1906  
  1907  	check.Assert(*vm.VM.VmSpecSection.NumCpus, Equals, newCpuCount)
  1908  	check.Assert(*vm.VM.VmSpecSection.NumCoresPerSocket, Equals, cores)
  1909  
  1910  	// Change only core count and check that CPU count remains as it was
  1911  	newCoreCount := 1
  1912  	err = vm.ChangeCPUAndCoreCount(nil, &newCoreCount)
  1913  	check.Assert(err, IsNil)
  1914  
  1915  	check.Assert(*vm.VM.VmSpecSection.NumCpus, Equals, newCpuCount)
  1916  	check.Assert(*vm.VM.VmSpecSection.NumCoresPerSocket, Equals, newCoreCount)
  1917  
  1918  	// return to previous value
  1919  	err = vm.ChangeCPUAndCoreCount(currentCpus, currentCores)
  1920  	check.Assert(err, IsNil)
  1921  }
  1922  
  1923  func (vcd *TestVCD) Test_VMChangeMemory(check *C) {
  1924  	if vcd.skipVappTests {
  1925  		check.Skip("Skipping test because vapp was not successfully created at setup")
  1926  	}
  1927  
  1928  	vapp := vcd.findFirstVapp()
  1929  	existingVm, vmName := vcd.findFirstVm(vapp)
  1930  	if vmName == "" {
  1931  		check.Skip("skipping test because no VM is found")
  1932  	}
  1933  	check.Assert(existingVm.VmSpecSection.MemoryResourceMb, Not(IsNil))
  1934  
  1935  	currentMemory := existingVm.VmSpecSection.MemoryResourceMb.Configured
  1936  	check.Assert(0, Not(Equals), currentMemory)
  1937  
  1938  	vm, err := vcd.client.Client.GetVMByHref(existingVm.HREF)
  1939  	check.Assert(err, IsNil)
  1940  
  1941  	err = vm.ChangeMemory(2304)
  1942  	check.Assert(err, IsNil)
  1943  
  1944  	check.Assert(existingVm.VmSpecSection.MemoryResourceMb, Not(IsNil))
  1945  	check.Assert(vm.VM.VmSpecSection.MemoryResourceMb.Configured, Equals, int64(2304))
  1946  
  1947  	// return to previous value
  1948  	err = vm.ChangeMemory(currentMemory)
  1949  	check.Assert(err, IsNil)
  1950  }
  1951  
  1952  func (vcd *TestVCD) Test_AddRawVm(check *C) {
  1953  	vapp, vm := createNsxtVAppAndVm(vcd, check)
  1954  	check.Assert(vapp, NotNil)
  1955  	check.Assert(vm, NotNil)
  1956  
  1957  	// Check that vApp did not lose its state
  1958  	vappStatus, err := vapp.GetStatus()
  1959  	check.Assert(err, IsNil)
  1960  	check.Assert(vappStatus, Equals, "MIXED") //vApp is powered on, but the VM within is powered off
  1961  	check.Assert(vapp.VApp.Name, Equals, check.TestName())
  1962  	check.Assert(vapp.VApp.Description, Equals, check.TestName())
  1963  
  1964  	// Check that VM is not powered on
  1965  	vmStatus, err := vm.GetStatus()
  1966  	check.Assert(err, IsNil)
  1967  	check.Assert(vmStatus, Equals, "POWERED_OFF")
  1968  
  1969  	// Cleanup
  1970  	task, err := vapp.Undeploy()
  1971  	check.Assert(err, IsNil)
  1972  	check.Assert(task, Not(Equals), Task{})
  1973  
  1974  	err = task.WaitTaskCompletion()
  1975  	check.Assert(err, IsNil)
  1976  
  1977  	task, err = vapp.Delete()
  1978  	check.Assert(err, IsNil)
  1979  	check.Assert(task, Not(Equals), Task{})
  1980  
  1981  	err = task.WaitTaskCompletion()
  1982  	check.Assert(err, IsNil)
  1983  }
  1984  
  1985  func createNsxtVAppAndVmWithEfiSupport(vcd *TestVCD, check *C) (*VApp, *VM) {
  1986  	if vcd.config.VCD.Catalog.CatalogItemWithEfiSupport == "" {
  1987  		check.Skip("EFI supporting OVA not provided in the config")
  1988  	}
  1989  
  1990  	cat, err := vcd.org.GetCatalogByName(vcd.config.VCD.Catalog.NsxtBackedCatalogName, false)
  1991  	check.Assert(err, IsNil)
  1992  	check.Assert(cat, NotNil)
  1993  	// Populate Catalog Item
  1994  	catitem, err := cat.GetCatalogItemByName(vcd.config.VCD.Catalog.CatalogItemWithEfiSupport, false)
  1995  	check.Assert(err, IsNil)
  1996  	check.Assert(catitem, NotNil)
  1997  	// Get VAppTemplate
  1998  	vapptemplate, err := catitem.GetVAppTemplate()
  1999  	check.Assert(err, IsNil)
  2000  	check.Assert(vapptemplate.VAppTemplate.Children.VM[0].HREF, NotNil)
  2001  
  2002  	vapp, err := vcd.nsxtVdc.CreateRawVApp(check.TestName(), check.TestName())
  2003  	check.Assert(err, IsNil)
  2004  	check.Assert(vapp, NotNil)
  2005  	// After a successful creation, the entity is added to the cleanup list.
  2006  	AddToCleanupList(vapp.VApp.Name, "vapp", vcd.nsxtVdc.Vdc.Name, check.TestName())
  2007  
  2008  	// Once the operation is successful, we won't trigger a failure
  2009  	// until after the vApp deletion
  2010  	check.Check(vapp.VApp.Name, Equals, check.TestName())
  2011  	check.Check(vapp.VApp.Description, Equals, check.TestName())
  2012  
  2013  	// Construct VM
  2014  	vmDef := &types.ReComposeVAppParams{
  2015  		Ovf:              types.XMLNamespaceOVF,
  2016  		Xsi:              types.XMLNamespaceXSI,
  2017  		Xmlns:            types.XMLNamespaceVCloud,
  2018  		AllEULAsAccepted: true,
  2019  		// Deploy:           false,
  2020  		Name: vapp.VApp.Name,
  2021  		// PowerOn: false, // Not touching power state at this phase
  2022  		SourcedItem: &types.SourcedCompositionItemParam{
  2023  			Source: &types.Reference{
  2024  				HREF: vapptemplate.VAppTemplate.Children.VM[0].HREF,
  2025  				Name: check.TestName() + "-vm-tmpl",
  2026  			},
  2027  			VMGeneralParams: &types.VMGeneralParams{
  2028  				Description: "test-vm-description",
  2029  			},
  2030  			InstantiationParams: &types.InstantiationParams{
  2031  				NetworkConnectionSection: &types.NetworkConnectionSection{},
  2032  			},
  2033  		},
  2034  	}
  2035  	vm, err := vapp.AddRawVM(vmDef)
  2036  	check.Assert(err, IsNil)
  2037  	check.Assert(vm, NotNil)
  2038  	check.Assert(vm.VM.Name, Equals, vmDef.SourcedItem.Source.Name)
  2039  
  2040  	// Refresh vApp to have latest state
  2041  	err = vapp.Refresh()
  2042  	check.Assert(err, IsNil)
  2043  
  2044  	return vapp, vm
  2045  }
  2046  
  2047  func (vcd *TestVCD) Test_GetOvfEnvironment(check *C) {
  2048  	version, err := vcd.client.Client.GetVcdShortVersion()
  2049  	check.Assert(err, IsNil)
  2050  	if version == "10.5.0" {
  2051  		check.Skip("There is a known bug with the OVF environment on 10.5.0")
  2052  	}
  2053  
  2054  	_, vm := createNsxtVAppAndVm(vcd, check)
  2055  	check.Assert(vm, NotNil)
  2056  
  2057  	task, err := vm.PowerOn()
  2058  	check.Assert(err, IsNil)
  2059  	err = task.WaitTaskCompletion()
  2060  	check.Assert(err, IsNil)
  2061  
  2062  	// Read ovfenv when VM is started
  2063  	ovfenv, err := vm.GetEnvironment()
  2064  	check.Assert(err, IsNil)
  2065  	check.Assert(ovfenv, NotNil)
  2066  
  2067  	// Provides information from the virtualization platform like VM moref
  2068  	check.Assert(strings.Contains(ovfenv.VCenterId, "vm-"), Equals, true)
  2069  
  2070  	// Check virtualization platform Vendor
  2071  	check.Assert(ovfenv.PlatformSection, NotNil)
  2072  	check.Assert(ovfenv.PlatformSection.Vendor, Equals, "VMware, Inc.")
  2073  
  2074  	// Check guest operating system level configuration for hostname
  2075  	check.Assert(ovfenv.PropertySection, NotNil)
  2076  	for _, p := range ovfenv.PropertySection.Properties {
  2077  		if p.Key == "vCloud_computerName" {
  2078  			check.Assert(p.Value, Not(Equals), "")
  2079  		}
  2080  	}
  2081  	check.Assert(ovfenv.EthernetAdapterSection, NotNil)
  2082  	for _, p := range ovfenv.EthernetAdapterSection.Adapters {
  2083  		check.Assert(p.Mac, Not(Equals), "")
  2084  	}
  2085  
  2086  	err = deleteNsxtVapp(vcd, check.TestName())
  2087  	check.Assert(err, IsNil)
  2088  }
  2089  
  2090  func (vcd *TestVCD) Test_QueryVMList(check *C) {
  2091  
  2092  	uniqueId := "2024-01-27"
  2093  	vappDefinition := map[string][]string{
  2094  		"Test_Vapp1_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
  2095  		"Test_Vapp2_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
  2096  		"Test_Vapp3_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
  2097  	}
  2098  	listVms := func(vms []*types.QueryResultVMRecordType) {
  2099  		if !testVerbose {
  2100  			return
  2101  		}
  2102  		for i, vm := range vms {
  2103  			standalone := ""
  2104  			if vm.AutoNature {
  2105  				standalone = " (standalone)"
  2106  			}
  2107  			fmt.Printf("%d (%s) %s %s\n", i, vm.VdcName, vm.Name, standalone)
  2108  		}
  2109  		fmt.Println()
  2110  	}
  2111  	_, err := makeVappGroup(check.TestName(), vcd.nsxtVdc, vappDefinition)
  2112  	check.Assert(err, IsNil)
  2113  
  2114  	// Retrieves all VMs with name 'Test_VmA_'+uniqueId
  2115  	vmList1, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, map[string]string{"name": "Test_VmA_" + uniqueId})
  2116  	check.Assert(err, IsNil)
  2117  	listVms(vmList1)
  2118  
  2119  	// Retrieves all VMs with name 'Test_VmB_'+uniqueId
  2120  	check.Assert(len(vmList1) == 3, Equals, true)
  2121  	vmList2, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, map[string]string{"name": "Test_VmB_" + uniqueId})
  2122  	check.Assert(err, IsNil)
  2123  	listVms(vmList2)
  2124  
  2125  	// Retrieves all VMs
  2126  	check.Assert(len(vmList2) == 3, Equals, true)
  2127  	vmList3, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, nil)
  2128  	check.Assert(err, IsNil)
  2129  	check.Assert(len(vmList3) >= 6, Equals, true)
  2130  	listVms(vmList3)
  2131  }
  2132  
  2133  // Test_VmConsolidateDisks attempts to validate vm.ConsolidateDisks by performing the following
  2134  // operations:
  2135  // * setting up a vApp and a VM
  2136  // * trying to resize VM disk and expecting to get an error (cannot be modified while the virtual machine has snapshots)
  2137  // * consolidating disks
  2138  // * resizing VM disk (growing by 1024MB)
  2139  // * verifying that new size is correct
  2140  // * attempting to consolidate once more (it is already consolidated so expecting a quick return)
  2141  // * cleanup
  2142  func (vcd *TestVCD) Test_VmConsolidateDisks(check *C) {
  2143  	org := vcd.org
  2144  	catalog, err := org.GetCatalogByName(vcd.config.VCD.Catalog.NsxtBackedCatalogName, false)
  2145  	check.Assert(err, IsNil)
  2146  	vappTemplateName := vcd.config.VCD.Catalog.CatalogItemWithMultiVms
  2147  	if vappTemplateName == "" {
  2148  		check.Skip(fmt.Sprintf("vApp template missing in configuration - Make sure there is such template in catalog %s -"+
  2149  			" Using test_resources/vapp_with_3_vms.ova",
  2150  			vcd.config.VCD.Catalog.NsxtBackedCatalogName))
  2151  	}
  2152  	vappTemplate, err := catalog.GetVAppTemplateByName(vappTemplateName)
  2153  	if err != nil {
  2154  		if ContainsNotFound(err) {
  2155  			check.Skip(fmt.Sprintf("vApp template %s not found - Make sure there is such template in catalog %s -"+
  2156  				" Using test_resources/vapp_with_3_vms.ova",
  2157  				vappTemplateName, vcd.config.VCD.Catalog.NsxtBackedCatalogName))
  2158  		}
  2159  	}
  2160  	check.Assert(err, IsNil)
  2161  	check.Assert(vappTemplate.VAppTemplate.Children, NotNil)
  2162  	check.Assert(vappTemplate.VAppTemplate.Children.VM, NotNil)
  2163  
  2164  	vapp, vm := createNsxtVAppAndVmFromCustomTemplate(vcd, check, vappTemplate)
  2165  	check.Assert(vapp, NotNil)
  2166  	check.Assert(vm, NotNil)
  2167  
  2168  	// Check that vApp did not lose its state
  2169  	vappStatus, err := vapp.GetStatus()
  2170  	check.Assert(err, IsNil)
  2171  	check.Assert(vappStatus, Equals, "MIXED") //vApp is powered on, but the VM within is powered off
  2172  	check.Assert(vapp.VApp.Name, Equals, check.TestName())
  2173  	check.Assert(vapp.VApp.Description, Equals, check.TestName())
  2174  
  2175  	// Check that VM is not powered on
  2176  	vmStatus, err := vm.GetStatus()
  2177  	check.Assert(err, IsNil)
  2178  	check.Assert(vmStatus, Equals, "POWERED_OFF")
  2179  
  2180  	// Attempt to resize before consolidating disks - it should fail
  2181  	vmSpecSection := vm.VM.VmSpecSection
  2182  	vmSizeBeforeGrowing := vmSpecSection.DiskSection.DiskSettings[0].SizeMb
  2183  	vmSpecSection.DiskSection.DiskSettings[0].SizeMb = vmSizeBeforeGrowing + 1024
  2184  	_, err = vm.UpdateInternalDisks(vmSpecSection)
  2185  	check.Assert(strings.Contains(err.Error(), "cannot be modified while the virtual machine has snapshots"), Equals, true)
  2186  
  2187  	// Trigger disk consolidation
  2188  	err = vm.ConsolidateDisks()
  2189  	check.Assert(err, IsNil)
  2190  
  2191  	// Resize disk after consolidation - it should work now
  2192  	err = vm.Refresh() // reloading VM structure to avoid
  2193  	check.Assert(err, IsNil)
  2194  	vmSpecSection = vm.VM.VmSpecSection
  2195  	vmSizeBeforeGrowing = vmSpecSection.DiskSection.DiskSettings[0].SizeMb
  2196  	vmSpecSection.DiskSection.DiskSettings[0].SizeMb = vmSizeBeforeGrowing + 1024
  2197  
  2198  	_, err = vm.UpdateInternalDisks(vmSpecSection)
  2199  	check.Assert(err, IsNil)
  2200  
  2201  	// Refresh VM and verify size
  2202  	err = vm.Refresh()
  2203  	check.Assert(err, IsNil)
  2204  	check.Assert(vm.VM.VmSpecSection.DiskSection.DiskSettings[0].SizeMb, Equals, vmSizeBeforeGrowing+1024)
  2205  
  2206  	// Trigger async disk consolidation - it will return instantly because the disk is already
  2207  	// consolidated and there is nothing to do
  2208  	task, err := vm.ConsolidateDisksAsync()
  2209  	check.Assert(err, IsNil)
  2210  	err = task.WaitTaskCompletion()
  2211  	check.Assert(err, IsNil)
  2212  
  2213  	// Cleanup
  2214  	task, err = vapp.Undeploy()
  2215  	check.Assert(err, IsNil)
  2216  	check.Assert(task, Not(Equals), Task{})
  2217  
  2218  	err = task.WaitTaskCompletion()
  2219  	check.Assert(err, IsNil)
  2220  
  2221  	task, err = vapp.Delete()
  2222  	check.Assert(err, IsNil)
  2223  	check.Assert(task, Not(Equals), Task{})
  2224  
  2225  	err = task.WaitTaskCompletion()
  2226  	check.Assert(err, IsNil)
  2227  }