Python libvirt 模块,open() 实例源码

我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用libvirt.open()

项目:virtualbmc    作者:umago    | 项目源码 | 文件源码
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)
项目:virtualbmc    作者:openstack    | 项目源码 | 文件源码
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)
项目:nitro    作者:KVM-VMI    | 项目源码 | 文件源码
def main(args):
    vm_name = args['<vm_name>']
    # get domain from libvirt
    con = libvirt.open('qemu:///system')
    domain = con.lookupByName(vm_name)

    path = os.path.join(os.getcwd(), '{}.raw'.format(vm_name))
    with open(path, 'w') as f:
        # chmod to be r/w by everyone
        os.chmod(path, stat.S_IRUSR | stat.S_IWUSR |
                                stat.S_IRGRP | stat.S_IWGRP |
                                stat.S_IROTH | stat.S_IWOTH)
        # take a ram dump
        flags = libvirt.VIR_DUMP_MEMORY_ONLY
        dumpformat = libvirt.VIR_DOMAIN_CORE_DUMP_FORMAT_RAW
        domain.coreDumpWithFormat(path, dumpformat, flags)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def __init__(self, uri, module):

        self.module = module

        cmd = "uname -r"
        rc, stdout, stderr = self.module.run_command(cmd)

        if "xen" in stdout:
            conn = libvirt.open(None)
        elif "esx" in uri:
            auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], [], None]
            conn = libvirt.openAuth(uri, auth)
        else:
            conn = libvirt.open(uri)

        if not conn:
            raise Exception("hypervisor connection failure")

        self.conn = conn
项目:JimV-N    作者:jamesiter    | 项目源码 | 文件源码
def guest_event_register(cls):
        cls.conn = libvirt.open()
        cls.conn.domainEventRegister(cls.guest_event_callback, None)

        # ?????https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventID
        cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
            None, libvirt.VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION,
            cls.guest_event_migration_iteration_callback, None))

        cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
            None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_ADDED,
            cls.guest_event_device_added_callback, None))

        cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
            None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED,
            cls.guest_event_device_removed_callback, None))
项目:daisy    作者:opnfv    | 项目源码 | 文件源码
def delete_virtual_network(network_xml):
    LI('Begin to find and delete network %s' % network_xml)
    tree = ET.ElementTree(file=network_xml)
    root = tree.getroot()
    names = root.findall('./name')
    assert len(names) == 1
    name = names[0].text

    result = 0
    conn = libvirt.open('qemu:///system')

    for net in conn.listAllNetworks():
        if name == net.name():
            if net.isActive():
                net.destroy()
                LI('Network %s is destroyed' % name)
            net.undefine()
            LI('Network %s is deleted' % name)
            result = 1
            break
    conn.close()
    if not result:
        LI('Network %s is not found' % name)
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def check_all_os(hostname, path_to_write_json=None):
    tuples_domain_disk = get_disks_all_domains()
    cmds1 = list()
    for domain_id, path_domain_disk in tuples_domain_disk:
        cmds1.append({'title': domain_id, 'cmd': cmd_check_os(path_domain_disk)})

    from pprint import pprint
    pprint(cmds1)
    array_out_err = execute_commands(hostname, cmds1, dict_mode=True)
    # from pprint import pprint
    # pprint(array_out_err)
    if path_to_write_json is not None:
        f = open(path_to_write_json, 'w')
        json.dump(array_out_err, f)
        f.close()

    return array_out_err
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def check_all_os(hostname, path_to_write_json=None):
    tuples_domain_disk = get_disks_all_domains()
    cmds1 = list()
    for domain_id, path_domain_disk in tuples_domain_disk:
        cmds1.append({'title': domain_id, 'cmd': cmd_check_os(path_domain_disk)})

    from pprint import pprint
    pprint(cmds1)
    array_out_err = execute_commands(hostname, cmds1, dict_mode=True)
    # from pprint import pprint
    # pprint(array_out_err)
    if path_to_write_json is not None:
        f = open(path_to_write_json, 'w')
        json.dump(array_out_err, f)
        f.close()

    return array_out_err
