python类libvirtError()的实例源码

utils.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __enter__(self):
        try:
            if self.sasl_username and self.sasl_password:

                def request_cred(credentials, user_data):
                    for credential in credentials:
                        if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                            credential[4] = self.sasl_username
                        elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                            credential[4] = self.sasl_password
                    return 0

                auth = [[libvirt.VIR_CRED_AUTHNAME,
                         libvirt.VIR_CRED_PASSPHRASE], request_cred, None]
                flags = libvirt.VIR_CONNECT_RO if self.readonly else 0
                self.conn = libvirt.openAuth(self.uri, auth, flags)
            elif self.readonly:
                self.conn = libvirt.openReadOnly(self.uri)
            else:
                self.conn = libvirt.open(self.uri)

            return self.conn

        except libvirt.libvirtError as e:
            raise exception.LibvirtConnectionOpenError(uri=self.uri, error=e)
utils.py 文件源码 项目:virtualbmc 作者: openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __enter__(self):
        try:
            if self.sasl_username and self.sasl_password:

                def request_cred(credentials, user_data):
                    for credential in credentials:
                        if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                            credential[4] = self.sasl_username
                        elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                            credential[4] = self.sasl_password
                    return 0

                auth = [[libvirt.VIR_CRED_AUTHNAME,
                         libvirt.VIR_CRED_PASSPHRASE], request_cred, None]
                flags = libvirt.VIR_CONNECT_RO if self.readonly else 0
                self.conn = libvirt.openAuth(self.uri, auth, flags)
            elif self.readonly:
                self.conn = libvirt.openReadOnly(self.uri)
            else:
                self.conn = libvirt.open(self.uri)

            return self.conn

        except libvirt.libvirtError as e:
            raise exception.LibvirtConnectionOpenError(uri=self.uri, error=e)
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_connection(self, host, login, passwd, conn):
        host = unicode(host)
        login = unicode(login)
        passwd = unicode(passwd) if passwd is not None else None
        connection = self._search_connection(host, login, passwd, conn)
        if (connection is None):
            self._connections_lock.acquireWrite()
            try:
                connection = self._search_connection(host, login, passwd, conn)
                if (connection is None):
                    connection = wvmConnection(host, login, passwd, conn)
                    if host in self._connections:
                        self._connections[host].append(connection)
                    else:
                        self._connections[host] = [connection]
            finally:
                self._connections_lock.release()

        elif not connection.connected:
            connection.connect()

        if connection.connected:
            return connection.connection
        else:
            raise libvirtError(connection.last_error)
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def createVolumes(self,pool,volume_name,volume_capacity,drive=None):
        if drive is None:drive = 'qcow2'
        volume_xml = """<volume>
                            <name>{volume_name}</name>
                            <allocation>0</allocation>
                            <capacity unit="G">{volume_capacity}</capacity>
                            <target> 
                                <format type="{drive}"/> 
                            </target>                             
                        </volume>
        """        
        volume_xml = volume_xml.format(volume_name=volume_name,volume_capacity=volume_capacity,drive=drive)
        try:
            return pool.createXML(volume_xml, 0)
        except libvirt.libvirtError,e:
            return '?????????????{result}'.format(result=e.get_error_message())
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def clone(self, pool,pool_name,name, clone, format=None):
        '''???'''
        storage_type = self.getStorageMode(pool_name)
        if storage_type == 'dir':
            clone += '.img'
        vol = self.getStorageVolume(pool,name)
        if vol:
            if not format:
                format = self.getStorageVolumeType(name)
            xml = """
                <volume>
                    <name>%s</name>
                    <capacity>0</capacity>
                    <allocation>0</allocation>
                    <target>
                        <format type='%s'/>
                    </target>
                </volume>""" % (clone, format)
            try:
                return self.createXMLFrom(xml, vol, 0)
            except libvirt.libvirtError,e:
                return '?????????????{result}'.format(result=e.get_error_message())
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def mountIso(self,instance,dev, image):
        tree = ElementTree.fromstring(self.getInsXMLDesc(instance,0))
        for disk in tree.findall('devices/disk'):
            if disk.get('device') == 'cdrom':
                for elm in disk:
                    if elm.tag == 'target':
                        if elm.get('dev') == dev:
                            src_media = ElementTree.Element('source')
                            src_media.set('file', image)
                            disk.append(src_media)
                            if instance.state()[0] == 1:
                                xml_disk = ElementTree.tostring(disk)
                                try:
                                    instance.attachDevice(xml_disk)
                                except libvirt.libvirtError,e:
                                    return '??????????{result}'.format(result=e.get_error_message()) 
                                xmldom = self.getInsXMLDesc(instance,1)
                            if instance.state()[0] == 5:
                                xmldom = ElementTree.tostring(tree)
                            try:
                                return self.defineXML(xmldom)
                            except libvirt.libvirtError,e:
                                return '??????????{result}'.format(result=e.get_error_message())
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def addInstanceInterface(self,instance,brName):
        netk = self.getNetwork(brName)
        if netk:     
            xml = netk.XMLDesc(0)
            tree = ElementTree.fromstring(xml)
            try:
                mode = tree.find('virtualport').get('type') 
            except:
                mode = 'brctl'
            model = tree.find('forward').get('mode')               
            interXml = Const.CreateNetcard(nkt_br=brName, ntk_name=brName +'-'+CommTools.radString(length=4), data={'type':model,'mode':mode})
            try:
                return instance.attachDeviceFlags(interXml,3)#??????????flags?3?????????????? 
            except libvirt.libvirtError,e:
                return '??????????????{result}'.format(result=e.get_error_message()) 
        else:return False
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def delInstanceInterface(self,instance,interName): 
        '''??????''' 
        interXml = None
        raw_xml = instance.XMLDesc(0)
        domXml = minidom.parseString(raw_xml)
        for ds in domXml.getElementsByTagName('interface'):
            try:
                dev = ds.getElementsByTagName('target')[0].getAttribute('dev')
            except:
                continue
            if dev == interName:interXml = ds.toxml()  
        if  interXml:
            try:
                return instance.detachDeviceFlags(interXml,3)
            except libvirt.libvirtError,e:
                return '??????????????{result}'.format(result=e.get_error_message()) 
        else:return False
