summaryrefslogtreecommitdiffstats
path: root/pyanaconda/storage/devicelibs/loop.py
blob: 8a4750cce167b93c7ce6c118e67d8bb526a5476b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#
# loop.py
# loop device functions
#
# Copyright (C) 2010  Red Hat, Inc.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): David Lehman <dlehman@redhat.com>
#

import os

from .. import util
from ..errors import *

import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)

import logging
log = logging.getLogger("storage")


def losetup(args, capture=False):
    if capture:
        exec_func = util.capture_output
    else:
        exec_func = util.run_program

    try:
        # ask losetup what this loop device's backing device is
        ret = exec_func(["losetup"] + args)
    except OSError as e:
        raise LoopError(e.strerror)

    return ret

def get_backing_file(name):
    path = ""
    sys_path  = "/sys/class/block/%s/loop/backing_file" % name
    if os.access(sys_path, os.R_OK):
        path = open(sys_path).read().strip()

    return path

def get_loop_name(path):
    args = ["-j", path]
    buf = losetup(args, capture=True)
    if len(buf.splitlines()) > 1:
        # there should never be more than one loop device listed
        raise LoopError("multiple loops associated with %s" % path)

    name = os.path.basename(buf.split(":")[0])
    return name

def loop_setup(path):
    args = ["-f", path]
    msg = None
    try:
        msg = losetup(args)
    except LoopError as e:
        msg = str(e)

    if msg:
        raise LoopError("failed to set up loop for %s: %s" % (path, msg))

def loop_teardown(path):
    args = ["-d", path]
    msg = None
    try:
        msg = losetup(args)
    except LoopError as e:
        msg = str(e)

    if msg:
        raise DeviceError("failed to tear down loop %s: %s" % (path, msg))