1
# Copyright 2014-2015 Canonical Limited.
3
# This file is part of charm-helpers.
5
# charm-helpers is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Lesser General Public License version 3 as
7
# published by the Free Software Foundation.
9
# charm-helpers is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU Lesser General Public License for more details.
14
# You should have received a copy of the GNU Lesser General Public License
15
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
19
from subprocess import (
27
##################################################
28
# loopback device helpers.
29
##################################################
30
def loopback_devices():
32
Parse through 'losetup -a' output to determine currently mapped
33
loopback devices. Output is expected to look like:
35
/dev/loop0: [0807]:961814 (/tmp/my.img)
37
:returns: dict: a dict mapping {loopback_dev: backing_file}
40
cmd = ['losetup', '-a']
41
devs = [d.strip().split(' ') for d in
42
check_output(cmd).splitlines() if d != '']
43
for dev, _, f in devs:
44
loopbacks[dev.replace(':', '')] = re.search('\((\S+)\)', f).groups()[0]
48
def create_loopback(file_path):
50
Create a loopback device for a given backing file.
52
:returns: str: Full path to new loopback device (eg, /dev/loop0)
54
file_path = os.path.abspath(file_path)
55
check_call(['losetup', '--find', file_path])
56
for d, f in six.iteritems(loopback_devices()):
61
def ensure_loopback_device(path, size):
63
Ensure a loopback device exists for a given backing file path and size.
64
If it a loopback device is not mapped to file, a new one will be created.
66
TODO: Confirm size of found loopback device.
68
:returns: str: Full path to the ensured loopback device (eg, /dev/loop0)
70
for d, f in six.iteritems(loopback_devices()):
74
if not os.path.exists(path):
75
cmd = ['truncate', '--size', size, path]
78
return create_loopback(path)