Python pyVmomi.vim.HostSystem() Examples

The following are 30 code examples of pyVmomi.vim.HostSystem(). 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: add_portgroup_to_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 7 votes vote down vote up
def GetVMHosts(content, regex_esxi=None):
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    match_obj = []
    if regex_esxi:
        for esxi in obj:
            if re.findall(r'%s.*' % regex_esxi, esxi.name):
                match_obj.append(esxi)
        match_obj_name = [match_esxi.name for match_esxi in match_obj]
        print("Matched ESXi hosts: %s" % match_obj_name)
        host_view.Destroy()
        return match_obj
    else:
        host_view.Destroy()
        return obj 
Example #2
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def erase_partition(self, host, device_path):
        """
        Erase the partitions on the disk

        Args:
            host (vim.HostSystem): Host instance
            device_path (str): Device path to erase the partition
               e.g:"/vmfs/devices/disks/naa.910229801b540c0125ef160f3048faba"

        """
        # set empty partition spec
        spec = vim.HostDiskPartitionSpec()
        host.configManager.storageSystem.UpdateDiskPartitions(
            device_path,
            spec
        ) 
Example #3
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 #4
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_storage_devices(self, host):
        """
        Fetches all the storage devices in the Host. It excludes
        the enclosures.

        Args:
            host (vim.HostSystem): Host instance

        Returns:
            list: List of storage devices in Host

        """
        logger.debug(f"Fetching all the storage devices in host {host.name}")
        storage_system = host.configManager.storageSystem
        storage_device_info = storage_system.storageDeviceInfo
        return [
            ScsiDisk.deviceName for ScsiDisk in storage_device_info.scsiLun
            if ScsiDisk.deviceType == 'disk'
        ] 
Example #5
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_mounted_devices_in_vsan(self, host):
        """
        Fetches the devices which was mounted in VSAN

        Args:
            host (vim.HostSystem): Host instance

        Returns:
            list: List of storage devices which was mounted

        """
        device_list = []
        logger.debug(
            f"Fetching all the storage devices mounted in host {host.name}"
        )
        disk_mapping = host.config.vsanHostConfig.storageInfo.diskMapping
        for each in disk_mapping:
            device_list.append(each.ssd.devicePath)
            for hd in each.nonSsd:
                device_list.append(hd.devicePath)
        logger.debug(f"Mounted devices in Host {host.name}: {device_list}")
        return device_list 
Example #6
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_mounted_devices(self, host, datastore_type="VMFS"):
        """
        Fetches the available storage devices on Host.

        Args:
            host (vim.HostSystem): Host instance
            datastore_type (str): Type of datastore. Either VMFS or vsan
                By default, it will take VMFS as datastore type.

        Returns:
            list: List of storage devices available for use

        """
        if datastore_type == VMFS:
            return self.get_mounted_devices_in_vmfs(host)
        else:
            return self.get_mounted_devices_in_vsan(host) 
Example #7
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_active_partition(self, host):
        """
        Fetches the active partition disk on Host

        Args:
            host (vim.HostSystem): Host instance

        Returns:
            str: Active partition disk

        """
        logger.debug(
            f"Getting the active partition device in host {host.name}"
        )
        active_partition = host.config.activeDiagnosticPartition
        if not active_partition:
            active_partition = self.get_active_partition_from_mount_info(host)
            return active_partition
        return active_partition.id.diskName 
Example #8
Source File: host.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def move_host_into_cluster_vim(context, host_name, cluster_name):
    """Use vim api to move host to another cluster"""
    TIMEOUT = 30  # sec

    host = context.testbed.entities['HOST_IDS'][host_name]
    host_mo = vim.HostSystem(host, context.soap_stub)

    # Move the host into the cluster
    if not host_mo.runtime.inMaintenanceMode:
        task = host_mo.EnterMaintenanceMode(TIMEOUT)
        pyVim.task.WaitForTask(task)
    print("Host '{}' ({}) in maintenance mode".format(host, host_name))

    cluster = context.testbed.entities['CLUSTER_IDS'][cluster_name]
    cluster_mo = vim.ClusterComputeResource(cluster, context.soap_stub)

    task = cluster_mo.MoveInto([host_mo])
    pyVim.task.WaitForTask(task)
    print("Host '{}' ({}) moved into Cluster {} ({})".
          format(host, host_name, cluster, cluster_name))

    task = host_mo.ExitMaintenanceMode(TIMEOUT)
    pyVim.task.WaitForTask(task)
    print("Host '{}' ({}) out of maintenance mode".format(host, host_name)) 
