Example #1
0
def detect_nfs_datastore_on_host(context, host_name):
    """Find NFS datastore on host"""
    names = set([host_name])
    datastore_name = context.testbed.config['NFS_DATASTORE_NAME']

    # Use vAPI find the Host managed identities
    host_svc = Host(context.stub_config)
    host_summaries = host_svc.list(Host.FilterSpec(names=names))

    for host_summary in host_summaries:
        # Convert the host identifier into a ManagedObject
        host = host_summary.host
        host_mo = vim.HostSystem(host, context.soap_stub)

        for datastore_mo in host_mo.datastore:
            if (datastore_mo.name == datastore_name and
                datastore_mo.summary.type == 'NFS'):
                datastore = datastore_mo._moId
                print("Detected NFS Volume '{}' as {} on Host '{}' ({})".
                      format(datastore_name, datastore, host_name, host))
                context.testbed.entities['HOST_NFS_DATASTORE_IDS'][host_name] \
                    = datastore
                return True

    print("NFS Volume '{}' missing on Host '{}'".
          format(datastore_name, host_name))
    return False
Example #2
0
def cleanup_nfs_datastore(context):
    """Cleanup NFS datastore after running vcenter samples"""
    # Remove NFS datastore from each Host
    host1_name = context.testbed.config['ESX_HOST1']
    host2_name = context.testbed.config['ESX_HOST2']
    names = set([host1_name, host2_name])

    datastore_name = context.testbed.config['NFS_DATASTORE_NAME']

    # Use vAPI find the Host managed identities
    host_svc = Host(context.stub_config)
    host_summaries = host_svc.list(Host.FilterSpec(names=names))

    for host_summary in host_summaries:
        # Convert the host identifier into a ManagedObject
        host = host_summary.host
        host_mo = vim.HostSystem(host, context.soap_stub)

        for datastore_mo in host_mo.datastore:
            if datastore_mo.name == datastore_name:
                datastore_system = host_mo.configManager.datastoreSystem
                datastore_system.RemoveDatastore(datastore_mo)
                print("Removed NFS Volume '{}' ({}) from Host '{}' ({})".
                      format(datastore_name, datastore_mo._moId,
                             host_mo.name, host_mo._moId))
Example #3
0
def detect_stdportgroup(context, host_name, network_name):
    """Find Distributed Switch based on host and network name"""
    # Ensure the standard switch is available on the host
    names = set([host_name])

    # Use vAPI find the Host managed identities
    host_summaries = context.client.vcenter.Host.list(
        Host.FilterSpec(names=names))

    for host_summary in host_summaries:
        # Convert the host identifier into a ManagedObject
        host = host_summary.host
        host_mo = vim.HostSystem(host, context.soap_stub)

        for network_mo in host_mo.network:
            if (type(network_mo) == vim.Network
                    and network_mo.name == network_name):
                network = network_mo._moId
                print(
                    "Detected Standard Portgroup '{}' as {} on Host '{}' ({})".
                    format(network_name, network, host_name, host))
                context.testbed.entities['HOST_STANDARD_SWITCH_IDS'][
                    host_name] = network
                return True

    print("Standard Portgroup '{}' missing on Host '{}'".format(
        network_name, host_name))
    return False
Example #4
0
def detect_vmfs_datastore(context, host_name, datastore_name):
    """Find VMFS datastore given host and datastore names"""
    names = set([host_name])

    # Use vAPI find the Host managed identities
    host_summaries = context.client.vcenter.Host.list(
        Host.FilterSpec(names=names))

    for host_summary in host_summaries:
        # Convert the host identifier into a ManagedObject
        host = host_summary.host
        host_mo = vim.HostSystem(host, context.soap_stub)

        for datastore_mo in host_mo.datastore:
            if (datastore_mo.name == datastore_name
                    and datastore_mo.summary.type == 'VMFS'):
                datastore = datastore_mo._moId
                print(
                    "Detected VMFS Volume '{}' as {} on Host '{}' ({})".format(
                        datastore_name, datastore, host_name, host))
                context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name] \
                    = datastore
                return True

    print("VMFS Volume '{}' missing on Host '{}'".format(
        datastore_name, host_name))
    return False
Example #5
0
 def get_host_by_name(self, datacenter_name, host_name):
     """
     Returns the identifier of a Host
     with the mentioned names.
     """
     datacenter = self.get_datacenter_by_name(datacenter_name)
     if not datacenter:
         return None
     names = set([host_name]) if host_name else None
     filter_spec = Host.FilterSpec(datacenters=set([datacenter]),
                                   names=names)
     host_summaries = self.api_client.vcenter.Host.list(filter_spec)
     host = host_summaries[0].host if len(host_summaries) > 0 else None
     return host
