当前位置: 首页>>代码示例>>Python>>正文


Python VIServer.get_resource_pools方法代码示例

本文整理汇总了Python中pysphere.VIServer.get_resource_pools方法的典型用法代码示例。如果您正苦于以下问题:Python VIServer.get_resource_pools方法的具体用法?Python VIServer.get_resource_pools怎么用?Python VIServer.get_resource_pools使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pysphere.VIServer的用法示例。


在下文中一共展示了VIServer.get_resource_pools方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
def main():
    """Sets up the module parameters, validates them and perform the change"""
    module = AnsibleModule(
        argument_spec=dict(
            vcenter_hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
            guest=dict(required=True),
            resource_pool=dict(required=True),
            cluster=dict(required=True),
            sync=dict(required=False, type='bool', default=True)
        ),
        supports_check_mode=True
    )

    server = VIServer()
    server.connect(
        module.params['vcenter_hostname'],
        module.params['username'],
        module.params['password'])
    virtualmachine = server.get_vm_by_name(module.params['guest'])

    old_name = virtualmachine.get_resource_pool_name()
    new_name = module.params['resource_pool']

    # find the clusters ManagedObjectReference
    cluster = None
    clusters = server.get_clusters()
    for mor, name in clusters.iteritems():
        if name == module.params['cluster']:
            cluster = mor
            break

    if cluster is None:
        module.fail_json(msg='Cluster %s not found on server %s' %
            (module.params['cluster'], module.params['vcenter_hostname']))

    # find the new resource pools Managed Object Reference and migrate the VM
    rps = server.get_resource_pools(from_mor=cluster)
    for mor, path in rps.iteritems():
        if re.match('.*%s$' % new_name, path):
            if not re.match('.*%s$' % old_name, path):
                if not module.check_mode:
                    virtualmachine.migrate(
                        resource_pool=mor,
                        host=virtualmachine.get_property('hostname'),
                        sync_run=module.params['sync'])
                module.exit_json(changed=True, changes=module.params)
            module.exit_json(changed=False, changes=module.params)
    module.fail_json(msg='Resource pool %s not found' %
        module.params['resource_pool'])
开发者ID:elrido,项目名称:ansible-modules-vsphere,代码行数:53,代码来源:vsphere_migrate_pool.py

示例2: VMWareSystem

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
class VMWareSystem(MgmtSystemAPIBase):
    """Client to Vsphere API

    This class piggy backs off pysphere.

    Benefits of pysphere:
      - Don't need intimate knowledge w/ vsphere api itself.
    Detriments of pysphere:
      - Response often are not detailed enough.

    """

    _stats_available = {
        'num_vm': lambda self: len(self.list_vm()),
        'num_host': lambda self: len(self.list_host()),
        'num_cluster': lambda self: len(self.list_cluster()),
        'num_template': lambda self: len(self.list_template()),
        'num_datastore': lambda self: len(self.list_datastore()),
    }

    def __init__(self, hostname, username, password, **kwargs):
        self.api = VIServer()
        self.api.connect(hostname, username, password)

    def _get_vm(self, vm_name=None):
        if vm_name is None:
            raise Exception('Could not find a VM named %s.' % vm_name)
        else:
            try:
                vm = self.api.get_vm_by_name(vm_name)
                return vm
            except VIException as ex:
                raise Exception(ex)

    def does_vm_exist(self, name):
        try:
            self._get_vm(name)
            return True
        except Exception:
            return False

    def _get_resource_pool(self, resource_pool_name=None):
        rps = self.api.get_resource_pools()
        for mor, path in rps.iteritems():
            if re.match('.*%s' % resource_pool_name, path):
                return mor
        # Just pick the first
        return rps.keys()[0]

    def get_ip_address(self, vm_name):
        vm = self._get_vm(vm_name)
        maxwait = 600
        net_info = None
        waitcount = 0
        while net_info is None:
            if waitcount > maxwait:
                break
            net_info = vm.get_property('net', False)
            waitcount += 5
            time.sleep(5)
        if net_info:
            ipv4_re = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
            for ip in net_info[0]['ip_addresses']:
                if re.match(ipv4_re, ip) and ip != '127.0.0.1':
                    return ip
        return None

    def _get_list_vms(self, get_template=False):
        template_or_vm_list = []

        props = self.api._retrieve_properties_traversal(property_names=['name', 'config.template'],
                                                        from_node=None,
                                                        obj_type=MORTypes.VirtualMachine)
        for prop in props:
            vm = None
            template = None
            for elem in prop.PropSet:
                if elem.Name == "name":
                    vm = elem.Val
                elif elem.Name == "config.template":
                    template = elem.Val
            if vm is None or template is None:
                continue
            if template == bool(get_template):
                template_or_vm_list.append(vm)
        return template_or_vm_list

    def start_vm(self, vm_name):
        vm = self._get_vm(vm_name)
        if vm.is_powered_on():
            return True
        else:
            vm.power_on()
            ack = vm.get_status()
            if ack == 'POWERED ON':
                return True
        return False

    def stop_vm(self, vm_name):
        vm = self._get_vm(vm_name)
