예제 #1
0
def run(test, params, env):
    """
    Test virt-admin srv-threadpool-info

    1) Change the threadpool related parameters in daemon conf file;
    2) Restart daemon;
    3) Check whether the parameter value listed by srv-threadpool-info
       are the same with the above settings.
    """
    min_workers = params.get("min_workers")
    max_workers = params.get("max_workers")
    prio_workers = params.get("prio_workers")
    admin_min_workers = params.get("admin_min_workers")
    admin_max_workers = params.get("admin_max_workers")
    server_name = params.get("server_name")

    if not server_name:
        server_name = virt_admin.check_server_name()
    config = virt_admin.managed_daemon_config()
    daemon = utils_libvirtd.Libvirtd()

    try:
        if server_name == "admin":
            config.admin_min_workers = admin_min_workers
            config.admin_max_workers = admin_max_workers
        else:
            config.min_workers = min_workers
            config.max_workers = max_workers
            config.prio_workers = prio_workers

        daemon.restart()
        vp = virt_admin.VirtadminPersistent()
        result = vp.srv_threadpool_info(server_name,
                                        ignore_status=True,
                                        debug=True)

        output = result.stdout.strip().splitlines()
        out_split = [item.split(':') for item in output]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])

        if result.exit_status:
            test.fail("This operation should success "
                      "but failed! Output: \n %s" % result)
        else:
            if server_name == "admin":
                if not (out_dict["minWorkers"] == admin_min_workers
                        and out_dict["maxWorkers"] == admin_max_workers):
                    test.fail("attributes info listed by "
                              "srv-threadpool-info is not correct!")
            else:
                if not (out_dict["minWorkers"] == min_workers
                        and out_dict["maxWorkers"] == max_workers
                        and out_dict["prioWorkers"] == prio_workers):
                    test.fail("attributes info listed by "
                              "srv-threadpool-info is not correct!")
    finally:
        config.restore()
        daemon.restart()
def run(test, params, env):
    """
    Test virt-admin srv-clients-info

    1) Change the clients related parameters in daemon config file;
    2) Restart daemon;
    3) Start several virsh connections;
    4) Check whether the parameters value listed by srv-clients-info
       are the same with the above settings.
    """
    max_clients = params.get("max_clients")
    max_anonymous_clients = params.get("max_anonymous_clients")
    server_name = params.get("server_name")
    num_clients = params.get("num_clients")
    local_pwd = params.get("local_pwd")

    if not server_name:
        server_name = virt_admin.check_server_name()

    config = virt_admin.managed_daemon_config()
    daemon = utils_libvirtd.Libvirtd()
    ssh_key.setup_remote_ssh_key("localhost", "root", local_pwd)

    try:
        config.max_clients = max_clients
        config.max_anonymous_clients = max_anonymous_clients
        daemon.restart()
        vp = virt_admin.VirtadminPersistent()

        virsh_instant = []
        for _ in range(int(num_clients)):
            # Under split daemon mode, we can connect to virtproxyd via
            # remote connections,can not connect to virtproxyd direct
            # on local host
            virsh_instant.append(
                virsh.VirshPersistent(uri="qemu+ssh://localhost/system"))

        result = vp.srv_clients_info(server_name,
                                     ignore_status=True,
                                     debug=True)
        output = result.stdout.strip().splitlines()
        out_split = [item.split(':') for item in output]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])

        if result.exit_status:
            test.fail("This operation should success "
                      "but failed. Output:\n %s" % result)
        else:
            if not (out_dict["nclients_max"] == max_clients and
                    out_dict["nclients_unauth_max"] == max_anonymous_clients):
                test.fail("attributes info listed by "
                          "srv-clients-info is not correct.")
            if not out_dict["nclients"] == num_clients:
                test.fail("the number of clients connect to daemon "
                          "is not correct.")
    finally:
        config.restore()
        daemon.restart()
