예제 #1
0
def remove_key_in_conf(value_list,
                       conf_type="libvirtd",
                       remote_params=None,
                       restart_libvirt=False):
    """
    Remove settings in configuration file on local or remote
    and restart libvirtd if needed

    :param value_list: A list of settings to delete, like ["log_level", "log_outputs"]
    :param conf_type: The configuration type to update on localhost,
        eg, "libvirt", "virtqemud"
    :param remote_params: The params for remote access
    :param restart_libvirt: True to restart libvirtd
    :return: remote.RemoteFile object for remote file or
        utils_config.LibvirtConfigCommon object for local configuration file
    """

    if remote_params:
        remote_ip = remote_params.get("server_ip",
                                      remote_params.get("remote_ip"))
        remote_pwd = remote_params.get("server_pwd",
                                       remote_params.get("remote_pwd"))
        remote_user = remote_params.get("server_user",
                                        remote_params.get("remote_user"))
        file_path = remote_params.get("file_path")
        if not all([remote_ip, remote_pwd, remote_user, file_path]):
            raise exceptions.TestError("remote_[ip|user|pwd] and file_path "
                                       "are necessary!")
        remote_file_obj = remote.RemoteFile(address=remote_ip,
                                            client='scp',
                                            username=remote_user,
                                            password=remote_pwd,
                                            port='22',
                                            remote_path=file_path)
        remote_file_obj.remove(value_list)

        if restart_libvirt:
            libvirt.remotely_control_libvirtd(remote_ip,
                                              remote_user,
                                              remote_pwd,
                                              action='restart',
                                              status_error='no')
        return remote_file_obj
    else:
        target_conf = utils_config.get_conf_obj(conf_type)
        for item in value_list:
            try:
                del target_conf[item]
            except utils_config.ConfigNoOptionError as err:
                LOG.error(err)
        if restart_libvirt:
            libvirtd = utils_libvirtd.Libvirtd()
            libvirtd.restart()
        return target_conf
예제 #2
0
def managed_daemon_config(conf_type="virtproxyd"):
    """
    Determine different daemon config under different daemon mode.

    :param conf_type: The configuration type to get
        For example, "libvirtd" or "virtqemud"
    :return: utils_config.LibvirtConfigCommon object
    """
    if not utils_split_daemons.is_modular_daemon():
        conf_type = "libvirtd"
    config = utils_config.get_conf_obj(conf_type)
    return config
예제 #3
0
def run(test, params, env):
    """
    Test pty type serial with log file
    """

    def prepare_serial_device():
        """
        Prepare a serial device XML according to parameters

        :return: the serial device xml object
        """
        serial = librarian.get('serial')(serial_type)

        serial.target_port = target_port
        serial.target_type = target_type
        serial.target_model = target_model
        serial.log_file = log_file

        return serial

    def update_qemu_conf():
        """
        update some settings in qemu conf file
        """
        qemu_conf.stdio_handler = stdio_handler
        daemon_service.restart()

    remove_devices = eval(params.get('remove_devices', []))
    target_model = params.get('target_model', '')
    serial_type = params.get('serial_dev_type', 'pty')
    log_file = params.get('log_file', '')
    target_type = params.get('target_type', 'isa-serial')
    target_port = params.get('target_port', '0')
    target_model = params.get('target_model', '')
    stdio_handler = params.get('stdio_handler', "logd")
    boot_prompt = params.get('boot_prompt', 'Login Prompts')
    vm_name = params.get("main_vm")

    qemu_conf = utils_config.get_conf_obj("qemu")
    daemon_service = utils_libvirtd.Libvirtd()

    update_qemu_conf()

    backup_xml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)

    try:
        vmxml = backup_xml.copy()
        vm = env.get_vm(vm_name)
        vm.undefine()

        for device_type in remove_devices:
            vmxml.remove_all_device_by_type(device_type)
        serial_dev = prepare_serial_device()
        vmxml.add_device(serial_dev)
        vmxml.sync()
        logging.debug("vmxml: %s" % vmxml)

        ret = virsh.define(vmxml.xml, debug=True)
        libvirt.check_exit_status(ret)
        virsh.start(vm_name, ignore_status=False)
        vm.wait_for_login().close()

        # Need to wait for a while to get login prompt
        if not utils_misc.wait_for(
                lambda: check_pty_log_file(log_file, boot_prompt), 3):
            test.fail("Failed to find the vm login prompt from %s" % log_file)

    except Exception as e:
        test.error('Unexpected error: {}'.format(e))
    finally:
        vm.destroy()
        backup_xml.sync()
        qemu_conf.restore()
        daemon_service.restart()