vMConUtils.py 文件源码 项目:VManagePlatform 作者: welliamcao 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def delInstanceDisk(self,instance,volPath):
        '''????'''
        diskXml = None
        raw_xml = instance.XMLDesc(0)
        domXml = minidom.parseString(raw_xml)
        for ds in domXml.getElementsByTagName('disk'):
            try:
                path = ds.getElementsByTagName('source')[0].getAttribute('file')
            except:
                continue
            if path == volPath:diskXml = ds.toxml()  
        if diskXml:
            try:
                return instance.detachDeviceFlags(diskXml,3)
            except libvirt.libvirtError,e:
                return '??????????????{result}'.format(result=e.get_error_message()) 
        else:return False
vmtest_helper.py 文件源码 项目:nitro 作者: KVM-VMI 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, domain, wait, cdrom):
        self.domain = domain
        if self.domain.isActive():
            self.domain.destroy()
        # revert to base snapshot if present
        try:
            snap = self.domain.snapshotLookupByName(SNAPSHOT_BASE)
            logging.info('Reverting to base snapshot')
            self.domain.revertToSnapshot(snap)
        except libvirt.libvirtError:
            logging.warning('Missing snapshot "%s"', SNAPSHOT_BASE)
        # start domain
        logging.info('Testing {}'.format(self.domain.name()))
        self.domain.create()
        # wait for IP address
        self.ip = self.wait_for_ip()
        self.wait = wait
        self.sleep_amount = 1
        logging.info('IP address: %s', self.ip)
        self.wait(self.ip, True)
        self.cdrom = cdrom
guest.py 文件源码 项目:JimV-N 作者: jamesiter 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def define_by_xml(self, conn=None):
        try:
            if conn.defineXML(xml=self.xml):
                log = u' '.join([u'?', self.name, u', UUID', self.uuid, u'????.'])
                logger.info(msg=log)
                log_emit.info(msg=log)
            else:
                log = u' '.join([u'?', self.name, u', UUID', self.uuid, u'????????.'])
                logger.info(msg=log)
                log_emit.info(msg=log)
                return False

        except libvirt.libvirtError as e:
            logger.error(e.message)
            log_emit.error(e.message)
            return False

        return True
