Example #1
0
  def testNonexistentDomain(self):
    """Test that loadDomainState can deal with nonexistent domains."""
    doms = {}
    for i in xrange(6):
      doms[('debmarshal-%d' % i, 'qemu')] = 500

    self.mox.StubOutWithMock(utils, '_clearLibvirtError')
    utils._clearLibvirtError()

    self.mox.StubOutWithMock(utils, 'loadState')
    utils.loadState('debmarshal-domains').AndReturn(dict(doms))

    self.mox.StubOutWithMock(hypervisors.qemu.QEMU, 'open')
    qemu_con = self.mox.CreateMock(libvirt.virConnect)
    hypervisors.qemu.QEMU.open().AndReturn(qemu_con)

    qemu_con.lookupByName('debmarshal-0').InAnyOrder()
    qemu_con.lookupByName('debmarshal-1').InAnyOrder()
    qemu_con.lookupByName('debmarshal-2').InAnyOrder().AndRaise(
        libvirt.libvirtError("Domain doesn't exist"))
    qemu_con.lookupByName('debmarshal-3').InAnyOrder()
    qemu_con.lookupByName('debmarshal-4').InAnyOrder().AndRaise(
        libvirt.libvirtError("Domain doesn't exist"))
    qemu_con.lookupByName('debmarshal-5').InAnyOrder()

    self.mox.ReplayAll()

    del doms[('debmarshal-2', 'qemu')]
    del doms[('debmarshal-4', 'qemu')]

    self.assertEqual(domains.loadDomainState(), doms)
Example #2
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 #3
0
    def createXMLWithType(self, xml, val, dom_tp):
        if self.vmClass is None:
            raise libvirt.libvirtError("%r can't create any domain" % \
                               self.__class__)

        if dom_tp != self.vmClass.domain_type:
            raise libvirt.libvirtError("%r can't create domaint type %r" % \
                               (self.__class__, dom_tp))
        
        return self.createXML(xml, val)
Example #4
0
 def backupBegin(self, backup_xml, checkpoint_xml, flags=None):
     if self.backing_up:
         raise libvirt.libvirtError("backup already running for that VM")
     if backup_xml and not isinstance(backup_xml, str):
         raise libvirt.libvirtError(
             "wrong argument, backup_xml should be string")
     if checkpoint_xml and not isinstance(checkpoint_xml, str):
         raise libvirt.libvirtError(
             "wrong argument, checkpoint_xml should be string")
     self.backing_up = True
     return 0
Example #5
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 #6
0
 def _create_fake_connection(self):
     connect = mock.Mock()
     connect.networkLookupByName = mock.Mock(
         side_effect=libvirt.libvirtError("networkLookupByName"))
     connect.lookupByName = mock.Mock(
         side_effect=libvirt.libvirtError("lookupByName"))
     connect.storagePoolLookupByName = mock.Mock(
         side_effect=libvirt.libvirtError("storagePoolLookupByName"))
     connect.networkCreateXML = mock.Mock(return_value=None)
     connect.defineXML = mock.Mock(return_value=None)
     connect.storagePoolDefineXML = mock.Mock(return_value=None)
     connect.close = mock.Mock(return_value=None)
     connect.newStream = mock.Mock(return_value=mock.Mock())
     return connect
    def test_snapshot_apply(self):
        self._test_common_backups(domain_tasks.snapshot_apply,
                                  "No servers for restore.")

        # apply snapshot
        _ctx = self._create_ctx()
        _ctx.instance.runtime_properties['resource_id'] = 'resource'

        snapshot = mock.Mock()
        snapshot.getName = mock.Mock(return_value="snapshot!")
        domain = mock.Mock()
        domain.revertToSnapshot = mock.Mock()
        domain.snapshotLookupByName = mock.Mock(return_value=snapshot)
        domain.name = mock.Mock(return_value="domain_name")
        domain.snapshotCreateXML = mock.Mock(
            side_effect=libvirt.libvirtError("e"))

        connect = self._create_fake_connection()
        connect.lookupByName = mock.Mock(return_value=domain)
        connect.restore = mock.Mock()
        with mock.patch("cloudify_libvirt.domain_tasks.libvirt.open",
                        mock.Mock(return_value=connect)):
            domain_tasks.snapshot_apply(ctx=_ctx,
                                        snapshot_name='snapshot_name',
                                        snapshot_incremental=True)
        domain.revertToSnapshot.assert_called_with(snapshot)

        # raw dump
        self._check_apply_backups(_ctx, connect, domain, True)

        # check fast backup
        self._check_apply_backups(_ctx, connect, domain, False)
