def _copy_until_end(self, end_event):
            #Copy until migration not end.
            while not end_event.isSet():
                logging.info("Copy file to guest %s.", self.vm_addr)
                remote.copy_files_to(self.vm_addr,
                                     "scp",
                                     guest_root,
                                     guest_pass,
                                     22,
                                     host_path,
                                     guest_path,
                                     limit=transfer_speed,
                                     verbose=True,
                                     timeout=transfer_timeout)
                logging.info("Copy file to guests %s done.", self.vm_addr)

                logging.info("Copy file from guest %s.", self.vm_addr)
                remote.copy_files_from(self.vm_addr,
                                       "scp",
                                       guest_root,
                                       guest_pass,
                                       22,
                                       guest_path,
                                       host_path_returned,
                                       limit=transfer_speed,
                                       verbose=True,
                                       timeout=transfer_timeout)
                logging.info("Copy file from guests %s done.", self.vm_addr)
                check_sum = client_utils.hash_file(host_path_returned)
                #store checksum for later check.
                self.file_check_sums.append(check_sum)
    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)
示例#3
0
def config_network(test,
                   vm,
                   interface,
                   ip=None,
                   mask="255.255.0.0",
                   gateway=None):
    """
    Config new added interface IP.
    If ip is None, use dhcp.
    """
    session = vm.wait_for_login()
    # Store working interface ip address
    vm_ip = vm.get_address()
    config_file = "/etc/sysconfig/network-scripts/ifcfg-%s" % interface
    mac = vm.get_interface_mac(interface)
    logging.debug("New Interface MAC:%s", mac)
    if mac is None:
        test.fail("Get new interface mac failed.")

    # Create a local file
    tmp_dir = data_dir.get_tmp_dir()
    local_file = tempfile.NamedTemporaryFile(prefix=("%s_" % interface),
                                             dir=tmp_dir)
    filepath = local_file.name
    local_file.close()
    lines = []
    lines.append("TYPE=Ethernet\n")
    lines.append("HWADDR=%s\n" % mac)
    lines.append("DEVICE=%s\n" % interface)
    if ip is not None:
        lines.append("BOOTPROTO=static\n")
        lines.append("IPADDR=%s\n" % ip)
        lines.append("NETMASK=%s\n" % mask)
        if gateway is not None:
            lines.append("GATEWAY=%s\n" % gateway)
    else:
        lines.append("BOOTPROTO=dhcp\n")
    lines.append("ONBOOT=no\n")
    ni = iter(lines)
    with open(filepath, "w") as fd:
        fd.writelines(ni)

    # copy file to vm and restart interface
    remote.copy_files_to(vm_ip, "scp", "root", "123456", 22, filepath,
                         config_file)
    try:
        session.cmd("ifdown %s" % interface)
    except Exception:
        pass  # The device may be not active, try to up it anyway
    try:
        session.cmd("ifup %s" % interface)
    finally:
        logging.debug(session.cmd_output("ifconfig -a"))
        session.close()
示例#4
0
def config_network(vm, interface, ip=None, mask="255.255.0.0", gateway=None):
    """
    Config new added interface IP.
    If ip is None, use dhcp.
    """
    session = vm.wait_for_login()
    # Store working interface ip address
    vm_ip = vm.get_address()
    config_file = "/etc/sysconfig/network-scripts/ifcfg-%s" % interface
    mac = vm.get_interface_mac(interface)
    logging.debug("New Interface MAC:%s", mac)
    if mac is None:
        raise error.TestFail("Get new interface mac failed.")

    # Create a local file
    tmp_dir = data_dir.get_tmp_dir()
    local_file = tempfile.NamedTemporaryFile(prefix=("%s_" % interface),
                                             dir=tmp_dir)
    filepath = local_file.name
    local_file.close()
    lines = []
    lines.append("TYPE=Ethernet\n")
    lines.append("HWADDR=%s\n" % mac)
    lines.append("DEVICE=%s\n" % interface)
    if ip is not None:
        lines.append("BOOTPROTO=static\n")
        lines.append("IPADDR=%s\n" % ip)
        lines.append("NETMASK=%s\n" % mask)
        if gateway is not None:
            lines.append("GATEWAY=%s\n" % gateway)
    else:
        lines.append("BOOTPROTO=dhcp\n")
    lines.append("ONBOOT=no\n")
    ni = iter(lines)
    fd = open(filepath, "w")
    fd.writelines(ni)
    fd.close()

    # copy file to vm and restart interface
    remote.copy_files_to(vm_ip, "scp", "root", "123456", 22,
                         filepath, config_file)
    try:
        session.cmd("ifdown %s" % interface)
    except:
        pass    # The device may be not active, try to up it anyway
    try:
        session.cmd("ifup %s" % interface)
    finally:
        logging.debug(session.cmd_output("ifconfig -a"))
        session.close()
示例#5
0
def deploy_video_file(test, vm_obj, params):
    """
    Deploy video file into destination on vm

    :param vm_obj - vm object
    :param params: Dictionary with the test parameters.
    """
    source_video_file = params.get("source_video_file")
    video_dir = os.path.join("deps", source_video_file)
    video_path = utils_misc.get_path(test.virtdir, video_dir)

    remote.copy_files_to(vm_obj.get_address(), 'scp', params.get("username"),
                         params.get("password"), params.get("shell_port"),
                         video_path, params.get("destination_video_file_path"))
示例#6
0
def deploy_video_file(test, vm_obj, params):
    """
    Deploy video file into destination on vm

    :param vm_obj - vm object
    :param params: Dictionary with the test parameters.
    """
    source_video_file = params.get("source_video_file")
    video_dir = os.path.join("deps", source_video_file)
    video_path = utils_misc.get_path(test.virtdir, video_dir)

    remote.copy_files_to(vm_obj.get_address(), 'scp',
                         params.get("username"),
                         params.get("password"),
                         params.get("shell_port"),
                         video_path,
                         params.get("destination_video_file_path"))
示例#7
0
    def server_setup(self):
        """
        setup private key and certificate file for server.

        (1).initialization for variables.
        (2).build server key.
        (3).copy files to server.
        (4).edit /etc/sysconfig/libvirtd on server.
        (5).edit /etc/libvirt/libvirtd.conf on server.
        (6).restart libvirtd service on server.
        """
        # initialize variables
        tmp_dir = self.tmp_dir
        cacert_path = '%s/cacert.pem' % tmp_dir
        serverkey_path = '%s/serverkey.pem' % tmp_dir
        servercert_path = '%s/servercert.pem' % tmp_dir
        server_ip = self.server_ip
        server_user = self.server_user
        server_pwd = self.server_pwd

        # build a server key.
        build_server_key(tmp_dir, self.server_cn, self.CERTTOOL)

        # scp cacert.pem, servercert.pem and serverkey.pem to server.
        server_session = self.server_session
        cmd = "mkdir -p %s" % self.libvirt_pki_private_dir
        status, output = server_session.cmd_status_output(cmd)
        if status:
            raise ConnMkdirError(self.libvirt_pki_private_dir, output)

        scp_dict = {
            cacert_path: self.pki_CA_dir,
            servercert_path: self.libvirt_pki_dir,
            serverkey_path: self.libvirt_pki_private_dir
        }

        for key in scp_dict:
            local_path = key
            remote_path = scp_dict[key]
            try:
                remote.copy_files_to(server_ip, 'scp', server_user, server_pwd,
                                     '22', local_path, remote_path)
            except remote.SCPError, detail:
                raise ConnSCPError('AdminHost', local_path, server_ip,
                                   remote_path, detail)
示例#8
0
    def server_setup(self):
        """
        setup private key and certificate file for server.

        (1).initialization for variables.
        (2).build server key.
        (3).copy files to server.
        (4).edit /etc/sysconfig/libvirtd on server.
        (5).edit /etc/libvirt/libvirtd.conf on server.
        (6).restart libvirtd service on server.
        """
        # initialize variables
        tmp_dir = self.tmp_dir
        cacert_path = '%s/cacert.pem' % tmp_dir
        serverkey_path = '%s/serverkey.pem' % tmp_dir
        servercert_path = '%s/servercert.pem' % tmp_dir
        server_ip = self.server_ip
        server_user = self.server_user
        server_pwd = self.server_pwd

        # build a server key.
        build_server_key(tmp_dir, self.server_cn, self.CERTTOOL)

        # scp cacert.pem, servercert.pem and serverkey.pem to server.
        server_session = self.server_session
        cmd = "mkdir -p %s" % self.libvirt_pki_private_dir
        status, output = server_session.cmd_status_output(cmd)
        if status:
            raise ConnMkdirError(self.libvirt_pki_private_dir, output)

        scp_dict = {cacert_path: self.pki_CA_dir,
                    servercert_path: self.libvirt_pki_dir,
                    serverkey_path: self.libvirt_pki_private_dir}

        for key in scp_dict:
            local_path = key
            remote_path = scp_dict[key]
            try:
                remote.copy_files_to(server_ip, 'scp', server_user,
                                     server_pwd, '22', local_path, remote_path)
            except remote.SCPError, detail:
                raise ConnSCPError('AdminHost', local_path,
                                   server_ip, remote_path, detail)
