| 1 |
# vim: set ft=python ts=4 sw=4 expandtab: |
| 2 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 3 |
# |
| 4 |
# C E D A R |
| 5 |
# S O L U T I O N S "Software done right." |
| 6 |
# S O F T W A R E |
| 7 |
# |
| 8 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 9 |
# |
| 10 |
# Copyright (c) 2004-2008,2010,2015 Kenneth J. Pronovici. |
| 11 |
# All rights reserved. |
| 12 |
# |
| 13 |
# This program is free software; you can redistribute it and/or |
| 14 |
# modify it under the terms of the GNU General Public License, |
| 15 |
# Version 2, as published by the Free Software Foundation. |
| 16 |
# |
| 17 |
# This program is distributed in the hope that it will be useful, |
| 18 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 19 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 20 |
# |
| 21 |
# Copies of the GNU General Public License are available from |
| 22 |
# the Free Software Foundation website, http://www.gnu.org/. |
| 23 |
# |
| 24 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 25 |
# |
| 26 |
# Author : Kenneth J. Pronovici <[email protected]> |
| 27 |
# Language : Python 3 |
| 28 |
# Project : Cedar Backup, release 3 |
| 29 |
# Purpose : Provides functionality related to CD writer devices. |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Module documentation |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Provides functionality related to CD writer devices. |
| 39 |
|
| 40 |
Module Attributes |
| 41 |
================= |
| 42 |
|
| 43 |
Attributes: |
| 44 |
MEDIA_CDRW_74: Constant representing 74-minute CD-RW media |
| 45 |
MEDIA_CDR_74: Constant representing 74-minute CD-R media |
| 46 |
MEDIA_CDRW_80: Constant representing 80-minute CD-RW media |
| 47 |
MEDIA_CDR_80: Constant representing 80-minute CD-R media |
| 48 |
|
| 49 |
:author: Kenneth J. Pronovici <[email protected]> |
| 50 |
""" |
| 51 |
|
| 52 |
######################################################################## |
| 53 |
# Imported modules |
| 54 |
######################################################################## |
| 55 |
|
| 56 |
import logging |
| 57 |
import os |
| 58 |
import posixpath |
| 59 |
import re |
| 60 |
import tempfile |
| 61 |
import time |
| 62 |
|
| 63 |
from CedarBackup3.util import ( |
| 64 |
UNIT_BYTES, |
| 65 |
UNIT_KBYTES, |
| 66 |
UNIT_MBYTES, |
| 67 |
UNIT_SECTORS, |
| 68 |
convertSize, |
| 69 |
displayBytes, |
| 70 |
encodePath, |
| 71 |
executeCommand, |
| 72 |
resolveCommand, |
| 73 |
) |
| 74 |
from CedarBackup3.writers.util import IsoImage, validateDevice, validateDriveSpeed, validateScsiId |
| 75 |
|
| 76 |
######################################################################## |
| 77 |
# Module-wide constants and variables |
| 78 |
######################################################################## |
| 79 |
|
| 80 |
logger = logging.getLogger("CedarBackup3.log.writers.cdwriter") |
| 81 |
|
| 82 |
MEDIA_CDRW_74 = 1 |
| 83 |
MEDIA_CDR_74 = 2 |
| 84 |
MEDIA_CDRW_80 = 3 |
| 85 |
MEDIA_CDR_80 = 4 |
| 86 |
|
| 87 |
CDRECORD_COMMAND = ["cdrecord"] |
| 88 |
EJECT_COMMAND = ["eject"] |
| 89 |
MKISOFS_COMMAND = ["mkisofs"] |
| 90 |
|
| 91 |
|
| 92 |
######################################################################## |
| 93 |
# MediaDefinition class definition |
| 94 |
######################################################################## |
| 95 |
|
| 96 |
|
| 97 |
class MediaDefinition: |
| 98 |
""" |
| 99 |
Class encapsulating information about CD media definitions. |
| 100 |
|
| 101 |
The following media types are accepted: |
| 102 |
|
| 103 |
- ``MEDIA_CDR_74``: 74-minute CD-R media (650 MB capacity) |
| 104 |
- ``MEDIA_CDRW_74``: 74-minute CD-RW media (650 MB capacity) |
| 105 |
- ``MEDIA_CDR_80``: 80-minute CD-R media (700 MB capacity) |
| 106 |
- ``MEDIA_CDRW_80``: 80-minute CD-RW media (700 MB capacity) |
| 107 |
|
| 108 |
Note that all of the capacities associated with a media definition are in |
| 109 |
terms of ISO sectors (``util.ISO_SECTOR_SIZE)``. |
| 110 |
|
| 111 |
""" |
| 112 |
|
| 113 |
def __init__(self, mediaType): |
| 114 |
""" |
| 115 |
Creates a media definition for the indicated media type. |
| 116 |
Args: |
| 117 |
mediaType: Type of the media, as discussed above |
| 118 |
Raises: |
| 119 |
ValueError: If the media type is unknown or unsupported |
| 120 |
""" |
| 121 |
self._mediaType = None |
| 122 |
self._rewritable = False |
| 123 |
self._initialLeadIn = 0.0 |
| 124 |
self._leadIn = 0.0 |
| 125 |
self._capacity = 0.0 |
| 126 |
self._setValues(mediaType) |
| 127 |
|
| 128 |
def _setValues(self, mediaType): |
| 129 |
""" |
| 130 |
Sets values based on media type. |
| 131 |
Args: |
| 132 |
mediaType: Type of the media, as discussed above |
| 133 |
Raises: |
| 134 |
ValueError: If the media type is unknown or unsupported |
| 135 |
""" |
| 136 |
if mediaType not in [MEDIA_CDR_74, MEDIA_CDRW_74, MEDIA_CDR_80, MEDIA_CDRW_80]: |
| 137 |
raise ValueError("Invalid media type %d." % mediaType) |
| 138 |
self._mediaType = mediaType |
| 139 |
self._initialLeadIn = 11400.0 # per cdrecord's documentation |
| 140 |
self._leadIn = 6900.0 # per cdrecord's documentation |
| 141 |
if self._mediaType == MEDIA_CDR_74: |
| 142 |
self._rewritable = False |
| 143 |
self._capacity = convertSize(650.0, UNIT_MBYTES, UNIT_SECTORS) |
| 144 |
elif self._mediaType == MEDIA_CDRW_74: |
| 145 |
self._rewritable = True |
| 146 |
self._capacity = convertSize(650.0, UNIT_MBYTES, UNIT_SECTORS) |
| 147 |
elif self._mediaType == MEDIA_CDR_80: |
| 148 |
self._rewritable = False |
| 149 |
self._capacity = convertSize(700.0, UNIT_MBYTES, UNIT_SECTORS) |
| 150 |
elif self._mediaType == MEDIA_CDRW_80: |
| 151 |
self._rewritable = True |
| 152 |
self._capacity = convertSize(700.0, UNIT_MBYTES, UNIT_SECTORS) |
| 153 |
|
| 154 |
def _getMediaType(self): |
| 155 |
""" |
| 156 |
Property target used to get the media type value. |
| 157 |
""" |
| 158 |
return self._mediaType |
| 159 |
|
| 160 |
def _getRewritable(self): |
| 161 |
""" |
| 162 |
Property target used to get the rewritable flag value. |
| 163 |
""" |
| 164 |
return self._rewritable |
| 165 |
|
| 166 |
def _getInitialLeadIn(self): |
| 167 |
""" |
| 168 |
Property target used to get the initial lead-in value. |
| 169 |
""" |
| 170 |
return self._initialLeadIn |
| 171 |
|
| 172 |
def _getLeadIn(self): |
| 173 |
""" |
| 174 |
Property target used to get the lead-in value. |
| 175 |
""" |
| 176 |
return self._leadIn |
| 177 |
|
| 178 |
def _getCapacity(self): |
| 179 |
""" |
| 180 |
Property target used to get the capacity value. |
| 181 |
""" |
| 182 |
return self._capacity |
| 183 |
|
| 184 |
mediaType = property(_getMediaType, None, None, doc="Configured media type.") |
| 185 |
rewritable = property(_getRewritable, None, None, doc="Boolean indicating whether the media is rewritable.") |
| 186 |
initialLeadIn = property(_getInitialLeadIn, None, None, doc="Initial lead-in required for first image written to media.") |
| 187 |
leadIn = property(_getLeadIn, None, None, doc="Lead-in required on successive images written to media.") |
| 188 |
capacity = property(_getCapacity, None, None, doc="Total capacity of the media before any required lead-in.") |
| 189 |
|
| 190 |
|
| 191 |
######################################################################## |
| 192 |
# MediaCapacity class definition |
| 193 |
######################################################################## |
| 194 |
|
| 195 |
|
| 196 |
class MediaCapacity: |
| 197 |
""" |
| 198 |
Class encapsulating information about CD media capacity. |
| 199 |
|
| 200 |
Space used includes the required media lead-in (unless the disk is unused). |
| 201 |
Space available attempts to provide a picture of how many bytes are |
| 202 |
available for data storage, including any required lead-in. |
| 203 |
|
| 204 |
The boundaries value is either ``None`` (if multisession discs are not |
| 205 |
supported or if the disc has no boundaries) or in exactly the form provided |
| 206 |
by ``cdrecord -msinfo``. It can be passed as-is to the ``IsoImage`` class. |
| 207 |
|
| 208 |
""" |
| 209 |
|
| 210 |
def __init__(self, bytesUsed, bytesAvailable, boundaries): |
| 211 |
""" |
| 212 |
Initializes a capacity object. |
| 213 |
|
| 214 |
Raises: |
| 215 |
IndexError: If the boundaries tuple does not have enough elements |
| 216 |
ValueError: If the boundaries values are not integers |
| 217 |
ValueError: If the bytes used and available values are not floats |
| 218 |
""" |
| 219 |
self._bytesUsed = float(bytesUsed) |
| 220 |
self._bytesAvailable = float(bytesAvailable) |
| 221 |
if boundaries is None: |
| 222 |
self._boundaries = None |
| 223 |
else: |
| 224 |
self._boundaries = (int(boundaries[0]), int(boundaries[1])) |
| 225 |
|
| 226 |
def __str__(self): |
| 227 |
""" |
| 228 |
Informal string representation for class instance. |
| 229 |
""" |
| 230 |
return "utilized %s of %s (%.2f%%)" % (displayBytes(self.bytesUsed), displayBytes(self.totalCapacity), self.utilized) |
| 231 |
|
| 232 |
def _getBytesUsed(self): |
| 233 |
""" |
| 234 |
Property target to get the bytes-used value. |
| 235 |
""" |
| 236 |
return self._bytesUsed |
| 237 |
|
| 238 |
def _getBytesAvailable(self): |
| 239 |
""" |
| 240 |
Property target to get the bytes-available value. |
| 241 |
""" |
| 242 |
return self._bytesAvailable |
| 243 |
|
| 244 |
def _getBoundaries(self): |
| 245 |
""" |
| 246 |
Property target to get the boundaries tuple. |
| 247 |
""" |
| 248 |
return self._boundaries |
| 249 |
|
| 250 |
def _getTotalCapacity(self): |
| 251 |
""" |
| 252 |
Property target to get the total capacity (used + available). |
| 253 |
""" |
| 254 |
return self.bytesUsed + self.bytesAvailable |
| 255 |
|
| 256 |
def _getUtilized(self): |
| 257 |
""" |
| 258 |
Property target to get the percent of capacity which is utilized. |
| 259 |
""" |
| 260 |
if self.bytesAvailable <= 0.0: |
| 261 |
return 100.0 |
| 262 |
elif self.bytesUsed <= 0.0: |
| 263 |
return 0.0 |
| 264 |
return (self.bytesUsed / self.totalCapacity) * 100.0 |
| 265 |
|
| 266 |
bytesUsed = property(_getBytesUsed, None, None, doc="Space used on disc, in bytes.") |
| 267 |
bytesAvailable = property(_getBytesAvailable, None, None, doc="Space available on disc, in bytes.") |
| 268 |
boundaries = property(_getBoundaries, None, None, doc="Session disc boundaries, in terms of ISO sectors.") |
| 269 |
totalCapacity = property(_getTotalCapacity, None, None, doc="Total capacity of the disc, in bytes.") |
| 270 |
utilized = property(_getUtilized, None, None, "Percentage of the total capacity which is utilized.") |
| 271 |
|
| 272 |
|
| 273 |
######################################################################## |
| 274 |
# _ImageProperties class definition |
| 275 |
######################################################################## |
| 276 |
|
| 277 |
|
| 278 |
class _ImageProperties: |
| 279 |
""" |
| 280 |
Simple value object to hold image properties for ``DvdWriter``. |
| 281 |
""" |
| 282 |
|
| 283 |
def __init__(self): |
| 284 |
self.newDisc = False |
| 285 |
self.tmpdir = None |
| 286 |
self.mediaLabel = None |
| 287 |
self.entries = None # dict mapping path to graft point |
| 288 |
|
| 289 |
|
| 290 |
######################################################################## |
| 291 |
# CdWriter class definition |
| 292 |
######################################################################## |
| 293 |
|
| 294 |
|
| 295 |
class CdWriter: |
| 296 |
###################### |
| 297 |
# Class documentation |
| 298 |
###################### |
| 299 |
|
| 300 |
""" |
| 301 |
Class representing a device that knows how to write CD media. |
| 302 |
|
| 303 |
This is a class representing a device that knows how to write CD media. It |
| 304 |
provides common operations for the device, such as ejecting the media, |
| 305 |
writing an ISO image to the media, or checking for the current media |
| 306 |
capacity. It also provides a place to store device attributes, such as |
| 307 |
whether the device supports writing multisession discs, etc. |
| 308 |
|
| 309 |
This class is implemented in terms of the ``eject`` and ``cdrecord`` |
| 310 |
programs, both of which should be available on most UN*X platforms. |
| 311 |
|
| 312 |
**Image Writer Interface** |
| 313 |
|
| 314 |
The following methods make up the "image writer" interface shared |
| 315 |
with other kinds of writers (such as DVD writers):: |
| 316 |
|
| 317 |
__init__ |
| 318 |
initializeImage() |
| 319 |
addImageEntry() |
| 320 |
writeImage() |
| 321 |
setImageNewDisc() |
| 322 |
retrieveCapacity() |
| 323 |
getEstimatedImageSize() |
| 324 |
|
| 325 |
Only these methods will be used by other Cedar Backup functionality |
| 326 |
that expects a compatible image writer. |
| 327 |
|
| 328 |
The media attribute is also assumed to be available. |
| 329 |
|
| 330 |
**Media Types** |
| 331 |
|
| 332 |
This class knows how to write to two different kinds of media, represented |
| 333 |
by the following constants: |
| 334 |
|
| 335 |
- ``MEDIA_CDR_74``: 74-minute CD-R media (650 MB capacity) |
| 336 |
- ``MEDIA_CDRW_74``: 74-minute CD-RW media (650 MB capacity) |
| 337 |
- ``MEDIA_CDR_80``: 80-minute CD-R media (700 MB capacity) |
| 338 |
- ``MEDIA_CDRW_80``: 80-minute CD-RW media (700 MB capacity) |
| 339 |
|
| 340 |
Most hardware can read and write both 74-minute and 80-minute CD-R and |
| 341 |
CD-RW media. Some older drives may only be able to write CD-R media. |
| 342 |
The difference between the two is that CD-RW media can be rewritten |
| 343 |
(erased), while CD-R media cannot be. |
| 344 |
|
| 345 |
I do not support any other configurations for a couple of reasons. The |
| 346 |
first is that I've never tested any other kind of media. The second is |
| 347 |
that anything other than 74 or 80 minute is apparently non-standard. |
| 348 |
|
| 349 |
**Device Attributes vs. Media Attributes** |
| 350 |
|
| 351 |
A given writer instance has two different kinds of attributes associated |
| 352 |
with it, which I call device attributes and media attributes. Device |
| 353 |
attributes are things which can be determined without looking at the |
| 354 |
media, such as whether the drive supports writing multisession disks or |
| 355 |
has a tray. Media attributes are attributes which vary depending on the |
| 356 |
state of the media, such as the remaining capacity on a disc. In |
| 357 |
general, device attributes are available via instance variables and are |
| 358 |
constant over the life of an object, while media attributes can be |
| 359 |
retrieved through method calls. |
| 360 |
|
| 361 |
**Talking to Hardware** |
| 362 |
|
| 363 |
This class needs to talk to CD writer hardware in two different ways: |
| 364 |
through cdrecord to actually write to the media, and through the |
| 365 |
filesystem to do things like open and close the tray. |
| 366 |
|
| 367 |
Historically, CdWriter has interacted with cdrecord using the scsiId |
| 368 |
attribute, and with most other utilities using the device attribute. |
| 369 |
This changed somewhat in Cedar Backup 2.9.0. |
| 370 |
|
| 371 |
When Cedar Backup was first written, the only way to interact with |
| 372 |
cdrecord was by using a SCSI device id. IDE devices were mapped to |
| 373 |
pseudo-SCSI devices through the kernel. Later, extended SCSI "methods" |
| 374 |
arrived, and it became common to see ``ATA:1,0,0`` or ``ATAPI:0,0,0`` as a |
| 375 |
way to address IDE hardware. By late 2006, ``ATA`` and ``ATAPI`` had |
| 376 |
apparently been deprecated in favor of just addressing the IDE device |
| 377 |
directly by name, i.e. ``/dev/cdrw``. |
| 378 |
|
| 379 |
Because of this latest development, it no longer makes sense to require a |
| 380 |
CdWriter to be created with a SCSI id -- there might not be one. So, the |
| 381 |
passed-in SCSI id is now optional. Also, there is now a hardwareId |
| 382 |
attribute. This attribute is filled in with either the SCSI id (if |
| 383 |
provided) or the device (otherwise). The hardware id is the value that |
| 384 |
will be passed to cdrecord in the ``dev=`` argument. |
| 385 |
|
| 386 |
**Testing** |
| 387 |
|
| 388 |
It's rather difficult to test this code in an automated fashion, even if |
| 389 |
you have access to a physical CD writer drive. It's even more difficult |
| 390 |
to test it if you are running on some build daemon (think of a Debian |
| 391 |
autobuilder) which can't be expected to have any hardware or any media |
| 392 |
that you could write to. |
| 393 |
|
| 394 |
Because of this, much of the implementation below is in terms of static |
| 395 |
methods that are supposed to take defined actions based on their |
| 396 |
arguments. Public methods are then implemented in terms of a series of |
| 397 |
calls to simplistic static methods. This way, we can test as much as |
| 398 |
possible of the functionality via testing the static methods, while |
| 399 |
hoping that if the static methods are called appropriately, things will |
| 400 |
work properly. It's not perfect, but it's much better than no testing at |
| 401 |
all. |
| 402 |
|
| 403 |
""" |
| 404 |
|
| 405 |
############## |
| 406 |
# Constructor |
| 407 |
############## |
| 408 |
|
| 409 |
def __init__( |
| 410 |
self, |
| 411 |
device, |
| 412 |
scsiId=None, |
| 413 |
driveSpeed=None, |
| 414 |
mediaType=MEDIA_CDRW_74, |
| 415 |
noEject=False, |
| 416 |
refreshMediaDelay=0, |
| 417 |
ejectDelay=0, |
| 418 |
unittest=False, |
| 419 |
): |
| 420 |
""" |
| 421 |
Initializes a CD writer object. |
| 422 |
|
| 423 |
The current user must have write access to the device at the time the |
| 424 |
object is instantiated, or an exception will be thrown. However, no |
| 425 |
media-related validation is done, and in fact there is no need for any |
| 426 |
media to be in the drive until one of the other media attribute-related |
| 427 |
methods is called. |
| 428 |
|
| 429 |
The various instance variables such as ``deviceType``, ``deviceVendor``, |
| 430 |
etc. might be ``None``, if we're unable to parse this specific information |
| 431 |
from the ``cdrecord`` output. This information is just for reference. |
| 432 |
|
| 433 |
The SCSI id is optional, but the device path is required. If the SCSI id |
| 434 |
is passed in, then the hardware id attribute will be taken from the SCSI |
| 435 |
id. Otherwise, the hardware id will be taken from the device. |
| 436 |
|
| 437 |
If cdrecord improperly detects whether your writer device has a tray and |
| 438 |
can be safely opened and closed, then pass in ``noEject=False``. This |
| 439 |
will override the properties and the device will never be ejected. |
| 440 |
|
| 441 |
*Note:* The ``unittest`` parameter should never be set to ``True`` |
| 442 |
outside of Cedar Backup code. It is intended for use in unit testing |
| 443 |
Cedar Backup internals and has no other sensible purpose. |
| 444 |
|
| 445 |
Args: |
| 446 |
device (Absolute path to a filesystem device, i.e. ``/dev/cdrw``): Filesystem device associated with this writer |
| 447 |
scsiId (If provided, SCSI id in the form ``[<method>:]scsibus,target,lun``): SCSI id for the device (optional) |
| 448 |
driveSpeed (Use ``2`` for 2x device, etc. or ``None`` to use device default): Speed at which the drive writes |
| 449 |
mediaType (One of the valid media type as discussed above): Type of the media that is assumed to be in the drive |
| 450 |
noEject (Boolean true/false): Overrides properties to indicate that the device does not support eject |
| 451 |
refreshMediaDelay (Number of seconds, an integer >= 0): Refresh media delay to use, if any |
| 452 |
ejectDelay (Number of seconds, an integer >= 0): Eject delay to use, if any |
| 453 |
unittest (Boolean true/false): Turns off certain validations, for use in unit testing |
| 454 |
Raises: |
| 455 |
ValueError: If the device is not valid for some reason |
| 456 |
ValueError: If the SCSI id is not in a valid form |
| 457 |
ValueError: If the drive speed is not an integer >= 1 |
| 458 |
IOError: If device properties could not be read for some reason |
| 459 |
""" |
| 460 |
self._image = None # optionally filled in by initializeImage() |
| 461 |
self._device = validateDevice(device, unittest) |
| 462 |
self._scsiId = validateScsiId(scsiId) |
| 463 |
self._driveSpeed = validateDriveSpeed(driveSpeed) |
| 464 |
self._media = MediaDefinition(mediaType) |
| 465 |
self._noEject = noEject |
| 466 |
self._refreshMediaDelay = refreshMediaDelay |
| 467 |
self._ejectDelay = ejectDelay |
| 468 |
if not unittest: |
| 469 |
( |
| 470 |
self._deviceType, |
| 471 |
self._deviceVendor, |
| 472 |
self._deviceId, |
| 473 |
self._deviceBufferSize, |
| 474 |
self._deviceSupportsMulti, |
| 475 |
self._deviceHasTray, |
| 476 |
self._deviceCanEject, |
| 477 |
) = self._retrieveProperties() |
| 478 |
|
| 479 |
############# |
| 480 |
# Properties |
| 481 |
############# |
| 482 |
|
| 483 |
def _getDevice(self): |
| 484 |
""" |
| 485 |
Property target used to get the device value. |
| 486 |
""" |
| 487 |
return self._device |
| 488 |
|
| 489 |
def _getScsiId(self): |
| 490 |
""" |
| 491 |
Property target used to get the SCSI id value. |
| 492 |
""" |
| 493 |
return self._scsiId |
| 494 |
|
| 495 |
def _getHardwareId(self): |
| 496 |
""" |
| 497 |
Property target used to get the hardware id value. |
| 498 |
""" |
| 499 |
if self._scsiId is None: |
| 500 |
return self._device |
| 501 |
return self._scsiId |
| 502 |
|
| 503 |
def _getDriveSpeed(self): |
| 504 |
""" |
| 505 |
Property target used to get the drive speed. |
| 506 |
""" |
| 507 |
return self._driveSpeed |
| 508 |
|
| 509 |
def _getMedia(self): |
| 510 |
""" |
| 511 |
Property target used to get the media description. |
| 512 |
""" |
| 513 |
return self._media |
| 514 |
|
| 515 |
def _getDeviceType(self): |
| 516 |
""" |
| 517 |
Property target used to get the device type. |
| 518 |
""" |
| 519 |
return self._deviceType |
| 520 |
|
| 521 |
def _getDeviceVendor(self): |
| 522 |
""" |
| 523 |
Property target used to get the device vendor. |
| 524 |
""" |
| 525 |
return self._deviceVendor |
| 526 |
|
| 527 |
def _getDeviceId(self): |
| 528 |
""" |
| 529 |
Property target used to get the device id. |
| 530 |
""" |
| 531 |
return self._deviceId |
| 532 |
|
| 533 |
def _getDeviceBufferSize(self): |
| 534 |
""" |
| 535 |
Property target used to get the device buffer size. |
| 536 |
""" |
| 537 |
return self._deviceBufferSize |
| 538 |
|
| 539 |
def _getDeviceSupportsMulti(self): |
| 540 |
""" |
| 541 |
Property target used to get the device-support-multi flag. |
| 542 |
""" |
| 543 |
return self._deviceSupportsMulti |
| 544 |
|
| 545 |
def _getDeviceHasTray(self): |
| 546 |
""" |
| 547 |
Property target used to get the device-has-tray flag. |
| 548 |
""" |
| 549 |
return self._deviceHasTray |
| 550 |
|
| 551 |
def _getDeviceCanEject(self): |
| 552 |
""" |
| 553 |
Property target used to get the device-can-eject flag. |
| 554 |
""" |
| 555 |
return self._deviceCanEject |
| 556 |
|
| 557 |
def _getRefreshMediaDelay(self): |
| 558 |
""" |
| 559 |
Property target used to get the configured refresh media delay, in seconds. |
| 560 |
""" |
| 561 |
return self._refreshMediaDelay |
| 562 |
|
| 563 |
def _getEjectDelay(self): |
| 564 |
""" |
| 565 |
Property target used to get the configured eject delay, in seconds. |
| 566 |
""" |
| 567 |
return self._ejectDelay |
| 568 |
|
| 569 |
device = property(_getDevice, None, None, doc="Filesystem device name for this writer.") |
| 570 |
scsiId = property(_getScsiId, None, None, doc="SCSI id for the device, in the form ``[<method>:]scsibus,target,lun``.") |
| 571 |
hardwareId = property(_getHardwareId, None, None, doc="Hardware id for this writer, either SCSI id or device path.") |
| 572 |
driveSpeed = property(_getDriveSpeed, None, None, doc="Speed at which the drive writes.") |
| 573 |
media = property(_getMedia, None, None, doc="Definition of media that is expected to be in the device.") |
| 574 |
deviceType = property(_getDeviceType, None, None, doc="Type of the device, as returned from ``cdrecord -prcap``.") |
| 575 |
deviceVendor = property(_getDeviceVendor, None, None, doc="Vendor of the device, as returned from ``cdrecord -prcap``.") |
| 576 |
deviceId = property(_getDeviceId, None, None, doc="Device identification, as returned from ``cdrecord -prcap``.") |
| 577 |
deviceBufferSize = property(_getDeviceBufferSize, None, None, doc="Size of the device's write buffer, in bytes.") |
| 578 |
deviceSupportsMulti = property(_getDeviceSupportsMulti, None, None, doc="Indicates whether device supports multisession discs.") |
| 579 |
deviceHasTray = property(_getDeviceHasTray, None, None, doc="Indicates whether the device has a media tray.") |
| 580 |
deviceCanEject = property(_getDeviceCanEject, None, None, doc="Indicates whether the device supports ejecting its media.") |
| 581 |
refreshMediaDelay = property(_getRefreshMediaDelay, None, None, doc="Refresh media delay, in seconds.") |
| 582 |
ejectDelay = property(_getEjectDelay, None, None, doc="Eject delay, in seconds.") |
| 583 |
|
| 584 |
################################################# |
| 585 |
# Methods related to device and media attributes |
| 586 |
################################################# |
| 587 |
|
| 588 |
def isRewritable(self): |
| 589 |
"""Indicates whether the media is rewritable per configuration.""" |
| 590 |
return self._media.rewritable |
| 591 |
|
| 592 |
def _retrieveProperties(self): |
| 593 |
""" |
| 594 |
Retrieves properties for a device from ``cdrecord``. |
| 595 |
|
| 596 |
The results are returned as a tuple of the object device attributes as |
| 597 |
returned from :any:`_parsePropertiesOutput`: C{(deviceType, deviceVendor, |
| 598 |
deviceId, deviceBufferSize, deviceSupportsMulti, deviceHasTray, |
| 599 |
deviceCanEject)}. |
| 600 |
|
| 601 |
Returns: |
| 602 |
Results tuple as described above |
| 603 |
Raises: |
| 604 |
IOError: If there is a problem talking to the device |
| 605 |
""" |
| 606 |
args = CdWriter._buildPropertiesArgs(self.hardwareId) |
| 607 |
command = resolveCommand(CDRECORD_COMMAND) |
| 608 |
(result, output) = executeCommand(command, args, returnOutput=True, ignoreStderr=True) |
| 609 |
if result != 0: |
| 610 |
raise OSError("Error (%d) executing cdrecord command to get properties." % result) |
| 611 |
return CdWriter._parsePropertiesOutput(output) |
| 612 |
|
| 613 |
def retrieveCapacity(self, entireDisc=False, useMulti=True): |
| 614 |
""" |
| 615 |
Retrieves capacity for the current media in terms of a ``MediaCapacity`` |
| 616 |
object. |
| 617 |
|
| 618 |
If ``entireDisc`` is passed in as ``True`` the capacity will be for the |
| 619 |
entire disc, as if it were to be rewritten from scratch. If the drive |
| 620 |
does not support writing multisession discs or if ``useMulti`` is passed |
| 621 |
in as ``False``, the capacity will also be as if the disc were to be |
| 622 |
rewritten from scratch, but the indicated boundaries value will be |
| 623 |
``None``. The same will happen if the disc cannot be read for some |
| 624 |
reason. Otherwise, the capacity (including the boundaries) will |
| 625 |
represent whatever space remains on the disc to be filled by future |
| 626 |
sessions. |
| 627 |
|
| 628 |
Args: |
| 629 |
entireDisc (Boolean true/false): Indicates whether to return capacity for entire disc |
| 630 |
useMulti (Boolean true/false): Indicates whether a multisession disc should be assumed, if possible |
| 631 |
Returns: |
| 632 |
``MediaCapacity`` object describing the capacity of the media |
| 633 |
Raises: |
| 634 |
IOError: If the media could not be read for some reason |
| 635 |
""" |
| 636 |
boundaries = self._getBoundaries(entireDisc, useMulti) |
| 637 |
return CdWriter._calculateCapacity(self._media, boundaries) |
| 638 |
|
| 639 |
def _getBoundaries(self, entireDisc=False, useMulti=True): |
| 640 |
""" |
| 641 |
Gets the ISO boundaries for the media. |
| 642 |
|
| 643 |
If ``entireDisc`` is passed in as ``True`` the boundaries will be ``None``, |
| 644 |
as if the disc were to be rewritten from scratch. If the drive does not |
| 645 |
support writing multisession discs, the returned value will be ``None``. |
| 646 |
The same will happen if the disc can't be read for some reason. |
| 647 |
Otherwise, the returned value will be represent the boundaries of the |
| 648 |
disc's current contents. |
| 649 |
|
| 650 |
The results are returned as a tuple of (lower, upper) as needed by the |
| 651 |
``IsoImage`` class. Note that these values are in terms of ISO sectors, |
| 652 |
not bytes. Clients should generally consider the boundaries value |
| 653 |
opaque, however. |
| 654 |
|
| 655 |
Args: |
| 656 |
entireDisc (Boolean true/false): Indicates whether to return capacity for entire disc |
| 657 |
useMulti (Boolean true/false): Indicates whether a multisession disc should be assumed, if possible |
| 658 |
Returns: |
| 659 |
Boundaries tuple or ``None``, as described above |
| 660 |
Raises: |
| 661 |
IOError: If the media could not be read for some reason |
| 662 |
""" |
| 663 |
if not self._deviceSupportsMulti: |
| 664 |
logger.debug("Device does not support multisession discs; returning boundaries None.") |
| 665 |
return None |
| 666 |
elif not useMulti: |
| 667 |
logger.debug("Use multisession flag is False; returning boundaries None.") |
| 668 |
return None |
| 669 |
elif entireDisc: |
| 670 |
logger.debug("Entire disc flag is True; returning boundaries None.") |
| 671 |
return None |
| 672 |
else: |
| 673 |
args = CdWriter._buildBoundariesArgs(self.hardwareId) |
| 674 |
command = resolveCommand(CDRECORD_COMMAND) |
| 675 |
(result, output) = executeCommand(command, args, returnOutput=True, ignoreStderr=True) |
| 676 |
if result != 0: |
| 677 |
logger.debug("Error (%d) executing cdrecord command to get capacity.", result) |
| 678 |
logger.warning("Unable to read disc (might not be initialized); returning boundaries of None.") |
| 679 |
return None |
| 680 |
boundaries = CdWriter._parseBoundariesOutput(output) |
| 681 |
if boundaries is None: |
| 682 |
logger.debug("Returning disc boundaries: None") |
| 683 |
else: |
| 684 |
logger.debug("Returning disc boundaries: (%d, %d)", boundaries[0], boundaries[1]) |
| 685 |
return boundaries |
| 686 |
|
| 687 |
@staticmethod |
| 688 |
def _calculateCapacity(media, boundaries): |
| 689 |
""" |
| 690 |
Calculates capacity for the media in terms of boundaries. |
| 691 |
|
| 692 |
If ``boundaries`` is ``None`` or the lower bound is 0 (zero), then the |
| 693 |
capacity will be for the entire disc minus the initial lead in. |
| 694 |
Otherwise, capacity will be as if the caller wanted to add an additional |
| 695 |
session to the end of the existing data on the disc. |
| 696 |
|
| 697 |
Args: |
| 698 |
media: MediaDescription object describing the media capacity |
| 699 |
boundaries: Session boundaries as returned from :any:`_getBoundaries` |
| 700 |
|
| 701 |
Returns: |
| 702 |
``MediaCapacity`` object describing the capacity of the media |
| 703 |
""" |
| 704 |
if boundaries is None or boundaries[1] == 0: |
| 705 |
logger.debug("Capacity calculations are based on a complete disc rewrite.") |
| 706 |
sectorsAvailable = media.capacity - media.initialLeadIn |
| 707 |
if sectorsAvailable < 0: |
| 708 |
sectorsAvailable = 0.0 |
| 709 |
bytesUsed = 0.0 |
| 710 |
bytesAvailable = convertSize(sectorsAvailable, UNIT_SECTORS, UNIT_BYTES) |
| 711 |
else: |
| 712 |
logger.debug("Capacity calculations are based on a new ISO session.") |
| 713 |
sectorsAvailable = media.capacity - boundaries[1] - media.leadIn |
| 714 |
if sectorsAvailable < 0: |
| 715 |
sectorsAvailable = 0.0 |
| 716 |
bytesUsed = convertSize(boundaries[1], UNIT_SECTORS, UNIT_BYTES) |
| 717 |
bytesAvailable = convertSize(sectorsAvailable, UNIT_SECTORS, UNIT_BYTES) |
| 718 |
logger.debug("Used [%s], available [%s].", displayBytes(bytesUsed), displayBytes(bytesAvailable)) |
| 719 |
return MediaCapacity(bytesUsed, bytesAvailable, boundaries) |
| 720 |
|
| 721 |
####################################################### |
| 722 |
# Methods used for working with the internal ISO image |
| 723 |
####################################################### |
| 724 |
|
| 725 |
def initializeImage(self, newDisc, tmpdir, mediaLabel=None): |
| 726 |
""" |
| 727 |
Initializes the writer's associated ISO image. |
| 728 |
|
| 729 |
This method initializes the ``image`` instance variable so that the caller |
| 730 |
can use the ``addImageEntry`` method. Once entries have been added, the |
| 731 |
``writeImage`` method can be called with no arguments. |
| 732 |
|
| 733 |
Args: |
| 734 |
newDisc (Boolean true/false): Indicates whether the disc should be re-initialized |
| 735 |
tmpdir (String representing a directory path on disk): Temporary directory to use if needed |
| 736 |
mediaLabel (String, no more than 25 characters long): Media label to be applied to the image, if any |
| 737 |
|
| 738 |
""" |
| 739 |
self._image = _ImageProperties() |
| 740 |
self._image.newDisc = newDisc |
| 741 |
self._image.tmpdir = encodePath(tmpdir) |
| 742 |
self._image.mediaLabel = mediaLabel |
| 743 |
self._image.entries = {} # mapping from path to graft point (if any) |
| 744 |
|
| 745 |
def addImageEntry(self, path, graftPoint): |
| 746 |
""" |
| 747 |
Adds a filepath entry to the writer's associated ISO image. |
| 748 |
|
| 749 |
The contents of the filepath -- but not the path itself -- will be added |
| 750 |
to the image at the indicated graft point. If you don't want to use a |
| 751 |
graft point, just pass ``None``. |
| 752 |
|
| 753 |
*Note:* Before calling this method, you must call :any:`initializeImage`. |
| 754 |
|
| 755 |
Args: |
| 756 |
path (String representing a path on disk): File or directory to be added to the image |
| 757 |
graftPoint (String representing a graft point path, as described above): Graft point to be used when adding this entry |
| 758 |
Raises: |
| 759 |
ValueError: If initializeImage() was not previously called |
| 760 |
""" |
| 761 |
if self._image is None: |
| 762 |
raise ValueError("Must call initializeImage() before using this method.") |
| 763 |
if not os.path.exists(path): |
| 764 |
raise ValueError("Path [%s] does not exist." % path) |
| 765 |
self._image.entries[path] = graftPoint |
| 766 |
|
| 767 |
def setImageNewDisc(self, newDisc): |
| 768 |
""" |
| 769 |
Resets (overrides) the newDisc flag on the internal image. |
| 770 |
Args: |
| 771 |
newDisc: New disc flag to set |
| 772 |
Raises: |
| 773 |
ValueError: If initializeImage() was not previously called |
| 774 |
""" |
| 775 |
if self._image is None: |
| 776 |
raise ValueError("Must call initializeImage() before using this method.") |
| 777 |
self._image.newDisc = newDisc |
| 778 |
|
| 779 |
def getEstimatedImageSize(self): |
| 780 |
""" |
| 781 |
Gets the estimated size of the image associated with the writer. |
| 782 |
Returns: |
| 783 |
Estimated size of the image, in bytes |
| 784 |
Raises: |
| 785 |
IOError: If there is a problem calling ``mkisofs`` |
| 786 |
ValueError: If initializeImage() was not previously called |
| 787 |
""" |
| 788 |
if self._image is None: |
| 789 |
raise ValueError("Must call initializeImage() before using this method.") |
| 790 |
image = IsoImage() |
| 791 |
for path in list(self._image.entries.keys()): |
| 792 |
image.addEntry(path, self._image.entries[path], override=False, contentsOnly=True) |
| 793 |
return image.getEstimatedSize() |
| 794 |
|
| 795 |
###################################### |
| 796 |
# Methods which expose device actions |
| 797 |
###################################### |
| 798 |
|
| 799 |
def openTray(self): |
| 800 |
""" |
| 801 |
Opens the device's tray and leaves it open. |
| 802 |
|
| 803 |
This only works if the device has a tray and supports ejecting its media. |
| 804 |
We have no way to know if the tray is currently open or closed, so we |
| 805 |
just send the appropriate command and hope for the best. If the device |
| 806 |
does not have a tray or does not support ejecting its media, then we do |
| 807 |
nothing. |
| 808 |
|
| 809 |
If the writer was constructed with ``noEject=True``, then this is a no-op. |
| 810 |
|
| 811 |
Starting with Debian wheezy on my backup hardware, I started seeing |
| 812 |
consistent problems with the eject command. I couldn't tell whether |
| 813 |
these problems were due to the device management system or to the new |
| 814 |
kernel (3.2.0). Initially, I saw simple eject failures, possibly because |
| 815 |
I was opening and closing the tray too quickly. I worked around that |
| 816 |
behavior with the new ejectDelay flag. |
| 817 |
|
| 818 |
Later, I sometimes ran into issues after writing an image to a disc: |
| 819 |
eject would give errors like "unable to eject, last error: Inappropriate |
| 820 |
ioctl for device". Various sources online (like Ubuntu bug #875543) |
| 821 |
suggested that the drive was being locked somehow, and that the |
| 822 |
workaround was to run 'eject -i off' to unlock it. Sure enough, that |
| 823 |
fixed the problem for me, so now it's a normal error-handling strategy. |
| 824 |
|
| 825 |
Raises: |
| 826 |
IOError: If there is an error talking to the device |
| 827 |
""" |
| 828 |
if not self._noEject: |
| 829 |
if self._deviceHasTray and self._deviceCanEject: |
| 830 |
args = CdWriter._buildOpenTrayArgs(self._device) |
| 831 |
result = executeCommand(EJECT_COMMAND, args)[0] |
| 832 |
if result != 0: |
| 833 |
logger.debug("Eject failed; attempting kludge of unlocking the tray before retrying.") |
| 834 |
self.unlockTray() |
| 835 |
result = executeCommand(EJECT_COMMAND, args)[0] |
| 836 |
if result != 0: |
| 837 |
raise OSError( |
| 838 |
"Error (%d) executing eject command to open tray (failed even after unlocking tray)." % result |
| 839 |
) |
| 840 |
logger.debug("Kludge was apparently successful.") |
| 841 |
if self.ejectDelay is not None: |
| 842 |
logger.debug("Per configuration, sleeping %d seconds after opening tray.", self.ejectDelay) |
| 843 |
time.sleep(self.ejectDelay) |
| 844 |
|
| 845 |
def unlockTray(self): |
| 846 |
""" |
| 847 |
Unlocks the device's tray. |
| 848 |
Raises: |
| 849 |
IOError: If there is an error talking to the device |
| 850 |
""" |
| 851 |
args = CdWriter._buildUnlockTrayArgs(self._device) |
| 852 |
command = resolveCommand(EJECT_COMMAND) |
| 853 |
result = executeCommand(command, args)[0] |
| 854 |
if result != 0: |
| 855 |
raise OSError("Error (%d) executing eject command to unlock tray." % result) |
| 856 |
|
| 857 |
def closeTray(self): |
| 858 |
""" |
| 859 |
Closes the device's tray. |
| 860 |
|
| 861 |
This only works if the device has a tray and supports ejecting its media. |
| 862 |
We have no way to know if the tray is currently open or closed, so we |
| 863 |
just send the appropriate command and hope for the best. If the device |
| 864 |
does not have a tray or does not support ejecting its media, then we do |
| 865 |
nothing. |
| 866 |
|
| 867 |
If the writer was constructed with ``noEject=True``, then this is a no-op. |
| 868 |
|
| 869 |
Raises: |
| 870 |
IOError: If there is an error talking to the device |
| 871 |
""" |
| 872 |
if not self._noEject: |
| 873 |
if self._deviceHasTray and self._deviceCanEject: |
| 874 |
args = CdWriter._buildCloseTrayArgs(self._device) |
| 875 |
command = resolveCommand(EJECT_COMMAND) |
| 876 |
result = executeCommand(command, args)[0] |
| 877 |
if result != 0: |
| 878 |
raise OSError("Error (%d) executing eject command to close tray." % result) |
| 879 |
|
| 880 |
def refreshMedia(self): |
| 881 |
""" |
| 882 |
Opens and then immediately closes the device's tray, to refresh the |
| 883 |
device's idea of the media. |
| 884 |
|
| 885 |
Sometimes, a device gets confused about the state of its media. Often, |
| 886 |
all it takes to solve the problem is to eject the media and then |
| 887 |
immediately reload it. (There are also configurable eject and refresh |
| 888 |
media delays which can be applied, for situations where this makes a |
| 889 |
difference.) |
| 890 |
|
| 891 |
This only works if the device has a tray and supports ejecting its media. |
| 892 |
We have no way to know if the tray is currently open or closed, so we |
| 893 |
just send the appropriate command and hope for the best. If the device |
| 894 |
does not have a tray or does not support ejecting its media, then we do |
| 895 |
nothing. The configured delays still apply, though. |
| 896 |
|
| 897 |
Raises: |
| 898 |
IOError: If there is an error talking to the device |
| 899 |
""" |
| 900 |
self.openTray() |
| 901 |
self.closeTray() |
| 902 |
self.unlockTray() # on some systems, writing a disc leaves the tray locked, yikes! |
| 903 |
if self.refreshMediaDelay is not None: |
| 904 |
logger.debug("Per configuration, sleeping %d seconds to stabilize media state.", self.refreshMediaDelay) |
| 905 |
time.sleep(self.refreshMediaDelay) |
| 906 |
logger.debug("Media refresh complete; hopefully media state is stable now.") |
| 907 |
|
| 908 |
def writeImage(self, imagePath=None, newDisc=False, writeMulti=True): |
| 909 |
""" |
| 910 |
Writes an ISO image to the media in the device. |
| 911 |
|
| 912 |
If ``newDisc`` is passed in as ``True``, we assume that the entire disc |
| 913 |
will be overwritten, and the media will be blanked before writing it if |
| 914 |
possible (i.e. if the media is rewritable). |
| 915 |
|
| 916 |
If ``writeMulti`` is passed in as ``True``, then a multisession disc will |
| 917 |
be written if possible (i.e. if the drive supports writing multisession |
| 918 |
discs). |
| 919 |
|
| 920 |
if ``imagePath`` is passed in as ``None``, then the existing image |
| 921 |
configured with ``initializeImage`` will be used. Under these |
| 922 |
circumstances, the passed-in ``newDisc`` flag will be ignored. |
| 923 |
|
| 924 |
By default, we assume that the disc can be written multisession and that |
| 925 |
we should append to the current contents of the disc. In any case, the |
| 926 |
ISO image must be generated appropriately (i.e. must take into account |
| 927 |
any existing session boundaries, etc.) |
| 928 |
|
| 929 |
Args: |
| 930 |
imagePath (String representing a path on disk): Path to an ISO image on disk, or ``None`` to use writer's image |
| 931 |
newDisc (Boolean true/false): Indicates whether the entire disc will overwritten |
| 932 |
writeMulti (Boolean true/false): Indicates whether a multisession disc should be written, if possible |
| 933 |
Raises: |
| 934 |
ValueError: If the image path is not absolute |
| 935 |
ValueError: If some path cannot be encoded properly |
| 936 |
IOError: If the media could not be written to for some reason |
| 937 |
ValueError: If no image is passed in and initializeImage() was not previously called |
| 938 |
""" |
| 939 |
if imagePath is None: |
| 940 |
if self._image is None: |
| 941 |
raise ValueError("Must call initializeImage() before using this method with no image path.") |
| 942 |
try: |
| 943 |
imagePath = self._createImage() |
| 944 |
self._writeImage(imagePath, writeMulti, self._image.newDisc) |
| 945 |
finally: |
| 946 |
if imagePath is not None and os.path.exists(imagePath): |
| 947 |
try: |
| 948 |
os.unlink(imagePath) |
| 949 |
except: |
| 950 |
pass |
| 951 |
else: |
| 952 |
imagePath = encodePath(imagePath) |
| 953 |
if not (os.path.isabs(imagePath) or posixpath.isabs(imagePath)): # Python 3.13+ does not treat / as absolute on Windows |
| 954 |
raise ValueError("Image path must be absolute.") |
| 955 |
self._writeImage(imagePath, writeMulti, newDisc) |
| 956 |
|
| 957 |
def _createImage(self): |
| 958 |
""" |
| 959 |
Creates an ISO image based on configuration in self._image. |
| 960 |
Returns: |
| 961 |
Path to the newly-created ISO image on disk |
| 962 |
Raises: |
| 963 |
IOError: If there is an error writing the image to disk |
| 964 |
ValueError: If there are no filesystem entries in the image |
| 965 |
ValueError: If a path cannot be encoded properly |
| 966 |
""" |
| 967 |
path = None |
| 968 |
capacity = self.retrieveCapacity(entireDisc=self._image.newDisc) |
| 969 |
image = IsoImage(self.device, capacity.boundaries) |
| 970 |
image.volumeId = self._image.mediaLabel # may be None, which is also valid |
| 971 |
for key in list(self._image.entries.keys()): |
| 972 |
image.addEntry(key, self._image.entries[key], override=False, contentsOnly=True) |
| 973 |
size = image.getEstimatedSize() |
| 974 |
logger.info("Image size will be %s.", displayBytes(size)) |
| 975 |
available = capacity.bytesAvailable |
| 976 |
logger.debug("Media capacity: %s", displayBytes(available)) |
| 977 |
if size > available: |
| 978 |
logger.error("Image [%s] does not fit in available capacity [%s].", displayBytes(size), displayBytes(available)) |
| 979 |
raise OSError("Media does not contain enough capacity to store image.") |
| 980 |
try: |
| 981 |
(handle, path) = tempfile.mkstemp(dir=self._image.tmpdir) |
| 982 |
try: |
| 983 |
os.close(handle) |
| 984 |
except: |
| 985 |
pass |
| 986 |
image.writeImage(path) |
| 987 |
logger.debug("Completed creating image [%s].", path) |
| 988 |
return path |
| 989 |
except Exception as e: |
| 990 |
if path is not None and os.path.exists(path): |
| 991 |
try: |
| 992 |
os.unlink(path) |
| 993 |
except: |
| 994 |
pass |
| 995 |
raise e |
| 996 |
|
| 997 |
def _writeImage(self, imagePath, writeMulti, newDisc): |
| 998 |
""" |
| 999 |
Write an ISO image to disc using cdrecord. |
| 1000 |
The disc is blanked first if ``newDisc`` is ``True``. |
| 1001 |
Args: |
| 1002 |
imagePath: Path to an ISO image on disk |
| 1003 |
writeMulti: Indicates whether a multisession disc should be written, if possible |
| 1004 |
newDisc: Indicates whether the entire disc will overwritten |
| 1005 |
""" |
| 1006 |
if newDisc: |
| 1007 |
self._blankMedia() |
| 1008 |
args = CdWriter._buildWriteArgs(self.hardwareId, imagePath, self._driveSpeed, writeMulti and self._deviceSupportsMulti) |
| 1009 |
command = resolveCommand(CDRECORD_COMMAND) |
| 1010 |
result = executeCommand(command, args)[0] |
| 1011 |
if result != 0: |
| 1012 |
raise OSError("Error (%d) executing command to write disc." % result) |
| 1013 |
self.refreshMedia() |
| 1014 |
|
| 1015 |
def _blankMedia(self): |
| 1016 |
""" |
| 1017 |
Blanks the media in the device, if the media is rewritable. |
| 1018 |
Raises: |
| 1019 |
IOError: If the media could not be written to for some reason |
| 1020 |
""" |
| 1021 |
if self.isRewritable(): |
| 1022 |
args = CdWriter._buildBlankArgs(self.hardwareId) |
| 1023 |
command = resolveCommand(CDRECORD_COMMAND) |
| 1024 |
result = executeCommand(command, args)[0] |
| 1025 |
if result != 0: |
| 1026 |
raise OSError("Error (%d) executing command to blank disc." % result) |
| 1027 |
self.refreshMedia() |
| 1028 |
|
| 1029 |
####################################### |
| 1030 |
# Methods used to parse command output |
| 1031 |
####################################### |
| 1032 |
|
| 1033 |
@staticmethod |
| 1034 |
def _parsePropertiesOutput(output): |
| 1035 |
""" |
| 1036 |
Parses the output from a ``cdrecord`` properties command. |
| 1037 |
|
| 1038 |
The ``output`` parameter should be a list of strings as returned from |
| 1039 |
``executeCommand`` for a ``cdrecord`` command with arguments as from |
| 1040 |
``_buildPropertiesArgs``. The list of strings will be parsed to yield |
| 1041 |
information about the properties of the device. |
| 1042 |
|
| 1043 |
The output is expected to be a huge long list of strings. Unfortunately, |
| 1044 |
the strings aren't in a completely regular format. However, the format |
| 1045 |
of individual lines seems to be regular enough that we can look for |
| 1046 |
specific values. Two kinds of parsing take place: one kind of parsing |
| 1047 |
picks out out specific values like the device id, device vendor, etc. |
| 1048 |
The other kind of parsing just sets a boolean flag ``True`` if a matching |
| 1049 |
line is found. All of the parsing is done with regular expressions. |
| 1050 |
|
| 1051 |
Right now, pretty much nothing in the output is required and we should |
| 1052 |
parse an empty document successfully (albeit resulting in a device that |
| 1053 |
can't eject, doesn't have a tray and doesnt't support multisession |
| 1054 |
discs). I had briefly considered erroring out if certain lines weren't |
| 1055 |
found or couldn't be parsed, but that seems like a bad idea given that |
| 1056 |
most of the information is just for reference. |
| 1057 |
|
| 1058 |
The results are returned as a tuple of the object device attributes: |
| 1059 |
C{(deviceType, deviceVendor, deviceId, deviceBufferSize, |
| 1060 |
deviceSupportsMulti, deviceHasTray, deviceCanEject)}. |
| 1061 |
|
| 1062 |
Args: |
| 1063 |
output: Output from a ``cdrecord -prcap`` command |
| 1064 |
|
| 1065 |
Returns: |
| 1066 |
Results tuple as described above |
| 1067 |
Raises: |
| 1068 |
IOError: If there is problem parsing the output |
| 1069 |
""" |
| 1070 |
deviceType = None |
| 1071 |
deviceVendor = None |
| 1072 |
deviceId = None |
| 1073 |
deviceBufferSize = None |
| 1074 |
deviceSupportsMulti = False |
| 1075 |
deviceHasTray = False |
| 1076 |
deviceCanEject = False |
| 1077 |
typePattern = re.compile(r"(^Device type\s*:\s*)(.*)(\s*)(.*$)") |
| 1078 |
vendorPattern = re.compile(r"(^Vendor_info\s*:\s*'\s*)(.*?)(\s*')(.*$)") |
| 1079 |
idPattern = re.compile(r"(^Identifikation\s*:\s*'\s*)(.*?)(\s*')(.*$)") |
| 1080 |
bufferPattern = re.compile(r"(^\s*Buffer size in KB:\s*)(.*?)(\s*$)") |
| 1081 |
multiPattern = re.compile(r"^\s*Does read multi-session.*$") |
| 1082 |
trayPattern = re.compile(r"^\s*Loading mechanism type: tray.*$") |
| 1083 |
ejectPattern = re.compile(r"^\s*Does support ejection.*$") |
| 1084 |
for line in output: |
| 1085 |
if typePattern.search(line): |
| 1086 |
deviceType = typePattern.search(line).group(2) |
| 1087 |
logger.info("Device type is [%s].", deviceType) |
| 1088 |
elif vendorPattern.search(line): |
| 1089 |
deviceVendor = vendorPattern.search(line).group(2) |
| 1090 |
logger.info("Device vendor is [%s].", deviceVendor) |
| 1091 |
elif idPattern.search(line): |
| 1092 |
deviceId = idPattern.search(line).group(2) |
| 1093 |
logger.info("Device id is [%s].", deviceId) |
| 1094 |
elif bufferPattern.search(line): |
| 1095 |
try: |
| 1096 |
sectors = int(bufferPattern.search(line).group(2)) |
| 1097 |
deviceBufferSize = convertSize(sectors, UNIT_KBYTES, UNIT_BYTES) |
| 1098 |
logger.info("Device buffer size is [%d] bytes.", deviceBufferSize) |
| 1099 |
except TypeError: |
| 1100 |
pass |
| 1101 |
elif multiPattern.search(line): |
| 1102 |
deviceSupportsMulti = True |
| 1103 |
logger.info("Device does support multisession discs.") |
| 1104 |
elif trayPattern.search(line): |
| 1105 |
deviceHasTray = True |
| 1106 |
logger.info("Device has a tray.") |
| 1107 |
elif ejectPattern.search(line): |
| 1108 |
deviceCanEject = True |
| 1109 |
logger.info("Device can eject its media.") |
| 1110 |
return (deviceType, deviceVendor, deviceId, deviceBufferSize, deviceSupportsMulti, deviceHasTray, deviceCanEject) |
| 1111 |
|
| 1112 |
@staticmethod |
| 1113 |
def _parseBoundariesOutput(output): |
| 1114 |
""" |
| 1115 |
Parses the output from a ``cdrecord`` capacity command. |
| 1116 |
|
| 1117 |
The ``output`` parameter should be a list of strings as returned from |
| 1118 |
``executeCommand`` for a ``cdrecord`` command with arguments as from |
| 1119 |
``_buildBoundaryArgs``. The list of strings will be parsed to yield |
| 1120 |
information about the capacity of the media in the device. |
| 1121 |
|
| 1122 |
Basically, we expect the list of strings to include just one line, a pair |
| 1123 |
of values. There isn't supposed to be whitespace, but we allow it anyway |
| 1124 |
in the regular expression. Any lines below the one line we parse are |
| 1125 |
completely ignored. It would be a good idea to ignore ``stderr`` when |
| 1126 |
executing the ``cdrecord`` command that generates output for this method, |
| 1127 |
because sometimes ``cdrecord`` spits out kernel warnings about the actual |
| 1128 |
output. |
| 1129 |
|
| 1130 |
The results are returned as a tuple of (lower, upper) as needed by the |
| 1131 |
``IsoImage`` class. Note that these values are in terms of ISO sectors, |
| 1132 |
not bytes. Clients should generally consider the boundaries value |
| 1133 |
opaque, however. |
| 1134 |
|
| 1135 |
*Note:* If the boundaries output can't be parsed, we return ``None``. |
| 1136 |
|
| 1137 |
Args: |
| 1138 |
output: Output from a ``cdrecord -msinfo`` command |
| 1139 |
|
| 1140 |
Returns: |
| 1141 |
Boundaries tuple as described above |
| 1142 |
Raises: |
| 1143 |
IOError: If there is problem parsing the output |
| 1144 |
""" |
| 1145 |
if len(output) < 1: |
| 1146 |
logger.warning("Unable to read disc (might not be initialized); returning full capacity.") |
| 1147 |
return None |
| 1148 |
boundaryPattern = re.compile(r"(^\s*)([0-9]*)(\s*,\s*)([0-9]*)(\s*$)") |
| 1149 |
parsed = boundaryPattern.search(output[0]) |
| 1150 |
if not parsed: |
| 1151 |
raise OSError("Unable to parse output of boundaries command.") |
| 1152 |
try: |
| 1153 |
boundaries = (int(parsed.group(2)), int(parsed.group(4))) |
| 1154 |
except TypeError: |
| 1155 |
raise OSError("Unable to parse output of boundaries command.") |
| 1156 |
return boundaries |
| 1157 |
|
| 1158 |
################################# |
| 1159 |
# Methods used to build commands |
| 1160 |
################################# |
| 1161 |
|
| 1162 |
@staticmethod |
| 1163 |
def _buildOpenTrayArgs(device): |
| 1164 |
""" |
| 1165 |
Builds a list of arguments to be passed to a ``eject`` command. |
| 1166 |
|
| 1167 |
The arguments will cause the ``eject`` command to open the tray and |
| 1168 |
eject the media. No validation is done by this method as to whether |
| 1169 |
this action actually makes sense. |
| 1170 |
|
| 1171 |
Args: |
| 1172 |
device: Filesystem device name for this writer, i.e. ``/dev/cdrw`` |
| 1173 |
|
| 1174 |
Returns: |
| 1175 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1176 |
""" |
| 1177 |
args = [] |
| 1178 |
args.append(device) |
| 1179 |
return args |
| 1180 |
|
| 1181 |
@staticmethod |
| 1182 |
def _buildUnlockTrayArgs(device): |
| 1183 |
""" |
| 1184 |
Builds a list of arguments to be passed to a ``eject`` command. |
| 1185 |
|
| 1186 |
The arguments will cause the ``eject`` command to unlock the tray. |
| 1187 |
|
| 1188 |
Args: |
| 1189 |
device: Filesystem device name for this writer, i.e. ``/dev/cdrw`` |
| 1190 |
|
| 1191 |
Returns: |
| 1192 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1193 |
""" |
| 1194 |
args = [] |
| 1195 |
args.append("-i") |
| 1196 |
args.append("off") |
| 1197 |
args.append(device) |
| 1198 |
return args |
| 1199 |
|
| 1200 |
@staticmethod |
| 1201 |
def _buildCloseTrayArgs(device): |
| 1202 |
""" |
| 1203 |
Builds a list of arguments to be passed to a ``eject`` command. |
| 1204 |
|
| 1205 |
The arguments will cause the ``eject`` command to close the tray and reload |
| 1206 |
the media. No validation is done by this method as to whether this |
| 1207 |
action actually makes sense. |
| 1208 |
|
| 1209 |
Args: |
| 1210 |
device: Filesystem device name for this writer, i.e. ``/dev/cdrw`` |
| 1211 |
|
| 1212 |
Returns: |
| 1213 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1214 |
""" |
| 1215 |
args = [] |
| 1216 |
args.append("-t") |
| 1217 |
args.append(device) |
| 1218 |
return args |
| 1219 |
|
| 1220 |
@staticmethod |
| 1221 |
def _buildPropertiesArgs(hardwareId): |
| 1222 |
""" |
| 1223 |
Builds a list of arguments to be passed to a ``cdrecord`` command. |
| 1224 |
|
| 1225 |
The arguments will cause the ``cdrecord`` command to ask the device |
| 1226 |
for a list of its capacities via the ``-prcap`` switch. |
| 1227 |
|
| 1228 |
Args: |
| 1229 |
hardwareId: Hardware id for the device (either SCSI id or device path) |
| 1230 |
|
| 1231 |
Returns: |
| 1232 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1233 |
""" |
| 1234 |
args = [] |
| 1235 |
args.append("-prcap") |
| 1236 |
args.append("dev=%s" % hardwareId) |
| 1237 |
return args |
| 1238 |
|
| 1239 |
@staticmethod |
| 1240 |
def _buildBoundariesArgs(hardwareId): |
| 1241 |
""" |
| 1242 |
Builds a list of arguments to be passed to a ``cdrecord`` command. |
| 1243 |
|
| 1244 |
The arguments will cause the ``cdrecord`` command to ask the device for |
| 1245 |
the current multisession boundaries of the media using the ``-msinfo`` |
| 1246 |
switch. |
| 1247 |
|
| 1248 |
Args: |
| 1249 |
hardwareId: Hardware id for the device (either SCSI id or device path) |
| 1250 |
|
| 1251 |
Returns: |
| 1252 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1253 |
""" |
| 1254 |
args = [] |
| 1255 |
args.append("-msinfo") |
| 1256 |
args.append("dev=%s" % hardwareId) |
| 1257 |
return args |
| 1258 |
|
| 1259 |
@staticmethod |
| 1260 |
def _buildBlankArgs(hardwareId, driveSpeed=None): |
| 1261 |
""" |
| 1262 |
Builds a list of arguments to be passed to a ``cdrecord`` command. |
| 1263 |
|
| 1264 |
The arguments will cause the ``cdrecord`` command to blank the media in |
| 1265 |
the device identified by ``hardwareId``. No validation is done by this method |
| 1266 |
as to whether the action makes sense (i.e. to whether the media even can |
| 1267 |
be blanked). |
| 1268 |
|
| 1269 |
Args: |
| 1270 |
hardwareId: Hardware id for the device (either SCSI id or device path) |
| 1271 |
driveSpeed: Speed at which the drive writes |
| 1272 |
|
| 1273 |
Returns: |
| 1274 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1275 |
""" |
| 1276 |
args = [] |
| 1277 |
args.append("-v") |
| 1278 |
args.append("blank=fast") |
| 1279 |
if driveSpeed is not None: |
| 1280 |
args.append("speed=%d" % driveSpeed) |
| 1281 |
args.append("dev=%s" % hardwareId) |
| 1282 |
return args |
| 1283 |
|
| 1284 |
@staticmethod |
| 1285 |
def _buildWriteArgs(hardwareId, imagePath, driveSpeed=None, writeMulti=True): |
| 1286 |
""" |
| 1287 |
Builds a list of arguments to be passed to a ``cdrecord`` command. |
| 1288 |
|
| 1289 |
The arguments will cause the ``cdrecord`` command to write the indicated |
| 1290 |
ISO image (``imagePath``) to the media in the device identified by |
| 1291 |
``hardwareId``. The ``writeMulti`` argument controls whether to write a |
| 1292 |
multisession disc. No validation is done by this method as to whether |
| 1293 |
the action makes sense (i.e. to whether the device even can write |
| 1294 |
multisession discs, for instance). |
| 1295 |
|
| 1296 |
Args: |
| 1297 |
hardwareId: Hardware id for the device (either SCSI id or device path) |
| 1298 |
imagePath: Path to an ISO image on disk |
| 1299 |
driveSpeed: Speed at which the drive writes |
| 1300 |
writeMulti: Indicates whether to write a multisession disc |
| 1301 |
|
| 1302 |
Returns: |
| 1303 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 1304 |
""" |
| 1305 |
args = [] |
| 1306 |
args.append("-v") |
| 1307 |
if driveSpeed is not None: |
| 1308 |
args.append("speed=%d" % driveSpeed) |
| 1309 |
args.append("dev=%s" % hardwareId) |
| 1310 |
if writeMulti: |
| 1311 |
args.append("-multi") |
| 1312 |
args.append("-data") |
| 1313 |
args.append(imagePath) |
| 1314 |
return args |