Example #1
0
    def get_handler(self):
        '''
        return the handler of the virt_driver
        '''
        if self._hypervisor_handler:
            return self._hypervisor_handler

        old = signal.signal(signal.SIGALRM, self.timeout_handler)
        signal.alarm(4)  # connetctions timeout set to 4 secs

        try:
            if self.hostname is None:
                url = DEFAULT_HV
                self._hypervisor_handler = libvirt.open(url)
            else:
                url = "{0}{1}{2}".format('qemu+tls://', self.hostname, '/system')
                self._hypervisor_handler = libvirt.openAuth(url, self._auth, 0)
        except Exception as error:
            log.debug("Can not connect to url: %s, error: %s. Retrying...", url, error)
            signal.alarm(4)
            try:
                url = "{0}{1}{2}".format('qemu+tcp://', self.hostname, '/system')
                self._hypervisor_handler = libvirt.openAuth(url, self._auth, 0)
            except Exception as error:
                log.error("Can not connect to url: %s, error: %s ", url, error)
                return None
        finally:
            signal.alarm(0)
            signal.signal(signal.SIGALRM, old)

        if not self._hypervisor_handler:
            return None

        return self._hypervisor_handler
Example #2
0
    def _get_root_handler(self):
        """
        Return the root handler of libvirt
        """
        if self._hypervisor_root_handler:
            return self._hypervisor_root_handler

        if self.hostname is None:
            hostname = "localhost"
        else:
            hostname = self.hostname
        url = "{0}{1}{2}".format('qemu+tls://', hostname, '/system')
        old = signal.signal(signal.SIGALRM, self.timeout_handler)
        signal.alarm(4)  # connetctions timeout set to 4 secs
        try:
            self._hypervisor_root_handler = libvirt.openAuth(url, self._auth, 0)
        except Exception as error:
            log.debug("Can not connect to %s, error: %s. Retrying...", url, error)
            url = "{0}{1}{2}".format('qemu+tcp://', hostname, '/system')
            signal.alarm(4)
            try:
                self._hypervisor_root_handler = libvirt.openAuth(url, self._auth, 0)
            except Exception as error:
                log.error("Can not connect to url:%s, error: %s", url, error)
                return None

        finally:
            signal.alarm(0)
            signal.signal(signal.SIGALRM, old)

        if self._hypervisor_root_handler:
            return self._hypervisor_root_handler

        return None
Example #3
0
    def __init__(self, host, login, passwd, conn):
        self.login = login
        self.host = host
        self.passwd = passwd
        self.conn = conn

        if self.conn == CONN_TCP:

            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tcp://%s/system' % self.host
            try:
                self.wvm = libvirt.openAuth(uri, auth, 0)
            except libvirtError:
                raise libvirtError('Connection Failed')

        if self.conn == CONN_SSH:
            uri = 'qemu+ssh://%s@%s/system' % (self.login, self.host)
            try:
                self.wvm = libvirt.open(uri)
            except libvirtError as err:
                raise err.message

        if self.conn == CONN_TLS:

            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tls://%s@%s/system' % (self.login, self.host)
            try:
                self.wvm = libvirt.openAuth(uri, auth, 0)
            except libvirtError:
                raise libvirtError('Connection Failed')
Example #4
0
    def __init__(self, host, login, passwd, conn):
        self.login = login
        self.host = host
        self.passwd = passwd
        self.conn = conn

        if self.conn == CONN_TCP:
            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tcp://%s/system' % self.host
            try:
                self.wvm = libvirt.openAuth(uri, auth, 0)
            except libvirtError:
                raise libvirtError('Connection Failed')

        if self.conn == CONN_SSH:
            uri = 'qemu+ssh://%s@%s/system' % (self.login, self.host)
            try:
                self.wvm = libvirt.open(uri)
            except libvirtError as err:
                raise err.message

        if self.conn == CONN_TLS:
            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tls://%s@%s/system' % (self.login, self.host)
            try:
                self.wvm = libvirt.openAuth(uri, auth, 0)
            except libvirtError:
                raise libvirtError('Connection Failed')
    def __init__(self, uri, key=None, secret=None):
        """
        :param  uri: Hypervisor URI (e.g. vbox:///session, qemu:///system,
                     etc.).
        :type   uri: ``str``

        :param  key: the username for a remote libvirtd server
        :type   key: ``str``

        :param  secret: the password for a remote libvirtd server
        :type   key: ``str``
        """
        if not have_libvirt:
            raise RuntimeError('Libvirt driver requires \'libvirt\' Python ' +
                               'package')

        self._uri = uri
        self._key = key
        self._secret = secret
        if uri is not None and '+tcp' in self._uri:
            if key is None and secret is None:
                raise RuntimeError('The remote Libvirt instance requires ' +
                                   'authentication, please set \'key\' and ' +
                                   '\'secret\' parameters')
            auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
                    self._cred_callback, None]
            self.connection = libvirt.openAuth(uri, auth, 0)
        else:
            self.connection = libvirt.open(uri)
        if uri is None:
            self._uri = self.connection.getInfo()