示例#9
0
    def client_setup(self):
        """
        setup private key and certificate file for client.

        (1).initialization for variables.
        (2).build a key for client.
        (3).copy files to client.
        (4).edit /etc/hosts on client.
        """
        # initialize variables
        tmp_dir = self.tmp_dir
        cacert_path = '%s/cacert.pem' % tmp_dir
        clientkey_path = '%s/clientkey.pem' % tmp_dir
        clientcert_path = '%s/clientcert.pem' % tmp_dir
        client_ip = self.client_ip
        client_user = self.client_user
        client_pwd = self.client_pwd

        # build a client key.
        build_client_key(tmp_dir, self.client_cn, self.CERTTOOL)

        # scp cacert.pem, clientcert.pem and clientkey.pem to client.
        client_session = self.client_session
        cmd = "mkdir -p %s" % self.libvirt_pki_private_dir
        status, output = client_session.cmd_status_output(cmd)
        if status:
            raise ConnMkdirError(self.libvirt_pki_private_dir, output)

        scp_dict = {
            cacert_path: self.pki_CA_dir,
            clientcert_path: self.libvirt_pki_dir,
            clientkey_path: self.libvirt_pki_private_dir
        }

        for key in scp_dict:
            local_path = key
            remote_path = scp_dict[key]
            try:
                remote.copy_files_to(client_ip, 'scp', client_user, client_pwd,
                                     '22', local_path, remote_path)
            except remote.SCPError, detail:
                raise ConnSCPError('AdminHost', local_path, client_ip,
                                   remote_path, detail)
示例#10
0
    def client_setup(self):
        """
        setup private key and certificate file for client.

        (1).initialization for variables.
        (2).build a key for client.
        (3).copy files to client.
        (4).edit /etc/hosts on client.
        """
        # initialize variables
        tmp_dir = self.tmp_dir
        cacert_path = '%s/cacert.pem' % tmp_dir
        clientkey_path = '%s/clientkey.pem' % tmp_dir
        clientcert_path = '%s/clientcert.pem' % tmp_dir
        client_ip = self.client_ip
        client_user = self.client_user
        client_pwd = self.client_pwd

        # build a client key.
        build_client_key(tmp_dir, self.client_cn, self.CERTTOOL)

        # scp cacert.pem, clientcert.pem and clientkey.pem to client.
        client_session = self.client_session
        cmd = "mkdir -p %s" % self.libvirt_pki_private_dir
        status, output = client_session.cmd_status_output(cmd)
        if status:
            raise ConnMkdirError(self.libvirt_pki_private_dir, output)

        scp_dict = {cacert_path: self.pki_CA_dir,
                    clientcert_path: self.libvirt_pki_dir,
                    clientkey_path: self.libvirt_pki_private_dir}

        for key in scp_dict:
            local_path = key
            remote_path = scp_dict[key]
            try:
                remote.copy_files_to(client_ip, 'scp', client_user,
                                     client_pwd, '22', local_path, remote_path)
            except remote.SCPError, detail:
                raise ConnSCPError('AdminHost', local_path,
                                   client_ip, remote_path, detail)
        def _copy_until_end(self, end_event):
            #Copy until migration not end.
            while not end_event.isSet():
                logging.info("Copy file to guest %s.", self.vm_addr)
                remote.copy_files_to(self.vm_addr, "scp", guest_root,
                                          guest_pass, 22, host_path,
                                          guest_path, limit=transfer_speed,
                                          verbose=True,
                                          timeout=transfer_timeout)
                logging.info("Copy file to guests %s done.", self.vm_addr)

                logging.info("Copy file from guest %s.", self.vm_addr)
                remote.copy_files_from(self.vm_addr, "scp", guest_root,
                                            guest_pass, 22, guest_path,
                                            host_path_returned,
                                            limit=transfer_speed, verbose=True,
                                            timeout=transfer_timeout)
                logging.info("Copy file from guests %s done.", self.vm_addr)
                check_sum = client_utils.hash_file(host_path_returned)
                #store checksum for later check.
                self.file_check_sums.append(check_sum)
示例#12
0
def run(test, params, env):
    """
    Test Step
        1. boot up two virtual machine
        2. For linux guest,Transfer data:
              host <--> guest1 <--> guest2 <-->host via ipv6
           For windows guest,Transfer data:
              host <--> guest1&guest2 via ipv6
        3. after data transfer, check data have no change
    Params:
        :param test: QEMU test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
    """
    timeout = int(params.get("login_timeout", '360'))
    client = params.get("file_transfer_client")
    port = params.get("file_transfer_port")
    password = params.get("password")
    username = params.get("username")
    tmp_dir = params["tmp_dir"]
    filesize = int(params.get("filesize", '4096'))
    dd_cmd = params["dd_cmd"]
    file_trans_timeout = int(params.get("file_trans_timeout", '1200'))
    file_md5_check_timeout = int(params.get("file_md5_check_timeout", '600'))

    def get_file_md5sum(file_name, session, timeout):
        """
        Get file md5sum from guest.
        """
        logging.info("Get md5sum of the file:'%s'" % file_name)
        try:
            o = session.cmd_output("md5sum %s" % file_name, timeout=timeout)
            file_md5sum = re.findall(r"\w+", o)[0]
        except IndexError:
            test.error("Could not get file md5sum in guest")
        return file_md5sum

    sessions = {}
    addresses = {}
    inet_name = {}
    vms = []

    error_context.context("Boot vms for test", logging.info)
    for vm_name in params.get("vms", "vm1 vm2").split():
        vms.append(env.get_vm(vm_name))

    # config ipv6 address host and guest.
    host_ifname = params.get("netdst")
    host_address = utils_net.get_host_ip_address(params,
                                                 ip_ver="ipv6",
                                                 linklocal=True)

    error_context.context("Get ipv6 address of host: %s" % host_address,
                          logging.info)
    for vm in vms:
        vm.verify_alive()
        sessions[vm] = vm.wait_for_login(timeout=timeout)
        if params.get("os_type") == "linux":
            inet_name[vm] = utils_net.get_linux_ifname(sessions[vm],
                                                       vm.get_mac_address())
        addresses[vm] = utils_net.get_guest_ip_addr(sessions[vm],
                                                    vm.get_mac_address(),
                                                    params.get("os_type"),
                                                    ip_version="ipv6",
                                                    linklocal=True)

        error_context.context(
            "Get ipv6 address of %s: %s" % (vm.name, addresses[vm]),
            logging.info)

    # prepare test data
    guest_path = (tmp_dir + "src-%s" % utils_misc.generate_random_string(8))
    dest_path = (tmp_dir + "dst-%s" % utils_misc.generate_random_string(8))
    host_path = os.path.join(test.tmpdir,
                             "tmp-%s" % utils_misc.generate_random_string(8))
    logging.info("Test setup: Creating %dMB file on host", filesize)
    process.run(dd_cmd % (host_path, filesize), shell=True)

    try:
        src_md5 = (crypto.hash_file(host_path, algorithm="md5"))
        error_context.context("md5 value of data from src: %s" % src_md5,
                              logging.info)
        # transfer data
        for vm in vms:
            error_context.context("Transfer data from host to %s" % vm.name,
                                  logging.info)
            remote.copy_files_to(addresses[vm],
                                 client,
                                 username,
                                 password,
                                 port,
                                 host_path,
                                 guest_path,
                                 timeout=file_trans_timeout,
                                 interface=host_ifname)
            dst_md5 = get_file_md5sum(guest_path,
                                      sessions[vm],
                                      timeout=file_md5_check_timeout)
            error_context.context(
                "md5 value of data in %s: %s" % (vm.name, dst_md5),
                logging.info)
            if dst_md5 != src_md5:
                test.fail("File changed after transfer host -> %s" % vm.name)

        if params.get("os_type") == "linux":
            for vm_src in addresses:
                for vm_dst in addresses:
                    if vm_src != vm_dst:
                        error_context.context(
                            "Transferring data from %s to %s" %
                            (vm_src.name, vm_dst.name), logging.info)
                        remote.scp_between_remotes(addresses[vm_src],
                                                   addresses[vm_dst],
                                                   port,
                                                   password,
                                                   password,
                                                   username,
                                                   username,
                                                   guest_path,
                                                   dest_path,
                                                   timeout=file_trans_timeout,
                                                   src_inter=host_ifname,
                                                   dst_inter=inet_name[vm_src])
                        dst_md5 = get_file_md5sum(
                            dest_path,
                            sessions[vm_dst],
                            timeout=file_md5_check_timeout)
                        error_context.context(
                            "md5 value of data in %s: %s" % (vm.name, dst_md5),
                            logging.info)
                        if dst_md5 != src_md5:
                            test.fail("File changed transfer %s -> %s" %
                                      (vm_src.name, vm_dst.name))

        for vm in vms:
            error_context.context("Transfer data from %s to host" % vm.name,
                                  logging.info)
            remote.copy_files_from(addresses[vm],
                                   client,
                                   username,
                                   password,
                                   port,
                                   guest_path,
                                   host_path,
                                   timeout=file_trans_timeout,
                                   interface=host_ifname)
            error_context.context("Check whether the file changed after trans",
                                  logging.info)
            dst_md5 = (crypto.hash_file(host_path, algorithm="md5"))
            error_context.context(
                "md5 value of data after copying to host: %s" % dst_md5,
                logging.info)

            if dst_md5 != src_md5:
                test.fail("File changed after transfer (md5sum mismatch)")
            process.system_output("rm -rf %s" % host_path, timeout=timeout)

    finally:
        process.system("rm -rf %s" % host_path,
                       timeout=timeout,
                       ignore_status=True)
        for vm in vms:
            if params.get("os_type") == "linux":
                sessions[vm].cmd("rm -rf %s %s || true" %
                                 (guest_path, dest_path),
                                 timeout=timeout,
                                 ignore_all_errors=True)
            else:
                sessions[vm].cmd("del /f %s" % guest_path,
                                 timeout=timeout,
                                 ignore_all_errors=True)
            sessions[vm].close()
