def run(test, params, env):
    """
    Test migration of multi vms.
    """
    vm_names = params.get("vms").split()
    if len(vm_names) < 2:
        raise error.TestNAError("No multi vms provided.")

    # Prepare parameters
    method = params.get("virsh_migrate_method")
    simultaneous = "yes" == params.get("simultaneous_migration", "no")
    jobabort = "yes" == params.get("virsh_migrate_jobabort", "no")
    options = params.get("virsh_migrate_options", "")
    status_error = "yes" == params.get("status_error", "no")
    #remote_migration = "yes" == params.get("remote_migration", "no")
    remote_host = params.get("remote_host", "DEST_HOSTNAME.EXAMPLE.COM")
    local_host = params.get("local_host", "SOURCE_HOSTNAME.EXAMPLE.COM")
    host_user = params.get("host_user", "root")
    host_passwd = params.get("host_password", "PASSWORD")
    desturi = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                dest_ip=remote_host)
    srcuri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                               dest_ip=local_host)

    # Don't allow the defaults.
    if srcuri.count('///') or srcuri.count('EXAMPLE'):
        raise error.TestNAError("The srcuri '%s' is invalid", srcuri)
    if desturi.count('///') or desturi.count('EXAMPLE'):
        raise error.TestNAError("The desturi '%s' is invalid", desturi)

    # Config ssh autologin for remote host
    ssh_key.setup_ssh_key(remote_host, host_user, host_passwd, port=22)

    # Prepare MigrationHelper instance
    helpers = []
    for vm_name in vm_names:
        helper = MigrationHelper(vm_name, test, params, env)
        helper.set_virsh_instance()
        helper.set_migration_cmd(options, method, desturi)
        helpers.append(helper)

    for helper in helpers:
        vm = helper.vm
        if vm.is_dead():
            vm.start()
        vm.wait_for_login()

    try:
        multi_migration(helpers, simultaneous=False, jobabort=False)
    finally:
        for helper in helpers:
            helper.virsh_instance.close_session()
            helper.cleanup_vm(srcuri, desturi)

        if not ret_migration:
            if not status_error:
                raise error.TestFail("Migration test failed.")
        if not ret_jobabort:
            if not status_error:
                raise error.TestFail("Abort migration failed.")
 def run_test(self):
     """
     Start test, Creat a threading to migrate VM.
     """
     remote_uri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                    dest_ip=self.remote_ip)
     option = "--live"
     if self.time_out_test:
         option += " --timeout %s" % self.time_out
     self.td = threading.Thread(target=virsh.migrate,
                                args=(self.vm_name, remote_uri, option))
     self.td.start()
def run(test, params, env):
    """
    Test migration of multi vms.
    """
    vm_names = params.get("migrate_vms").split()
    if len(vm_names) < 2:
        raise exceptions.TestSkipError("No multi vms provided.")

    # Prepare parameters
    method = params.get("virsh_migrate_method")
    jobabort = "yes" == params.get("virsh_migrate_jobabort", "no")
    options = params.get("virsh_migrate_options", "")
    status_error = "yes" == params.get("status_error", "no")
    remote_host = params.get("remote_host", "DEST_HOSTNAME.EXAMPLE.COM")
    local_host = params.get("local_host", "SOURCE_HOSTNAME.EXAMPLE.COM")
    host_user = params.get("host_user", "root")
    host_passwd = params.get("host_password", "PASSWORD")
    nfs_shared_disk = params.get("nfs_shared_disk", True)
    migration_type = params.get("virsh_migration_type", "simultaneous")
    migrate_timeout = int(params.get("virsh_migrate_thread_timeout", 900))
    migration_time = int(params.get("virsh_migrate_timeout", 60))

    # Params for NFS and SSH setup
    params["server_ip"] = params.get("migrate_dest_host")
    params["server_user"] = "******"
    params["server_pwd"] = params.get("migrate_dest_pwd")
    params["client_ip"] = params.get("migrate_source_host")
    params["client_user"] = "******"
    params["client_pwd"] = params.get("migrate_source_pwd")
    params["nfs_client_ip"] = params.get("migrate_dest_host")
    params["nfs_server_ip"] = params.get("migrate_source_host")
    desturi = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                dest_ip=remote_host)
    srcuri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                               dest_ip=local_host)

    # Don't allow the defaults.
    if srcuri.count('///') or srcuri.count('EXAMPLE'):
        raise exceptions.TestSkipError("The srcuri '%s' is invalid" % srcuri)
    if desturi.count('///') or desturi.count('EXAMPLE'):
        raise exceptions.TestSkipError("The desturi '%s' is invalid" % desturi)

    # Config ssh autologin for remote host
    ssh_key.setup_remote_ssh_key(remote_host, host_user, host_passwd, port=22,
                                 public_key="rsa")

    # Prepare local session and remote session
    localrunner = remote.RemoteRunner(host=remote_host, username=host_user,
                                      password=host_passwd)
    remoterunner = remote.RemoteRunner(host=remote_host, username=host_user,
                                       password=host_passwd)
    # Configure NFS in remote host
    if nfs_shared_disk:
        nfs_client = nfs.NFSClient(params)
        nfs_client.setup()

    # Prepare MigrationHelper instance
    vms = []
    for vm_name in vm_names:
        vm = env.get_vm(vm_name)
        vms.append(vm)

    try:
        option = make_migration_options(method, options, migration_time)

        # make sure cache=none
        if "unsafe" not in options:
            device_target = params.get("virsh_device_target", "sda")
            for vm in vms:
                if vm.is_alive():
                    vm.destroy()
            for each_vm in vm_names:
                logging.info("configure cache=none")
                vmxml = vm_xml.VMXML.new_from_dumpxml(each_vm)
                device_source = str(vmxml.get_disk_attr(each_vm, device_target,
                                                        'source', 'file'))
                ret_detach = virsh.detach_disk(each_vm, device_target,
                                               "--config")
                status = ret_detach.exit_status
                output = ret_detach.stdout.strip()
                logging.info("Status:%s", status)
                logging.info("Output:\n%s", output)
                if not ret_detach:
                    raise exceptions.TestError("Detach disks fails")

                subdriver = utils_test.get_image_info(device_source)['format']
                ret_attach = virsh.attach_disk(each_vm, device_source,
                                               device_target, "--driver qemu "
                                               "--config --cache none "
                                               "--subdriver %s" % subdriver)
                status = ret_attach.exit_status
                output = ret_attach.stdout.strip()
                logging.info("Status:%s", status)
                logging.info("Output:\n%s", output)
                if not ret_attach:
                    raise exceptions.TestError("Attach disks fails")

        for vm in vms:
            if vm.is_dead():
                vm.start()
                vm.wait_for_login()
        multi_migration(vms, srcuri, desturi, option, migration_type,
                        migrate_timeout, jobabort, lrunner=localrunner,
                        rrunner=remoterunner)
    except Exception, info:
        logging.error("Test failed: %s" % info)
        flag_migration = False