Example #6
0
def hypervisor_connecting_test(uri, auth_tls, username,
                               password, logger, expected_result):
    """ connect remote server """
    ret = 0
    try:
        if auth_tls == 'none':
            conn = libvirt.open(uri)
        elif auth_tls == 'sasl':
            user_data = [username, password]
            auth = [[libvirt.VIR_CRED_AUTHNAME,
                     libvirt.VIR_CRED_PASSPHRASE],
                    request_credentials,
                    user_data]
            conn = libvirt.openAuth(uri, auth, 0)
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.message, e.get_error_code()))
        ret = 1

    conn.close()

    if ret == 0 and expected_result == 'success':
        logger.info("tls authentication success")
        return 0
    elif ret == 1 and expected_result == 'fail':
        logger.info("tls authentication failed, but that is expected")
        return 0
    elif ret == 0 and expected_result == 'fail':
        logger.error("tls authentication success, but we hope the reverse")
        return 1
    elif ret == 1 and expected_result == 'success':
        logger.error("tls authentication failed")
        return 1

    return 0
Example #7
0
    def _openVirConn(self):
        """Open a libvirt connection, and return the virConnect object.
        This method also ensures that the libvirt event is running."""
        def requestCredentials(creds, unused):
            for cred in creds:
                if cred[0] == libvirt.VIR_CRED_AUTHNAME:
                    cred[4] = "root"
                elif cred[0] == libvirt.VIR_CRED_PASSPHRASE:
                    cred[4] = self.password
                else:
                    return -1
            return 0

        # ensure an event loop is running
        if Host.eventThread is None:
            xenrt.TEC().logverbose("Starting libvirt event loop")
            libvirt.virEventRegisterDefaultImpl()
            Host.eventThread = thread.start_new_thread(Host.virEventLoop, ())

        # make the connection to the libvirt daemon on the guest
        xenrt.TEC().logverbose("Connecting to libvirt daemon for %s" % self)
        uri = self._getVirURL()
        auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
                requestCredentials, None]
        virConn = libvirt.openAuth(uri, auth, 0)

        # if necessary, check that the version of libvirt that's on the guest is recent enough
        if self.LIBVIRT_REMOTE_DAEMON and virConn.getLibVersion(
        ) < LIBVIRT_GUEST_MIN_VERSION:
            raise xenrt.XRTError(
                "libvirt version on the guest (%d) is not recent enough (need >= %d)"
                % (virConn.getLibVersion(), LIBVIRT_GUEST_MIN_VERSION))

        return virConn
Example #8
0
def create_snapshot(virtURI, hostUsername, hostPassword, vmName, name, comment, remove=False):
#create/remove snapshot
	#authentificate
	global LIBVIRT_USERNAME
	global LIBVIRT_PASSWORD
	LIBVIRT_USERNAME = hostUsername
	LIBVIRT_PASSWORD = hostPassword

	LOGGER.debug("Creating snapshot with user '" + hostUsername + "'...")
	auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], get_libvirt_credentials, None]
	
	conn = libvirt.openAuth(virtURI, auth, 0)
	
	if conn == None:
		LOGGER.error("Unable to establish connection to hypervisor!")
		#sys.exit(1)
		return False
	
	try:
		targetVM = conn.lookupByName(vmName)
		if remove:
			#remove snapshot
			targetSnap = targetVM.snapshotLookupByName(name, 0)
			return targetSnap.delete(0)
		else:
			#create snapshot
			snapXML = "<domainsnapshot><name>" + name + "</name><description>" + comment + "</description></domainsnapshot>"
			return targetVM.snapshotCreateXML(snapXML, 0)
	except Exception,e: 
		#Snapshot 'Before maintenance' already exists
		if remove:
			LOGGER.error("Unable to remove snapshot: '" + str(e) + "'")
		else:
			LOGGER.error("Unable to create snapshot: '" + str(e) + "'")
		return False
