Ejemplo n.º 1
0
    def reset_interface(self, iface_mac):
        """
        Check interface through guestfish.Fix mac if necessary.
        """
        # disk or domain
        vm_ref = self.params.get("libvirt_domain")
        if not vm_ref:
            vm_ref = self.params.get("disk_img")
            if not vm_ref:
                logging.error("No object to edit.")
                return False
        logging.info("Resetting %s's mac to %s", vm_ref, iface_mac)

        # Fix file which includes interface devices information
        # Default is /etc/udev/rules.d/70-persistent-net.rules
        devices_file = "/etc/udev/rules.d/70-persistent-net.rules"
        # Set file which binds mac and IP-address
        ifcfg_files = [
            "/etc/sysconfig/network-scripts/ifcfg-p1p1",
            "/etc/sysconfig/network-scripts/ifcfg-eth0"
        ]
        # Fix devices file
        mac_regex = (r"\w.:\w.:\w.:\w.:\w.:\w.")
        edit_expr = "s/%s/%s/g" % (mac_regex, iface_mac)
        file_ret = self.is_file(devices_file)
        if file_ret.stdout.strip() == "true":
            self.close_session()
            try:
                result = lgf.virt_edit_cmd(vm_ref,
                                           devices_file,
                                           expr=edit_expr,
                                           debug=True,
                                           ignore_status=True)
                if result.exit_status:
                    logging.error("Edit %s failed:%s", devices_file, result)
                    return False
            except lgf.LibguestfsCmdError, detail:
                logging.error("Edit %s failed:%s", devices_file, detail)
                return False
            self.new_session()
            # Just to keep output looking better
            self.is_ready()
            logging.debug(self.cat(devices_file))
Ejemplo n.º 2
0
    def reset_interface(self, iface_mac):
        """
        Check interface through guestfish.Fix mac if necessary.
        """
        # disk or domain
        vm_ref = self.params.get("libvirt_domain")
        if not vm_ref:
            vm_ref = self.params.get("disk_img")
            if not vm_ref:
                logging.error("No object to edit.")
                return False
        logging.info("Resetting %s's mac to %s", vm_ref, iface_mac)

        # Fix file which includes interface devices information
        # Default is /etc/udev/rules.d/70-persistent-net.rules
        devices_file = "/etc/udev/rules.d/70-persistent-net.rules"
        # Set file which binds mac and IP-address
        ifcfg_files = ["/etc/sysconfig/network-scripts/ifcfg-p1p1",
                       "/etc/sysconfig/network-scripts/ifcfg-eth0"]
        # Fix devices file
        mac_regex = (r"\w.:\w.:\w.:\w.:\w.:\w.")
        edit_expr = "s/%s/%s/g" % (mac_regex, iface_mac)
        file_ret = self.is_file(devices_file)
        if file_ret.stdout.strip() == "true":
            self.close_session()
            try:
                result = lgf.virt_edit_cmd(vm_ref, devices_file,
                                           expr=edit_expr, debug=True,
                                           ignore_status=True)
                if result.exit_status:
                    logging.error("Edit %s failed:%s", devices_file, result)
                    return False
            except lgf.LibguestfsCmdError, detail:
                logging.error("Edit %s failed:%s", devices_file, detail)
                return False
            self.new_session()
            # Just to keep output looking better
            self.is_ready()
            logging.debug(self.cat(devices_file))