Esempio n. 4
0
def run(test, params, env):
    """
    Test command: virsh connect.
    """
    def unix_transport_setup():
        """
        Setup a unix connect to local libvirtd.
        """
        shutil.copy(libvirtd_conf_path, libvirtd_conf_bak_path)

        with open(libvirtd_conf_path, 'r') as libvirtdconf_file:
            line_list = libvirtdconf_file.readlines()
        conf_dict = {r'auth_unix_rw\s*=': 'auth_unix_rw="none"\n', }
        for key in conf_dict:
            pattern = key
            conf_line = conf_dict[key]
            flag = False
            for index in range(len(line_list)):
                line = line_list[index]
                if not re.search(pattern, line):
                    continue
                else:
                    line_list[index] = conf_line
                    flag = True
                    break
            if not flag:
                line_list.append(conf_line)

        with open(libvirtd_conf_path, 'w') as libvirtdconf_file:
            libvirtdconf_file.writelines(line_list)

        # restart libvirtd service
        utils_libvirtd.libvirtd_restart()

    def unix_transport_recover():
        """
        Recover the libvirtd on local.
        """
        if os.path.exists(libvirtd_conf_bak_path):
            shutil.copy(libvirtd_conf_bak_path, libvirtd_conf_path)
            utils_libvirtd.libvirtd_restart()

    # get the params from subtests.
    # params for general.
    connect_arg = params.get("connect_arg", "")
    connect_opt = params.get("connect_opt", "")
    status_error = params.get("status_error", "no")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    client_ip = local_ip
    client_pwd = local_pwd
    server_ip = local_ip
    server_pwd = local_pwd

    # params special for tls connect.
    server_cn = params.get("connect_server_cn", "TLSServer")
    client_cn = params.get("connect_client_cn", "TLSClient")

    # params special for tcp connect.
    tcp_port = params.get("tcp_port", '16509')

    # params special for unix transport.
    libvirtd_conf_path = '/etc/libvirt/libvirtd.conf'
    libvirtd_conf_bak_path = '%s/libvirtd.conf.bak' % data_dir.get_tmp_dir()

    # check the config
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_ip.count("ENTER")):
        test.cancel("Parameter local_ip is not configured"
                    "in remote test.")
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_pwd.count("ENTER")):
        test.cancel("Parameter local_pwd is not configured"
                    "in remote test.")
    # In Ubuntu libvirt_lxc available in /usr/lib/libvirt
    if (connect_arg.count("lxc") and
            (not (os.path.exists("/usr/libexec/libvirt_lxc") or
                  os.path.exists("/usr/lib/libvirt/libvirt_lxc")))):
        test.cancel("Connect test of lxc:/// is not suggested on "
                    "the host with no lxc driver.")
    if connect_arg.count("xen") and (not os.path.exists("/var/run/xend")):
        test.cancel("Connect test of xen:/// is not suggested on "
                    "the host with no xen driver.")
    if connect_arg.count("qemu") and (not os.path.exists("/dev/kvm")):
        test.cancel("Connect test of qemu:/// is not suggested"
                    "on the host with no qemu driver.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=client_ip,
                                                      client_pwd=client_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport, dest_ip=server_ip)
        elif transport == "tls":
            tls_connection = utils_conn.TLSConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=client_ip,
                                                      client_pwd=client_pwd,
                                                      server_cn=server_cn,
                                                      client_cn=client_cn)
            tls_connection.conn_setup()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport, dest_ip=server_cn)
        elif transport == "tcp":
            tcp_connection = utils_conn.TCPConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      tcp_port=tcp_port)
            tcp_connection.conn_setup()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip="%s:%s"
                % (server_ip, tcp_port))
        elif transport == "unix":
            unix_transport_setup()
            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip="")
        else:
            test.cancel("Configuration of transport=%s is "
                        "not recognized." % transport)
    else:
        connect_uri = connect_arg

    try:
        try:
            uri = do_virsh_connect(connect_uri, connect_opt)
            # connect successfully
            if status_error == "yes":
                test.fail("Connect successfully in the "
                          "case expected to fail.")
            # get the expect uri when connect argument is ""
            if connect_uri == "":
                connect_uri = virsh.canonical_uri().split()[-1]

            logging.debug("expected uri is: %s", connect_uri)
            logging.debug("actual uri after connect is: %s", uri)
            if not uri == connect_uri:
                test.fail("Command exit normally but the uri is "
                          "not setted as expected.")
        except process.CmdError as detail:
            if status_error == "no":
                test.fail("Connect failed in the case expected"
                          "to success.\n"
                          "Error: %s" % detail)
    finally:
        if transport == "unix":
            unix_transport_recover()
        if transport == "tcp":
            tcp_connection.conn_recover()
        if transport == "tls":
            tls_connection.conn_recover()
