Python libvirt.libvirtError() Examples

The following are 30 code examples of libvirt.libvirtError(). 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: qemu_test.py    From see with Apache License 2.0 6 votes vote down vote up
def test_clone_fwdslash(self, os_mock):
        """QEMU Clone no COW."""
        os_mock.return_value = True
        logger = mock.Mock()
        pool = mock.Mock()
        volume = mock.Mock()
        hypervisor = mock.Mock()
        hypervisor.storageVolLookupByPath.side_effect = libvirt.libvirtError('BAM!')
        pool.XMLDesc.return_value = """<pool><target><path>/pool/path</path></target></pool>"""
        volume.XMLDesc.return_value = """<volume><target><path>/path/volume.qcow2</path>""" +\
                                      """</target><capacity>10</capacity></volume>"""
        expected = """<volume type="file"><name>foo</name><uuid>foo</uuid><target>""" +\
                   """<path>/pool/path/foo.qcow2</path><permissions>""" +\
                   """<mode>0644</mode></permissions>""" +\
                   """<format type="qcow2" /></target>""" +\
                   """<capacity>10</capacity></volume>"""
        with self.assertRaises(libvirt.libvirtError) as error:
            qemu.disk_clone(hypervisor, 'foo', pool, {}, '/foo/bar/baz.qcow2', logger)
        self.assertFalse('/' in etree.fromstring(hypervisor.storagePoolDefineXML.call_args[0][0]).find('.//name').text) 
Example #2
Source File: network.py    From see with Apache License 2.0 6 votes vote down vote up
def active_network_addresses(hypervisor):
    """Query libvirt for the already reserved addresses."""
    active = []

    for network in hypervisor.listNetworks():
        try:
            xml = hypervisor.networkLookupByName(network).XMLDesc(0)
        except libvirt.libvirtError:  # network has been destroyed meanwhile
            continue
        else:
            ip_element = etree.fromstring(xml).find('.//ip')
            address = ip_element.get('address')
            netmask = ip_element.get('netmask')

            active.append(ipaddress.IPv4Network(u'/'.join((address, netmask)),
                                                strict=False))

    return active 
Example #3
Source File: lxc_test.py    From see with Apache License 2.0 6 votes vote down vote up
def test_allocate_fail(self, create_mock, libvirt_mock, network_mock):
        """LXC network is destroyed on allocation fail."""
        network = mock.Mock()
        network.name.return_value = 'baz'
        network_mock.lookup = mock.Mock()
        network_mock.create.return_value = network

        resources = lxc.LXCResources('foo', {'domain': 'bar',
                                             'network': 'baz',
                                             'disk': {'image': '/foo/bar'}})
        create_mock.side_effect = libvirt.libvirtError('BOOM')
        with self.assertRaises(libvirt.libvirtError):
            resources.allocate()
        resources.deallocate()

        network_mock.delete.assert_called_with(resources.network) 
Example #4
Source File: lxc.py    From see with Apache License 2.0 6 votes vote down vote up
def domain_delete(domain, logger, filesystem):
    """libvirt domain undefinition.

    @raise: libvirt.libvirtError.

    """
    if domain is not None:
        try:
            if domain.isActive():
                domain.destroy()
        except libvirt.libvirtError:
            logger.exception("Unable to destroy the domain.")
        try:
            domain.undefine()
        except libvirt.libvirtError:
            logger.exception("Unable to undefine the domain.")
        try:
            if filesystem is not None and os.path.exists(filesystem):
                shutil.rmtree(filesystem)
        except Exception:
            logger.exception("Unable to remove the shared folder.") 
Example #5
Source File: lxc.py    From see with Apache License 2.0 6 votes vote down vote up
def domain_create(hypervisor, identifier, configuration, network_name=None):
    """libvirt Domain definition.

    @raise: ConfigError, IOError, libvirt.libvirtError.

    """
    mounts = []

    with open(configuration['configuration']) as config_file:
        domain_config = config_file.read()

    if 'filesystem' in configuration:
        if isinstance(configuration['filesystem'], (list, tuple)):
            for mount in configuration['filesystem']:
                mounts.append(mountpoint(mount, identifier))
        else:
            mounts.append(mountpoint(configuration['filesystem'], identifier))

    xml_config = domain_xml(identifier, domain_config, tuple(mounts), network_name=network_name)

    return hypervisor.defineXML(xml_config) 