Ejemplo n.º 3
0
def run(test, params, env):
    """
    Test of virt-edit.

    1) Get and init parameters for test.
    2) Prepare environment.
    3) Run virt-edit command and get result.
    5) Recover environment.
    6) Check result.
    """

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    remote_host = params.get("virt_edit_remote_host", "HOST.EXAMPLE")
    remote_user = params.get("virt_edit_remote_user", "root")
    remote_passwd = params.get("virt_edit_remote_passwd", "PASSWD.EXAMPLE")
    connect_uri = params.get("virt_edit_connect_uri")
    if connect_uri is not None:
        uri = "qemu+ssh://%s@%s/system" % (remote_user, remote_host)
        if uri.count("EXAMPLE"):
            raise error.TestNAError("Please config host and passwd first.")
        # Config ssh autologin for it
        ssh_key.setup_ssh_key(remote_host, remote_user, remote_passwd, port=22)
    else:
        uri = libvirt_vm.normalize_connect_uri(
            params.get("connect_uri", "default"))
    start_vm = params.get("start_vm", "no")
    vm_ref = params.get("virt_edit_vm_ref", vm_name)
    file_ref = params.get("virt_edit_file_ref", "/etc/hosts")
    created_img = params.get("virt_edit_created_img", "/tmp/foo.img")
    foo_line = params.get("foo_line", "")
    options = params.get("virt_edit_options")
    options_suffix = params.get("virt_edit_options_suffix")
    status_error = params.get("status_error", "no")
    backup_extension = params.get("virt_edit_backup_extension")
    test_format = params.get("virt_edit_format")

    # virt-edit should not be used when vm is running.
    # (for normal test)
    if vm.is_alive() and start_vm == "no":
        vm.destroy(gracefully=True)

    dom_disk_dict = vm.get_disk_devices()  # TODO
    dom_uuid = vm.get_uuid()
    # Disk format: raw or qcow2
    disk_format = None
    # If object is a disk file path
    is_disk = False

    if vm_ref == "domdisk":
        if len(dom_disk_dict) != 1:
            raise error.TestError("Only one disk device should exist on "
                                  "%s:\n%s." % (vm_name, dom_disk_dict))
        disk_detail = dom_disk_dict.values()[0]
        vm_ref = disk_detail['source']
        logging.info("disk to be edit:%s", vm_ref)
        if test_format:
            # Get format:raw or qcow2
            info = utils.run("qemu-img info %s" % vm_ref).stdout
            for line in info.splitlines():
                comps = line.split(':')
                if comps[0].count("format"):
                    disk_format = comps[-1].strip()
                    break
            if disk_format is None:
                raise error.TestError("Cannot get disk format:%s" % info)
        is_disk = True
    elif vm_ref == "domname":
        vm_ref = vm_name
    elif vm_ref == "domuuid":
        vm_ref = dom_uuid
    elif vm_ref == "createdimg":
        vm_ref = created_img
        utils.run("dd if=/dev/zero of=%s bs=256M count=1" % created_img)
        is_disk = True

    # Decide whether pass a exprt for virt-edit command.
    if foo_line != "":
        expr = "s/$/%s/" % foo_line
    else:
        expr = ""

    if backup_extension is not None:
        if options is None:
            options = ""
        options += " -b %s" % backup_extension

    # Stop libvirtd if test need.
    libvirtd = params.get("libvirtd", "on")
    if libvirtd == "off":
        utils_libvirtd.libvirtd_stop()

    # Run test
    result = lgf.virt_edit_cmd(vm_ref,
                               file_ref,
                               is_disk=is_disk,
                               disk_format=disk_format,
                               options=options,
                               extra=options_suffix,
                               expr=expr,
                               connect_uri=uri,
                               debug=True)
    status = result.exit_status

    # Recover libvirtd.
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    utils.run("rm -f %s" % created_img)

    # Remove backup file in vm if it exists
    if backup_extension is not None:
        backup_file = file_ref + backup_extension
        cleanup_file_in_vm(vm, backup_file)

    status_error = (status_error == "yes")
    if status != 0:
        if not status_error:
            raise error.TestFail("Command executed failed.")
    else:
        if (expr != ""
                and (not login_to_check_foo_line(vm, file_ref, foo_line))):
            raise error.TestFail("Virt-edit to add %s in %s failed."
                                 "Test failed." % (foo_line, file_ref))