Example #8
0
 def test_power_shutdown_error(self, mock_libvirt_domain,
                               mock_libvirt_open):
     mock_libvirt_domain.side_effect = libvirt.libvirtError('boom')
     ret = self.vbmc.power_shutdown()
     self.assertEqual(0xd5, ret)
     mock_libvirt_domain.return_value.shutdown.assert_not_called()
     self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open)
Example #9
0
 def test_power_shutdown_error(self, mock_libvirt_domain,
                               mock_libvirt_open):
     mock_libvirt_domain.side_effect = libvirt.libvirtError('boom')
     ret = self.vbmc.power_shutdown()
     self.assertEqual(0xC0, ret)
     mock_libvirt_domain.return_value.shutdown.assert_not_called()
     self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open)
Example #10
0
 def metadata(self, flags, url):
     # Note(xiexianbin): vm not create by nova-compute don't have metadata
     # elements like: '<nova:instance
     #  xmlns:nova="http://openstack.org/xmlns/libvirt/nova/1.0">'
     # When invoke get metadata method, raise libvirtError.
     raise libvirt.libvirtError(
         "metadata not found: Requested metadata element is not present")
Example #11
0
def qemuAttach(conn, pid_value, flags):
    """This API is QEMU specific, so it will only work with hypervisor
    connections to the QEMU driver.
    
    This API will attach to an externally launched QEMU process
    identified by @pid. There are several requirements to successfully
    attach to an external QEMU process:
    
      - It must have been started with a monitor socket using the UNIX
        domain socket protocol.
      - No device hotplug/unplug, or other configuration changes can
        have been made via the monitor since it started.
      - The '-name' and '-uuid' arguments should have been set (not
        mandatory, but strongly recommended)
    
    To date, the only platforms we know of where pid_t is larger than
    unsigned int (64-bit Windows) also lack UNIX sockets, so the choice
    of @pid_value as an unsigned int should not present any difficulties.
    
    If successful, then the guest will appear in the list of running
    domains for this connection, and other APIs should operate
    normally (provided the above requirements were honored). """
    ret = libvirtmod_qemu.virDomainQemuAttach(conn._o, pid_value, flags)
    if ret is None:
        raise libvirt.libvirtError("virDomainQemuAttach() failed")
    __tmp = virDomain(conn, _obj=ret)
    return __tmp
Example #12
0
    def filterDefineXMLMock(self, xml):
        class FakeNWFilterInternal:
            def __init__(self, parent, name, u, xml):
                self.name = name
                self.uuid = u
                self.parent = parent
                self.xml = xml

            def XMLDesc(self, flags):
                return self.xml

            def undefine(self):
                del self.parent.filters[self.name]

        tree = etree.fromstring(xml)
        name = tree.get('name')
        u = tree.find('uuid')
        if u is None:
            u = uuid.uuid4().hex
        else:
            u = u.text
        if name not in self.filters:
            self.filters[name] = FakeNWFilterInternal(self, name, u, xml)
        else:
            if self.filters[name].uuid != u:
                raise libvirt.libvirtError(
                    "Mismatching name '%s' with uuid '%s' vs '%s'" %
                    (name, self.filters[name].uuid, u))
            self.filters[name].xml = xml
        return True
Example #13
0
 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)
Example #14
0
 def lookupByUUIDString(self, uuid):
     if uuid in self.known_uuids:
         return vmfakecon.FakeRunningVm(uuid)
     else:
         error = libvirt.libvirtError("error")
         error.err = [self.error]
         raise error
 def test_create_vm_storage_libvirt_error(self, mock_libvirt_open):
     # setup mock
     conn = mock_libvirt_open.return_value
     pool = conn.storagePoolLookupByName.return_value
     pool.storageVolLookupByName.side_effect = libvirt.libvirtError('ermsg')
     # execute
     assert_raises(libvirt.libvirtError, create_vm_storage, 'test')