Example #9
0
    def __connect_tcp(self):
        """ 同时支持libvirt远程tcp认证和不认证连接
            (但测试下来tcp认证远程连接有问题,目前还没有明确解决方案,#### todo)
        """
        uri = 'qemu+tcp://%s/system' % self.host

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

        except libvirtError as e:
            if 'authentication failed' in str(e):
                flags = [
                    libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE
                ]
                auth = [flags, self.__libvirt_auth_credentials_callback, None]
                try:
                    self.connection = libvirt.openAuth(uri, auth, 0)
                    self.last_error = None
                except libvirtError as err:
                    self.last_error = 'Connection Failed: ' + str(err)
                    self.connection = None
            else:
                self.last_error = 'Connection Failed: ' + str(e)
                self.connection = None
Example #10
0
def libvirt_conn(host):
    """

    Function for connect to libvirt host.
    Create exceptions and return if not connnected.

    """

    if host.conn_type == 'tcp':
        def creds(credentials, user_data):
            for credential in credentials:
                if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                    credential[4] = host.login
                    if len(credential[4]) == 0:
                        credential[4] = credential[3]
                elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                    credential[4] = host.passwd
                else:
                    return -1
            return 0

        flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
        auth = [flags, creds, None]
        uri = 'qemu+tcp://%s/system' % host.ipaddr
    if host.conn_type == 'ssh':
        uri = 'qemu+ssh://%s@%s:%s/system' % (host.login, host.ipaddr, host.ssh_port)

    try:
        if host.conn_type == 'tcp':
            conn = libvirt.openAuth(uri, auth, 0)
        if host.conn_type == 'ssh':
            conn = libvirt.open(uri)
        return conn
    except libvirt.libvirtError as e:
        return {'error': e.message}
Example #11
0
    def open(self, authcb, cbdata):
        if self._magic_uri:
            self._magic_uri.validate()

        # Mirror the set of libvirt.c virConnectCredTypeDefault
        valid_auth_options = [
            libvirt.VIR_CRED_AUTHNAME,
            libvirt.VIR_CRED_ECHOPROMPT,
            libvirt.VIR_CRED_REALM,
            libvirt.VIR_CRED_PASSPHRASE,
            libvirt.VIR_CRED_NOECHOPROMPT,
            libvirt.VIR_CRED_EXTERNAL,
        ]
        open_flags = 0

        conn = libvirt.openAuth(self._open_uri,
                [valid_auth_options, authcb, cbdata],
                open_flags)

        if self._magic_uri:
            self._magic_uri.overwrite_conn_functions(conn)

        self._libvirtconn = conn
        if not self._open_uri:
            self._uri = self._libvirtconn.getURI()
            self._uriobj = URI(self._uri)
Example #12
0
    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 is None:
            LOG.error('Failed to open connection to %s',
                      creds['qemu_instance'])
            LOG.warn('check PAWS documentation %s' % LIBVIRT_AUTH_HELP)
            raise SystemExit(1)

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

        return conn
Example #13
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)
Example #14
0
 def _global_connect(self):
     """Set the single connection handle."""
     try:
         self.auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], self._auth_callback, None]
         return libvirt.openAuth(self.dsn, self.auth, 0)
     except libvirt.libvirtError as libvex:
         raise CuckooCriticalError("libvirt returned an exception on connection: %s" % libvex)
Example #15
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)
Example #16
0
    def __init__(self, host):
        """

        Return connection object.

        """

        self.login = host.login
        self.host = host.ipaddr
        self.passwd = host.passwd
        self.type = host.conn_type
        self.port = host.ssh_port

        if self.type == 'tcp':

            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tcp://%s/system' % self.host
            self.conn = libvirt.openAuth(uri, auth, 0)
        if self.type == 'ssh':
            uri = 'qemu+ssh://%s@%s:%s/system' % (self.login, self.host,
                                                  self.port)
            self.conn = libvirt.open(uri)
    def __init__(self, uri, key=None, secret=None):
        """
        :param  uri: Hypervisor URI (e.g. vbox:///session, qemu:///system,
                     etc.).
        :type   uri: ``str``

        :param  key: the username for a remote libvirtd server
        :type   key: ``str``

        :param  secret: the password for a remote libvirtd server
        :type   key: ``str``
        """
        if not have_libvirt:
            raise RuntimeError('Libvirt driver requires \'libvirt\' Python ' +
                               'package')

        self._uri = uri
        self._key = key
        self._secret = secret
        if uri is not None and '+tcp' in self._uri:
            if key is None and secret is None:
                raise RuntimeError('The remote Libvirt instance requires ' +
                                   'authentication, please set \'key\' and ' +
                                   '\'secret\' parameters')
            auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
                    self._cred_callback, None]
            self.connection = libvirt.openAuth(uri, auth, 0)
        else:
            self.connection = libvirt.open(uri)
        if uri is None:
            self._uri = self.connection.getInfo()