Ejemplo n.º 4
0
def run_virt_edit(test, params, env):
    """
    Test of virt-edit.

    1) Get and init parameters for test.
    2) Prepare environment.
    3) Run virt-edit command and get result.
    5) Recover environment.
    6) Check result.
    """

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri",
                                                       "default"))
    start_vm = params.get("start_vm", "no")
    vm_ref = params.get("virt_edit_vm_ref", vm_name)
    file_ref = params.get("virt_edit_file_ref", "/etc/hosts")
    created_img = params.get("virt_edit_created_img", "/tmp/foo.img")
    foo_line = params.get("foo_line", "")
    options = params.get("virt_edit_options")
    options_suffix = params.get("virt_edit_options_suffix")
    status_error = params.get("status_error", "no")

    # virt-edit should not be used when vm is running.
    # (for normal test)
    if vm.is_alive() and start_vm == "no":
        vm.destroy(gracefully=True)

    dom_disk_dict = vm.get_disk_devices() # TODO
    dom_uuid = vm.get_uuid()

    if vm_ref == "domdisk":
        if len(dom_disk_dict) != 1:
            raise error.TestError("Only one disk device should exist on "
                                  "%s:\n%s." % (vm_name, dom_disk_dict))
        disk_detail = dom_disk_dict.values()[0]
        vm_ref = disk_detail['source']
        logging.info("disk to be edit:%s", vm_ref)
    elif vm_ref == "domname":
        vm_ref = vm_name
    elif vm_ref == "domuuid":
        vm_ref = dom_uuid
    elif vm_ref == "createdimg":
        vm_ref = created_img
        utils.run("dd if=/dev/zero of=%s bs=256M count=1" % created_img)

    # Decide whether pass a exprt for virt-edit command.
    if foo_line != "":
        expr = "s/$/%s/" % foo_line
    else:
        expr = ""

    # Stop libvirtd if test need.
    libvirtd = params.get("libvirtd", "on")
    if libvirtd == "off":
        utils_libvirtd.libvirtd_stop()

    # Run test
    virsh_dargs = {'ignore_status': True, 'debug': True, 'uri': uri}
    result = lgf.virt_edit_cmd(vm_ref, file_ref, options,
                               options_suffix, expr, **virsh_dargs)
    status = result.exit_status

    # Recover libvirtd.
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    utils.run("rm -f %s" % created_img)

    status_error = (status_error == "yes")
    if status != 0:
        if not status_error:
            raise error.TestFail("Command executed failed.")
    else:
        if (expr != "" and
           (not login_to_check_foo_line(vm, file_ref, foo_line))):
            raise error.TestFail("Virt-edit to add %s in %s failed."
                                 "Test failed." % (foo_line, file_ref))
