def check(self):
        super(zstack_vcenter_image_file_checker, self).check()

        server = VIServer()
        server.connect(vcenter_ip, domain_name, password)
        all_vms = server._get_managed_objects(MORTypes.VirtualMachine)

        for mor, name in all_vms.iteritems():
            if name == sync_image_name:
                return self.judge(True)
        else:        
            return self.judge(False)
    def check(self):
        super(zstack_vcenter_image_file_checker, self).check()

        server = VIServer()
        server.connect(vcenter_ip, domain_name, password)
        all_vms = server._get_managed_objects(MORTypes.VirtualMachine)

        for mor, name in all_vms.iteritems():
            if name == sync_image_name:
                return self.judge(True)
        else:
            return self.judge(False)
Ejemplo n.º 3
0
class Server:
    """Vsphere server that a client can connect to"""

    SUPPORTED_FILTER_KEYWORDS = ["uuidSpec", "pathSpec", "nameSpec"]

    url = os.getenv("VSPHERE_URL")
    """URL of vSphere endpoint"""

    # : vSphere account username
    username = os.getenv("VSPHERE_USER")

    # : vSphere account password
    password = os.getenv("VSPHERE_PASSWORD")

    def __init__(self, url=None, username=None, password=None):
        """Constructs an Server instance with given endpoint and credentials
        
        :param url: end point hostname/URL to connect to.
           As of this release, url must be an http url with port 80, e.g.
           like this: http://vsphere.example.com
           
        :param username: vSphere account username
        :param password: vSphere account password
        
        """
        self._server = VIServer()
        self._vm_datacenters = {}

        # don't set to None if already set from environment
        if url:
            self.url = url
        if username:
            self.username = username
        if password:
            self.password = password

    def connect(self, url=None, username=None, password=None):
        """Connects to vSphere server using optional arguments
         that may override those in Server constructor.
        If arguments are not given, previously specified arguments will
        be used for connection in this order:
        
        * last connect arguments (if specified)
        * constructor arguments (if specified)
        * environment variables
        
        If none of the above is specified, the exception MissingArgumentException
        is raised
        
        
        :type url: string
        :param url: end point hostname/URL to connect to
        :type username: string
        :param username: vSphere account username
        :type password: string
        :param password: vSphere account password
        :type password: string
        :param password: vSphere account password
        
        """
        if url:
            self.url = url
        if username:
            self.username = username
        if password:
            self.password = password

        # check if all needed properties available for connect
        argErrors = []
        if not self.url:
            argErrors.append("url unknown")
        if not self.username:
            argErrors.append("username unknown")
        if not self.password:
            argErrors.append("password unknown")

        if argErrors:
            raise MissingArgumentError(" ".join(argErrors))
        # parse host from url
        host = urlparse(self.url).hostname
        # perform connect
        logger.debug("connect: %s; %s" % (url, username))
        self._server.connect(host, self.username, self.password, trace_file=prototrace_file)

    def disconnect(self):
        """Disconnects from vSphere server"""
        self._server.disconnect()
        self._server = []

    def power_on_vm(self, instanceUuid, sync_run=True, host=None):
        """Powers on a virtual machine for a given instanceUuid"""
        return self._get_instance(instanceUuid).power_on(sync_run, host)

    def power_off_vm(self, instanceUuid, sync_run=True):
        """Powers off a virtual machine for a given instanceUuid"""
        return self._get_instance(instanceUuid).power_off(sync_run)

    def clone_vm(self, instanceUuid, name=None, sync_run=True, host=None):
        """Clones a virtual machine for a given instanceUuid.
        
        :param instanceUuid: instanceUuid of VM to clone
        :param name: name to give to the cloned machine.
         if None, a new name will be generated using the original instance
         name with time stamp appended, e.g.:
         'ubuntu_csk1_08-1349968939'
         
        """
        import time

        instance = self._get_instance(instanceUuid)
        if not name:
            name = "%s-%d" % (instance.get_property("name"), time.time())
        return instance.clone(name, sync_run, host=host)

    def reset_vm(self, instanceUuid, sync_run=True):
        """Powers off a virtual machine for a given instanceUuid"""
        return self._get_instance(instanceUuid).reset(sync_run)

    def suspend_vm(self, instanceUuid, sync_run=True):
        """Suspends a virtual machine for a given instanceUuid"""
        return self._get_instance(instanceUuid).suspend(sync_run)

    def list_instances(self, instanceUuid=None, filter=None, datacenter=None):
        """Lists all vmware instances that match the given filter.

        :type instanceUuid: string
        :param instanceUuid: InstanceUuid to filter on. This is a convenience
          parameter that will override a corresponding value in filter, 
          if it exists. 
          
        :param datacenter: name of datacenter to filter VMs registered in that datacenter

        :type filter: dict
        :param filter: represents a filter specification and can consist of 
            any valid properties, such as
            
            { 'config.instanceUuid': [ '50398c64-55ad-7eb2-f14a-6f70b6903b06' ] }
            
            or
            
            {'runtime.powerState': ['poweredOn']}
            
            or
            
            {'runtime.powerState': ['poweredOff'], 'config.instanceUuid': [ '50398c64-55ad-7eb2-f14a-6f70b6903b06' ] }
            


        :rtype: list
        :return: A list of :class:`vmware.vsphere.VM`
        
        """

        # get the vm paths
        if instanceUuid and len(instanceUuid):
            if not isinstance(instanceUuid, str):
                raise BadParameterError("instanceUuid parameter must be a string")
            if not filter:
                filter = {}
            filter["config.instanceUuid"] = [instanceUuid]

        self._vmspaths = self._server.get_registered_vms(datacenter, advanced_filters=filter)
        logger.debug("list_instances: retrieved %d vm paths" % len(self._vmspaths))
        # instantiate instances for vm paths
        self.vms = []
        for p in self._vmspaths:
            self.vms.append(VM(p, self))

        # first time this function runs, fetch information about vm to datacenter mapping
        self._fetch_datacenter_vms()
        return self.vms

    def get_hosts(self, datacenter=None):
        """Returns a dictionary of the existing hosts keys are their names
        and values their ManagedObjectReference object.
        
        Example usage:
        >>> server.get_hosts()
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        >>> server.get_hosts('datacenter-12')
        >>> from catosphere import Server
        >>> server = Server()
        >>> server.connect()
        >>> server.get_datacenters()
        {'datacenter-12': 'csk3', 'datacenter-2': 'csk1', 'datacenter-7': 'csk2'}
        >>> server.get_hosts('datacenter-2')
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219'}
        >>> server.get_hosts('datacenter-7')
        {'host-36': '173.71.195.168'}
        >>> server.get_hosts('datacenter-12')
        {}
        >>> server.get_hosts()
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        >>> server.disconnect()
        
        
        :return: a dict   
         e.g.
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        if not hosts are found, empty dict is returned.

        """
        if datacenter:
            hosts = self._server._get_managed_objects(MORTypes.HostSystem, from_mor=datacenter)
        else:
            hosts = self._server.get_hosts()
        return hosts

    def get_datacenters(self):
        """Returns a dictionary of the existing datacenters. keys are their
        ManagedObjectReference objects and values their names.
                
        :return: a dict   
         e.g.
        {'datacenter-12': 'csk3', 'datacenter-2': 'csk1', 'datacenter-7': 'csk2'}

        """
        return self._server.get_datacenters()

    # ******************************************************
    # ***************** Private Methods *******************
    # ******************************************************

    def _fetch_datacenter_vms(self):
        """ Fetch/cache datacenter vm mapping information.
        
        This can be later used to retrieve datacenter information for each
        VM.
        """
        if not self._vm_datacenters:
            dcs = self.get_datacenters()
            for name in dcs.keys():
                self._vm_datacenters[name] = self._server._get_managed_objects(MORTypes.VirtualMachine, from_mor=name)

            # logger.debug(': _vm_datacenters: %s' % self._vm_datacenters)

    def _get_instance(self, instanceUuid):
        """ Retrieves instance by its instanceUuid.
        
        TODO: make this faster by caching instances.
        """
        instances = self.list_instances(instanceUuid)
        if not instances:
            raise InstanceNotFoundError("Instance %s not found" % instanceUuid)
        else:
            return instances[0]
            vcip = '10.1.8.50'
    
        logger.debug("Trying to connect %s" % vcip)
        vc.connect(vcip,'sbgcf\\svc_report','VMwar3!!')
        cur_region = region

        try:
            host_d = {}
            vm_d = {}
            for c_mor, c_name in vc.get_clusters().items():
                if(not c_name in clstrname_d): continue
                logger.debug("Fetching cluster '%s'",c_name)
                for h_mor,h_name in vc.get_hosts(from_mor=c_mor).items():
                    logger.debug("Fetching host %s",h_name)
                    host_d[h_name] = c_name
                    for v_mor, v_name in vc._get_managed_objects(MORTypes.VirtualMachine, from_mor=h_mor).items():
                        vm_d[v_name] = h_name
        except:
            raise Exception("Failed to query VM list from vCenter %s" % vcip)

    is_replica = re.match('.+REPLICA',appid)

    if(not vm in vm_d):
        if(is_replica):
            ERROR(ErrorCode.E_MISSING_REPLICA,appid," (%s)" % vm)
        else:
            ERROR(ErrorCode.E_MISSING_VM,appid," (%s)" % vm)
        continue      
    
    m = re.match('(\S+-\S+-\S+-\S+-(AMP|MGMT))',appid)
    clstrid = m.group(1)
