• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils_misc.get_path函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中utils_misc.get_path函数的典型用法代码示例。如果您正苦于以下问题:Python get_path函数的具体用法?Python get_path怎么用?Python get_path使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_path函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, test, params, image_name, blkdebug_cfg="",
                 prompt=r"qemu-io>\s*$", log_filename=None, io_options="",
                 log_func=None):
        self.type = ""
        if log_filename:
            log_filename += "-" + utils_misc.generate_random_string(4)
            self.output_func = utils_misc.log_line
            self.output_params = (log_filename,)
        else:
            self.output_func = None
            self.output_params = ()
        self.output_prefix = ""
        self.prompt=prompt
        self.blkdebug_cfg=blkdebug_cfg

        base_dir = utils_misc.get_path(data_dir.get_root_dir(),
                                       params.get("vm_type"))
        self.qemu_io_cmd = utils_misc.get_path(base_dir,
                                               params.get("qemu_io_binary",
                                                          "qemu-io"))
        self.io_options = io_options
        self.run_command = False
        self.image_name = image_name
        self.blkdebug_cfg = blkdebug_cfg
        self.log_func = log_func
开发者ID:FengYang,项目名称:virt-test,代码行数:25,代码来源:qemu_io.py


示例2: _store_vm_register

def _store_vm_register(test, params, env):
    global _vm_register_thread_termination_event
    delay = float(params.get("vm_register_delay", 5))
    counter = {}
    while True:
        for vm in env.get_all_vms():
            if not vm.is_alive():
                logging.warn("%s is not alive. Can not query the "
                             "register status" % vm.name)
                continue
            vm_pid = vm.get_pid()
            vr_dir = utils_misc.get_path(test.debugdir,
                                         "vm_register_%s_%s" % (vm.name,
                                                                vm_pid))
            try:
                os.makedirs(vr_dir)
            except OSError:
                pass

            if vm not in counter:
                counter[vm] = 1
            vr_filename = utils_misc.get_path(vr_dir, "%04d" % counter[vm])
            stored_log = store_vm_register(vm, vr_filename)
            if stored_log:
                counter[vm] += 1

        if _vm_register_thread_termination_event is not None:
            if _vm_register_thread_termination_event.isSet():
                _vm_register_thread_termination_event = None
                break
            _vm_register_thread_termination_event.wait(delay)
        else:
            # Exit event was deleted, exit this thread
            break
开发者ID:Guannan-Ren,项目名称:virt-test,代码行数:34,代码来源:env_process.py


示例3: _store_vm_register

def _store_vm_register(test, params, env):
    def report_result(status, results):
        msg = "%s." % status
        for vm_instance in results.keys():
            if results[vm_instance] > 0:
                msg += " Used to failed to get register info from guest"
                msg += " %s for %s times." % (vm_instance, results[vm_instance])

        if msg != "%s." % status:
            logging.debug(msg)

    global _vm_register_thread_termination_event
    delay = float(params.get("vm_register_delay", 5))
    counter = {}
    vm_register_error_count = {}
    while True:
        for vm in env.get_all_vms():
            if vm.instance not in vm_register_error_count:
                vm_register_error_count[vm.instance] = 0

            if not vm.is_alive():
                if vm_register_error_count[vm.instance] < 1:
                    logging.warn("%s is not alive. Can not query the "
                                 "register status" % vm.name)
                vm_register_error_count[vm.instance] += 1
                continue
            vm_pid = vm.get_pid()
            vr_dir = utils_misc.get_path(test.debugdir,
                                         "vm_register_%s_%s" % (vm.name,
                                                                vm_pid))
            try:
                os.makedirs(vr_dir)
            except OSError:
                pass

            if vm.instance not in counter:
                counter[vm.instance] = 1
            vr_filename = utils_misc.get_path(vr_dir, "%04d" % counter[vm.instance])
            stored_log = store_vm_register(vm, vr_filename)
            if vm_register_error_count[vm.instance] >= 1:
                logging.debug("%s alive now. Used to failed to get register"
                              " info from guest %s"
                              " times" % (vm.name,
                                          vm_register_error_count[vm.instance]))
                vm_register_error_count[vm.instance] = 0
            if stored_log:
                counter[vm.instance] += 1

        if _vm_register_thread_termination_event is not None:
            if _vm_register_thread_termination_event.isSet():
                _vm_register_thread_termination_event = None
                report_result("Thread quit", vm_register_error_count)
                break
            _vm_register_thread_termination_event.wait(delay)
        else:
            report_result("Thread quit", vm_register_error_count)
            # Exit event was deleted, exit this thread
            break
