Python libvirt.openReadOnly() Examples

The following are 9 code examples of libvirt.openReadOnly(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module libvirt , or try the search function .
Example #1
Source File: utils.py    From virtualbmc with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: kvm_virtualisation.py    From igcollect with MIT License 5 votes vote down vote up
def main():
    args = parse_args()
    conn = libvirt.openReadOnly(None)
    now = str(int(time()))
    core2node = get_cpu_core_to_numa_node_mapping()

    total_mem_used = 0

    for dom in conn.listAllDomains():
        name = dom.name()
        if args.trim_domain:
            if name.endswith('.' + args.trim_domain):
                name = name[:-len('.' + args.trim_domain)]
        # Strip objectid from domain name to get the hostname
        if '_' in name:
            name = name.split('_', 1)[1]
        # Make hostname save for graphite
        name = name.replace('.', '_')

        dom_state, dom_reason = dom.state()
        if dom_state == libvirt.VIR_DOMAIN_RUNNING:
            get_dom_vcpu_stats(dom, args.prefix, name, now, core2node)
            get_dom_network_stats(dom, args.prefix, name, now)
            get_dom_disk_stats(dom, args.prefix, name, now)

        total_mem_used += get_dom_memory_stats(dom, args.prefix, name, now)
        get_dom_storage_usage(conn, dom, args.prefix, name, now)

    get_hv_storage_usage(conn, args.prefix, now)
    get_hv_memory_usage(conn, args.prefix, now, total_mem_used) 
Example #3
Source File: register_close.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def register_close(params):
    global logger
    logger = params['logger']

    if not version_compare("libvirt-python", 3, 8, 0, logger):
        eventLoopPure(logger)

    conn = libvirt.openReadOnly("qemu:///system")
    conn.registerCloseCallback(connCloseCallback, None)
    time.sleep(1)
    t = threading.Thread(target=restart_libvirtd, args=(conn, logger))

    t.start()
    t.join()

    count = 0
    while count < 5:
        count += 1
        if callback:
            logger.info("PASS: registerCloseCallback successful.")
            break
        time.sleep(2)
        if count == 5:
            logger.error("FAIL: registerCloseCallback failed.")
            return 1

    return 0 
Example #4
Source File: libvirtd.py    From virt-who with GNU General Public License v2.0 5 votes vote down vote up
def _connect(self):
        url = self.config.get('server', "")
        self.logger.info("Using libvirt url: %s", url if url else '""')
        try:
            if self.config.get('password', None):
                auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], libvirt_cred_request, self.config]
                v = libvirt.openAuth(url, auth, libvirt.VIR_CONNECT_RO)
            else:
                v = libvirt.openReadOnly(url)
        except libvirt.libvirtError as e:
            self.logger.exception("Error in libvirt backend")
            raise VirtError(str(e))
        v.domainEventRegister(self._callback, None)
        v.setKeepAlive(5, 3)
        return v 
Example #5
Source File: zabbix-libvirt-res.py    From zabbix-kvm-res with GNU General Public License v2.0 5 votes vote down vote up
def connect(self, uri = None):
        if uri is None:
            uri = self.uri
        try:
            self.conn = libvirt.openReadOnly(uri)
        except:
            print("There was an error connecting to the local libvirt daemon using '%s'." % uri, file=sys.stderr)
            self.conn = None
        return self.conn 
