Example #1
0
def get_free_loop_device(loop_device_major_number=7,
                         max_loop_devices_count=255):
    """Returns the name of free loop device.

    It should return the name of free loop device or raise an exception.
    Unfortunately, free loop device couldn't be reversed for the later usage,
    so we must start to use it as fast as we can.
    If there's no free loop it will try to create new one and ask a system for
    free loop again.
    """
    for minor in range(0, max_loop_devices_count):
        cur_loop = "/dev/loop%s" % minor
        if not os.path.exists(cur_loop):
            os.mknod(cur_loop, 0o660 | stat.S_IFBLK,
                     os.makedev(loop_device_major_number, minor))
        try:
            return utils.execute('losetup', '--find')[0].split()[0]
        except (IndexError, errors.ProcessExecutionError):
            LOG.debug("Couldn't find free loop device, trying again")
    raise errors.NoFreeLoopDevices('Free loop device not found')
Example #2
0
def attach_file_to_free_loop_device(filename,
                                    max_loop_devices_count=255,
                                    loop_device_major_number=7,
                                    max_attempts=1):
    """Find free loop device and try to attach `filename` to it.

    If attaching fails then retry again. Max allowed attempts is
    `max_attempts`.

    Returns loop device to which file is attached. Otherwise, raises
    errors.NoFreeLoopDevices.
    """
    loop_device = None
    for i in range(0, max_attempts):
        try:
            LOG.debug('Looking for a free loop device')
            loop_device = get_free_loop_device(
                loop_device_major_number=loop_device_major_number,
                max_loop_devices_count=max_loop_devices_count)

            log_msg = "Attaching image file '{0}' to free loop device '{1}'"
            LOG.debug(log_msg.format(filename, loop_device))
            attach_file_to_loop(filename, loop_device)
            break
        except errors.ProcessExecutionError:
            log_msg = "Couldn't attach image file '{0}' to loop device '{1}'."
            LOG.debug(log_msg.format(filename, loop_device))

            if i == max_attempts - 1:
                log_msg = ("Maximum allowed attempts ({0}) to attach image "
                           "file '{1}' to loop device '{2}' is exceeded.")
                LOG.debug(log_msg.format(max_attempts, filename, loop_device))
                raise errors.NoFreeLoopDevices('Free loop device not found.')
            else:
                log_msg = ("Trying again to attach image file '{0}' "
                           "to free loop device '{1}'. "
                           "Attempt #{2} out of {3}")
                LOG.debug(
                    log_msg.format(filename, loop_device, i + 1, max_attempts))

    return loop_device