开发者ID:xiagao,项目名称:virt-test,代码行数:58,代码来源:env_process.py


示例4: verify_kernel_crash

    def verify_kernel_crash(self):
        """
        Find kernel crash message on the VM serial console.

        :raise: VMDeadKernelCrashError, in case a kernel crash message was
                found.
        """
        panic_re = [r"BUG:.*---\[ end trace .* \]---"]
        panic_re.append(r"----------\[ cut here.* BUG .*\[ end trace .* \]---")
        panic_re.append(r"general protection fault:.* RSP.*>")
        panic_re = "|".join(panic_re)
        if self.serial_console is not None:
            data = self.serial_console.get_output()
            match = re.search(panic_re, data, re.DOTALL | re.MULTILINE | re.I)
            if match is not None:
                raise VMDeadKernelCrashError(match.group(0))
        #For windows guest
        if self.params.get("check_guest_bsod", "no") == 'yes':
            try:
                scrdump_file = os.path.join("/tmp", "scrdump-img.ppm")
                ref_img_path = self.params.get("bsod_reference_img", "")
                bsod_base_dir = os.path.join(data_dir.get_deps_dir(),
                                             "bsod_img")
                ref_img = utils_misc.get_path(bsod_base_dir, ref_img_path)
                try:
                    self.screendump(filename=scrdump_file, debug=False)
                except Exception, err:
                    logging.warn("Cannot catch guest screendump, %s" % err)
                    pass
                if (os.path.exists(scrdump_file) and
                    ppm_utils.have_similar_img(scrdump_file, ref_img)):
                    err_msg = "Windows Guest appears to have suffered a BSOD,"
                    err_msg += " please check test video."
                    raise VMDeadKernelCrashError(err_msg)
            finally:
开发者ID:WenliQuan,项目名称:virt-test,代码行数:35,代码来源:virt_vm.py


示例5: __init__

    def __init__(self, params, root_dir, tag):
        """
        Init the default value for image object.

        @param params: Dictionary containing the test parameters.
        @param root_dir: Base directory for relative filenames.
        @param tag: Image tag defined in parameter images
        """
        storage.QemuImg.__init__(self, params, root_dir, tag)
        self.image_cmd = utils_misc.get_path(root_dir,
                                 params.get("qemu_img_binary","qemu-img"))
开发者ID:iwamatsu,项目名称:autotest,代码行数:11,代码来源:kvm_storage.py


示例6: verify_bsod

 def verify_bsod(self, scrdump_file):
     # For windows guest
     if (os.path.exists(scrdump_file) and
             self.params.get("check_guest_bsod", "no") == 'yes' and
             ppm_utils.Image is not None):
         ref_img_path = self.params.get("bsod_reference_img", "")
         bsod_base_dir = os.path.join(data_dir.get_root_dir(),
                                      "shared", "deps",
                                      "bsod_img")
         ref_img = utils_misc.get_path(bsod_base_dir, ref_img_path)
         if ppm_utils.have_similar_img(scrdump_file, ref_img):
             err_msg = "Windows Guest appears to have suffered a BSOD,"
             err_msg += " please check %s against %s." % (scrdump_file, ref_img)
             raise VMDeadKernelCrashError(err_msg)
开发者ID:cheliu,项目名称:virt-test,代码行数:14,代码来源:virt_vm.py


示例7: __init__

    def __init__(self, params, root_dir, tag):
        """
        Init the default value for image object.

        @param params: Dictionary containing the test parameters.
        @param root_dir: Base directory for relative filenames.
        @param tag: Image tag defined in parameter images
        """
        storage.QemuImg.__init__(self, params, root_dir, tag)
        # qemu img binary can be found in the test dir, not data_dir
        qemu_img_base_dir = os.path.join(data_dir.get_root_dir(),
                                         params.get("vm_type"))
        self.image_cmd = utils_misc.get_path(qemu_img_base_dir,
                                 params.get("qemu_img_binary","qemu-img"))