项目:paws    作者:rhpit    | 项目源码 | 文件源码
def get_connection(self):
        """ Get connection with libvirt using QEMU driver and system
        context

        :return conn: connection with libvirt
        :rtype conn: libvirt connection
        """
        creds = self.args.credentials

        if 'username' in creds:
            auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
                    creds['username'], None]
            conn = libvirt.openAuth(creds['qemu_instance'], auth, 0)
        else:
            conn = libvirt.open(creds['qemu_instance'])

        if conn == None:
            LOG.error('Failed to open connection to %s',
                      creds['qemu_instance'])
            LOG.warn('check PAWS documentation %s' % LIBVIRT_AUTH_HELP)
            raise PawsPreTaskError

        LOG.debug("connected successfully to %s" % creds['qemu_instance'])

        return conn
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def __init__(self, name = "", uri = "qemu:///system"):
        self.name = name
        self.id = ""
        self.xml = ""  #don't modify it 
        self.temp = {
                    'total_cpu_time': 0L,
                    'last_cpu_idle_time': 0L,
                    'disk_read_request': 0L,
                    'disk_write_request': 0L,
                    'disk_read': 0L,
                    'disk_write': 0L,
                    'disk_read_delay': 0,
                    'disk_write_delay': 0,
                    'network_receive_bytes': 0L,
                    'network_transfer_bytes': 0L,
                    'disk_partition_info': {},
                    'timestamp': 0L
                }
        try:
            conn = libvirt.open(uri)
            dom = conn.lookupByName(name)
            self.xml = dom.XMLDesc()
            conn.close()
        except Exception, e:
            logger.exception(e)
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def define(name,  xml, uri="qemu:///system"):
        conn = None
        ret={}

        try:
            conn = libvirt.open(uri)
            dom = conn.defineXML(xml)

            ret["status_code"] = 0 
            ret["msg"] = "OK"
        except Exception, e:
            logger.exception(e)
            ret["status_code"] = -1
            ret["msg"] = str(e)

        if conn:
            conn.close()

        logger.debug(ret)

        return ret
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def undefine(self, uri="qemu:///system"):
        conn = None
        ret={}
        status_code = 0
        msg = "OK"

        try:
            conn = libvirt.open(uri)
            dom = conn.lookupByName(self.name)
            dom.undefine()
            status_code = 0
            msg = "OK"
        except Exception, e:
            status_code = -1
            msg = e
            logger.exception(e)

        if conn:
            conn.close()

        ret["status_code"] = status_code
        ret["msg"] = str(msg)
        logger.debug(ret)

        return ret
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def shutdown(self, uri="qemu:///system"):
        conn = None
        ret={}
        status_code = 0
        msg = "OK"

        try:
            conn = libvirt.open(uri)
            dom = conn.lookupByName(self.name)
            dom.shutdown()
            status_code = 0
            msg = "OK"
        except Exception, e:
            status_code = -1
            msg = e
            logger.exception(e)

        if conn:
            conn.close()

        ret["status_code"] = status_code
        ret["msg"] = str(msg)
        logger.debug(ret)

        return ret
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def destroy(self, uri="qemu:///system"):
        conn = None
        ret={}
        status_code = 0
        msg = "OK"

        try:
            conn = libvirt.open(uri)
            dom = conn.lookupByName(self.name)
            dom.destroy()
            status_code = 0
            msg = "OK"
        except Exception, e:
            status_code = -1
            msg = e
            logger.exception(e)

        if conn:
            conn.close()

        ret["status_code"] = status_code
        ret["msg"] = str(msg)
        logger.debug(ret)

        return ret
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def read_vm_file(self, path, uri="qemu:///system"):
        FILE_OPEN_READ="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"r"}}"""
        FILE_READ="""{"execute":"guest-file-read", "arguments":{"handle":%s,"count":%d}}"""
        FILE_CLOSE="""{"execute":"guest-file-close", "arguments":{"handle":%s}}"""

        file_handle=-1
        try:
            file_handle=self.EXE(FILE_OPEN_READ % path)["return"]
            file_content=self.EXE(FILE_READ % (file_handle,1024000))["return"]["buf-b64"]
            file_content = base64.standard_b64decode(file_content)
        except Exception,e:
            logger.exception(e)
            return None
        finally:
            self.EXE(FILE_CLOSE % file_handle)
        return file_content
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def write_vm_file(self, path, content, uri="qemu:///system"):
        FILE_OPEN_WRITE="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"w+"}}"""
        FILE_WRITE="""{"execute":"guest-file-write", "arguments":{"handle":%s,"buf-b64":"%s"}}"""
        FILE_CLOSE="""{"execute":"guest-file-close", "arguments":{"handle":%s}}"""  
        FILE_FLUSH="""{"execute":"guest-file-flush", "arguments":{"handle":%s}}"""  
        file_handle=-1
        enc_content = base64.standard_b64encode(content)
        try:
            file_handle=self.EXE(FILE_OPEN_WRITE % path)["return"]
            write_count=self.EXE(FILE_WRITE % (file_handle,enc_content))["return"]["count"]
            logger.debug("content:\n%s\npath:\n%s"%(content, path))
        except Exception,ex:
            print Exception,":",ex
            return -1
        finally:
            self.EXE(FILE_FLUSH % file_handle)
            self.EXE(FILE_CLOSE % file_handle)
        return write_count
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def build_host_hw(sn, uri = "qemu:///system"):

    conn = None
    try:
        conn = libvirt.open(uri)
    except Exception, e:
        logger.exception(e)

    ret_dict = {}
    ret_dict['req'] = "host.hw"
    ret_dict['sn'] = sn

    chost = vmmhost(sn, conn)

    ret_dict['body'] = [ chost.get_hw_info() ]

    if conn:
        conn.close()

    return ret_dict
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
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)
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
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")
项目:virtapi    作者:spiperac    | 项目源码 | 文件源码
def _uploadimage(self, name, newname, pool='default', origin='/tmp', suffix='.iso'):
        name = "%s" % (name)
        _pool = self.conn.storagePoolLookupByName(pool)
        poolxml = _pool.XMLDesc(0)
        root = ET.fromstring(poolxml)
        for element in root.getiterator('path'):
            poolpath = element.text
            break
        imagepath = "%s/%s" % (poolpath, newname)
        imagexml = self._xmlvolume(path=imagepath, size=0, diskformat='raw')
        _pool.createXML(imagexml, 0)
        imagevolume = self.conn.storageVolLookupByPath(imagepath)
        stream = self.conn.newStream(0)
        imagevolume.upload(stream, 0, 0)
        with open("%s/%s" % (origin, name)) as ori:
            stream.sendAll(self.handler, ori)
            stream.finish()
        return imagepath