예제 #3
0
 def check_config_file():
     """
     Check whether the config file take effects by checking max_clients.
     """
     connect_uri = daemon_name + ":///system"
     vp = virt_admin.VirtadminPersistent(uri=connect_uri)
     result = vp.srv_clients_info(daemon_name, uri=connect_uri, ignore_status=True, debug=True)
     output = result.stdout.strip().splitlines()
     out_split = [item.split(':') for item in output]
     out_dict = dict([[item[0].strip(), item[1].strip()] for item in out_split])
     if int(out_dict["nclients_max"]) != check_max_clients:
         test.fail('Expected max_clients is %s, but got %s' %
                   (check_max_clients, out_dict["nclients_max"]))
def run(test, params, env):
    """
    Test virt-admin srv-clients-info

    1) Change the clients related parameters in libvirtd.conf;
    2) Restart libvirtd daemon;
    3) Start several virsh connections;
    4) Check whether the parameters value listed by srv-clents-info
       are the same with the above settings.
    """
    max_clients = params.get("max_clients")
    max_anonymous_clients = params.get("max_anonymous_clients")
    server_name = params.get("server_name")
    num_clients = params.get("num_clients")

    config = utils_config.LibvirtdConfig()
    libvirtd = utils_libvirtd.Libvirtd()

    try:
        config.max_clients = max_clients
        config.max_anonymous_clients = max_anonymous_clients
        libvirtd.restart()
        vp = virt_admin.VirtadminPersistent()

        virsh_instant = []
        for _ in range(int(num_clients)):
            virsh_instant.append(virsh.VirshPersistent(uri="qemu:///system"))

        result = vp.srv_clients_info(server_name,
                                     ignore_status=True,
                                     debug=True)
        output = result.stdout.strip().splitlines()
        out_split = [item.split(':') for item in output]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])

        if result.exit_status:
            raise exceptions.TestFail("This operation should success "
                                      "but failed. Output:\n %s" % result)
        else:
            if not (out_dict["nclients_max"] == max_clients and
                    out_dict["nclients_unauth_max"] == max_anonymous_clients):
                raise exceptions.TestFail("attributes info listed by "
                                          "srv-clients-info is not correct.")
            if not out_dict["nclients"] == num_clients:
                raise exceptions.TestFail(
                    "the number of clients connect to libvirtd "
                    "is not correct.")
    finally:
        config.restore()
        libvirtd.restart()
예제 #5
0
def run(test, params, env):
    """
    Test virt-admin client-disconnect

    1) Start several virsh connections;
    2) disconnect some connections;
    3) check whether virsh gives out the
       correct error messages;
    4) check whether srv_clients_info gives out the
       correct info about the virsh clients.
    """
    num_clients = params.get("num_clients")
    server_name = params.get("server_name")
    vp = virt_admin.VirtadminPersistent()
    daemon = utils_libvirtd.Libvirtd()
    local_pwd = params.get("local_pwd")

    if not server_name:
        server_name = virt_admin.check_server_name()
    ssh_key.setup_remote_ssh_key("localhost", "root", local_pwd)

    try:
        virsh_instant = []
        for _ in range(int(num_clients)):
            virsh_instant.append(
                virsh.VirshPersistent(uri="qemu+ssh://localhost/system"))

        out = vp.srv_clients_list(server_name, ignore_status=True, debug=True)
        client_id = out.stdout.strip().splitlines()[-1].split()[0]
        result = vp.client_disconnect(server_name,
                                      client_id,
                                      ignore_status=True,
                                      debug=True)

        if result.exit_status:
            test.fail("This operation should "
                      "success but failed. output: \n %s" % result)
        elif result.stdout.strip().split()[1][1:-1] != client_id:
            test.fail("virt-admin did not " "disconnect the correct client.")
    finally:
        daemon.restart()
예제 #6
0
def run(test, params, env):
    """
    Test command: virt-admin srv-list.

    1) execute virt-admin srv-list
    2) check whether the server names printed by the
       above execution are correct
    """
    server_name = params.get("server_name")
    if not server_name:
        server_name = virt_admin.check_server_name()

    vp = virt_admin.VirtadminPersistent()
    result = vp.srv_list(ignore_status=True, debug=True)
    output = result.stdout.strip()

    if result.exit_status:
        test.fail("This operation should success "
                  "but failed! output:\n%s " % result)
    else:
        if not re.search(server_name, output):
            test.fail("server %s is not listed! " % server_name)