Example #6
Source File: newest_dhcp_lease.py    From kolla-ansible with Apache License 2.0 5 votes vote down vote up
def libvirt_conn(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        conn = libvirt.openReadOnly('qemu:///system')
        return f(conn, *args, **kwargs)
    return wrapper 
Example #7
Source File: main.py    From libvirt_metadata_api with GNU General Public License v3.0 5 votes vote down vote up
def main():
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', type=int, default=1024)
    parser.add_argument('-c', '--connect', dest='libvirt_connection_string', default='qemu:///system')
    parser.add_argument('--enable-xheaders', default=False, action='store_true')
    parser.add_argument('--load-edited-domain-xml', default=False, action='store_true',
                        help='Use this flag to make changes to Domain XML to be reflected immediately (opposed ' +
                        'to requiring a restart of the domain)')
    parser.add_argument('--plugin', action='append', help='Load this plugin. This simply imports the module. ' +
                                                          'See example for more details')
    args = parser.parse_args()

    if args.plugin:
        for plugin in args.plugin:
            __import__(plugin)

    application = tornado.web.Application(
        handlers.routes,
        machine_resolver=utils.machine_resolver.LibvirtMachineResolver(
            libvirt.openReadOnly(args.libvirt_connection_string),
            args.load_edited_domain_xml)
    )

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.xheaders = args.enable_xheaders
    http_server.listen(args.port)
    tornado.ioloop.IOLoop.instance().start() 
Example #8
Source File: libvirt_generic.py    From origin-ci-tool with Apache License 2.0 4 votes vote down vote up
def get_inventory(self):
        ''' Construct the inventory '''

        inventory = dict(_meta=dict(hostvars=dict()))

        conn = libvirt.openReadOnly(self.libvirt_uri)
        if conn is None:
            print "Failed to open connection to %s" % self.libvirt_uri
            sys.exit(1)

        domains = conn.listAllDomains()
        if domains is None:
            print "Failed to list domains for connection %s" % self.libvirt_uri
            sys.exit(1)

        for domain in domains:
            hostvars = dict(libvirt_name=domain.name(),
                            libvirt_id=domain.ID(),
                            libvirt_uuid=domain.UUIDString())
            domain_name = domain.name()

            # TODO: add support for guests that are not in a running state
            state, _ = domain.state()
            # 2 is the state for a running guest
            if state != 1:
                continue

            hostvars['libvirt_status'] = 'running'

            root = ET.fromstring(domain.XMLDesc())
            ansible_ns = {'ansible': 'https://github.com/ansible/ansible'}
            for tag_elem in root.findall('./metadata/ansible:tags/ansible:tag', ansible_ns):
                tag = tag_elem.text
                _push(inventory, "tag_%s" % tag, domain_name)
                _push(hostvars, 'libvirt_tags', tag)

            # TODO: support more than one network interface, also support
            # interface types other than 'network'
            interface = root.find("./devices/interface[@type='network']")
            if interface is not None:
                source_elem = interface.find('source')
                mac_elem = interface.find('mac')
                if source_elem is not None and \
                   mac_elem    is not None:
                    # Adding this to disable pylint check specifically
                    # ignoring libvirt-python versions that
                    # do not include DHCPLeases
                    # This is needed until we upgrade the build bot to
                    # RHEL7 (>= 1.2.6 libvirt)
                    # pylint: disable=no-member
                    dhcp_leases = conn.networkLookupByName(source_elem.get('network')) \
                                      .DHCPLeases(mac_elem.get('address'))
                    if len(dhcp_leases) > 0:
                        ip_address = dhcp_leases[0]['ipaddr']
                        hostvars['ansible_ssh_host'] = ip_address
                        hostvars['libvirt_ip_address'] = ip_address

            inventory['_meta']['hostvars'][domain_name] = hostvars

        return inventory 
Example #9
Source File: unix_perm_sasl.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def hypervisor_connecting_test(uri, unix_sock_group, auth_unix_ro, auth_unix_rw, logger):
    """connect to hypervisor"""
    logger.info("connect to hypervisor")
    orginal_user = os.geteuid()
    testing_user_id = getpwnam(TESTING_USER)[2]
    logger.info("the testing_user id is %d" % testing_user_id)

    logger.info("set euid to %d" % testing_user_id)
    os.seteuid(testing_user_id)

    if utils.version_compare("libvirt", 3, 2, 0, logger):
        cmd = "klist -A | grep 'Ticket cache: FILE:' | awk '{print $3}'"
        ret, out = utils.exec_cmd(cmd, shell=True)
        if ret:
            logger.error("get ticket cache file failed.")
            logger.error("cmd: %s" % cmd)
            logger.error("out: %s" % out)
            return 1

        TICKET_CACHE = out[0].split(':')[1]
        cmd = "chown %s:%s %s" % (TESTING_USER, unix_sock_group, TICKET_CACHE)
        ret, out = utils.exec_cmd(cmd, shell=True)
        if ret:
            logger.error("change %s owner failed." % TICKET_CACHE)
            return 1

    try:
        if auth_unix_ro == 'none':
            conn = libvirt.openReadOnly(uri)
        elif auth_unix_ro == 'sasl':
            user_data = [TESTING_USER, TESTING_USER]
            auth = [[libvirt.VIR_CRED_AUTHNAME,
                     libvirt.VIR_CRED_PASSPHRASE],
                    request_credentials, user_data]
            conn = libvirt.openAuth(uri, auth, 0)

        if auth_unix_rw == 'none':
            conn = libvirt.open(uri)
        elif auth_unix_rw == 'sasl':
            user_data = [TESTING_USER, TESTING_USER]
            auth = [[libvirt.VIR_CRED_AUTHNAME,
                     libvirt.VIR_CRED_PASSPHRASE],
                    request_credentials, user_data]
            conn = libvirt.openAuth(uri, auth, 0)
        conn.close()
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.get_error_message(), e.get_error_code()))
        logger.info("set euid back to %d" % orginal_user)
        os.seteuid(orginal_user)
        conn.close()
        return 1

    logger.info("set euid back to %d" % orginal_user)
    os.seteuid(orginal_user)
    return 0