Example #6
Source File: vbox.py    From see with Apache License 2.0 6 votes vote down vote up
def domain_delete(domain, logger):
    """libvirt domain undefinition.

    @raise: libvirt.libvirtError.

    """
    if domain is not None:
        try:
            if domain.isActive():
                domain.destroy()
        except libvirt.libvirtError:
            logger.exception("Unable to destroy the domain.")
        try:
            domain.undefine()
        except libvirt.libvirtError:
            try:
                domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)  # domain with snapshots
            except libvirt.libvirtError:
                logger.exception("Unable to undefine the domain.") 
Example #7
Source File: libvirt_pool.py    From see with Apache License 2.0 6 votes vote down vote up
def image(self):
        path = "%s/%s" % (self.configuration.get(
            'storage_pool_path').rstrip('/'), self.name.lstrip('/'))

        if not os.path.exists(path):
            raise FileNotFoundError(path)

        hypervisor = libvirt.open(
            self.configuration.get('hypervisor', 'qemu:///system'))

        try:
            volume = hypervisor.storageVolLookupByPath(path)
            return volume.path()
        except libvirt.libvirtError:
            pool = hypervisor.storagePoolDefineXML(POOL_CONFIG_XML.format(
                self.configuration.get('storage_pool_path')))
            pool.setAutostart(True)
            pool.create()
            pool.refresh()
            return pool.storageVolLookupByName(self.name).path() 
Example #8
Source File: network_test.py    From see with Apache License 2.0 6 votes vote down vote up
def test_create_too_many_attempts(self):
        """NETWORK RuntimeError is raised if too many fails to create a network."""
        xml = '<network><forward mode="nat"/></network>'
        network.MAX_ATTEMPTS = 3
        hypervisor = mock.Mock()
        hypervisor.listNetworks.return_value = []
        hypervisor.networkCreateXML.side_effect = libvirt.libvirtError('BOOM')
        configuration = {'configuration': 'bar',
                         'dynamic_address': {'ipv4': '10.0.0.0',
                                             'prefix': 16,
                                             'subnet_prefix': 24}}

        with mock.patch('see.context.resources.network.open',
                        mock.mock_open(read_data=xml), create=True):
            try:
                network.create(hypervisor, 'foo', configuration)
            except RuntimeError as error:
                self.assertEqual(
                    error.args,
                    ("Exceeded failed attempts (3) to get IP address.",
                     "Last error: BOOM")) 
Example #9
Source File: virt.py    From dwarf with Apache License 2.0 6 votes vote down vote up
def create_network(self):
        """
        Create the network
        """
        LOG.info('create_network()')

        self._connect()
        try:
            # Check if the network already exists
            net = self.libvirt.networkLookupByName(CONF.libvirt_network_name)
        except libvirt.libvirtError as e:
            if e.get_error_code() != libvirt.VIR_ERR_NO_NETWORK:
                # Unexpected error
                raise
            # Define the network
            xml = _create_net_xml()
            net = self.libvirt.networkDefineXML(xml)

        # Configure the network to automatically start on host boot
        net.setAutostart(1)

        # Create (start) the network
        if net.isActive() == 0:
            net.create() 
