Source

vinstall / vinstall / backend / media.py

  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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/bin/env python

"""Media handling. Implements objects providing methods
for mounting, umounting, formating and querying media.

"""

__author__ = "rbistolfi"


import re
import os
import parted
from vinstall.backend import sp
from utils import mountiso, mount, umount, is_mounted, format_partition
from _ped import DiskLabelException


DEV_DIR = '/dev'
CD_INFO = '/proc/sys/dev/cdrom/info'
PARTITIONS = '/proc/partitions'
ISO_MOUNTPOINT = "/tmp/ISOMNT"


class StorageDevice(object):
    """Base class for Storage Devices
    
    """
    def size(self, unit="GB"):
        """ Returns size, by default in GB, unit can be GB or MB

        """
        return NotImplemented

    def path(self):
        """Return the node path for this device
        
        """
        return NotImplemented

    def is_read_only(self):
        """Return True if the device is read-only
        
        """
        return NotImplemented


class MountMixin(object):
    """Mixin for devices that can be mounted
    
    """
    @property
    def mountpoint(self):
        """Return actual mountpoint if device is mounted. If its not mounted,
        create a mountpoint from the device path. Wrapped in a property for API
        compatibility.
        
        """
        if self.is_mounted():
            for line in open("/proc/mounts"):
                device, mountpoint, _ = line.split(" ", 2)
                if device == self.device_path:
                    break
            else:
                err = "Couldn't find mountpoint for %s" % self.device_path
                raise RuntimeError(err)
            return mountpoint
        else:
            mntpoint =  self.device_path.replace("/dev", "/mnt")
            if not os.path.exists(mntpoint):
                os.mkdir(mntpoint)
            return mntpoint
 
    def mount(self, mountpoint=None, filesystem="auto"):
        """Mount the media in the specified mountpoint.
        
        """
        if mountpoint is None:
            mountpoint = self.mountpoint
        return mount(self.device_path, mountpoint, filesystem=filesystem)

    def umount(self):
        """Umount the media.
        
        """
        return umount(self.mountpoint)

    def is_mounted(self):
        """Returns True if the media is mounted, False otherwise.
        
        """
        return is_mounted(self.device_path)


class FormatMixin(object):
    """Mixin for devices that can be formated
    
    """
    def query_filesystem(self):
        """Retrieve the current filesystem type from the system.

        """
        try:
            pfs = self._parted_partition.fileSystem.type
        except AttributeError:
            # partition has no format
            pfs = ""
        if "swap" in pfs:
            pfs = "swap"
        return pfs

    def format(self, filesystem):
        """Create a filesystem in this partition.

        """
        format_partition(self.device_path, filesystem)


class Partition(StorageDevice, MountMixin, FormatMixin):
    """A class representing a partition in a hard disk.

    """
    def __str__(self):
        if self.query_filesystem():
            filesystem = self.query_filesystem()
        else:
            filesystem = "Not formated"
        return '%s (%s %s)' % (self.device_path, self.size("GB"), filesystem)

    def __repr__(self):
        return '<Partition %s>' % self.device_path

    def __init__(self, device_path):
        """Initializes a Media object from the device path.
        
        """
        self.device_path = device_path

    def size(self, unit="GB"):
        """Return the partition size in the specified unit as a string.
        Defaults to GB

        """
        try:
            s = self._parted_partition.getSize(unit)
        except AttributeError:
            s = self._parted_partition.getLength(unit)
        return Size(s, unit) 

    def path(self):
        """Return the device path (only for interface compatibility with
        Disk)

        """
        return self.device_path

    @classmethod
    def all(cls):
        """Return all the partitions in the system

        """
        disks = [ i for i in Disk.all() if i.has_partition_table() ]
        partitions = []
        for dsk in disks:
            partitions.extend(dsk._disk.partitions)

        for part in partitions:
            if part.type in (parted.PARTITION_NORMAL,
                             parted.PARTITION_LOGICAL,):
                p = cls(part.path)
                p._parted_partition = part
                yield p


class CDRom(StorageDevice, MountMixin):
    """API for operating on CDROM devices

    """
    def __init__(self, device_path):
        super(CDRom, self).__init__()
        self.device_path = device_path
        self.is_cdrom = True
        self.is_disk = False
        self.is_iso = False
        
    def is_read_only(self):
        return True
    
    def path(self):
        # api compat
        return self.device_path

    @classmethod
    def all(cls):
        devices = list_cdroms()
        for dev in devices:
            yield cls(dev)


class ISOFile(StorageDevice, MountMixin):
    """API for operations with ISO files.

    """
    def __repr__(self):
        return "<ISOFile %s>" % self.path()
        
    def __init__(self, path):
        super(ISOFile, self).__init__()
        self.device_path = path
        self.is_iso = True
        self.is_cdrom = False
        self.is_disk = False

    def path(self):
        # API compat
        return self.device_path

    def is_read_only(self):
        return True

    @property
    def mountpoint(self):
        # API compat
        return ISO_MOUNTPOINT

    def mount(self, mountpoint=None):
        """Mount ISO in a loop device

        """
        if mountpoint is None:
            mountpoint = self.mountpoint
        return mountiso(self.path(), mountpoint)

    @classmethod
    def all(cls, root_dir):
        for f in os.listdir(root_dir):
            path = os.path.join(root_dir, f)
            if os.path.isfile(path) and f.endswith(".iso"):
                yield cls(path)