def run(test, params, env):
    """
    Test command: virt-admin server-update-tls.

    1) when tls related files changed, notify server to update TLS related files
        online, without restart daemon
    """
    def add_remote_firewall_port(port, params):
        """
        Add the port on remote host

        :param port: port to add
        :param params: Dictionary with the test parameters
        """
        server_ip = params.get("server_ip")
        server_user = params.get("server_user")
        server_pwd = params.get("server_pwd")
        remote_session = remote.wait_for_login('ssh', server_ip, '22',
                                               server_user, server_pwd,
                                               r"[\#\$]\s*$")
        firewall_cmd = utils_iptables.Firewall_cmd(remote_session)
        firewall_cmd.add_port(port, 'tcp', permanent=True)
        remote_session.close()

    def remove_remote_firewall_port(port, params):
        """
        Remove the port on remote host

        :param port: port to remove
        :param params: Dictionary with the test parameters
        """
        server_ip = params.get("server_ip")
        server_user = params.get("server_user")
        server_pwd = params.get("server_pwd")
        remote_session = remote.wait_for_login('ssh', server_ip, '22',
                                               server_user, server_pwd,
                                               r"[\#\$]\s*$")
        firewall_cmd = utils_iptables.Firewall_cmd(remote_session)
        firewall_cmd.remove_port(port, 'tcp', permanent=True)
        remote_session.close()

    def update_server_pem(cert_saved_dir, remote_libvirt_pki_dir):
        """
        Update the server info and re-build servercert

        :param cert_saved_dir: The directory where cert files are saved
        :param remote_libvirt_pki_dir: Directory to store pki on remote
        """
        logging.debug("Update serverinfo")
        serverinfo = os.path.join(cert_saved_dir, "server.info")
        with open(os.path.join(cert_saved_dir, "server.info"), "r") as f1:
            lines = f1.readlines()
        with open(os.path.join(cert_saved_dir, "server2.info"), "w") as f2:
            for line in lines:
                if fake_ip in line:
                    line = line.replace(fake_ip, server_ip)
                f2.write(line)

        cmd = ("certtool --generate-certificate --load-privkey "
               "{0}/serverkey.pem --load-ca-certificate {0}/cacert.pem "
               "--load-ca-privkey {0}/cakey.pem --template {0}/server2.info "
               "--outfile {0}/servercert.pem".format(cert_saved_dir))
        servercert_pem = os.path.join(cert_saved_dir, "servercert.pem")
        process.run(cmd, shell=True, verbose=True)
        remote.copy_files_to(server_ip, 'scp', server_user, server_pwd, '22',
                             servercert_pem, remote_libvirt_pki_dir)

    server_ip = params["server_ip"] = params.get("remote_ip")
    server_user = params["server_user"] = params.get("remote_user", "root")
    server_pwd = params["server_pwd"] = params.get("remote_pwd")
    client_ip = params["client_ip"] = params.get("local_ip")
    client_pwd = params["client_pwd"] = params.get("local_pwd")
    tls_port = params.get("tls_port", "16514")
    uri = "qemu+tls://%s:%s/system" % (server_ip, tls_port)

    remote_virt_dargs = {
        'remote_ip': server_ip,
        'remote_user': server_user,
        'remote_pwd': server_pwd,
        'unprivileged_user': None,
        'ssh_remote_auth': True
    }
    tls_obj = None

    if not libvirt_version.version_compare(6, 2, 0):
        test.cancel("This libvirt version doesn't support "
                    "virt-admin server-update-tls.")
    try:
        vp = virt_admin.VirtadminPersistent(**remote_virt_dargs)

        add_remote_firewall_port(tls_port, params)

        # Generate a fake ip for testing
        repl = str(int(server_ip.strip().split('.')[-1]) + 1 % 255)
        fake_ip = re.sub("([0-9]+)$", repl, server_ip)
        params.update({"server_info_ip": fake_ip})

        tls_obj = TLSConnection(params)
        tls_obj.conn_setup()
        tls_obj.auto_recover = True

        # Connection should fail because TLS is set incorrectly
        ret, output = libvirt.connect_libvirtd(uri)
        if ret:
            test.fail(
                "Connection should fail but succeed. ret: {}, output: {}".
                format(ret, output))
        if "authentication failed" not in output:
            test.fail(
                "Unablee to find the expected error message. output: %s" %
                output)

        tmp_dir = tls_obj.tmp_dir
        remote_libvirt_pki_dir = tls_obj.libvirt_pki_dir
        update_server_pem(tmp_dir, remote_libvirt_pki_dir)

        serv_name = virt_admin.check_server_name()
        logging.debug("service name: %s", serv_name)
        result = vp.server_update_tls(serv_name, debug=True)
        libvirt.check_exit_status(result)

        # Re-connect to the server
        ret, output = libvirt.connect_libvirtd(uri)
        if not ret:
            test.fail("Connection fails, ret: {}, output: {}".format(
                ret, output))
    finally:
        logging.info("Recover test environment")
        remove_remote_firewall_port(tls_port, params)