Ejemplo n.º 5
0
def run(test, params, env):
    """
    Test of virt-edit.

    1) Get and init parameters for test.
    2) Prepare environment.
    3) Run virt-edit command and get result.
    5) Recover environment.
    6) Check result.
    """

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    remote_host = params.get("virt_edit_remote_host", "HOST.EXAMPLE")
    remote_user = params.get("virt_edit_remote_user", "root")
    remote_passwd = params.get("virt_edit_remote_passwd", "PASSWD.EXAMPLE")
    connect_uri = params.get("virt_edit_connect_uri")
    if connect_uri is not None:
        uri = "qemu+ssh://%s@%s/system" % (remote_user, remote_host)
        if uri.count("EXAMPLE"):
            raise error.TestNAError("Please config host and passwd first.")
        # Config ssh autologin for it
        ssh_key.setup_ssh_key(remote_host, remote_user, remote_passwd, port=22)
    else:
        uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                          "default"))
    start_vm = params.get("start_vm", "no")
    vm_ref = params.get("virt_edit_vm_ref", vm_name)
    file_ref = params.get("virt_edit_file_ref", "/etc/hosts")
    created_img = params.get("virt_edit_created_img", "/tmp/foo.img")
    foo_line = params.get("foo_line", "")
    options = params.get("virt_edit_options")
    options_suffix = params.get("virt_edit_options_suffix")
    status_error = params.get("status_error", "no")
    backup_extension = params.get("virt_edit_backup_extension")
    test_format = params.get("virt_edit_format")

    # virt-edit should not be used when vm is running.
    # (for normal test)
    if vm.is_alive() and start_vm == "no":
        vm.destroy(gracefully=True)

    dom_disk_dict = vm.get_disk_devices()  # TODO
    dom_uuid = vm.get_uuid()
    # Disk format: raw or qcow2
    disk_format = None
    # If object is a disk file path
    is_disk = False

    if vm_ref == "domdisk":
        if len(dom_disk_dict) != 1:
            raise error.TestError("Only one disk device should exist on "
                                  "%s:\n%s." % (vm_name, dom_disk_dict))
        disk_detail = dom_disk_dict.values()[0]
        vm_ref = disk_detail['source']
        logging.info("disk to be edit:%s", vm_ref)
        if test_format:
            # Get format:raw or qcow2
            info = utils.run("qemu-img info %s" % vm_ref).stdout
            for line in info.splitlines():
                comps = line.split(':')
                if comps[0].count("format"):
                    disk_format = comps[-1].strip()
                    break
            if disk_format is None:
                raise error.TestError("Cannot get disk format:%s" % info)
            options = "--format=%s" % disk_format
        is_disk = True
    elif vm_ref == "domname":
        vm_ref = vm_name
    elif vm_ref == "domuuid":
        vm_ref = dom_uuid
    elif vm_ref == "createdimg":
        vm_ref = created_img
        utils.run("dd if=/dev/zero of=%s bs=256M count=1" % created_img)
        is_disk = True

    # Decide whether pass a exprt for virt-edit command.
    if foo_line != "":
        expr = "s/$/%s/" % foo_line
    else:
        expr = ""

    if backup_extension is not None:
        if options is None:
            options = ""
        options += " -b %s" % backup_extension

    # Stop libvirtd if test need.
    libvirtd = params.get("libvirtd", "on")
    if libvirtd == "off":
        utils_libvirtd.libvirtd_stop()

    # Run test
    result = lgf.virt_edit_cmd(vm_ref, file_ref, is_disk, options,
                               options_suffix, expr, uri, debug=True)
    status = result.exit_status

    # Recover libvirtd.
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    utils.run("rm -f %s" % created_img)

    # Remove backup file in vm if it exists
    if backup_extension is not None:
        backup_file = file_ref + backup_extension
        cleanup_file_in_vm(vm, backup_file)

    status_error = (status_error == "yes")
    if status != 0:
        if not status_error:
            raise error.TestFail("Command executed failed.")
    else:
        if (expr != "" and
                (not login_to_check_foo_line(vm, file_ref, foo_line))):
            raise error.TestFail("Virt-edit to add %s in %s failed."
                                 "Test failed." % (foo_line, file_ref))