Example #16
0
 def test_get_power_state_error(self, mock_libvirt_domain,
                                mock_libvirt_open):
     mock_libvirt_domain.side_effect = libvirt.libvirtError('boom')
     ret = self.vbmc.get_power_state()
     self.assertEqual(0xd5, ret)
     self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open,
                                readonly=True)
Example #17
0
def qemuAttach(conn, pid_value, flags):
    """This API is QEMU specific, so it will only work with hypervisor
    connections to the QEMU driver.
    
    This API will attach to an externally launched QEMU process
    identified by @pid. There are several requirements to successfully
    attach to an external QEMU process:
    
      - It must have been started with a monitor socket using the UNIX
        domain socket protocol.
      - No device hotplug/unplug, or other configuration changes can
        have been made via the monitor since it started.
      - The '-name' and '-uuid' arguments should have been set (not
        mandatory, but strongly recommended)
    
    To date, the only platforms we know of where pid_t is larger than
    unsigned int (64-bit Windows) also lack UNIX sockets, so the choice
    of @pid_value as an unsigned int should not present any difficulties.
    
    If successful, then the guest will appear in the list of running
    domains for this connection, and other APIs should operate
    normally (provided the above requirements were honored). """
    ret = libvirtmod_qemu.virDomainQemuAttach(conn._o, pid_value, flags)
    if ret is None:
        raise libvirt.libvirtError('virDomainQemuAttach() failed')
    __tmp = libvirt.virDomain(conn, _obj=ret)
    return __tmp
Example #18
0
def qemuAgentCommand(domain, cmd, timeout, flags):
    """Send a Guest Agent command to domain """
    ret = libvirtmod_qemu.virDomainQemuAgentCommand(domain._o, cmd, timeout,
                                                    flags)
    if ret is None:
        raise libvirt.libvirtError('virDomainQemuAgentCommand() failed')
    return ret
Example #19
0
def qemuMonitorEventRegister(conn: libvirt.virConnect,
                             dom: libvirt.virDomain,
                             event: str,
                             cb: Callable[[
                                 libvirt.virConnect, libvirt.
                                 virDomain, str, int, int, str, libvirt._T
                             ], None],
                             opaque: libvirt._T,
                             flags: int = 0) -> int:
    """Adds a qemu monitor event callback. Registering for a monitor
       callback will enable delivery of the events"""
    if not hasattr(conn, 'qemuMonitorEventCallbackID'):
        conn.qemuMonitorEventCallbackID = {}  # type: ignore
    cbData = {"cb": cb, "conn": conn, "opaque": opaque}
    if dom is None:
        ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(
            conn._o, None, event, cbData, flags)
    else:
        ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(
            conn._o, dom._o, event, cbData, flags)
    if ret == -1:
        raise libvirt.libvirtError(
            'virConnectDomainQemuMonitorEventRegister() failed')
    conn.qemuMonitorEventCallbackID[ret] = opaque  # type: ignore
    return ret
Example #20
0
 def metadata(self, flags, url):
     # Note(xiexianbin): vm not create by nova-compute don't have metadata
     # elements like: '<nova:instance
     #  xmlns:nova="http://openstack.org/xmlns/libvirt/nova/1.0">'
     # When invoke get metadata method, raise libvirtError.
     raise libvirt.libvirtError(
         "metadata not found: Requested metadata element is not present")
Example #21
0
def _lookupNodeName(conn, name):
    try:
        nodedev = conn.nodeDeviceLookupByName(name)
    except libvirt.libvirtError, e:
        raise libvirt.libvirtError(
            _("Did not find node device '%s': %s" %
            (name, str(e))))
Example #22
0
    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 #23