#.........这里部分代码省略.........
开发者ID:jwadkins,项目名称:cfme_tests,代码行数:103,代码来源:mgmt_system.py

示例3: VMWareSystem

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
class VMWareSystem(MgmtSystemAPIBase):
    """Client to Vsphere API

    This class piggy backs off pysphere.

    Benefits of pysphere:
      - Don't need intimate knowledge w/ vsphere api itself.
    Detriments of pysphere:
      - Response often are not detailed enough.

    """

    def __init__(self, hostname, username, password, **kwargs):
        self.api = VIServer()
        self.api.connect(hostname, username, password)

    def _get_vm(self, vm_name=None):
        if vm_name is None:
            raise Exception('Could not find a VM named %s.' % vm_name)
        else:
            try:
                vm = self.api.get_vm_by_name(vm_name)
                return vm
            except VIException as ex:
                raise Exception(ex)

    def _get_resource_pool(self, resource_pool_name=None):
        rps = self.api.get_resource_pools()
        for mor, path in rps.iteritems():
            if re.match('.*%s' % resource_pool_name, path):
                return mor
        # Just pick the first
        return rps.keys()[0]

    def _find_ip(self, vm):
        maxwait = 600
        net_info = None
        waitcount = 0
        while net_info is None:
            if waitcount > maxwait:
                break
            net_info = vm.get_property('net', False)
            waitcount += 5
            time.sleep(5)
        if net_info:
            ipv4_re = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
            for ip in net_info[0]['ip_addresses']:
                if re.match(ipv4_re, ip) and ip != '127.0.0.1':
                    return ip
        return None

    def start_vm(self, vm_name):
        vm = self._get_vm(vm_name)
        if vm.is_powered_on():
            return True
        else:
            vm.power_on()
            ack = vm.get_status()
            if ack == 'POWERED ON':
                return True
        return False

    def stop_vm(self, vm_name):
        vm = self._get_vm(vm_name)
        if vm.is_powered_off():
            return True
        else:
            vm.power_off()
            ack = vm.get_status()
            if ack == 'POWERED OFF':
                return True
        return False

    def delete_vm(self, vm_name):
        vm = self._get_vm(vm_name)

        if vm.is_powered_on():
            self.stop_vm(vm_name)

        # When pysphere moves up to 0.1.8, we can just do:
        # vm.destroy()
        request = VI.Destroy_TaskRequestMsg()
        _this = request.new__this(vm._mor)
        _this.set_attribute_type(vm._mor.get_attribute_type())
        request.set_element__this(_this)
        rtn = self.api._proxy.Destroy_Task(request)._returnval

        task = VITask(rtn, self.api)
        status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
        if status == task.STATE_SUCCESS:
            return True
        else:
            return False

    def create_vm(self, vm_name):
        raise NotImplementedError('This function has not yet been implemented.')

    def restart_vm(self, vm_name):
        if not self.stop_vm(vm_name):
            return False
#.........这里部分代码省略.........
开发者ID:apagac,项目名称:cfme_pages,代码行数:103,代码来源:mgmt_system.py