예제 #8
0
def run(test, params, env):
    """
    Test virt-admin server-threadpool-set

    1) Test the --min-workers options
       set the params of threadpool by virt-admin server-threadpool-set,
       check whether the result printed by server-threadpool-info
       are consistent with the above setting.
    """
    server_name = params.get("server_name")
    options_ref = params.get("options_ref")
    min_workers = params.get("min_workers")
    max_workers = params.get("max_workers")
    nworkers = params.get("nworkers")
    priority_workers = params.get("priority_workers")
    is_positive = params.get("is_positive") == "yes"
    min_workers_gt_nworkers = params.get("min_workers_gt_nworkers") == "yes"
    max_workers_gt_nworkers = params.get("max_workers_gt_nworkers") == "yes"
    options_test_together = params.get("options_test_together") == "yes"

    if not server_name:
        server_name = virt_admin.check_server_name()

    daemon = utils_libvirtd.Libvirtd()
    vp = virt_admin.VirtadminPersistent()

    def threadpool_info(server):
        """
        check the attributes by server-threadpool-set.
        1) get the output returned by server-threadpool-set;
        2) split the output to get a dictionary of those attributes.
        :param server: get the threadpool info of this server.
        :return: a dict obtained by converting result_info.
        """
        result_info = vp.srv_threadpool_info(server,
                                             ignore_status=True,
                                             debug=True)
        out = result_info.stdout.strip().splitlines()
        out_split = [item.split(':') for item in out]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])
        return out_dict

    try:
        if options_ref:
            if "min-workers" in options_ref:
                result = vp.srv_threadpool_set(server_name,
                                               min_workers=min_workers,
                                               ignore_status=True,
                                               debug=True)
            if "max-workers" in options_ref:
                if not max_workers_gt_nworkers:
                    vp.srv_threadpool_set(server_name,
                                          min_workers=min_workers,
                                          ignore_status=True,
                                          debug=True)
                logging.debug(
                    "The current workers state of the daemon server is %s",
                    threadpool_info(server_name))
                result = vp.srv_threadpool_set(server_name,
                                               max_workers=max_workers,
                                               ignore_status=True,
                                               debug=True)
            if "priority-workers" in options_ref:
                result = vp.srv_threadpool_set(server_name,
                                               prio_workers=priority_workers,
                                               ignore_status=True,
                                               debug=True)
        elif options_test_together:
            result = vp.srv_threadpool_set(server_name,
                                           max_workers=max_workers,
                                           min_workers=min_workers,
                                           prio_workers=priority_workers,
                                           ignore_status=True,
                                           debug=True)

        if result.exit_status:
            if is_positive:
                test.fail("This operation should success "
                          "but failed! output:\n%s" % result)
            else:
                logging.debug(
                    "This is the expected failure for negative cases")
        else:
            if is_positive:
                outdict = threadpool_info(server_name)
                if options_ref:
                    if "min-workers" in options_ref:
                        if outdict["minWorkers"] != min_workers:
                            test.fail(
                                "minWorkers set by server-threadpool-set "
                                "is not correct!")
                        if min_workers_gt_nworkers:
                            if outdict["nWorkers"] != min_workers:
                                test.fail(
                                    "nworkers is not increased as min-workers increased."
                                )
                    if "max-workers" in options_ref:
                        if outdict["maxWorkers"] != max_workers:
                            test.fail(
                                "maxWorkers set by server-threadpool-set "
                                "is not correct!")
                        if not max_workers_gt_nworkers:
                            if outdict["nWorkers"] != max_workers:
                                test.fail(
                                    "nworkers is not increased as max-workers decreased."
                                )
                    if "priority_workers" in options_ref:
                        if outdict["prioWorkers"] != priority_workers:
                            test.fail(
                                "priority workers set by server-threadpool-set "
                                "is not correct!")
                elif options_test_together:
                    if (outdict["minWorkers"] != min_workers
                            or outdict["maxWorkers"] != max_workers
                            or outdict["prioWorkers"] != priority_workers):
                        test.fail(
                            "The numbers of workers set together by server-threadpool-set "
                            "are not correct!")
            else:
                test.fail("This operation should fail but succeeded!")
    finally:
        daemon.restart()