开发者ID:kmaehara,项目名称:virt-test,代码行数:14,代码来源:qemu_storage.py


示例8: get_image_filename

def get_image_filename(params, root_dir):
    """
    Generate an image path from params and root_dir.

    @param params: Dictionary containing the test parameters.
    @param root_dir: Base directory for relative filenames.

    @note: params should contain:
           image_name -- the name of the image file, without extension
           image_format -- the format of the image (qcow2, raw etc)
    @raise VMDeviceError: When no matching disk found (in indirect method).
    """
    image_name = params.get("image_name", "image")
    indirect_image_select = params.get("indirect_image_select")
    if indirect_image_select:
        re_name = image_name
        indirect_image_select = int(indirect_image_select)
        matching_images = utils.system_output("ls -1d %s" % re_name)
        matching_images = sorted(matching_images.split('\n'))
        if matching_images[-1] == '':
            matching_images = matching_images[:-1]
        try:
            image_name = matching_images[indirect_image_select]
        except IndexError:
            raise virt_vm.VMDeviceError("No matching disk found for "
                                        "name = '%s', matching = '%s' and "
                                        "selector = '%s'" %
                                        (re_name, matching_images,
                                         indirect_image_select))
        for protected in params.get('indirect_image_blacklist', '').split(' '):
            if re.match(protected, image_name):
                raise virt_vm.VMDeviceError("Matching disk is in blacklist. "
                                            "name = '%s', matching = '%s' and "
                                            "selector = '%s'" %
                                            (re_name, matching_images,
                                             indirect_image_select))
    image_format = params.get("image_format", "qcow2")
    if params.get("image_raw_device") == "yes":
        return image_name
    if image_format:
        image_filename = "%s.%s" % (image_name, image_format)
    else:
        image_filename = image_name
    image_filename = utils_misc.get_path(root_dir, image_filename)
    return image_filename
开发者ID:HeidCloud,项目名称:virt-test,代码行数:45,代码来源:storage.py


示例9: get_image_blkdebug_filename

def get_image_blkdebug_filename(params, root_dir):
    """
    Generate an blkdebug file path from params and root_dir.

    blkdebug files allow error injection in the block subsystem.

    :param params: Dictionary containing the test parameters.
    :param root_dir: Base directory for relative filenames.

    :note: params should contain:
           blkdebug -- the name of the debug file.
    """
    blkdebug_name = params.get("drive_blkdebug", None)
    if blkdebug_name is not None:
        blkdebug_filename = utils_misc.get_path(root_dir, blkdebug_name)
    else:
        blkdebug_filename = None
    return blkdebug_filename
开发者ID:Guannan-Ren,项目名称:virt-test,代码行数:18,代码来源:storage.py


