本文整理汇总了Python中virttest.libvirt_xml.vm_xml.VMXML类的典型用法代码示例。如果您正苦于以下问题:Python VMXML类的具体用法?Python VMXML怎么用?Python VMXML使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VMXML类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: configure_serial_console
def configure_serial_console(vm_name):
"""Configure serial console"""
# Check the primary serial and set it to pty.
VMXML.set_primary_serial(vm_name, 'pty', '0', None)
# Configure VM pty console.
vm_pty_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_pty_xml.remove_all_device_by_type('console')
console = Console()
console.target_port = '0'
console.target_type = 'serial'
vm_pty_xml.add_device(console)
vm_pty_xml.sync()
示例2: _find_comm_paths
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
示例3: run_mix_boot_order_os_boot
def run_mix_boot_order_os_boot(params, libvirtd, vm):
"""
Define a domain mixing boot device and disk boot order.
"""
vm_name = vm.name
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
try:
if not vm_xml.os.boots:
os_xml = vm_xml.os
os_xml.boots = {'dev': 'hd'}
vm_xml.os = os_xml
else:
logging.debug(vm_xml.os.boots)
order = 0
devices = vm_xml.devices
for device in devices:
if device.device_tag == 'disk':
device.boot = order
order += 1
vm_xml.devices = devices
try:
vm_xml.sync()
except LibvirtXMLError:
pass
finally:
vm_xml_backup.sync()
示例4: run
def run(test, params, env):
"""
Test svirt in virt-clone.
"""
VIRT_CLONE = None
try:
VIRT_CLONE = utils_misc.find_command("virt-clone")
except ValueError:
raise error.TestNAError("No virt-clone command found.")
# Get general variables.
status_error = ('yes' == params.get("status_error", 'no'))
host_sestatus = params.get("svirt_virt_clone_host_selinux", "enforcing")
# Get variables about seclabel for VM.
sec_type = params.get("svirt_virt_clone_vm_sec_type", "dynamic")
sec_model = params.get("svirt_virt_clone_vm_sec_model", "selinux")
sec_label = params.get("svirt_virt_clone_vm_sec_label", None)
sec_relabel = params.get("svirt_virt_clone_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_virt_clone_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()
clone_name = ("%s-clone" % vm.name)
try:
cmd = ("%s --original %s --name %s --auto-clone" %
(VIRT_CLONE, vm.name, clone_name))
cmd_result = utils.run(cmd, ignore_status=True)
if cmd_result.exit_status:
raise error.TestFail("Failed to execute virt-clone command."
"Detail: %s." % cmd_result)
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)
if not virsh.domstate(clone_name).exit_status:
libvirt_vm.VM(clone_name, params, None, None).remove_with_storage()
示例5: run
def run(test, params, env):
"""
Test for adding controller for usb.
"""
# get the params from params
vm_name = params.get("main_vm", "avocado-vt-vm1")
vm = env.get_vm(vm_name)
index = params.get("index", "1")
index_conflict = "yes" == params.get("index_conflict", "no")
model = params.get("model", "nec-xhci")
status_error = "yes" == params.get("status_error", "no")
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
controllers = vm_xml.get_devices(device_type="controller")
devices = vm_xml.get_devices()
for dev in controllers:
if dev.type == "usb":
devices.remove(dev)
controller = Controller("controller")
controller.type = "usb"
controller.index = index
controller.model = model
devices.append(controller)
if index_conflict:
controller_1 = Controller("controller")
controller_1.type = "usb"
controller_1.index = index
devices.append(controller)
vm_xml.set_devices(devices)
try:
try:
vm_xml.sync()
vm.start()
if status_error:
raise error.TestFail("Add controller successfully in negative case.")
else:
try:
session = vm.wait_for_login()
except (LoginError, ShellError), e:
error_msg = "Test failed in positive case.\n error: %s\n" % e
raise error.TestFail(error_msg)
cmd = "dmesg -c | grep %s" % model.split('-')[-1]
stat_dmesg = session.cmd_status(cmd)
if stat_dmesg != 0:
raise error.TestNAError("Fail to run dmesg in guest")
session.close()
except (LibvirtXMLError, VMStartError), e:
if not status_error:
raise error.TestFail("Add controller failed. Detail: %s" % e)
finally:
vm_xml_backup.sync()
示例6: _check_xml
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))
示例7: run
def run(test, params, env):
"""
Test of libvirt SPICE related features.
1) Block specified ports if required;
2) Setup SPICE TLS certification if required;
3) Setup graphics tag in VM;
4) Try to start VM;
5) Parse and check result with expected.
6) Clean up environment.
"""
vm_name = params.get("main_vm", "virt-tests-vm1")
spice_xml = params.get("spice_xml", "no") == 'yes'
vnc_xml = params.get("vnc_xml", "no") == 'yes'
vm = env.get_vm(vm_name)
if vm.is_alive():
vm.destroy()
sockets = block_ports(params)
networks = setup_networks(params)
expected_result = get_expected_results(params, networks)
env_state = EnvState(params, expected_result)
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
try:
vm_xml.remove_all_graphics()
if spice_xml:
spice_graphic = generate_spice_graphic_xml(params, expected_result)
logging.debug('Test SPICE XML is: %s', spice_graphic)
vm_xml.devices = vm_xml.devices.append(spice_graphic)
if vnc_xml:
vnc_graphic = generate_vnc_graphic_xml(params, expected_result)
logging.debug('Test VNC XML is: %s', vnc_graphic)
vm_xml.devices = vm_xml.devices.append(vnc_graphic)
vm_xml.sync()
all_ips = utils_net.get_all_ips()
fail_patts = expected_result['fail_patts']
try:
vm.start()
except virt_vm.VMStartError, detail:
if not fail_patts:
raise error.TestFail(
"Expect VM can be started, but failed with: %s" % detail)
for patt in fail_patts:
if re.search(patt, str(detail)):
return
raise error.TestFail(
"Expect fail with error in %s, but failed with: %s"
% (fail_patts, detail))
else:
示例8: check_dumpxml
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)
示例9: run_invalid_interface
def run_invalid_interface(params, libvirtd, vm):
"""
Define a domain with an invalid interface device.
"""
vm_name = vm.name
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
try:
iface_xml = interface.Interface('bridge')
iface_xml.set_target({'dev': 'vnet'})
devices = vm_xml.devices
devices.append(iface_xml)
vm_xml.devices = devices
try:
vm_xml.sync()
except LibvirtXMLError:
pass
finally:
vm_xml_backup.sync()
示例10: run
def run(test, params, env):
"""
Test for hotplug usb device.
"""
# get the params from params
vm_name = params.get("main_vm", "virt-tests-vm1")
vm = env.get_vm(vm_name)
usb_type = params.get("usb_type", "kbd")
attach_type = params.get("attach_type", "attach_device")
attach_count = int(params.get("attach_count", "1"))
if usb_type == "storage":
model = params.get("model", "nec-xhci")
index = params.get("index", "1")
status_error = "yes" == params.get("status_error", "no")
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
# Set selinux of host.
backup_sestatus = utils_selinux.get_status()
utils_selinux.set_status("permissive")
if usb_type == "storage":
controllers = vm_xml.get_devices(device_type="controller")
devices = vm_xml.get_devices()
for dev in controllers:
if dev.type == "usb" and dev.index == "1":
devices.remove(dev)
controller = Controller("controller")
controller.type = "usb"
controller.index = index
controller.model = model
devices.append(controller)
vm_xml.set_devices(devices)
try:
session = vm.wait_for_login()
except (LoginError, VMError, ShellError), e:
raise error.TestFail("Test failed: %s" % str(e))
示例11: get_controller_addr
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
示例12: run_pm_test
def run_pm_test(params, libvirtd, vm):
"""
Destroy VM after executed a series of operations about S3 and save restore
"""
vm_name = vm.name
vm_xml = VMXML.new_from_inactive_dumpxml(vm_name)
vm_xml_backup = vm_xml.copy()
save_path = os.path.join(data_dir.get_tmp_dir(), 'tmp.save')
try:
pm_xml = VMPMXML()
pm_xml.mem_enabled = 'yes'
vm_xml.pm = pm_xml
vm_xml.sync()
vm.prepare_guest_agent()
virsh.dompmsuspend(vm.name, 'mem')
virsh.dompmwakeup(vm.name)
virsh.save(vm.name, save_path)
virsh.restore(save_path)
virsh.dompmsuspend(vm.name, 'mem')
virsh.save(vm.name, save_path)
virsh.destroy(vm.name)
finally:
vm_xml_backup.sync()
示例13: run
def run(test, params, env):
"""
Test for PCI device passthrough to libvirt guest.
a). NIC:
1. Get params.
2. Get the pci device for specific net_name.
3. Attach pci device to guest.
4. Start guest and set the ip of guest.
5. Ping the server_ip of from guest
to verify the new network device.
b). STORAGE:
1. Get params.
2. Get the pci device for specific storage_dev_name.
3. Store the result of 'fdisk -l' on guest.
3. Attach pci device to guest.
4. Start guest and get the result of 'fdisk -l' on guest.
5. Compare the result of 'fdisk -l' before and after
attaching storage pci device to guest.
"""
# get the params from params
vm_name = params.get("main_vm")
vm = env.get_vm(vm_name)
sriov = ('yes' == params.get("libvirt_pci_SRIOV", 'no'))
device_type = params.get("libvirt_pci_device_type", "NIC")
net_name = params.get("libvirt_pci_net_name", "eth0")
server_ip = params.get("libvirt_pci_server_ip")
storage_dev_name = params.get("libvirt_pci_storage_dev_name", "/dev/sdb")
fdisk_list_before = None
vmxml = VMXML.new_from_inactive_dumpxml(vm_name)
backup_xml = vmxml.copy()
pci_address = None
if device_type == "NIC":
# Find the pci device for given network device.
result = virsh.nodedev_list(cap="net")
nodedev_nets = result.stdout.strip().splitlines()
device = None
for nodedev in nodedev_nets:
netxml = NodedevXML.new_from_dumpxml(nodedev)
if netxml.cap.interface == net_name:
device = nodedev
break
if not device:
raise error.TestNAError("There is no network device name of %s." %
net_name)
pci_dev = netxml.parent
if sriov:
# set the parameter max_vfs of igb module to 7. Then we can use
# the virtual function pci device for network device.
# command 'modprobe -r igb' to unload igb module
# command '&& modprobe igb max_vfs=7' to load it again
# with max_vfs=7
# command '|| echo 'FAIL' > output_file' is a flag to mean
# modprobe igb with max_vfs=7 failed.
# command '|| modprobe igb' is a handler of error occured
# when we load igb again. If command 2 failed,
# this command will be executed to recover network.
output_file = os.path.join(test.tmpdir, "output")
if os.path.exists(output_file):
os.remove(output_file)
mod_cmd = ("modprobe -r igb && modprobe igb max_vfs=7 ||"
"echo 'FAIL' > %s && modprobe igb &" % output_file)
result = utils.run(mod_cmd, ignore_status=True)
if os.path.exists(output_file):
raise error.TestError("Failed to modprobe igb with max_vfs=7.")
# Get the virtual function pci device which was generated above.
pci_xml = NodedevXML.new_from_dumpxml(pci_dev)
virt_functions = pci_xml.cap.virt_functions
if not virt_functions:
raise error.TestError("Init virtual function failed.")
pci_address = virt_functions[0]
pci_dev = utils_test.libvirt.pci_label_from_address(pci_address,
radix=16)
# Find the network name (ethX) is using this pci device.
network_service = service.Factory.create_service("network")
network_service.restart()
result = virsh.nodedev_list("net")
nodedev_nets = result.stdout.strip().splitlines()
device = None
for nodedev in nodedev_nets:
netxml = NodedevXML.new_from_dumpxml(nodedev)
if netxml.parent == pci_dev:
device = nodedev
break
if not device:
raise error.TestNAError("There is no network name is using "
"Virtual Function PCI device %s." %
pci_dev)
pci_xml = NodedevXML.new_from_dumpxml(pci_dev)
pci_address = pci_xml.cap.get_address_dict()
#.........这里部分代码省略.........
示例14: run
def run(test, params, env):
"""
Test svirt in adding disk to VM.
(1).Init variables for test.
(2).Config qemu conf if need
(3).Label the VM and disk with proper label.
(4).Start VM and check the context.
(5).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_baselabel = params.get("svirt_start_destroy_vm_sec_baselabel", None)
security_driver = params.get("security_driver", None)
security_default_confined = params.get("security_default_confined", None)
security_require_confined = params.get("security_require_confined", None)
no_sec_model = 'yes' == params.get("no_sec_model", 'no')
sec_relabel = params.get("svirt_start_destroy_vm_sec_relabel", "yes")
sec_dict = {'type': sec_type, 'relabel': sec_relabel}
sec_dict_list = []
def _set_sec_model(model):
"""
Set sec_dict_list base on given sec model type
"""
sec_dict_copy = sec_dict.copy()
sec_dict_copy['model'] = model
if sec_type != "none":
if sec_type == "dynamic" and sec_baselabel:
sec_dict_copy['baselabel'] = sec_baselabel
else:
sec_dict_copy['label'] = sec_label
sec_dict_list.append(sec_dict_copy)
if not no_sec_model:
if "," in sec_model:
sec_models = sec_model.split(",")
for model in sec_models:
_set_sec_model(model)
else:
_set_sec_model(sec_model)
else:
sec_dict_list.append(sec_dict)
logging.debug("sec_dict_list is: %s" % sec_dict_list)
poweroff_with_destroy = ("destroy" == params.get(
"svirt_start_destroy_vm_poweroff", "destroy"))
# 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')
# Backup disk Labels.
disks = vm.get_disk_devices()
backup_labels_of_disks = {}
backup_ownership_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)
f = os.open(disk_path, 0)
stat_re = os.fstat(f)
backup_ownership_of_disks[disk_path] = "%s:%s" % (stat_re.st_uid,
stat_re.st_gid)
# Backup selinux of host.
backup_sestatus = utils_selinux.get_status()
qemu_conf = utils_config.LibvirtQemuConfig()
libvirtd = utils_libvirtd.Libvirtd()
def _resolve_label(label_string):
labels = label_string.split(":")
label_type = labels[2]
if len(labels) == 4:
label_range = labels[3]
elif len(labels) > 4:
label_range = "%s:%s" % (labels[3], labels[4])
else:
label_range = None
return (label_type, label_range)
def _check_label_equal(label1, label2):
label1s = label1.split(":")
label2s = label2.split(":")
for i in range(len(label1s)):
if label1s[i] != label2s[i]:
return False
return True
try:
# Set disk label
(img_label_type, img_label_range) = _resolve_label(img_label)
#.........这里部分代码省略.........
示例15: test_active_nodedev_reset
def test_active_nodedev_reset(device, vm, expect_succeed):
"""
Test nodedev-reset when the specified device is attached to a VM
:param devices : Specified node device to be tested.
:param vm : VM the device is to be attached to.
:param expect_succeed : 'yes' for expect command run successfully
and 'no' for fail.
:raise TestFail : If result doesn't meet expectation.
:raise TestError : If failed to recover environment.
"""
# Split device name such as `pci_0000_00_19_0` and fill the XML.
hostdev_xml = """
<hostdev mode='subsystem' type='%s' managed='yes'>
<source>
<address domain='0x%s' bus='0x%s' slot='0x%s' function='0x%s'/>
</source>
</hostdev>""" % tuple(device.split('_'))
try:
# The device need to be detached before attach to VM.
virsh.nodedev_detach(device)
try:
# Backup VM XML.
vmxml = VMXML.new_from_inactive_dumpxml(vm.name)
# Generate a temp file to store host device XML.
dev_fd, dev_fname = tempfile.mkstemp(dir=data_dir.get_tmp_dir())
os.close(dev_fd)
dev_file = open(dev_fname, 'w')
dev_file.write(hostdev_xml)
dev_file.close()
# Only live VM allows attach device.
if not vm.is_alive():
vm.start()
try:
result = virsh.attach_device(vm.name, dev_fname)
logging.debug(result)
test_nodedev_reset([device], expect_succeed)
finally:
# Detach device from VM.
result = virsh.detach_device(vm.name, dev_fname)
# Raise error when detach failed.
if result.exit_status:
raise error.TestError(
'Failed to dettach device %s from %s. Result:\n %s'
% (device, vm.name, result))
finally:
# Cleanup temp XML file and recover test VM.
os.remove(dev_fname)
vmxml.sync()
finally:
# Reattach node device
result = virsh.nodedev_reattach(device)
# Raise error when reattach failed.
if result.exit_status:
raise error.TestError(
'Failed to reattach nodedev %s. Result:\n %s'
% (device, result))