0
    def filterDefineXMLMock(self, xml):
        class FakeNWFilterInternal:
            def __init__(self, parent, name, u, xml):
                self.name = name
                self.uuid = u
                self.parent = parent
                self.xml = xml

            def XMLDesc(self, flags):
                return self.xml

            def undefine(self):
                del self.parent.filters[self.name]

        tree = etree.fromstring(xml)
        name = tree.get('name')
        u = tree.find('uuid')
        if u is None:
            u = uuid.uuid4().hex
        else:
            u = u.text
        if name not in self.filters:
            self.filters[name] = FakeNWFilterInternal(self, name, u, xml)
        else:
            if self.filters[name].uuid != u:
                raise libvirt.libvirtError(
                    "Mismatching name '%s' with uuid '%s' vs '%s'"
                    % (name, self.filters[name].uuid, u))
            self.filters[name].xml = xml
        return True
Example #24
0
    def fromVirDomain(cls, domain):
        domxml = etree.fromstring(domain.XMLDesc(0))

        find = domxml.find
        findall = domxml.findall
        find_text = lambda path : find(path).text.strip()
        
        domain.__class__ = cls
        
        if domain.__class__ is libvirt.virDomain:
            raise libvirt.libvirtError("Domain type %r isn't supported by libvirtex" %
                               domain)
            
        domain.etree = domxml
        
        domain.memory = int(find_text('memory'))
        domain.vcpu = int(find_text('vcpu'))
        
        domain.devices = []

        for device_class in [ETHNetworkDevice, ETHBridgedDevice,
                       HDDBlockDevice, HDDFileDevice, FileSystemDevice]:
            domain.devices.extend(device_class.fromxml(findall))

        domain.name = find_text('name')
        domain.persistent = True
        
        return domain
Example #25
0
 def lookupByName(self, domain_name):
     """
     :return: MockedDomain with UUID_1
     """
     if domain_name == DOMAIN_NAME_1:
         return MockedDomain(UUID_1)
     raise libvirtError('')
Example #26
0
    def makeXML(cls, name, memory, vcpu, *devices):
        
        if cls.domain_type is None:
            raise libvirt.libvirtError("%r can't be instanciated - no domain type" \
                                % cls)
            
        
        cfg = DomainConfig(name, memory, vcpu, devices)
        
        root = XMLBuilder('domain', type=cls.domain_type)

        cls.commonFields(root, cfg)
                    
        with root.os:
            cls.generateOS(root, cfg)
        
        root.clock(sync='localtime')
        
        cls.powerFeatures(root, cfg)
        
        with root.devices:
            cls.emulator(root, cfg)
            
            for dev in devices: 
                dev.toxml(root)
            
            cls.commonDevices(root, cfg)

        return root
Example #27
0
    def test_image_not_in_pool(self, os_mock, libvirt_mock):
        volume = mock.MagicMock()
        volume.path.return_value = '/nowhere/foo/bar'
        pool = mock.MagicMock()
        pool.storageVolLookupByName.return_value = volume
        hypervisor = mock.MagicMock()
        hypervisor.storagePoolDefineXML.return_value = pool
        import see
        hypervisor.storageVolLookupByPath.side_effect = libvirt.libvirtError('BOOM')
        libvirt_mock.return_value = hypervisor
        os_mock.exists.return_value = True

        resources = Resources('foo', self.config)
        expected_image_path = '%s%s' % (
            self.config['disk']['image'][
                'provider_configuration']['storage_pool_path'],
            self.config['disk']['image']['name'])

        assert expected_image_path == resources.provider_image

        libvirt_mock.assert_called_with('baz')
        pool.assert_has_calls([
            mock.call.setAutostart(True),
            mock.call.create(),
            mock.call.refresh(),
            mock.call.storageVolLookupByName(self.config['disk']['image']['name'])
        ])
Example #28
0
    def metadata(self, type, uri, flags):
        self._failIfRequested()

        if not self._metadata:
            e = libvirt.libvirtError("No metadata")
            e.err = [libvirt.VIR_ERR_NO_DOMAIN_METADATA]
            raise e
        return self._metadata
Example #29
0
 def test_delete_destroy_error(self):
     """Domain destroy raises error."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = True
     domain.destroy.side_effect = libvirt.libvirtError("BOOM")
     vbox.domain_delete(domain, logger)
     self.assertTrue(domain.undefine.called)
Example #30
0
 def test_delete_destroy_error(self):
     """Domain destroy raises error."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = True
     domain.destroy.side_effect = libvirt.libvirtError("BOOM")
     lxc.domain_delete(domain, logger, None)
     self.assertTrue(domain.undefine.called)