def run(test, params, env):
    """
    Test virt-admin  server-clients-set
    2) Change max_clients to a new value;
    3) get the current clients info;
    4) check whether the clients info is correct;
    5) try to connect other client onto the server;
    6) check whether the above connection status is correct.
    """

    server_name = params.get("server_name")
    is_positive = params.get("is_positive") == "yes"
    options_ref = params.get("options_ref")
    nclients_max = params.get("nclients_maxi")
    nclients = params.get("nclients")
    nclients_unauth_max = params.get("nclients_unauth_maxi")
    connect_able = params.get("connect_able")
    options_test_together = params.get("options_test_together")

    config = utils_config.LibvirtdConfig()
    libvirtd = utils_libvirtd.Libvirtd()
    vp = virt_admin.VirtadminPersistent()
    virsh_instance = []

    def clients_info(server):
        """
        check the attributes by server-clients-set.
        1) get the output  returned by server-clients-set;
        2) split the output to get a dictionary of those attributes;
        :params server: print the info of the clients connecting to this server
        :return: a dict obtained by transforming the result_info
        """
        result_info = vp.srv_clients_info(server,
                                          ignore_status=True,
                                          debug=True)
        out = result_info.stdout.strip().splitlines()
        out_split = [item.split(':') for item in out]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])
        return out_dict

    def chk_connect_to_libvirtd(connect_able):
        try:
            virsh_instance.append(virsh.VirshPersistent(uri='qemu:///system'))
        except Exception as info:
            if connect_able == "yes":
                test.fail(
                    "Connection to libvirtd is not success, error:\n %s" %
                    info)
            else:
                logging.info("Connections to libvirtd should not success, "
                             "this is a correct test result!")
        else:
            if connect_able == "yes":
                logging.info("Connections to libvirtd is successful, "
                             "this is a correct test result!")
            else:
                test.fail("error: Connection to libvirtd should not success! "
                          "Check the attributes.")

    try:
        if options_ref:
            if "max-clients" in options_ref:
                if nclients:
                    if int(nclients_max) > int(nclients):
                        config.max_clients = nclients
                        config.max_anonymous_clients = nclients_unauth_max
                        libvirtd.restart()
                        for _ in range(int(nclients)):
                            virsh_instance.append(
                                virsh.VirshPersistent(uri='qemu:///system'))
                        result = vp.srv_clients_set(server_name,
                                                    max_clients=nclients_max,
                                                    ignore_status=True,
                                                    debug=True)
                    elif int(nclients_max) <= int(nclients):
                        for _ in range(int(nclients)):
                            virsh_instance.append(
                                virsh.VirshPersistent(uri='qemu:///system'))
                        result = vp.srv_clients_set(
                            server_name,
                            max_clients=nclients_max,
                            max_unauth_clients=nclients_unauth_max,
                            ignore_status=True,
                            debug=True)

                else:
                    result = vp.srv_clients_set(server_name,
                                                max_clients=nclients_max,
                                                ignore_status=True,
                                                debug=True)
            elif "max-unauth-clients" in options_ref:
                result = vp.srv_clients_set(
                    server_name,
                    max_unauth_clients=nclients_unauth_max,
                    ignore_status=True,
                    debug=True)
        elif options_test_together:
            result = vp.srv_clients_set(server_name,
                                        max_clients=nclients_max,
                                        max_unauth_clients=nclients_unauth_max,
                                        ignore_status=True,
                                        debug=True)

        outdict = clients_info(server_name)

        if result.exit_status:
            if is_positive:
                test.fail("This operation should success "
                          "but failed! output:\n%s " % result)
            else:
                logging.debug("This failure is expected!")
        else:
            if is_positive:
                if options_ref:
                    if "max-clients" in options_ref:
                        if outdict["nclients_max"] != nclients_max:
                            test.fail("attributes set by server-clients-set "
                                      "is not correct!")
                        if nclients:
                            chk_connect_to_libvirtd(connect_able)
                    elif "max_unauth_clients" in options_ref:
                        if outdict[
                                "nclients_unauth_max"] != nclients_unauth_max:
                            test.fail("attributes set by server-clients-set "
                                      "is not correct!")
                elif options_test_together:
                    if (outdict["nclients_max"] != nclients_max
                            or outdict["nclients_unauth_max"] !=
                            nclients_unauth_max):
                        test.fail("attributes set by server-clients-set "
                                  "is not correct!")
            else:
                test.fail("This is a negative case, should get failure.")
    finally:
        for session in virsh_instance:
            session.close_session()
        config.restore()
        libvirtd.restart()