项目:python    作者:hienha    | 项目源码 | 文件源码
def main():
    dic = {}
    vconn = libvirt.open('qemu:///system')
    try:
        name = sys.argv[1]
    except IndexError, e:
        print e
        sys.exit()
    dic.update(getUUID())
    # dic.update(getIP())
    dic.update({'http_host': '192.168.10.213'})
    dic.update(getMAC())
    dic.update(getPort())
    dic.update(getName(name))
    xml = XML % dic
    if createVM(vconn, name, xml):
        print 'created vmachine name is: %s, and port is %s' % (dic['name'], dic['port'])
    time.sleep(15)
    runVM(vconn, xml, name)
项目:apex    作者:opnfv    | 项目源码 | 文件源码
def clean_networks():
    logging.debug('Cleaning all network config')
    for network in constants.OPNFV_NETWORK_TYPES:
        logging.info("Cleaning Jump Host Network config for network "
                     "{}".format(network))
        jumphost.detach_interface_from_ovs(network)
        jumphost.remove_ovs_bridge(network)

    conn = libvirt.open('qemu:///system')
    if not conn:
        raise ApexCleanException('Unable to open libvirt connection')
    logging.debug('Destroying all virsh networks')
    for network in conn.listNetworks():
        if network in constants.OPNFV_NETWORK_TYPES:
            virsh_net = conn.networkLookupByName(network)
            logging.debug("Destroying virsh network: {}".format(network))
            if virsh_net.isActive():
                virsh_net.destroy()
            virsh_net.undefine()