Ejemplo n.º 6
0
class GuestfishTools(lgf.GuestfishPersistent):

    """Useful Tools for Guestfish class."""

    __slots__ = ('params', )

    def __init__(self, params):
        """
        Init a persistent guestfish shellsession.
        """
        self.params = params
        disk_img = params.get("disk_img")
        ro_mode = bool(params.get("gf_ro_mode", False))
        libvirt_domain = params.get("libvirt_domain")
        inspector = bool(params.get("gf_inspector", False))
        mount_options = params.get("mount_options")
        run_mode = params.get("gf_run_mode", "interactive")
        super(GuestfishTools, self).__init__(disk_img, ro_mode,
                                             libvirt_domain, inspector,
                                             mount_options=mount_options,
                                             run_mode=run_mode)

    def get_root(self):
        """
        Get root filesystem w/ guestfish
        """
        getroot_result = self.inspect_os()
        roots_list = getroot_result.stdout.splitlines()
        if getroot_result.exit_status or not len(roots_list):
            logging.error("Get root failed:%s", getroot_result)
            return (False, getroot_result)
        return (True, roots_list[0].strip())

    def analyse_release(self):
        """
        Analyse /etc/redhat-release
        """
        logging.info("Analysing /etc/redhat-release...")
        release_result = self.cat("/etc/redhat-release")
        logging.debug(release_result)
        if release_result.exit_status:
            logging.error("Cat /etc/redhat-release failed")
            return (False, release_result)

        release_type = {'rhel': "Red Hat Enterprise Linux",
                        'fedora': "Fedora"}
        for key in release_type:
            if re.search(release_type[key], release_result.stdout):
                return (True, key)

    def write_file(self, path, content):
        """
        Create a new file to vm with guestfish
        """
        logging.info("Creating file %s in vm...", path)
        write_result = self.write(path, content)
        if write_result.exit_status:
            logging.error("Create '%s' with content '%s' failed:%s",
                          path, content, write_result)
            return False
        return True

    def get_partitions_info(self, device="/dev/sda"):
        """
        Get disk partition's information.
        """
        list_result = self.part_list(device)
        if list_result.exit_status:
            logging.error("List partition info failed:%s", list_result)
            return (False, list_result)
        list_lines = list_result.stdout.splitlines()
        # This dict is a struct like this: {key:{a dict}, key:{a dict}}
        partitions = {}
        # This dict is a struct of normal dict, for temp value of a partition
        part_details = {}
        index = -1
        for line in list_lines:
            # Init for a partition
            if re.search("\[\d\]\s+=", line):
                index = line.split("]")[0].split("[")[-1]
                part_details = {}
                partitions[index] = part_details

            if re.search("part_num", line):
                part_num = int(line.split(":")[-1].strip())
                part_details['num'] = part_num
            elif re.search("part_start", line):
                part_start = int(line.split(":")[-1].strip())
                part_details['start'] = part_start
            elif re.search("part_end", line):
                part_end = int(line.split(":")[-1].strip())
                part_details['end'] = part_end
            elif re.search("part_size", line):
                part_size = int(line.split(":")[-1].strip())
                part_details['size'] = part_size

            if index != -1:
                partitions[index] = part_details
        logging.info(partitions)
        return (True, partitions)

    def get_part_size(self, part_num):
        status, partitions = self.get_partitions_info()
        if status is False:
            return None
        for partition in partitions.values():
            if str(partition.get("num")) == str(part_num):
                return partition.get("size")

    def create_fs(self):
        """
        Create filesystem of disk

        Choose lvm or physical partition and create fs on it
        """
        image_path = self.params.get("image_path")
        self.add_drive(image_path)
        self.run()

        partition_type = self.params.get("partition_type")
        fs_type = self.params.get("fs_type", "ext3")
        image_size = self.params.get("image_size", "6G")
        with_blocksize = self.params.get("with_blocksize")
        blocksize = self.params.get("blocksize")
        tarball_path = self.params.get("tarball_path")

        if partition_type not in ['lvm', 'physical']:
            return (False, "partition_type is incorrect, support [physical,lvm]")

        if partition_type == "lvm":
            logging.info("create lvm partition...")
            pv_name = self.params.get("pv_name", "/dev/sdb")
            vg_name = self.params.get("vg_name", "vol_test")
            lv_name = self.params.get("lv_name", "vol_file")
            mount_point = "/dev/%s/%s" % (vg_name, lv_name)
            lv_size = int(image_size.replace('G', '')) * 1000

            self.pvcreate(pv_name)
            self.vgcreate(vg_name, pv_name)
            self.lvcreate(lv_name, vg_name, lv_size)

        elif partition_type == "physical":
            logging.info("create physical partition...")
            pv_name = self.params.get("pv_name", "/dev/sdb")
            mount_point = pv_name + "1"

            self.part_disk(pv_name, "mbr")
            self.part_list(pv_name)

        if with_blocksize == "yes" and fs_type != "btrfs":
            if blocksize:
                self.mkfs_opts(fs_type, mount_point, "blocksize:%s" % (blocksize))
                self.vfs_type(mount_point)
            else:
                logging.error("with_blocksize is set but blocksize not given")
                self.umount_all()
                self.sync()
                return (False, "with_blocksize is set but blocksize not given")
        else:
            self.mkfs(fs_type, mount_point)
            self.vfs_type(mount_point)

        if tarball_path:
            self.mount_options("noatime", mount_point, '/')
            self.tar_in(tarball_path, '/')
            self.ll('/')

        self.umount_all()
        self.sync()
        return (True, "create_fs successfully")

    def create_msdos_part(self, device, start="1", end="-1"):
        """
        Create a msdos partition in given device.
        Default partition section is whole disk(1~-1).
        And return its part name if part add succeed.
        """
        logging.info("Creating a new partition on %s...", device)
        init_result = self.part_init(device, "msdos")
        if init_result.exit_status:
            logging.error("Init disk failed:%s", init_result)
            return (False, init_result)
        add_result = self.part_add(device, "p", start, end)
        if add_result.exit_status:
            logging.error("Add a partition failed:%s", add_result)
            return (False, add_result)

        # Get latest created part num to return
        status, partitions = self.get_partitions_info(device)
        if status is False:
            return (False, partitions)
        part_num = -1
        for partition in partitions.values():
            cur_num = partition.get("num")
            if cur_num > part_num:
                part_num = cur_num

        if part_num == -1:
            return (False, partitions)

        return (True, part_num)

    def create_whole_disk_msdos_part(self, device):
        """
        Create only one msdos partition in given device.
        And return its part name if part add succeed.
        """
        logging.info("Creating one partition of whole %s...", device)
        init_result = self.part_init(device, "msdos")
        if init_result.exit_status:
            logging.error("Init disk failed:%s", init_result)
            return (False, init_result)
        disk_result = self.part_disk(device, "msdos")
        if disk_result.exit_status:
            logging.error("Init disk failed:%s", disk_result)
            return (False, disk_result)

        # Get latest created part num to return
        status, partitions = self.get_partitions_info(device)
        if status is False:
            return (False, partitions)
        part_num = -1
        for partition in partitions.values():
            cur_num = partition.get("num")
            if cur_num > part_num:
                part_num = cur_num

        if part_num == -1:
            return (False, partitions)

        return (True, part_num)

    def get_bootable_part(self, device="/dev/sda"):
        status, partitions = self.get_partitions_info(device)
        if status is False:
            return (False, partitions)
        for partition in partitions.values():
            num = partition.get("num")
            ba_result = self.part_get_bootable(device, num)
            if ba_result.stdout.strip() == "true":
                return (True, "%s%s" % (device, num))
        return (False, partitions)

    def get_mbr_id(self, device="/dev/sda"):
        status, partitions = self.get_partitions_info(device)
        if status is False:
            return (False, partitions)
        for partition in partitions.values():
            num = partition.get("num")
            mbr_id_result = self.part_get_mbr_id(device, num)
            if mbr_id_result.exit_status == 0:
                return (True, mbr_id_result.stdout.strip())
        return (False, partitions)

    def get_part_type(self, device="/dev/sda"):
        part_type_result = self.part_get_parttype(device)
        if part_type_result.exit_status:
            return (False, part_type_result)
        return (True, part_type_result.stdout.strip())

    def get_md5(self, path):
        """
        Get files md5 value.
        """
        logging.info("Computing %s's md5...", path)
        md5_result = self.checksum("md5", path)
        if md5_result.exit_status:
            logging.error("Check %s's md5 failed:%s", path, md5_result)
            return (False, md5_result)
        return (True, md5_result.stdout.strip())

    def reset_interface(self, iface_mac):
        """
        Check interface through guestfish.Fix mac if necessary.
        """
        # disk or domain
        vm_ref = self.params.get("libvirt_domain")
        if not vm_ref:
            vm_ref = self.params.get("disk_img")
            if not vm_ref:
                logging.error("No object to edit.")
                return False
        logging.info("Resetting %s's mac to %s", vm_ref, iface_mac)

        # Fix file which includes interface devices information
        # Default is /etc/udev/rules.d/70-persistent-net.rules
        devices_file = "/etc/udev/rules.d/70-persistent-net.rules"
        # Set file which binds mac and IP-address
        ifcfg_files = ["/etc/sysconfig/network-scripts/ifcfg-p1p1",
                       "/etc/sysconfig/network-scripts/ifcfg-eth0"]
        # Fix devices file
        mac_regex = (r"\w.:\w.:\w.:\w.:\w.:\w.")
        edit_expr = "s/%s/%s/g" % (mac_regex, iface_mac)
        file_ret = self.is_file(devices_file)
        if file_ret.stdout.strip() == "true":
            self.close_session()
            try:
                result = lgf.virt_edit_cmd(vm_ref, devices_file,
                                           expr=edit_expr, debug=True,
                                           ignore_status=True)
                if result.exit_status:
                    logging.error("Edit %s failed:%s", devices_file, result)
                    return False
            except lgf.LibguestfsCmdError, detail:
                logging.error("Edit %s failed:%s", devices_file, detail)
                return False
            self.new_session()
            # Just to keep output looking better
            self.is_ready()
            logging.debug(self.cat(devices_file))

        # Fix interface file
        for ifcfg_file in ifcfg_files:
            file_ret = self.is_file(ifcfg_file)
            if file_ret.stdout.strip() == "false":
                continue
            self.close_session()
            self.params['ifcfg_file'] = ifcfg_file
            try:
                result = lgf.virt_edit_cmd(vm_ref, ifcfg_file,
                                           expr=edit_expr, debug=True,
                                           ignore_status=True)
                if result.exit_status:
                    logging.error("Edit %s failed:%s", ifcfg_file, result)
                    return False
            except lgf.LibguestfsCmdError, detail:
                logging.error("Edit %s failed:%s", ifcfg_file, detail)
                return False
            self.new_session()
            # Just to keep output looking better
            self.is_ready()
            logging.debug(self.cat(ifcfg_file))