Esempio n. 5
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    connect_uri = None
    # check the config
    if (connect_arg == "transport" and transport_type == "remote"
            and local_ip.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_ip is not configured "
                                       "in remote test.")
    if (connect_arg == "transport" and transport_type == "remote"
            and local_pwd.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_pwd is not configured "
                                       "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip=server_ip)
            virsh_dargs = {
                'remote_ip': server_ip,
                'remote_user': '******',
                'remote_pwd': server_pwd,
                'ssh_remote_auth': True
            }
            virsh_instance = virsh.VirshPersistent(**virsh_dargs)
    else:
        connect_uri = connect_arg
        virsh_instance = virsh

    if libvirt_version.version_compare(2, 3, 0):
        try:
            maxvcpus = None
            maxvcpus_cap = None
            dom_capabilities = None
            # make sure we take maxvcpus from right host, helps in case remote
            try:
                dom_capabilities = domcap.DomCapabilityXML(
                    virsh_instance=virsh_instance)
                maxvcpus = dom_capabilities.max
                logging.debug(
                    "maxvcpus calculate from domcapabilities "
                    "is %s", maxvcpus)
            except Exception as details:
                raise exceptions.TestFail("Failed to get maxvcpus from "
                                          "domcapabilities xml:\n%s" %
                                          dom_capabilities)
            try:
                cap_xml = capability_xml.CapabilityXML()
                maxvcpus_cap = cap_xml.get_guest_capabilities()['hvm'][
                    platform.machine()]['maxcpus']
                logging.debug('maxvcpus_cap is %s', maxvcpus_cap)
            except Exception as details:
                logging.debug(
                    "Failed to get maxvcpu from virsh "
                    "capabilities: %s", details)
                # Let's fall back in case of failure
                maxvcpus_cap = maxvcpus
            if not maxvcpus:
                raise exceptions.TestFail("Failed to get max value for vcpu"
                                          "from domcapabilities "
                                          "xml:\n%s" % dom_capabilities)
        except Exception as details:
            raise exceptions.TestFail(
                "Failed get the virsh instance with uri: "
                "%s\n Details: %s" % (connect_uri, details))

    is_arm = "aarch" in platform.machine()
    gic_version = ''
    if is_arm:
        for gic_enum in domcap.DomCapabilityXML()['features']['gic_enums']:
            if gic_enum['name'] == "version":
                gic_version = gic_enum['values'][0].get_value()

    # Run test case
    result = virsh.maxvcpus(option,
                            uri=connect_uri,
                            ignore_status=True,
                            debug=True)

    maxvcpus_test = result.stdout.strip()
    status = result.exit_status

    # Check status_error
    if status_error == "yes":
        if status == 0:
            raise exceptions.TestFail("Run succeeded with unsupported option!")
        else:
            logging.info("Run failed with unsupported option %s " % option)
    elif status_error == "no":
        if status == 0:
            if not libvirt_version.version_compare(2, 3, 0):
                if "kqemu" in option:
                    if not maxvcpus_test == '1':
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " %
                                                  (maxvcpus_test, option))
                elif option in ['qemu', '--type qemu', '']:
                    if not maxvcpus_test == '16':
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " %
                                                  (maxvcpus_test, option))
                else:
                    # No check with other types
                    pass
            else:
                # It covers all possible combinations
                if option in [
                        'qemu', 'kvm', '--type qemu', '--type kvm', 'kqemu',
                        '--type kqemu', ''
                ]:
                    if (is_arm and gic_version == '2'
                            and option in ['kvm', '']):
                        if not maxvcpus_test == '8':
                            raise exceptions.TestFail(
                                "Command output %s is not "
                                "expected for %s " % (maxvcpus_test, option))
                    elif not (maxvcpus_test == maxvcpus
                              or maxvcpus_test == maxvcpus_cap):
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " %
                                                  (maxvcpus_test, option))
                else:
                    # No check with other types
                    pass
        else:
            raise exceptions.TestFail("Run command failed")