class Disk(StorageDevice, MountMixin, FormatMixin):
    """Disk objects provide access to hard disk devices

    """
    def __init__(self, device_path):
        super(Disk, self).__init__()
        self.device_path = device_path
        self._device = None
        self._disk = None
        self.is_cdrom = False
        self.is_disk = True
        self.is_iso = False
        
    def __repr__(self):

        return "<Disk %s>" % self.path()

    def __str__(self):

        return "%s - %s (%s)" % (self.model(), self.size(), self.path())

    def model(self):
        """Return the string describing the device model"""
        return self._device.model

    def path(self):
        self.device_path = self._device.path
        return self._device.path

    def size(self, unit="GB"):
        """ Returns size, by default in GB, unit can be GB or MB

        """
        # fix parted api change
        try:
            s = self._device.getSize(unit)
        except AttributeError:
            s = self._device.getLength(unit)
        return Size(s, unit)

    def is_read_only(self):
        return False

    def has_partition_table(self):
        """Return True if the disk has a partition table.  False otherwise

        """
        return self._disk is not None

    def partitions(self):
        """Return iterable with partitions from this disk

        """
        for part in self._disk.partitions:
            if part.type in (parted.PARTITION_NORMAL,
                             parted.PARTITION_LOGICAL,):
                p = Partition(part.path)
                p._parted_partition = part
                yield p

    @classmethod
    def all(cls):
        devices = ( dev for dev in parted.getAllDevices() if dev.readOnly is False )
        if not devices:
            raise RuntimeError("No hard drives found")
        for dev in devices:
            disk = cls(dev.path)
            disk._device = dev
            try:
                disk._disk = parted.Disk(dev)
            except DiskLabelException, e:
                #print "%s Has no partion table. Cannot read partitions" % disk
                pass
            yield disk


class Size(object):
    """Size objects provide an API for handling storage device sizes.
    They can be part of arithmetic operations (either with other Size
    instances or with other numeric types) and can be compared (also
    with other Size instances or numeric types.) Size instances holding
    values in different units can be compared safely, but arithmetic
    operations require the same unit for both objects.
    While doing arihmetic, keep in mind that values are stored internally
    as floats by default.

    """
    units = {
        "B":   1,
        "KB":  1000,
        "MB":  1000**2,
        "GB":  1000**3,
        "KiB": 1024,
        "MiB": 1024**2,
        "GiB": 1024**3
    }

    n_type = float

    def __repr__(self):
        return "<Size %s %s>" % (self.n, self.unit)

    def __str__(self):
        return "%s %s" % (round(self.n, 2), self.unit)
        
    def __init__(self, n, unit="GB"):
        self.unit = unit
        self.n = self.n_type(n)

    def __add__(self, other):
        if isinstance(other, Size):
            if self.unit != other.unit:
                return NotImplemented
            n = other.n
        else:
            selfn = self.n
            n = other
            return self.__class__(selfn + n, self.unit)

    def __mul__(self, other):
        if isinstance(other, Size):
            if self.unit != other.unit:
                return NotImplemented
            n = other.n
        else:
            n = other
        return self.__class__(self.n * n, self.unit)

    def __div__(self, other):
        if isinstance(other, Size):
            if self.unit != other.unit:
                return NotImplemented
            n = other.n
        else:
            n = other
        return self.__class__(self.n / n, self.unit)
        
    def __lt__(self, other):
        if isinstance(other, Size):
            selfn = self.to("B").n
            n = other.to("B").n
            return selfn < n
        return self.n < other

    def __gt__(self, other):
        if isinstance(other, Size):
            selfn = self.to("B").n
            n = other.to("B").n
            return selfn > n
        return self.n > other

    def __eq__(self, other):
        if isinstance(other, Size):
            selfn = self.to("B").n
            n = other.to("B").n
            return selfn == n
        return self.n == other

    def __float__(self):
        return float(self.n)

    def __int__(self):
        return int(self.n)

    def to(self, unit):
        """Convert this value to another unit.
        Unit can be one of 'B', 'KB', 'MB', 'KiB', 'MiB' or 'GiB'

        """
        n = self.n * self.units[self.unit] / self.units[unit]
        return self.__class__(n, unit)


def list_cdroms(proc_info=CD_INFO):
    """Find CDROM devices based in the information stored in the proc tree.

    """
    with open(proc_info) as file_handler:
        cdroms = re.findall(r'([hs]d[a-z]|s[rg]\d*)', file_handler.read(), re.M)
    return ( os.path.join("/dev", i) for i in cdroms )


def list_swap():
    """Returns a list of swap devices.

    """
    swaps = []
    for i in Partition.all():
        data = sp.check_output(['blkid', i.path()])
        if "swap" in data:
            swaps.append(i.path())
    return swaps