Ejemplo n.º 5
0
        if num_args == 11:
            oneview_build_number = str(sys.argv[8])
            oneview_passbuild_id = str(sys.argv[9])
            is_purge = str(sys.argv[10])
            vm_munged_name_prefix = vm_name_prefix + version + "_P" + oneview_passbuild_id + "_" + oneview_build_number
        else:
            oneview_build_number = ""
            vm_munged_name_prefix = vm_name_prefix + version

        log("Connecting to vCenter %s..." % server_name)
        server = VIServer()
        server.connect(server_name, user_name, password)

        # Get a reference to the folder in which VM needs to be created
        folders_list = server._get_managed_objects(MORTypes.Folder)
        for key in folders_list.keys():
            if folders_list[key] == folder_name:
                folder_mor = key
                break
        else:
            raise Exception("Folder not found")

#         folder_filter = {"parent": folder_mor}
        clusters_list = server.get_clusters()
        for cluster_key in clusters_list.keys():
            if clusters_list[cluster_key] == cluster_name:
                resourcepool = server.get_resource_pools(cluster_key).keys()[0]
# WPST
        folder_mor = [
            mor for mor, name in server._get_managed_objects(
Ejemplo n.º 6
0
        pass
    print("k and v = %s %s" % (k, v))

print("Couldn't find folder '%s'" % (folder_name))

#look for the resource pool whose path is rp_path

for ds, ds_name in s.get_datastores().items():
    print ds_name
    if ds_name == DATASTORE:
        print "Found Datacenter: %s" % DATASTORE
        pprint(ds)

#VMs should be created by a folder, in ESX always uses the vm folder
vmfmor = [
    k for k, v in s._get_managed_objects(MORTypes.Folder).items() if v == "vm"
][0]
print "vmfmor = %s" % vmfmor

#look for the resource pool whose path is rp_path
rpmor = [k for k, v in s.get_resource_pools().items() if v == rp_path][0]
print "rpmor = %s" % rpmor

#ESXs have just one host, so use that one
hostmor = s.get_hosts().keys()[0]
print "hostmor = %s" % hostmor

create_folder_request = VI.CreateFolderRequestMsg()
config = VI.folder
#config = create_folder_request.new_config()
create_folder_request.set_element_config(config)