Example #18
0
 def _global_connect(self):
     """Set the single connection handle."""
     try:
         self.auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], self._auth_callback, None]
         return libvirt.openAuth(self.dsn, self.auth, 0)
     except libvirt.libvirtError as libvex:
         raise CuckooCriticalError("libvirt returned an exception on connection: %s" % libvex)
Example #19
0
    def get_domxml(self):
        def auth_cb(cred, _):
            for c in cred:
                if c[0] == libvirt.VIR_CRED_AUTHNAME:
                    c[4] = self.user
                elif c[0] == libvirt.VIR_CRED_PASSPHRASE:
                    c[4] = self._password
                else:
                    return -1
            return 0

        cred_info = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
                     auth_cb, None]

        if self._uri.startswith('ssh://'):
            uri = "esx://%s@%s/" % (quote(self.user), self.server)
            if self.insecure:
                uri += '?no_verify=1'
        else:
            uri = self._uri

        conn = libvirt.openAuth(uri, cred_info)
        domxml = conn.lookupByName(self._vm_name).XMLDesc()
        logging.debug('Fetched domxml: \n%s', domxml)

        return domxml
Example #20
0
def get_conn(uri='', username='', password=''):
    """ get connection object from libvirt module
    """
    user_data = [username, password]
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_credentials, user_data]
    conn = libvirt.openAuth(uri, auth, 0)
    return conn
Example #21
0
def list_networks():
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], authcb, None]
    uri = "qemu:///system"
    conn = libvirt.openAuth(uri, auth, 0)
    networks = conn.listNetworks()
    conn.close()
    return networks
Example #22
0
    def __init__(self, host):
        """

        Return connection object.

        """

        self.login = host.login
        self.host = host.ipaddr
        self.passwd = host.passwd
        self.type = host.conn_type
        self.port = host.ssh_port

        if self.type == 'tcp':
            def creds(credentials, user_data):
                for credential in credentials:
                    if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                        credential[4] = self.login
                        if len(credential[4]) == 0:
                            credential[4] = credential[3]
                    elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
                        credential[4] = self.passwd
                    else:
                        return -1
                return 0

            flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
            auth = [flags, creds, None]
            uri = 'qemu+tcp://%s/system' % self.host
            self.conn = libvirt.openAuth(uri, auth, 0)
        if self.type == 'ssh':
            uri = 'qemu+ssh://%s@%s:%s/system' % (self.login, self.host, self.port)
            self.conn = libvirt.open(uri)
Example #23
0
async def get_conn(hub, connection=None, username=None, password=None):
    '''
    Detects what type of dom this node is and attempts to connect to the
    correct hypervisor via libvirt.

    :param connection: libvirt connection URI, overriding defaults
    :param username: username to connect with, overriding defaults
    :param password: password to connect with, overriding defaults

    '''
    conn_str = connection or hub.OPT['virt']['uri']

    try:
        auth_types = [
            libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT,
            libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE,
            libvirt.VIR_CRED_EXTERNAL
        ]
        conn = libvirt.openAuth(
            conn_str,
            [auth_types,
             __get_request_auth(hub, username, password), None], 0)
    except Exception:  # pylint: disable=broad-except
        raise Exception(
            'Sorry, failed to open a connection to the hypervisor software at {0}'
            .format(conn_str))
    return conn
Example #24
0
    def _try_open(self):
        flags = 0

        vmm = self._open_dev_conn(self.get_uri())
        if vmm:
            return vmm

        if self.readOnly:
            logging.info("Caller requested read only connection")
            flags = libvirt.VIR_CONNECT_RO

        if virtinst.support.support_openauth():
            vmm = libvirt.openAuth(self.get_uri(),
                                   [[libvirt.VIR_CRED_AUTHNAME,
                                     libvirt.VIR_CRED_PASSPHRASE,
                                     libvirt.VIR_CRED_EXTERNAL],
                                    self._do_creds, None],
                                   flags)
        else:
            if flags:
                vmm = libvirt.openReadOnly(self.get_uri())
            else:
                vmm = libvirt.open(self.get_uri())

        return vmm
    def authHelper(self, username, password):
        with TestLibvirtConnAuth.tempxmlfile(self.connXML) as fname:
            magic = 142857

            def authCB(creds, opaque):
                if opaque != magic:
                    return -1

                for cred in creds:
                    if (cred[0] == libvirt.VIR_CRED_AUTHNAME
                            and username is not None):
                        cred[4] = username
                        return 0
                    elif (cred[0] == libvirt.VIR_CRED_PASSPHRASE
                          and password is not None):
                        cred[4] = password
                        return 0
                    return -1
                return 0

            auth = [[
                libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_ECHOPROMPT,
                libvirt.VIR_CRED_REALM, libvirt.VIR_CRED_PASSPHRASE,
                libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_EXTERNAL
            ], authCB, magic]

            return libvirt.openAuth("test://" + fname, auth, 0)