Esempio n. 6
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")

    # check the config
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_ip.count("ENTER")):
        raise error.TestNAError("Parameter local_ip is not configured"
                                "in remote test.")
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_pwd.count("ENTER")):
        raise error.TestNAError("Parameter local_pwd is not configured"
                                "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport, dest_ip=server_ip)
    else:
        connect_uri = connect_arg

    # Run test case
    result = virsh.maxvcpus(option, uri=connect_uri, ignore_status=True,
                            debug=True)

    maxvcpus_test = result.stdout.strip()
    status = result.exit_status

    # Check status_error
    if status_error == "yes":
        if status == 0:
            raise error.TestFail("Run successed with unsupported option!")
        else:
            logging.info("Run failed with unsupported option %s " % option)
    elif status_error == "no":
        if status == 0:
            if "kqemu" in option:
                if not maxvcpus_test == '1':
                    raise error.TestFail("Command output %s is not expected "
                                         "for %s " % (maxvcpus_test, option))
            elif option == 'qemu' or option == '--type qemu' or option == '':
                if not maxvcpus_test == '16':
                    raise error.TestFail("Command output %s is not expected "
                                         "for %s " % (maxvcpus_test, option))
            else:
                # No check with other types
                pass
        else:
            raise error.TestFail("Run command failed")
Esempio n. 7
0
def run(test, params, env):
    """
    Test migration of multi vms.
    """
    vm_names = params.get("migrate_vms").split()
    if len(vm_names) < 2:
        raise error.TestNAError("No multi vms provided.")

    # Prepare parameters
    method = params.get("virsh_migrate_method")
    simultaneous = "yes" == params.get("simultaneous_migration", "no")
    jobabort = "yes" == params.get("virsh_migrate_jobabort", "no")
    options = params.get("virsh_migrate_options", "")
    status_error = "yes" == params.get("status_error", "no")
    #remote_migration = "yes" == params.get("remote_migration", "no")
    remote_host = params.get("remote_host", "DEST_HOSTNAME.EXAMPLE.COM")
    local_host = params.get("local_host", "SOURCE_HOSTNAME.EXAMPLE.COM")
    host_user = params.get("host_user", "root")
    host_passwd = params.get("host_password", "PASSWORD")
    desturi = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                dest_ip=remote_host)
    srcuri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                               dest_ip=local_host)

    # Don't allow the defaults.
    if srcuri.count('///') or srcuri.count('EXAMPLE'):
        raise error.TestNAError("The srcuri '%s' is invalid" % srcuri)
    if desturi.count('///') or desturi.count('EXAMPLE'):
        raise error.TestNAError("The desturi '%s' is invalid" % desturi)

    # Config ssh autologin for remote host
    ssh_key.setup_ssh_key(remote_host, host_user, host_passwd, port=22)

    # Prepare local session and remote session
    localrunner = remote.RemoteRunner(host=remote_host,
                                      username=host_user,
                                      password=host_passwd)
    remoterunner = remote.RemoteRunner(host=remote_host,
                                       username=host_user,
                                       password=host_passwd)

    # Prepare MigrationHelper instance
    helpers = []
    for vm_name in vm_names:
        helper = MigrationHelper(vm_name, test, params, env)
        helper.set_virsh_instance()
        helper.set_migration_cmd(options, method, desturi)
        helpers.append(helper)

    for helper in helpers:
        vm = helper.vm
        if vm.is_dead():
            vm.start()
        vm.wait_for_login()
        # Used for checking downtime
        helper.vm_ip = vm.get_address()

    try:
        multi_migration(helpers,
                        simultaneous=False,
                        jobabort=False,
                        lrunner=localrunner,
                        rrunner=remoterunner)
    finally:
        for helper in helpers:
            helper.virsh_instance.close_session()
            helper.cleanup_vm(srcuri, desturi)

        localrunner.session.close()
        remoterunner.session.close()

        if not ret_migration:
            if not status_error:
                raise error.TestFail("Migration test failed.")
        if not ret_jobabort:
            if not status_error:
                raise error.TestFail("Abort migration failed.")
        if not ret_downtime_tolerable:
            raise error.TestFail("Downtime during migration is intolerable.")