예제 #10
0
def run(test, params, env):
    """
    Test virt-admin itself group commands, which exclude connect and help,
    in interactive mode.
    Virsh itself (help keyword 'virt-admin'):
       cd                             change the current directory
       echo                           echo arguments
       exit                           quit this interactive terminal
       pwd                            print the current directory
       quit                           quit this interactive terminal
    """
    # Get parameters for test
    cd_option = params.get("cd_option", "/")
    invalid_cmd = params.get("invalid_cmd", " ")
    cd_extra = params.get("cd_extra", "")
    pwd_extra = params.get("pwd_extra", "")
    echo_extra = params.get("echo_extra", "")
    exit_cmd = params.get("exit_cmd", "exit")
    echo_option = params.get("echo_option", "")
    echo_str = params.get("echo_str", "xyz")
    invalid_status_error = params.get("invalid_status_error", "no")
    cd_status_error = params.get("cd_status_error", "no")
    pwd_status_error = params.get("pwd_status_error", "no")
    echo_status_error = params.get("echo_status_error", "no")

    # Run virtadmin command in interactive mode
    vp = virt_admin.VirtadminPersistent()

    # Run invalid command
    result = vp.command(invalid_cmd, ignore_status=True, debug=True)
    status = result.exit_status
    if invalid_status_error == "yes":
        if status == 0:
            raise exceptions.TestFail("Run successful with wrong command!")
        else:
            logging.info("Run command failed as expected.")
    else:
        if status != 0:
            raise exceptions.TestFail("Run failed with right command!\n%s",
                                      result)

    # Run cd command
    result = vp.cd(cd_option, cd_extra, ignore_status=True, debug=True)
    cd_status = result.exit_status
    if cd_status_error == "yes":
        if cd_status == 0:
            raise exceptions.TestFail("Run successful with wrong command!")
        else:
            logging.info("Run command failed as expected.")
    else:
        if cd_status != 0:
            raise exceptions.TestFail("Run failed with right command!\n%s",
                                      result)

    # Run pwd command
    result = vp.pwd(pwd_extra, ignore_status=True, debug=True)
    status = result.exit_status
    output = result.stdout.strip()
    if pwd_status_error == "yes":
        if status == 0:
            raise exceptions.TestFail("Run successful with wrong command!")
        else:
            logging.info("Run command failed as expected.")
    else:
        if status != 0:
            raise exceptions.TestFail("Run failed with right command!\n%s",
                                      result)
        elif cd_option and cd_status == 0:
            if output != cd_option:
                raise exceptions.TestFail("The pwd is not right with set!")

    # Run echo command
    options = "%s %s" % (echo_option, echo_extra)
    result = vp.echo(echo_str, options, ignore_status=True, debug=True)
    status = result.exit_status
    output = result.stdout.strip()
    if echo_status_error == "yes":
        if status == 0:
            raise exceptions.TestFail("Run successful with wrong command!")
        else:
            logging.info("Run command failed as expected.")
    else:
        if status != 0:
            raise exceptions.TestFail("Run failed with right command!\n%s",
                                      result)
        elif "--xml" in echo_option:
            escape_out = element_tree._escape_attrib(echo_str)
            if escape_out != output:
                raise exceptions.TestFail(
                    "%s did not match with expected output %s" %
                    (output, escape_out))
        else:
            escaped_str = sh_escape(echo_str)
            if not check_echo_shell(escaped_str, output):
                raise exceptions.TestFail("Command output is not expected.")

    # Run exit command and close the session
    try:
        if 'exit' in exit_cmd:
            vp.exit(ignore_status=True, debug=True)
        elif 'quit' in exit_cmd:
            vp.quit(ignore_status=True, debug=True)
    except aexpect.ShellProcessTerminatedError:
        logging.debug("Exit virt-admin session successfully.")