项目:ops    作者:xiaomatech    | 项目源码 | 文件源码
def __init__(self, host, conn):
        """
        Sets all class attributes and tries to open the connection
        """
        # connection lock is used to lock all changes to the connection state attributes
        # (connection and last_error)
        self.connection_state_lock = threading.Lock()
        self.connection = None
        self.last_error = None

        # credentials
        self.host = host
        self.login = kvm_config.get('user')
        self.passwd = kvm_config.get('password')
        self.type = conn

        # connect
        self.connect()
项目:sushy-tools    作者:openstack    | 项目源码 | 文件源码
def __enter__(self):
        try:
            self._conn = (libvirt.openReadOnly(self.uri)
                          if self.readonly else
                          libvirt.open(self.uri))
            return self._conn
        except libvirt.libvirtError as e:
            print('Error when connecting to the libvirt URI "%(uri)s": '
                  '%(error)s' % {'uri': self.uri, 'error': e})
            flask.abort(500)
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def __connect_socket(self):
        uri = 'qemu:///system'

        try:
            return libvirt.open(uri)
        except libvirtError as e:
            self.last_error = 'Connection Failed: ' + str(e)
            self.connection = None
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def __connect_socket(self):
        uri = 'qemu:///system'

        try:
            self.connection = libvirt.open(uri)
            self.last_error = None

        except libvirtError as e:
            self.last_error = 'Connection Failed: ' + str(e)
            self.connection = None
项目:virtualpdu    作者:openstack    | 项目源码 | 文件源码
def _connect(self):
        return closing(libvirt.open(self.uri))
项目:virtualpdu    作者:openstack    | 项目源码 | 文件源码
def __enter__(self):
        if not self.connection:
            self.connection = libvirt.open(self.uri)

        return self.connection
项目:nitro    作者:KVM-VMI    | 项目源码 | 文件源码
def testSetUp(cls, test_class):
        con = libvirt.open('qemu:///system')
        test_class.domain = con.lookupByName(test_class.domain_name)
        test_class.vm = test_class.test_helper(test_class.domain)
项目:nitro    作者:KVM-VMI    | 项目源码 | 文件源码
def prepare_domain_xml(domain_name, qemu_bin_path, nitro_image_path, open_vnc):
    with open('template_domain.xml') as templ:
        domain_xml = templ.read()
        domain_xml = domain_xml.format(domain_name, qemu_bin_path,
                                       nitro_image_path)
        root = tree.fromstring(domain_xml)
        if open_vnc:
            # search for graphics element
            graphics_elem = root.findall("./devices/graphics")[0]
            graphics_elem.attrib['listen'] = '0.0.0.0'
        domain_xml = tree.tostring(root).decode()
        return domain_xml
    return None
项目:nitro    作者:KVM-VMI    | 项目源码 | 文件源码
def __init__(self, vm_name, analyze_enabled, output=None):
        self.vm_name = vm_name
        self.analyze_enabled = analyze_enabled
        self.output = output
        # get domain from libvirt
        con = libvirt.open('qemu:///system')
        self.domain = con.lookupByName(vm_name)
        self.events = []
        self.nitro = None
        # define new SIGINT handler, to stop nitro
        signal.signal(signal.SIGINT, self.sigint_handler)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def __init__(self, uri, module):

        self.module = module

        conn = libvirt.open(uri)

        if not conn:
            raise Exception("hypervisor connection failure")

        self.conn = conn
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def __init__(self, uri, module):

        self.module = module

        conn = libvirt.open(uri)

        if not conn:
            raise Exception("hypervisor connection failure")

        self.conn = conn