示例10: check_disk_params

    def check_disk_params(self, params):
        """
        Check gathered info from qtree/block with params
        :param params: autotest params
        :return: number of errors
        """
        def check_drive_format(node, params):
            """ checks the drive format according to qtree info """
            expected = params.get('drive_format')
            if expected == 'scsi':
                if arch.ARCH == 'ppc64':
                    expected = 'spapr-vscsi'
                else:
                    expected = 'lsi53c895a'
            elif expected.startswith('scsi'):
                expected = params.get('scsi_hba', 'virtio-scsi-pci')
            elif expected.startswith('usb'):
                expected = 'usb-storage'
            try:
                if expected == 'virtio':
                    actual = node.qtree['type']
                else:
                    actual = node.parent.parent.qtree.get('type')
            except AttributeError:
                logging.error("Failed to check drive format, can't get parent"
                              "of:\n%s", node)
            if actual == 'virtio-scsi-device':  # new name for virtio-scsi
                actual = 'virtio-scsi-pci'
            if expected not in actual:
                return ("drive format in qemu is %s, in autotest %s"
                        % (actual, expected))

        err = 0
        disks = {}
        for disk in self.disks:
            if isinstance(disk, QtreeDisk):
                disks[disk.get_qname()] = (disk.get_params().copy(), disk)
        # We don't have the params name so we need to map file_names instead
        qname = None
        for name in params.objects('cdroms'):
            image_name = utils_misc.get_path(data_dir.get_data_dir(),
                                             params.object_params(name).get('cdrom', ''))
            image_name = os.path.realpath(image_name)
            for (qname, disk) in disks.iteritems():
                if disk[0].get('image_name') == image_name:
                    break
            else:
                continue    # Not /proc/scsi cdrom device
            disks.pop(qname)
        for name in params.objects('images'):
            current = None
            image_params = params.object_params(name)

            base_dir = image_params.get("images_base_dir",
                                        data_dir.get_data_dir())

            image_name = os.path.realpath(
                storage.get_image_filename(image_params,
                                           base_dir))
            for (qname, disk) in disks.iteritems():
                if disk[0].get('image_name') == image_name:
                    current = disk[0]
                    current_node = disk[1]
                    # autotest params might use relative path
                    current['image_name'] = image_params.get('image_name')
                    break
            if not current:
                logging.error("Disk %s is not in qtree but is in params.",
                              name)
                err += 1
                continue
            for prop in current.iterkeys():
                handled = False
                if prop == "drive_format":
                    out = check_drive_format(current_node, image_params)
                    if out:
                        logging.error("Disk %s %s", qname, out)
                        err += 1
                    handled = True
                elif (image_params.get(prop) and
                        image_params.get(prop) == current.get(prop)):
                    handled = True
                if not handled:
                    logging.error("Disk %s property %s=%s doesn't match params"
                                  " %s", qname, prop, current.get(prop),
                                  image_params.get(prop))
                    err += 1
            disks.pop(qname)
        if disks:
            logging.error('Some disks were in qtree but not in autotest params'
                          ': %s', disks)
            err += 1
        return err
开发者ID:ayiyaliing,项目名称:virt-test,代码行数:93,代码来源:qemu_qtree.py


示例11: get_image_filename_filesytem

def get_image_filename_filesytem(params, root_dir):
    """
    Generate an image path from params and root_dir.

    :param params: Dictionary containing the test parameters.
    :param root_dir: Base directory for relative filenames.

    :note: params should contain:
           image_name -- the name of the image file, without extension
           image_format -- the format of the image (qcow2, raw etc)
    :raise VMDeviceError: When no matching disk found (in indirect method).
    """
    def sort_cmp(first, second):
        """
        This function used for sort to suit for this test, first sort by len
        then by value.
        """
        first_contains_digit = re.findall(r'[vhs]d[a-z]*[\d]+', first)
        second_contains_digit = re.findall(r'[vhs]d[a-z]*[\d]+', second)

        if not first_contains_digit and not second_contains_digit:
            if len(first) > len(second):
                return 1
            elif len(first) < len(second):
                return -1
        if len(first) == len(second):
            if first_contains_digit and second_contains_digit:
                return cmp(first, second)
            elif first_contains_digit:
                return -1
            elif second_contains_digit:
                return 1
        return cmp(first, second)

    image_name = params.get("image_name", "image")
    indirect_image_select = params.get("indirect_image_select")
    if indirect_image_select:
        re_name = image_name
        indirect_image_select = int(indirect_image_select)
        matching_images = utils.system_output("ls -1d %s" % re_name)
        matching_images = sorted(matching_images.split('\n'), cmp=sort_cmp)
        if matching_images[-1] == '':
            matching_images = matching_images[:-1]
        try:
            image_name = matching_images[indirect_image_select]
        except IndexError:
            raise virt_vm.VMDeviceError("No matching disk found for "
                                        "name = '%s', matching = '%s' and "
                                        "selector = '%s'" %
                                        (re_name, matching_images,
                                         indirect_image_select))
        for protected in params.get('indirect_image_blacklist', '').split(' '):
            match_image = re.match(protected, image_name)
            if match_image and match_image.group(0) == image_name:
                # We just need raise an error if it is totally match, such as
                # sda sda1 and so on, but sdaa should not raise an error.
                raise virt_vm.VMDeviceError("Matching disk is in blacklist. "
                                            "name = '%s', matching = '%s' and "
                                            "selector = '%s'" %
                                            (re_name, matching_images,
                                             indirect_image_select))

    image_format = params.get("image_format", "qcow2")
    if params.get("image_raw_device") == "yes":
        return image_name
    if image_format:
        image_filename = "%s.%s" % (image_name, image_format)
    else:
        image_filename = image_name

    image_filename = utils_misc.get_path(root_dir, image_filename)
    return image_filename
