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)
python类open()的实例源码
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 main(args):
vm_name = args['<vm_name>']
# get domain from libvirt
con = libvirt.open('qemu:///system')
domain = con.lookupByName(vm_name)
path = os.path.join(os.getcwd(), '{}.raw'.format(vm_name))
with open(path, 'w') as f:
# chmod to be r/w by everyone
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR |
stat.S_IRGRP | stat.S_IWGRP |
stat.S_IROTH | stat.S_IWOTH)
# take a ram dump
flags = libvirt.VIR_DUMP_MEMORY_ONLY
dumpformat = libvirt.VIR_DOMAIN_CORE_DUMP_FORMAT_RAW
domain.coreDumpWithFormat(path, dumpformat, flags)
def __init__(self, uri, module):
self.module = module
cmd = "uname -r"
rc, stdout, stderr = self.module.run_command(cmd)
if "xen" in stdout:
conn = libvirt.open(None)
elif "esx" in uri:
auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], [], None]
conn = libvirt.openAuth(uri, auth)
else:
conn = libvirt.open(uri)
if not conn:
raise Exception("hypervisor connection failure")
self.conn = conn
def guest_event_register(cls):
cls.conn = libvirt.open()
cls.conn.domainEventRegister(cls.guest_event_callback, None)
# ?????https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventID
cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
None, libvirt.VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION,
cls.guest_event_migration_iteration_callback, None))
cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_ADDED,
cls.guest_event_device_added_callback, None))
cls.guest_callbacks.append(cls.conn.domainEventRegisterAny(
None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED,
cls.guest_event_device_removed_callback, None))
def delete_virtual_network(network_xml):
LI('Begin to find and delete network %s' % network_xml)
tree = ET.ElementTree(file=network_xml)
root = tree.getroot()
names = root.findall('./name')
assert len(names) == 1
name = names[0].text
result = 0
conn = libvirt.open('qemu:///system')
for net in conn.listAllNetworks():
if name == net.name():
if net.isActive():
net.destroy()
LI('Network %s is destroyed' % name)
net.undefine()
LI('Network %s is deleted' % name)
result = 1
break
conn.close()
if not result:
LI('Network %s is not found' % name)
def check_all_os(hostname, path_to_write_json=None):
tuples_domain_disk = get_disks_all_domains()
cmds1 = list()
for domain_id, path_domain_disk in tuples_domain_disk:
cmds1.append({'title': domain_id, 'cmd': cmd_check_os(path_domain_disk)})
from pprint import pprint
pprint(cmds1)
array_out_err = execute_commands(hostname, cmds1, dict_mode=True)
# from pprint import pprint
# pprint(array_out_err)
if path_to_write_json is not None:
f = open(path_to_write_json, 'w')
json.dump(array_out_err, f)
f.close()
return array_out_err
def check_all_os(hostname, path_to_write_json=None):
tuples_domain_disk = get_disks_all_domains()
cmds1 = list()
for domain_id, path_domain_disk in tuples_domain_disk:
cmds1.append({'title': domain_id, 'cmd': cmd_check_os(path_domain_disk)})
from pprint import pprint
pprint(cmds1)
array_out_err = execute_commands(hostname, cmds1, dict_mode=True)
# from pprint import pprint
# pprint(array_out_err)
if path_to_write_json is not None:
f = open(path_to_write_json, 'w')
json.dump(array_out_err, f)
f.close()
return array_out_err
def get_connection(self):
""" Get connection with libvirt using QEMU driver and system
context
:return conn: connection with libvirt
:rtype conn: libvirt connection
"""
creds = self.args.credentials
if 'username' in creds:
auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
creds['username'], None]
conn = libvirt.openAuth(creds['qemu_instance'], auth, 0)
else:
conn = libvirt.open(creds['qemu_instance'])
if conn == None:
LOG.error('Failed to open connection to %s',
creds['qemu_instance'])
LOG.warn('check PAWS documentation %s' % LIBVIRT_AUTH_HELP)
raise PawsPreTaskError
LOG.debug("connected successfully to %s" % creds['qemu_instance'])
return conn
def __init__(self, name = "", uri = "qemu:///system"):
self.name = name
self.id = ""
self.xml = "" #don't modify it
self.temp = {
'total_cpu_time': 0L,
'last_cpu_idle_time': 0L,
'disk_read_request': 0L,
'disk_write_request': 0L,
'disk_read': 0L,
'disk_write': 0L,
'disk_read_delay': 0,
'disk_write_delay': 0,
'network_receive_bytes': 0L,
'network_transfer_bytes': 0L,
'disk_partition_info': {},
'timestamp': 0L
}
try:
conn = libvirt.open(uri)
dom = conn.lookupByName(name)
self.xml = dom.XMLDesc()
conn.close()
except Exception, e:
logger.exception(e)
def define(name, xml, uri="qemu:///system"):
conn = None
ret={}
try:
conn = libvirt.open(uri)
dom = conn.defineXML(xml)
ret["status_code"] = 0
ret["msg"] = "OK"
except Exception, e:
logger.exception(e)
ret["status_code"] = -1
ret["msg"] = str(e)
if conn:
conn.close()
logger.debug(ret)
return ret
def undefine(self, uri="qemu:///system"):
conn = None
ret={}
status_code = 0
msg = "OK"
try:
conn = libvirt.open(uri)
dom = conn.lookupByName(self.name)
dom.undefine()
status_code = 0
msg = "OK"
except Exception, e:
status_code = -1
msg = e
logger.exception(e)
if conn:
conn.close()
ret["status_code"] = status_code
ret["msg"] = str(msg)
logger.debug(ret)
return ret
def shutdown(self, uri="qemu:///system"):
conn = None
ret={}
status_code = 0
msg = "OK"
try:
conn = libvirt.open(uri)
dom = conn.lookupByName(self.name)
dom.shutdown()
status_code = 0
msg = "OK"
except Exception, e:
status_code = -1
msg = e
logger.exception(e)
if conn:
conn.close()
ret["status_code"] = status_code
ret["msg"] = str(msg)
logger.debug(ret)
return ret
def destroy(self, uri="qemu:///system"):
conn = None
ret={}
status_code = 0
msg = "OK"
try:
conn = libvirt.open(uri)
dom = conn.lookupByName(self.name)
dom.destroy()
status_code = 0
msg = "OK"
except Exception, e:
status_code = -1
msg = e
logger.exception(e)
if conn:
conn.close()
ret["status_code"] = status_code
ret["msg"] = str(msg)
logger.debug(ret)
return ret
def read_vm_file(self, path, uri="qemu:///system"):
FILE_OPEN_READ="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"r"}}"""
FILE_READ="""{"execute":"guest-file-read", "arguments":{"handle":%s,"count":%d}}"""
FILE_CLOSE="""{"execute":"guest-file-close", "arguments":{"handle":%s}}"""
file_handle=-1
try:
file_handle=self.EXE(FILE_OPEN_READ % path)["return"]
file_content=self.EXE(FILE_READ % (file_handle,1024000))["return"]["buf-b64"]
file_content = base64.standard_b64decode(file_content)
except Exception,e:
logger.exception(e)
return None
finally:
self.EXE(FILE_CLOSE % file_handle)
return file_content
def write_vm_file(self, path, content, uri="qemu:///system"):
FILE_OPEN_WRITE="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"w+"}}"""
FILE_WRITE="""{"execute":"guest-file-write", "arguments":{"handle":%s,"buf-b64":"%s"}}"""
FILE_CLOSE="""{"execute":"guest-file-close", "arguments":{"handle":%s}}"""
FILE_FLUSH="""{"execute":"guest-file-flush", "arguments":{"handle":%s}}"""
file_handle=-1
enc_content = base64.standard_b64encode(content)
try:
file_handle=self.EXE(FILE_OPEN_WRITE % path)["return"]
write_count=self.EXE(FILE_WRITE % (file_handle,enc_content))["return"]["count"]
logger.debug("content:\n%s\npath:\n%s"%(content, path))
except Exception,ex:
print Exception,":",ex
return -1
finally:
self.EXE(FILE_FLUSH % file_handle)
self.EXE(FILE_CLOSE % file_handle)
return write_count
def build_host_hw(sn, uri = "qemu:///system"):
conn = None
try:
conn = libvirt.open(uri)
except Exception, e:
logger.exception(e)
ret_dict = {}
ret_dict['req'] = "host.hw"
ret_dict['sn'] = sn
chost = vmmhost(sn, conn)
ret_dict['body'] = [ chost.get_hw_info() ]
if conn:
conn.close()
return ret_dict
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 _uploadimage(self, name, newname, pool='default', origin='/tmp', suffix='.iso'):
name = "%s" % (name)
_pool = self.conn.storagePoolLookupByName(pool)
poolxml = _pool.XMLDesc(0)
root = ET.fromstring(poolxml)
for element in root.getiterator('path'):
poolpath = element.text
break
imagepath = "%s/%s" % (poolpath, newname)
imagexml = self._xmlvolume(path=imagepath, size=0, diskformat='raw')
_pool.createXML(imagexml, 0)
imagevolume = self.conn.storageVolLookupByPath(imagepath)
stream = self.conn.newStream(0)
imagevolume.upload(stream, 0, 0)
with open("%s/%s" % (origin, name)) as ori:
stream.sendAll(self.handler, ori)
stream.finish()
return imagepath
def main():
dic = {}
vconn = libvirt.open('qemu:///system')
try:
name = sys.argv[1]
except IndexError, e:
print e
sys.exit()
dic.update(getUUID())
# dic.update(getIP())
dic.update({'http_host': '192.168.10.213'})
dic.update(getMAC())
dic.update(getPort())
dic.update(getName(name))
xml = XML % dic
if createVM(vconn, name, xml):
print 'created vmachine name is: %s, and port is %s' % (dic['name'], dic['port'])
time.sleep(15)
runVM(vconn, xml, name)
def clean_networks():
logging.debug('Cleaning all network config')
for network in constants.OPNFV_NETWORK_TYPES:
logging.info("Cleaning Jump Host Network config for network "
"{}".format(network))
jumphost.detach_interface_from_ovs(network)
jumphost.remove_ovs_bridge(network)
conn = libvirt.open('qemu:///system')
if not conn:
raise ApexCleanException('Unable to open libvirt connection')
logging.debug('Destroying all virsh networks')
for network in conn.listNetworks():
if network in constants.OPNFV_NETWORK_TYPES:
virsh_net = conn.networkLookupByName(network)
logging.debug("Destroying virsh network: {}".format(network))
if virsh_net.isActive():
virsh_net.destroy()
virsh_net.undefine()
def __init__(self, host, conn):
"""
Sets all class attributes and tries to open the connection
"""
# connection lock is used to lock all changes to the connection state attributes
# (connection and last_error)
self.connection_state_lock = threading.Lock()
self.connection = None
self.last_error = None
# credentials
self.host = host
self.login = kvm_config.get('user')
self.passwd = kvm_config.get('password')
self.type = conn
# connect
self.connect()
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 __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
def __connect_socket(self):
uri = 'qemu:///system'
try:
self.connection = libvirt.open(uri)
self.last_error = None
except libvirtError as e:
self.last_error = 'Connection Failed: ' + str(e)
self.connection = None
def _connect(self):
return closing(libvirt.open(self.uri))
def __enter__(self):
if not self.connection:
self.connection = libvirt.open(self.uri)
return self.connection
def testSetUp(cls, test_class):
con = libvirt.open('qemu:///system')
test_class.domain = con.lookupByName(test_class.domain_name)
test_class.vm = test_class.test_helper(test_class.domain)
def prepare_domain_xml(domain_name, qemu_bin_path, nitro_image_path, open_vnc):
with open('template_domain.xml') as templ:
domain_xml = templ.read()
domain_xml = domain_xml.format(domain_name, qemu_bin_path,
nitro_image_path)
root = tree.fromstring(domain_xml)
if open_vnc:
# search for graphics element
graphics_elem = root.findall("./devices/graphics")[0]
graphics_elem.attrib['listen'] = '0.0.0.0'
domain_xml = tree.tostring(root).decode()
return domain_xml
return None