Esempio n. 8
0
def run(test, params, env):
    """
    Test command: virsh connect.
    """
    def unix_transport_setup():
        """
        Setup a unix connect to local libvirtd.
        """
        shutil.copy(libvirtd_conf_path, libvirtd_conf_bak_path)

        with open(libvirtd_conf_path, 'r') as libvirtdconf_file:
            line_list = libvirtdconf_file.readlines()
        conf_dict = {
            r'auth_unix_rw\s*=': 'auth_unix_rw="none"\n',
        }
        for key in conf_dict:
            pattern = key
            conf_line = conf_dict[key]
            flag = False
            for index in range(len(line_list)):
                line = line_list[index]
                if not re.search(pattern, line):
                    continue
                else:
                    line_list[index] = conf_line
                    flag = True
                    break
            if not flag:
                line_list.append(conf_line)

        with open(libvirtd_conf_path, 'w') as libvirtdconf_file:
            libvirtdconf_file.writelines(line_list)

        # restart libvirtd service
        utils_libvirtd.libvirtd_restart()

    def unix_transport_recover():
        """
        Recover the libvirtd on local.
        """
        if os.path.exists(libvirtd_conf_bak_path):
            shutil.copy(libvirtd_conf_bak_path, libvirtd_conf_path)
            utils_libvirtd.libvirtd_restart()

    # get the params from subtests.
    # params for general.
    connect_arg = params.get("connect_arg", "")
    connect_opt = params.get("connect_opt", "")
    status_error = params.get("status_error", "no")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    client_ip = local_ip
    client_pwd = local_pwd
    server_ip = local_ip
    server_pwd = local_pwd

    # params special for tls connect.
    server_cn = params.get("connect_server_cn", "TLSServer")
    client_cn = params.get("connect_client_cn", "TLSClient")

    # params special for tcp connect.
    tcp_port = params.get("tcp_port", '16509')

    # params special for unix transport.
    libvirtd_conf_path = '/etc/libvirt/libvirtd.conf'
    libvirtd_conf_bak_path = '%s/libvirtd.conf.bak' % data_dir.get_tmp_dir()

    # special params for test connection alive
    alive = params.get('alive', None)

    if alive:
        check_virsh_connect_alive(test, params)
        return

    # check the config
    if (connect_arg == "transport" and transport_type == "remote"
            and local_ip.count("ENTER")):
        test.cancel("Parameter local_ip is not configured" "in remote test.")
    if (connect_arg == "transport" and transport_type == "remote"
            and local_pwd.count("ENTER")):
        test.cancel("Parameter local_pwd is not configured" "in remote test.")
    # In Ubuntu libvirt_lxc available in /usr/lib/libvirt
    if (connect_arg.count("lxc")
            and (not (os.path.exists("/usr/libexec/libvirt_lxc")
                      or os.path.exists("/usr/lib/libvirt/libvirt_lxc")))):
        test.cancel("Connect test of lxc:/// is not suggested on "
                    "the host with no lxc driver.")
    if connect_arg.count("xen") and (not os.path.exists("/var/run/xend")):
        test.cancel("Connect test of xen:/// is not suggested on "
                    "the host with no xen driver.")
    if connect_arg.count("qemu") and (not os.path.exists("/dev/kvm")):
        test.cancel("Connect test of qemu:/// is not suggested"
                    "on the host with no qemu driver.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=client_ip,
                                                      client_pwd=client_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip=server_ip)
        elif transport == "tls":
            tls_connection = utils_conn.TLSConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=client_ip,
                                                      client_pwd=client_pwd,
                                                      server_cn=server_cn,
                                                      client_cn=client_cn,
                                                      special_cn='yes')
            tls_connection.conn_setup()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip=server_cn)
        elif transport == "tcp":
            tcp_connection = utils_conn.TCPConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      tcp_port=tcp_port)
            tcp_connection.conn_setup()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip="%s:%s" % (server_ip, tcp_port))
        elif transport == "unix":
            unix_transport_setup()
            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type, transport=transport, dest_ip="")
        else:
            test.cancel("Configuration of transport=%s is "
                        "not recognized." % transport)
    else:
        connect_uri = connect_arg

    try:
        try:
            uri = do_virsh_connect(connect_uri, connect_opt)
            # connect successfully
            if status_error == "yes":
                test.fail("Connect successfully in the "
                          "case expected to fail.")
            # get the expect uri when connect argument is ""
            if connect_uri == "":
                connect_uri = virsh.canonical_uri().split()[-1]

            logging.debug("expected uri is: %s", connect_uri)
            logging.debug("actual uri after connect is: %s", uri)
            if not uri == connect_uri:
                test.fail("Command exit normally but the uri is "
                          "not set as expected.")
        except process.CmdError as detail:
            if status_error == "no":
                test.fail("Connect failed in the case expected"
                          "to success.\n"
                          "Error: %s" % detail)
    finally:
        if transport == "unix":
            unix_transport_recover()
        if transport == "tcp":
            tcp_connection.conn_recover()
        if transport == "tls":
            tls_connection.conn_recover()