项目:freezer-dr    作者:openstack    | 项目源码 | 文件源码
def __init__(self, nodes, fencer_conf):
        super(LibvirtDriver, self).__init__(nodes, fencer_conf)
        self.parser = YamlParser(self.fencer_conf['credentials_file'])
        # initiate libvirt connection
        conn_name = self.fencer_conf.get('name', None)
        self.connection = libvirt.open(name=conn_name)
项目:JimV-N    作者:jamesiter    | 项目源码 | 文件源码
def init_conn(self):
        self.conn = libvirt.open()

        if self.conn is None:
            raise ConnFailed(u'?????? --> ' + sys.stderr)
项目:daisy    作者:opnfv    | 项目源码 | 文件源码
def create_vm(template, name=None, disks=None, physical_bridge=None):
    LI('Begin to create VM %s' % template)

    if name or disks or physical_bridge:
        tree = ET.ElementTree(file=template)
        root = tree.getroot()
        if name:
            modify_vm_name(root, name)
        if disks:
            modify_vm_disk_file(root, disks)
        if physical_bridge:
            modify_vm_bridge(root, physical_bridge)

        temp_file = path_join(WORKSPACE, 'tmp.xml')
        tree.write(temp_file)
        output = commands.getoutput('cat %s' % temp_file)
        os.remove(temp_file)
    else:
        output = commands.getoutput('cat %s' % template)

    conn = libvirt.open('qemu:///system')
    domain = conn.defineXML(output)
    if domain is None:
        err_exit('Failed to define VM %s' % template)
    if domain.create() < 0:
        err_exit('Failed to start VM %s' % template)
    domain.setAutostart(1)
    conn.close()

    LI('VM %s is started' % domain.name())
    return domain
项目:daisy    作者:opnfv    | 项目源码 | 文件源码
def reboot_vm(vm_name, boot_devs=None):
    LI('Begin to reboot VM %s', vm_name)
    conn = libvirt.open('qemu:///system')
    try:
        vm = conn.lookupByName(vm_name)
    except libvirt.libvirtError as e:
        LE(e)
        err_exit('VM %s is not found: ' % vm_name)

    if boot_devs:
        if vm.isActive():
            vm.destroy()
            LI('Destroy VM %s' % vm_name)

        root = ET.fromstring(vm.XMLDesc())
        LI('Modify the boot order %s' % boot_devs)
        modify_vm_boot_order(root, boot_devs)

        LI('Re-define and start the VM %s' % vm_name)
        vm.undefine()
        vm = conn.defineXML(ET.tostring(root))
        vm.create()
        vm.setAutostart(1)
    else:
        vm.reset()

    conn.close()
项目:daisy    作者:opnfv    | 项目源码 | 文件源码
def delete_vm_and_disk(vm_name):
    LI('Begin to delete VM %s', vm_name)
    conn = libvirt.open('qemu:///system')
    vm = None
    for item in conn.listAllDomains():
        if vm_name == item.name():
            vm = item
            break
    if vm is None:
        conn.close()
        LI('VM %s is not found' % vm_name)
        return

    output = vm.XMLDesc()
    root = ET.fromstring(output)

    if vm.isActive():
        vm.destroy()
        LI('Destroy VM %s' % vm.name())
    vm.undefine()

    for disk_file in get_disk_file(root):
        if os.path.isfile(disk_file):
            status, output = commands.getstatusoutput('rm -f %s' % disk_file)
            if status:
                LW('Failed to delete the VM disk file %s' % disk_file)

    conn.close()
    LI('VM %s is removed' % vm_name)