Example #31
0
 def test_delete_undefine_error(self, os_mock):
     """Domain undefine raises error."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = False
     domain.undefine.side_effect = libvirt.libvirtError("BOOM")
     lxc.domain_delete(domain, logger, '/foo/bar/baz')
     self.assertTrue(os_mock.called)
Example #32
0
 def test_clone_error(self):
     """QEMU RuntimeError is raised if the base image is not contained within a libvirt Pool."""
     pool = mock.Mock()
     hypervisor = mock.Mock()
     hypervisor.storageVolLookupByPath.side_effect = libvirt.libvirtError('BOOM')
     with self.assertRaises(RuntimeError) as error:
         qemu.disk_clone(hypervisor, 'foo', pool, {'image': '/foo/bar/baz.qcow2', 'clone': {}})
         self.assertEqual(str(error), "/foo/bar/baz.qcow2 disk must be contained in a libvirt storage pool.")
Example #33
0
    def metadata(self, type, uri, flags):
        self._failIfRequested()

        if not self._metadata:
            e = libvirt.libvirtError("No metadata")
            e.err = [libvirt.VIR_ERR_NO_DOMAIN_METADATA]
            raise e
        return self._metadata
Example #34
0
 def storagePoolLookupByName(self, path):
     """Mock of libvirt.virConnect.storagePoolLookupByName()"""
     try:
         return next((pool for pool in self.pools + self.defined_pools \
                           if pool.path == path))
     except StopIteration:
         raise libvirtError("Storage pool not found: no pool with matching" \
                            "name '{path}'".format(path=path))
Example #35
0
    def backupBegin(self, backup_xml, checkpoint_xml, flags=None):
        if self.backing_up:
            raise libvirt.libvirtError("backup already running for that VM")

        self.input_checkpoint_xml = checkpoint_xml
        self.backup_xml = self._generate_backup_xml(backup_xml)
        self.backing_up = True
        return 0
Example #36
0
 def test_delete_undefine_error(self, os_mock):
     """Domain undefine raises error."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = False
     domain.undefine.side_effect = libvirt.libvirtError("BOOM")
     lxc.domain_delete(domain, logger, '/foo/bar/baz')
     self.assertTrue(os_mock.called)
Example #37
0
 def test_create_no_xml_too_many_attempts(self):
     """RuntimeError is raised if too many attempt to create a network are made."""
     hypervisor = mock.Mock()
     hypervisor.listNetworks.return_value = []
     hypervisor.networkCreateXML.side_effect = libvirt.libvirtError('BOOM')
     with self.assertRaises(RuntimeError) as error:
         network.create(hypervisor, 'foo', {}, max_attempts=1)
         self.assertEqual(str(error), "Too many attempts (1) to get a valid IP address.")