Example #10
Source File: vbmc.py    From virtualbmc with Apache License 2.0 6 votes vote down vote up
def get_power_state(self):
        LOG.debug('Get power state called for domain %(domain)s',
                  {'domain': 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:
            msg = ('Error getting the power state of domain %(domain)s. '
                   'Error: %(error)s' % {'domain': self.domain_name,
                                         'error': e})
            LOG.error(msg)
            raise exception.VirtualBMCError(message=msg)

        return POWEROFF 
Example #11
Source File: qemu_test.py    From see with Apache License 2.0 6 votes vote down vote up
def test_allocate_fail(self, _, create_mock, libvirt_mock, network_mock):
        """QEMU network is destroyed on allocation fail."""
        network = mock.Mock()
        network.name.return_value = 'baz'
        network_mock.lookup = mock.Mock()
        network_mock.create.return_value = network

        resources = qemu.QEMUResources('foo', {'domain': 'bar',
                                               'network': 'baz',
                                               'disk': {'image': '/foo/bar'}})
        create_mock.side_effect = libvirt.libvirtError('BOOM')
        with self.assertRaises(libvirt.libvirtError):
            resources.allocate()

        resources.deallocate()

        network_mock.delete.assert_called_with(resources.network) 
Example #12
Source File: app.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def register_event_handlers(self, old_connection=None):
        """Register libvirt event handlers, which will translate libvirt
        events into qubes.events. This function should be called only in
        'qubesd' process and only when mainloop has been already set.
        """
        if old_connection:
            try:
                old_connection.domainEventDeregisterAny(
                    self._domain_event_callback_id)
            except libvirt.libvirtError:
                # the connection is probably in a bad state; but call the above
                # anyway to cleanup the client structures
                pass
        self._domain_event_callback_id = (
            self.vmm.libvirt_conn.domainEventRegisterAny(
                None,  # any domain
                libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
                self._domain_event_callback,
                None)) 
Example #13
Source File: app.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __delitem__(self, key):
        vm = self[key]
        if not vm.is_halted():
            raise qubes.exc.QubesVMNotHaltedError(vm)
        self.app.fire_event('domain-pre-delete', pre_event=True, vm=vm)
        try:
            if vm.libvirt_domain:
                vm.libvirt_domain.undefine()
            # pylint: disable=protected-access
            vm._libvirt_domain = None
        except libvirt.libvirtError as e:
            if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
                # already undefined
                pass
        del self._dict[vm.qid]
        self.app.fire_event('domain-delete', vm=vm) 
Example #14
Source File: app.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __getattr__(self, attrname):
        attr = getattr(self._conn, attrname)
        if not isinstance(attr, collections.abc.Callable):
            return attr
        if attrname == 'close':
            return attr

        @functools.wraps(attr)
        def wrapper(*args, **kwargs):
            try:
                return self._wrap_domain(attr(*args, **kwargs))
            except libvirt.libvirtError:
                if self._reconnect_if_dead():
                    return self._wrap_domain(
                        getattr(self._conn, attrname)(*args, **kwargs))
                raise

        return wrapper 
Example #15
Source File: LibvirtClient.py    From katprep with GNU General Public License v3.0 6 votes vote down vote up
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:
            if "no domain with name" in err.message.lower():
                #snapshot not found
                raise EmptySetException("No snapshots found")
            else:
                self.LOGGER.error("Unable to determine snapshot: '{}'".format(err))
                raise SessionException(err) 
Example #16
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 #17
Source File: LibvirtClient.py    From katprep with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #18
Source File: factory.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def initialise(self):
        """Delete the default libvirt network if it exists."""
        libvirt = self.po__get_registered_object('libvirt_connector').get_connection()
        try:
            default = libvirt.networkLookupByName(DEFAULT_LIBVIRT_NETWORK_NAME)
            try:
                default.destroy()
            except Exception:
                pass

            try:
                default.undefine()
            except Exception:
                pass

        except libvirtError:
            # Fail silently (ish)
            Syslogger.logger().info(
                'Failed to find default network (%s)' % DEFAULT_LIBVIRT_NETWORK_NAME
            ) 
Example #19
Source File: list_all_children.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def list_all_children(params):
    logger = params['logger']
    guestname = params['guestname']
    checkpoint_name = params['checkpoint_name']
    flag = utils.parse_flags(params)

    if not utils.version_compare('libvirt-python', 5, 6, 0, logger):
        logger.info("Current libvirt-python don't support listAllChildren().")
        return 0

    logger.info("Checkpoint name: %s" % checkpoint_name)
    logger.info("flag: %s" % flag)

    try:
        conn = libvirt.open()
        dom = conn.lookupByName(guestname)
        cp = dom.checkpointLookupByName(checkpoint_name)
        cp_lists = cp.listAllChildren(flag)
        for cp_list in cp_lists:
            logger.info("Checkpoint children list: %s" % cp_list.getName())
    except libvirtError as err:
        logger.error("API error message: %s" % err.get_error_message())
        return 1

    return 0 
Example #20
Source File: checkpoint_lookup.py    From libvirt-test-API with GNU General Public License v2.0 6 votes vote down vote up
def checkpoint_lookup(params):
    logger = params['logger']
    guestname = params['guestname']
    checkpoint_name = params.get('checkpoint_name', None)

    logger.info("Checkpoint name: %s" % checkpoint_name)
    if not utils.version_compare('libvirt-python', 5, 6, 0, logger):
        logger.info("Current libvirt-python don't support checkpointLookupByName().")
        return 0

    try:
        conn = libvirt.open()
        dom = conn.lookupByName(guestname)
        cp = dom.checkpointLookupByName(checkpoint_name, 0)
    except libvirtError as err:
        logger.error("API error message: %s" % err.get_error_message())
        return 1

    # check checkpoint
    if cp.getName() == checkpoint_name:
        logger.info("PASS: check checkpoint name successful.")
        return 0
    else:
        logger.error("FAIL: check checkpoint name failed.")
        return 1 
Example #21
Source File: vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def pulse_diag(self):
        LOG.debug('Power diag called for domain %(domain)s',
                  {'domain': 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.injectNMI()
        except libvirt.libvirtError as e:
            LOG.error('Error powering diag the domain %(domain)s. '
                      'Error: %(error)s', {'domain': self.domain_name,
                                           'error': e})
            # Command failed, but let client to retry
            return IPMI_COMMAND_NODE_BUSY 
Example #22
Source File: vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def power_on(self):
        LOG.debug('Power on called for domain %(domain)s',
                  {'domain': 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})
            # Command failed, but let client to retry
            return IPMI_COMMAND_NODE_BUSY 
Example #23
Source File: vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def power_shutdown(self):
        LOG.debug('Soft power off called for domain %(domain)s',
                  {'domain': 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.shutdown()
        except libvirt.libvirtError as e:
            LOG.error('Error soft powering off the domain %(domain)s. '
                      'Error: %(error)s', {'domain': self.domain_name,
                                           'error': e})
            # Command failed, but let client to retry
            return IPMI_COMMAND_NODE_BUSY 
Example #24
Source File: vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def power_reset(self):
        LOG.debug('Power reset called for domain %(domain)s',
                  {'domain': 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.reset()
        except libvirt.libvirtError as e:
            LOG.error('Error reseting the domain %(domain)s. '
                      'Error: %(error)s', {'domain': self.domain_name,
                                           'error': e})
            # Command not supported in present state
            return IPMI_COMMAND_NODE_BUSY 
Example #25
Source File: vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
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:
            # Invalid data field in request
            return IPMI_INVALID_DATA

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

                # Remove all "boot" element under "devices"
                # They are mutually exclusive with "os/boot"
                for device_element in tree.findall('devices/*'):
                    self._remove_boot_elements(device_element)

                for os_element in tree.findall('os'):
                    # Remove all "boot" elements under "os"
                    self._remove_boot_elements(os_element)

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

                conn.defineXML(ET.tostring(tree, encoding="unicode"))
        except libvirt.libvirtError:
            LOG.error('Failed setting the boot device  %(bootdev)s for '
                      'domain %(domain)s', {'bootdev': device,
                                            'domain': self.domain_name})
            # Command failed, but let client to retry
            return IPMI_COMMAND_NODE_BUSY 
Example #26
Source File: utils.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def get_libvirt_domain(conn, domain):
    try:
        return conn.lookupByName(domain)
    except libvirt.libvirtError:
        raise exception.DomainNotFound(domain=domain) 
Example #27
Source File: qemu.py    From see with Apache License 2.0 5 votes vote down vote up
def pool_lookup(hypervisor, disk_path):
    """Storage pool lookup.

    Retrieves the the virStoragepool which contains the disk at the given path.

    """
    try:
        volume = hypervisor.storageVolLookupByPath(disk_path)

        return volume.storagePoolLookupByVolume()
    except libvirt.libvirtError:
        return None 
Example #28
Source File: factory.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def pre_check_network(self, name, interface):
        """Perform pre-limiary checks on node before determining
           that a network can be added."""
        self.po__get_registered_object('auth').assert_user_type('ConnectionUser', 'ClusterUser')
        # Ensure that the physical interface exists
        self.assert_interface_exists(interface)

        # Ensure that there are no interfaces present on the MCVirt instance
        # that match the network
        if self.check_exists(name):
            raise NetworkAlreadyExistsException('Network already exists on node: %s %s' %
                                                (name, get_hostname()))

        # Ensure that there is not already a network with the same name defined in
        # libvirt
        try:
            self.po__get_registered_object(
                'libvirt_connector'
            ).get_connection().networkLookupByName(name)

            # If the libvirt connect did not throw an error that
            # the network does not exist, raise an exception
            # as the network must be pressent
            # @TODO: do this more nicely. Get list of networks and
            # assert that it's not in the list
            raise NetworkAlreadyExistsException(
                'Network already defined in libvirt on node: %s %s' %
                (name, get_hostname()))
        except libvirtError:
            pass 
Example #29
Source File: test_vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def test_set_boot_device_error(self, mock_libvirt_domain,
                                   mock_libvirt_open):
        mock_libvirt_domain.side_effect = libvirt.libvirtError('boom')
        ret = self.vbmc.set_boot_device('network')
        self.assertEqual(0xc0, ret)
        self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open) 
Example #30
Source File: test_vbmc.py    From virtualbmc with Apache License 2.0 5 votes vote down vote up
def test_get_power_state_error(self, mock_libvirt_domain,
                                   mock_libvirt_open):
        mock_libvirt_domain.side_effect = libvirt.libvirtError('boom')
        self.assertRaises(exception.VirtualBMCError, self.vbmc.get_power_state)
        self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open,
                                   readonly=True)