summaryrefslogtreecommitdiffstats
path: root/storage/udev.py
blob: 450b54aa62b94714b98ec6276d211006e56f2e03 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# udev.py
# Python module for querying the udev database for device information.
#
# Copyright (C) 2009  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Dave Lehman <dlehman@redhat.com>
#

import os
import stat

import iutil
from errors import *
from baseudev import *

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

def udev_resolve_devspec(devspec):
    if not devspec:
        return None

    import devices as _devices
    ret = None
    for dev in udev_get_block_devices():
        if devspec.startswith("LABEL="):
            if udev_device_get_label(dev) == devspec[6:]:
                ret = dev
                break
        elif devspec.startswith("UUID="):
            if udev_device_get_uuid(dev) == devspec[5:]:
                ret = dev
                break
        else:
            if udev_device_get_name(dev) == _devices.devicePathToName(devspec):
                ret = dev
                break

    del _devices
    if ret:
        return udev_device_get_name(dev)

def udev_get_block_devices():
    udev_settle(timeout=30)
    entries = []
    for path in udev_enumerate_block_devices():
        entry = udev_get_block_device(path)
        if entry:
            entries.append(entry)
    return entries

def __is_blacklisted_blockdev(dev_name):
    """Is this a blockdev we never want for an install?"""
    if dev_name.startswith("loop") or dev_name.startswith("ram") or dev_name.startswith("fd"):
        return True
    # FIXME: the backing dev for the live image can't be used as an
    # install target.  note that this is a little bit of a hack 
    # since we're assuming that /dev/live will exist
    if os.path.exists("/dev/live") and \
            stat.S_ISBLK(os.stat("/dev/live")[stat.ST_MODE]):
        livetarget = os.path.realpath("/dev/live")
        if livetarget.startswith("/dev"):
            livetarget = livetarget[5:]
        if livetarget.startswith(dev_name):
            log.info("%s looks to be the live device; ignoring" % (dev_name,))
            return True

    if os.path.exists("/sys/class/block/%s/device/model" %(dev_name,)):
        model = open("/sys/class/block/%s/device/model" %(dev_name,)).read()
        for bad in ("IBM *STMF KERNEL", "SCEI Flash-5", "DGC LUNZ"):
            if model.find(bad) != -1:
                log.info("ignoring %s with model %s" %(dev_name, model))
                return True

    return False

def udev_enumerate_block_devices():
    import os.path

    return filter(lambda d: not __is_blacklisted_blockdev(os.path.basename(d)),
                  udev_enumerate_devices(deviceClass="block"))

def udev_get_block_device(sysfs_path):
    dev = udev_get_device(sysfs_path)
    if not dev or not dev.has_key("name"):
        return {"name": None, "symlinks": []}
    else:
        return dev

def udev_parse_block_entry(buf):
    dev = udev_parse_entry(buf)

    for (key, value) in dev.iteritems():
        if value.count(" "):
            # eg: DEVLINKS
            dev.update({key: value.split()})

    return dev


# These are functions for retrieving specific pieces of information from
# udev database entries.
def udev_device_get_name(udev_info):
    """ Return the best name for a device based on the udev db data. """
    return udev_info.get("DM_NAME", udev_info["name"])

def udev_device_get_format(udev_info):
    """ Return a device's format type as reported by udev. """
    return udev_info.get("ID_FS_TYPE")

def udev_device_get_uuid(udev_info):
    """ Get the UUID from the device's format as reported by udev. """
    md_uuid = udev_info.get("MD_UUID")
    uuid = udev_info.get("ID_FS_UUID")
    # we don't want to return the array's uuid as a member's uuid
    if uuid and not md_uuid == uuid:
        return udev_info.get("ID_FS_UUID")

def udev_device_get_label(udev_info):
    """ Get the label from the device's format as reported by udev. """
    return udev_info.get("ID_FS_LABEL")

def udev_device_is_dm(info):
    """ Return True if the device is a device-mapper device. """
    return info.has_key("DM_NAME")

def udev_device_is_md(info):
    """ Return True if the device is a mdraid array device. """
    return info.has_key("MD_DEVNAME") and \
           info.has_key("MD_METADATA")

def udev_device_is_cdrom(info):
    """ Return True if the device is an optical drive. """
    # FIXME: how can we differentiate USB drives from CD-ROM drives?
    #         -- USB drives also generate a sdX device.
    return info.get("ID_CDROM") == "1"

def udev_device_is_disk(info):
    """ Return True is the device is a disk. """
    has_range = os.path.exists("/sys/%s/range" % info['sysfs_path'])
    return info.get("DEVTYPE") == "disk" or has_range

def udev_device_is_partition(info):
    has_start = os.path.exists("/sys/%s/start" % info['sysfs_path'])
    return info.get("DEVTYPE") == "partition" or has_start

def udev_device_get_sysfs_path(info):
    return info['sysfs_path']

def udev_device_get_major(info):
    return int(info["MAJOR"])

def udev_device_get_minor(info):
    return int(info["MINOR"])

def udev_device_get_md_level(info):
    return info["MD_LEVEL"]

def udev_device_get_md_devices(info):
    return int(info["MD_DEVICES"])

def udev_device_get_md_uuid(info):
    return info["MD_UUID"]