Example #38
0
 def test_delete_undefine_snapshots(self):
     """Domain undefine with snapshots metadata."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = False
     domain.undefine.side_effect = libvirt.libvirtError("BOOM")
     vbox.domain_delete(domain, logger)
     domain.undefineFlags.assert_called_with(libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)
Example #39
0
 def test_clean_vms_skip_vol(self, mock_libvirt):
     ml = mock_libvirt.return_value
     pool = ml.storagePoolLookupByName.return_value
     pool.storageVolLookupByName.side_effect = libvirt.libvirtError('msg')
     uc = MagicMock()
     uc.name.return_value = 'undercloud'
     ml.listAllDomains.return_value = [uc]
     clean.clean_vms()
Example #40
0
    def networkLookupByName(self, name):
        """Mock of libvirt.virConnect.networkLookupByName()"""

        try:
            return next((net for net in self.networks + self.defined_networks \
                             if net.name == name))
        except StopIteration:
            raise libvirtError("Network not found: no network with matching" \
                               "name '{name}'".format(name=name))
Example #41
0
    def storageVolLookupByName(self, name):
        """Mock of libvirt.virStoragePool.storageVolLookupByName()"""

        try:
            return next((vol for vol in self.volumes \
                             if vol == name))
        except StopIteration:
            raise libvirtError("Storage volume not found: no storage vol " \
                               "with matching name '{name}'".format(name=name))
Example #42
0
 def test_create_no_xml_too_many_attempts(self):
     """RuntimeError is raised if too many attempt to create a network are made."""
     hypervisor = mock.Mock()
     hypervisor.listNetworks.return_value = []
     hypervisor.networkCreateXML.side_effect = libvirt.libvirtError('BOOM')
     with self.assertRaises(RuntimeError) as error:
         network.create(hypervisor, 'foo', {}, max_attempts=1)
         self.assertEqual(
             str(error), "Too many attempts (1) to get a valid IP address.")
Example #43
0
 def test_delete_pool_folder_error(self, os_mock, rm_mock):
     """QEMU Pool's folder is deleted in case of error."""
     pool = mock.MagicMock()
     logger = mock.Mock()
     os_mock.return_value = True
     pool.XMLDesc.return_value = """<pool><path>/foo/bar/baz</path></pool>"""
     pool.destroy.side_effect = libvirt.libvirtError('BOOM')
     qemu.pool_delete(pool, logger)
     rm_mock.assert_called_with('/foo/bar/baz')
Example #44
0
def lxcEnterCGroup(domain, flags):
    """This API is LXC specific, so it will only work with hypervisor
    connections to the LXC driver.
    
    Attaches the process to the control cgroups associated
    with the container @domain. """
    ret = libvirtmod_lxc.virDomainLxcEnterCGroup(domain._o, flags)
    if ret is None: raise libvirt.libvirtError('virDomainLxcEnterCGroup() failed')
    return ret
Example #45
0
 def test_stream_callback_error(self, mock_libvirt_domain,
                                mock_libvirt_open):
     mock_stream = mock.MagicMock()
     mock_stream.recv.side_effect = libvirt.libvirtError('boom')
     mock_sol = mock.MagicMock()
     self.vbmc.sol = mock_sol
     self.vbmc._stream = mock_stream
     vbmc.stream_callback(None, None, self.vbmc)
     mock_sol.send_data.assert_not_called()
Example #46
0
 def test_delete_undefine_snapshots(self):
     """Domain undefine with snapshots metadata."""
     domain = mock.Mock()
     logger = mock.Mock()
     domain.isActive.return_value = False
     domain.undefine.side_effect = libvirt.libvirtError("BOOM")
     vbox.domain_delete(domain, logger)
     domain.undefineFlags.assert_called_with(
         libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)
 def libvirt_conn(self):
     if self.offline_mode:
         import libvirt
         raise libvirt.libvirtError('phony error')
     else:
         libvirt_mock = unittest.mock.Mock()
         vm_mock = libvirt_mock.lookupByUUID.return_value
         vm_mock.isActive.return_value = False
         return libvirt_mock
Example #48
0
    def lookupByID(self, id):
        """Mock of libvirt.virConnect.lookupByID()"""

        try:
            return next((domain for domain \
                                in self.domains + self.defined_domains \
                                if domain.id == id))
        except StopIteration:
            raise libvirtError("Domain not found: no domain with matching" \
                               "id {id}".format(id=id))
Example #49
0
    def lookupByName(self, name):
        """Mock of libvirt.virConnect.lookupByName()"""

        try:
            return next((domain for domain \
                                in self.domains + self.defined_domains \
                                if domain._name == name))
        except StopIteration:
            raise libvirtError("Domain not found: no domain with matching" \
                               "name '{name}'".format(name=name))
Example #50
0
 def createXMLWithType(self, xml, val, domtp):
     for conn in self.conns:
         try:
             return conn.createXMLWithType(xml, val, domtp)
         except libvirt.libvirtError:
             pass
     raise libvirt.libvirtError(\
         "Can't find appropriate connection for %r domain type" % domtp)
     
     
    def test_power_off_domain_not_found(self, mock_open):
        connection_mock = mock.Mock()
        connection_mock.lookupByName.side_effect = \
            libvirt.libvirtError('virDomainLookupByName() failed',
                                 conn=connection_mock)
        mock_open.return_value = connection_mock

        self.assertRaises(drivers.DeviceNotFound,
                          self.driver.power_off, 'domainA')

        connection_mock.close.assert_called_with()