Example #9
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_host_obj(self, host_name):
        """
        Fetches the Host object

        Args:
            host_name (str): Host name

        Returns:
            vim.HostSystem: Host instance

        """
        content = self.get_content
        host_view = content.viewManager.CreateContainerView(
            content.rootFolder,
            [vim.HostSystem],
            True
        )
        host_obj = [host for host in host_view.view]
        host_view.Destroy()
        for host in host_obj:
            if host.name == host_name:
                return host 
Example #10
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_used_devices(self, host):
        """
        Fetches the used storage devices in Host.

        Note: Storage devices may be used in different Resource Pools
        of OCS clusters.

        Args:
             host (vim.HostSystem): Host instance

        Returns:
            list: List of storage devices used

        """
        logger.debug(
            f"Fetching all the storage devices used in host {host.name}"
        )
        cluster = host.parent
        dc = cluster.parent.parent.name
        lunids = self.get_lunids(dc)
        host_devices_mapping = self.map_lunids_to_devices(**lunids)
        return host_devices_mapping.get(host) 
Example #11
Source File: run.py    From vcenter-netbox-sync with Apache License 2.0 6 votes vote down vote up
def create_view(self, vc_obj_type):
        """
        Create a view scoped to the vCenter object type desired.

        This should be called before collecting data about vCenter object types.
        :param vc_obj_type: vCenter object type to extract, must be key in vc_obj_views
        :type vc_obj_type: str
        """
        # Mapping of object type keywords to view types
        vc_obj_views = {
            "datacenters": vim.Datacenter,
            "clusters": vim.ClusterComputeResource,
            "hosts": vim.HostSystem,
            "virtual_machines": vim.VirtualMachine,
            }
        # Ensure an active vCenter session exists
        if not self.vc_session:
            log.info("No existing vCenter session found.")
            self.authenticate()
        return self.vc_session.viewManager.CreateContainerView(
            self.vc_session.rootFolder, # View starting point
            [vc_obj_views[vc_obj_type]], # Object types to look for
            True # Should we recurively look into view
            ) 
Example #12
Source File: ezmomi.py    From ezmomi with MIT License 6 votes vote down vote up
def get_host_system_failfast(
            self,
            name,
            verbose=False,
            host_system_term='HS'
    ):
        """
        Get a HostSystem object
        fail fast if the object isn't a valid reference
        """
        if verbose:
            print("Finding HostSystem named %s..." % name)

        hs = self.get_host_system(name)

        if hs is None:
            print("Error: %s '%s' does not exist" % (host_system_term, name))
            sys.exit(1)

        if verbose:
            print("Found HostSystem: {0} Name: {1}" % (hs, hs.name))

        return hs 
Example #13
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def available_storage_devices(self, host, datastore_type="VMFS"):
        """
        Fetches the available storage devices on Host.

        Args:
            host (vim.HostSystem): Host instance
            datastore_type (str): Type of datastore. Either VMFS or vsan
                By default, it will take VMFS as datastore type.

        Returns:
            list: List of storage devices available for use

        """
        storage_devices = self.get_storage_devices(host)
        mounted_devices = self.get_mounted_devices(host, datastore_type)
        used_devices = self.get_used_devices(host)
        active_partition = self.get_active_partition(host)

        used_devices_all = deepcopy(mounted_devices)
        if used_devices:
            used_devices_all += used_devices

        devices_with_active_disk = list(
            set(storage_devices) - set(used_devices_all)
        )
        logger.debug(f"Host {host.name} Storage Devices information:")
        logger.debug(f"Available Storage Devices: {storage_devices}")
        logger.debug(f"Mounted Storage Devices: {mounted_devices}")
        logger.debug(f"Used Storage Devices: {used_devices}")
        logger.debug(
            f"Storage Devices with active partition:"
            f" {devices_with_active_disk}"
        )

        return [
            device for device in devices_with_active_disk
            if active_partition not in device
        ] 
