本文整理匯總了Python中libvirt.libvirtError方法的典型用法代碼示例。如果您正苦於以下問題:Python libvirt.libvirtError方法的具體用法?Python libvirt.libvirtError怎麽用?Python libvirt.libvirtError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類libvirt
的用法示例。
在下文中一共展示了libvirt.libvirtError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __getattr__
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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
示例2: __delitem__
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例3: register_event_handlers
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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))
示例4: image
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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()
示例5: domain_create
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例6: domain_delete
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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.")
示例7: active_network_addresses
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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
示例8: domain_delete
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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.")
示例9: test_create_too_many_attempts
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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"))
示例10: test_clone_fwdslash
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例11: test_allocate_fail
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例12: test_allocate_fail
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例13: initialise
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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
)
示例14: __enter__
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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)
示例15: get_power_state
# 需要導入模塊: import libvirt [as 別名]
# 或者: from libvirt import libvirtError [as 別名]
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