开发者ID:Guannan-Ren,项目名称:virt-test,代码行数:72,代码来源:storage.py


示例12: backup_image

    def backup_image(self, params, root_dir, action, good=True,
                     skip_existing=False):
        """
        Backup or restore a disk image, depending on the action chosen.

        :param params: Dictionary containing the test parameters.
        :param root_dir: Base directory for relative filenames.
        :param action: Whether we want to backup or restore the image.
        :param good: If we are backing up a good image(we want to restore it)
            or a bad image (we are saving a bad image for posterior analysis).

        :note: params should contain:
               image_name -- the name of the image file, without extension
               image_format -- the format of the image (qcow2, raw etc)
        """
        def backup_raw_device(src, dst):
            if os.path.exists(src):
                utils.system("dd if=%s of=%s bs=4k conv=sync" % (src, dst))
            else:
                logging.info("No source %s, skipping dd...", src)

        def backup_image_file(src, dst):
            logging.debug("Copying %s -> %s", src, dst)
            if os.path.isfile(dst) and os.path.isfile(src):
                os.unlink(dst)
            if os.path.isfile(src):
                shutil.copy(src, dst)
            else:
                logging.info("No source file %s, skipping copy...", src)

        def get_backup_set(filename, backup_dir, action, good):
            """
            Get all sources and destinations required for each backup.
            """
            if not os.path.isdir(backup_dir):
                os.makedirs(backup_dir)
            basename = os.path.basename(filename)
            bkp_set = []
            if good:
                src = filename
                dst = os.path.join(backup_dir, "%s.backup" % basename)
                if action == 'backup':
                    bkp_set = [[src, dst]]
                elif action == 'restore':
                    bkp_set = [[dst, src]]
            else:
                # We have to make 2 backups, one of the bad image, another one
                # of the good image
                src_bad = filename
                src_good = os.path.join(backup_dir, "%s.backup" % basename)
                hsh = utils_misc.generate_random_string(4)
                dst_bad = (os.path.join(backup_dir, "%s.bad.%s" %
                                        (basename, hsh)))
                dst_good = (os.path.join(backup_dir, "%s.good.%s" %
                                         (basename, hsh)))
                if action == 'backup':
                    bkp_set = [[src_bad, dst_bad], [src_good, dst_good]]
                elif action == 'restore':
                    bkp_set = [[src_good, src_bad]]

            if not bkp_set:
                logging.error("No backup sets for action: %s, state: %s",
                              action, good)

            return bkp_set

        image_filename = self.image_filename
        backup_dir = params.get("backup_dir", "")
        if not os.path.isabs(backup_dir):
            backup_dir = os.path.join(root_dir, backup_dir)
        if params.get('image_raw_device') == 'yes':
            iname = "raw_device"
            iformat = params.get("image_format", "qcow2")
            ifilename = "%s.%s" % (iname, iformat)
            ifilename = utils_misc.get_path(root_dir, ifilename)
            backup_set = get_backup_set(ifilename, backup_dir, action, good)
            backup_func = backup_raw_device
        else:
            backup_set = get_backup_set(image_filename, backup_dir, action,
                                        good)
            backup_func = backup_image_file

        if action == 'backup':
            image_dir = os.path.dirname(image_filename)
            image_dir_disk_free = utils.freespace(image_dir)

            backup_size = 0
            for src, dst in backup_set:
                if os.path.isfile(src):
                    backup_size += os.path.getsize(src)

            minimum_disk_free = 1.2 * backup_size
            if image_dir_disk_free < minimum_disk_free:
                image_dir_disk_free_gb = float(image_dir_disk_free) / 10 ** 9
                backup_size_gb = float(backup_size) / 10 ** 9
                minimum_disk_free_gb = float(minimum_disk_free) / 10 ** 9
                logging.error("Free space on %s: %.1f GB", image_dir,
                              image_dir_disk_free_gb)
                logging.error("Backup size: %.1f GB", backup_size_gb)
                logging.error("Minimum free space acceptable: %.1f GB",
#.........这里部分代码省略.........
开发者ID:Guannan-Ren,项目名称:virt-test,代码行数:101,代码来源:storage.py


示例13: backup_image

    def backup_image(self, params, root_dir, action, good=True):
        """
        Backup or restore a disk image, depending on the action chosen.

        @param params: Dictionary containing the test parameters.
        @param root_dir: Base directory for relative filenames.
        @param action: Whether we want to backup or restore the image.
        @param good: If we are backing up a good image(we want to restore it)
            or a bad image (we are saving a bad image for posterior analysis).

        @note: params should contain:
               image_name -- the name of the image file, without extension
               image_format -- the format of the image (qcow2, raw etc)
        """
        def backup_raw_device(src, dst):
            utils.system("dd if=%s of=%s bs=4k conv=sync" % (src, dst))

        def backup_image_file(src, dst):
            logging.debug("Copying %s -> %s", src, dst)
            shutil.copy(src, dst)

        def get_backup_name(filename, backup_dir, good):
            if not os.path.isdir(backup_dir):
                os.makedirs(backup_dir)
            basename = os.path.basename(filename)
            if good:
                backup_filename = "%s.backup" % basename
            else:
                backup_filename = ("%s.bad.%s" %
                                   (basename,
                                    utils_misc.generate_random_string(4)))
            return os.path.join(backup_dir, backup_filename)


        image_filename = self.image_filename
        backup_dir = params.get("backup_dir")
        if params.get('image_raw_device') == 'yes':
            iname = "raw_device"
            iformat = params.get("image_format", "qcow2")
            ifilename = "%s.%s" % (iname, iformat)
            ifilename = utils_misc.get_path(root_dir, ifilename)
            image_filename_backup = get_backup_name(ifilename, backup_dir, good)
            backup_func = backup_raw_device
        else:
            image_filename_backup = get_backup_name(image_filename, backup_dir,
                                                    good)
            backup_func = backup_image_file

        if action == 'backup':
            image_dir = os.path.dirname(image_filename)
            image_dir_disk_free = utils.freespace(image_dir)
            image_filename_size = os.path.getsize(image_filename)
            image_filename_backup_size = 0
            if os.path.isfile(image_filename_backup):
                image_filename_backup_size = os.path.getsize(
                                                        image_filename_backup)
            disk_free = image_dir_disk_free + image_filename_backup_size
            minimum_disk_free = 1.2 * image_filename_size
            if disk_free < minimum_disk_free:
                image_dir_disk_free_gb = float(image_dir_disk_free) / 10**9
                minimum_disk_free_gb = float(minimum_disk_free) / 10**9
                logging.error("Dir %s has %.1f GB free, less than the minimum "
                              "required to store a backup, defined to be 120%% "
                              "of the backup size, %.1f GB. Skipping backup...",
                              image_dir, image_dir_disk_free_gb,
                              minimum_disk_free_gb)
                return
            if good:
                # In case of qemu-img check return 1, we will make 2 backups,
                # one for investigation and other, to use as a 'pristine'
                # image for further tests
                state = 'good'
            else:
                state = 'bad'
            logging.info("Backing up %s image file %s", state, image_filename)
            src, dst = image_filename, image_filename_backup
        elif action == 'restore':
            if not os.path.isfile(image_filename_backup):
                logging.error('Image backup %s not found, skipping restore...',
                              image_filename_backup)
                return
            logging.info("Restoring image file %s from backup",
                         image_filename)
            src, dst = image_filename_backup, image_filename

        backup_func(src, dst)
开发者ID:iwamatsu,项目名称:autotest,代码行数:86,代码来源:storage.py


示例14: _take_screendumps

def _take_screendumps(test, params, env):
    global _screendump_thread_termination_event
    temp_dir = test.debugdir
    if params.get("screendump_temp_dir"):
        temp_dir = utils_misc.get_path(test.bindir,
                                      params.get("screendump_temp_dir"))
        try:
            os.makedirs(temp_dir)
        except OSError:
            pass
    temp_filename = os.path.join(temp_dir, "scrdump-%s.ppm" %
                                 utils_misc.generate_random_string(6))
    delay = float(params.get("screendump_delay", 5))
    quality = int(params.get("screendump_quality", 30))

    cache = {}
    counter = {}

    while True:
        for vm in env.get_all_vms():
            if vm not in counter.keys():
                counter[vm] = 0
            if not vm.is_alive():
                continue
            try:
                vm.screendump(filename=temp_filename, debug=False)
            except kvm_monitor.MonitorError, e:
                logging.warn(e)
                continue
            except AttributeError, e:
                logging.warn(e)
                continue
            if not os.path.exists(temp_filename):
                logging.warn("VM '%s' failed to produce a screendump", vm.name)
                continue
            if not ppm_utils.image_verify_ppm_file(temp_filename):
                logging.warn("VM '%s' produced an invalid screendump", vm.name)
                os.unlink(temp_filename)
                continue
            screendump_dir = os.path.join(test.debugdir,
                                          "screendumps_%s" % vm.name)
            try:
                os.makedirs(screendump_dir)
            except OSError:
                pass
            counter[vm] += 1
            screendump_filename = os.path.join(screendump_dir, "%04d.jpg" %
                                               counter[vm])
            hsh = utils.hash_file(temp_filename)
            if hsh in cache:
                try:
                    os.link(cache[hsh], screendump_filename)
                except OSError:
                    pass
            else:
                try:
                    try:
                        image = PIL.Image.open(temp_filename)
                        image.save(screendump_filename, format="JPEG",
                                   quality=quality)
                        cache[hsh] = screendump_filename
                    except IOError, error_detail:
                        logging.warning("VM '%s' failed to produce a "
                                        "screendump: %s", vm.name, error_detail)
                        # Decrement the counter as we in fact failed to
                        # produce a converted screendump
                        counter[vm] -= 1
                except NameError:
                    pass
            os.unlink(temp_filename)
开发者ID:ddefolo,项目名称:autotest,代码行数:70,代码来源:env_process.py


示例15: check_disk_params

    def check_disk_params(self, params):
        """
        Check gathered info from qtree/block with params
        @param params: autotest params
        @return: number of errors
        """
        err = 0
        disks = {}
        for disk in self.disks:
            if isinstance(disk, QtreeDisk):
                disks[disk.get_qname()] = disk.get_params().copy()
        # We don't have the params name so we need to map file_names instead
        qname = None
        for name in params.objects('cdroms'):
            image_name = utils_misc.get_path(data_dir.get_data_dir(),
                                params.object_params(name).get('cdrom', ''))
            image_name = os.path.realpath(image_name)
            for (qname, disk) in disks.iteritems():
                if disk.get('image_name') == image_name:
                    break
            else:
                continue    # Not /proc/scsi cdrom device
            disks.pop(qname)
        for name in params.objects('images'):
            current = None
            image_params = params.object_params(name)

            base_dir = image_params.get("images_base_dir",
                                        data_dir.get_data_dir())

            image_name = os.path.realpath(
                        storage.get_image_filename(image_params,
                                                   base_dir))
            for (qname, disk) in disks.iteritems():
                if disk.get('image_name') == image_name:
                    current = disk
                    # autotest params might use relative path
                    current['image_name'] = image_params.get('image_name')
                    break
            if not current:
                logging.error("Disk %s is not in qtree but is in params.", name)
                err += 1
                continue
            for prop in current.iterkeys():
                handled = False
                if prop == "drive_format":
                    # HOOK: ahci disk is ide-* disk
                    if (image_params.get(prop) == 'ahci' and
                                current.get(prop).startswith('ide-')):
                        handled = True
                    # HOOK: params to qemu translation
                    elif current.get(prop).startswith(image_params.get(prop)):
                        handled = True
                elif (image_params.get(prop) and
                        image_params.get(prop) == current.get(prop)):
                    handled = True
                if not handled:
                    logging.error("Disk %s property %s=%s doesn't match params"
                                  " %s", qname, prop, current.get(prop),
                                  image_params.get(prop))
                    err += 1
            disks.pop(qname)
        if disks:
            logging.error('Some disks were in qtree but not in autotest params'
                          ': %s', disks)
            err += 1
        return err
开发者ID:QiuMike,项目名称:virt-test,代码行数:67,代码来源:qemu_qtree.py


示例16: preprocess


#.........这里部分代码省略.........
    requested_vms = params.objects("vms")
    for key in env.keys():
        vm = env[key]
        if not isinstance(vm, virt_vm.BaseVM):
            continue
        if not vm.name in requested_vms:
            vm.destroy()
            del env[key]

    # Get Host cpu type
    if params.get("auto_cpu_model") == "yes":
        if not env.get("cpu_model"):
            env["cpu_model"] = utils_misc.get_cpu_model()
        params["cpu_model"] = env.get("cpu_model")

    kvm_ver_cmd = params.get("kvm_ver_cmd", "")

    if kvm_ver_cmd:
        try:
            cmd_result = utils.run(kvm_ver_cmd)
            kvm_version = cmd_result.stdout.strip()
        except error.CmdError:
            kvm_version = "Unknown"
    else:
        # Get the KVM kernel module version and write it as a keyval
        if os.path.exists("/dev/kvm"):
            try:
                kvm_version = open("/sys/module/kvm/version").read().strip()
            except Exception:
                kvm_version = os.uname()[2]
        else:
            logging.warning("KVM module not loaded")
            kvm_version = "Unknown"

    logging.debug("KVM version: %s" % kvm_version)
    test.write_test_keyval({"kvm_version": kvm_version})

    # Get the KVM userspace version and write it as a keyval
    kvm_userspace_ver_cmd = params.get("kvm_userspace_ver_cmd", "")

    if kvm_userspace_ver_cmd:
        try:
            cmd_result = utils.run(kvm_userspace_ver_cmd)
            kvm_userspace_version = cmd_result.stdout.strip()
        except error.CmdError:
            kvm_userspace_version = "Unknown"
    else:
        qemu_path = utils_misc.get_path(test.bindir,
                                        params.get("qemu_binary", "qemu"))
        version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
        matches = re.findall("[Vv]ersion .*?,", version_line)
        if matches:
            kvm_userspace_version = " ".join(matches[0].split()[1:]).strip(",")
        else:
            kvm_userspace_version = "Unknown"

    logging.debug("KVM userspace version: %s" % kvm_userspace_version)
    test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})

    if params.get("setup_hugepages") == "yes":
        h = test_setup.HugePageConfig(params)
        h.setup()
        if params.get("vm_type") == "libvirt":
            libvirt_vm.libvirtd_restart()

    if params.get("setup_thp") == "yes":
        thp = test_setup.TransparentHugePageConfig(test, params)
        thp.setup()

    # Execute any pre_commands
    if params.get("pre_command"):
        process_command(test, params, env, params.get("pre_command"),
                        int(params.get("pre_command_timeout", "600")),
                        params.get("pre_command_noncritical") == "yes")

    #Clone master image from vms.
    base_dir = data_dir.get_data_dir()
    if params.get("master_images_clone"):
        for vm_name in params.get("vms").split():
            vm = env.get_vm(vm_name)
            if vm:
                vm.destroy(free_mac_addresses=False)
                env.unregister_vm(vm_name)

            vm_params = params.object_params(vm_name)
            for image in vm_params.get("master_images_clone").split():
                image_obj = qemu_storage.QemuImg(params, base_dir, image)
                image_obj.clone_image(params, vm_name, image, base_dir)

    # Preprocess all VMs and images
    if params.get("not_preprocess","no") == "no":
        process(test, params, env, preprocess_image, preprocess_vm)

    # Start the screendump thread
    if params.get("take_regular_screendumps") == "yes":
        global _screendump_thread, _screendump_thread_termination_event
        _screendump_thread_termination_event = threading.Event()
        _screendump_thread = threading.Thread(target=_take_screendumps,
                                              args=(test, params, env))
        _screendump_thread.start()
开发者ID:ehabkost,项目名称:virt-test,代码行数:101,代码来源:env_process.py


示例17: make_create_command


#.........这里部分代码省略.........
            else:
                result = ""
            if has_option(help_text, "bridge"):
                # older libvirt (--network=NATdev --bridge=bridgename --mac=mac)
                if nettype != "user":
                    result += ":%s" % netdst
                if mac:  # possible to specify --mac w/o --network
                    result += " --mac=%s" % mac
            else:
                # newer libvirt (--network=mynet,model=virtio,mac=00:11)
                if nettype != "user":
                    result += "=%s" % netdst
                if nettype and nic_model:  # only supported along with nettype
                    result += ",model= 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils_misc.wait_for函数代码示例发布时间:2022-05-26
下一篇:
Python utils_misc.generate_random_string函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap