Python pyVmomi.vim.ComputeResource() Examples

The following are 10 code examples of pyVmomi.vim.ComputeResource(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVmomi.vim , or try the search function .
Example #1
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def report(self):
        si = self.si
        about = si.content.about
        print("Host: %s" % self.vcip)
        print("Datacenter: %s" % self.dc.name)
        print("Version: %s" % about.version)
        print("Api Version: %s" % about.apiVersion)
        print("Datacenter: %s" % self.dc.name)
        rootFolder = self.rootFolder
        o = si.content.viewManager.CreateContainerView(rootFolder, [vim.HostSystem], True)
        view = o.view
        o.Destroy()
        for h in view:
            print("Host: %s" % h.name)
        o = si.content.viewManager.CreateContainerView(rootFolder, [vim.ComputeResource], True)
        view = o.view
        o.Destroy()
        for clu in view:
            print("Cluster: %s" % clu.name)
            for dts in clu.datastore:
                print("Pool: %s" % dts.name) 
Example #2
Source File: nsxt_vcenter_moids.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def find_object_by_name(module,content, object_name):
    try:
    	if(object_name == module.params['datacenter']):
    	    vmware_objects = get_all_objs(module,content,[vim.Datacenter])
    	elif (object_name == module.params['cluster']):
    	    vmware_objects = get_all_objs(module,content,[vim.ComputeResource])
    	elif (object_name == module.params['datastore']):
            vmware_objects = get_all_objs(module,content,[vim.Datastore])
    	elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ):
            vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network])
 
    	for object in vmware_objects:
            if object.name == object_name:
            	logger.info('object: %s',object.name)
            	return object
    	return None
    except Exception as err:
       module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err))) 
Example #3
Source File: vmware_guest2.py    From skylight with GNU General Public License v3.0 5 votes vote down vote up
def get_resource_pool(self, cluster=None, host=None, resource_pool=None):
        """ Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given """

        cluster_name = cluster or self.params.get('cluster', None)
        host_name = host or self.params.get('esxi_hostname', None)
        resource_pool_name = resource_pool or self.params.get('resource_pool', None)

        # get the datacenter object
        datacenter = find_obj(self.content, [vim.Datacenter], self.params['datacenter'])
        if not datacenter:
            self.module.fail_json(msg='Unable to find datacenter "%s"' % self.params['datacenter'])

        # if cluster is given, get the cluster object
        if cluster_name:
            cluster = find_obj(self.content, [vim.ComputeResource], cluster_name, folder=datacenter)
            if not cluster:
                self.module.fail_json(msg='Unable to find cluster "%s"' % cluster_name)
        # if host is given, get the cluster object using the host
        elif host_name:
            host = find_obj(self.content, [vim.HostSystem], host_name, folder=datacenter)
            if not host:
                self.module.fail_json(msg='Unable to find host "%s"' % host_name)
            cluster = host.parent
        else:
            cluster = None

        # get resource pools limiting search to cluster or datacenter
        resource_pool = find_obj(self.content, [vim.ResourcePool], resource_pool_name, folder=cluster or datacenter)
        if not resource_pool:
            if resource_pool_name:
                self.module.fail_json(msg='Unable to find resource_pool "%s"' % resource_pool_name)
            else:
                self.module.fail_json(msg='Unable to find resource pool, need esxi_hostname, resource_pool, or cluster')
        return resource_pool 
Example #4
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def list_pools(self):
        pools = []
        rootFolder = self.rootFolder
        si = self.si
        # dc = self.dc
        clu = find(si, rootFolder, vim.ComputeResource, self.clu)
        for dts in clu.datastore:
            pools.append(dts.name)
            # datastorename = dts.name
            # total = dssize(dts)[0].replace('GB', '')
            # available = dssize(dts)[1].replace('GB', '')
            # results[datastorename] = [float(total), float(available), dc.name]
        return pools 
Example #5
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def beststorage(self):
        rootFolder = self.rootFolder
        si = self.si
        clu = find(si, rootFolder, vim.ComputeResource, self.clu)
        bestds = ''
        bestsize = 0
        for dts in clu.datastore:
            datastorename = dts.name
            available = float(dssize(dts)[1].replace('GB', ''))
            if available > bestsize:
                bestsize = available
                bestds = datastorename
        return bestds 
Example #6
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def _getisos(self):
        rootFolder = self.rootFolder
        si = self.si
        clu = find(si, rootFolder, vim.ComputeResource, self.clu)
        isos = []
        results = {}
        searchspec = vim.host.DatastoreBrowser.SearchSpec()
        filequery = [vim.host.DatastoreBrowser.IsoImageQuery(), vim.host.DatastoreBrowser.FolderQuery()]
        filequeryflags = vim.host.DatastoreBrowser.FileInfo.Details()
        filequeryflags.fileSize = True
        filequeryflags.modification = False
        filequeryflags.fileOwner = False
        filequeryflags.fileType = False
        searchspec.query = filequery
        searchspec.details = filequeryflags
        searchspec.sortFoldersFirst = True
        searchspec.searchCaseInsensitive = True
        for dts in clu.datastore:
            datastorename = dts.name
            datastorepath = "[" + datastorename + "]"
            browser = dts.browser
            t = browser.SearchDatastore_Task(datastorepath, searchspec)
            waitForMe(t)
            result = t.info.result
            fileinfo = result.file
            for element in fileinfo:
                folderpath = element.path
                if not folderpath.endswith('iso') and 'ISO' in folderpath.upper():
                    t = browser.SearchDatastoreSubFolders_Task("%s%s" % (datastorepath, folderpath), searchspec)
                    waitForMe(t)
                    results = t.info.result
                    for r in results:
                        fileinfo = r.file
                        for isofile in fileinfo:
                            path = isofile.path
                            if path.endswith('.iso'):
                                isos.append("%s/%s/%s" % (datastorepath, folderpath, path))
        return isos 
Example #7
Source File: vmutils.py    From devops with Apache License 2.0 5 votes vote down vote up
def get_cluster(si, name, folder=None):
    """
    Find a cluster by it's name and return it
    """
    return _get_obj(si.RetrieveContent(), [vim.ComputeResource], name,
                    folder) 
Example #8
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def host_labels(self):

        def _collect(node, level=1, dc=None, folder=None):
            inventory = {}
            if isinstance(node, vim.Folder) and not isinstance(node, vim.StoragePod):
                logging.debug("[Folder    ] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                for child in node.childEntity:
                    inventory.update(_collect(child, level + 1, dc))
            elif isinstance(node, vim.Datacenter):
                logging.debug("[Datacenter] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                inventory.update(_collect(node.hostFolder, level + 1, node.name))
            elif isinstance(node, vim.ComputeResource):
                logging.debug("[ComputeRes] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                for host in node.host:
                    inventory.update(_collect(host, level + 1, dc, node))
            elif isinstance(node, vim.HostSystem):
                logging.debug("[HostSystem] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                inventory[node._moId] = [
                    node.summary.config.name.rstrip('.'),
                    dc,
                    folder.name if isinstance(folder, vim.ClusterComputeResource) else ''
                ]
            else:
                logging.debug("[?         ] {level} {node}".format(level=('-' * level).ljust(7), node=node))
            return inventory

        labels = {}
        dcs = yield self.datacenter_inventory
        for dc in dcs:
            result = yield threads.deferToThread(lambda: _collect(dc))
            labels.update(result)
        return labels 
Example #9
Source File: utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_parent_tags_recursively(mor, infrastructure_data):
    # type: (vim.ManagedEntity, InfrastructureData) -> List[str]
    """Go up the resources hierarchy from the given mor. Note that a host running a VM is not considered to be a
    parent of that VM.

    rootFolder(vim.Folder):
      - vm(vim.Folder):
          VM1-1
          VM1-2
      - host(vim.Folder):
          HOST1
          HOST2

    """
    mor_props = infrastructure_data[mor]
    parent = mor_props.get('parent')
    if parent:
        tags = []
        parent_props = infrastructure_data.get(parent, {})
        parent_name = to_string(parent_props.get('name', 'unknown'))
        if isinstance(parent, vim.HostSystem):
            tags.append('vsphere_host:{}'.format(parent_name))
        elif isinstance(parent, vim.Folder):
            tags.append('vsphere_folder:{}'.format(parent_name))
        elif isinstance(parent, vim.ComputeResource):
            if isinstance(parent, vim.ClusterComputeResource):
                tags.append('vsphere_cluster:{}'.format(parent_name))
            tags.append('vsphere_compute:{}'.format(parent_name))
        elif isinstance(parent, vim.Datacenter):
            tags.append('vsphere_datacenter:{}'.format(parent_name))
        elif isinstance(parent, vim.Datastore):
            tags.append('vsphere_datastore:{}'.format(parent_name))

        parent_tags = get_parent_tags_recursively(parent, infrastructure_data)
        parent_tags.extend(tags)
        return parent_tags
    return [] 
Example #10
Source File: 01_get_vmware_vm_info.py    From blueprints with MIT License 4 votes vote down vote up
def parse_service_instance(clustername, service_instance):
    '''
    :param service_instance:
    :return:
    '''

    content = service_instance.RetrieveContent()
    object_view = content.viewManager.CreateContainerView(content.rootFolder, [], True)
    vm_info_list = []
    vm_info_list.append(["virtual_machine_name","virtual_machine_uuid","virtual_machine_ip","num_cpu",
        "num_vcpus","memory_size","guest_family","host_uuid","datastore","power_state"])

    for obj in object_view.view:
        if isinstance(obj, vim.ComputeResource):
            if isinstance(obj, vim.ClusterComputeResource) and obj.name == clustername :
                #instance_name,instance_id,address,num_sockets,num_vcpus_per_socket,memory_size_mib,guestFamily,host_uuid, datastore
                for h in obj.host:
                    nic = h.config.network.vnic[0].spec
                    esxi_config = h.summary.config
                    #host_ip = h.summary.config.name
                    #host_id = str(h).split(":")[1][:-1]
                    host_uuid = h.hardware.systemInfo.uuid

                    for vx in h.vm:
                        if vx.summary.config.template is False:
                            ## Check if guestFullName contains `Windows` to determine the guest os is windows
                            ## otherwise we assumed that it is linux.
                            os = "Windows" if "Windows" in vx.summary.config.guestFullName else "Linux"
                            power_state = "poweron" if vx.runtime.powerState == "poweredOn" else "poweroff"

                            ## We assume here that guest os datastore will always have url start as `ds:///vmfs/volumes`
                            datastore =  [ d.info.url for d in vx.datastore if d.info.url.startswith("ds:///vmfs/volumes")]
                            vm_info  = [vx.name, vx.config.instanceUuid, vx.summary.guest.ipAddress,
                                vx.config.hardware.numCPU, vx.config.hardware.numCoresPerSocket,
                                vx.summary.config.memorySizeMB, os, host_uuid, datastore[0], power_state]

                            vm_info_list.append(vm_info)
    object_view.Destroy()

    with open("{}.csv".format(clustername), 'w') as file:
        writer = csv.writer(file)
        writer.writerows(vm_info_list)