示例4: __init__

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
class Creator:
    # todo; add comment
    """

    """

    def __init__(self, manager_address, manager_user, manager_password):
        """

        :param manager_address:
        :param manager_user:
        :param manager_password:
        """
        self.esx_server = VIServer()
        self.esx_address = manager_address
        self.esx_user = manager_user
        self.esx_password = manager_password

    def __del__(self):
        self._disconnect_from_esx()

    # todo; add comment
    def _connect_to_esx(self):
        """


        :raise:
        """
        if not self.esx_server.is_connected():
            try:
                self.esx_server.connect(self.esx_address, self.esx_user, self.esx_password)
            except Exception as inst:
                raise CreatorException(str(inst))

    def _disconnect_from_esx(self):
        # todo; add comment
        """

        """
        if self.esx_server.is_connected():
            self.esx_server.disconnect()

    def create_resource_pool(
        self,
        name,
        parent_rp="/",
        esx_hostname=None,
        cpu_resources=("normal", 4000, 0, True, -1),
        memory_resources=("normal", 163840, 0, True, -1),
    ):

        """
        Creates a resource pool on esx server
        name - name for new resource pool
        parent_pr - parent resource pool
        esx_hostname - host name of esx server when resource pool will be created
        cpu_resources and memory_resources: tuple
        0:share level - 'low' 'normal' 'high' 'custom'
        1:share value - 'custom' share value, int
        2:reservation - reserved CPU/Memory, int
        3:expandable reservation - bool
        4:limit - -1 - unlimited, another value - limit value, int

        :raise: CreatorException
        """
        self._connect_to_esx()

        if parent_rp == "/":
            parent_rpmor = None
            try:
                rp_mor_temp = [k for k, v in self.esx_server.get_resource_pools().items() if v == "/Resources"]
            except IndexError:
                raise CreatorException("Couldn't find parent resource pool")
            if len(rp_mor_temp) == 0:
                raise CreatorException("Couldn't find parent resource pool")

            if esx_hostname:
                for rp in rp_mor_temp:
                    prop = VIProperty(self.esx_server, rp)
                    if prop.parent.name == esx_hostname:
                        parent_rpmor = rp
                        break
                if not parent_rpmor:
                    raise CreatorException("Couldn't find host")
            else:
                parent_rpmor = rp_mor_temp[0]
        else:
            parent_rp = "/Resources" + parent_rp
            parent_rpmor = None
            try:
                parent_rp_temp = [k for k, v in self.esx_server.get_resource_pools().items() if v == parent_rp]
            except IndexError:
                raise CreatorException("Couldn't find parent a resource pool")
            if len(parent_rp_temp) == 0:
                raise CreatorException("Couldn't find parent a resource pool")
                ##222
            if len(parent_rp_temp) == 1:
                parent_rpmor = parent_rp_temp[0]
            elif esx_hostname:
                for rp in parent_rp_temp:
#.........这里部分代码省略.........
开发者ID:rkhozinov,项目名称:deployment_system,代码行数:103,代码来源:hatchery.py