Example #26
0
 def connect(self):
     conn = None
     if self.conn_status is False:
         return False
     if self.host_protocol == 'libssh2':
         self.auth = [[
             libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE
         ], self.request_cred, None]
         if self.host_url == None:
             conn = libvirt.open("qemu:///system")
         else:
             url = "{}://{}/?sshauth=password".format(
                 VIRT_CONN_LIBSSH2, self.host_url)
             conn = libvirt.openAuth(url, self.auth, 0)
     elif self.host_protocol == 'ssh':
         if self.host_url == None:
             conn = libvirt.open("qemu:///system")
         else:
             url = "{}://{}@{}/system?socket=/var/run/libvirt/libvirt-sock&keyfile={}".format(
                 VIRT_CONN_SSH, self.host_username, self.host_url,
                 self.host_key)
             conn = libvirt.open(url)
     elif self.host_protocol == 'qemu':
         conn = libvirt.open("qemu:///system")
     if conn == None:
         logging.error('Connection to hypervisor failed!')
         return False
     else:
         logging.info('Connection succesfull.')
         self.conn = conn
Example #27
0
File: utils.py Project: tinez/lago
def get_libvirt_connection(name):
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            auth_callback, None]
    libvirt_url = config.get('libvirt_url', 'qemu:///system')

    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
    return libvirt.openAuth(libvirt_url, auth)
Example #28
0
    def _virt_event(self, uri):
        auth = [[
            libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_ECHOPROMPT,
            libvirt.VIR_CRED_REALM, libvirt.VIR_CRED_PASSPHRASE,
            libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_EXTERNAL
        ], InstancemonitorManager._connect_auth_cb, None]

        flags = libvirt.VIR_CONNECT_RO

        # Run a background thread with the event loop
        self._vir_event_loop_native_start()

        event_callback_handlers = {
            libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE:
            self._my_domain_event_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_REBOOT:
            self._my_domain_event_reboot_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_RTC_CHANGE:
            self._my_domain_event_rtc_change_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR:
            self._my_domain_event_io_error_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_WATCHDOG:
            self._my_domain_event_watchdog_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_GRAPHICS:
            self._my_domain_event_graphics_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_DISK_CHANGE:
            self._my_domain_event_disk_change_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON:
            self._my_domain_event_io_error_reason_callback,
            libvirt.VIR_DOMAIN_EVENT_ID_CONTROL_ERROR:
            self._my_domain_event_generic_callback
        }
        # Connect to libvirt - If be disconnected, reprocess.
        self.running = True
        while self.running:
            vc = libvirt.openAuth(uri, auth, flags)

            # Event callback settings
            callback_ids = []
            for event, callback in event_callback_handlers.items():
                cid = vc.domainEventRegisterAny(None, event, callback, None)
                callback_ids.append(cid)

            # Connection monitoring.
            vc.setKeepAlive(5, 3)
            while vc.isAlive() == 1 and self.running:
                eventlet.greenthread.sleep(1)

            # If connection between libvirtd was lost,
            # clear callback connection.
            LOG.warning("Libvirt Connection Closed Unexpectedly.")
            for cid in callback_ids:
                try:
                    vc.domainEventDeregisterAny(cid)
                except Exception:
                    pass
            vc.close()
            del vc
            time.sleep(3)
 def openAuth(self, uri, auth, flags = 0):
     try:
         self.conn = libvirt.openAuth(uri, auth, flags)
         return self.conn
     except libvirt.libvirtError, e:
         message = e.get_error_message()
         code = e.get_error_code()
         raise exception.LibvirtAPI(message, code)
Example #30
0
    def connect(self):
        auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], self.request_cred, None]
        conn = libvirt.openAuth(self.uri, auth, 0)

        if conn == None:
            print("cannot connect")
            return 0
        return conn