示例#13
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    :param client_vm - vm object
    :param guest_vm - vm object
    :param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    rv_ld_library_path = params.get("rv_ld_library_path")
    display = params.get("display")

    proxy = params.get("spice_proxy", None)
    if proxy:
        try:
            socket.inet_aton(params.get("proxy_ip", None))
        except socket.error:
            raise error.TestNAError("Parameter proxy_ip not changed from default values")

    host_ip = utils_net.get_host_ip_address(params)
    host_port = None
    if guest_vm.get_spice_var("listening_addr") == "ipv6":
        host_ip = "[" + utils_misc.convert_ipv4_to_ipv6(host_ip) + "]"
    host_tls_port = None

    disable_audio = params.get("disable_audio", "no")
    full_screen = params.get("full_screen")

    check_spice_info = params.get("spice_info")
    ssltype = params.get("ssltype")
    test_type = params.get("test_type")

    # cmd var keeps final remote-viewer command line
    # to be executed on client
    cmd = rv_binary
    if client_vm.params.get("os_type") != "windows":
        cmd = cmd + " --display=:0.0"

    # If qemu_ticket is set, set the password
    #  of the VM using the qemu-monitor
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s" % qemu_ticket)

    gencerts = params.get("gencerts")
    certdb = params.get("certdb")
    smartcard = params.get("smartcard")
    host_subj = None
    cacert = None

    rv_parameters_from = params.get("rv_parameters_from", "cmd")
    if rv_parameters_from == "file":
        cmd += " ~/rv_file.vv"

    client_session = client_vm.wait_for_login(timeout=int(params.get("login_timeout", 360)))

    if display == "spice":

        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":

            # client needs cacert file
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"),
            )
            client_session.cmd(
                "rm -rf %s && mkdir -p %s"
                % (guest_vm.get_spice_var("spice_x509_prefix"), guest_vm.get_spice_var("spice_x509_prefix"))
            )
            remote.copy_files_to(
                client_vm.get_address(),
                "scp",
                params.get("username"),
                params.get("password"),
                params.get("shell_port"),
                cacert,
                cacert,
            )

            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")

            # cacert subj is in format for create certificate(with '/' delimiter)
            # remote-viewer needs ',' delimiter. And also is needed to remove
            # first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace("/", ",")[1:]
            if ssltype == "invalid_explicit_hs":
                host_subj = "Invalid Explicit HS"
            else:
                host_subj += host_ip

            # If it's invalid implicit, a remote-viewer connection
            # will be attempted with the hostname, since ssl certs were
            # generated with the ip address
            hostname = socket.gethostname()
            if ssltype == "invalid_implicit_hs":
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (hostname, host_tls_port, host_port)
            else:
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (host_ip, host_tls_port, host_port)

            if rv_parameters_from == "menu":
                line = spice_url
            elif rv_parameters_from == "file":
                pass
            else:
                cmd += spice_url

            if not rv_parameters_from == "file":
                cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes" and not rv_parameters_from == "file":
                cmd += ' --spice-host-subject="%s"' % host_subj

        else:
            host_port = guest_vm.get_spice_var("spice_port")
            if rv_parameters_from == "menu":
                # line to be sent through monitor once r-v is started
                # without spice url
                line = "spice://%s?port=%s" % (host_ip, host_port)
            elif rv_parameters_from == "file":
                pass
            else:
                cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes" and not rv_parameters_from == "file":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    if disable_audio == "yes":
        logging.info("Remote Viewer Set to disable audio")
        cmd += " --spice-disable-audio"

    # Check to see if the test is using a smartcard.
    if smartcard == "yes":
        logging.info("remote viewer Set to use a smartcard")
        if not rv_parameters_from == file:
            cmd += " --spice-smartcard"

        if certdb is not None:
            logging.debug("Remote Viewer set to use the following certificate" " database: " + certdb)
            cmd += " --spice-smartcard-db " + certdb

        if gencerts is not None:
            logging.debug("Remote Viewer set to use the following certs: " + gencerts)
            cmd += " --spice-smartcard-certificates " + gencerts

    if client_vm.params.get("os_type") == "linux":
        cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background
        if rv_ld_library_path:
            cmd = "export LD_LIBRARY_PATH=" + rv_ld_library_path + ";" + cmd

    if rv_parameters_from == "file":
        print "Generating file"
        utils_spice.gen_rv_file(params, guest_vm, host_subj, cacert)
        print "Uploading file to client"
        client_vm.copy_files_to("rv_file.vv", "~/rv_file.vv")

    # Launching the actual set of commands
    try:
        if rv_ld_library_path:
            print_rv_version(client_session, "LD_LIBRARY_PATH=/usr/local/lib " + rv_binary)
        else:
            print_rv_version(client_session, rv_binary)

    except (ShellStatusError, ShellProcessTerminatedError):
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug(
            "Ignoring a Status Exception that occurs from calling " "print versions of remote-viewer or spice-gtk"
        )

    logging.info("Launching %s on the client (virtual)", cmd)

    if proxy:
        if "http" in proxy:
            split = proxy.split("//")[1].split(":")
        else:
            split = proxy.split(":")
        host_ip = split[0]
        if len(split) > 1:
            host_port = split[1]
        else:
            host_port = "3128"
        if rv_parameters_from != "file":
            client_session.cmd("export SPICE_PROXY=%s" % proxy)

    if not params.get("rv_verify") == "only":
        try:
            client_session.cmd(cmd)
        except ShellStatusError:
            logging.debug("Ignoring a status exception, will check connection" "of remote-viewer later")

        # Send command line through monitor since url was not provided
        if rv_parameters_from == "menu":
            utils_spice.wait_timeout(1)
            str_input(client_vm, line)

        # client waits for user entry (authentication) if spice_password is set
        # use qemu monitor password if set, else, if set, try normal password.
        if qemu_ticket:
            # Wait for remote-viewer to launch
            utils_spice.wait_timeout(5)
            str_input(client_vm, qemu_ticket)
        elif ticket:
            if ticket_send:
                ticket = ticket_send

            utils_spice.wait_timeout(5)  # Wait for remote-viewer to launch
            str_input(client_vm, ticket)

        utils_spice.wait_timeout(5)  # Wait for conncetion to establish

    is_rv_connected = True

    try:
        utils_spice.verify_established(
            client_vm, host_ip, host_port, rv_binary, host_tls_port, params.get("spice_secure_channels", None)
        )
    except utils_spice.RVConnectError:
        if test_type == "negative":
            logging.info("remote-viewer connection failed as expected")
            if ssltype in ("invalid_implicit_hs", "invalid_explicit_hs"):
                # Check the qemu process output to verify what is expected
                qemulog = guest_vm.process.get_output()
                if "SSL_accept failed" in qemulog:
                    return
                else:
                    raise error.TestFail("SSL_accept failed not shown in qemu" + "process as expected.")
            is_rv_connected = False
        else:
            raise error.TestFail("remote-viewer connection failed")

    if test_type == "negative" and is_rv_connected:
        raise error.TestFail("remote-viewer connection was established when" + " it was supposed to be unsuccessful")

    # Get spice info
    output = guest_vm.monitor.cmd("info spice")
    logging.debug("INFO SPICE")
    logging.debug(output)

    # Check to see if ipv6 address is reported back from qemu monitor
    if check_spice_info == "ipv6":
        logging.info("Test to check if ipv6 address is reported" " back from the qemu monitor")
        # Remove brackets from ipv6 host ip
        if host_ip[1 : len(host_ip) - 1] in output:
            logging.info("Reported ipv6 address found in output from" " 'info spice'")
        else:
            raise error.TestFail("ipv6 address not found from qemu monitor" " command: 'info spice'")
    else:
        logging.info("Not checking the value of 'info spice'" " from the qemu monitor")

    # prevent from kill remote-viewer after test finish
    if client_vm.params.get("os_type") == "linux":
        cmd = "disown -ar"
    client_session.cmd_output(cmd)
