Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function QueryVmList #646

Merged
merged 5 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/v2.23.0/646-features.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Added method `client.QueryVmList` to search VMs across VDCs [GH-646]
1 change: 1 addition & 0 deletions .changes/v2.23.0/646-improvements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Added missing field `vdcName` to `types.QueryResultVMRecordType` [GH-646]
56 changes: 56 additions & 0 deletions govcd/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
Expand Down Expand Up @@ -856,3 +857,58 @@ func (vcd *TestVCD) checkSkipWhenApiToken(check *C) {
check.Skip("This test can't run on API token")
}
}

// makeVappGroup creates multiple vApps, each with several VMs,
// as defined in `groupDefinition`.
// Returns a list of vApps
func makeVappGroup(label string, vdc *Vdc, groupDefinition map[string][]string) ([]*VApp, error) {
var vappList []*VApp
for vappName, vmNames := range groupDefinition {
existingVapp, err := vdc.GetVAppByName(vappName, false)
if err == nil {

if existingVapp.VApp.Children == nil || len(existingVapp.VApp.Children.VM) == 0 {
return nil, fmt.Errorf("found vApp %s but without VMs", vappName)
}
foundVms := 0
for _, vmName := range vmNames {
for _, existingVM := range existingVapp.VApp.Children.VM {
if existingVM.Name == vmName {
foundVms++
}
}
}
if foundVms < 2 {
return nil, fmt.Errorf("found vApp %s but with %d VMs instead of 2 ", vappName, foundVms)
}

vappList = append(vappList, existingVapp)
if testVerbose {
fmt.Printf("Using existing vApp %s\n", vappName)
}
continue
}

if testVerbose {
fmt.Printf("Creating vApp %s\n", vappName)
}
vapp, err := makeEmptyVapp(vdc, vappName, "")
if err != nil {
return nil, err
}
if os.Getenv("GOVCD_KEEP_TEST_OBJECTS") == "" {
AddToCleanupList(vappName, "vapp", vdc.Vdc.Name, label)
}
for _, vmName := range vmNames {
if testVerbose {
fmt.Printf("\tCreating VM %s/%s\n", vappName, vmName)
}
_, err := makeEmptyVm(vapp, vmName)
if err != nil {
return nil, err
}
}
vappList = append(vappList, vapp)
}
return vappList, nil
}
2 changes: 1 addition & 1 deletion govcd/query_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func queryFieldsOnDemand(queryType string) ([]string, error) {
vmFields = []string{"catalogName", "container", "containerName", "datastoreName", "description",
"gcStatus", "guestOs", "hardwareVersion", "hostName", "isAutoNature", "isDeleted", "isDeployed", "isPublished",
"isVAppTemplate", "isVdcEnabled", "memoryMB", "moref", "name", "numberOfCpus", "org", "status",
"storageProfileName", "vc", "vdc", "vmToolsVersion", "containerStatus", "pvdcHighestSupportedHardwareVersion",
"storageProfileName", "vc", "vdc", "vdcName", "vmToolsVersion", "containerStatus", "pvdcHighestSupportedHardwareVersion",
"isComputePolicyCompliant", "vmSizingPolicyId", "vmPlacementPolicyId", "encrypted", "dateCreated",
"totalStorageAllocatedMb", "isExpired"}
vappFields = []string{"creationDate", "isBusy", "isDeployed", "isEnabled", "isExpired", "isInMaintenanceMode", "isPublic",
Expand Down
29 changes: 29 additions & 0 deletions govcd/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -1704,6 +1704,35 @@ func queryVmList(filter types.VmQueryFilter, client *Client, filterParent, filte
return vmList, nil
}

// QueryVmList retrieves a list of VMs across all VDC, using parameters defined in searchParams
func QueryVmList(vmType types.VmQueryFilter, client *Client, searchParams map[string]string) ([]*types.QueryResultVMRecordType, error) {
var vmList []*types.QueryResultVMRecordType
queryType := client.GetQueryType(types.QtVm)
params := map[string]string{
"type": queryType,
"filterEncoded": "true",
}
filterText := ""
if vmType.String() != "" {
// The first filter will be the type of VM, i.e. deployed (inside a vApp) or not (inside a vApp template)
filterText = vmType.String()
}
for k, v := range searchParams {
filterText = fmt.Sprintf("%s;%s==%s", filterText, k, v)
}

params["filter"] = filterText
vmResult, err := client.cumulativeQuery(queryType, nil, params)
if err != nil {
return nil, fmt.Errorf("error getting VM list : %s", err)
}
vmList = vmResult.Results.VMRecord
if client.IsSysAdmin {
vmList = vmResult.Results.AdminVMRecord
}
return vmList, nil
}

// UpdateVmCpuAndMemoryHotAdd updates VM Capabilities and returns refreshed VM or error.
func (vm *VM) UpdateVmCpuAndMemoryHotAdd(cpuAdd, memoryAdd bool) (*VM, error) {
task, err := vm.UpdateVmCpuAndMemoryHotAddAsync(cpuAdd, memoryAdd)
Expand Down
55 changes: 0 additions & 55 deletions govcd/vm_affinity_rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,58 +271,3 @@ func (vcd *TestVCD) Test_VmAffinityRule(check *C) {
}, check)

}

// makeVappGroup creates multiple vApps, each with several VMs,
// as defined in `groupDefinition`.
// Returns a list of vApps
func makeVappGroup(label string, vdc *Vdc, groupDefinition map[string][]string) ([]*VApp, error) {
var vappList []*VApp
for vappName, vmNames := range groupDefinition {
existingVapp, err := vdc.GetVAppByName(vappName, false)
if err == nil {

if existingVapp.VApp.Children == nil || len(existingVapp.VApp.Children.VM) == 0 {
return nil, fmt.Errorf("found vApp %s but without VMs", vappName)
}
foundVms := 0
for _, vmName := range vmNames {
for _, existingVM := range existingVapp.VApp.Children.VM {
if existingVM.Name == vmName {
foundVms++
}
}
}
if foundVms < 2 {
return nil, fmt.Errorf("found vApp %s but with %d VMs instead of 2 ", vappName, foundVms)
}

vappList = append(vappList, existingVapp)
if testVerbose {
fmt.Printf("Using existing vApp %s\n", vappName)
}
continue
}

if testVerbose {
fmt.Printf("Creating vApp %s\n", vappName)
}
vapp, err := makeEmptyVapp(vdc, vappName, "")
if err != nil {
return nil, err
}
if os.Getenv("GOVCD_KEEP_TEST_OBJECTS") == "" {
AddToCleanupList(vappName, "vapp", vdc.Vdc.Name, label)
}
for _, vmName := range vmNames {
if testVerbose {
fmt.Printf("\tCreating VM %s/%s\n", vappName, vmName)
}
_, err := makeEmptyVm(vapp, vmName)
if err != nil {
return nil, err
}
}
vappList = append(vappList, vapp)
}
return vappList, nil
}
43 changes: 43 additions & 0 deletions govcd/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2164,6 +2164,49 @@ func (vcd *TestVCD) Test_GetOvfEnvironment(check *C) {
check.Assert(err, IsNil)
}

func (vcd *TestVCD) Test_QueryVMList(check *C) {

uniqueId := "2024-01-27"
vappDefinition := map[string][]string{
"Test_Vapp1_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
"Test_Vapp2_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
"Test_Vapp3_" + uniqueId: []string{"Test_VmA_" + uniqueId, "Test_VmB_" + uniqueId},
}
listVms := func(vms []*types.QueryResultVMRecordType) {
if !testVerbose {
return
}
for i, vm := range vms {
standalone := ""
if vm.AutoNature {
standalone = " (standalone)"
}
fmt.Printf("%d (%s) %s %s\n", i, vm.VdcName, vm.Name, standalone)
}
fmt.Println()
}
_, err := makeVappGroup(check.TestName(), vcd.nsxtVdc, vappDefinition)
check.Assert(err, IsNil)

// Retrieves all VMs with name 'Test_VmA_'+uniqueId
vmList1, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, map[string]string{"name": "Test_VmA_" + uniqueId})
check.Assert(err, IsNil)
listVms(vmList1)

// Retrieves all VMs with name 'Test_VmB_'+uniqueId
check.Assert(len(vmList1) == 3, Equals, true)
vmList2, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, map[string]string{"name": "Test_VmB_" + uniqueId})
check.Assert(err, IsNil)
listVms(vmList2)

// Retrieves all VMs
check.Assert(len(vmList2) == 3, Equals, true)
vmList3, err := QueryVmList(types.VmQueryFilterOnlyDeployed, &vcd.client.Client, nil)
check.Assert(err, IsNil)
check.Assert(len(vmList3) >= 6, Equals, true)
listVms(vmList3)
}

// Test_VmConsolidateDisks attempts to validate vm.ConsolidateDisks by performing the following
// operations:
// * setting up a vApp and a VM
Expand Down
1 change: 1 addition & 0 deletions types/v56/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2564,6 +2564,7 @@ type QueryResultVMRecordType struct {
OwnerName string `xml:"ownerName,attr,omitempty"`
Owner string `xml:"owner,attr,omitempty"`
VdcHREF string `xml:"vdc,attr,omitempty"`
VdcName string `xml:"vdcName,attr,omitempty"`
VAppTemplate bool `xml:"isVAppTemplate,attr,omitempty"`
Deleted bool `xml:"isDeleted,attr,omitempty"`
GuestOS string `xml:"guestOs,attr,omitempty"`
Expand Down
Loading