Example #52
0
 def _raiseAbortError():
     e = libvirt.libvirtError(defmsg='')
     # we have to override the value to get what we want
     # err might be None
     e.err = (libvirt.VIR_ERR_OPERATION_ABORTED,  # error code
              libvirt.VIR_FROM_QEMU,              # error domain
              'operation aborted',                # error message
              libvirt.VIR_ERR_WARNING,            # error level
              '', '', '',                         # str1, str2, str3,
              -1, -1)                             # int1, int2
     raise e
Example #53
0
 def test_create_xml_error(self):
     """NETWORK RuntimeError is raised in case of creation error."""
     xml = """<network><forward mode="nat"/><ip address="192.168.1.1" netmask="255.255.255.0">""" + \
           """<dhcp><range end="192.168.1.128" start="192.168.1.2"/></dhcp></ip></network>"""
     hypervisor = mock.Mock()
     hypervisor.listNetworks.return_value = []
     hypervisor.networkCreateXML.side_effect = libvirt.libvirtError('BOOM')
     with mock.patch('see.context.resources.network.open', mock.mock_open(read_data=xml), create=True):
         with self.assertRaises(RuntimeError) as error:
             network.create(hypervisor, 'foo', {'configuration': '/foo', 'ip_autodiscovery': False})
             self.assertEqual(str(error), "Unable to create new network: BOOM.")
Example #54
0
def open_libvirt(uri, *dt, **mp):
    conn = libvirt.open(uri, *dt, **mp)
    
    if not isinstance(conn.__class__, virConnectEx):
        for pref, cls in ALL_CONNECTIONS_MAP.items():
            if uri.startswith(pref):
                conn.__class__ = cls

    if not issubclass(conn.__class__, virConnectEx):
        raise libvirt.libvirtError("Can't find extended connection class for %r uri" \
                            % uri)
    
    return conn
def lxcOpenNamespace(domain, flags):
    """This API is LXC specific, so it will only work with hypervisor
    connections to the LXC driver.
    
    Open the namespaces associated with the container @domain
    and return a list of file descriptors associated with the
    container.
    
    The returned file descriptors are intended to be used with
    the setns() system call. """
    ret = libvirtmod_lxc.virDomainLxcOpenNamespace(domain._o, flags)
    if ret is None: raise libvirt.libvirtError('virDomainLxcOpenNamespace() failed')
    return ret
Example #56
0
 def test_volume_deletion_error(self):
     """QEMU The failure of deletion of a Volume does not stop the deletion process."""
     pool = mock.MagicMock()
     logger = mock.Mock()
     volumes = {'foo': mock.Mock(), 'bar': mock.Mock(), 'baz': mock.Mock()}
     pool.XMLDesc.return_value = """<pool><path>/foo/bar</path></pool>"""
     pool.listVolumes.return_value = ('foo', 'bar', 'baz')
     pool.storageVolLookupByName.side_effect = lambda n: volumes[n]
     volumes['foo'].delete.side_effect = libvirt.libvirtError('BOOM')
     qemu.pool_delete(pool, logger)
     volumes['foo'].delete.assert_called_with(0)
     volumes['bar'].delete.assert_called_with(0)
     volumes['baz'].delete.assert_called_with(0)
     self.assertTrue(pool.destroy.called)
Example #57
0
File: errors.py Project: EdDev/vdsm
def throw(code=libvirt.VIR_ERR_OPERATION_UNSUPPORTED,
          message='operation not supported',
          domain=libvirt.VIR_FROM_PROXY,
          warning=False):
    level = libvirt.VIR_ERR_WARNING if warning else libvirt.VIR_ERR_ERROR
    e = libvirt.libvirtError(defmsg='')
    # we have to override the value to get what we want
    # err might be None
    e.err = (code,          # error code
             domain,        # error domain
             message,       # error message
             level,         # error level
             '', '', '',    # str1, str2, str3,
             -1, -1)        # int1, int2
    raise e