Esempio n. 9
0
def run(test, params, env):
    """
    Test migration of multi vms.
    """
    vm_names = params.get("migrate_vms").split()
    if len(vm_names) < 2:
        raise exceptions.TestSkipError("No multi vms provided.")

    # Prepare parameters
    method = params.get("virsh_migrate_method")
    jobabort = "yes" == params.get("virsh_migrate_jobabort", "no")
    options = params.get("virsh_migrate_options", "")
    status_error = "yes" == params.get("status_error", "no")
    remote_host = params.get("remote_host", "DEST_HOSTNAME.EXAMPLE.COM")
    local_host = params.get("local_host", "SOURCE_HOSTNAME.EXAMPLE.COM")
    host_user = params.get("host_user", "root")
    host_passwd = params.get("host_password", "PASSWORD")
    nfs_shared_disk = params.get("nfs_shared_disk", True)
    migration_type = params.get("virsh_migration_type", "simultaneous")
    migrate_timeout = int(params.get("virsh_migrate_thread_timeout", 900))
    migration_time = int(params.get("virsh_migrate_timeout", 60))

    # Params for NFS and SSH setup
    params["server_ip"] = params.get("migrate_dest_host")
    params["server_user"] = "******"
    params["server_pwd"] = params.get("migrate_dest_pwd")
    params["client_ip"] = params.get("migrate_source_host")
    params["client_user"] = "******"
    params["client_pwd"] = params.get("migrate_source_pwd")
    params["nfs_client_ip"] = params.get("migrate_dest_host")
    params["nfs_server_ip"] = params.get("migrate_source_host")
    desturi = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                dest_ip=remote_host)
    srcuri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                               dest_ip=local_host)

    # Don't allow the defaults.
    if srcuri.count('///') or srcuri.count('EXAMPLE'):
        raise exceptions.TestSkipError("The srcuri '%s' is invalid" % srcuri)
    if desturi.count('///') or desturi.count('EXAMPLE'):
        raise exceptions.TestSkipError("The desturi '%s' is invalid" % desturi)

    # Config ssh autologin for remote host
    ssh_key.setup_remote_ssh_key(remote_host,
                                 host_user,
                                 host_passwd,
                                 port=22,
                                 public_key="rsa")

    # Prepare local session and remote session
    localrunner = remote.RemoteRunner(host=remote_host,
                                      username=host_user,
                                      password=host_passwd)
    remoterunner = remote.RemoteRunner(host=remote_host,
                                       username=host_user,
                                       password=host_passwd)
    # Configure NFS in remote host
    if nfs_shared_disk:
        nfs_client = nfs.NFSClient(params)
        nfs_client.setup()

    # Prepare MigrationHelper instance
    vms = []
    for vm_name in vm_names:
        vm = env.get_vm(vm_name)
        vms.append(vm)

    try:
        option = make_migration_options(method, options, migration_time)

        # make sure cache=none
        if "unsafe" not in options:
            device_target = params.get("virsh_device_target", "sda")
            for vm in vms:
                if vm.is_alive():
                    vm.destroy()
            for each_vm in vm_names:
                logging.info("configure cache=none")
                vmxml = vm_xml.VMXML.new_from_dumpxml(each_vm)
                device_source = str(
                    vmxml.get_disk_attr(each_vm, device_target, 'source',
                                        'file'))
                ret_detach = virsh.detach_disk(each_vm, device_target,
                                               "--config")
                status = ret_detach.exit_status
                output = ret_detach.stdout.strip()
                logging.info("Status:%s", status)
                logging.info("Output:\n%s", output)
                if not ret_detach:
                    raise exceptions.TestError("Detach disks fails")

                subdriver = utils_test.get_image_info(device_source)['format']
                ret_attach = virsh.attach_disk(
                    each_vm, device_source, device_target, "--driver qemu "
                    "--config --cache none "
                    "--subdriver %s" % subdriver)
                status = ret_attach.exit_status
                output = ret_attach.stdout.strip()
                logging.info("Status:%s", status)
                logging.info("Output:\n%s", output)
                if not ret_attach:
                    raise exceptions.TestError("Attach disks fails")

        for vm in vms:
            if vm.is_dead():
                vm.start()
                vm.wait_for_login()
        multi_migration(vms,
                        srcuri,
                        desturi,
                        option,
                        migration_type,
                        migrate_timeout,
                        jobabort,
                        lrunner=localrunner,
                        rrunner=remoterunner)
    except Exception as info:
        logging.error("Test failed: %s" % info)
        flag_migration = False

    # NFS cleanup
    if nfs_shared_disk:
        logging.info("NFS cleanup")
        nfs_client.cleanup(ssh_auto_recover=False)

    localrunner.session.close()
    remoterunner.session.close()

    if not (ret_migration or flag_migration):
        if not status_error:
            raise exceptions.TestFail("Migration test failed")
    if not ret_jobabort:
        if not status_error:
            raise exceptions.TestFail("Abort migration failed")
    if not ret_downtime_tolerable:
        raise exceptions.TestFail("Downtime during migration is intolerable")
Esempio n. 10
0
def run(test, params, env):
    """
    Test command: virsh nodesuspend <target> <duration>

    This command will make host suspend or hibernate, running tests on testing
    grid may cause unexpected behavior.

    This tests only work when test runner setup a remote host (physical or
    virtual) with testing version of libvirt daemon running. After that change
    the remote_xxx parameters in configuration file to corresponding value.
    """
    # Retrive parameters
    remote_ip = params.get('nodesuspend_remote_ip',
                           'ENTER.YOUR.REMOTE.EXAMPLE.COM')
    remote_user = params.get('nodesuspend_remote_user', 'root')
    remote_pwd = params.get('nodesuspend_remote_pwd', 'EXAMPLE.PWD')
    suspend_target = params.get('suspend_target', 'mem')
    suspend_time = int(params.get('suspend_time', '60'))
    upper_tolerance = int(params.get('upper_tolerance', '8'))
    lower_tolerance = int(params.get('lower_tolerance', '0'))
    expect_succeed = params.get('expect_succeed', 'yes')

    # Check if remote_ip is set
    if 'EXAMPLE' in remote_ip:
        msg = ('Configuration parameter `nodesuspend_remote_ip` need to be '
               'changed to the ip of host to be tested')
        raise error.TestNAError(msg)

    # Create remote virsh session
    remote_uri = libvirt_vm.get_uri_with_transport(
        transport="ssh", dest_ip=remote_ip)
    virsh_dargs = {
        'remote_user': remote_user,
        'remote_pwd': remote_pwd,
        'uri': remote_uri}
    try:
        vrsh = virsh.VirshPersistent(**virsh_dargs)
    except (LoginTimeoutError, LoginProcessTerminatedError):
        raise error.TestNAError('Cannot login to remote host, Skipping')

    # Run test
    result = vrsh.nodesuspend(suspend_target, suspend_time, ignore_status=True)
    logging.debug(result)

    # Check real suspend time if command successfully run
    if result.exit_status == 0:
        try:
            down_time = check_host_down_time(
                remote_ip,
                timeout=suspend_time + upper_tolerance)

            # Wait for PM to return completely
            time.sleep(5)

            # Check if host down time within tolerance
            if not (suspend_time - lower_tolerance
                    < down_time
                    < suspend_time + upper_tolerance):
                raise error.TestFail('Down time (%.2fs) not in range (%ds)'
                                     '+ (%ds) - (%ds).'
                                     % (down_time, suspend_time,
                                        upper_tolerance, lower_tolerance))
        except TimeoutError, e:
            # Mark test FAIL if down time exceeds expectation
            logging.debug(e)
            vrsh.close_session()
            raise error.TestFail('Timeout when checking host down time.')