Example #14
Source File: test_filters.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_realtime_resource_collected_by_filters(realtime_instance):
    realtime_instance['resource_filters'] = [
        {'resource': 'vm', 'property': 'name', 'patterns': [r'^\$VM5$', r'^VM4-2\d$']},
        {'resource': 'vm', 'property': 'inventory_path', 'patterns': [u'\\/D\xe4tacenter\\/vm\\/m.*']},
        {'resource': 'vm', 'property': 'hostname', 'patterns': [r'10\.0\.0\.103']},
        {'resource': 'vm', 'property': 'guest_hostname', 'patterns': [r'ubuntu-test']},
        {'resource': 'vm', 'property': 'tag', 'patterns': [r'env:production']},
        {'resource': 'host', 'property': 'name', 'patterns': [r'10\.0\.0\.103'], 'type': 'blacklist'},
    ]
    realtime_instance['collect_tags'] = True

    collected_resources = [
        'VM2-1',
        '$VM3-2',
        '$VM5',
        '10.0.0.101',
        '10.0.0.102',
        '10.0.0.104',
        u'VM1-6ê',
        'VM3-1',
        'VM4-20',
        'migrationTest',
    ]

    check = VSphereCheck('vsphere', {}, [realtime_instance])

    formatted_filters = check.config.resource_filters

    infra = MockedAPI(realtime_instance).get_infrastructure()
    resources = [m for m in infra if m.__class__ in (vim.VirtualMachine, vim.HostSystem)]
    VM2_1 = next(r for r in resources if infra.get(r).get('name') == 'VM2-1')
    check.infrastructure_cache.set_all_tags({vim.VirtualMachine: {VM2_1._moId: ['env:production', 'tag:2']}})
    for resource in resources:
        is_collected = infra.get(resource).get('name') in collected_resources
        assert (
            is_resource_collected_by_filters(
                resource, infra, formatted_filters, check.infrastructure_cache.get_mor_tags(resource)
            )
            == is_collected
        ) 
Example #15
Source File: test_api_rest.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_resource_tags(realtime_instance):
    config = VSphereConfig(realtime_instance, logger)
    mock_api = VSphereRestAPI(config, log=logger)
    mock_mors = [MagicMock(spec=vim.VirtualMachine, _moId="foo")]

    resource_tags = mock_api.get_resource_tags_for_mors(mock_mors)

    expected_resource_tags = {
        vim.HostSystem: {'10.0.0.104-1': ['my_cat_name_2:my_tag_name_2']},
        vim.VirtualMachine: {'VM4-4-1': ['my_cat_name_1:my_tag_name_1', 'my_cat_name_2:my_tag_name_2']},
        vim.Datacenter: {},
        vim.Datastore: {'NFS-Share-1': ['my_cat_name_2:my_tag_name_2']},
        vim.ClusterComputeResource: {},
    }
    assert expected_resource_tags == resource_tags 
Example #16
Source File: test_vsphere.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test__is_excluded():
    """
     * Exclude hosts/vms not compliant with the user's `*_include` configuration.
     * Exclude "non-labeled" virtual machines when the user configuration instructs to.
    """
    # Sample(s)
    include_regexes = {'host_include': "f[o]+", 'vm_include': "f[o]+"}

    # OK
    included_host = MockedMOR(spec="HostSystem", name="foo")
    included_vm = MockedMOR(spec="VirtualMachine", name="foo")

    assert not VSphereLegacyCheck._is_excluded(included_host, {"name": included_host.name}, include_regexes, None)
    assert not VSphereLegacyCheck._is_excluded(included_vm, {"name": included_vm.name}, include_regexes, None)

    # Not OK!
    excluded_host = MockedMOR(spec="HostSystem", name="bar")
    excluded_vm = MockedMOR(spec="VirtualMachine", name="bar")

    assert VSphereLegacyCheck._is_excluded(excluded_host, {"name": excluded_host.name}, include_regexes, None)
    assert VSphereLegacyCheck._is_excluded(excluded_vm, {"name": excluded_vm.name}, include_regexes, None)

    # Sample(s)
    include_regexes = None
    include_only_marked = True

    # OK
    included_vm = MockedMOR(spec="VirtualMachine", name="foo", label=True)
    assert not VSphereLegacyCheck._is_excluded(
        included_vm, {"customValue": included_vm.customValue}, include_regexes, include_only_marked
    )

    # Not OK
    included_vm = MockedMOR(spec="VirtualMachine", name="foo")
    assert VSphereLegacyCheck._is_excluded(included_vm, {"customValue": []}, include_regexes, include_only_marked) 