def open(uri, passwordcb):
    valid_auth_options = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
    authcb = auth_cb
    authcb_data = passwordcb

    conn = libvirt.openAuth(uri, [valid_auth_options, auth_cb, (authcb_data, valid_auth_options)], 0)

    return conn
Example #32
0
def get_libvirt_connection(name, libvirt_url='qemu:///system'):
    if name not in LIBVIRT_CONNECTIONS:
        auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
                auth_callback, None]

        LIBVIRT_CONNECTIONS[name] = libvirt.openAuth(libvirt_url, auth)

    return LIBVIRT_CONNECTIONS[name]
Example #33
0
def get_conn(uri='', username='', password=''):
    """ get connection object from libvirt module
    """
    user_data = [username, password]
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            request_credentials, user_data]
    conn = libvirt.openAuth(uri, auth, 0)
    return conn
Example #34
0
def check_network(network_name):
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], authcb, None]
    uri = "qemu:///system"
    conn = libvirt.openAuth(uri, auth, 0)
    nw = conn.networkLookupByName(network_name)
    if nw.destroy() != 0:
        return 1
    nw.create()
    return 0
Example #35
0
def vm_conn(host_ip, creds):
   try:
      flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
      auth = [flags, creds, None]
      uri = 'qemu+tcp://' + host_ip + '/system'
      conn = libvirt.openAuth(uri, auth, 0)
      return conn
   except:
      print "Not connected"
Example #36
0
def vm_conn(host_ip, creds):
    try:
        flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
        auth = [flags, creds, None]
        uri = 'qemu+tcp://' + host_ip + '/system'
        conn = libvirt.openAuth(uri, auth, 0)
        return conn
    except:
        print "Not connected"
Example #37
0
def delete_network(network_name):
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], authcb, None]
    uri = "qemu:///system"
    conn = libvirt.openAuth(uri, auth, 0)
    nw = conn.networkLookupByName(network_name) 
    if check_network(network_name) == 0:
        nw.destroy()
        nw.undefine()
    return 0
Example #38
0
    def _connect(uri, read_only):
        auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
                'root',
                None]

        if read_only:
            return libvirt.openReadOnly(uri)
        else:
            return libvirt.openAuth(uri, auth, 0)
Example #39
0
def open_connection(uri):
    open_flags = 0
    valid_auth_options = [libvirt.VIR_CRED_AUTHNAME,
                          libvirt.VIR_CRED_PASSPHRASE,
                          libvirt.VIR_CRED_EXTERNAL]
    authcb = do_creds
    authcb_data = None

    return libvirt.openAuth(uri, [valid_auth_options, authcb, authcb_data],
                            open_flags)
Example #40
0
	def vm_conn():
		try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
			auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
			conn = libvirt.openAuth(uri, auth, 0)
			return conn
		except libvirt.libvirtError as e:
			add_error(e)
			return "error"
Example #41
0
 def vm_conn():
     try:
         flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
         auth = [flags, creds, None]
         uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
         conn = libvirt.openAuth(uri, auth, 0)
         return conn
     except libvirt.libvirtError as e:
         add_error(e)
         return "error"
Example #42
0
def get_libvirt_connection(name, libvirt_url='qemu://system'):
    if name not in LIBVIRT_CONNECTIONS:
        auth = [
            [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            auth_callback, None
        ]

        LIBVIRT_CONNECTIONS[name] = libvirt.openAuth(libvirt_url, auth)

    return LIBVIRT_CONNECTIONS[name]
def multiple_thread_block_on_domain_create(params):
    """ spawn multiple threads to create guest simultaneously
        check the return status of calling create API
    """
    logger = params['logger']
    guestos = params.get('guestos')
    arch = params.get('guestarch')
    num = params.get('guestnum')
    xmlstr = params['xml']

    logger.info("the os of guest is %s" % guestos)
    logger.info("the arch of guest is %s" % arch)
    logger.info("the number of guest we are going to install is %s" % num)

    hypervisor = utils.get_hypervisor()
    uri = params['uri']

    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_credentials, None]

    conn = libvirt.openAuth(uri, auth, 0)

    logger.info("the type of hypervisor is %s" % hypervisor)
    logger.debug("the uri to connect is %s" % uri)

    envfile = os.path.join(HOME_PATH, 'global.cfg')
    envparser = env_parser.Envparser(envfile)
    ostree = envparser.get_value("guest", guestos + "_" + arch)
    ks = envparser.get_value("guest", guestos + "_" + arch +
                                "_http_ks")

    # download vmlinuz and initrd.img
    vmlinuzpath = os.path.join(ostree, 'isolinux/vmlinuz')
    initrdpath = os.path.join(ostree, 'isolinux/initrd.img')

    urllib.urlretrieve(vmlinuzpath, '/var/lib/libvirt/boot/vmlinuz')
    urllib.urlretrieve(initrdpath, '/var/lib/libvirt/boot/initrd.img')


    name = "guest"
    start_num = num.split('-')[0]
    end_num = num.split('-')[1]
    thread_pid = []
    for i in range(int(start_num), int(end_num)):
        guestname =  name + str(i)
        thr = guest_install(guestname, guestos, arch, ks, conn, xmlstr, logger)
        thread_pid.append(thr)

    for id in thread_pid:
        id.start()

    for id in thread_pid:
        id.join()

    conn.close()
    return 0