check_libvirt_hosts.py 文件源码 项目:igmonplugins 作者: innogames 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def main():
    try:
        conn = openReadOnly(None)
    except libvirtError as error:
        print('WARNING: could not connect to libvirt: ' + str(error))
        exit(1)

    inactive_domains = [d for d in conn.listAllDomains() if not d.isActive()]
    if inactive_domains:
        print('WARNING: ' + ', '.join(
            '{} is defined but not running'.format(d.name())
            for d in inactive_domains
        ))
        exit(1)

    print('OK: all defined domains are running')
    exit(0)
libvirt_kvm.py 文件源码 项目:paws 作者: rhpit 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create_vm(conn, xml_path):
        """Define a new domain in Libvirt, creating new Virtual Machine

        :param conn: Libvirt connection
        :type conn: object
        :param xml_path: full path for XML with VM definition
        :type xml_path: str
        :return True
        :rtype Boolean
        """
        LOG.debug("VM creation, defining new domain in libvirt")
        try:
            conn.defineXMLFlags(xml_path)
            LOG.debug("VM creation, complete")
            return True
        except (SystemExit, libvirtError) as ex:
            LOG.error(ex)
            raise SystemExit(1)
libvirt_kvm.py 文件源码 项目:paws 作者: rhpit 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def start_vm(self, vm):
        """Start virtual machine instance on Libvirt

        :param vm: virtual machine
        :type vm: object
        """
        if self.is_running(vm):
            LOG.debug("VM %s is running" % vm.name())
            return True

        try:
            vm.create()
            LOG.debug("Importing VM %s" % vm)
            # the raise exception is to force the vm state be checked again
            raise Exception
        except libvirt.libvirtError as ex:
            raise ex
libvirt_kvm.py 文件源码 项目:paws 作者: rhpit 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def delete_vm(conn, vm, flag=None):
        """ """
        #TODO: PAWS-84 flag to delete VM during teardown
        try:
            vm.undefineFlags(1)
            LOG.debug("VM %s deleted" % vm.name())
            if flag:
                storage_pools = conn.listAllStoragePools()

                for pool in storage_pools:
                    stgvols = pool.listVolumes()
                    LOG.error(stgvols)

            return True
        except (libvirt.libvirtError, Exception) as ex:
            LOG.error(ex)
pattern.py 文件源码 项目:virt-backup 作者: Anthony25 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def pattern_matching_domains_in_libvirt(pattern, conn):
    """
    Parse the host pattern as written in the config and find matching hosts

    :param pattern: pattern to match on one or several domain names
    :param conn: connection with libvirt
    """
    exclude, pattern = _handle_possible_exclusion_host_pattern(pattern)
    if pattern.startswith("r:"):
        pattern = pattern[2:]
        domains = search_domains_regex(pattern, conn)
    elif pattern.startswith("g:"):
        domains = _include_group_domains(pattern)
    else:
        try:
            # will raise libvirt.libvirtError if the domain is not found
            conn.lookupByName(pattern)
            domains = (pattern,)
        except libvirt.libvirtError as e:
            logger.error(e)
            domains = tuple()

    return {"domains": domains, "exclude": exclude}
abstracts.py 文件源码 项目:CAPE 作者: ctxis 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def dump_memory(self, label, path):
        """Takes a memory dump.
        @param path: path to where to store the memory dump.
        """
        log.debug("Dumping memory for machine %s", label)

        conn = self._connect(label)
        try:
            # create the memory dump file ourselves first so it doesn't end up root/root 0600
            # it'll still be owned by root, so we can't delete it, but at least we can read it
            fd = open(path, "w")
            fd.close()
            self.vms[label].coreDump(path, flags=libvirt.VIR_DUMP_MEMORY_ONLY)
        except libvirt.libvirtError as e:
            raise CuckooMachineError("Error dumping memory virtual machine "
                                     "{0}: {1}".format(label, e))
        finally:
            self._disconnect(conn)