项目:daisy    作者:opnfv    | 项目源码 | 文件源码
def create_virtual_network(template):
    LI('Begin to create virtual network %s' % template)
    output = commands.getoutput('cat %s' % template)
    conn = libvirt.open('qemu:///system')
    network = conn.networkDefineXML(output)
    if network is None:
        err_exit('Failed to define a virtual network %s' % template)

    network.create()  # set the network active
    network.setAutostart(1)
    conn.close()
    LI('Virtual network %s is created' % network.name())
    return network.name()
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def test_hypervisor_conn(uri):
    """ test hypervisor connecton, if fail an error message in log """
    try:
        handle = libvirt.open(uri)
        return handle
    except:
        log.error(sys.exc_info()[1])
        return False
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def analize_backing_chains_outputs(array_out_err=[], path_to_write_json=None, path_to_read_json=None):
    if path_to_write_json is not None:
        f = open(path_to_write_json, 'w')
        json.dump(array_out_err, f)
        f.close()

    if path_to_read_json is not None:
        f = open(path_to_read_json, 'r')
        array_out_err = json.load(f)
        log.debug(len(array_out_err))
        f.close()

    domains_ok = 0
    domains_err = 0
    for d in array_out_err:
        id = d['title']
        if len(d['err']) > 0:
            domains_err += 1
            log.info(d['err'])
            update_domain_status('Failed', id, detail=d['err'])
        else:
            log.debug(id)
            domains_ok += 1
            if type(d['out']) is not str:
                out = out.decode('utf-8')
            else:
                out = d['out']
            l = json.loads(out)

            from pprint import pprint
            pprint(l)
            update_disk_backing_chain(id, 0, l[0]['filename'], l)

    return ({'ok': domains_ok, 'err': domains_err})
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def test_hypervisor_conn(uri):
    """ test hypervisor connecton, if fail an error message in log """
    try:
        handle = libvirt.open(uri)
        return handle
    except:
        log.error(sys.exc_info()[1])
        return False
项目:paws    作者:rhpit    | 项目源码 | 文件源码
def download(link, file_dst, label):
        """Create HTTP request to download a file"""
        # delimit labels to be at same size and a better visualization
        # when printing the progres bar
        fill_out = 20 - len(label)
        extra = " " * fill_out
        pbar_label = label + extra
        LOG.debug("Starting download %s" % link)
        try:
            req = urllib2.urlopen(link)
            remote_file_size = int(req.headers.get('content-length'))
            CHUNK = 16 * 1024
            with open(file_dst, 'wb') as fp:
                with progressbar(length=remote_file_size,
                                 fill_char=style('#', fg='green'),
                                 empty_char=' ',
                                 label=pbar_label,
                                 show_percent=True) as bar:
                    while True:
                        chunk = req.read(CHUNK)
                        if not chunk: break
                        fp.write(chunk)
                        bar.update(len(chunk))

            LOG.debug("Download complete, file %s saved locally" % file_dst)
        except (HTTPError, RequestException, Exception) as ex:
            raise ex
项目:neos    作者:Aftermath    | 项目源码 | 文件源码
def connect(self):
        """Connect to hypervisor and return object."""
        try:
            if self.read_only:
                conn = libvirt.openReadOnly(self.uri)
            else:
                conn = libvirt.open(self.uri)
        except:
            raise
        return conn
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def get_domain(self, uri="qemu:///system"):
        try:
            conn = libvirt.open(uri)
            dom = conn.lookupByName(self.name)
            return dom
            conn.close()
        except Exception, e:
            logger.exception(e)
            return None
项目:webkvmmgr    作者:crazw    | 项目源码 | 文件源码
def change_cur_cpu_number(self, number, uri="qemu:///system"):
        try:
            conn = libvirt.open(uri)
            nodeinfo = conn.getInfo()
        except Exception, e:
            logger.exception(e)
            return None 
        if conn:
            conn.close()

        host_maxcpus = int(nodeinfo[2])
        if number > host_maxcpus or number <= 0:
            logger.warning("invalid cpu number")
            return None

        tree = ET.fromstring(self.xml)
        vcpu_ele = tree.find('vcpu')
        max_vcpu = vcpu_ele.text
        if max_vcpu is not None and int(max_vcpu) < number:
            vcpu_ele.text = str(number)
        vcpu_ele.set('current', str(number))

        topo_ele = tree.find('cpu/topology')
        if topo_ele:
            topo_ele.set('sockets', vcpu_ele.text)
            topo_ele.set('cores', '1')
            topo_ele.set('threads', '1')
        self.xml = ET.tostring(tree)
        return self.xml