Example #44
0
 def __connect(self):
     """This function establishes a connection to the hypervisor."""
     #create weirdo auth dict
     auth = [
         [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
         self.retrieve_credentials, None
         ]
     #authenticate
     self.SESSION = libvirt.openAuth(self.URI, auth, 0)
     if self.SESSION == None:
         raise SessionException("Unable to establish connection to hypervisor!")
Example #45
0
def multiple_thread_block_on_domain_create(params):
    """ spawn multiple threads to create guest simultaneously
        check the return status of calling create API
    """
    logger = params['logger']
    guestos = params.get('guestos')
    arch = params.get('guestarch')
    num = params.get('guestnum')
    xmlstr = params['xml']

    logger.info("the os of guest is %s" % guestos)
    logger.info("the arch of guest is %s" % arch)
    logger.info("the number of guest we are going to install is %s" % num)

    hypervisor = utils.get_hypervisor()
    uri = params['uri']

    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            request_credentials, None]

    conn = libvirt.openAuth(uri, auth, 0)

    logger.info("the type of hypervisor is %s" % hypervisor)
    logger.debug("the uri to connect is %s" % uri)

    envfile = os.path.join(HOME_PATH, 'global.cfg')
    envparser = env_parser.Envparser(envfile)
    ostree = envparser.get_value("guest", guestos + "_" + arch)
    ks = envparser.get_value("guest", guestos + "_" + arch + "_http_ks")

    # download vmlinuz and initrd.img
    vmlinuzpath = os.path.join(ostree, 'isolinux/vmlinuz')
    initrdpath = os.path.join(ostree, 'isolinux/initrd.img')

    urllib.urlretrieve(vmlinuzpath, '/var/lib/libvirt/boot/vmlinuz')
    urllib.urlretrieve(initrdpath, '/var/lib/libvirt/boot/initrd.img')

    name = "guest"
    start_num = num.split('-')[0]
    end_num = num.split('-')[1]
    thread_pid = []
    for i in range(int(start_num), int(end_num)):
        guestname = name + str(i)
        thr = guest_install(guestname, guestos, arch, ks, conn, xmlstr, logger)
        thread_pid.append(thr)

    for id in thread_pid:
        id.start()

    for id in thread_pid:
        id.join()

    conn.close()
    return 0
Example #46
0
def power_control_virsh(poweraddr, machine, power_change, password):
  login = poweraddr.split('@')
  user.append(login[0])
  test.append(password)
  uri = ("esx://%s?no_verify=1") % login[1]
  auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_cred, None]
  conn = libvirt.openAuth(uri, auth, 0)
  data = conn.lookupByName(machine)
  if power_change == 'on':
	data.create()
  if power_change == 'off':
	data.destroy()
Example #47
0
    def __connect_tls(self):
        flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
        auth = [flags, self.__libvirt_auth_credentials_callback, None]
        uri = 'qemu+tls://%s@%s/system' % (self.login, self.host)

        try:
            self.connection = libvirt.openAuth(uri, auth, 0)
            self.last_error = None

        except libvirtError as e:
            self.last_error = 'Connection Failed: ' + str(e)
            self.connection = None
Example #48
0
File: utils.py Project: nirs/lago
def get_libvirt_connection(name):
    if name not in LIBVIRT_CONNECTIONS:
        auth = [
            [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE],
            auth_callback, None
        ]
        libvirt_url = config.get('libvirt_url', 'qemu:///system')

        libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
        LIBVIRT_CONNECTIONS[name] = libvirt.openAuth(libvirt_url, auth)

    return LIBVIRT_CONNECTIONS[name]
Example #49
0
    def __connect_tcp(self):
        flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
        auth = [flags, self.__libvirt_auth_credentials_callback, None]
        uri = '%s+tcp://%s%s' % (self.hypervisor, self.host, self.path)

        try:
            self.connection = libvirt.openAuth(uri, auth, 0)
            self.last_error = None

        except libvirtError as e:
            self.last_error = 'Connection Failed: ' + str(e)
            self.connection = None
