本文整理汇总了Python中virttest.virsh.undefine函数的典型用法代码示例。如果您正苦于以下问题:Python undefine函数的具体用法?Python undefine怎么用?Python undefine使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了undefine函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vm_undefine_check
def vm_undefine_check(vm_name):
"""
Check if vm can be undefined with manage-save option
"""
#backup xml file
xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
if not os.path.exists(managed_save_file):
raise error.TestFail("Can't find managed save image")
#undefine domain with no options.
if not virsh.undefine(vm_name, options=None,
ignore_status=True).exit_status:
raise error.TestFail("Guest shouldn't be undefined"
"while domain managed save image exists")
#undefine domain with managed-save option.
if virsh.undefine(vm_name, options="--managed-save",
ignore_status=True).exit_status:
raise error.TestFail("Guest can't be undefine with "
"managed-save option")
if os.path.exists(managed_save_file):
raise error.TestFail("Managed save image exists"
" after undefining vm")
#restore and start the vm.
xml_backup.define()
vm.start()
示例2: cleanup_vm
def cleanup_vm(vm_name=None, disk=None):
"""
Cleanup the vm with its disk deleted.
"""
try:
if vm_name is not None:
virsh.undefine(vm_name)
except error.CmdError, detail:
logging.error("Undefine %s failed:%s", vm_name, detail)
示例3: cleanup_vm
def cleanup_vm(vm_name=None):
"""
Cleanup the vm.
"""
try:
if vm_name is not None:
virsh.undefine(vm_name)
except error.CmdError:
pass
示例4: reset_env
def reset_env(vm_name, xml_file):
"""
Reset env
:param vm_name: the vm name
:xml_file: domain xml file
"""
virsh.destroy(vm_name)
virsh.undefine(vm_name)
virsh.define(xml_file)
if os.path.exists(xml_file):
os.remove(xml_file)
示例5: clean_clone_vm
def clean_clone_vm():
"""
Clean up cloned domain.
"""
try:
if virsh.domain_exists(vm_clone_name):
if virsh.is_alive(vm_clone_name):
virsh.destroy(vm_clone_name, ignore_status=False)
virsh.undefine(vm_clone_name, ignore_status=False)
if os.path.exists(clone_image):
os.remove(clone_image)
except error.CmdError, detail:
raise error.TestFail("Clean clone guest failed!:%s" % detail)
示例6: cleanup_vm
def cleanup_vm(vm_name=None, disk_removed=None):
"""
Cleanup the vm with its disk deleted.
"""
try:
if vm_name is not None:
virsh.undefine(vm_name)
except process.CmdError:
pass
try:
if disk_removed is not None:
os.remove(disk_removed)
except IOError:
pass
示例7: test_add_domain
def test_add_domain(vm, params):
"""
Test command add_domain:
"""
add_ref = params.get("gf_add_ref", "disk")
readonly = "yes" == params.get("gf_add_readonly")
gf = utils_test.libguestfs.GuestfishTools(params)
image_path = params.get("image_path")
pv_name = params.get("pv_name")
test_domain_name = "libguestfs_test_domain"
test_dir = params.get("img_dir", data_dir.get_tmp_dir())
test_xml = test_dir + '/test_domain.xml'
xml_content = "<domain type='kvm'>\n\
<memory>500000</memory>\n\
<name>%s</name>\n\
<vcpu>1</vcpu>\n\
<os>\n\
<type>hvm</type>\n\
<boot dev='hd'/>\n\
</os>\n\
<devices>\n\
<disk type='file' device='disk'>\n\
<source file='%s'/>\n\
<target dev='hda' bus='ide'/>\n\
</disk>\n\
</devices>\n\
</domain>\n\
" % (test_domain_name, image_path)
f = open(test_xml, "w")
f.write(xml_content)
f.close()
virsh.define(test_xml)
gf.add_domain(test_domain_name)
gf.run()
gf_result = gf.list_devices()
if '/dev/sd' not in gf_result.stdout:
gf.close_session()
logging.error(gf_result)
virsh.undefine(test_domain_name)
os.system('rm -f %s' % test_xml)
raise error.TestFail("test_add_domain failed")
gf.close_session()
virsh.undefine(test_domain_name)
os.system('rm -f %s' % test_xml)
示例8: run
def run(test, params, env):
"""
Test undefine after set preferred numa tuning
"""
bug_url = params.get("bug_url", "")
vm_name = params.get("main_vm")
backup_xml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)
# Prepare numatune memory parameter dict
mem_tuple = ('memory_mode', 'memory_placement', 'memory_nodeset')
numa_memory = {}
for mem_param in mem_tuple:
value = params.get(mem_param)
if value:
numa_memory[mem_param.split('_')[1]] = value
libvirtd = utils_libvirtd.Libvirtd()
libvirtd.start()
try:
vmxml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)
vmxml.numa_memory = numa_memory
logging.debug("vm xml is %s", vmxml)
vmxml.sync()
result = virsh.undefine(vm_name, debug=True, ignore_status=True)
if result.exit_status:
raise error.TestFail("Undefine vm failed, check %s" % bug_url)
finally:
libvirtd.restart()
backup_xml.sync()
示例9: remove
def remove(self, name):
dom = name
if dom['state'] != 'shut off':
res = virsh.destroy(dom['name'])
if res.exit_status:
raise Exception(str(res))
if dom['persistent'] == 'yes':
# Make sure the domain is remove anyway
res = virsh.undefine(
dom['name'], options='--snapshots-metadata --managed-save')
if res.exit_status:
raise Exception(str(res))
示例10: prepare_env
def prepare_env(self):
"""
Prepare the environment before all tests.
"""
print 'Running bootstrap'
self.bootstrap()
print 'Removing VM', # TODO: use virt-test api remove VM
sys.stdout.flush()
status, res, err_msg = self.run_test(
'remove_guest.without_disk', need_check=False)
if not 'PASS' in status:
virsh.undefine('virt-tests-vm1', '--snapshots-metadata')
print ' WARNING: Failed to remove guest'
print 'Installing VM',
sys.stdout.flush()
status, res, err_msg = self.run_test(
'unattended_install.import.import.default_install.aio_native',
restore_image=True, need_check=False)
if not 'PASS' in status:
raise Exception(' ERROR: Failed to install guest \n %s' %
res.stderr)
virsh.destroy('virt-tests-vm1')
示例11:
xml_exist = True
# Check if save file exists if use --managed-save
save_exist = False
if os.path.exists(save_file):
save_exist = True
# Check if save file exists if use --managed-save
volume_exist = False
if volume and os.path.exists(volume):
volume_exist = True
# Test define with acl control and recover domain.
if params.get('setup_libvirt_polkit') == 'yes':
if virsh.domain_exists(vm.name):
virsh.undefine(vm_ref, ignore_status=True)
cmd = "chmod 666 %s" % backup_xml.xml
utils.run(cmd, ignore_status=False)
s_define = virsh.define(backup_xml.xml,
unprivileged_user=unprivileged_user,
uri=uri, ignore_status=True, debug=True)
status3 = s_define.exit_status
finally:
# Recover main VM.
backup_xml.sync()
# Clean up pool
if pvtest:
pvtest.cleanup_pool(pool_name, pool_type,
pool_target, emulated_img)
示例12: run
def run(test, params, env):
"""
Test virsh undefine command.
Undefine an inactive domain, or convert persistent to transient.
1.Prepare test environment.
2.Backup the VM's information to a xml file.
3.When the libvirtd == "off", stop the libvirtd service.
4.Perform virsh undefine operation.
5.Recover test environment.(libvirts service,VM)
6.Confirm the test result.
"""
vm_ref = params.get("undefine_vm_ref", "vm_name")
extra = params.get("undefine_extra", "")
option = params.get("undefine_option", "")
libvirtd_state = params.get("libvirtd", "on")
status_error = ("yes" == params.get("status_error", "no"))
undefine_twice = ("yes" == params.get("undefine_twice", 'no'))
local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
remote_user = params.get("remote_user", "user")
remote_pwd = params.get("remote_pwd", "password")
remote_prompt = params.get("remote_prompt", "#")
vm_name = params.get("main_vm", "virt-tests-vm1")
vm = env.get_vm(vm_name)
vm_id = vm.get_id()
vm_uuid = vm.get_uuid()
# Back up xml file.Xen host has no guest xml file to define a guset.
backup_xml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
# Confirm how to reference a VM.
if vm_ref == "vm_name":
vm_ref = vm_name
elif vm_ref == "id":
vm_ref = vm_id
elif vm_ref == "hex_vm_id":
vm_ref = hex(int(vm_id))
elif vm_ref == "uuid":
vm_ref = vm_uuid
elif vm_ref.find("invalid") != -1:
vm_ref = params.get(vm_ref)
save_file = "/var/lib/libvirt/qemu/save/%s.save" % vm_name
if option.count("managedsave") and vm.is_alive():
virsh.managedsave(vm_name)
snp_list = virsh.snapshot_list(vm_name)
if option.count("snapshot"):
snp_file_list = []
if not len(snp_list):
virsh.snapshot_create(vm_name)
logging.debug("Create a snapshot for test!")
else:
# Backup snapshots for domain
for snp_item in snp_list:
tmp_file = os.path.join(test.tmpdir, snp_item+".xml")
virsh.snapshot_dumpxml(vm_name, snp_item, to_file=tmp_file)
snp_file_list.append(tmp_file)
else:
if len(snp_list):
raise error.TestNAError("This domain has snapshot(s), "
"cannot be undefined!")
# Turn libvirtd into certain state.
if libvirtd_state == "off":
utils_libvirtd.libvirtd_stop()
# Test virsh undefine command.
if vm_ref != "remote":
vm_ref = "%s %s" % (vm_ref, extra)
cmdresult = virsh.undefine(vm_ref, option,
ignore_status=True, debug=True)
status = cmdresult.exit_status
if status:
logging.debug("Error status, command output: %s", cmdresult.stdout)
if undefine_twice:
status2 = virsh.undefine(vm_ref,
ignore_status=True).exit_status
else:
if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
raise error.TestNAError("remote_ip and/or local_ip parameters not"
" changed from default values")
try:
uri = libvirt_vm.complete_uri(local_ip)
session = remote.remote_login("ssh", remote_ip, "22", remote_user,
remote_pwd, remote_prompt)
cmd_undefine = "virsh -c %s undefine %s" % (uri, vm_name)
status, output = session.cmd_status_output(cmd_undefine)
logging.info("Undefine output: %s", output)
except (error.CmdError, remote.LoginError, aexpect.ShellError), detail:
logging.error("Detail: %s", detail)
status = 1
示例13: run
#.........这里部分代码省略.........
(i, i, install_root), shell=True)
# Config basic network
net_file = install_root + '/etc/sysconfig/network'
with open(net_file, 'w') as f:
f.write('NETWORKING=yes\nHOSTNAME=%s\n' % vm_name)
net_script = install_root + '/etc/sysconfig/network-scripts/ifcfg-eth0'
with open(net_script, 'w') as f:
f.write('DEVICE=eth0\nBOOTPROTO=dhcp\nONBOOT=yes\n')
# Set root password and enable sshd
session = aexpect.ShellSession("chroot %s" % install_root)
session.sendline('echo %s|passwd root --stdin' % passwd)
session.sendline('chkconfig sshd on')
session.close()
# Create
result = virsh.create(vmxml.xml, **virsh_args)
utlv.check_exit_status(result)
check_state('running')
# Destroy
result = virsh.destroy(vm_name, **virsh_args)
utlv.check_exit_status(result)
if not virsh.domain_exists(vm_name, **virsh_args):
logging.info("Destroy transient LXC domain successfully")
else:
raise TestFail("Transient LXC domain still exist after destroy")
# Define
result = virsh.define(vmxml.xml, **virsh_args)
utlv.check_exit_status(result)
check_state('shut off')
# List
result = virsh.dom_list('--inactive', **virsh_args)
utlv.check_exit_status(result)
if re.findall("(%s)\s+shut off" % vm_name, result.stdout):
logging.info("Find %s in virsh list output", vm_name)
else:
raise TestFail("Not find %s in virsh list output")
# Dumpxml
result = virsh.dumpxml(vm_name, uri=uri, debug=False)
utlv.check_exit_status(result)
# Edit
edit_vcpu = '2'
logging.info("Change vcpu of LXC container to %s", edit_vcpu)
edit_cmd = [r":%s /[0-9]*<\/vcpu>/" + edit_vcpu + r"<\/vcpu>"]
if not utlv.exec_virsh_edit(vm_name, edit_cmd, connect_uri=uri):
raise TestFail("Run edit command fail")
else:
result = virsh.dumpxml(vm_name, **virsh_args)
new_vcpu = re.search(r'(\d*)</vcpu>', result.stdout).group(1)
if new_vcpu == edit_vcpu:
logging.info("vcpu number is expected after do edit")
else:
raise TestFail("vcpu number is unexpected after do edit")
# Start
result = virsh.start(vm_name, **virsh_args)
utlv.check_exit_status(result)
check_state('running')
# Suspend
result = virsh.suspend(vm_name, **virsh_args)
utlv.check_exit_status(result)
check_state('paused')
# Resume
result = virsh.resume(vm_name, **virsh_args)
utlv.check_exit_status(result)
check_state('running')
# Reboot(not supported on RHEL6)
result = virsh.reboot(vm_name, **virsh_args)
supported_err = 'not supported by the connection driver: virDomainReboot'
if supported_err in result.stderr.strip():
logging.info("Reboot is not supported")
else:
utlv.check_exit_status(result)
# Destroy
result = virsh.destroy(vm_name, **virsh_args)
utlv.check_exit_status(result)
check_state('shut off')
# Undefine
result = virsh.undefine(vm_name, **virsh_args)
utlv.check_exit_status(result)
if not virsh.domain_exists(vm_name, **virsh_args):
logging.info("Undefine LXC domain successfully")
else:
raise TestFail("LXC domain still exist after undefine")
finally:
virsh.remove_domain(vm_name, **virsh_args)
if full_os and os.path.exists(install_root):
shutil.rmtree(install_root)
示例14: run_virsh_edit
#.........这里部分代码省略.........
vcpucount_result = virsh.vcpucount(vm_name, options="--config")
if vcpucount_result.exit_status:
raise error.TestError("Failed to get vcpucount. Detail:\n%s"
% vcpucount_result)
original_vcpu = vcpucount_result.stdout.strip()
expected_vcpu = str(int(original_vcpu)+1)
libvirtd = params.get("libvirtd", "on")
vm_ref = params.get("edit_vm_ref")
status_error = params.get("status_error")
def modify_vcpu(source, edit_cmd):
"""
Modify vm's cpu infomation.
@param: source : virsh edit's option.
@param: dic_mode : a edit commad line .
@return: True if edit successed,False if edit failed.
"""
session = aexpect.ShellSession("sudo -s")
try:
session.sendline("virsh edit %s" % source)
session.sendline(edit_cmd)
session.send('\x1b')
session.send('ZZ')
# use sleep(1) to make sure the modify has been completed.
time.sleep(1)
session.close()
return True
except:
return False
def edit_vcpu(source, guest_name):
"""
Modify vm's cpu infomation by virsh edit command.
@param: source : virsh edit's option.
@param: guest_name : vm's name.
@return: True if edit successed,False if edit failed.
"""
dic_mode = {"edit": ":%s /[0-9]*<\/vcpu>/"+expected_vcpu+"<\/vcpu>",
"recover": ":%s /[0-9]*<\/vcpu>/"+original_vcpu+"<\/vcpu>"}
status = modify_vcpu(source, dic_mode["edit"])
if not status:
return status
if params.get("paused_after_start_vm") == "yes":
virsh.resume(guest_name, ignore_status=True)
virsh.destroy(guest_name)
elif params.get("start_vm") == "yes":
virsh.destroy(guest_name)
vcpus = vm.dominfo()["CPU(s)"]
#Recover cpuinfo
status = modify_vcpu(source, dic_mode["recover"])
if status and vcpus != expected_vcpu:
return False
return status
#run test case
xml_file = os.path.join(test.tmpdir, 'tmp.xml')
virsh.dumpxml(vm_name, extra="", to_file=xml_file)
if libvirtd == "off":
utils_libvirtd.libvirtd_stop()
try:
if vm_ref == "id":
status = edit_vcpu(domid, vm_name)
elif vm_ref == "uuid":
status = edit_vcpu(domuuid, vm_name)
elif vm_ref == "name" and status_error == "no":
status = edit_vcpu(vm_name, vm_name)
else:
status = False
if vm_ref.find("invalid") != -1:
vm_ref = params.get(vm_ref)
elif vm_ref == "name":
vm_ref = "%s %s" % (vm_name, params.get("edit_extra_param"))
edit_status = virsh.edit(vm_ref).exit_status
if edit_status == 0:
status = True
except:
status = False
#recover libvirtd service start
if libvirtd == "off":
utils_libvirtd.libvirtd_start()
#Recover VM
if vm.is_alive():
vm.destroy()
virsh.undefine(vm_name)
virsh.define(xml_file)
#check status_error
if status_error == "yes":
if status:
raise error.TestFail("Run successfully with wrong command!")
elif status_error == "no":
if not status:
raise error.TestFail("Run failed with right command")
示例15: run
#.........这里部分代码省略.........
if if_device == "no_exist_net":
device = "vnet-1"
elif if_device == "no_exist_mac":
# Generate random mac address for negative test
device = utils_net.VirtIface.complete_mac_address("01:02")
elif if_device == " ":
device = "''"
# Setlink opertation
result = domif_setlink(vm_name[1], device, if_operation, options)
status = result.exit_status
logging.info("Setlink done")
# Getlink opertation
get_result = domif_getlink(vm_name[1], device, options)
getlink_output = get_result.stdout.strip()
# Check the getlink command output
if status_error == "no":
if not re.search(if_operation, getlink_output):
test.fail("Getlink result should "
"equal with setlink operation")
logging.info("Getlink done")
# If --config or --persistent is given should restart the vm then test link status
if any(options == option for option in ["--config", "--persistent"]) and vm.is_alive():
vm.destroy()
vm.start()
logging.info("Restart VM")
elif start_vm == "no":
vm.start()
error_msg = None
if status_error == "no":
# Serial login the vm to check link status
# Start vm check the link statue
session = vm.wait_for_serial_login(username=username,
password=password)
guest_if_name = utils_net.get_linux_ifname(session, mac_address)
# Check link state in guest
if check_link_state:
if (if_operation == "up" and
not guest_if_state(guest_if_name, session)):
error_msg = "Link state should be up in guest"
if (if_operation == "down" and
guest_if_state(guest_if_name, session)):
error_msg = "Link state should be down in guest"
# Test of setting link state by update_device command
if check_link_by_update_device:
if not check_update_device(vm, guest_if_name, session):
error_msg = "Check update_device failed"
# Set the link up make host connect with vm
domif_setlink(vm_name[0], device, "up", "")
if not utils_misc.wait_for(
lambda: guest_if_state(guest_if_name, session), 5):
error_msg = "Link state isn't up in guest"
# Ignore status of this one
cmd = 'ip link set down %s' % guest_if_name
session.cmd_status_output(cmd, timeout=10)
pattern = "%s:.*state DOWN.*" % guest_if_name
pattern_cmd = 'ip addr show dev %s' % guest_if_name
guest_cmd_check(pattern_cmd, session, pattern)
cmd = 'ip link set up %s' % guest_if_name
session.cmd_status_output(cmd, timeout=10)
pattern = "%s:.*state UP.*" % guest_if_name
if not guest_cmd_check(pattern_cmd, session, pattern):
error_msg = ("Could not bring up interface %s inside guest"
% guest_if_name)
else: # negative test
# stop guest, so state is always consistent on next start
vm.destroy()
if error_msg:
test.fail(error_msg)
# Check status_error
if status_error == "yes":
if status:
logging.info("Expected error (negative testing). Output: %s",
result.stderr.strip())
else:
test.fail("Unexpected return code %d "
"(negative testing)" % status)
elif status_error != "no":
test.error("Invalid value for status_error '%s' "
"(must be 'yes' or 'no')" % status_error)
finally:
# Recover VM.
if vm.is_alive():
vm.destroy(gracefully=False)
virsh.undefine(vm_name[0])
virsh.define(vm_xml_file)
os.remove(vm_xml_file)