Esempio n. 11
0
def run(test, params, env):
    """
    Test command: virsh nodesuspend <target> <duration>

    This command will make host suspend or hibernate, running tests on testing
    grid may cause unexpected behavior.

    This tests only work when test runner setup a remote host (physical or
    virtual) with testing version of libvirt daemon running. After that change
    the remote_xxx parameters in configuration file to corresponding value.
    """
    # Retrive parameters
    remote_ip = params.get('nodesuspend_remote_ip',
                           'ENTER.YOUR.REMOTE.EXAMPLE.COM')
    remote_user = params.get('nodesuspend_remote_user', 'root')
    remote_pwd = params.get('nodesuspend_remote_pwd', 'EXAMPLE.PWD')
    suspend_target = params.get('suspend_target', 'mem')
    suspend_time = int(params.get('suspend_time', '60'))
    upper_tolerance = int(params.get('upper_tolerance', '8'))
    lower_tolerance = int(params.get('lower_tolerance', '0'))
    expect_succeed = params.get('expect_succeed', 'yes')

    # Check if remote_ip is set
    if 'EXAMPLE' in remote_ip:
        msg = ('Configuration parameter `nodesuspend_remote_ip` need to be '
               'changed to the ip of host to be tested')
        raise error.TestNAError(msg)

    # Create remote virsh session
    remote_uri = libvirt_vm.get_uri_with_transport(transport="ssh",
                                                   dest_ip=remote_ip)
    virsh_dargs = {
        'remote_user': remote_user,
        'remote_pwd': remote_pwd,
        'uri': remote_uri
    }
    try:
        vrsh = virsh.VirshPersistent(**virsh_dargs)
    except (LoginTimeoutError, LoginProcessTerminatedError):
        raise error.TestNAError('Cannot login to remote host, Skipping')

    # Run test
    result = vrsh.nodesuspend(suspend_target, suspend_time, ignore_status=True)
    logging.debug(result)

    # Check real suspend time if command successfully run
    if result.exit_status == 0:
        try:
            down_time = check_host_down_time(remote_ip,
                                             timeout=suspend_time +
                                             upper_tolerance)

            # Wait for PM to return completely
            time.sleep(5)

            # Check if host down time within tolerance
            if not (suspend_time - lower_tolerance < down_time <
                    suspend_time + upper_tolerance):
                raise error.TestFail('Down time (%.2fs) not in range (%ds)'
                                     '+ (%ds) - (%ds).' %
                                     (down_time, suspend_time, upper_tolerance,
                                      lower_tolerance))
        except TimeoutError, e:
            # Mark test FAIL if down time exceeds expectation
            logging.debug(e)
            vrsh.close_session()
            raise error.TestFail('Timeout when checking host down time.')
Esempio n. 12
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    connect_uri = None
    # check the config
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_ip.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_ip is not configured "
                                       "in remote test.")
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_pwd.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_pwd is not configured "
                                       "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport, dest_ip=server_ip)
    else:
        connect_uri = connect_arg

    if libvirt_version.version_compare(2, 3, 0):
        try:
            maxvcpus = None
            dom_capabilities = None
            # make sure we take maxvcpus from right host, helps incase remote
            try:
                dom_capabilities = domcap.DomCapabilityXML()
                maxvcpus = dom_capabilities.max
                logging.debug("maxvcpus calculate from domcapabilities "
                              "is %s", maxvcpus)
            except Exception as details:
                raise exceptions.TestFail("Failed to get maxvcpus from "
                                          "domcapabilities xml:\n%s"
                                          % dom_capabilities)
            if not maxvcpus:
                raise exceptions.TestFail("Failed to get max value for vcpu"
                                          "from domcapabilities "
                                          "xml:\n%s" % dom_capabilities)
        except Exception as details:
            raise exceptions.TestFail("Failed get the virsh instance with uri: "
                                      "%s\n Details: %s" % (connect_uri, details))

    is_arm = "aarch" in platform.machine()
    if is_arm:
        for gic_enum in domcap.DomCapabilityXML()['features']['gic_enums']:
            if gic_enum['name'] == "version":
                gic_version = gic_enum['values'][0].get_value()

    # Run test case
    result = virsh.maxvcpus(option, uri=connect_uri, ignore_status=True,
                            debug=True)

    maxvcpus_test = result.stdout.strip()
    status = result.exit_status

    # Check status_error
    if status_error == "yes":
        if status == 0:
            raise exceptions.TestFail("Run successed with unsupported option!")
        else:
            logging.info("Run failed with unsupported option %s " % option)
    elif status_error == "no":
        if status == 0:
            if not libvirt_version.version_compare(2, 3, 0):
                if "kqemu" in option:
                    if not maxvcpus_test == '1':
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " % (maxvcpus_test, option))
                elif option in ['qemu', '--type qemu', '']:
                    if not maxvcpus_test == '16':
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " % (maxvcpus_test, option))
                else:
                    # No check with other types
                    pass
            else:
                # It covers all possible combinations
                if option in ['qemu', 'kvm', '--type qemu', '--type kvm', 'kqemu', '--type kqemu', '']:
                    if (is_arm and gic_version == '2' and option in ['kvm', '']):
                        if not maxvcpus_test == '8':
                            raise exceptions.TestFail("Command output %s is not "
                                                      "expected for %s " % (maxvcpus_test, option))
                    elif not maxvcpus_test == maxvcpus:
                        raise exceptions.TestFail("Command output %s is not "
                                                  "expected for %s " % (maxvcpus_test, option))
                else:
                    # No check with other types
                    pass
        else:
            raise exceptions.TestFail("Run command failed")