def run(test, params, env):
    """
    Test virt-admin server-threadpool-set

    1) Test the --min-workers options
       set the params of threadpool by virt-admin server-threadpool-set,
       check whether the result printed by server-threadpool-info
       are consistent with the above setting.
    """
    server_name = params.get("server_name")
    options_ref = params.get("options_ref")
    min_workers = params.get("min_workers")
    max_workers = params.get("max_workers")
    nworkers = params.get("nworkers")

    libvirtd = utils_libvirtd.Libvirtd()
    vp = virt_admin.VirtadminPersistent()

    def threadpool_info(server):
        """
        check the attributes by server-threadpool-set.
        1) get the output returned by server-threadpool-set;
        2) split the output to get a dictionary of those attributes.
        :param server: get the threadpool info of this server.
        :return: a dict obtained by converting result_info.
        """
        result_info = vp.srv_threadpool_info(server,
                                             ignore_status=True,
                                             debug=True)
        out = result_info.stdout.strip().splitlines()
        out_split = [item.split(':') for item in out]
        out_dict = dict([[item[0].strip(), item[1].strip()]
                         for item in out_split])
        return out_dict

    try:
        if "min-workers" in options_ref:
            if int(min_workers) < int(nworkers):
                result = vp.srv_threadpool_set(server_name,
                                               min_workers=min_workers,
                                               ignore_status=True,
                                               debug=True)
        if "max-workers" in options_ref:
            if int(max_workers) > int(nworkers):
                result = vp.srv_threadpool_set(server_name,
                                               max_workers=max_workers,
                                               ignore_status=True,
                                               debug=True)

        outdict = threadpool_info(server_name)
        if result.exit_status:
            raise exceptions.TestFail("This operation should success "
                                      "but failed! output:\n%s" % result)
        if "min-workers" in options_ref:
            if outdict["minWorkers"] != min_workers:
                raise exceptions.TestFail(
                    "minWorkers set by server-threadpool-set "
                    "is not correct!")
        elif "max-workers" in options_ref:
            if outdict["maxWorkers"] != max_workers:
                raise exceptions.TestFail(
                    "maxWorkers set by server-threadpool-set "
                    "is not correct!")
    finally:
        libvirtd.restart()