5
from subprocess import (
11
##################################################
12
# loopback device helpers.
13
##################################################
14
def loopback_devices():
16
Parse through 'losetup -a' output to determine currently mapped
17
loopback devices. Output is expected to look like:
19
/dev/loop0: [0807]:961814 (/tmp/my.img)
21
:returns: dict: a dict mapping {loopback_dev: backing_file}
24
cmd = ['losetup', '-a']
25
devs = [d.strip().split(' ') for d in
26
check_output(cmd).splitlines() if d != '']
27
for dev, _, f in devs:
28
loopbacks[dev.replace(':', '')] = re.search('\((\S+)\)', f).groups()[0]
32
def create_loopback(file_path):
34
Create a loopback device for a given backing file.
36
:returns: str: Full path to new loopback device (eg, /dev/loop0)
38
file_path = os.path.abspath(file_path)
39
check_call(['losetup', '--find', file_path])
40
for d, f in loopback_devices().iteritems():
45
def ensure_loopback_device(path, size):
47
Ensure a loopback device exists for a given backing file path and size.
48
If it a loopback device is not mapped to file, a new one will be created.
50
TODO: Confirm size of found loopback device.
52
:returns: str: Full path to the ensured loopback device (eg, /dev/loop0)
54
for d, f in loopback_devices().iteritems():
58
if not os.path.exists(path):
59
cmd = ['truncate', '--size', size, path]
62
return create_loopback(path)