示例#14
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_net.get_host_ip_address(params)
    test_type = params.get("test_type")
    host_port = None
    full_screen = params.get("full_screen")
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")

    #If qemu_ticket is set, set the password of the VM using the qemu-monitor
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s" %
                     qemu_ticket)

    client_session = client_vm.wait_for_login(
        timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]

            cmd += " spice://%s?tls-port=%s\&port=%s" % (
                host_ip, host_tls_port, host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" %
                               (guest_vm.get_spice_var("spice_x509_prefix"),
                                guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                 params.get("username"),
                                 params.get("password"),
                                 params.get("shell_port"), cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background

    # Launching the actual set of commands
    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError, ShellProcessTerminatedError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling "
                      "print versions of remote-viewer or spice-gtk")
示例#15
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_misc.get_host_ip_address(params)
    host_port = None
    full_screen = params.get("full_screen")
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None

    client_session = client_vm.wait_for_login(
            timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_port = guest_vm.get_spice_var("spice_tls_port")
            cacert = "%s/%s" % (guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]

            cmd += " spice://%s?tls-port=%s" % (host_ip, host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" % (
                               guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                      params.get("username"),
                                      params.get("password"),
                                      params.get("shell_port"),
                                      cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"


    cmd = "nohup " + cmd + " &> /dev/null &" # Launch it on background

    # Launching the actual set of commands
    try:
        client_session.cmd("startx &", timeout=15)
    except (ShellCmdError, ShellStatusError):
        logging.debug("Ignoring an Exception that Occurs from calling startx")

    utils_spice.wait_timeout(15)

    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling " \
                      + "print versions of remote-viewer or spice-gtk")

    logging.info("Launching %s on the client (virtual)", cmd)
    client_session.cmd(cmd)

    # client waits for user entry (authentication) if spice_password is set
    if ticket:
        utils_spice.wait_timeout(5)  # Wait for remote-viewer to launch
        send_ticket(client_vm, ticket)

    utils_spice.wait_timeout(5)  # Wait for conncetion to establish
    verify_established(client_session, host_ip, host_port, rv_binary)

    #prevent from kill remote-viewer after test finish
    cmd = "disown -ar"
    client_session.cmd(cmd)
示例#16
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_net.get_host_ip_address(params)
    test_type = params.get("test_type")
    host_port = None
    full_screen = params.get("full_screen")
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")

    #If qemu_ticket is set, set the password of the VM using the qemu-monitor
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s"
                     % qemu_ticket)

    client_session = client_vm.wait_for_login(
            timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")
            cacert = "%s/%s" % (guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]

            cmd += " spice://%s?tls-port=%s\&port=%s" % (host_ip, host_tls_port,
                                                         host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" % (
                               guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                      params.get("username"),
                                      params.get("password"),
                                      params.get("shell_port"),
                                      cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"


    cmd = "nohup " + cmd + " &> /dev/null &" # Launch it on background

    # Launching the actual set of commands
    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError, ShellProcessTerminatedError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling "
                      "print versions of remote-viewer or spice-gtk")
示例#17
0
def run(test, params, env):
    """
    Test Step
        1. boot up two virtual machine
        2. For linux guest,Transfer data:
              host <--> guest1 <--> guest2 <-->host via ipv6
           For windows guest,Transfer data:
              host <--> guest1&guest2 via ipv6
        3. after data transfer, check data have no change
    Params:
        :param test: QEMU test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
    """
    timeout = int(params.get("login_timeout", '360'))
    client = params.get("file_transfer_client")
    port = params.get("file_transfer_port")
    password = params.get("password")
    username = params.get("username")
    tmp_dir = params["tmp_dir"]
    filesize = int(params.get("filesize", '4096'))
    dd_cmd = params["dd_cmd"]
    file_trans_timeout = int(params.get("file_trans_timeout", '1200'))
    file_md5_check_timeout = int(params.get("file_md5_check_timeout", '600'))

    def get_file_md5sum(file_name, session, timeout):
        """
        Get file md5sum from guest.
        """
        logging.info("Get md5sum of the file:'%s'" % file_name)
        s, o = session.cmd_status_output("md5sum %s" % file_name, timeout=timeout)
        if s != 0:
            test.error("Get file md5sum failed as %s" % o)
        return re.findall(r"\w{32}", o)[0]

    sessions = {}
    addresses = {}
    inet_name = {}
    vms = []

    error_context.context("Boot vms for test", logging.info)
    for vm_name in params.get("vms", "vm1 vm2").split():
        vms.append(env.get_vm(vm_name))

    # config ipv6 address host and guest.
    host_ifname = params.get("netdst")
    host_address = utils_net.get_host_ip_address(
        params, ip_ver="ipv6", linklocal=True)

    error_context.context("Get ipv6 address of host: %s" % host_address,
                          logging.info)
    for vm in vms:
        vm.verify_alive()
        sessions[vm] = vm.wait_for_login(timeout=timeout)
        if params.get("os_type") == "linux":
            inet_name[vm] = utils_net.get_linux_ifname(sessions[vm],
                                                       vm.get_mac_address())
        addresses[vm] = utils_net.get_guest_ip_addr(
            sessions[vm],
            vm.get_mac_address(),
            params.get("os_type"),
            ip_version="ipv6",
            linklocal=True)

        error_context.context("Get ipv6 address of %s: %s" % (vm.name, addresses[vm]),
                              logging.info)

    # prepare test data
    guest_path = (tmp_dir + "src-%s" % utils_misc.generate_random_string(8))
    dest_path = (tmp_dir + "dst-%s" % utils_misc.generate_random_string(8))
    host_path = os.path.join(test.tmpdir, "tmp-%s" %
                             utils_misc.generate_random_string(8))
    logging.info("Test setup: Creating %dMB file on host", filesize)
    process.run(dd_cmd % (host_path, filesize), shell=True)

    try:
        src_md5 = (crypto.hash_file(host_path, algorithm="md5"))
        error_context.context("md5 value of data from src: %s" % src_md5,
                              logging.info)
        # transfer data
        for vm in vms:
            error_context.context("Transfer data from host to %s" % vm.name,
                                  logging.info)
            remote.copy_files_to(addresses[vm],
                                 client, username, password, port,
                                 host_path, guest_path,
                                 timeout=file_trans_timeout,
                                 interface=host_ifname)
            dst_md5 = get_file_md5sum(guest_path, sessions[vm],
                                      timeout=file_md5_check_timeout)
            error_context.context("md5 value of data in %s: %s" % (vm.name, dst_md5),
                                  logging.info)
            if dst_md5 != src_md5:
                test.fail("File changed after transfer host -> %s" % vm.name)

        if params.get("os_type") == "linux":
            for vm_src in addresses:
                for vm_dst in addresses:
                    if vm_src != vm_dst:
                        error_context.context("Transferring data from %s to %s" %
                                              (vm_src.name, vm_dst.name),
                                              logging.info)
                        remote.scp_between_remotes(addresses[vm_src],
                                                   addresses[vm_dst],
                                                   port, password, password,
                                                   username, username,
                                                   guest_path, dest_path,
                                                   timeout=file_trans_timeout,
                                                   src_inter=host_ifname,
                                                   dst_inter=inet_name[vm_src])
                        dst_md5 = get_file_md5sum(dest_path, sessions[vm_dst],
                                                  timeout=file_md5_check_timeout)
                        error_context.context("md5 value of data in %s: %s" % (vm.name, dst_md5),
                                              logging.info)
                        if dst_md5 != src_md5:
                            test.fail("File changed transfer %s -> %s"
                                      % (vm_src.name, vm_dst.name))

        for vm in vms:
            error_context.context("Transfer data from %s to host" % vm.name,
                                  logging.info)
            remote.copy_files_from(addresses[vm],
                                   client, username, password, port,
                                   guest_path, host_path,
                                   timeout=file_trans_timeout,
                                   interface=host_ifname)
            error_context.context("Check whether the file changed after trans",
                                  logging.info)
            dst_md5 = (crypto.hash_file(host_path, algorithm="md5"))
            error_context.context("md5 value of data after copying to host: %s" % dst_md5,
                                  logging.info)

            if dst_md5 != src_md5:
                test.fail("File changed after transfer (md5sum mismatch)")
            process.system_output("rm -rf %s" % host_path, timeout=timeout)

    finally:
        process.system("rm -rf %s" % host_path, timeout=timeout,
                       ignore_status=True)
        for vm in vms:
            if params.get("os_type") == "linux":
                sessions[vm].cmd("rm -rf %s %s || true" % (guest_path, dest_path),
                                 timeout=timeout, ignore_all_errors=True)
            else:
                sessions[vm].cmd("del /f %s" % guest_path,
                                 timeout=timeout, ignore_all_errors=True)
            sessions[vm].close()
示例#18
0
    def sync_directories(self):
        """
        Synchronize the directories between the local and remote machines
        :returns: True if any files needed to be copied; False otherwise. Does
        not support symlinks.
        """

        def get_local_hashes(path):
            """
            Create a dict of the hashes of all files in path on the local
            machine.
            :param path: Path to search
            """
            def hash_file(file_name):
                """
                Calculate hex-encoded hash of a file
                :param file_name: File to hash
                """
                f = open(file_name, mode='r')
                h = hashlib.sha1()
                while True:
                    buf = f.read(4096)
                    if not buf:
                        break
                    h.update(buf)
                return h.hexdigest()

            def visit(arg, dir_name, file_names):
                """
                Callback function to calculate and store hashes
                :param arg: Tuple with base path and the hash that will contain
                            the results.
                :param dir_name: Current directory
                :param file_names: File names in the current directory
                """
                (base_path, result) = arg
                for file_name in file_names:
                    path = os.path.join(dir_name, file_name)
                    if os.path.isfile(path):
                        result[
                            os.path.relpath(path, base_path)] = hash_file(path)

            result = {}
            os.path.walk(path, visit, (path, result))

            return result

        def get_remote_hashes(path, session, linesep):
            """
            Create a dict of the hashes of all files in path on the remote
            machine.
            :param path: Path to search
            :param session: Session object to use
            :param linesep: Line separation string for the remote system
            """

            cmd = 'test \! -d %s || find %s -type f | xargs sha1sum' % (path,
                                                                        path)
            status, output = session.cmd_status_output(cmd)
            if not status == 0:
                raise BuildError("Unable to get hashes of remote files: '%s'"
                                 % output)
            result = {}
            # Output is "<sum>  <filename><linesep><sum>  <filename>..."
            for line in output.split(linesep):
                if re.match("^[a-f0-9]{32,}  [^ ].*$", line):
                    (h, f) = line.split(None, 1)
                    result[os.path.relpath(f, path)] = h

            return result

        def list_recursive_dirnames(path):
            """
            List all directories that exist in path on the local machine
            :param path: Path to search
            """
            def visit(arg, dir_name, file_names):
                """
                Callback function list alla directories
                :param arg: Tuple with base path and the list that will contain
                            the results.
                :param dir_name: Current directory
                :param file_names: File names in the current directory
                """
                (base_path, result) = arg
                for file_name in file_names:
                    path = os.path.join(dir_name, file_name)
                    if os.path.isdir(path):
                        result.append(os.path.relpath(path, base_path))

            result = []
            os.path.walk(path, visit, (path, result))

            return result

        remote_hashes = get_remote_hashes(self.full_build_path, self.session,
                                          self.linesep)
        local_hashes = get_local_hashes(self.source)

        to_transfer = []
        for rel_path in list(local_hashes.keys()):
            rhash = remote_hashes.get(rel_path)
            if rhash is None or not rhash == local_hashes[rel_path]:
                to_transfer.append(rel_path)

        need_build = False
        if to_transfer:
            logging.info("Need to copy files to %s on target" %
                         self.full_build_path)
            need_build = True

            # Create all directories
            dirs = list_recursive_dirnames(self.source)
            if dirs:
                dirs_text = " ".join(dirs)
                fmt_arg = (self.full_build_path, self.full_build_path,
                           dirs_text)
                cmd = 'mkdir -p %s && cd %s && mkdir -p %s' % fmt_arg
            else:
                cmd = 'mkdir -p %s' % self.full_build_path
            status, output = self.session.cmd_status_output(cmd)
            if not status == 0:
                raise BuildError("Unable to create remote directories: '%s'"
                                 % output)

            # Copy files
            for file_name in to_transfer:
                local_path = os.path.join(self.source, file_name)
                remote_path = os.path.join(self.full_build_path, file_name)
                remote.copy_files_to(self.address, self.file_transfer_client,
                                     self.username, self.password,
                                     self.file_transfer_port, local_path,
                                     remote_path)

        else:
            logging.info("Directory %s on target already up-to-date" %
                         self.full_build_path)

        return need_build
示例#19
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_misc.get_host_ip_address(params)
    host_port = None
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None

    client_session = client_vm.wait_for_login(
            timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_port = guest_vm.get_spice_var("spice_tls_port")
            cacert = "%s/%s" % (guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/',',')[1:]

            cmd += " spice://%s?tls-port=%s" % (host_ip, host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" % (
                               guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                      params.get("username"),
                                      params.get("password"),
                                      params.get("shell_port"),
                                      cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")
    cmd = "nohup " + cmd + " &> /dev/null &" # Launch it on background

    # Launching the actual set of commands
    launch_xorg(client_session)
    wait_timeout() # Wait for Xorg to start up
    launch_gnome_session(client_session)
    wait_timeout() # Wait till gnome-session starts up

    print_rv_version(client_session, rv_binary)

    logging.info("Launching %s on the client (virtual)", cmd)
    client_session.cmd(cmd)

    # client waits for user entry (authentication) if spice_password is set
    if ticket:
        wait_timeout() # Wait for remote-viewer to launch
        send_ticket(client_vm, ticket)

    wait_timeout() # Wait for conncetion to establish
    verify_established(client_session, host_ip, host_port, rv_binary)

    #prevent from kill remote-viewer after test finish
    cmd = "disown -ar"
    client_session.cmd(cmd)
示例#20
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_misc.get_host_ip_address(params)
    host_port = None
    full_screen = params.get("full_screen")
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None

    client_session = client_vm.wait_for_login(
        timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_port = guest_vm.get_spice_var("spice_tls_port")
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]

            cmd += " spice://%s?tls-port=%s" % (host_ip, host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" %
                               (guest_vm.get_spice_var("spice_x509_prefix"),
                                guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                 params.get("username"),
                                 params.get("password"),
                                 params.get("shell_port"), cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background

    # Launching the actual set of commands
    try:
        client_session.cmd("startx &", timeout=15)
    except (ShellCmdError, ShellStatusError):
        logging.debug("Ignoring an Exception that Occurs from calling startx")

    utils_spice.wait_timeout(15)

    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling " \
                      + "print versions of remote-viewer or spice-gtk")

    logging.info("Launching %s on the client (virtual)", cmd)
    client_session.cmd(cmd)

    # client waits for user entry (authentication) if spice_password is set
    if ticket:
        utils_spice.wait_timeout(5)  # Wait for remote-viewer to launch
        send_ticket(client_vm, ticket)

    utils_spice.wait_timeout(5)  # Wait for conncetion to establish
    verify_established(client_session, host_ip, host_port, rv_binary)

    #prevent from kill remote-viewer after test finish
    cmd = "disown -ar"
    client_session.cmd(cmd)
示例#21
0
def run(test, params, env):
    """
    Test Step
        1. boot up two virtual machine
        2. Transfer data: host <--> guest1 <--> guest2 <-->host via ipv6
        3. after data transfer, check data have no change
    Params:
        :param test: QEMU test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
    """
    timeout = int(params.get("login_timeout", '360'))
    client = params.get("file_transfer_client")
    port = params.get("file_transfer_port")
    password = params.get("password")
    username = params.get("username")
    tmp_dir = params.get("tmp_dir", "/tmp/")
    filesize = int(params.get("filesize", '4096'))
    dd_cmd = params.get("dd_cmd")
    file_trans_timeout = int(params.get("file_trans_timeout", '1200'))
    file_md5_check_timeout = int(params.get("file_md5_check_timeout", '600'))

    def get_linux_ipv6_linklocal_address(ifname, session=None):
        """
        Get host/guest ipv6 linklocal address via ifname
        """
        if session is not None:
            o = session.cmd_output("ifconfig %s" % ifname)
        else:
            o = utils.system_output("ifconfig %s" % ifname)
        ipv6_address_reg = re.compile(r"(fe80::[^\s|/]*)")
        if o:
            ipv6_linklocal_address = ipv6_address_reg.findall(o)
            if not ipv6_linklocal_address:
                raise error.TestError("Can't get %s linklocal address" %
                                      ifname)
            return ipv6_linklocal_address[0]
        else:
            return None

    def get_file_md5sum(file_name, session, timeout):
        """
        Get file md5sum from guest.
        """
        logging.info("Get md5sum of the file:'%s'" % file_name)
        try:
            o = session.cmd_output("md5sum %s" % file_name, timeout=timeout)
            file_md5sum = re.findall("\w+", o)[0]
        except IndexError:
            raise error.TestError("Could not get file md5sum in guest")
        return file_md5sum

    sessions = {}
    addresses = {}
    inet_name = {}
    vms = []

    error.context("Boot vms for test", logging.info)
    for vm_name in params.get("vms", "vm1 vm2").split():
        vms.append(env.get_vm(vm_name))

    # config ipv6 address host and guest.
    host_ifname = params.get("netdst")

    for vm in vms:
        vm.verify_alive()
        sessions[vm] = vm.wait_for_login(timeout=timeout)
        inet_name[vm] = utils_net.get_linux_ifname(sessions[vm],
                                                   vm.get_mac_address())
        addresses[vm] = get_linux_ipv6_linklocal_address(
            inet_name[vm], sessions[vm])

    # prepare test data
    guest_path = (tmp_dir + "src-%s" % utils_misc.generate_random_string(8))
    dest_path = (tmp_dir + "dst-%s" % utils_misc.generate_random_string(8))
    host_path = os.path.join(test.tmpdir,
                             "tmp-%s" % utils_misc.generate_random_string(8))
    logging.info("Test setup: Creating %dMB file on host", filesize)
    utils.run(dd_cmd % (host_path, filesize))

    try:
        src_md5 = (utils.hash_file(host_path, method="md5"))
        # transfer data
        for vm in vms:
            error.context("Transfer data from host to %s" % vm.name,
                          logging.info)
            remote.copy_files_to(addresses[vm],
                                 client,
                                 username,
                                 password,
                                 port,
                                 host_path,
                                 guest_path,
                                 timeout=file_trans_timeout,
                                 interface=host_ifname)
            dst_md5 = get_file_md5sum(guest_path,
                                      sessions[vm],
                                      timeout=file_md5_check_timeout)
            if dst_md5 != src_md5:
                raise error.TestFail("File changed after transfer host -> %s" %
                                     vm.name)

        for vm_src in addresses:
            for vm_dst in addresses:
                if vm_src != vm_dst:
                    error.context(
                        "Transferring data from %s to %s" %
                        (vm_src.name, vm_dst.name), logging.info)
                    remote.scp_between_remotes(addresses[vm_src],
                                               addresses[vm_dst],
                                               port,
                                               password,
                                               password,
                                               username,
                                               username,
                                               guest_path,
                                               dest_path,
                                               timeout=file_trans_timeout,
                                               src_inter=host_ifname,
                                               dst_inter=inet_name[vm_src])
                    dst_md5 = get_file_md5sum(dest_path,
                                              sessions[vm_dst],
                                              timeout=file_md5_check_timeout)
                    if dst_md5 != src_md5:
                        raise error.TestFail("File changed transfer %s -> %s" %
                                             (vm_src.name, vm_dst.name))

        for vm in vms:
            error.context("Transfer data from %s to host" % vm.name,
                          logging.info)
            remote.copy_files_from(addresses[vm],
                                   client,
                                   username,
                                   password,
                                   port,
                                   dest_path,
                                   host_path,
                                   timeout=file_trans_timeout,
                                   interface=host_ifname)
            error.context("Check whether the file changed after trans",
                          logging.info)
            dst_md5 = (utils.hash_file(host_path, method="md5"))
            if dst_md5 != src_md5:
                raise error.TestFail("File changed after transfer",
                                     "Files md5sum mismatch!")
            utils.system_output("rm -rf %s" % host_path, timeout=timeout)

    finally:
        utils.system("rm -rf %s" % host_path,
                     timeout=timeout,
                     ignore_status=True)
        for vm in vms:
            sessions[vm].cmd("rm -rf %s %s || true" % (guest_path, dest_path),
                             timeout=timeout,
                             ignore_all_errors=True)
            sessions[vm].close()
示例#22
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    :param client_vm - vm object
    :param guest_vm - vm object
    :param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_net.get_host_ip_address(params)
    if guest_vm.get_spice_var("listening_addr") == "ipv6":
        host_ip = "[" + utils_misc.convert_ipv4_to_ipv6(host_ip) + "]"
    check_spice_info = params.get("spice_info")
    ssltype = params.get("ssltype")
    test_type = params.get("test_type")
    host_port = None
    full_screen = params.get("full_screen")
    disable_audio = params.get("disable_audio", "no")
    display = params.get("display")
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")
    gencerts = params.get("gencerts")
    certdb = params.get("certdb")
    smartcard = params.get("smartcard")
    menu = params.get("rv_menu", None)
    # cmd var keeps final remote-viewer command line to be executed on client
    cmd = rv_binary + " --display=:0.0"

    # If qemu_ticket is set, set the password of the VM using the qemu-monitor
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s" %
                     qemu_ticket)

    client_session = client_vm.wait_for_login(
        timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"))
            # cacert subj is in format for create certificate(with '/' delimiter)
            # remote-viewer needs ',' delimiter. And also is needed to remove
            # first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]
            if ssltype == "invalid_explicit_hs":
                host_subj = "Invalid Explicit HS"
            else:
                host_subj += host_ip

            # If it's invalid implicit, a remote-viewer connection
            # will be attempted with the hostname, since ssl certs were
            # generated with the ip address
            hostname = socket.gethostname()
            if ssltype == "invalid_implicit_hs":
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (
                    hostname, host_tls_port, host_port)
            else:
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (
                    host_ip, host_tls_port, host_port)

            if menu == "yes":
                line = spice_url
            else:
                cmd += spice_url

            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            # client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" %
                               (guest_vm.get_spice_var("spice_x509_prefix"),
                                guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                 params.get("username"),
                                 params.get("password"),
                                 params.get("shell_port"), cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            if menu == "yes":
                # line to be sent through monitor once r-v is started
                # without spice url
                line = "spice://%s?port=%s" % (host_ip, host_port)
            else:
                cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    if disable_audio == "yes":
        logging.info("Remote Viewer Set to disable audio")
        cmd += " --spice-disable-audio"

    # Check to see if the test is using a smartcard.
    if smartcard == "yes":
        logging.info("remote viewer Set to use a smartcard")
        cmd += " --spice-smartcard"

        if certdb is not None:
            logging.debug("Remote Viewer set to use the following certificate"
                          " database: " + certdb)
            cmd += " --spice-smartcard-db " + certdb

        if gencerts is not None:
            logging.debug("Remote Viewer set to use the following certs: " +
                          gencerts)
            cmd += " --spice-smartcard-certificates " + gencerts

    cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background

    # Launching the actual set of commands
    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError, ShellProcessTerminatedError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling "
                      "print versions of remote-viewer or spice-gtk")
示例#23
0
def run(test, params, env):
    """
    Test Step
        1. boot up two virtual machine
        2. Transfer data: host <--> guest1 <--> guest2 <-->host via ipv6
        3. after data transfer, check data have no change
    Params:
        :param test: QEMU test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
    """
    timeout = int(params.get("login_timeout", '360'))
    client = params.get("file_transfer_client")
    port = params.get("file_transfer_port")
    password = params.get("password")
    username = params.get("username")
    tmp_dir = params.get("tmp_dir", "/tmp/")
    filesize = int(params.get("filesize", '4096'))
    dd_cmd = params.get("dd_cmd")
    file_trans_timeout = int(params.get("file_trans_timeout", '1200'))
    file_md5_check_timeout = int(params.get("file_md5_check_timeout", '600'))

    def get_linux_ipv6_linklocal_address(ifname, session=None):
        """
        Get host/guest ipv6 linklocal address via ifname
        """
        if session is not None:
            o = session.cmd_output("ifconfig %s" % ifname)
        else:
            o = utils.system_output("ifconfig %s" % ifname)
        ipv6_address_reg = re.compile(r"(fe80::[^\s|/]*)")
        if o:
            ipv6_linklocal_address = ipv6_address_reg.findall(o)
            if not ipv6_linklocal_address:
                raise error.TestError("Can't get %s linklocal address"
                                      % ifname)
            return ipv6_linklocal_address[0]
        else:
            return None

    def get_file_md5sum(file_name, session, timeout):
        """
        Get file md5sum from guest.
        """
        logging.info("Get md5sum of the file:'%s'" % file_name)
        try:
            o = session.cmd_output("md5sum %s" % file_name, timeout=timeout)
            file_md5sum = re.findall("\w+", o)[0]
        except IndexError:
            raise error.TestError("Could not get file md5sum in guest")
        return file_md5sum

    sessions = {}
    addresses = {}
    inet_name = {}
    vms = []

    error.context("Boot vms for test", logging.info)
    for vm_name in params.get("vms", "vm1 vm2").split():
        vms.append(env.get_vm(vm_name))

    # config ipv6 address host and guest.
    host_ifname = params.get("netdst")

    for vm in vms:
        vm.verify_alive()
        sessions[vm] = vm.wait_for_login(timeout=timeout)
        inet_name[vm] = utils_net.get_linux_ifname(sessions[vm],
                                                   vm.get_mac_address())
        addresses[vm] = get_linux_ipv6_linklocal_address(inet_name[vm],
                                                         sessions[vm])

    # prepare test data
    guest_path = (tmp_dir + "src-%s" % utils_misc.generate_random_string(8))
    dest_path = (tmp_dir + "dst-%s" % utils_misc.generate_random_string(8))
    host_path = os.path.join(test.tmpdir, "tmp-%s" %
                             utils_misc.generate_random_string(8))
    logging.info("Test setup: Creating %dMB file on host", filesize)
    utils.run(dd_cmd % (host_path, filesize))

    try:
        src_md5 = (utils.hash_file(host_path, method="md5"))
        # transfer data
        for vm in vms:
            error.context("Transfer data from host to %s" % vm.name,
                          logging.info)
            remote.copy_files_to(addresses[vm],
                                 client, username, password, port,
                                 host_path, guest_path,
                                 timeout=file_trans_timeout,
                                 interface=host_ifname)
            dst_md5 = get_file_md5sum(guest_path, sessions[vm],
                                      timeout=file_md5_check_timeout)
            if dst_md5 != src_md5:
                raise error.TestFail("File changed after transfer host -> %s"
                                     % vm.name)

        for vm_src in addresses:
            for vm_dst in addresses:
                if vm_src != vm_dst:
                    error.context("Transferring data from %s to %s" %
                                  (vm_src.name, vm_dst.name), logging.info)
                    remote.scp_between_remotes(addresses[vm_src],
                                               addresses[vm_dst],
                                               port, password, password,
                                               username, username,
                                               guest_path, dest_path,
                                               timeout=file_trans_timeout,
                                               src_inter=host_ifname,
                                               dst_inter=inet_name[vm_src])
                    dst_md5 = get_file_md5sum(dest_path, sessions[vm_dst],
                                              timeout=file_md5_check_timeout)
                    if dst_md5 != src_md5:
                        raise error.TestFail("File changed transfer %s -> %s"
                                             % (vm_src.name, vm_dst.name))

        for vm in vms:
            error.context("Transfer data from %s to host" % vm.name,
                          logging.info)
            remote.copy_files_from(addresses[vm],
                                   client, username, password, port,
                                   dest_path, host_path,
                                   timeout=file_trans_timeout,
                                   interface=host_ifname)
            error.context("Check whether the file changed after trans",
                          logging.info)
            dst_md5 = (utils.hash_file(host_path, method="md5"))
            if dst_md5 != src_md5:
                raise error.TestFail("File changed after transfer (md5sum mismatch)")
            utils.system_output("rm -rf %s" % host_path, timeout=timeout)

    finally:
        utils.system("rm -rf %s" % host_path, timeout=timeout,
                     ignore_status=True)
        for vm in vms:
            sessions[vm].cmd("rm -rf %s %s || true" % (guest_path, dest_path),
                             timeout=timeout, ignore_all_errors=True)
            sessions[vm].close()
示例#24
0
def launch_rv(test, client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    :param client_vm - vm object
    :param guest_vm - vm object
    :param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    rv_ld_library_path = params.get("rv_ld_library_path")
    display = params.get("display")

    proxy = params.get("spice_proxy", None)
    if proxy:
        try:
            socket.inet_aton(params.get("proxy_ip", None))
        except socket.error:
            test.cancel('Parameter proxy_ip not changed from default values')

    host_ip = utils_net.get_host_ip_address(params)
    host_port = None
    if guest_vm.get_spice_var("listening_addr") == "ipv6":
        host_ip = ("[" + utils_misc.convert_ipv4_to_ipv6(host_ip) + "]")
    host_tls_port = None

    disable_audio = params.get("disable_audio", "no")
    full_screen = params.get("full_screen")

    check_spice_info = params.get("spice_info")
    ssltype = params.get("ssltype")
    test_type = params.get("test_type")

    # cmd var keeps final remote-viewer command line
    # to be executed on client
    cmd = rv_binary
    if client_vm.params.get("os_type") != "windows":
        cmd = cmd + " --display=:0.0"

    # If qemu_ticket is set, set the password
    #  of the VM using the qemu-monitor
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s",
                     qemu_ticket)

    gencerts = params.get("gencerts")
    certdb = params.get("certdb")
    smartcard = params.get("smartcard")
    host_subj = None
    cacert = None

    rv_parameters_from = params.get("rv_parameters_from", "cmd")
    if rv_parameters_from == 'file':
        cmd += " ~/rv_file.vv"

    client_session = client_vm.wait_for_login(
        timeout=int(params.get("login_timeout", 360)))

    if display == "spice":

        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":

            # client needs cacert file
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"))
            client_session.cmd("rm -rf %s && mkdir -p %s" %
                               (guest_vm.get_spice_var("spice_x509_prefix"),
                                guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                 params.get("username"),
                                 params.get("password"),
                                 params.get("shell_port"), cacert, cacert)

            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")

            # cacert subj is in format for create certificate(with '/' delimiter)
            # remote-viewer needs ',' delimiter. And also is needed to remove
            # first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]
            if ssltype == "invalid_explicit_hs":
                host_subj = "Invalid Explicit HS"
            else:
                host_subj += host_ip

            # If it's invalid implicit, a remote-viewer connection
            # will be attempted with the hostname, since ssl certs were
            # generated with the ip address
            hostname = socket.gethostname()
            if ssltype == "invalid_implicit_hs":
                spice_url = r" spice://%s?tls-port=%s\&port=%s" % (
                    hostname, host_tls_port, host_port)
            else:
                spice_url = r" spice://%s?tls-port=%s\&port=%s" % (
                    host_ip, host_tls_port, host_port)

            if rv_parameters_from == "menu":
                line = spice_url
            elif rv_parameters_from == "file":
                pass
            else:
                cmd += spice_url

            if not rv_parameters_from == "file":
                cmd += " --spice-ca-file=%s" % cacert

            if (params.get("spice_client_host_subject") == "yes"
                    and not rv_parameters_from == "file"):
                cmd += " --spice-host-subject=\"%s\"" % host_subj

        else:
            host_port = guest_vm.get_spice_var("spice_port")
            if rv_parameters_from == "menu":
                # line to be sent through monitor once r-v is started
                # without spice url
                line = "spice://%s?port=%s" % (host_ip, host_port)
            elif rv_parameters_from == "file":
                pass
            else:
                cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes" and not rv_parameters_from == "file":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    if disable_audio == "yes":
        logging.info("Remote Viewer Set to disable audio")
        cmd += " --spice-disable-audio"

    # Check to see if the test is using a smartcard.
    if smartcard == "yes":
        logging.info("remote viewer Set to use a smartcard")
        if not rv_parameters_from == "file":
            cmd += " --spice-smartcard"

        if certdb is not None:
            logging.debug(
                "Remote Viewer set to use the following certificate"
                " database: %s", certdb)
            cmd += " --spice-smartcard-db " + certdb

        if gencerts is not None:
            logging.debug("Remote Viewer set to use the following certs: %s",
                          gencerts)
            cmd += " --spice-smartcard-certificates " + gencerts

    if client_vm.params.get("os_type") == "linux":
        cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background
        if rv_ld_library_path:
            cmd = "export LD_LIBRARY_PATH=" + rv_ld_library_path + ";" + cmd

    if rv_parameters_from == "file":
        logging.info("Generating file")
        utils_spice.gen_rv_file(params, guest_vm, host_subj, cacert)
        logging.info("Uploading file to client")
        client_vm.copy_files_to("rv_file.vv", "~/rv_file.vv")

    # Launching the actual set of commands
    try:
        if rv_ld_library_path:
            print_rv_version(client_session,
                             "LD_LIBRARY_PATH=/usr/local/lib " + rv_binary)
        else:
            print_rv_version(client_session, rv_binary)

    except (ShellStatusError, ShellProcessTerminatedError):
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling "
                      "print versions of remote-viewer or spice-gtk")

    logging.info("Launching %s on the client (virtual)", cmd)

    if proxy:
        if "http" in proxy:
            split = proxy.split('//')[1].split(':')
        else:
            split = proxy.split(':')
        host_ip = split[0]
        if len(split) > 1:
            host_port = split[1]
        else:
            host_port = "3128"
        if rv_parameters_from != "file":
            client_session.cmd("export SPICE_PROXY=%s" % proxy)

    if not params.get("rv_verify") == "only":
        try:
            client_session.cmd(cmd)
        except ShellStatusError:
            logging.debug("Ignoring a status exception, will check connection"
                          "of remote-viewer later")

        # Send command line through monitor since url was not provided
        if rv_parameters_from == "menu":
            utils_spice.wait_timeout(1)
            str_input(client_vm, line)

        # client waits for user entry (authentication) if spice_password is set
        # use qemu monitor password if set, else, if set, try normal password.
        if qemu_ticket:
            # Wait for remote-viewer to launch
            utils_spice.wait_timeout(5)
            str_input(client_vm, qemu_ticket)
        elif ticket:
            if ticket_send:
                ticket = ticket_send

            utils_spice.wait_timeout(5)  # Wait for remote-viewer to launch
            str_input(client_vm, ticket)

        utils_spice.wait_timeout(15)  # Wait for conncetion to establish

    is_rv_connected = True

    try:
        utils_spice.verify_established(
            client_vm, host_ip, host_port, rv_binary, host_tls_port,
            params.get("spice_secure_channels", None))
    except utils_spice.RVConnectError:
        if test_type == "negative":
            logging.info("remote-viewer connection failed as expected")
            if ssltype in ("invalid_implicit_hs", "invalid_explicit_hs"):
                # Check the qemu process output to verify what is expected
                qemulog = guest_vm.process.get_output()
                if "SSL_accept failed" in qemulog:
                    return
                else:
                    test.fail("SSL_accept failed not shown in qemu"
                              "process as expected.")
            is_rv_connected = False
        else:
            test.fail("remote-viewer connection failed")

    if test_type == "negative" and is_rv_connected:
        test.fail("remote-viewer connection was established when"
                  " it was supposed to be unsuccessful")

    # Get spice info
    output = guest_vm.monitor.cmd("info spice")
    logging.debug("INFO SPICE")
    logging.debug(output)

    # Check to see if ipv6 address is reported back from qemu monitor
    if (check_spice_info == "ipv6"):
        logging.info("Test to check if ipv6 address is reported"
                     " back from the qemu monitor")
        # Remove brackets from ipv6 host ip
        if (host_ip[1:len(host_ip) - 1] in output):
            logging.info("Reported ipv6 address found in output from"
                         " 'info spice'")
        else:
            test.fail("ipv6 address not found from qemu monitor"
                      " command: 'info spice'")
    else:
        logging.info("Not checking the value of 'info spice'"
                     " from the qemu monitor")

    # prevent from kill remote-viewer after test finish
    if client_vm.params.get("os_type") == "linux":
        cmd = "disown -ar"
    client_session.cmd_output(cmd)
示例#25
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_net.get_host_ip_address(params)
    if guest_vm.get_spice_var("listening_addr") == "ipv6":
        host_ip = "[" + utils_misc.convert_ipv4_to_ipv6(host_ip) + "]"
    check_spice_info = params.get("spice_info")
    ssltype = params.get("ssltype")
    test_type = params.get("test_type")
    host_port = None
    full_screen = params.get("full_screen")
    disable_audio = params.get("disable_audio", "no")
    display = params.get("display")
    ticket = None
    ticket_send = params.get("spice_password_send")
    qemu_ticket = params.get("qemu_password")
    gencerts = params.get("gencerts")
    certdb = params.get("certdb")
    smartcard = params.get("smartcard")
    menu = params.get("rv_menu", None)
    #cmd var keeps final remote-viewer command line to be executed on client
    cmd = rv_binary + " --display=:0.0"

    #If qemu_ticket is set, set the password of the VM using the qemu-monitor
    if qemu_ticket:
        guest_vm.monitor.cmd("set_password spice %s" % qemu_ticket)
        logging.info("Sending to qemu monitor: set_password spice %s"
                     % qemu_ticket)

    client_session = client_vm.wait_for_login(
            timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_tls_port = guest_vm.get_spice_var("spice_tls_port")
            host_port = guest_vm.get_spice_var("spice_port")
            cacert = "%s/%s" % (guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]
            if ssltype == "invalid_explicit_hs":
                host_subj = "Invalid Explicit HS"
            else:
                host_subj += host_ip

            # If it's invalid implicit, a remote-viewer connection
            # will be attempted with the hostname, since ssl certs were
            # generated with the ip address
            hostname = socket.gethostname()
            if ssltype == "invalid_implicit_hs":
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (hostname,
                                              host_tls_port, host_port)
            else:
                spice_url = " spice://%s?tls-port=%s\&port=%s" % (host_ip,
                                              host_tls_port, host_port)

            if menu == "yes":
                line = spice_url
            else:
                cmd += spice_url

            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" % (
                               guest_vm.get_spice_var("spice_x509_prefix"),
                               guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                      params.get("username"),
                                      params.get("password"),
                                      params.get("shell_port"),
                                      cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            if menu == "yes":
                #line to be sent through monitor once r-v is started
                #without spice url
                line = "spice://%s?port=%s" % (host_ip, host_port)
            else:
                cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")

    # Check to see if the test is using the full screen option.
    if full_screen == "yes":
        logging.info("Remote Viewer Set to use Full Screen")
        cmd += " --full-screen"

    if disable_audio == "yes":
        logging.info("Remote Viewer Set to disable audio")
        cmd += " --spice-disable-audio"

    # Check to see if the test is using a smartcard.
    if smartcard == "yes":
        logging.info("remote viewer Set to use a smartcard")
        cmd += " --spice-smartcard"

        if certdb != None:
            logging.debug("Remote Viewer set to use the following certificate"
                          " database: " + certdb)
            cmd += " --spice-smartcard-db " + certdb

        if gencerts != None:
            logging.debug("Remote Viewer set to use the following certs: " +
                          gencerts)
            cmd += " --spice-smartcard-certificates " + gencerts

    cmd = "nohup " + cmd + " &> /dev/null &" # Launch it on background

    # Launching the actual set of commands
    try:
        print_rv_version(client_session, rv_binary)
    except ShellStatusError, ShellProcessTerminatedError:
        # Sometimes It fails with Status error, ingore it and continue.
        # It's not that important to have printed versions in the log.
        logging.debug("Ignoring a Status Exception that occurs from calling "
                      "print versions of remote-viewer or spice-gtk")
示例#26
0
def launch_rv(client_vm, guest_vm, params):
    """
    Launches rv_binary with args based on spice configuration
    inside client_session on background.
    remote-viewer will try to connect from vm1 from vm2

    @param client_vm - vm object
    @param guest_vm - vm object
    @param params
    """
    rv_binary = params.get("rv_binary", "remote-viewer")
    host_ip = utils_misc.get_host_ip_address(params)
    host_port = None
    display = params.get("display")
    cmd = rv_binary + " --display=:0.0"
    ticket = None

    client_session = client_vm.wait_for_login(
        timeout=int(params.get("login_timeout", 360)))

    if display == "spice":
        ticket = guest_vm.get_spice_var("spice_password")

        if guest_vm.get_spice_var("spice_ssl") == "yes":
            host_port = guest_vm.get_spice_var("spice_tls_port")
            cacert = "%s/%s" % (
                guest_vm.get_spice_var("spice_x509_prefix"),
                guest_vm.get_spice_var("spice_x509_cacert_file"))
            #cacert subj is in format for create certificate(with '/' delimiter)
            #remote-viewer needs ',' delimiter. And also is needed to remove
            #first character (it's '/')
            host_subj = guest_vm.get_spice_var("spice_x509_server_subj")
            host_subj = host_subj.replace('/', ',')[1:]

            cmd += " spice://%s?tls-port=%s" % (host_ip, host_port)
            cmd += " --spice-ca-file=%s" % cacert

            if params.get("spice_client_host_subject") == "yes":
                cmd += " --spice-host-subject=\"%s\"" % host_subj

            #client needs cacert file
            client_session.cmd("rm -rf %s && mkdir -p %s" %
                               (guest_vm.get_spice_var("spice_x509_prefix"),
                                guest_vm.get_spice_var("spice_x509_prefix")))
            remote.copy_files_to(client_vm.get_address(), 'scp',
                                 params.get("username"),
                                 params.get("password"),
                                 params.get("shell_port"), cacert, cacert)
        else:
            host_port = guest_vm.get_spice_var("spice_port")
            cmd += " spice://%s?port=%s" % (host_ip, host_port)

    elif display == "vnc":
        raise NotImplementedError("remote-viewer vnc")

    else:
        raise Exception("Unsupported display value")
    cmd = "nohup " + cmd + " &> /dev/null &"  # Launch it on background

    # Launching the actual set of commands
    launch_xorg(client_session)
    wait_timeout()  # Wait for Xorg to start up
    launch_gnome_session(client_session)
    wait_timeout()  # Wait till gnome-session starts up

    print_rv_version(client_session, rv_binary)

    logging.info("Launching %s on the client (virtual)", cmd)
    client_session.cmd(cmd)

    # client waits for user entry (authentication) if spice_password is set
    if ticket:
        wait_timeout()  # Wait for remote-viewer to launch
        send_ticket(client_vm, ticket)

    wait_timeout()  # Wait for conncetion to establish
    verify_established(client_session, host_ip, host_port, rv_binary)

    #prevent from kill remote-viewer after test finish
    cmd = "disown -ar"
    client_session.cmd(cmd)