def udev_device_get_vg_name(info):
    return info['LVM2_VG_NAME']

def udev_device_get_vg_uuid(info):
    return info['LVM2_VG_UUID']

def udev_device_get_vg_size(info):
    # lvm's decmial precision is not configurable, so we tell it to use
    # KB and convert to MB here
    return float(info['LVM2_VG_SIZE']) / 1024

def udev_device_get_vg_free(info):
    # lvm's decmial precision is not configurable, so we tell it to use
    # KB and convert to MB here
    return float(info['LVM2_VG_FREE']) / 1024

def udev_device_get_vg_extent_size(info):
    # lvm's decmial precision is not configurable, so we tell it to use
    # KB and convert to MB here
    return float(info['LVM2_VG_EXTENT_SIZE']) / 1024

def udev_device_get_vg_extent_count(info):
    return int(info['LVM2_VG_EXTENT_COUNT'])

def udev_device_get_vg_free_extents(info):
    return int(info['LVM2_VG_FREE_COUNT'])

def udev_device_get_vg_pv_count(info):
    return int(info['LVM2_PV_COUNT'])

def udev_device_get_pv_pe_start(info):
    # lvm's decmial precision is not configurable, so we tell it to use
    # KB and convert to MB here
    return float(info['LVM2_PE_START']) / 1024

def udev_device_get_lv_names(info):
    names = info['LVM2_LV_NAME']
    if not names:
        names = []
    elif not isinstance(names, list):
        names = [names]
    return names

def udev_device_get_lv_uuids(info):
    uuids = info['LVM2_LV_UUID']
    if not uuids:
        uuids = []
    elif not isinstance(uuids, list):
        uuids = [uuids]
    return uuids

def udev_device_get_lv_sizes(info):
    # lvm's decmial precision is not configurable, so we tell it to use
    # KB and convert to MB here
    sizes = info['LVM2_LV_SIZE']
    if not sizes:
        sizes = []
    elif not isinstance(sizes, list):
        sizes = [sizes]

    return [float(s) / 1024 for s in sizes]

def udev_device_is_biosraid(info):
    # Note that this function does *not* identify raid sets.
    # Tests to see if device is parto of a dmraid set.
    # dmraid and mdraid have the same ID_FS_USAGE string, ID_FS_TYPE has a
    # string that describes the type of dmraid (isw_raid_member...),  I don't
    # want to maintain a list and mdraid's ID_FS_TYPE='linux_raid_member', so
    # dmraid will be everything that is raid and not linux_raid_member
    from formats.dmraid import DMRaidMember
    from formats.mdraid import MDRaidMember
    if info.has_key("ID_FS_TYPE") and \
            (info["ID_FS_TYPE"] in DMRaidMember._udevTypes or \
             info["ID_FS_TYPE"] in MDRaidMember._udevTypes) and \
            info["ID_FS_TYPE"] != "linux_raid_member":
        return True

    return False

def udev_device_get_dmraid_partition_disk(info):
    try:
        p_index = info["DM_NAME"].rindex("p")
    except (KeyError, AttributeError, ValueError):
        return None

    if not info["DM_NAME"][p_index+1:].isdigit():
        return None

    return info["DM_NAME"][:p_index]

def udev_device_is_dmraid_partition(info, devicetree):
    diskname = udev_device_get_dmraid_partition_disk(info)
    dmraid_devices = devicetree.getDevicesByType("dm-raid array")

    for device in dmraid_devices:
        if diskname == device.name:
            return True

    return False

# iscsi disks have ID_PATH in the form of:
# ip-${iscsi_address}:${iscsi_port}-iscsi-${iscsi_tgtname}-lun-${lun}
def udev_device_is_iscsi(info):
    try:
        path_components = info["ID_PATH"].split("-")

        if info["ID_BUS"] == "scsi" and len(path_components) >= 6 and \
           path_components[0] == "ip" and path_components[2] == "iscsi":
            return True
    except KeyError:
        pass

    return False

def udev_device_get_iscsi_name(info):
    path_components = info["ID_PATH"].split("-")

    # Tricky, the name itself contains atleast 1 - char
    return "-".join(path_components[3:len(path_components)-2])

def udev_device_get_iscsi_address(info):
    path_components = info["ID_PATH"].split("-")

    return path_components[1].split(":")[0]

def udev_device_get_iscsi_port(info):
    path_components = info["ID_PATH"].split("-")

    return path_components[1].split(":")[1]

# fcoe disks have ID_PATH in the form of:
# pci-eth#-fc-${id}
# fcoe parts look like this:
# pci-eth#-fc-${id}-part#
def udev_device_is_fcoe(info):
    try:
        path_components = info["ID_PATH"].split("-")

        if info["ID_BUS"] == "scsi" and len(path_components) >= 4 and \
           path_components[0] == "pci" and path_components[2] == "fc" and \
           path_components[1][0:3] == "eth":
            return True
    except LookupError:
        pass

    return False

def udev_device_get_fcoe_nic(info):
    path_components = info["ID_PATH"].split("-")

    return path_components[1]

def udev_device_get_fcoe_identifier(info):
    path_components = info["ID_PATH"].split("-")

    return path_components[3]