示例5: connect

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
class basicOps:

    server=None

    def connect(self):
        configuration=Config()
        server = configuration._config_value("general", "server")
        if server is None:
            raise ValueError("server must be supplied on command line"+"or in configuration file.")
        username = configuration._config_value("general", "username")
        if username is None:
            raise ValueError("username must be supplied on command line"
                         " or in configuration file.")
        password = configuration._config_value("general", "password")
        if password is None:
            raise ValueError("password must be supplied on command line"
                         " or in configuration file.")
        self.server=VIServer()
        self.server.connect(server,username,password)

    def startVm(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        status=vm.get_status()
        if status=="POWERED OFF":
            task=vm.power_on(run_sync=False)
            return task

    def stopVm(self, vmname):
        vm=self.server.get_vm_by_name(vmname)
        status=vm.get_status()
        if status=="POWERED ON":
            task=vm.power_off(run_sync=False)
            return task


    def stopGuest(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        task=vm.shutdown_guest(run_sync=False)
        return task

    def rebootGuest(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        task=vm.reboot_guest(run_sync=False)
        return task

    def getDataCenters(self):
        return self.server.get_datacenters()

    def clone(self,templateName,cloneName="Template Clone"):
        vm=self.server.get_vm_by_name(templateName)
        resourcePool=self.getResourcePool()
        print resourcePool
        task=vm.clone(cloneName,resourcepool=resourcePool,sync_run=False)
        try:
            status=task.get_state()
            print(status)
            print "Creating machine from template:Job Status:" + status
            if  status!="error":
              while (status!="success" or status !="error"):
                  status=task.get_state()
                  if  status=="success":
                   break;
            print "Creating machine from template: Job Status:" + status
            #vm_new=self.server.get_vm_by_name(cloneName)
            #return vm_new
        except:
            print("Error Occured:")


    def getResourcePool(self):

        configuration=Config()
        datacenter = configuration._config_value("vmware", "datacenter")
        if datacenter is None:
            raise ValueError("server must be supplied"+"in configuration file.")
        cluster = configuration._config_value("vmware", "cluster")
        if cluster is None:
            raise ValueError("cluster name must be supplied in configuration file.")
        resourcePool = configuration._config_value("vmware", "resourcePool")
        if resourcePool is None:
            raise ValueError("Resource Pool name must be supplied in configuration file")
        clusters=self.server.get_clusters()
            #print clusters
        keycluster=self.find_key(clusters,cluster)
           # print(keycluster)
        resource_pools=self.server.get_resource_pools(keycluster)
       # print(resource_pools)
        resourcePool=self.find_key(resource_pools,resourcePool,True)
       # print (resourcePool)
        return resourcePool


 #               resource_pools=self.server.get_resource_pools()
    def find_key(self,dic, val, partial=False):
      retval=None
      if partial==False:
       retval=[k for k, v in dic.iteritems() if v == val][0]
      else:
        retval =[k for k, v in dic.iteritems() if (v.find(val)>0)][0]
      return retval
#.........这里部分代码省略.........
开发者ID:ichaudhry786,项目名称:vmware,代码行数:103,代码来源:basicOps.py

示例6: __init__

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]

#.........这里部分代码省略.........
            return True
        return False

    #To get all the definition registered vms from the connected server
    #@param[string]: can be set as ALL, POWER_ON, POWER_OFF, SUSPENDED
    #According to the param, returns a list of VM Paths. You might also filter by datacenter,
    #cluster, or resource pool by providing their name or MORs.
    #if  cluster is set, datacenter is ignored, and if resource pool is set
    #both, datacenter and cluster are ignored.
    def get_registered_vms(self, param, status=None, datacenter=None, cluster=None,
                           resource_pool=None):
        if param not in ['ALL', 'POWER_ON', 'POWER_OFF', 'SUSPENDED']:
            print "Get VMs error: param can only be set as ALL, POWER_ON, POWER_OFF, or SUSPENDED."
            return None
        if self.connect_flag == False:
            print "Get VMs error: Server not connected."
            return None
        if param == 'ALL':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool)
        elif param == 'POWER_ON':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='poweredOn')
        elif param == 'POWER_OFF':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='poweredOff')
        elif param == 'SUSPENDED':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='suspended')
        else:
            return None

    #Disconnect to the Server
    def disconnect(self):
        if self.connect_flag == True:
            self.server = self.server.disconnect()
            self.connect_flag == False

    #To keep session alive
    def keep_session_alive(self):
        assert self.server.keep_session_alive()

    #To get the server type
    def get_server_type(self):
        return self.server.get_server_type()

    #To get performance manager
    def get_performance_manager(self):
        return self.server.get_performance_manager()

    #To get the all the server's hosts
    def get_all_hosts(self):
        """
        Returns a dictionary of the existing hosts keys are their names
        and values their ManagedObjectReference object.
        """
        return self.server.get_hosts()

    #To get all datastores
    def get_all_datastores(self):
        """
        Returns a dictionary of the existing datastores. Keys are
        ManagedObjectReference and values datastore names.
        """
        return self.server.get_datastores()

    #To get all clusters
    def get_all_clusters(self):
        """
        Returns a dictionary of the existing clusters. Keys are their
        ManagedObjectReference objects and values their names.
        """
        return self.server.get_clusters()

    #To get all datacenters
    def get_all_datacenters(self):
        """
        Returns a dictionary of the existing datacenters. keys are their
        ManagedObjectReference objects and values their names.
        """
        return self.server.get_datacenters()

    #To get all resource pools
    def get_all_resource_pools(self):
        """
        Returns a dictionary of the existing ResourcePools. keys are their
        ManagedObjectReference objects and values their full path names.
        """
        return self.server.get_resource_pools()

    #To get hosts by name
    def get_hosts_by_name(self, from_mor):
        """
        Returns a dictionary of the existing ResourcePools. keys are their
        ManagedObjectReference objects and values their full path names.
        @from_mor: if given, retrieves the hosts contained within the specified
            managed entity.
        """
        try:
            hosts_dic = self.server.get_hosts(from_mor)
        except:
            print "Get hosts error!"
            return None
        return hosts_dic
