本文整理汇总了Python中virttest.libvirt_xml.vm_xml.VMXML.new_from_dumpxml方法的典型用法代码示例。如果您正苦于以下问题:Python VMXML.new_from_dumpxml方法的具体用法?Python VMXML.new_from_dumpxml怎么用?Python VMXML.new_from_dumpxml使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类virttest.libvirt_xml.vm_xml.VMXML
的用法示例。
在下文中一共展示了VMXML.new_from_dumpxml方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find_comm_paths
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def _find_comm_paths(session):
if source_path is None:
host_path = _get_autopath()
else:
host_path = source_path
name_port_map = {}
base_path = '/sys/class/virtio-ports'
vports = session.cmd_output('ls %s' % base_path).split()
status = session.cmd_status('ls %s/*/name' % base_path)
if status == 0:
for vport in vports:
vport_path = os.path.join(base_path, vport)
name_path = os.path.join(vport_path, 'name')
name = session.cmd_output('cat %s' % name_path).strip()
name_port_map[name] = vport
if expect_name not in name_port_map:
raise error.TestFail("Expect get vport name %s, got %s" %
(expect_name, name_port_map))
vport = name_port_map[expect_name]
else:
active_xml = VMXML.new_from_dumpxml(vm_name)
port_number = active_xml.xmltreefile.find(
'/devices/channel/address').get('port')
vport = 'vport1p%s' % port_number
guest_path = '/dev/%s' % vport
return guest_path, host_path
示例2: _check_xml
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def _check_xml():
"""
Check defined XML against expectation
"""
expected_channel = Channel(channel_type)
try:
source_dict = channel.source
except LibvirtXMLNotFoundError:
source_dict = {}
if channel_type == 'pty':
source_dict = {}
elif channel_type == 'unix':
if source_mode is None:
if source_path:
source_dict['mode'] = 'connect'
else:
source_dict['mode'] = 'bind'
if source_path is None:
source_dict['path'] = _get_autopath()
if source_autopath:
del source_dict['autopath']
target_dict = {}
if target_type == 'virtio':
expected_channel.address = {
'bus': '0',
'controller': '0',
'port': '1',
'type': 'virtio-serial',
}
if 'type' in channel.target:
target_dict['type'] = channel.target['type']
if 'name' in channel.target:
target_dict['name'] = channel.target['name']
elif target_type == 'guestfwd':
if 'type' in channel.target:
target_dict['type'] = channel.target['type']
if 'address' in channel.target:
target_dict['address'] = channel.target['address']
if 'port' in channel.target:
target_dict['port'] = channel.target['port']
if source_dict:
expected_channel.source = source_dict
if target_dict:
expected_channel.target = target_dict
current_xml = VMXML.new_from_dumpxml(vm_name)
channel_elem = current_xml.xmltreefile.find('devices/channel')
cur_channel = Channel.new_from_element(channel_elem)
if not (expected_channel == cur_channel):
raise error.TestFail("Expect generate channel:\n%s\nBut got:\n%s" %
(expected_channel, cur_channel))
示例3: check_dumpxml
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def check_dumpxml():
"""
Check whether the added devices are shown in the guest xml
"""
pattern = "<sound model=\"%s\">" % sound_model
# Check sound model
xml_after_adding_device = VMXML.new_from_dumpxml(vm_name)
if pattern not in str(xml_after_adding_device):
test.fail("Can not find the %s sound device xml "
"in the guest xml file." % sound_model)
# Check codec type
if codec_type:
pattern = "<codec type=\"%s\" />" % codec_type
if pattern not in str(xml_after_adding_device):
test.fail("Can not find the %s codec xml for sound dev "
"in the guest xml file." % codec_type)
示例4: get_controller_addr
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def get_controller_addr(cntlr_type=None, model=None, index=None):
"""
Get the address of testing controller from VM XML as a string with
format "bus:slot.function".
"""
cur_vm_xml = VMXML.new_from_dumpxml(vm_name)
addr = None
for elem in cur_vm_xml.xmltreefile.findall('/devices/controller'):
if (
(cntlr_type is None or elem.get('type') == cntlr_type) and
(model is None or elem.get('model') == model) and
(index is None or elem.get('index') == index)):
addr_elem = elem.find('./address')
if addr_elem is not None:
addr = Address.new_from_element(addr_elem).attrs
if addr is not None:
bus = int(addr['bus'], 0)
slot = int(addr['slot'], 0)
func = int(addr['function'], 0)
addr_str = '%02d:%02d.%1d' % (bus, slot, func)
logging.debug("String for address element %s is %s", addr, addr_str)
return addr_str
示例5: run
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
#.........这里部分代码省略.........
# Set qemu conf
if security_driver:
qemu_conf.set_string('security_driver', security_driver)
if security_default_confined:
qemu_conf.security_default_confined = security_default_confined
if security_require_confined:
qemu_conf.security_require_confined = security_require_confined
if (security_driver or security_default_confined or
security_require_confined):
logging.debug("the qemu.conf content is: %s" % qemu_conf)
libvirtd.restart()
# Set the context of the VM.
vmxml.set_seclabel(sec_dict_list)
vmxml.sync()
logging.debug("the domain xml is: %s" % vmxml.xmltreefile)
# restart libvirtd
libvirtd.restart()
# Start VM to check the VM is able to access the image or not.
try:
vm.start()
# Start VM successfully.
# VM with seclabel can access the image with the context.
if status_error:
raise error.TestFail("Test succeeded in negative case.")
# Check the label of VM and image when VM is running.
vm_context = utils_selinux.get_context_of_process(vm.get_pid())
if (sec_type == "static") and (not vm_context == sec_label):
raise error.TestFail("Label of VM is not expected after "
"starting.\n"
"Detail: vm_context=%s, sec_label=%s"
% (vm_context, sec_label))
disk_context = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (sec_relabel == "no") and (not disk_context == img_label):
raise error.TestFail("Label of disk is not expected after VM "
"starting.\n"
"Detail: disk_context=%s, img_label=%s."
% (disk_context, img_label))
if sec_relabel == "yes" and not no_sec_model:
vmxml = VMXML.new_from_dumpxml(vm_name)
imagelabel = vmxml.get_seclabel()[0]['imagelabel']
# the disk context is 'system_u:object_r:svirt_image_t:s0',
# when VM started, the MLS/MCS Range will be added automatically.
# imagelabel turns to be 'system_u:object_r:svirt_image_t:s0:cxx,cxxx'
# but we shouldn't check the MCS range.
if not _check_label_equal(disk_context, imagelabel):
raise error.TestFail("Label of disk is not relabeled by "
"VM\nDetal: disk_context="
"%s, imagelabel=%s"
% (disk_context, imagelabel))
# Check the label of disk after VM being destroyed.
if poweroff_with_destroy:
vm.destroy(gracefully=False)
else:
vm.wait_for_login()
vm.shutdown()
img_label_after = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (not img_label_after == img_label):
# Bug 547546 - RFE: the security drivers must remember original
# permissions/labels and restore them after
# https://bugzilla.redhat.com/show_bug.cgi?id=547546
err_msg = "Label of disk is not restored in VM shuting down.\n"
err_msg += "Detail: img_label_after=%s, " % img_label_after
err_msg += "img_label_before=%s.\n" % img_label
err_msg += "More info in https://bugzilla.redhat.com/show_bug"
err_msg += ".cgi?id=547546"
raise error.TestFail(err_msg)
except virt_vm.VMStartError, e:
# Starting VM failed.
# VM with seclabel can not access the image with the context.
if not status_error:
raise error.TestFail("Test failed in positive case."
"error: %s" % e)
finally:
# clean up
for path, label in backup_labels_of_disks.items():
# Using semanage set context persistently
dir_path = "%s(/.*)?" % os.path.dirname(path)
(img_label_type, img_label_range) = _resolve_label(label)
utils_selinux.set_defcon(context_type=img_label_type,
pathregex=dir_path,
context_range=img_label_range)
utils_selinux.verify_defcon(pathname=path,
readonly=False,
forcedesc=True)
for path, label in backup_ownership_of_disks.items():
label_list = label.split(":")
os.chown(path, int(label_list[0]), int(label_list[1]))
backup_xml.sync()
utils_selinux.set_status(backup_sestatus)
if (security_driver or security_default_confined or
security_require_confined):
qemu_conf.restore()
libvirtd.restart()
示例6: run_svirt_attach_disk
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_svirt_attach_disk(test, params, env):
"""
Test svirt in adding disk to VM.
(1).Init variables for test.
(2).Create a image to attached to VM.
(3).Attach disk.
(4).Start VM and check result.
"""
# Get general variables.
status_error = ('yes' == params.get("status_error", 'no'))
host_sestatus = params.get("svirt_attach_disk_host_selinux", "enforcing")
# Get variables about seclabel for VM.
sec_type = params.get("svirt_attach_disk_vm_sec_type", "dynamic")
sec_model = params.get("svirt_attach_disk_vm_sec_model", "selinux")
sec_label = params.get("svirt_attach_disk_vm_sec_label", None)
sec_relabel = params.get("svirt_attach_disk_vm_sec_relabel", "yes")
sec_dict = {'type': sec_type, 'model': sec_model, 'label': sec_label,
'relabel': sec_relabel}
# Get variables about VM and get a VM object and VMXML instance.
vm_name = params.get("main_vm")
vm = env.get_vm(vm_name)
vmxml = VMXML.new_from_dumpxml(vm_name)
backup_xml = vmxml.copy()
# Get varialbles about image.
img_label = params.get('svirt_attach_disk_disk_label')
img_name = "svirt_disk"
# Default label for the other disks.
# To ensure VM is able to access other disks.
default_label = params.get('svirt_attach_disk_disk_default_label', None)
# Set selinux of host.
backup_sestatus = utils_selinux.get_status()
utils_selinux.set_status(host_sestatus)
# Set the default label to other disks of vm.
disks = vm.get_disk_devices()
for disk in disks.values():
utils_selinux.set_context_of_file(filename=disk['source'],
context=default_label)
# Init a QemuImg instance.
params['image_name'] = img_name
tmp_dir = data_dir.get_tmp_dir()
image = qemu_storage.QemuImg(params, tmp_dir, img_name)
# Create a image.
img_path, result = image.create(params)
# Set the context of the image.
utils_selinux.set_context_of_file(filename=img_path, context=img_label)
# Set the context of the VM.
vmxml.set_seclabel(sec_dict)
vmxml.sync()
# Do the attach action.
try:
virsh.attach_disk(vm_name, source=img_path, target="vdf",
extra="--persistent", ignore_status=False)
except error.CmdError:
raise error.TestFail("Attach disk %s to vdf on VM %s failed."
% (img_path, vm.name))
# Check result.
try:
# Start VM to check the VM is able to access the image or not.
try:
vm.start()
# Start VM successfully.
# VM with set seclabel can access the image with the
# set context.
if status_error:
raise error.TestFail('Test successed in negative case.')
except virt_vm.VMStartError, e:
# Starting VM failed.
# VM with set seclabel can not access the image with the
# set context.
if not status_error:
raise error.TestFail("Test failed in positive case."
"error: %s" % e)
finally:
# clean up
try:
virsh.detach_disk(vm_name, target="vdf", extra="--persistent",
ignore_status=False)
except error.CmdError:
raise error.TestFail("Detach disk 'vdf' from VM %s failed."
% vm.name)
image.remove()
backup_xml.sync()
utils_selinux.set_status(backup_sestatus)
示例7: run_svirt_start_destroy
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_svirt_start_destroy(test, params, env):
"""
Test svirt in adding disk to VM.
(1).Init variables for test.
(2).Label the VM and disk with proper label.
(3).Start VM and check the context.
(4).Destroy VM and check the context.
"""
# Get general variables.
status_error = ('yes' == params.get("status_error", 'no'))
host_sestatus = params.get("svirt_start_destroy_host_selinux", "enforcing")
# Get variables about seclabel for VM.
sec_type = params.get("svirt_start_destroy_vm_sec_type", "dynamic")
sec_model = params.get("svirt_start_destroy_vm_sec_model", "selinux")
sec_label = params.get("svirt_start_destroy_vm_sec_label", None)
sec_relabel = params.get("svirt_start_destroy_vm_sec_relabel", "yes")
sec_dict = {'type': sec_type, 'model': sec_model, 'label': sec_label,
'relabel': sec_relabel}
# Get variables about VM and get a VM object and VMXML instance.
vm_name = params.get("main_vm")
vm = env.get_vm(vm_name)
vmxml = VMXML.new_from_inactive_dumpxml(vm_name)
backup_xml = vmxml.copy()
# Get varialbles about image.
img_label = params.get('svirt_start_destroy_disk_label')
# Label the disks of VM with img_label.
disks = vm.get_disk_devices()
backup_labels_of_disks = {}
for disk in disks.values():
disk_path = disk['source']
backup_labels_of_disks[disk_path] = utils_selinux.get_context_of_file(
filename=disk_path)
utils_selinux.set_context_of_file(filename=disk_path,
context=img_label)
# Set selinux of host.
backup_sestatus = utils_selinux.get_status()
utils_selinux.set_status(host_sestatus)
# Set the context of the VM.
vmxml.set_seclabel(sec_dict)
vmxml.sync()
try:
# Start VM to check the VM is able to access the image or not.
try:
vm.start()
# Start VM successfully.
# VM with seclabel can access the image with the context.
if status_error:
raise error.TestFail("Test successed in negative case.")
# Check the label of VM and image when VM is running.
vm_context = utils_selinux.get_context_of_process(vm.get_pid())
if (sec_type == "static") and (not vm_context == sec_label):
raise error.TestFail("Label of VM is not expected after starting.\n"
"Detail: vm_context=%s, sec_label=%s"
% (vm_context, sec_label))
disk_context = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (sec_relabel == "no") and (not disk_context == img_label):
raise error.TestFail("Label of disk is not expected after VM "
"starting.\n"
"Detail: disk_context=%s, img_label=%s."
% (disk_context, img_label))
if sec_relabel == "yes":
vmxml = VMXML.new_from_dumpxml(vm_name)
imagelabel = vmxml.get_seclabel()['imagelabel']
if not disk_context == imagelabel:
raise error.TestFail("Label of disk is not relabeled by VM\n"
"Detal: disk_context=%s, imagelabel=%s"
% (disk_context, imagelabel))
# Check the label of disk after VM being destroyed.
vm.destroy()
img_label_after = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (not img_label_after == img_label):
raise error.TestFail("Bug: Label of disk is not restored in VM "
"shuting down.\n"
"Detail: img_label_after=%s, "
"img_label_before=%s.\n"
% (img_label_after, img_label))
except virt_vm.VMStartError, e:
# Starting VM failed.
# VM with seclabel can not access the image with the context.
if not status_error:
raise error.TestFail("Test failed in positive case."
"error: %s" % e)
finally:
# clean up
for path, label in backup_labels_of_disks.items():
utils_selinux.set_context_of_file(filename=path, context=label)
backup_xml.sync()
utils_selinux.set_status(backup_sestatus)
示例8: run_libvirt_network_bandwidth
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_libvirt_network_bandwidth(test, params, env):
"""
Test for network bandwidth in libvirt.
1. Preparation:
* Init variables from params.
* Keep a backup for vmxml and networkxml.
* Build a file with dd command.
2. Edit vmxml and networkxml to control the bandwidth.
3. Verify the bandwidth with scp.
4. Clean up.
"""
# get the params from params
vm_name = params.get("main_vm", "virt-tests-vm1")
vm = env.get_vm(vm_name)
inbound_average = params.get("LNB_inbound_average", "512")
inbound_peak = params.get("LNB_inbound_peak", "512")
inbound_burst = params.get("LNB_inbound_burst", "32")
outbound_average = params.get("LNB_outbound_average", "512")
outbound_peak = params.get("LNB_outbound_peak", "512")
outbound_burst = params.get("LNB_outbound_burst", "32")
config_type = params.get("LNB_config_type", "network")
bandwidth_tolerance = float(params.get("LNB_bandwidth_tolerance", "20"))/100
file_size = params.get("LNB_verify_file_size", "10")
nic1_params = params.object_params('nic1')
nettype = params.get('nettype')
netdst = params.get('netdst')
vm_xml = VMXML.new_from_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
# This test assume that VM is using default network.
# Check the interfaces of VM to make sure default network
# is used by VM.
interfaces = vm_xml.get_devices(device_type="interface")
# interface which is using default network.
default_interface = None
for interface in interfaces:
if interface.source == {nettype: netdst}:
default_interface = interface
break
if not default_interface:
raise error.TestNAError("VM is not using default network,"
"skip this test.")
bandwidth_inbound = {'average': inbound_average,
'peak': inbound_peak,
'burst': inbound_burst}
bandwidth_outbound = {'average': outbound_average,
'peak': outbound_peak,
'burst': outbound_burst}
network_xml = NetworkXML.new_from_net_dumpxml("default")
network_xml_backup = network_xml.copy()
tmp_dir = data_dir.get_tmp_dir()
file_path = os.path.join(tmp_dir, "scp_file")
# Init a QemuImg instance.
cmd = "dd if=/dev/zero of=%s bs=1M count=%s" % (file_path, file_size)
utils.run(cmd)
try:
if config_type == "network":
network_xml.bandwidth_inbound = bandwidth_inbound
network_xml.bandwidth_outbound = bandwidth_outbound
network_xml.sync()
elif config_type == "interface":
devices = vm_xml.devices
for index in range(len(devices)):
if not (devices[index].device_tag ==
default_interface.device_tag):
continue
if devices[index].mac_address == default_interface.mac_address:
default_interface.bandwidth_inbound = bandwidth_inbound
default_interface.bandwidth_outbound = bandwidth_outbound
devices[index] = default_interface
break
vm_xml.devices = devices
vm_xml.sync()
elif config_type == "portgroup":
# Add a portgroup into default network
portgroup_name = "test_portgroup"
portgroup = PortgroupXML()
portgroup.name = portgroup_name
portgroup.bandwidth_inbound = bandwidth_inbound
portgroup.bandwidth_outbound = bandwidth_outbound
network_xml.portgroup = portgroup
network_xml.sync()
# Using the portgroup in VM.
devices = vm_xml.devices
for index in range(len(devices)):
if not (devices[index].device_tag ==
default_interface.device_tag):
continue
if devices[index].mac_address == default_interface.mac_address:
#.........这里部分代码省略.........
示例9: run_libvirt_scsi
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_libvirt_scsi(test, params, env):
# Get variables.
status_error = ('yes' == params.get("status_error", 'no'))
img_type = ('yes' == params.get("libvirt_scsi_img_type", "no"))
cdrom_type = ('yes' == params.get("libvirt_scsi_cdrom_type", "no"))
partition_type = ('yes' == params.get("libvirt_scsi_partition_type", "no"))
partition = params.get("libvirt_scsi_partition",
"ENTER.YOUR.AVAILIBLE.PARTITION")
vm_name = params.get("main_vm", "virt-tests-vm1")
# Init a VM instance and a VMXML instance.
vm = env.get_vm(vm_name)
vmxml = VMXML.new_from_dumpxml(vm_name)
# Keep a backup of xml to restore it in cleanup.
backup_xml = vmxml.copy()
# Add a scsi controller if there is not.
controller_devices = vmxml.get_devices("controller")
scsi_controller_exists = False
for device in controller_devices:
if device.type == "scsi":
scsi_controller_exists = True
break
if not scsi_controller_exists:
scsi_controller = Controller("controller")
scsi_controller.type = "scsi"
scsi_controller.index = "0"
scsi_controller.model = "virtio-scsi"
vmxml.add_device(scsi_controller)
# Add disk with bus of scsi into vmxml.
if img_type:
# Init a QemuImg instance.
img_name = "libvirt_scsi"
params['image_name'] = img_name
image = qemu_storage.QemuImg(params, data_dir.get_tmp_dir(), img_name)
# Create a image.
img_path, _ = image.create(params)
img_disk = Disk(type_name="file")
img_disk.device = "disk"
img_disk.source = img_disk.new_disk_source(
**{'attrs': {'file': img_path}})
img_disk.target = {'dev': "vde",
'bus': "scsi"}
vmxml.add_device(img_disk)
if cdrom_type:
# Init a CdromDisk instance.
cdrom_path = os.path.join(data_dir.get_tmp_dir(), "libvirt_scsi")
cdrom = CdromDisk(cdrom_path, data_dir.get_tmp_dir())
cdrom.close()
cdrom_disk = Disk(type_name="file")
cdrom_disk.device = "cdrom"
cdrom_disk.target = {'dev': "vdf",
'bus': "scsi"}
cdrom_disk.source = cdrom_disk.new_disk_source(
**{'attrs': {'file': cdrom_path}})
vmxml.add_device(cdrom_disk)
if partition_type:
if partition.count("ENTER.YOUR"):
raise error.TestNAError("Partition for partition test"
"is not configured.")
partition_disk = Disk(type_name="block")
partition_disk.device = "disk"
partition_disk.target = {'dev': "vdg",
'bus': "scsi"}
partition_disk.source = partition_disk.new_disk_source(
**{'attrs': {'dev': partition}})
vmxml.add_device(partition_disk)
# sync the vmxml with VM.
vmxml.sync()
# Check the result of scsi disk.
try:
try:
vm.start()
# Start VM successfully.
if status_error:
raise error.TestFail('Starting VM successed in negative case.')
except virt_vm.VMStartError, e:
# Starting VM failed.
if not status_error:
raise error.TestFail("Test failed in positive case."
"error: %s" % e)
finally:
# clean up.
backup_xml.sync()
示例10: check_xml
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def check_xml():
"""
Predict the result serial device and generated console device
and check the result domain XML against expectation
"""
console_cls = librarian.get('console')
local_serial_type = serial_type
if serial_type == 'tls':
local_serial_type = 'tcp'
# Predict expected serial and console XML
expected_console = console_cls(local_serial_type)
if local_serial_type == 'udp':
sources = []
for source in serial_dev.sources:
if 'service' in source and 'mode' not in source:
source['mode'] = 'connect'
sources.append(source)
else:
sources = serial_dev.sources
expected_console.sources = sources
if local_serial_type == 'tcp':
if 'protocol_type' in local_serial_type:
expected_console.protocol_type = serial_dev.protocol_type
else:
expected_console.protocol_type = "raw"
expected_console.target_port = serial_dev.target_port
if 'target_type' in serial_dev:
expected_console.target_type = serial_dev.target_type
expected_console.target_type = console_target_type
logging.debug("Expected console XML is:\n%s", expected_console)
# Get current serial and console XML
current_xml = VMXML.new_from_dumpxml(vm_name)
serial_elem = current_xml.xmltreefile.find('devices/serial')
console_elem = current_xml.xmltreefile.find('devices/console')
if console_elem is None:
test.fail("Expect generate console automatically, "
"but found none.")
if serial_elem and console_target_type != 'serial':
test.fail("Don't Expect exist serial device, "
"but found:\n%s" % serial_elem)
cur_console = console_cls.new_from_element(console_elem)
logging.debug("Current console XML is:\n%s", cur_console)
# Compare current serial and console with oracle.
if not expected_console == cur_console:
# "==" has been override
test.fail("Expect generate console:\n%s\nBut got:\n%s" %
(expected_console, cur_console))
if console_target_type == 'serial':
serial_cls = librarian.get('serial')
expected_serial = serial_cls(local_serial_type)
expected_serial.sources = sources
set_targets(expected_serial)
if local_serial_type == 'tcp':
if 'protocol_type' in local_serial_type:
expected_serial.protocol_type = serial_dev.protocol_type
else:
expected_serial.protocol_type = "raw"
expected_serial.target_port = serial_dev.target_port
if serial_elem is None:
test.fail("Expect exist serial device, "
"but found none.")
cur_serial = serial_cls.new_from_element(serial_elem)
if target_type == 'pci-serial':
if cur_serial.address is None:
test.fail("Expect serial device address is not assigned")
else:
logging.debug("Serial address is: %s", cur_serial.address)
logging.debug("Expected serial XML is:\n%s", expected_serial)
logging.debug("Current serial XML is:\n%s", cur_serial)
# Compare current serial and console with oracle.
if target_type != 'pci-serial' and not expected_serial == cur_serial:
# "==" has been override
test.fail("Expect serial device:\n%s\nBut got:\n "
"%s" % (expected_serial, cur_serial))
示例11: run
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
#.........这里部分代码省略.........
if dev.type == 'pci' and dev.model == pci_model]
if not cur_pci_br:
test.error('Failed to add %s controller to vm xml' % pci_model)
pci_br = cur_pci_br[0]
logging.debug('pci_br: %s', pci_br)
pci_br_index = pci_br.index
# If test scenario requires another pci device on pci/pcie-to-pci
# bridge before hotplug, add a sound device and make sure
# the 'bus' is same with pci bridge index
if need_pci_br and pci_br_has_device:
sound_dev = Sound()
sound_dev.model_type = sound_dev_model_type
sound_dev.address = eval(sound_dev_address % pci_br_index)
logging.debug('sound_dev.address: %s', sound_dev.address)
vmxml.add_device(sound_dev)
if case != 'vm_with_pcie_br_1_br':
vmxml.sync()
# Test hotplug scenario
if hotplug:
vm.start()
vm.wait_for_login().close()
# Create interface to be hotplugged
logging.info('Create interface to be hotplugged')
iface = create_iface(iface_model, iface_source)
mac = iface.mac_address
result = virsh.attach_device(vm_name, iface.xml, debug=True)
libvirt.check_exit_status(result)
xml_after_attach = VMXML.new_from_dumpxml(vm_name)
logging.debug(virsh.dumpxml(vm_name))
# Check if the iface with given mac address is successfully
# attached with address bus equal to pcie/pci bridge's index
iface_list = [
iface for iface in xml_after_attach.get_devices('interface')
if iface.mac_address == mac and
int(iface.address['attrs']['bus'], 16) == int(pci_br_index, 16)
]
logging.debug('iface list after attach: %s', iface_list)
if not iface_list:
test.error('Failed to attach interface %s' % iface)
# Check inside vm
def check_inside_vm(session, expect=True):
ip_output = session.cmd('ip a')
logging.debug('output of "ip a": %s', ip_output)
return expect if mac in ip_output else not expect
session = vm.wait_for_serial_login()
if not utils_misc.wait_for(lambda: check_inside_vm(session, True),
timeout=60, step=5):
test.fail('Check interface inside vm failed,'
'interface not successfully attached:'
'not found mac address %s' % mac)
session.close()
# Test hotunplug
result = virsh.detach_device(vm_name, iface.xml, debug=True)
libvirt.check_exit_status(result)
示例12: run
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
#.........这里部分代码省略.........
stat_re.st_gid)
# Backup selinux of host.
backup_sestatus = utils_selinux.get_status()
qemu_conf = utils_config.LibvirtQemuConfig()
libvirtd = utils_libvirtd.Libvirtd()
try:
# Set disk label
for disk in disks.values():
disk_path = disk['source']
utils_selinux.set_context_of_file(filename=disk_path,
context=img_label)
os.chown(disk_path, 107, 107)
# Set selinux of host.
utils_selinux.set_status(host_sestatus)
# Set qemu conf
if security_driver:
qemu_conf.set_string('security_driver', security_driver)
if security_default_confined:
qemu_conf.security_default_confined = security_default_confined
if security_require_confined:
qemu_conf.security_require_confined = security_require_confined
if (security_driver or security_default_confined or
security_require_confined):
logging.debug("the qemu.conf content is: %s" % qemu_conf)
libvirtd.restart()
# Set the context of the VM.
vmxml.set_seclabel(sec_dict_list)
vmxml.sync()
logging.debug("the domain xml is: %s" % vmxml.xmltreefile)
# Start VM to check the VM is able to access the image or not.
try:
vm.start()
# Start VM successfully.
# VM with seclabel can access the image with the context.
if status_error:
raise error.TestFail("Test succeeded in negative case.")
# Check the label of VM and image when VM is running.
vm_context = utils_selinux.get_context_of_process(vm.get_pid())
if (sec_type == "static") and (not vm_context == sec_label):
raise error.TestFail("Label of VM is not expected after "
"starting.\n"
"Detail: vm_context=%s, sec_label=%s"
% (vm_context, sec_label))
disk_context = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (sec_relabel == "no") and (not disk_context == img_label):
raise error.TestFail("Label of disk is not expected after VM "
"starting.\n"
"Detail: disk_context=%s, img_label=%s."
% (disk_context, img_label))
if sec_relabel == "yes" and not no_sec_model:
vmxml = VMXML.new_from_dumpxml(vm_name)
imagelabel = vmxml.get_seclabel()[0]['imagelabel']
if not disk_context == imagelabel:
raise error.TestFail("Label of disk is not relabeled by "
"VM\nDetal: disk_context="
"%s, imagelabel=%s"
% (disk_context, imagelabel))
# Check the label of disk after VM being destroyed.
if poweroff_with_destroy:
vm.destroy(gracefully=False)
else:
vm.wait_for_login()
vm.shutdown()
img_label_after = utils_selinux.get_context_of_file(
filename=disks.values()[0]['source'])
if (not img_label_after == img_label):
# Bug 547546 - RFE: the security drivers must remember original
# permissions/labels and restore them after
# https://bugzilla.redhat.com/show_bug.cgi?id=547546
err_msg = "Label of disk is not restored in VM shuting down.\n"
err_msg += "Detail: img_label_after=%s, " % img_label_after
err_msg += "img_label_before=%s.\n" % img_label
err_msg += "More info in https://bugzilla.redhat.com/show_bug"
err_msg += ".cgi?id=547546"
raise error.TestFail(err_msg)
except virt_vm.VMStartError, e:
# Starting VM failed.
# VM with seclabel can not access the image with the context.
if not status_error:
raise error.TestFail("Test failed in positive case."
"error: %s" % e)
finally:
# clean up
for path, label in backup_labels_of_disks.items():
utils_selinux.set_context_of_file(filename=path, context=label)
for path, label in backup_ownership_of_disks.items():
label_list = label.split(":")
os.chown(path, int(label_list[0]), int(label_list[1]))
backup_xml.sync()
utils_selinux.set_status(backup_sestatus)
if (security_driver or security_default_confined or
security_require_confined):
qemu_conf.restore()
libvirtd.restart()
示例13: run
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run(test, params, env):
"""
Test the sound virtual devices
1. prepare a guest with different sound devices
2. check whether the guest can be started
3. check the xml and qemu cmd line
"""
# Sound element supported since 0.4.3.
if not libvirt_version.version_compare(0, 4, 3):
test.cancel("Sound device is not supported "
"on current version.")
# Codec sub-element supported since 0.9.13
codec_type = params.get("codec_type", None)
if codec_type and not libvirt_version.version_compare(0, 9, 13):
test.cancel("codec sub-element is not supported "
"on current version.")
def check_dumpxml():
"""
Check whether the added devices are shown in the guest xml
"""
pattern = "<sound model=\"%s\">" % sound_model
# Check sound model
xml_after_adding_device = VMXML.new_from_dumpxml(vm_name)
if pattern not in str(xml_after_adding_device):
test.fail("Can not find the %s sound device xml "
"in the guest xml file." % sound_model)
# Check codec type
if codec_type:
pattern = "<codec type=\"%s\" />" % codec_type
if pattern not in str(xml_after_adding_device):
test.fail("Can not find the %s codec xml for sound dev "
"in the guest xml file." % codec_type)
def check_qemu_cmd_line():
"""
Check whether the added devices are shown in the qemu cmd line
"""
if not vm.get_pid():
test.fail('VM pid file missing.')
with open('/proc/%s/cmdline' % vm.get_pid()) as cmdline_file:
cmdline = cmdline_file.read()
# Check sound model
if sound_model == "ac97":
pattern = r"-device.AC97"
elif sound_model == "ich6":
pattern = r"-device.intel-hda"
else:
pattern = r"-device.ich9-intel-hda"
if not re.search(pattern, cmdline):
test.fail("Can not find the %s sound device "
"in qemu cmd line." % sound_model)
# Check codec type
if sound_model in ["ich6", "ich9"]:
if codec_type == "micro":
pattern = r"-device.hda-micro"
else:
# Duplex is default in qemu cli even codec not set
# But before 0.9.13, no codec_type so no default
if libvirt_version.version_compare(0, 9, 13):
pattern = r"-device.hda-duplex"
if not re.search(pattern, cmdline):
test.fail("Can not find the %s codec for sound dev "
"in qemu cmd line." % codec_type)
vm_name = params.get("main_vm", "avocado-vt-vm1")
vm = env.get_vm(vm_name)
status_error = params.get("status_error", "no") == "yes"
sound_model = params.get("sound_model")
# AC97 sound model supported since 0.6.0
if sound_model == "ac97":
if not libvirt_version.version_compare(0, 6, 0):
test.cancel("ac97 sound model is not supported "
"on current version.")
# Ich6 sound model supported since 0.8.8
if sound_model == "ich6":
if not libvirt_version.version_compare(0, 8, 8):
test.cancel("ich6 sound model is not supported "
"on current version.")
# Ich9 sound model supported since 1.1.3
if sound_model == "ich9":
if not libvirt_version.version_compare(1, 1, 3):
test.cancel("ich9 sound model is not supported "
"on current version.")
vm_xml = VMXML.new_from_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
logging.debug("vm xml is %s", vm_xml_backup)
if vm.is_alive():
vm.destroy()
try:
vm_xml.remove_all_device_by_type('sound')
sound_dev = Sound()
sound_dev.model_type = sound_model
if codec_type:
sound_dev.codec_type = codec_type
#.........这里部分代码省略.........
示例14: run_svirt_save_restore
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_svirt_save_restore(test, params, env):
"""
Test svirt in adding disk to VM.
(1).Init variables for test.
(2).Label the VM and disk with proper label.
(3).Save VM and check the context.
(4).Restore VM and check the context.
"""
# Get general variables.
status_error = "yes" == params.get("status_error", "no")
host_sestatus = params.get("svirt_save_restore_host_selinux", "enforcing")
# Get variables about seclabel for VM.
sec_type = params.get("svirt_save_restore_vm_sec_type", "dynamic")
sec_model = params.get("svirt_save_restore_vm_sec_model", "selinux")
sec_label = params.get("svirt_save_restore_vm_sec_label", None)
sec_relabel = params.get("svirt_save_restore_vm_sec_relabel", "yes")
sec_dict = {"type": sec_type, "model": sec_model, "label": sec_label, "relabel": sec_relabel}
# Get variables about VM and get a VM object and VMXML instance.
vm_name = params.get("main_vm")
vm = env.get_vm(vm_name)
vmxml = VMXML.new_from_dumpxml(vm_name)
backup_xml = vmxml.copy()
# Get varialbles about image.
img_label = params.get("svirt_save_restore_disk_label")
# Label the disks of VM with img_label.
disks = vm.get_disk_devices()
backup_labels_of_disks = {}
for disk in disks.values():
disk_path = disk["source"]
backup_labels_of_disks[disk_path] = utils_selinux.get_context_of_file(filename=disk_path)
utils_selinux.set_context_of_file(filename=disk_path, context=img_label)
# Set selinux of host.
backup_sestatus = utils_selinux.get_status()
utils_selinux.set_status(host_sestatus)
# Set the context of the VM.
vmxml.set_seclabel(sec_dict)
vmxml.sync()
# Init a path to save VM.
save_path = os.path.join(test.tmpdir, "svirt_save")
try:
# Start VM to check the VM is able to access the image or not.
try:
vm.start()
vm.save_to_file(path=save_path)
vm.restore_from_file(path=save_path)
# Save and restore VM successfully.
if status_error:
raise error.TestFail("Test successed in negative case.")
except virt_vm.VMError, e:
if not status_error:
error_msg = "Test failed in positive case.\n error: %s\n" % e
if str(e).count("getfd"):
error_msg += "More info pleass refer to" " https://bugzilla.redhat.com/show_bug.cgi?id=976632"
raise error.TestFail(error_msg)
finally:
# clean up
for path, label in backup_labels_of_disks.items():
utils_selinux.set_context_of_file(filename=path, context=label)
backup_xml.sync()
utils_selinux.set_status(backup_sestatus)
示例15: run_virsh_attach_device
# 需要导入模块: from virttest.libvirt_xml.vm_xml import VMXML [as 别名]
# 或者: from virttest.libvirt_xml.vm_xml.VMXML import new_from_dumpxml [as 别名]
def run_virsh_attach_device(test, params, env):
"""
Test virsh {at|de}tach-interface command.
1) Prepare test environment and its parameters
2) Operate virsh on one or more devices
3) Check functionality of each device
4) Check functionality of mmconfig option
5) Restore domain
6) Handle results
"""
logging.info("Preparing initial VM state")
# Prepare test environment and its parameters
test_params = TestParams(params, env, test)
if test_params.start_vm:
# Make sure VM is working
test_params.main_vm.verify_alive()
test_params.main_vm.wait_for_login().close()
else: # VM not suppose to be started
if test_params.main_vm.is_alive():
test_params.main_vm.destroy(gracefully=True)
# Capture backup of original XML early in test
test_params.vmxml = VMXML.new_from_dumpxml(test_params.main_vm.name)
# All devices should share same access state
test_params.virsh = virsh.Virsh(ignore_status=True)
logging.info("Creating %d test device instances", len(test_params.devs))
# Create test objects from cfg. class names via subclasses above
test_devices = [globals()[class_name](test_params) # instantiate
for class_name in test_params.devs] # vadu_dev_objs
operational_results = []
preboot_results = []
pstboot_results = []
try:
operational_action(test_params, test_devices, operational_results)
# Can't do functional testing with a cold VM, only test hot-attach
preboot_action(test_params, test_devices, preboot_results)
logging.info("Preparing test VM state for post-boot functional testing")
if test_params.start_vm:
# Hard-reboot required
test_params.main_vm.destroy(gracefully=True,
free_mac_addresses=False)
try:
test_params.main_vm.start()
except virt_vm.VMStartError:
raise error.TestFail('VM Failed to start for some reason!')
# Signal devices reboot is finished
for test_device in test_devices:
test_device.booted = True
test_params.main_vm.wait_for_login().close()
postboot_action(test_params, test_devices, pstboot_results)
analyze_results(test_params, operational_results,
preboot_results, pstboot_results)
finally:
logging.info("Restoring VM from backup, then checking results")
test_params.main_vm.destroy(gracefully=False,
free_mac_addresses=False)
test_params.vmxml.undefine()
test_params.vmxml.restore() # Recover the original XML
test_params.vmxml.define()
if not test_params.start_vm:
# Test began with not start_vm, shut it down.
test_params.main_vm.destroy(gracefully=True)
# Device cleanup can raise multiple exceptions, do it last:
logging.info("Cleaning up test devices")
test_params.cleanup(test_devices)