def guest_power_on(domobj, domname, mac): """ power on guest virtual machine""" try: domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to power on guest %s" % domname) return 1 timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % domname) logger.info("the ip address of vm %s is %s" % (domname, ip)) break if timeout == 0: logger.info("fail to power on vm %s" % domname) return 1 return 0
def create(params): """create a domain from xml""" logger = params['logger'] guestname = params['guestname'] xmlstr = params['xml'] flags = params.get('flags', 'none') if flags != "none" and flags != "start_paused": logger.error("flags value either \"none\" or \"start_paused\"") return 1 conn = sharedmod.libvirtobj['conn'] # Create domain from xml try: if flags == "none": domobj = conn.createXML(xmlstr, NONE) elif flags == "start_paused": domobj = conn.createXML(xmlstr, START_PAUSED) else: logger.error("flags error") except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to create domain %s" % guestname) return 1 if flags == "start_paused": state = domobj.info()[0] if state == libvirt.VIR_DOMAIN_PAUSED: logger.info("guest start with state paused successfully") return 0 else: logger.error("guest state error") return 1 logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout == 0: logger.info("fail to power on vm %s" % guestname) return 1 return 0
def guest_start(domobj, guestname, logger): """start guest""" timeout = 600 ip = '' mac = utils.get_dom_mac_addr(guestname) try: logger.info("start guest") domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain") return 1 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout <= 0: logger.info("fail to power on vm %s" % guestname) return 1, ip return 0, ip
def shutdown(params): """Shutdown domain Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py guestname -- same as the domain name Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] logger = params['logger'] conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) timeout = 600 logger.info('shutdown domain') mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of guest is %s" % ip) # Shutdown domain try: domobj.shutdown() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("shutdown failed") return 1
def check_current_vcpu(domobj, username, password): """dump domain xml description to get current vcpu number """ guestxml = domobj.XMLDesc(1) logger.debug("domain %s xml is :\n%s" % (domobj.name(), guestxml)) xml = minidom.parseString(guestxml) vcpu = xml.getElementsByTagName('vcpu')[0] if vcpu.hasAttribute('current'): attr = vcpu.getAttributeNode('current') current_vcpu = int(attr.nodeValue) else: logger.info("domain did not have 'current' attribute in vcpu element") current_vcpu = int(vcpu.childNodes[0].data) logger.info("check cpu number in domain") ip = utils.mac_to_ip(mac, 180) cmd = "cat /proc/cpuinfo | grep processor | wc -l" ret, output = utils.remote_exec_pexpect(ip, username, password, cmd) if not ret: logger.info("cpu number in domain is %s" % output) if int(output) == current_vcpu: logger.info("cpu number in domain is equal to current vcpu value") return current_vcpu else: logger.error("current vcpu is not equal as check in domain") return False else: logger.error("check in domain fail") return False
def set_user_passwd(params): """ test API for setUserPassword in class virDomain """ logger = params["logger"] guest = params["guestname"] username = params["username"] userpasswd = params["userpassword"] if "flags" in params: if params["flags"] == "encrypted": flags = libvirt.VIR_DOMAIN_PASSWORD_ENCRYPTED else: flags = 0 else: flags = 0 try: if "conn" in params: conn = libvirt.open(params["conn"]) else: conn = libvirt.open(optional_params["conn"]) logger.info("get connection to libvirtd") vm = conn.lookupByName(guest) logger.info("test guest name: %s" % guest) if not check_agent_status(vm): logger.error("guest agent is not connected") return 1 mac = get_guest_mac(vm) if not mac: logger.error("cannot get guest interface mac") return 1 ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.error("cannot get guest IP") return 1 if flags > 0: passwd = crypt.crypt("123456", crypt.mksalt(crypt.METHOD_SHA512)) else: passwd = "123456" if create_new_user(ipaddr, "usertestapi", username, userpasswd, logger) != 0: return 1 vm.setUserPassword("usertestapi", passwd, flags) if verify_cur_user(ipaddr, "usertestapi", "123456") != 0: logger.error("cannot login guest via new user") return 1 except libvirtError, e: logger.error("API error message: %s" % e.message) return 1
def flag_check(params): """ check if the flag file is present or not""" logger = params['logger'] guestname = params['guestname'] username = params['username'] password = params['password'] if 'expectedret' in params: expected_result = params['expectedret'] else: expected_result = "exist" conn = sharedmod.libvirtobj['conn'] if not check_domain_running(conn, guestname, logger): logger.error("need a running guest") return 1 logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.info(str(timeout) + "s left") time.sleep(10) timeout -= 10 else: logger.info("the ip address of vm %s is %s" % (guestname, ipaddr)) break if timeout == 0: logger.info("vm %s failed to get ip address" % guestname) return 1 ret, out = utils.remote_exec_pexpect( ipaddr, username, password, FLAG_CHECK) if ret: logger.error("connecting to guest OS timeout") return 1 elif out == FLAG_FILE and expected_result == "exist": logger.info("checking flag %s in guest OS succeeded" % FLAG_FILE) return 0 elif out == FLAG_FILE and expected_result == 'noexist': logger.error("flag %s still exist, FAILED." % FLAG_FILE) return 1 elif out is not None and expected_result == "exist": logger.error( "no flag %s exists in the guest %s " % (FLAG_FILE, guestname)) return 1 elif out is not None and expected_result == 'noexist': logger.info("flag %s is not present, checking succeeded" % FLAG_FILE) return 0 return 0
def flag_check(params): """ check if the flag file is present or not""" logger = params['logger'] guestname = params['guestname'] username = params['username'] password = params['password'] if 'expectedret' in params: expected_result = params['expectedret'] else: expected_result = "exist" conn = sharedmod.libvirtobj['conn'] if not check_domain_running(conn, guestname, logger): logger.error("need a running guest") return 1 logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.info(str(timeout) + "s left") time.sleep(10) timeout -= 10 else: logger.info("the ip address of vm %s is %s" % (guestname, ipaddr)) break if timeout == 0: logger.info("vm %s failed to get ip address" % guestname) return 1 ret, out = utils.remote_exec_pexpect(ipaddr, username, password, FLAG_CHECK) if ret: logger.error("connecting to guest OS timeout") return 1 elif out == FLAG_FILE and expected_result == "exist": logger.info("checking flag %s in guest OS succeeded" % FLAG_FILE) return 0 elif out == FLAG_FILE and expected_result == 'noexist': logger.error("flag %s still exist, FAILED." % FLAG_FILE) return 1 elif out is not None and expected_result == "exist": logger.error("no flag %s exists in the guest %s " % (FLAG_FILE, guestname)) return 1 elif out is not None and expected_result == 'noexist': logger.info("flag %s is not present, checking succeeded" % FLAG_FILE) return 0 return 0
def destroy(params): """destroy domain Argument is a dictionary with two keys: {'guestname': guestname} logger -- an object of utils/log.py guestname -- the domain name flags -- optional arguments: noping: Don't do the ping test Return 0 on SUCCESS or 1 on FAILURE """ # Initiate and check parameters global logger logger = params['logger'] params.pop('logger') guestname = params['guestname'] br = params.get('bridgename', 'virbr0') flags = "" if params.has_key('flags'): flags = params['flags'] conn = sharedmod.libvirtobj['conn'] # Get running domain by name guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.error("guest %s doesn't exist or isn't running." % guestname) return 1 domobj = conn.lookupByName(guestname) timeout = 60 logger.info('destroy domain') if not "noping" in flags: # Get domain ip mac = utils.get_dom_mac_addr(guestname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180, br) logger.info("the ip address of guest is %s" % ip) # Destroy domain try: domobj.destroy() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("failed to destroy domain") return 1
def get_current_memory(guestname, username, password): """get domain current memory inside domain """ logger.debug("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.debug("the mac address of vm %s is %s" % (guestname, mac)) ip = utils.mac_to_ip(mac, 180) current = utils.get_remote_memory(ip, username, password) return current
def destroy(params): """destroy domain Argument is a dictionary with two keys: {'guestname': guestname} logger -- an object of utils/log.py guestname -- the domain name flags -- optional arguments: noping: Don't do the ping test Return 0 on SUCCESS or 1 on FAILURE """ # Initiate and check parameters global logger logger = params['logger'] params.pop('logger') guestname = params['guestname'] flags = "" if params.has_key('flags'): flags = params['flags'] conn = sharedmod.libvirtobj['conn'] # Get running domain by name guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.error("guest %s doesn't exist or isn't running." % guestname) return 1 domobj = conn.lookupByName(guestname) timeout = 60 logger.info('destroy domain') if not "noping" in flags: # Get domain ip mac = utils.get_dom_mac_addr(guestname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of guest is %s" % ip) # Destroy domain try: domobj.destroy() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("failed to destroy domain") return 1
def shutdown(params): """Shutdown domain Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py guestname -- same as the domain name Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] logger = params['logger'] conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) timeout = 600 logger.info('shutdown domain') mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of guest is %s" % ip) # Shutdown domain try: domobj.shutdown() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("shutdown failed") return 1 # Check domain status by ping ip while timeout: time.sleep(10) timeout -= 10 logger.info(str(timeout) + "s left") state = domobj.info()[0] if state == libvirt.VIR_DOMAIN_SHUTOFF: break if timeout <= 0: logger.error('The domain state is not equal to "shutoff"') return 1 logger.info('ping guest') if utils.do_ping(ip, 300): logger.error('The guest is still active, IP: ' + str(ip)) return 1 else: logger.info("domain %s shutdown successfully" % domname) return 0
def ifstats(params): """Domain interface statistic""" logger = params['logger'] guestname = params['guestname'] conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(guestname) if check_guest_status(domobj): pass else: try: logger.info("%s is not running , power on it" % guestname) domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("start failed") return 1 mac = utils.get_dom_mac_addr(guestname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info('ping guest') if not utils.do_ping(ip, 300): logger.error('Failed on ping guest, IP: ' + str(ip)) return 1 xml = domobj.XMLDesc(0) doc = libxml2.parseDoc(xml) ctx = doc.xpathNewContext() devs = ctx.xpathEval("/domain/devices/interface/target/@dev") path = devs[0].content ifstats = domobj.interfaceStats(path) if ifstats: # check_interface_stats() logger.debug(ifstats) logger.info("%s rx_bytes %s" % (path, ifstats[0])) logger.info("%s rx_packets %s" % (path, ifstats[1])) logger.info("%s rx_errs %s" % (path, ifstats[2])) logger.info("%s rx_drop %s" % (path, ifstats[3])) logger.info("%s tx_bytes %s" % (path, ifstats[4])) logger.info("%s tx_packets %s" % (path, ifstats[5])) logger.info("%s tx_errs %s" % (path, ifstats[6])) logger.info("%s tx_drop %s" % (path, ifstats[7])) else: logger.error("fail to get domain interface statistics\n") return 1 return 0
def set_guest_time(params): """ test setting guest time """ logger = params['logger'] guestname = params['guestname'] username = params['username'] userpassword = params['userpassword'] seconds = long(params['seconds']) nseconds = long(params.get('nseconds', 0)) f = params.get('flags', 0) flags = parse_flags(f) if flags == -1: logger.error("unrecongnized flags: %s" % f) return 1 conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(guestname) # Check domain status if check_guest_status(domobj): pass else: domobj.create() time.sleep(90) # get guest MAC mac = get_guest_mac(domobj) if mac == None: logger.error("Failed to get guest's MAC address") return 1 else: logger.info("guest's MAC is %s" % mac) ipaddr = utils.mac_to_ip(mac, 180) if mac == None: logger.error("Failed to get guest's IP address") return 1 else: logger.info("guest's IP is %s" % ipaddr) try: domobj.setTime({'seconds': seconds, 'nseconds': nseconds}, flags) sec = long(utils.remote_exec(ipaddr, username, userpassword, GET_TIME)) except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) return 1
def guest_time(params): """ test guest time """ logger = params['logger'] guestname = params['guestname'] username = params['username'] userpassword = params['userpassword'] conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(guestname) # Check domain status if check_guest_status(domobj): pass else: domobj.create() time.sleep(90) # get guest MAC mac = get_guest_mac(domobj) if mac is None: logger.error("Failed to get guest's MAC address") return 1 else: logger.info("guest's MAC is %s" % mac) ipaddr = utils.mac_to_ip(mac, 180) if mac is None: logger.error("Failed to get guest's IP address") return 1 else: logger.info("guest's IP is %s" % ipaddr) try: t1 = utils.remote_exec(ipaddr, username, userpassword, GET_TIME) t2 = domobj.getTime()['seconds'] except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) return 1 if check_guest_time(long(t1), t2): logger.info("checking guest time: %s" % t2) else: logger.error("checking guest time: failed") return 1 return 0
def suspend(params): """Suspend domain Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py guestname -- same as the domain name Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] logger = params['logger'] conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) # Suspend domain logger.info('suspend domain') try: domobj.suspend() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) return 1 time.sleep(1) state = domobj.info()[0] if state != libvirt.VIR_DOMAIN_PAUSED: logger.error('The domain state is not equal to "paused"') return 1 mac = utils.get_dom_mac_addr(domname) time.sleep(3) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 10) time.sleep(10) logger.info('ping guest') if utils.do_ping(ip, 20): logger.error('The guest is still active, IP: ' + str(ip)) return 1 logger.info('PASS') return 0
def get_guest_ipaddr(*args): """Get guest ip address""" (guestname, logger) = args mac = utils.get_dom_mac_addr(guestname) logger.debug("guest mac address: %s" % mac) ipaddr = utils.mac_to_ip(mac, 15) logger.debug("guest ip address: %s" % ipaddr) if utils.do_ping(ipaddr, 20) == 1: logger.info("ping current guest successfull") return ipaddr else: logger.error("Error: can't ping current guest") return None
def resume(params): """Resume domain Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py guestname -- same as the domain name Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] logger = params['logger'] # Resume domain conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) logger.info('resume domain') try: domobj.resume() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("resume failed") return 1 state = domobj.info()[0] expect_states = [ libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED] if state not in expect_states: logger.error('The domain state is not equal to "paused"') return 1 mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 120) logger.info('ping guest') if not utils.do_ping(ip, 300): logger.error('Failed on ping guest, IP: ' + str(ip)) return 1 logger.info("PASS") return 0
def resume(params): """Resume domain Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py guestname -- same as the domain name Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] logger = params['logger'] # Resume domain conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) logger.info('resume domain') try: domobj.resume() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("resume failed") return 1 state = domobj.info()[0] expect_states = [ libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED ] if state not in expect_states: logger.error('The domain state is not equal to "paused"') return 1 mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 120) logger.info('ping guest') if not utils.do_ping(ip, 300): logger.error('Failed on ping guest, IP: ' + str(ip)) return 1 logger.info("PASS") return 0
def get_current_vcpu(domobj, username, password): """dump domain live xml description to get current vcpu number and check in domain to confirm """ try: guestxml = domobj.XMLDesc(1) guestname = domobj.name() logger.debug("domain %s xml is :\n%s" % (guestname, guestxml)) xml = minidom.parseString(guestxml) vcpu = xml.getElementsByTagName('vcpu')[0] if vcpu.hasAttribute('current'): attr = vcpu.getAttributeNode('current') current = int(attr.nodeValue) else: logger.info("no 'current' atrribute for element vcpu") current = int(vcpu.childNodes[0].data) logger.info("domain current vcpu number in live xml is: %s" % current) except libvirtError as e: logger.error("libvirt call failed: " + str(e)) return False logger.debug("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.debug("the mac address of vm %s is %s" % (guestname, mac)) logger.info("check cpu number in domain") ip = utils.mac_to_ip(mac, 180) cmd = "cat /proc/cpuinfo | grep processor | wc -l" ret, output = utils.remote_exec_pexpect(ip, username, password, cmd) if not ret: logger.info("cpu number in domain is %s" % output) if int(output) == current: logger.info("cpu in domain is equal to current vcpu value") else: logger.error("current vcpu is not equal as check in domain") return False else: logger.error("check in domain fail") return False return current
def fsinfo(params): """ test API for fsInfo in class virDomain """ logger = params['logger'] guest = params['guestname'] username = params['username'] userpasswd = params['userpassword'] try: conn = libvirt.open(params['conn']) logger.info("get connection to libvirtd") vm = conn.lookupByName(guest) logger.info("test guest name: %s" % guest) if not check_agent_status(vm): logger.error("guest agent is not connected") return 1 fsinfo = vm.fsInfo() logger.info("get guest filesystem information") mac = get_guest_mac(vm) if not mac: logger.error("cannot get guest interface mac") return 1 ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.error("cannot get guest IP") return 1 if not check_fsinfo(ipaddr, username, userpasswd, fsinfo, logger): return 1 except libvirtError as e: logger.error("API error message: %s" % e.message) return 1 return 0
def file_flag(params): """ create a new file in the /tmp folder of the guest as a flag """ logger = params['logger'] guestname = params['guestname'] username = params['username'] password = params['password'] conn = sharedmod.libvirtobj['conn'] if not check_domain_running(conn, guestname, logger): logger.error("need a running guest") return 1 logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.info(str(timeout) + "s left") time.sleep(10) timeout -= 10 else: logger.info("the ip address of vm %s is %s" % (guestname, ipaddr)) break if timeout == 0: logger.info("vm %s failed to get ip address" % guestname) return 1 if not make_flag(ipaddr, username, password, logger): logger.error("making flag in guest %s failed" % guestname) return 1 else: logger.info("making flag in guest %s succeeded" % guestname) return 0
def check_guest_kernel(*args): """Check guest kernel version""" (guestname, logger) = args mac = utils.get_dom_mac_addr(guestname) logger.debug("guest mac address: %s" % mac) ipaddr = utils.mac_to_ip(mac, 15) if ipaddr is None: logger.error("can't get guest ip") return None logger.debug("guest ip address: %s" % ipaddr) kernel = utils.get_remote_kernel(ipaddr, "root", "redhat") logger.debug("current kernel version: %s" % kernel) if kernel: return kernel else: return None
def set_vcpus(domobj, domain_name, vcpu): """set the value of virtual machine to vcpu offline , then boot up the virtual machine """ timeout = 60 logger.info('destroy domain') logger.info("get the mac address of vm %s" % domain_name) mac = utils.get_dom_mac_addr(domain_name) logger.info("the mac address of vm %s is %s" % (domain_name, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) try: domobj.destroy() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("fail to destroy domain") return 1
def reboot(params): """Reboot virtual machine Return 0 on SUCCESS or 1 on FAILURE """ # Initiate and check parameters global logger logger = params['logger'] params.pop('logger') domain_name = params['guestname'] # Connect to local hypervisor connection URI hypervisor = utils.get_hypervisor() if hypervisor == "kvm": logger.info("kvm hypervisor doesn't support the funtion now") return 0 conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domain_name) # Get domain ip logger.info("get the mac address of vm %s" % domain_name) mac = utils.get_dom_mac_addr(domain_name) logger.info("the mac address of vm %s is %s" % (domain_name, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) timeout = 600 logger.info('reboot vm %s now' % domain_name) # Reboot domain try: domobj = reboot(0) except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("fail to reboot domain") return 1
# Resume domain conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) logger.info('resume domain') try: domobj.resume() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("resume failed") return 1 state = domobj.info()[0] expect_states = [libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED] if state not in expect_states: logger.error('The domain state is not equal to "paused"') return 1 mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 120) logger.info('ping guest') if not utils.do_ping(ip, 300): logger.error('Failed on ping guest, IP: ' + str(ip)) return 1 logger.info("PASS") return 0
def restart(params): """restart libvirtd test""" logger = params['logger'] guestname = params['guestname'] conn = sharedmod.libvirtobj['conn'] logger.info("check the domain state") ret = check_domain_running(conn, guestname, logger) if ret: return 1 logger.info("check the libvirtd status:") ret = libvirtd_check(logger) if ret: return 1 # Get domain ip logger.info("get the mac address of domain %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of domain %s is %s" % (guestname, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of domain %s is %s" % (guestname, ip)) logger.info("ping to domain %s" % guestname) if utils.do_ping(ip, 0): logger.info("Success ping domain %s" % guestname) else: logger.error("fail to ping domain %s" % guestname) return 1 ret, pid_before = get_domain_pid(logger, guestname) if ret: return 1 logger.info("restart libvirtd service:") ret, out = utils.exec_cmd(RESTART_CMD, shell=True) if ret != 0: logger.error("failed to restart libvirtd") for i in range(len(out)): logger.error(out[i]) return 1 else: for i in range(len(out)): logger.info(out[i]) logger.info("recheck libvirtd status:") ret = libvirtd_check(logger) if ret: return 1 logger.info("ping to domain %s again" % guestname) if utils.do_ping(ip, 0): logger.info("Success ping domain %s" % guestname) else: logger.error("fail to ping domain %s" % guestname) return 1 ret, pid_after = get_domain_pid(logger, guestname) if ret: return 1 if pid_before != pid_after: logger.error("%s pid changed during libvirtd restart" % guestname) return 1 else: logger.info("domain pid not change, %s keeps running during \ libvirtd restart" % guestname) return 0
def install_linux_check(params): """check guest status after installation, including network ping, read/write option in guest. return value: 0 - ok; 1 - bad """ global logger logger = params['logger'] params.pop('logger') guestname = params.get('guestname') virt_type = params.get('virt_type') logger.info("the name of guest is %s" % guestname) # Connect to local hypervisor connection URI hypervisor = utils.get_hypervisor() logger.info("the type of hypervisor is %s" % hypervisor) conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(guestname) state = domobj.info()[0] if(state == libvirt.VIR_DOMAIN_SHUTOFF): logger.info("guest is shutoff, if u want to run this case, \ guest must be started") return 1 logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.info(str(timeout) + "s left") time.sleep(10) timeout -= 10 else: logger.info("the ip address of vm %s is %s" % (guestname, ipaddr)) break if timeout == 0: logger.info("vm %s fail to get ip address" % guestname) return 1 time.sleep(120) logger.info("Now checking guest health after installation") domain_name=guestname blk_type=params['hddriver'] nic_type=params['nicdriver'] Test_Result = 0 # Ping guest from host logger.info("check point1: ping guest from host") if utils.do_ping(ipaddr, 20) == 1: logger.info("ping current guest successfull") else: logger.error("Error: can't ping current guest") Test_Result = 1 return Test_Result # Creat file and read file in guest. logger.info("check point2: creat and read dirctory/file in guest") if utils.create_dir(ipaddr, "root", "redhat") == 0: logger.info("create dir - /tmp/test successfully") if utils.write_file(ipaddr, "root", "redhat") == 0: logger.info("write and read file: /tmp/test/test.log successfully") else: logger.error("Error: fail to write/read file - /tmp/test/test.log") Test_Result = 1 return Test_Result else: logger.error("Error: fail to create dir - /tmp/test") Test_Result = 1 return Test_Result # Check whether vcpu equals the value set in geust config xml logger.info("check point3: check cpu number in guest equals to \ the value set in domain config xml") vcpunum_expect = int(utils.get_num_vcpus(domain_name)) logger.info("vcpu number in domain config xml - %s is %s" % \ (domain_name, vcpunum_expect)) vcpunum_actual = int(utils.get_remote_vcpus(ipaddr, "root", "redhat")) logger.info("The actual vcpu number in guest - %s is %s" % (domain_name, vcpunum_actual)) if vcpunum_expect == vcpunum_actual: logger.info("The actual vcpu number in guest is \ equal to the setting your domain config xml") else: logger.error("Error: The actual vcpu number in guest is \ NOT equal to the setting your domain config xml") Test_Result = 1 return Test_Result # Check whether mem in guest is equal to the value set in domain config xml logger.info("check point4: check whether mem in guest is equal to \ the value set in domain config xml") mem_expect = utils.get_size_mem(domain_name) logger.info("current mem size in domain config xml - %s is %s" % (domain_name, mem_expect)) mem_actual = utils.get_remote_memory(ipaddr, "root", "redhat") logger.info("The actual mem size in guest - %s is %s" % (domain_name, mem_actual)) diff_range = int(mem_expect) * 0.07 diff = int(mem_expect) - int(mem_actual) if int(math.fabs(diff)) < int(diff_range): logger.info("The actual mem size in guest is almost equal to \ the setting your domain config xml") else: logger.error("Error: The actual mem size in guest is NOT equal to \ the setting your domain config xml") Test_Result = 1 return Test_Result # Check app works fine in guest, such as: wget logger.info("check point5: check app works fine in guest, such as: wget") logger.info("get system environment information") envfile = os.path.join(HOME_PATH, 'global.cfg') logger.info("the environment file is %s" % envfile) envparser = env_parser.Envparser(envfile) file_url = envparser.get_value("other", "wget_url") if utils.run_wget_app(ipaddr, "root", "redhat", file_url, logger) == 0: logger.info("run wget successfully in guest.") else: logger.error("Error: fail to run wget in guest") Test_Result = 1 return Test_Result # Check nic and blk driver in guest if 'kvm' in virt_type or 'xenfv' in virt_type: logger.info("check point6: check nic and blk driver in guest is \ expected as your config:") if utils.validate_remote_nic_type(ipaddr, "root", "redhat", nic_type, logger) == 0 and \ utils.validate_remote_blk_type(ipaddr, "root", "redhat", blk_type, logger) == 0: logger.info("nic type - %s and blk type - %s check successfully" % (nic_type, blk_type)) else: logger.error("Error: nic type - %s or blk type - %s check failed" % (nic_type, blk_type)) Test_Result = 1 return Test_Result return Test_Result
try: logger.info('boot guest up ...') domobj.create() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % domain_name) return 1 timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % domain_name) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) break if timeout <= 0: logger.info("fail to power on vm %s" % domain_name) return 1 return 0 def vcpu_affinity_check(domain_name, vcpu, expected_pinned_cpu, hypervisor):
try: logger.info('boot guest up ...') domobj.create() except libvirtError, e: logger.error("API error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % domain_name) return 1 timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % domain_name) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) break if timeout <= 0: logger.info("fail to power on vm %s" % domain_name) return 1 return 0
def install_linux_cdrom(params): """ install a new virtual machine """ logger = params['logger'] guestname = params.get('guestname') guestos = params.get('guestos') guestarch = params.get('guestarch') br = params.get('bridgename', 'virbr0') xmlstr = params['xml'] logger.info("the name of guest is %s" % guestname) conn = sharedmod.libvirtobj['conn'] check_domain_state(conn, guestname, logger) logger.info("the macaddress is %s" % params.get('macaddr', '52:54:00:97:e4:28')) diskpath = params.get('diskpath', '/var/lib/libvirt/images/libvirt-test-api') logger.info("disk image is %s" % diskpath) seeksize = params.get('disksize', 10) imageformat = params.get('imageformat', 'raw') logger.info("create disk image with size %sG, format %s" % (seeksize, imageformat)) disk_create = "qemu-img create -f %s %s %sG" % \ (imageformat, diskpath, seeksize) logger.debug("the command line of creating disk images is '%s'" % disk_create) (status, message) = commands.getstatusoutput(disk_create) if status != 0: logger.debug(message) return 1 os.chown(diskpath, 107, 107) logger.info("creating disk images file is successful.") hddriver = params.get('hddriver', 'virtio') if hddriver == 'virtio': xmlstr = xmlstr.replace('DEV', 'vda') elif hddriver == 'ide': xmlstr = xmlstr.replace('DEV', 'hda') elif hddriver == 'scsi': xmlstr = xmlstr.replace('DEV', 'sda') logger.info("get system environment information") envfile = os.path.join(HOME_PATH, 'global.cfg') logger.info("the environment file is %s" % envfile) os_arch = guestos + "_" + guestarch envparser = env_parser.Envparser(envfile) ostree = envparser.get_value("guest", os_arch) ks = envparser.get_value("guest", os_arch + "_http_ks") logger.debug('install source:\n %s' % ostree) logger.debug('kisckstart file:\n %s' % ks) if (ostree == 'http://'): logger.error("no os tree defined in %s for %s" % (envfile, os_arch)) return 1 logger.info('prepare installation...') cache_folder = envparser.get_value("variables", "domain_cache_folder") logger.info("begin to customize the custom.iso file") prepare_cdrom(ostree, ks, guestname, cache_folder, logger) bootcd = '%s/custom.iso' % \ (os.path.join(cache_folder, guestname)) xmlstr = xmlstr.replace('CUSTOMISO', bootcd) logger.debug('dump installation guest xml:\n%s' % xmlstr) installtype = params.get('type', 'define') if installtype == 'define': logger.info('define guest from xml description') try: domobj = conn.defineXML(xmlstr) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 logger.info('start installation guest ...') try: domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % guestname) return 1 elif installtype == 'create': logger.info('create guest from xml description') try: domobj = conn.createXML(xmlstr, 0) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 interval = 0 while (interval < 2400): time.sleep(10) if installtype == 'define': state = domobj.info()[0] if (state == libvirt.VIR_DOMAIN_SHUTOFF): logger.info("guest installaton of define type is complete.") logger.info("boot guest vm off harddisk") ret = prepare_boot_guest(domobj, xmlstr, guestname, installtype, logger) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 10 logger.info('%s seconds passed away...' % interval) elif installtype == 'create': guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.info("guest installation of create type is complete.") logger.info("define the vm and boot it up") ret = prepare_boot_guest(domobj, xmlstr, guestname, installtype, logger) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 10 logger.info('%s seconds passed away...' % interval) if interval == 2400: if 'rhel3u9' in guestname: logger.info( "guest installaton will be destoryed forcelly for rhel3u9 guest" ) domobj.destroy() logger.info("boot guest vm off harddisk") ret = prepare_boot_guest(domobj, xmlstr, guestname, installtype, logger) if ret: logger.info("booting guest vm off harddisk failed") return 1 else: logger.info("guest installation timeout 2400s") return 1 else: logger.info("guest is booting up") logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180, br) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout == 0: logger.info("fail to power on vm %s" % guestname) return 1 time.sleep(60) return 0
def set_vcpus(domobj, guestname, vcpu, username, password): """set the value of virtual machine to vcpu offline , then boot up the virtual machine """ timeout = 60 logger.info('destroy domain') try: domobj.destroy() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to destroy domain") return 1 newguestxml = redefine_vcpu_number(domobj, guestname, vcpu) logger.debug('''new guest %s xml :\n%s''' % (guestname, newguestxml)) logger.info("undefine the original guest") try: domobj.undefine() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to undefine guest %s" % guestname) return 1 logger.info("define guest with new xml") try: conn = domobj._conn conn.defineXML(newguestxml) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define guest %s" % guestname) return 1 try: logger.info('boot guest up ...') domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % guestname) return 1 timeout = 600 while timeout: time.sleep(10) timeout -= 10 logger.debug("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.debug("the ip address of vm %s is %s" % (guestname, ip)) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout <= 0: logger.info("fail to power on vm %s" % guestname) return 1 ret = check_current_vcpu(domobj, username, password) if ret != 'False': return 0 else: return 1 return 0
def reboot(params): """Reboot virtual machine Return 0 on SUCCESS or 1 on FAILURE """ # Initiate and check parameters global logger logger = params['logger'] params.pop('logger') domain_name = params['guestname'] # Connect to local hypervisor connection URI hypervisor = utils.get_hypervisor() if hypervisor == "kvm": logger.info("kvm hypervisor doesn't support the funtion now") return 0 conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domain_name) # Get domain ip logger.info("get the mac address of vm %s" % domain_name) mac = utils.get_dom_mac_addr(domain_name) logger.info("the mac address of vm %s is %s" % (domain_name, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) timeout = 600 logger.info('reboot vm %s now' % domain_name) # Reboot domain try: domobj = reboot(0) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to reboot domain") return 1 logger.info("the vm %s is power off" % domain_name) # Check domain status by ping ip while timeout: time.sleep(10) timeout -= 10 if utils.do_ping(ip, 0): logger.info(str(timeout) + "s left") else: logger.info("vm %s power off successfully" % domain_name) break if timeout == 0: logger.info("fail to power off %s" % domain_name) return 1 timeout = 600 logger.info("the vm %s is power on" % domain_name) while timeout: time.sleep(10) timeout -= 10 if not utils.do_ping(ip, 0): logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully") break if timeout == 0: logger.info("fail to power on vm %s" % domain_name) return 1 return 0
def restart(params): """restart libvirtd test""" logger = params['logger'] guestname = params['guestname'] conn = sharedmod.libvirtobj['conn'] logger.info("check the domain state") ret = check_domain_running(conn, guestname, logger) if ret: return 1 logger.info("check the libvirtd status:") ret = libvirtd_check(logger) if ret: return 1 # Get domain ip logger.info("get the mac address of domain %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of domain %s is %s" % (guestname, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of domain %s is %s" % (guestname, ip)) logger.info("ping to domain %s" % guestname) if utils.do_ping(ip, 0): logger.info("Success ping domain %s" % guestname) else: logger.error("fail to ping domain %s" % guestname) return 1 ret, pid_before = get_domain_pid(logger, guestname) if ret: return 1 logger.info("restart libvirtd service:") ret, out = utils.exec_cmd(RESTART_CMD, shell=True) if ret != 0: logger.error("failed to restart libvirtd") for i in range(len(out)): logger.error(out[i]) return 1 else: for i in range(len(out)): logger.info(out[i]) logger.info("recheck libvirtd status:") ret = libvirtd_check(logger) if ret: return 1 logger.info("ping to domain %s again" % guestname) if utils.do_ping(ip, 0): logger.info("Success ping domain %s" % guestname) else: logger.error("fail to ping domain %s" % guestname) return 1 ret, pid_after = get_domain_pid(logger, guestname) if ret: return 1 if pid_before != pid_after: logger.error("%s pid changed during libvirtd restart" % \ guestname) return 1 else: logger.info("domain pid not change, %s keeps running during \ libvirtd restart" % guestname) return 0
def install_windows_cdrom(params): """ install a windows guest virtual machine by using iso file """ # Initiate and check parameters global logger logger = params['logger'] guestname = params.get('guestname') guestos = params.get('guestos') guestarch = params.get('guestarch') xmlstr = params['xml'] logger.info("the name of guest is %s" % guestname) conn = sharedmod.libvirtobj['conn'] check_domain_state(conn, guestname) logger.info("the macaddress is %s" % params.get('macaddr', '52:54:00:97:e4:28')) diskpath = params.get('diskpath', '/var/lib/libvirt/images/libvirt-test-api') logger.info("disk image is %s" % diskpath) seeksize = params.get('disksize', 20) imageformat = params.get('imageformat', 'raw') logger.info("create disk image with size %sG, format %s" % (seeksize, imageformat)) disk_create = "qemu-img create -f %s %s %sG" % \ (imageformat, diskpath, seeksize) logger.debug("the command line of creating disk images is '%s'" % disk_create) (status, message) = commands.getstatusoutput(disk_create) if status != 0: logger.debug(message) return 1 os.chown(diskpath, 107, 107) logger.info("creating disk images file is successful.") hddriver = params.get('hddriver', 'virtio') if hddriver == 'virtio': xmlstr = xmlstr.replace('DEV', 'vda') elif hddriver == 'ide': xmlstr = xmlstr.replace('DEV', 'hda') elif hddriver == 'scsi': xmlstr = xmlstr.replace('DEV', 'sda') logger.info("get system environment information") envfile = os.path.join(HOME_PATH, 'global.cfg') logger.info("the environment file is %s" % envfile) # Get iso file based on guest os and arch from global.cfg envparser = env_parser.Envparser(envfile) iso_file = envparser.get_value("guest", guestos + '_' + guestarch) cdkey = envparser.get_value("guest", "%s_%s_key" % (guestos, guestarch)) windows_unattended_path = os.path.join(HOME_PATH, "repos/domain/windows_unattended") logger.debug('install source:\n %s' % iso_file) logger.info('prepare pre-installation environment...') iso_local_path = prepare_iso(iso_file) xmlstr = xmlstr.replace('WINDOWSISO', iso_local_path) status = prepare_floppy_image(guestname, guestos, guestarch, windows_unattended_path, cdkey, FLOOPY_IMG) if status: logger.error("making floppy image failed") return 1 xmlstr = xmlstr.replace('FLOPPY', FLOOPY_IMG) logger.debug('dump installation guest xml:\n%s' % xmlstr) # Generate guest xml installtype = params.get('type', 'define') if installtype == 'define': logger.info('define guest from xml description') try: domobj = conn.defineXML(xmlstr) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 logger.info('start installation guest ...') try: domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % guestname) return 1 elif installtype == 'create': logger.info('create guest from xml description') try: conn.createXML(xmlstr, 0) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 interval = 0 while (interval < 7200): time.sleep(20) if installtype == 'define': state = domobj.info()[0] if (state == libvirt.VIR_DOMAIN_SHUTOFF): logger.info("guest installaton of define type is complete.") logger.info("boot guest vm off harddisk") ret = prepare_boot_guest(domobj, xmlstr, guestname, installtype) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 20 logger.info('%s seconds passed away...' % interval) elif installtype == 'create': guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.info("guest installation of create type is complete.") logger.info("define the vm and boot it up") ret = prepare_boot_guest(domobj, xmlstr, guestname, installtype) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 20 logger.info('%s seconds passed away...' % interval) if interval == 7200: logger.info("guest installation timeout 7200s") return 1 else: logger.info("guest is booting up") logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 0) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout == 0: logger.info("fail to power on vm %s" % guestname) return 1 time.sleep(60) return 0
def destroy(params): """destroy domain Argument is a dictionary with two keys: {'guestname': guestname} logger -- an object of utils/log.py guestname -- the domain name flags -- optional arguments: noping: Don't do the ping test Return 0 on SUCCESS or 1 on FAILURE """ # Initiate and check parameters global logger logger = params['logger'] params.pop('logger') guestname = params['guestname'] br = params.get('bridgename', 'virbr0') flags = "" if 'flags' in params: flags = params['flags'] conn = sharedmod.libvirtobj['conn'] # Get running domain by name guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.error("guest %s doesn't exist or isn't running." % guestname) return 1 domobj = conn.lookupByName(guestname) timeout = 60 logger.info('destroy domain') if "noping" not in flags: # Get domain ip mac = utils.get_dom_mac_addr(guestname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180, br) logger.info("the ip address of guest is %s" % ip) # Destroy domain try: domobj.destroy() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("failed to destroy domain") return 1 # Check domain status by ping ip if "noping" not in flags: while timeout: time.sleep(10) timeout -= 10 logger.info(str(timeout) + "s left") logger.info('ping guest') if utils.do_ping(ip, 30): logger.error('The guest is still active, IP: ' + str(ip)) return 1 else: logger.info("domain %s was destroyed successfully" % guestname) break if timeout <= 0: logger.error("the domain couldn't be destroyed within 60 seconds.") return 1 return 0
def install_linux_net(params): """install a new virtual machine""" # Initiate and check parameters logger = params['logger'] guestname = params.get('guestname') guestos = params.get('guestos') guestarch = params.get('guestarch') xmlstr = params['xml'] installmethod = params.get('netmethod', 'http') logger.info("the name of guest is %s" % guestname) logger.info("the installation method is %s" % installmethod) conn = sharedmod.libvirtobj['conn'] check_domain_state(conn, guestname, logger) logger.info("the macaddress is %s" % params.get('macaddr', '52:54:00:97:e4:28')) diskpath = params.get( 'diskpath', '/var/lib/libvirt/images/libvirt-test-api') logger.info("disk image is %s" % diskpath) seeksize = params.get('disksize', 10) imageformat = params.get('imageformat', 'raw') logger.info( "create disk image with size %sG, format %s" % (seeksize, imageformat)) disk_create = "qemu-img create -f %s %s %sG" % \ (imageformat, diskpath, seeksize) logger.debug("the command line of creating disk images is '%s'" % disk_create) (status, message) = commands.getstatusoutput(disk_create) if status != 0: logger.debug(message) return 1 os.chown(diskpath, 107, 107) logger.info("creating disk images file is successful.") hddriver = params.get('hddriver', 'virtio') if hddriver == 'virtio': xmlstr = xmlstr.replace('DEV', 'vda') elif hddriver == 'ide': xmlstr = xmlstr.replace('DEV', 'hda') elif hddriver == 'scsi': xmlstr = xmlstr.replace('DEV', 'sda') logger.info("get system environment information") envfile = os.path.join(HOME_PATH, 'global.cfg') logger.info("the environment file is %s" % envfile) envparser = env_parser.Envparser(envfile) # Get http, ftp or nfs url based on guest os, arch # and installation method from global.cfg os_arch = guestos + "_" + guestarch if installmethod == 'http': ks = envparser.get_value("guest", os_arch + "_http_ks") elif installmethod == 'ftp': ks = envparser.get_value("guest", os_arch + "_ftp_ks") elif installmethod == "nfs": ks = envparser.get_value("guest", os_arch + "_nfs_ks") xmlstr = xmlstr.replace('KS', ks) ostree = envparser.get_value("guest", os_arch) logger.debug('install source:\n %s' % ostree) logger.debug('kisckstart file:\n %s' % ks) if (ostree == 'http://'): logger.error("no os tree defined in %s for %s" % (envfile, os_arch)) return 1 logger.info('prepare installation...') vmlinuzpath = os.path.join(ostree, 'isolinux/vmlinuz') initrdpath = os.path.join(ostree, 'isolinux/initrd.img') logger.debug("the url of vmlinuz file is %s" % vmlinuzpath) logger.debug("the url of initrd file is %s" % initrdpath) urllib.urlretrieve(vmlinuzpath, VMLINUZ) urllib.urlretrieve(initrdpath, INITRD) logger.debug("vmlinuz and initrd.img are located in %s" % BOOT_DIR) xmlstr = xmlstr.replace('KERNEL', VMLINUZ) xmlstr = xmlstr.replace('INITRD', INITRD) logger.debug('dump installation guest xml:\n%s' % xmlstr) installtype = params.get('type', 'define') if installtype == 'define': logger.info('define guest from xml description') try: domobj = conn.defineXML(xmlstr) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 logger.info('start installation guest ...') try: domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % guestname) return 1 elif installtype == 'create': logger.info('create guest from xml description') try: domobj = conn.createXML(xmlstr, 0) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define domain %s" % guestname) return 1 if 'rhel3u9' in guestos: interval = 0 logger.info("waiting 1000 seconds for the installation to complete...") while(interval < 1000): logger.info('%s seconds passed away...' % interval) time.sleep(10) interval += 10 domobj.destroy() ret = prepare_boot_guest( domobj, xmlstr, guestname, logger, installtype) if ret: logger.info("booting guest vm off harddisk failed") return 1 else: logger.info("guest is booting up") else: interval = 0 while(interval < 3600): time.sleep(10) if installtype is None or installtype == 'define': state = domobj.info()[0] if(state == libvirt.VIR_DOMAIN_SHUTOFF): logger.info("guest installaton of define type is complete") logger.info("boot guest vm off harddisk") ret = prepare_boot_guest(domobj, xmlstr, guestname, logger, installtype) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 10 logger.info('%s seconds passed away...' % interval) elif installtype == 'create': guest_names = [] ids = conn.listDomainsID() for id in ids: obj = conn.lookupByID(id) guest_names.append(obj.name()) if guestname not in guest_names: logger.info( "guest installation of create type is complete") logger.info("define the vm and boot it up") ret = prepare_boot_guest(domobj, xmlstr, guestname, logger, installtype) if ret: logger.info("booting guest vm off harddisk failed") return 1 break else: interval += 10 logger.info('%s seconds passed away...' % interval) if interval == 3600: logger.info("guest installation timeout 3600s") return 1 else: logger.info("guest is booting up") logger.info("get the mac address of vm %s" % guestname) mac = utils.get_dom_mac_addr(guestname) logger.info("the mac address of vm %s is %s" % (guestname, mac)) timeout = 300 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % guestname) logger.info("the ip address of vm %s is %s" % (guestname, ip)) break if timeout == 0: logger.info("fail to power on vm %s" % guestname) return 1 return 0
def set_vcpus(domobj, domain_name, vcpu): """set the value of virtual machine to vcpu offline , then boot up the virtual machine """ timeout = 60 logger.info('destroy domain') logger.info("get the mac address of vm %s" % domain_name) mac = utils.get_dom_mac_addr(domain_name) logger.info("the mac address of vm %s is %s" % (domain_name, mac)) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) try: domobj.destroy() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to destroy domain") return 1 while timeout: time.sleep(10) timeout -= 10 logger.info(str(timeout) + "s left") logger.info('ping guest') if utils.do_ping(ip, 30): logger.error('The guest is still active, IP: ' + str(ip)) else: logger.info("domain %s is destroied successfully" % domain_name) break if timeout <= 0: logger.error("the domain couldn't be destroied within 60 secs.") return 1 newguestxml = redefine_vcpu_number(domobj, domain_name, vcpu) logger.debug('''new guest %s xml :\n%s''' % (domain_name, newguestxml)) logger.info("undefine the original guest") try: domobj.undefine() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to undefine guest %s" % domain_name) return 1 logger.info("define guest with new xml") try: conn = domobj._conn conn.defineXML(newguestxml) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to define guest %s" % domain_name) return 1 try: logger.info('boot guest up ...') domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.message, e.get_error_code())) logger.error("fail to start domain %s" % domain_name) return 1 timeout = 600 while timeout: time.sleep(10) timeout -= 10 ip = utils.mac_to_ip(mac, 180) if not ip: logger.info(str(timeout) + "s left") else: logger.info("vm %s power on successfully" % domain_name) logger.info("the ip address of vm %s is %s" % (domain_name, ip)) break if timeout <= 0: logger.info("fail to power on vm %s" % domain_name) return 1 return 0
def managedsave_start(params): """ Start domain with managedsave image and check if its status is right according to given flags of running managedsave command.If it is correctly paused , resume it. Argument is a dictionary with two keys: {'logger': logger, 'guestname': guestname} logger -- an object of utils/log.py mandatory arguments : guestname -- same as the domain name optional arguments : flags -- domain create flags <none|start_paused |noping>.It allows only one flag be given. Return 0 on SUCCESS or 1 on FAILURE """ domname = params['guestname'] global logger logger = params['logger'] flags = params.get('flags', '') # Get given flags of managedsave if 'flagsave' in sharedmod.data: flagsave = sharedmod.data.get('flagsave') else: logger.error("Failed to get flags from managedsave") # Clean sharedmod.data sharedmod.data = {} conn = sharedmod.libvirtobj['conn'] domobj = conn.lookupByName(domname) timeout = 600 logger.info('start domain') # Check if guest has managedsave image before start if domobj.hasManagedSaveImage(0): logger.info("Domain has managedsave image") else: logger.info("Domain hasn't managedsave image") try: if "none" in flags: domobj.createWithFlags(NONE) elif "start_paused" in flags: domobj.createWithFlags(START_PAUSED) else: # this covers flags = None as well as flags = 'noping' domobj.create() except libvirtError as e: logger.error("API error message: %s, error code is %s" % e.message) logger.error("start failed") return 1 while timeout: state = domobj.info()[0] expect_states = [ libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED ] if state in expect_states: break time.sleep(10) timeout -= 10 logger.info(str(timeout) + "s left") if timeout <= 0: logger.error('The domain state is not as expected, state: ' + state) return 1 logger.info("Guest started") """If domain's current state is paused. Check if start command has --paused flag or managedsave has --paused flag (given flags in managedsave include '4'). If yes, it means domain successfully paused , then resume it. If not, throw error -guest state error.""" if state == libvirt.VIR_DOMAIN_PAUSED: if "start_paused" in flags or "4" in flagsave: logger.info("Guest paused successfully ") try: domobj.resume() except libvirtError as e: logger.error("API error message: %s, error code is %s" % e.message) logger.error("resume failed") return 1 stateresume = domobj.info()[0] expect_states = [ libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_NOSTATE, libvirt.VIR_DOMAIN_BLOCKED ] if stateresume not in expect_states: logger.error('The domain state is not equal to "paused"') return 1 else: logger.info('Domain resume successfully') return 0 else: logger.error("guest state error") return 1 # Get domain ip and ping ip to check domain's status if "noping" not in flags: mac = utils.get_dom_mac_addr(domname) logger.info("get ip by mac address") ip = utils.mac_to_ip(mac, 180) logger.info('ping guest') if not utils.do_ping(ip, 300): logger.error('Failed on ping guest, IP: ' + str(ip)) return 1 # Check if domain' managedsave image exists,if not, return 0. if not domobj.hasManagedSaveImage(0) and check_savefile_remove(domname): logger.info("Domain %s with managedsave image successfully start" % domname) return 0 else: logger.error("Fail to start domain %s with managedsave image" % domname) return 1