Example #6
0
def detect_host(context, host_name):
    """Find host based on host name"""
    names = set([host_name])

    host_summaries = context.client.vcenter.Host.list(
        Host.FilterSpec(names=names))
    if len(host_summaries) > 0:
        host = host_summaries[0].host
        print("Detected Host '{}' as {}".format(host_name, host))
        context.testbed.entities['HOST_IDS'][host_name] = host
        return True
    else:
        print("Host '{}' missing".format(host_name))
        return False
Example #7
0
def cleanup_hosts(context):
    """Delete hosts after sample run"""
    host1_name = context.testbed.config['ESX_HOST1']
    host2_name = context.testbed.config['ESX_HOST2']
    names = set([host1_name, host2_name])

    host_summaries = context.client.vcenter.Host.list(
        Host.FilterSpec(names=names))
    print('Found {} Hosts matching names {}'.format(
        len(host_summaries), ', '.join(["'{}'".format(n) for n in names])))

    for host_summary in host_summaries:
        host = host_summary.host
        print("Deleting Host '{}' ({})".format(host_summary.name, host))
        context.client.vcenter.Host.delete(host)
Example #8
0
def setup_vmfs_datastore(context, host_name, datastore_name):
    """Find VMFS datastore given host and datastore names"""
    context.testbed.entities['HOST_VMFS_DATASTORE_IDS'] = {}

    names = set([host_name])

    # Use vAPI find the Host managed identities
    host_svc = Host(context.stub_config)
    host_summaries = host_svc.list(Host.FilterSpec(names=names))

    host_summary = host_summaries[0]
    # Convert the host identifier into a ManagedObject
    host = host_summary.host
    host_mo = vim.HostSystem(host, context.soap_stub)

    vmfs_datastores = dict([(datastore_mo.name, datastore_mo)
                            for datastore_mo in host_mo.datastore
                            if datastore_mo.summary.type == 'VMFS'])

    # The VMFS volume exists.  No need to do anything
    if datastore_name in vmfs_datastores:
        datastore = vmfs_datastores[datastore_name]._moId
        print("Detected VMFS Volume '{}' as {} on Host '{}' ({})".
              format(datastore_name, datastore, host_name, host))
        context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name] \
            = datastore
        return True

    # Rename a VMFS datastore
    if len(vmfs_datastores) > 0:
        datastore_mo = list(vmfs_datastores.values())[0]
        datastore = datastore_mo._moId
        print("Renaming VMFS Volume '{}' ({}) on Host '{}' ({}) to '{}'".
              format(datastore_mo.name, datastore,
                     host_name, host, datastore_name))
        task = datastore_mo.Rename(datastore_name)
        pyVim.task.WaitForTask(task)
        return True

    return False
Example #9
0
# Disable the secure connection warning for demo purpose.
# This is not recommended in a production environment.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Connect to a vCenter Server using username and password
config = VsCreadential.load('.credentials.yaml')
client = create_vsphere_client(server=config.hostname, username=config.username, password=config.password, session=session)

context = None # get_unverified_context

filter_spec = Datacenter.FilterSpec(names=set(['Datacenter']))
datacenter_summaries = client.vcenter.Datacenter.list(filter_spec)
datacenter = datacenter_summaries[0].datacenter

filter_spec = Host.FilterSpec(names=set(['esxi-1.prod.vmware.haf']))
host_summaries = client.vcenter.Host.list(filter_spec)
host = host_summaries[0].host

print(client.vcenter.Host.list())