kvmremote.py 文件源码 项目:CAPE 作者: ctxis 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _connect(self, label=None):
        """Connects to libvirt subsystem.
            @raise CuckooMachineError: when unable to connect to libvirt.
            """
        # Check if a connection string is available.

        dsn = self.options.get(label).get("dsn", None)

        if not dsn:
            raise CuckooMachineError("You must provide a proper "
                                     "connection string for "+label)

        try:
            return libvirt.open(dsn)
        except libvirt.libvirtError:
            raise CuckooMachineError("Cannot connect to libvirt")
webvirt.py 文件源码 项目:gunsen 作者: CyberPoint 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def node_snapshot_create(self, domain):
        domains = [ dom.name() for dom in self.domains ]
        if domain not in domains:
            return

        xml_head = """<domainsnapshot> <name>snapshot</name>
        <state>running</state> <memory snapshot='internal'/>
        <disks><disk name='hda' snapshot='internal'/></disks>"""
        xml_tail = "</domainsnapshot>"
        try:
            domain = self.conn.lookupByName(domain)
            self.node_snapshot_clear(domain)
            xml_desc = xml_head + domain.XMLDesc() + xml_tail
            domain.snapshotCreateXML(xml_desc)
            return True
        except libvirt.libvirtError, e:
            logging.error("{} - Failed to create snapshot:\n{}".format(domain, e))
LibvirtClient.py 文件源码 项目:katprep 作者: stdevel 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def has_snapshot(self, vm_name, snapshot_title):
        """
        Returns whether a particular virtual machine is currently protected
        by a snapshot. This requires specifying a VM name.

        :param vm_name: Name of a virtual machine
        :type vm_name: str
        :param snapshot_title: Snapshot title
        :type snapshot_title: str
        """
        try:
            #find VM and get all snapshots
            target_vm = self.SESSION.lookupByName(vm_name)
            target_snapshots = target_vm.snapshotListNames(0)
            if snapshot_title in target_snapshots:
                return True
        except libvirt.libvirtError as err:
            self.LOGGER.error("Unable to determine snapshot: '{}'".format(err))
            raise SessionException(err)
        except Exception as err:
            raise SessionException(err)
LibvirtClient.py 文件源码 项目:katprep 作者: stdevel 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_vm_ips(self):
        """
        Returns a list of VMs and their IPs available through the current 
        connection.
        """
        try:
            #get all VMs
            vms = self.SESSION.listDefinedDomains()
            result = []

            #scan _all_ the VMs
            for vm in vms:
                #get VM and lookup hostname
                target_vm = self.SESSION.lookupByName(vm)
                target_hostname = target_vm.hostname()
                #lookup IP
                target_ip = socket.gethostbyname(target_hostname)
                result.append(
                    {"hostname": target_hostname, "ip": target_ip}
                )
            return result
        except libvirt.libvirtError as err:
            raise SessionException("Unable to get VM IP information: '{}'".format(err))
LibvirtClient.py 文件源码 项目:katprep 作者: stdevel 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def restart_vm(self, vm_name, force=False):
        """
        Restarts a particular VM (default: soft reboot using guest tools).

        :param vm_name: Name of a virtual machine
        :type vm_name: str
        :param force: Flag whether a hard reboot is requested
        :type force: bool
        """
        try:
            target_vm = self.SESSION.lookupByName(vm_name)
            if force:
                #kill it with fire
                target_vm.reboot(1)
            else:
                #killing me softly
                target_vm.reboot(0)
        except libvirt.libvirtError as err:
            if "unsupported flags" in err.message.lower():
                #trying hypervisor default
                target_vm.reboot(0)
                self.LOGGER.error(
                    "Forcing reboot impossible, trying hypervisor default")
            else:
                raise SessionException("Unable to restart VM: '{}'".format(err))
rest.py 文件源码 项目:vAdvisor 作者: kubevirt 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def getVMSpecs(id):
    data = None
    try:
        uuid = UUID(id)
    except Exception:
        uuid = None
    with app.conn as conn:
        try:
            if uuid:
                domain = conn.lookupByUUIDString(id)
            else:
                domain = conn.lookupByName(id)
        except libvirt.libvirtError as e:
            if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
                abort(404)
            raise e
        data = parse_domain_xml(domain.XMLDesc())

    return Response(
        json.dumps(data, default=_datetime_serial),
        mimetype='application/json'
    )