开发者ID:cloudtrends,项目名称:scaffold-shell,代码行数:104,代码来源:esxitools.py

示例7: VIServer

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
    logging.basicConfig(level=logging.DEBUG)
    #you can get the resource pools running s.get_resource_pools()
    RESOURCE_POOL = "/Resources"
    OVF_FILE = "ovf.ovf"
    #you can get the host names running s.get_hosts()
    HOST = "10.16.120.54"
    DATASTORE = "datastore1"
    NETWORK_MAPPING = {"bridged":"VM Network"}
    VAPP_NAME = "import1"
    s = VIServer()
    s.connect("10.16.120.178", "administrator", "R3dhat!")
    try:
        LOGGER.debug('Hosts: %s.', s.get_hosts())
        host = [k for k,v in s.get_hosts().items() if v==HOST][0]

        resource_pool = [k for k,v in s.get_resource_pools().items()
                         if v == RESOURCE_POOL][0]
        LOGGER.debug('Datastores: %s', s.get_datastores())
        datastore = [k for k,v in s.get_datastores().items() if v==DATASTORE][0]

        ovf = get_descriptor(OVF_FILE)
        descriptor_info =  parse_descriptor(ovf)
        if hasattr(descriptor_info, "Warning"):
            LOGGER.warning(str(descriptor_info.Warning[0].LocalizedMessage))
        if hasattr(descriptor_info, "Error"):
            LOGGER.error(str(descriptor_info.Error[0].LocalizedMessage))
            exit()
        support_info = validate_host(host, ovf)
        import_spec = create_import_spec(resource_pool,
                                         datastore,
                                         ovf,
开发者ID:jaryn,项目名称:vsphere_importer,代码行数:33,代码来源:vsphere_ovf_import.py

示例8: raw_input

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_resource_pools [as 别名]
try:
  options.vm_path
except NameError:
  options.vm_path = raw_input("Enter the Template/VM to convert: ")

# Make the vcenter connection
server = VIServer()
server.connect(options.vcenter, options.username, options.password)

# Set the host, cluster and resource pool to "deploy" it into
# We get teh "mor" which is a number to identify with vCenter
hosts = server.get_hosts()
host = [k for k,v in hosts.items() if v=="esxhost.local"][0]
vm = server.get_vm_by_name(options.vm_path)
cluster_name = "DevTest_Cluster"
resource_pool = "/Resources"
cluster = [k for k,v in server.get_clusters().items() if v==cluster_name][0]
rpmor = [k for k,v in server.get_resource_pools(from_mor=cluster).items() if v==resource_pool][0]

# This is the request message we send off to make the change, setting the 
# vm, host, and resource pool.
request = VI.MarkAsVirtualMachineRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
request.set_element_pool(rpmor)
request.set_element_host(host)
server._proxy.MarkAsVirtualMachine(request)

server.disconnect()
开发者ID:morphizer,项目名称:misc,代码行数:32,代码来源:mark_virtual.py


注:本文中的pysphere.VIServer.get_resource_pools方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。