# List all VMs inside the vCenter Server
for vm in client.vcenter.VM.list():
    print(vm)
    VM = client.vcenter.VM.get(vm.vm)
    #print(VM)
    print(type(VM))

    def run(self):
        # Get the virtual machine and power it off.
        self.vm_id = get_vm(self.client, self.vm_name)
        self.vm_info = self.client.vcenter.VM.get(self.vm_id)
        if not self.vm_info:
            raise ValueError("Virtual machine {} not found".format(
                self.vm_name))
        else:
            if self.vm_info.power_state == Power.State.POWERED_ON:
                self.client.vcenter.vm.Power.stop(self.vm_id)
            elif self.vm_info.power_state == Power.State.SUSPENDED:
                self.client.vcenter.vm.Power.start(self.vm_id)
                self.client.vcenter.vm.Power.stop(self.vm_id)

        # Get the tags.
        tags = self.client.tagging.Tag.list()
        for tag in tags:
            info = self.client.tagging.Tag.get(tag)
            if info.name == self.vm_tag_name:
                vm_tag = info
            if info.name == self.host_tag_name:
                host_tag = info

        if not vm_tag or not host_tag:
            raise ValueError("Provided tag(s) not found")

        # Tag the virtual machine and the host.
        attach_tag(self.client, self.vm_id, "VirtualMachine", vm_tag)

        filter_spec = Host.FilterSpec(names=set([self.host_name]))
        all_hosts = self.client.vcenter.Host.list(filter_spec)
        if not len(all_hosts) > 0:
            raise ValueError("Provided host not found")
        host_id = all_hosts[0].host

        attach_tag(self.client, host_id, "HostSystem", host_tag)

        # Create a vm-host affinity policy.
        create_spec = CreateSpec(vm_tag=vm_tag.id,
                                 host_tag=host_tag.id,
                                 name=self.policy_name,
                                 description=self.policy_desc)
        print("Creating a VM-Host affinity policy")
        try:
            self.policy_id = self.client.vcenter.compute.\
                             Policies.create(create_spec)
        except Exception as e:
            print("Policy creation failed")
            raise e
        print("Policy created with id: {}".format(self.policy_id))

        # Power-on the virtual machine.
        print("Powering on {}".format(self.vm_name))
        self.client.vcenter.vm.Power.start(self.vm_id)
        self.vm_info = self.client.vcenter.VM.get(self.vm_id)
        assert self.vm_info.power_state == Power.State.POWERED_ON

        # Check the compliance status of the policy on this virtual machine.
        status = self.client.vcenter.vm.compute.Policies.get(
            self.vm_id, self.policy_id)
        print("The compliance status of policy {} for virtual machine "
              "{} is {}".format(self.policy_id, self.vm_id, status.status))
Example #11
0
    def _get_vm_filter_spec(self):
        vm_filter_spec = VM.FilterSpec()
        datacenters = self.get_option('datacenters')
        if datacenters:
            temp_dcs = []
            for datacenter_name in datacenters:
                dc_filter_spec = Datacenter.FilterSpec(
                    names=set([datacenter_name]))
                datacenter_summaries = self.pyv.rest_content.vcenter.Datacenter.list(
                    dc_filter_spec)
                if len(datacenter_summaries) > 0:
                    temp_dcs.append(datacenter_summaries[0].datacenter)
                else:
                    self._handle_error(message="Unable to find datacenter %s" %
                                       datacenter_name)
            vm_filter_spec.datacenters = set(temp_dcs)

        clusters = self.get_option('clusters')
        if clusters:
            temp_clusters = []
            for cluster_name in clusters:
                ccr_filter_spec = Cluster.FilterSpec(names=set([cluster_name]))
                cluster_summaries = self.pyv.rest_content.vcenter.Cluster.list(
                    ccr_filter_spec)
                if len(cluster_summaries) > 0:
                    temp_clusters.append(cluster_summaries[0].cluster)
                else:
                    self._handle_error(message="Unable to find cluster %s" %
                                       cluster_name)
            vm_filter_spec.clusters = set(temp_clusters)

        folders = self.get_option('folders')
        if folders:
            temp_folders = []
            for folder_name in folders:
                folder_filter_spec = Folder.FilterSpec(
                    names=set([folder_name]))
                folder_summaries = self.pyv.rest_content.vcenter.Folder.list(
                    folder_filter_spec)
                if len(folder_summaries) > 0:
                    temp_folders.append(folder_summaries[0].folder)
                else:
                    self._handle_error(message="Unable to find folder %s" %
                                       folder_name)
            vm_filter_spec.folders = set(temp_folders)

        esxi_hosts = self.get_option('esxi_hostsystems')
        if esxi_hosts:
            temp_hosts = []
            for esxi_name in esxi_hosts:
                esxi_filter_spec = Host.FilterSpec(names=set([esxi_name]))
                esxi_summaries = self.pyv.rest_content.vcenter.Host.list(
                    esxi_filter_spec)
                if len(esxi_summaries) > 0:
                    temp_hosts.append(esxi_summaries[0].host)
                else:
                    self._handle_error(
                        message="Unable to find esxi hostsystem %s" %
                        esxi_name)
            vm_filter_spec.folders = set(temp_hosts)

        resource_pools = self.get_option('resource_pools')
        if resource_pools:
            temp_rps = []
            for rp_name in resource_pools:
                rp_filter_spec = ResourcePool.FilterSpec(names=set([rp_name]))
                rp_summaries = self.pyv.rest_content.vcenter.ResourcePool.list(
                    rp_filter_spec)
                if len(rp_summaries) > 0:
                    temp_rps.append(rp_summaries[0].resourcepool)
                else:
                    self._handle_error(
                        message="Unable to find resource pool %s" % rp_name)
            vm_filter_spec.folders = set(temp_rps)

        return vm_filter_spec