Example #17
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 #18
Source File: vmware-v2.1.py    From Trillian with Apache License 2.0 5 votes vote down vote up
def find_hostsystem_by_name(content, hostname):

    host_system = get_all_objs(content, [vim.HostSystem])
    for host in host_system:
        if host.name == hostname:
            return host
    return None 
Example #19
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_host(self, vm):
        """
        Fetches the Host for the VM. Host where VM resides

        Args:
            vm (vim.VirtualMachine): VM instance

        Returns:
             vim.HostSystem: Host instance

        """
        return vm.runtime.host 
Example #20
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 #21
Source File: vsphere_client.py    From vmware_guest_auth_bypass with Apache License 2.0 5 votes vote down vote up
def get_host_by_name(self, host_name):
        """
        Get host by name.
        """
        return self.get_obj([vim.HostSystem], host_name) 
Example #22
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_all_objs(self, content, vimtype, folder=None, recurse=True):
        """
        Generate objects of type vimtype

        Args:
            content (vim.ServiceInstanceContent): Service Instance Content
            vimtype (vim.type): Type of vim
                (e.g: For VM's, type is vim.VirtualMachine
                For Hosts, type is vim.HostSystem)
            folder (str): Folder name
            recurse (bool): True for recursive search

        Returns:
            dict: Dictionary of objects and corresponding name
               e.g:{
                   'vim.Datastore:datastore-12158': 'datastore1 (1)',
                   'vim.Datastore:datastore-12157': 'datastore1 (2)'
                   }

        """
        if not folder:
            folder = content.rootFolder

        obj = {}
        container = content.viewManager.CreateContainerView(
            folder,
            vimtype,
            recurse
        )
        for managed_object_ref in container.view:
            obj.update({managed_object_ref: managed_object_ref.name})
        container.Destroy()
        return obj 
Example #23
Source File: vcenter_addvmk.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def find_hostsystem_by_name(content, host_name):
    host = find_vcenter_object_by_name(content, vim.HostSystem, host_name)
    if(host != ""):
        return host
    else:
        print "Host not found"
        return None 
Example #24
Source File: vSphereAutoRestartManager.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def get_hosts(conn):
    print "Getting All hosts Objects"
    content = conn.RetrieveContent()
    container = content.viewManager.CreateContainerView(
        content.rootFolder, [vim.HostSystem], True)
    obj = [host for host in container.view]
    return obj 
Example #25
Source File: del_portgroup_from_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def GetVMHosts(content):
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    host_view.Destroy()
    return obj 
Example #26
Source File: getvnicinfo.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def GetVMHosts(content):
    print("Getting all ESX hosts ...")
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    host_view.Destroy()
    return obj 
Example #27
Source File: add_vswitch_to_host.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def GetVMHosts(content):
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    host_view.Destroy()
    return obj 
Example #28
Source File: del_vswitch_from_host.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def GetVMHosts(content):
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    host_view.Destroy()
    return obj 
Example #29
Source File: reconfigure_host_for_ha.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE

    service_instance = connect.SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=int(args.port),
                                            sslContext=context)
    if not service_instance:
        print("Unable to connect with the vCenter Server "
              "using the provided credentials")
        return -1

    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.RetrieveContent()
    object_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                          [vim.HostSystem],
                                                          True)

    host_list = object_view.view
    object_view.Destroy()

    for host in host_list:
        if host.name == args.esx_host:
            esx = host

    print "Proceeding to execute operation 'Reconfigure for HA' in host %s" % \
          esx.name
    reconf_ha = esx.ReconfigureHostForDAS_Task()
    task = reconf_ha
    tasks.wait_for_tasks(service_instance, [task])
    print "Operation complete"

    return 0

# Main execution 
Example #30
Source File: vsphere_client.py    From vmware_guest_auth_bypass with Apache License 2.0 5 votes vote down vote up
def get_host(self, host_moid):
        """
        Get host by moid.
        """
        return self._get_obj_by_moid(vim.HostSystem, host_moid)