我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用libvirt.libvirtError()。
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)
def get_connection(self, host, login, passwd, conn): host = unicode(host) login = unicode(login) passwd = unicode(passwd) if passwd is not None else None connection = self._search_connection(host, login, passwd, conn) if (connection is None): self._connections_lock.acquireWrite() try: connection = self._search_connection(host, login, passwd, conn) if (connection is None): connection = wvmConnection(host, login, passwd, conn) if host in self._connections: self._connections[host].append(connection) else: self._connections[host] = [connection] finally: self._connections_lock.release() elif not connection.connected: connection.connect() if connection.connected: return connection.connection else: raise libvirtError(connection.last_error)
def createVolumes(self,pool,volume_name,volume_capacity,drive=None): if drive is None:drive = 'qcow2' volume_xml = """<volume> <name>{volume_name}</name> <allocation>0</allocation> <capacity unit="G">{volume_capacity}</capacity> <target> <format type="{drive}"/> </target> </volume> """ volume_xml = volume_xml.format(volume_name=volume_name,volume_capacity=volume_capacity,drive=drive) try: return pool.createXML(volume_xml, 0) except libvirt.libvirtError,e: return '?????????????{result}'.format(result=e.get_error_message())
def clone(self, pool,pool_name,name, clone, format=None): '''???''' storage_type = self.getStorageMode(pool_name) if storage_type == 'dir': clone += '.img' vol = self.getStorageVolume(pool,name) if vol: if not format: format = self.getStorageVolumeType(name) xml = """ <volume> <name>%s</name> <capacity>0</capacity> <allocation>0</allocation> <target> <format type='%s'/> </target> </volume>""" % (clone, format) try: return self.createXMLFrom(xml, vol, 0) except libvirt.libvirtError,e: return '?????????????{result}'.format(result=e.get_error_message())
def mountIso(self,instance,dev, image): tree = ElementTree.fromstring(self.getInsXMLDesc(instance,0)) for disk in tree.findall('devices/disk'): if disk.get('device') == 'cdrom': for elm in disk: if elm.tag == 'target': if elm.get('dev') == dev: src_media = ElementTree.Element('source') src_media.set('file', image) disk.append(src_media) if instance.state()[0] == 1: xml_disk = ElementTree.tostring(disk) try: instance.attachDevice(xml_disk) except libvirt.libvirtError,e: return '??????????{result}'.format(result=e.get_error_message()) xmldom = self.getInsXMLDesc(instance,1) if instance.state()[0] == 5: xmldom = ElementTree.tostring(tree) try: return self.defineXML(xmldom) except libvirt.libvirtError,e: return '??????????{result}'.format(result=e.get_error_message())
def addInstanceInterface(self,instance,brName): netk = self.getNetwork(brName) if netk: xml = netk.XMLDesc(0) tree = ElementTree.fromstring(xml) try: mode = tree.find('virtualport').get('type') except: mode = 'brctl' model = tree.find('forward').get('mode') interXml = Const.CreateNetcard(nkt_br=brName, ntk_name=brName +'-'+CommTools.radString(length=4), data={'type':model,'mode':mode}) try: return instance.attachDeviceFlags(interXml,3)#??????????flags?3?????????????? except libvirt.libvirtError,e: return '??????????????{result}'.format(result=e.get_error_message()) else:return False
def delInstanceInterface(self,instance,interName): '''??????''' interXml = None raw_xml = instance.XMLDesc(0) domXml = minidom.parseString(raw_xml) for ds in domXml.getElementsByTagName('interface'): try: dev = ds.getElementsByTagName('target')[0].getAttribute('dev') except: continue if dev == interName:interXml = ds.toxml() if interXml: try: return instance.detachDeviceFlags(interXml,3) except libvirt.libvirtError,e: return '??????????????{result}'.format(result=e.get_error_message()) else:return False
def delInstanceDisk(self,instance,volPath): '''????''' diskXml = None raw_xml = instance.XMLDesc(0) domXml = minidom.parseString(raw_xml) for ds in domXml.getElementsByTagName('disk'): try: path = ds.getElementsByTagName('source')[0].getAttribute('file') except: continue if path == volPath:diskXml = ds.toxml() if diskXml: try: return instance.detachDeviceFlags(diskXml,3) except libvirt.libvirtError,e: return '??????????????{result}'.format(result=e.get_error_message()) else:return False
def __init__(self, domain, wait, cdrom): self.domain = domain if self.domain.isActive(): self.domain.destroy() # revert to base snapshot if present try: snap = self.domain.snapshotLookupByName(SNAPSHOT_BASE) logging.info('Reverting to base snapshot') self.domain.revertToSnapshot(snap) except libvirt.libvirtError: logging.warning('Missing snapshot "%s"', SNAPSHOT_BASE) # start domain logging.info('Testing {}'.format(self.domain.name())) self.domain.create() # wait for IP address self.ip = self.wait_for_ip() self.wait = wait self.sleep_amount = 1 logging.info('IP address: %s', self.ip) self.wait(self.ip, True) self.cdrom = cdrom
def define_by_xml(self, conn=None): try: if conn.defineXML(xml=self.xml): log = u' '.join([u'?', self.name, u', UUID', self.uuid, u'????.']) logger.info(msg=log) log_emit.info(msg=log) else: log = u' '.join([u'?', self.name, u', UUID', self.uuid, u'????????.']) logger.info(msg=log) log_emit.info(msg=log) return False except libvirt.libvirtError as e: logger.error(e.message) log_emit.error(e.message) return False return True
def main(): try: conn = openReadOnly(None) except libvirtError as error: print('WARNING: could not connect to libvirt: ' + str(error)) exit(1) inactive_domains = [d for d in conn.listAllDomains() if not d.isActive()] if inactive_domains: print('WARNING: ' + ', '.join( '{} is defined but not running'.format(d.name()) for d in inactive_domains )) exit(1) print('OK: all defined domains are running') exit(0)
def create_vm(conn, xml_path): """Define a new domain in Libvirt, creating new Virtual Machine :param conn: Libvirt connection :type conn: object :param xml_path: full path for XML with VM definition :type xml_path: str :return True :rtype Boolean """ LOG.debug("VM creation, defining new domain in libvirt") try: conn.defineXMLFlags(xml_path) LOG.debug("VM creation, complete") return True except (SystemExit, libvirtError) as ex: LOG.error(ex) raise SystemExit(1)
def start_vm(self, vm): """Start virtual machine instance on Libvirt :param vm: virtual machine :type vm: object """ if self.is_running(vm): LOG.debug("VM %s is running" % vm.name()) return True try: vm.create() LOG.debug("Importing VM %s" % vm) # the raise exception is to force the vm state be checked again raise Exception except libvirt.libvirtError as ex: raise ex
def delete_vm(conn, vm, flag=None): """ """ #TODO: PAWS-84 flag to delete VM during teardown try: vm.undefineFlags(1) LOG.debug("VM %s deleted" % vm.name()) if flag: storage_pools = conn.listAllStoragePools() for pool in storage_pools: stgvols = pool.listVolumes() LOG.error(stgvols) return True except (libvirt.libvirtError, Exception) as ex: LOG.error(ex)
def pattern_matching_domains_in_libvirt(pattern, conn): """ Parse the host pattern as written in the config and find matching hosts :param pattern: pattern to match on one or several domain names :param conn: connection with libvirt """ exclude, pattern = _handle_possible_exclusion_host_pattern(pattern) if pattern.startswith("r:"): pattern = pattern[2:] domains = search_domains_regex(pattern, conn) elif pattern.startswith("g:"): domains = _include_group_domains(pattern) else: try: # will raise libvirt.libvirtError if the domain is not found conn.lookupByName(pattern) domains = (pattern,) except libvirt.libvirtError as e: logger.error(e) domains = tuple() return {"domains": domains, "exclude": exclude}
def dump_memory(self, label, path): """Takes a memory dump. @param path: path to where to store the memory dump. """ log.debug("Dumping memory for machine %s", label) conn = self._connect(label) try: # create the memory dump file ourselves first so it doesn't end up root/root 0600 # it'll still be owned by root, so we can't delete it, but at least we can read it fd = open(path, "w") fd.close() self.vms[label].coreDump(path, flags=libvirt.VIR_DUMP_MEMORY_ONLY) except libvirt.libvirtError as e: raise CuckooMachineError("Error dumping memory virtual machine " "{0}: {1}".format(label, e)) finally: self._disconnect(conn)
def _connect(self, label=None): """Connects to libvirt subsystem. @raise CuckooMachineError: when unable to connect to libvirt. """ # Check if a connection string is available. dsn = self.options.get(label).get("dsn", None) if not dsn: raise CuckooMachineError("You must provide a proper " "connection string for "+label) try: return libvirt.open(dsn) except libvirt.libvirtError: raise CuckooMachineError("Cannot connect to libvirt")
def node_snapshot_create(self, domain): domains = [ dom.name() for dom in self.domains ] if domain not in domains: return xml_head = """<domainsnapshot> <name>snapshot</name> <state>running</state> <memory snapshot='internal'/> <disks><disk name='hda' snapshot='internal'/></disks>""" xml_tail = "</domainsnapshot>" try: domain = self.conn.lookupByName(domain) self.node_snapshot_clear(domain) xml_desc = xml_head + domain.XMLDesc() + xml_tail domain.snapshotCreateXML(xml_desc) return True except libvirt.libvirtError, e: logging.error("{} - Failed to create snapshot:\n{}".format(domain, e))
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: self.LOGGER.error("Unable to determine snapshot: '{}'".format(err)) raise SessionException(err) except Exception as err: raise SessionException(err)
def get_vm_ips(self): """ Returns a list of VMs and their IPs available through the current connection. """ try: #get all VMs vms = self.SESSION.listDefinedDomains() result = [] #scan _all_ the VMs for vm in vms: #get VM and lookup hostname target_vm = self.SESSION.lookupByName(vm) target_hostname = target_vm.hostname() #lookup IP target_ip = socket.gethostbyname(target_hostname) result.append( {"hostname": target_hostname, "ip": target_ip} ) return result except libvirt.libvirtError as err: raise SessionException("Unable to get VM IP information: '{}'".format(err))
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))
def getVMSpecs(id): data = None try: uuid = UUID(id) except Exception: uuid = None with app.conn as conn: try: if uuid: domain = conn.lookupByUUIDString(id) else: domain = conn.lookupByName(id) except libvirt.libvirtError as e: if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN: abort(404) raise e data = parse_domain_xml(domain.XMLDesc()) return Response( json.dumps(data, default=_datetime_serial), mimetype='application/json' )
def close(self): """ closes the connection (if it is active) """ self.connection_state_lock.acquire() try: if self.connected: try: # to-do: handle errors? self.connection.close() except libvirtError as e: log_error(str(e)) self.connection = None self.last_error = None finally: self.connection_state_lock.release()
def set_console_keymap(self, keymap): xml = self._XMLDesc(VIR_DOMAIN_XML_SECURE) root = ElementTree.fromstring(xml) console_type = self.get_console_type() try: graphic = root.find("devices/graphics[@type='%s']" % console_type) except SyntaxError as e: log_error(str(e)) # Little fix for old version ElementTree graphic = root.find("devices/graphics") if keymap: graphic.set('keymap', keymap) else: try: graphic.attrib.pop('keymap') except libvirtError as e: log_error(str(e)) newxml = ElementTree.tostring(root) self._defineXML(newxml)
def get_storages_images(self): """ Function return all images on all storages """ images = [] storages = self.get_storages() for storage in storages: stg = self.get_storage(storage) try: stg.refresh(0) except libvirtError as e: log_error(str(e)) for img in stg.listVolumes(): if img.endswith('.iso'): pass else: images.append(img) return images
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: return 0xd5 with utils.libvirt_open(**self._conn_args) as conn: domain = utils.get_libvirt_domain(conn, self.domain_name) tree = ET.fromstring(domain.XMLDesc()) for os_element in tree.findall('os'): # Remove all "boot" elements for boot_element in os_element.findall('boot'): os_element.remove(boot_element) # Add a new boot element with the request boot device boot_element = ET.SubElement(os_element, 'boot') boot_element.set('dev', device) try: conn.defineXML(ET.tostring(tree)) except libvirt.libvirtError as e: LOG.error('Failed setting the boot device %(bootdev)s for ' 'domain %(domain)s', {'bootdev': device, 'domain': self.domain_name})
def get_power_state(self): LOG.debug('Get power state called for domain %s', 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: LOG.error('Error getting the power state of domain %(domain)s. ' 'Error: %(error)s', {'domain': self.domain_name, 'error': e}) return return POWEROFF
def power_off(self): LOG.debug('Power off called for domain %s', 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.destroy() except libvirt.libvirtError as e: LOG.error('Error powering off the domain %(domain)s. ' 'Error: %(error)s' % {'domain': self.domain_name, 'error': e}) return
def power_on(self): LOG.debug('Power on called for domain %s', 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}) return
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(0xd5, ret) self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open)
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)
def test_pulse_diag_error(self, mock_libvirt_domain, mock_libvirt_open): mock_libvirt_domain.side_effect = libvirt.libvirtError('boom') ret = self.vbmc.pulse_diag() self.assertEqual(0xd5, ret) mock_libvirt_domain.return_value.injectNMI.assert_not_called() self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open)
def test_power_off_error(self, mock_libvirt_domain, mock_libvirt_open): mock_libvirt_domain.side_effect = libvirt.libvirtError('boom') ret = self.vbmc.power_off() self.assertEqual(0xd5, ret) mock_libvirt_domain.return_value.destroy.assert_not_called() self._assert_libvirt_calls(mock_libvirt_domain, mock_libvirt_open)
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)
def test_get_libvirt_domain_not_found(self): self.fake_connection.lookupByName.side_effect = libvirt.libvirtError( 'boom') self.assertRaises(exception.DomainNotFound, utils.get_libvirt_domain, self.fake_connection, 'Fred') self.fake_connection.lookupByName.assert_called_once_with('Fred')
def test_libvirt_open_error(self, mock_open): mock_open.side_effect = libvirt.libvirtError('boom') self.assertRaises(exception.LibvirtConnectionOpenError, self._test_libvirt_open, mock_open) mock_open.assert_called_once_with(self.uri)
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 0xcc try: with utils.libvirt_open(**self._conn_args) as conn: domain = utils.get_libvirt_domain(conn, self.domain_name) tree = ET.fromstring(domain.XMLDesc()) for os_element in tree.findall('os'): # Remove all "boot" elements for boot_element in os_element.findall('boot'): os_element.remove(boot_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)) except libvirt.libvirtError: LOG.error('Failed setting the boot device %(bootdev)s for ' 'domain %(domain)s', {'bootdev': device, 'domain': self.domain_name}) # Command not supported in present state return 0xd5
def get_power_state(self): LOG.debug('Get power state called for domain %s', 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: LOG.error('Error getting the power state of domain %(domain)s. ' 'Error: %(error)s', {'domain': self.domain_name, 'error': e}) # Command not supported in present state return 0xd5 return POWEROFF
def pulse_diag(self): LOG.debug('Power diag called for domain %s', 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 not supported in present state return 0xd5
def power_on(self): LOG.debug('Power on called for domain %s', 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 not supported in present state return 0xd5
def power_shutdown(self): LOG.debug('Soft power off called for domain %s', 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 not supported in present state return 0xd5
def get_libvirt_domain(conn, domain): try: return conn.lookupByName(domain) except libvirt.libvirtError: raise exception.DomainNotFound(domain=domain)
def __enter__(self): try: self._conn = (libvirt.openReadOnly(self.uri) if self.readonly else libvirt.open(self.uri)) return self._conn except libvirt.libvirtError as e: print('Error when connecting to the libvirt URI "%(uri)s": ' '%(error)s' % {'uri': self.uri, 'error': e}) flask.abort(500)
def get_libvirt_domain(connection, domain): try: return connection.lookupByName(domain) except libvirt.libvirtError: flask.abort(404)
def system_reset_action(identity): reset_type = flask.request.json.get('ResetType') with libvirt_open(LIBVIRT_URI) as conn: domain = get_libvirt_domain(conn, identity) try: if reset_type in ('On', 'ForceOn'): if not domain.isActive(): domain.create() elif reset_type == 'ForceOff': if domain.isActive(): domain.destroy() elif reset_type == 'GracefulShutdown': if domain.isActive(): domain.shutdown() elif reset_type == 'GracefulRestart': if domain.isActive(): domain.reboot() elif reset_type == 'ForceRestart': if domain.isActive(): domain.reset() elif reset_type == 'Nmi': if domain.isActive(): domain.injectNMI() except libvirt.libvirtError: flask.abort(500) return '', 204
def __connect_tcp(self): flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE] auth = [flags, self.__libvirt_auth_credentials_callback, None] uri = 'qemu+tcp://%s/system' % self.host try: return libvirt.openAuth(uri, auth, 0) except libvirtError as e: self.last_error = 'Connection Failed: ' + str(e) self.connection = None
def __connect_socket(self): uri = 'qemu:///system' try: return libvirt.open(uri) except libvirtError as e: self.last_error = 'Connection Failed: ' + str(e) self.connection = None