Esempio n. 13
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    connect_uri = None
    # check the config
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_ip.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_ip is not configured "
                                       "in remote test.")
    if (connect_arg == "transport" and
            transport_type == "remote" and
            local_pwd.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_pwd is not configured "
                                       "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport, dest_ip=server_ip)
    else:
        connect_uri = connect_arg

    if libvirt_version.version_compare(2, 3, 0):
        try:
            maxvcpus = None
            dom_capabilities = None
            # make sure we take maxvcpus from right host, helps incase remote
            try:
                dom_capabilities = domcap.DomCapabilityXML()
                maxvcpus = dom_capabilities.max
                logging.debug("maxvcpus calculate from domcapabilities "
                              "is %s", maxvcpus)
            except:
                raise exceptions.TestFail("Failed to get maxvcpus from "
                                          "domcapabilities xml:\n%s"
                                          % dom_capabilities)
            if not maxvcpus:
                raise exceptions.TestFail("Failed to get max value for vcpu"
                                          "from domcapabilities "
                                          "xml:\n%s" % dom_capabilities)
        except Exception, details:
            raise exceptions.TestFail("Failed get the virsh instance with uri: "
                                      "%s\n Details: %s" % (connect_uri, details))
Esempio n. 14
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")
    connect_uri = None
    # check the config
    if (connect_arg == "transport" and transport_type == "remote"
            and local_ip.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_ip is not configured "
                                       "in remote test.")
    if (connect_arg == "transport" and transport_type == "remote"
            and local_pwd.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_pwd is not configured "
                                       "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip=server_ip)
    else:
        connect_uri = connect_arg

    if libvirt_version.version_compare(2, 3, 0):
        try:
            maxvcpus = None
            dom_capabilities = None
            # make sure we take maxvcpus from right host, helps incase remote
            try:
                dom_capabilities = domcap.DomCapabilityXML()
                maxvcpus = dom_capabilities.max
                logging.debug(
                    "maxvcpus calculate from domcapabilities "
                    "is %s", maxvcpus)
            except:
                raise exceptions.TestFail("Failed to get maxvcpus from "
                                          "domcapabilities xml:\n%s" %
                                          dom_capabilities)
            if not maxvcpus:
                raise exceptions.TestFail("Failed to get max value for vcpu"
                                          "from domcapabilities "
                                          "xml:\n%s" % dom_capabilities)
        except Exception, details:
            raise exceptions.TestFail(
                "Failed get the virsh instance with uri: "
                "%s\n Details: %s" % (connect_uri, details))
Esempio n. 15
0
def run(test, params, env):
    """
    Test the command virsh maxvcpus

    (1) Call virsh maxvcpus
    (2) Call virsh -c remote_uri maxvcpus
    (3) Call virsh maxvcpus with an unexpected option
    """

    # get the params from subtests.
    # params for general.
    option = params.get("virsh_maxvcpus_options")
    status_error = params.get("status_error")
    connect_arg = params.get("connect_arg", "")

    # params for transport connect.
    local_ip = params.get("local_ip", "ENTER.YOUR.LOCAL.IP")
    local_pwd = params.get("local_pwd", "ENTER.YOUR.LOCAL.ROOT.PASSWORD")
    server_ip = params.get("remote_ip", local_ip)
    server_pwd = params.get("remote_pwd", local_pwd)
    transport_type = params.get("connect_transport_type", "local")
    transport = params.get("connect_transport", "ssh")

    # check the config
    if (connect_arg == "transport" and transport_type == "remote"
            and local_ip.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_ip is not configured "
                                       "in remote test.")
    if (connect_arg == "transport" and transport_type == "remote"
            and local_pwd.count("ENTER")):
        raise exceptions.TestSkipError("Parameter local_pwd is not configured "
                                       "in remote test.")

    if connect_arg == "transport":
        canonical_uri_type = virsh.driver()

        if transport == "ssh":
            ssh_connection = utils_conn.SSHConnection(server_ip=server_ip,
                                                      server_pwd=server_pwd,
                                                      client_ip=local_ip,
                                                      client_pwd=local_pwd)
            try:
                ssh_connection.conn_check()
            except utils_conn.ConnectionError:
                ssh_connection.conn_setup()
                ssh_connection.conn_check()

            connect_uri = libvirt_vm.get_uri_with_transport(
                uri_type=canonical_uri_type,
                transport=transport,
                dest_ip=server_ip)
    else:
        connect_uri = connect_arg

    if libvirt_version.version_compare(2, 3, 0):
        try:
            maxvcpus = None
            # make sure we take maxvcpus from right host, helps incase remote
            virsh_dargs = {'uri': connect_uri}
            virsh_instance = virsh.Virsh(virsh_dargs)
            try:
                capa = capability_xml.CapabilityXML(virsh_instance)
                host_arch = capa.arch
                maxvcpus = capa.get_guest_capabilities(
                )['hvm'][host_arch]['maxcpus']
            except:
                raise exceptions.TestFail("Failed to get maxvcpus from "
                                          "capabilities xml\n%s" % capa)
            if not maxvcpus:
                raise exceptions.TestFail("Failed to get guest section for "
                                          "host arch: %s from capabilities "
                                          "xml\n%s" % (host_arch, capa))
        except Exception, details:
            raise exceptions.TestFail(
                "Failed get the virsh instance with uri: "
                "%s\n Details: %s" % (connect_uri, details))