Ejemplo n.º 7
0
def run_virt_edit(test, params, env):
    """
    Test of virt-edit.

    1) Get and init parameters for test.
    2) Prepare environment.
    3) Run virt-edit command and get result.
    5) Recover environment.
    6) Check result.
    """

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                      "default"))
    start_vm = params.get("start_vm", "no")
    vm_ref = params.get("virt_edit_vm_ref", vm_name)
    file_ref = params.get("virt_edit_file_ref", "/etc/hosts")
    created_img = params.get("virt_edit_created_img", "/tmp/foo.img")
    foo_line = params.get("foo_line", "")
    options = params.get("virt_edit_options")
    options_suffix = params.get("virt_edit_options_suffix")
    status_error = params.get("status_error", "no")

    # virt-edit should not be used when vm is running.
    # (for normal test)
    if vm.is_alive() and start_vm == "no":
        vm.destroy(gracefully=True)

    dom_disk_dict = vm.get_disk_devices()  # TODO
    dom_uuid = vm.get_uuid()

    if vm_ref == "domdisk":
        if len(dom_disk_dict) != 1:
            raise error.TestError("Only one disk device should exist on "
                                  "%s:\n%s." % (vm_name, dom_disk_dict))
        disk_detail = dom_disk_dict.values()[0]
        vm_ref = disk_detail['source']
        logging.info("disk to be edit:%s", vm_ref)
    elif vm_ref == "domname":
        vm_ref = vm_name
    elif vm_ref == "domuuid":
        vm_ref = dom_uuid
    elif vm_ref == "createdimg":
        vm_ref = created_img
        utils.run("dd if=/dev/zero of=%s bs=256M count=1" % created_img)

    # Decide whether pass a exprt for virt-edit command.
    if foo_line != "":
        expr = "s/$/%s/" % foo_line
    else:
        expr = ""

    # Stop libvirtd if test need.
    libvirtd = params.get("libvirtd", "on")
    if libvirtd == "off":
        libvirt_vm.libvirtd_stop()

    # Run test
    virsh_dargs = {'ignore_status': True, 'debug': True, 'uri': uri}
    result = lgf.virt_edit_cmd(vm_ref, file_ref, options, options_suffix, expr,
                               **virsh_dargs)
    status = result.exit_status

    # Recover libvirtd.
    if libvirtd == "off":
        libvirt_vm.libvirtd_start()

    utils.run("rm -f %s" % created_img)

    status_error = (status_error == "yes")
    if status != 0:
        if not status_error:
            raise error.TestFail("Command executed failed.")
    else:
        if (expr != ""
                and (not login_to_check_foo_line(vm, file_ref, foo_line))):
            raise error.TestFail("Virt-edit to add %s in %s failed."
                                 "Test failed." % (foo_line, file_ref))