def hypervisor_connecting_test(uri, 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)

    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.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
Example #51
0
def hypervisor_connecting_test(uri, auth_tls, username, password, logger, expected_result):
    """ connect remote server """
    ret = 0
    try:
        if auth_tls == "none":
            conn = libvirt.open(uri)
        elif auth_tls == "sasl":
            user_data = [username, password]
            auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_credentials, user_data]
            conn = libvirt.openAuth(uri, auth, 0)
    except libvirtError, e:
        logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code()))
        ret = 1
 def connect_libvirt(self):
     """
     connect to the libvirt according to parameters in configuration
     """
     if self.need_auth:
         auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], self.libvirt_credential_callback, None]
         self.libvirt_connection = libvirt.openAuth(self.local_libvirt_uri, auth, 0)
     else:
         self.libvirt_connection = libvirt.open(self.local_libvirt_uri)
         if self.libvirt_connection == None:
             self.log.error("unable to connect libvirt")
             sys.exit(-42)
     self.log.info("connected to libvirt uri %s" % self.local_libvirt_uri)
Example #53
0
 def connections(self):
     '''Return an iterator over connections to cluster hosts.'''
     for uri in self.hosts:
         try:
             auth = [
                     [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
                     self.authCallback,
                     uri]
             yield libvirt.openAuth(uri, auth, 0)
         except libvirt.libvirtError, detail:
             print >>sys.stderr, 'ERROR: %s: %s' % (
                     uri, detail.get_error_message())
             continue
Example #54
0
    def libvirt_connect(self):
        open_flags = 0
        valid_auth_options = [
            libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT
        ]
        authcb = None
        authcb_data = None

        uri = "hyperv://%s@%s/?transport=http" % (
            self.hostinfo.get("username"), self.hostinfo.get("api_server")
        )
        self.connection = libvirt.openAuth(
            uri, [valid_auth_options, authcb, authcb_data], open_flags
        )
Example #55
0
 def _get_connection(self):
     # TODO(termie): maybe lazy load after initial check for permissions
     # TODO(termie): check whether we can be disconnected
     if FLAGS.fake_libvirt:
         conn = fakevirt.FakeVirtConnection.instance()
     else:
         auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], 
                 'root',
                 None]
         conn = libvirt.openAuth('qemu:///system', auth, 0)
         if conn == None:
             logging.error('Failed to open connection to the hypervisor')
             sys.exit(1)
     return conn
Example #56
0
def virtual_machine(cmd_args):
    auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_cred, None]
    try:
        conn = libvirt.openAuth(cmd_args.connection, auth, 0)
    except libvirt.libvirtError as e:
        raise RuntimeError("Failed to open connection:\n%s", str(e))

    try:
        dom = conn.lookupByName(cmd_args.name)
    except libvirt.libvirtError:
        raise RuntimeError("Virtual machine %s not found", cmd_args.name)

    snapshots = dom.snapshotListNames()
    if SNAP_NAME in snapshots:
        try:
            snap = dom.snapshotLookupByName(SNAP_NAME)
            snap.delete()
        except libvirt.libvirtError as e:
            raise RuntimeError("Failed to delete snapshot:\n %s", str(e))

    # start the VM
    try:
        dom.create()
    except libvirt.libvirtError as e:
        raise RuntimeError("Failed to start virtual machine:%s", str(e))

    # wait for virtual machine to boot and create snapshot
    time.sleep(120)
    with ssh_connection(cmd_args):
        try:
            snap_xml = "<domainsnapshot><name>%s</name></domainsnapshot>" % SNAP_NAME
            dom.snapshotCreateXML(snap_xml)
        except libvirt.libvirtError as e:
            raise RuntimeError("Failed to create snapshot:\n%s.", str(e))

    yield dom

    # stop the VM
    try:
        dom.destroy()
    except libvirt.libvirtError as e:
        raise RuntimeError("Failed to stop virtual machine:%s", str(e))

    # remove the snapshot
    try:
        snap = dom.snapshotLookupByName(SNAP_NAME)
        snap.delete()
    except libvirt.libvirtError as e:
        raise RuntimeError("Failed to delete snapshot:\n %s", str(e))
Example #57
0
 def _connect(self):
     url = self._get_url()
     self.logger.info("Using libvirt url: %s", url if url else '""')
     try:
         if self.config.password:
             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