kvm.py 文件源码 项目:ops 作者: xiaomatech 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def close(self):
        """
        closes the connection (if it is active)
        """
        self.connection_state_lock.acquire()
        try:
            if self.connected:
                try:
                    # to-do: handle errors?
                    self.connection.close()
                except libvirtError as e:
                    log_error(str(e))

            self.connection = None
            self.last_error = None
        finally:
            self.connection_state_lock.release()
kvm.py 文件源码 项目:ops 作者: xiaomatech 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def set_console_keymap(self, keymap):
        xml = self._XMLDesc(VIR_DOMAIN_XML_SECURE)
        root = ElementTree.fromstring(xml)
        console_type = self.get_console_type()
        try:
            graphic = root.find("devices/graphics[@type='%s']" % console_type)
        except SyntaxError as e:
            log_error(str(e))
            # Little fix for old version ElementTree
            graphic = root.find("devices/graphics")
        if keymap:
            graphic.set('keymap', keymap)
        else:
            try:
                graphic.attrib.pop('keymap')
            except libvirtError as e:
                log_error(str(e))
        newxml = ElementTree.tostring(root)
        self._defineXML(newxml)
kvm.py 文件源码 项目:ops 作者: xiaomatech 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_storages_images(self):
        """
        Function return all images on all storages
        """
        images = []
        storages = self.get_storages()
        for storage in storages:
            stg = self.get_storage(storage)
            try:
                stg.refresh(0)
            except libvirtError as e:
                log_error(str(e))
            for img in stg.listVolumes():
                if img.endswith('.iso'):
                    pass
                else:
                    images.append(img)
        return images
virtualbmc.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def set_boot_device(self, bootdevice):
        LOG.debug('Set boot device called for %(domain)s with boot '
                  'device "%(bootdev)s"', {'domain': self.domain_name,
                                           'bootdev': bootdevice})
        device = SET_BOOT_DEVICES_MAP.get(bootdevice)
        if device is None:
            return 0xd5

        with utils.libvirt_open(**self._conn_args) as conn:
            domain = utils.get_libvirt_domain(conn, self.domain_name)
            tree = ET.fromstring(domain.XMLDesc())

            for os_element in tree.findall('os'):
                # Remove all "boot" elements
                for boot_element in os_element.findall('boot'):
                    os_element.remove(boot_element)

                # Add a new boot element with the request boot device
                boot_element = ET.SubElement(os_element, 'boot')
                boot_element.set('dev', device)

            try:
                conn.defineXML(ET.tostring(tree))
            except libvirt.libvirtError as e:
                LOG.error('Failed setting the boot device  %(bootdev)s for '
                          'domain %(domain)s', {'bootdev': device,
                                                'domain': self.domain_name})
virtualbmc.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_power_state(self):
        LOG.debug('Get power state called for domain %s', self.domain_name)
        try:
            with utils.libvirt_open(readonly=True, **self._conn_args) as conn:
                domain = utils.get_libvirt_domain(conn, self.domain_name)
                if domain.isActive():
                    return POWERON
        except libvirt.libvirtError as e:
            LOG.error('Error getting the power state of domain %(domain)s. '
                      'Error: %(error)s', {'domain': self.domain_name,
                                           'error': e})
            return

        return POWEROFF
virtualbmc.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def power_off(self):
        LOG.debug('Power off called for domain %s', self.domain_name)
        try:
            with utils.libvirt_open(**self._conn_args) as conn:
                domain = utils.get_libvirt_domain(conn, self.domain_name)
                if domain.isActive():
                    domain.destroy()
        except libvirt.libvirtError as e:
            LOG.error('Error powering off the domain %(domain)s. '
                      'Error: %(error)s' % {'domain': self.domain_name,
                                            'error': e})
            return
virtualbmc.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def power_on(self):
        LOG.debug('Power on called for domain %s', self.domain_name)
        try:
            with utils.libvirt_open(**self._conn_args) as conn:
                domain = utils.get_libvirt_domain(conn, self.domain_name)
                if not domain.isActive():
                    domain.create()
        except libvirt.libvirtError as e:
            LOG.error('Error powering on the domain %(domain)s. '
                      'Error: %(error)s' % {'domain': self.domain_name,
                                            'error': e})
            return


问题


面经


文章

微信
公众号

扫码关注公众号