예제 #4
0
def run(test, params, env):
    """
    Start libvirt daemon with different options.
    Check socket files.
    """
    log = []

    def _logger(line):
        """
        Callback function to log libvirtd output.
        """
        log.append(line)

    def check_help(params):
        """
        Check whether the output is help and meets expectation
        """
        expected_help = params.get('expected_help', 'no') == 'yes'
        is_help = any(line.startswith('Usage:') for line in log)
        if expected_help != is_help:
            test.fail(
                'Expected output help is %s, but get output:\n%s' %
                (expected_help, '\n'.join(log)))

    def check_version(params):
        """
        Check whether the output is libvirtd version.
        """
        expected_version = params.get('expected_version', 'no') == 'yes'
        is_version = log[0].startswith('{} (libvirt)'.format(daemon_name))
        if expected_version != is_version:
            test.fail(
                'Expected output version is %s, but get output:\n%s' %
                (expected_version, '\n'.join(log)))

    def check_unix_socket_files():
        """
        Check whether the socket file exists.
        """
        rw_sock_path = '/var/run/libvirt/libvirt-sock'
        ro_sock_path = '/var/run/libvirt/libvirt-sock-ro'

        if libvirtd.running or libvirt_version.version_compare(5, 6, 0):
            if not os.path.exists(rw_sock_path):
                test.fail('RW unix socket file not found at %s' %
                          rw_sock_path)
            if not os.path.exists(ro_sock_path):
                test.fail('RO unix socket file not found at %s' %
                          ro_sock_path)
        else:
            if os.path.exists(rw_sock_path) or os.path.exists(ro_sock_path):
                test.fail('Expect unix socket file do not exists '
                          'when libvirtd is stopped')

    def check_pid_file():
        """
        Check whether the pid file exists.
        """
        if not os.path.exists(pid_path):
            test.fail("PID file not found at %s" % pid_path)

        with open(pid_path) as pid_file:
            pid = int(pid_file.readline())
        result = process.run('pgrep %s' % daemon_name,
                             ignore_status=True, shell=True)
        expected_pid = int(result.stdout_text.strip().split()[0])

        if pid != expected_pid:
            test.fail("PID file content mismatch. Expected %s "
                      "but got %s" % (expected_pid, pid))

    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"]))

    MAX_TIMEOUT = 10
    arg_str = params.get("libvirtd_arg", "")
    time_tolerance = float(params.get("exit_time_tolerance", 1))
    expected_exit_time = float(params.get("expected_exit_time", 'inf'))
    config_path = params.get('expected_config_path', "")
    pid_path = params.get('expected_pid_path', "")
    daemon_name = params.get('daemon_name', "")
    test_config = params.get('test_config', "no") == "yes"
    require_modular_daemon = params.get('require_modular_daemon', "no") == "yes"

    utils_split_daemons.daemon_mode_check(require_modular_daemon)
    if expected_exit_time == float('inf'):
        timeout = MAX_TIMEOUT
    else:
        if expected_exit_time > 0:
            if len(virsh.dom_list('--name').stdout.strip().splitlines()):
                test.cancel('Timeout option will be ignore if '
                            'there exists living domain')
        timeout = expected_exit_time + time_tolerance

    libvirtd = LibvirtdSession(service_name=daemon_name, logging_handler=_logger)

    # Setup config file.
    check_max_clients = int(101)
    if test_config:
        config = utils_config.get_conf_obj(daemon_name)
        logging.debug(config.conf_path)
        config_path = config.conf_path
        config.max_clients = check_max_clients
        arg_str = arg_str + config_path

    try:
        check_unix_socket_files()

        Libvirtd(daemon_name).stop()
        libvirtd.start(arg_str=arg_str, wait_for_working=False)

        start = time.time()
        libvirtd_exited = libvirtd.wait_for_stop(timeout=timeout, step=0.1)
        wait_time = time.time() - start

        if log:
            logging.debug("Libvirtd log:")
            for line in log:
                logging.debug(line)

            check_help(params)
            check_version(params)

        if libvirtd_exited:
            if expected_exit_time == float('inf'):
                test.fail("Expected never stop, but ran %ss" % wait_time)
            elif wait_time < expected_exit_time - time_tolerance:
                test.fail("Expected exit in %ss(+-%ss), but ran %ss" %
                          (expected_exit_time, time_tolerance, wait_time))
        else:
            if expected_exit_time != float('inf'):
                test.fail("Expected exit in %ss(+-%ss), but ran timeout in %ss" %
                          (expected_exit_time, time_tolerance, wait_time))

        not libvirt_version.version_compare(5, 6, 0) and check_unix_socket_files()
        if test_config:
            check_config_file()
        if pid_path:
            check_pid_file()
    finally:
        libvirtd.exit()
        Libvirtd(daemon_name).stop()
        socket_name = daemon_name + ".socket"
        Libvirtd(socket_name).restart()
        Libvirtd(daemon_name).start()

        # Clean up config file
        if test_config:
            config.restore()
        if os.path.exists(pid_path):
            os.remove(pid_path)