示例#1
0
文件: vmomi.go 项目: zhaog918/govmax
func (vmh *VMHost) FindHosts(targetVM *object.VirtualMachine) (hosts []*object.HostSystem, err error) {
	targetResourcePool, err := targetVM.ResourcePool(vmh.Ctx)
	if err != nil {
		return nil, errors.New("Error with finding Resource Pool of VM")
	}
	var resourcePoolProp mo.ResourcePool
	err = targetResourcePool.Properties(vmh.Ctx, targetResourcePool.Reference(), []string{"owner"}, &resourcePoolProp)

	if err != nil {
		return nil, errors.New("Error with finding Owner of Resource Pool")
	}

	typeOfOwningResource := resourcePoolProp.Owner.Type
	//Scenario in which VM is apart of a Cluster (Not tied to 1 ESXi host) - VMware DRS
	if typeOfOwningResource == "ClusterComputeResource" {
		cluster := object.NewClusterComputeResource(vmh.client.Client, resourcePoolProp.Owner)
		var clusterProp mo.ClusterComputeResource
		err = cluster.Properties(vmh.Ctx, cluster.Reference(), []string{"host"}, &clusterProp)
		if err != nil {
			return nil, errors.New("Error with finding Hosts of Cluster")
		}

		//convert Managed Object References into actual host_sytem objects to return
		var hosts []*object.HostSystem
		for _, host := range clusterProp.Host {
			newHost := object.NewHostSystem(vmh.client.Client, host)
			hosts = append(hosts, newHost)
		}
		return hosts, nil
	} else {
		return nil, errors.New("Looks like you are on a single/Non-Clustered host and we havent gotten to this yet!!")
	}

}