| 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-2007,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 utilities related to image writers. |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Module documentation |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Provides utilities related to image writers. |
| 39 |
:author: Kenneth J. Pronovici <[email protected]> |
| 40 |
""" |
| 41 |
|
| 42 |
|
| 43 |
######################################################################## |
| 44 |
# Imported modules |
| 45 |
######################################################################## |
| 46 |
|
| 47 |
import logging |
| 48 |
import os |
| 49 |
import posixpath |
| 50 |
import re |
| 51 |
|
| 52 |
from CedarBackup3.util import UNIT_BYTES, UNIT_SECTORS, convertSize, encodePath, executeCommand, pathJoin, resolveCommand |
| 53 |
|
| 54 |
######################################################################## |
| 55 |
# Module-wide constants and variables |
| 56 |
######################################################################## |
| 57 |
|
| 58 |
logger = logging.getLogger("CedarBackup3.log.writers.util") |
| 59 |
|
| 60 |
MKISOFS_COMMAND = ["mkisofs"] |
| 61 |
VOLNAME_COMMAND = ["volname"] |
| 62 |
|
| 63 |
|
| 64 |
######################################################################## |
| 65 |
# Functions used to portably validate certain kinds of values |
| 66 |
######################################################################## |
| 67 |
|
| 68 |
############################ |
| 69 |
# validateDevice() function |
| 70 |
############################ |
| 71 |
|
| 72 |
|
| 73 |
def validateDevice(device, unittest=False): |
| 74 |
""" |
| 75 |
Validates a configured device. |
| 76 |
The device must be an absolute path, must exist, and must be writable. |
| 77 |
The unittest flag turns off validation of the device on disk. |
| 78 |
Args: |
| 79 |
device: Filesystem device path |
| 80 |
unittest: Indicates whether we're unit testing |
| 81 |
Returns: |
| 82 |
Device as a string, for instance ``"/dev/cdrw"`` |
| 83 |
Raises: |
| 84 |
ValueError: If the device value is invalid |
| 85 |
ValueError: If some path cannot be encoded properly |
| 86 |
""" |
| 87 |
if device is None: |
| 88 |
raise ValueError("Device must be filled in.") |
| 89 |
device = encodePath(device) |
| 90 |
if not (os.path.isabs(device) or posixpath.isabs(device)): # Python 3.13+ does not treat / as absolute on Windows |
| 91 |
raise ValueError("Backup device must be an absolute path.") |
| 92 |
if not unittest and not os.path.exists(device): |
| 93 |
raise ValueError("Backup device must exist on disk.") |
| 94 |
if not unittest and not os.access(device, os.W_OK): |
| 95 |
raise ValueError("Backup device is not writable by the current user.") |
| 96 |
return device |
| 97 |
|
| 98 |
|
| 99 |
############################ |
| 100 |
# validateScsiId() function |
| 101 |
############################ |
| 102 |
|
| 103 |
|
| 104 |
def validateScsiId(scsiId): |
| 105 |
""" |
| 106 |
Validates a SCSI id string. |
| 107 |
SCSI id must be a string in the form ``[<method>:]scsibus,target,lun``. |
| 108 |
For Mac OS X (Darwin), we also accept the form ``IO.*Services[/N]``. |
| 109 |
*Note:* For consistency, if ``None`` is passed in, ``None`` will be returned. |
| 110 |
Args: |
| 111 |
scsiId: SCSI id for the device |
| 112 |
Returns: |
| 113 |
SCSI id as a string, for instance ``"ATA:1,0,0"`` |
| 114 |
Raises: |
| 115 |
ValueError: If the SCSI id string is invalid |
| 116 |
""" |
| 117 |
if scsiId is not None: |
| 118 |
pattern = re.compile(r"^\s*(.*:)?\s*[0-9][0-9]*\s*,\s*[0-9][0-9]*\s*,\s*[0-9][0-9]*\s*$") |
| 119 |
if not pattern.search(scsiId): |
| 120 |
pattern = re.compile(r"^\s*IO.*Services(/[0-9][0-9]*)?\s*$") |
| 121 |
if not pattern.search(scsiId): |
| 122 |
raise ValueError("SCSI id is not in a valid form.") |
| 123 |
return scsiId |
| 124 |
|
| 125 |
|
| 126 |
################################ |
| 127 |
# validateDriveSpeed() function |
| 128 |
################################ |
| 129 |
|
| 130 |
|
| 131 |
def validateDriveSpeed(driveSpeed): |
| 132 |
""" |
| 133 |
Validates a drive speed value. |
| 134 |
Drive speed must be an integer which is >= 1. |
| 135 |
*Note:* For consistency, if ``None`` is passed in, ``None`` will be returned. |
| 136 |
Args: |
| 137 |
driveSpeed: Speed at which the drive writes |
| 138 |
Returns: |
| 139 |
Drive speed as an integer |
| 140 |
Raises: |
| 141 |
ValueError: If the drive speed value is invalid |
| 142 |
""" |
| 143 |
if driveSpeed is None: |
| 144 |
return None |
| 145 |
try: |
| 146 |
intSpeed = int(driveSpeed) |
| 147 |
except TypeError: |
| 148 |
raise ValueError("Drive speed must be an integer >= 1.") |
| 149 |
if intSpeed < 1: |
| 150 |
raise ValueError("Drive speed must an integer >= 1.") |
| 151 |
return intSpeed |
| 152 |
|
| 153 |
|
| 154 |
######################################################################## |
| 155 |
# General writer-related utility functions |
| 156 |
######################################################################## |
| 157 |
|
| 158 |
############################ |
| 159 |
# readMediaLabel() function |
| 160 |
############################ |
| 161 |
|
| 162 |
|
| 163 |
def readMediaLabel(devicePath): |
| 164 |
""" |
| 165 |
Reads the media label (volume name) from the indicated device. |
| 166 |
The volume name is read using the ``volname`` command. |
| 167 |
Args: |
| 168 |
devicePath: Device path to read from |
| 169 |
Returns: |
| 170 |
Media label as a string, or None if there is no name or it could not be read |
| 171 |
""" |
| 172 |
args = [devicePath] |
| 173 |
command = resolveCommand(VOLNAME_COMMAND) |
| 174 |
(result, output) = executeCommand(command, args, returnOutput=True, ignoreStderr=True) |
| 175 |
if result != 0: |
| 176 |
return None |
| 177 |
if output is None or len(output) < 1: |
| 178 |
return None |
| 179 |
return output[0].rstrip() |
| 180 |
|
| 181 |
|
| 182 |
######################################################################## |
| 183 |
# IsoImage class definition |
| 184 |
######################################################################## |
| 185 |
|
| 186 |
|
| 187 |
class IsoImage: |
| 188 |
###################### |
| 189 |
# Class documentation |
| 190 |
###################### |
| 191 |
|
| 192 |
""" |
| 193 |
Represents an ISO filesystem image. |
| 194 |
|
| 195 |
**Summary** |
| 196 |
|
| 197 |
This object represents an ISO 9660 filesystem image. It is implemented |
| 198 |
in terms of the ``mkisofs`` program, which has been ported to many |
| 199 |
operating systems and platforms. A "sensible subset" of the ``mkisofs`` |
| 200 |
functionality is made available through the public interface, allowing |
| 201 |
callers to set a variety of basic options such as publisher id, |
| 202 |
application id, etc. as well as specify exactly which files and |
| 203 |
directories they want included in their image. |
| 204 |
|
| 205 |
By default, the image is created using the Rock Ridge protocol (using the |
| 206 |
``-r`` option to ``mkisofs``) because Rock Ridge discs are generally more |
| 207 |
useful on UN*X filesystems than standard ISO 9660 images. However, |
| 208 |
callers can fall back to the default ``mkisofs`` functionality by setting |
| 209 |
the ``useRockRidge`` instance variable to ``False``. Note, however, that |
| 210 |
this option is not well-tested. |
| 211 |
|
| 212 |
**Where Files and Directories are Placed in the Image** |
| 213 |
|
| 214 |
Although this class is implemented in terms of the ``mkisofs`` program, |
| 215 |
its standard "image contents" semantics are slightly different than the original |
| 216 |
``mkisofs`` semantics. The difference is that files and directories are |
| 217 |
added to the image with some additional information about their source |
| 218 |
directory kept intact. |
| 219 |
|
| 220 |
As an example, suppose you add the file ``/etc/profile`` to your image and |
| 221 |
you do not configure a graft point. The file ``/profile`` will be created |
| 222 |
in the image. The behavior for directories is similar. For instance, |
| 223 |
suppose that you add ``/etc/X11`` to the image and do not configure a |
| 224 |
graft point. In this case, the directory ``/X11`` will be created in the |
| 225 |
image, even if the original ``/etc/X11`` directory is empty. I{This |
| 226 |
behavior differs from the standard ``mkisofs`` behavior!} |
| 227 |
|
| 228 |
If a graft point is configured, it will be used to modify the point at |
| 229 |
which a file or directory is added into an image. Using the examples |
| 230 |
from above, let's assume you set a graft point of ``base`` when adding |
| 231 |
``/etc/profile`` and ``/etc/X11`` to your image. In this case, the file |
| 232 |
``/base/profile`` and the directory ``/base/X11`` would be added to the |
| 233 |
image. |
| 234 |
|
| 235 |
I feel that this behavior is more consistent than the original ``mkisofs`` |
| 236 |
behavior. However, to be fair, it is not quite as flexible, and some |
| 237 |
users might not like it. For this reason, the ``contentsOnly`` parameter |
| 238 |
to the :any:`addEntry` method can be used to revert to the original behavior |
| 239 |
if desired. |
| 240 |
|
| 241 |
""" |
| 242 |
|
| 243 |
############## |
| 244 |
# Constructor |
| 245 |
############## |
| 246 |
|
| 247 |
def __init__(self, device=None, boundaries=None, graftPoint=None): |
| 248 |
""" |
| 249 |
Initializes an empty ISO image object. |
| 250 |
|
| 251 |
Only the most commonly-used configuration items can be set using this |
| 252 |
constructor. If you have a need to change the others, do so immediately |
| 253 |
after creating your object. |
| 254 |
|
| 255 |
The device and boundaries values are both required in order to write |
| 256 |
multisession discs. If either is missing or ``None``, a multisession disc |
| 257 |
will not be written. The boundaries tuple is in terms of ISO sectors, as |
| 258 |
built by an image writer class and returned in a ``writer.MediaCapacity`` |
| 259 |
object. |
| 260 |
|
| 261 |
The boundaries parameter is a tuple of ``(last_sess_start, next_sess_start)``, |
| 262 |
as returned from ``cdrecord -msinfo``. |
| 263 |
|
| 264 |
Args: |
| 265 |
device (Either be a filesystem path or a SCSI address): Name of the device that the image will be written to |
| 266 |
boundaries: Session boundaries as required by ``mkisofs``, or ``None`` |
| 267 |
graftPoint (String representing a graft point path (see :any:`addEntry`)): Default graft point for this page |
| 268 |
""" |
| 269 |
self._device = None |
| 270 |
self._boundaries = None |
| 271 |
self._graftPoint = None |
| 272 |
self._useRockRidge = True |
| 273 |
self._applicationId = None |
| 274 |
self._biblioFile = None |
| 275 |
self._publisherId = None |
| 276 |
self._preparerId = None |
| 277 |
self._volumeId = None |
| 278 |
self.entries = {} |
| 279 |
self.device = device |
| 280 |
self.boundaries = boundaries |
| 281 |
self.graftPoint = graftPoint |
| 282 |
self.useRockRidge = True |
| 283 |
self.applicationId = None |
| 284 |
self.biblioFile = None |
| 285 |
self.publisherId = None |
| 286 |
self.preparerId = None |
| 287 |
self.volumeId = None |
| 288 |
logger.debug("Created new ISO image object.") |
| 289 |
|
| 290 |
############# |
| 291 |
# Properties |
| 292 |
############# |
| 293 |
|
| 294 |
def _setDevice(self, value): |
| 295 |
""" |
| 296 |
Property target used to set the device value. |
| 297 |
If not ``None``, the value can be either an absolute path or a SCSI id. |
| 298 |
Raises: |
| 299 |
ValueError: If the value is not valid |
| 300 |
""" |
| 301 |
try: |
| 302 |
if value is None: |
| 303 |
self._device = None |
| 304 |
else: |
| 305 |
if os.path.isabs(value) or posixpath.isabs(value): # Python 3.13+ does not treat / as absolute on Windows |
| 306 |
self._device = value |
| 307 |
else: |
| 308 |
self._device = validateScsiId(value) |
| 309 |
except ValueError: |
| 310 |
raise ValueError("Device must either be an absolute path or a valid SCSI id.") |
| 311 |
|
| 312 |
def _getDevice(self): |
| 313 |
""" |
| 314 |
Property target used to get the device value. |
| 315 |
""" |
| 316 |
return self._device |
| 317 |
|
| 318 |
def _setBoundaries(self, value): |
| 319 |
""" |
| 320 |
Property target used to set the boundaries tuple. |
| 321 |
If not ``None``, the value must be a tuple of two integers. |
| 322 |
Raises: |
| 323 |
ValueError: If the tuple values are not integers |
| 324 |
IndexError: If the tuple does not contain enough elements |
| 325 |
""" |
| 326 |
if value is None: |
| 327 |
self._boundaries = None |
| 328 |
else: |
| 329 |
self._boundaries = (int(value[0]), int(value[1])) |
| 330 |
|
| 331 |
def _getBoundaries(self): |
| 332 |
""" |
| 333 |
Property target used to get the boundaries value. |
| 334 |
""" |
| 335 |
return self._boundaries |
| 336 |
|
| 337 |
def _setGraftPoint(self, value): |
| 338 |
""" |
| 339 |
Property target used to set the graft point. |
| 340 |
The value must be a non-empty string if it is not ``None``. |
| 341 |
Raises: |
| 342 |
ValueError: If the value is an empty string |
| 343 |
""" |
| 344 |
if value is not None: |
| 345 |
if len(value) < 1: |
| 346 |
raise ValueError("The graft point must be a non-empty string.") |
| 347 |
self._graftPoint = value |
| 348 |
|
| 349 |
def _getGraftPoint(self): |
| 350 |
""" |
| 351 |
Property target used to get the graft point. |
| 352 |
""" |
| 353 |
return self._graftPoint |
| 354 |
|
| 355 |
def _setUseRockRidge(self, value): |
| 356 |
""" |
| 357 |
Property target used to set the use RockRidge flag. |
| 358 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 359 |
""" |
| 360 |
if value: |
| 361 |
self._useRockRidge = True |
| 362 |
else: |
| 363 |
self._useRockRidge = False |
| 364 |
|
| 365 |
def _getUseRockRidge(self): |
| 366 |
""" |
| 367 |
Property target used to get the use RockRidge flag. |
| 368 |
""" |
| 369 |
return self._useRockRidge |
| 370 |
|
| 371 |
def _setApplicationId(self, value): |
| 372 |
""" |
| 373 |
Property target used to set the application id. |
| 374 |
The value must be a non-empty string if it is not ``None``. |
| 375 |
Raises: |
| 376 |
ValueError: If the value is an empty string |
| 377 |
""" |
| 378 |
if value is not None: |
| 379 |
if len(value) < 1: |
| 380 |
raise ValueError("The application id must be a non-empty string.") |
| 381 |
self._applicationId = value |
| 382 |
|
| 383 |
def _getApplicationId(self): |
| 384 |
""" |
| 385 |
Property target used to get the application id. |
| 386 |
""" |
| 387 |
return self._applicationId |
| 388 |
|
| 389 |
def _setBiblioFile(self, value): |
| 390 |
""" |
| 391 |
Property target used to set the biblio file. |
| 392 |
The value must be a non-empty string if it is not ``None``. |
| 393 |
Raises: |
| 394 |
ValueError: If the value is an empty string |
| 395 |
""" |
| 396 |
if value is not None: |
| 397 |
if len(value) < 1: |
| 398 |
raise ValueError("The biblio file must be a non-empty string.") |
| 399 |
self._biblioFile = value |
| 400 |
|
| 401 |
def _getBiblioFile(self): |
| 402 |
""" |
| 403 |
Property target used to get the biblio file. |
| 404 |
""" |
| 405 |
return self._biblioFile |
| 406 |
|
| 407 |
def _setPublisherId(self, value): |
| 408 |
""" |
| 409 |
Property target used to set the publisher id. |
| 410 |
The value must be a non-empty string if it is not ``None``. |
| 411 |
Raises: |
| 412 |
ValueError: If the value is an empty string |
| 413 |
""" |
| 414 |
if value is not None: |
| 415 |
if len(value) < 1: |
| 416 |
raise ValueError("The publisher id must be a non-empty string.") |
| 417 |
self._publisherId = value |
| 418 |
|
| 419 |
def _getPublisherId(self): |
| 420 |
""" |
| 421 |
Property target used to get the publisher id. |
| 422 |
""" |
| 423 |
return self._publisherId |
| 424 |
|
| 425 |
def _setPreparerId(self, value): |
| 426 |
""" |
| 427 |
Property target used to set the preparer id. |
| 428 |
The value must be a non-empty string if it is not ``None``. |
| 429 |
Raises: |
| 430 |
ValueError: If the value is an empty string |
| 431 |
""" |
| 432 |
if value is not None: |
| 433 |
if len(value) < 1: |
| 434 |
raise ValueError("The preparer id must be a non-empty string.") |
| 435 |
self._preparerId = value |
| 436 |
|
| 437 |
def _getPreparerId(self): |
| 438 |
""" |
| 439 |
Property target used to get the preparer id. |
| 440 |
""" |
| 441 |
return self._preparerId |
| 442 |
|
| 443 |
def _setVolumeId(self, value): |
| 444 |
""" |
| 445 |
Property target used to set the volume id. |
| 446 |
The value must be a non-empty string if it is not ``None``. |
| 447 |
Raises: |
| 448 |
ValueError: If the value is an empty string |
| 449 |
""" |
| 450 |
if value is not None: |
| 451 |
if len(value) < 1: |
| 452 |
raise ValueError("The volume id must be a non-empty string.") |
| 453 |
self._volumeId = value |
| 454 |
|
| 455 |
def _getVolumeId(self): |
| 456 |
""" |
| 457 |
Property target used to get the volume id. |
| 458 |
""" |
| 459 |
return self._volumeId |
| 460 |
|
| 461 |
device = property(_getDevice, _setDevice, None, "Device that image will be written to (device path or SCSI id).") |
| 462 |
boundaries = property(_getBoundaries, _setBoundaries, None, "Session boundaries as required by ``mkisofs``.") |
| 463 |
graftPoint = property(_getGraftPoint, _setGraftPoint, None, "Default image-wide graft point (see :any:`addEntry` for details).") |
| 464 |
useRockRidge = property(_getUseRockRidge, _setUseRockRidge, None, "Indicates whether to use RockRidge (default is ``True``).") |
| 465 |
applicationId = property( |
| 466 |
_getApplicationId, _setApplicationId, None, "Optionally specifies the ISO header application id value." |
| 467 |
) |
| 468 |
biblioFile = property(_getBiblioFile, _setBiblioFile, None, "Optionally specifies the ISO bibliographic file name.") |
| 469 |
publisherId = property(_getPublisherId, _setPublisherId, None, "Optionally specifies the ISO header publisher id value.") |
| 470 |
preparerId = property(_getPreparerId, _setPreparerId, None, "Optionally specifies the ISO header preparer id value.") |
| 471 |
volumeId = property(_getVolumeId, _setVolumeId, None, "Optionally specifies the ISO header volume id value.") |
| 472 |
|
| 473 |
######################### |
| 474 |
# General public methods |
| 475 |
######################### |
| 476 |
|
| 477 |
def addEntry(self, path, graftPoint=None, override=False, contentsOnly=False): |
| 478 |
""" |
| 479 |
Adds an individual file or directory into the ISO image. |
| 480 |
|
| 481 |
The path must exist and must be a file or a directory. By default, the |
| 482 |
entry will be placed into the image at the root directory, but this |
| 483 |
behavior can be overridden using the ``graftPoint`` parameter or instance |
| 484 |
variable. |
| 485 |
|
| 486 |
You can use the ``contentsOnly`` behavior to revert to the "original" |
| 487 |
``mkisofs`` behavior for adding directories, which is to add only the |
| 488 |
items within the directory, and not the directory itself. |
| 489 |
|
| 490 |
*Note:* Things get *odd* if you try to add a directory to an image that |
| 491 |
will be written to a multisession disc, and the same directory already |
| 492 |
exists in an earlier session on that disc. Not all of the data gets |
| 493 |
written. You really wouldn't want to do this anyway, I guess. |
| 494 |
|
| 495 |
*Note:* An exception will be thrown if the path has already been added to |
| 496 |
the image, unless the ``override`` parameter is set to ``True``. |
| 497 |
|
| 498 |
*Note:* The method ``graftPoints`` parameter overrides the object-wide |
| 499 |
instance variable. If neither the method parameter or object-wide value |
| 500 |
is set, the path will be written at the image root. The graft point |
| 501 |
behavior is determined by the value which is in effect I{at the time this |
| 502 |
method is called}, so you *must* set the object-wide value before |
| 503 |
calling this method for the first time, or your image may not be |
| 504 |
consistent. |
| 505 |
|
| 506 |
*Note:* You *cannot* use the local ``graftPoint`` parameter to "turn off" |
| 507 |
an object-wide instance variable by setting it to ``None``. Python's |
| 508 |
default argument functionality buys us a lot, but it can't make this |
| 509 |
method psychic. :) |
| 510 |
|
| 511 |
Args: |
| 512 |
path (String representing a path on disk): File or directory to be added to the image |
| 513 |
graftPoint (String representing a graft point path, as described above): Graft point to be used when adding this entry |
| 514 |
override (Boolean true/false): Override an existing entry with the same path |
| 515 |
contentsOnly (Boolean true/false): Add directory contents only (standard ``mkisofs`` behavior) |
| 516 |
Raises: |
| 517 |
ValueError: If path is not a file or directory, or does not exist |
| 518 |
ValueError: If the path has already been added, and override is not set |
| 519 |
ValueError: If a path cannot be encoded properly |
| 520 |
""" |
| 521 |
path = encodePath(path) |
| 522 |
if not override: |
| 523 |
if path in list(self.entries.keys()): |
| 524 |
raise ValueError("Path has already been added to the image.") |
| 525 |
if os.path.islink(path): |
| 526 |
raise ValueError("Path must not be a link.") |
| 527 |
if os.path.isdir(path): |
| 528 |
if graftPoint is not None: |
| 529 |
if contentsOnly: |
| 530 |
self.entries[path] = graftPoint |
| 531 |
else: |
| 532 |
self.entries[path] = pathJoin(graftPoint, os.path.basename(path)) |
| 533 |
elif self.graftPoint is not None: |
| 534 |
if contentsOnly: |
| 535 |
self.entries[path] = self.graftPoint |
| 536 |
else: |
| 537 |
self.entries[path] = pathJoin(self.graftPoint, os.path.basename(path)) |
| 538 |
else: |
| 539 |
if contentsOnly: |
| 540 |
self.entries[path] = None |
| 541 |
else: |
| 542 |
self.entries[path] = os.path.basename(path) |
| 543 |
elif os.path.isfile(path): |
| 544 |
if graftPoint is not None: |
| 545 |
self.entries[path] = graftPoint |
| 546 |
elif self.graftPoint is not None: |
| 547 |
self.entries[path] = self.graftPoint |
| 548 |
else: |
| 549 |
self.entries[path] = None |
| 550 |
else: |
| 551 |
raise ValueError("Path must be a file or a directory.") |
| 552 |
|
| 553 |
def getEstimatedSize(self): |
| 554 |
""" |
| 555 |
Returns the estimated size (in bytes) of the ISO image. |
| 556 |
|
| 557 |
This is implemented via the ``-print-size`` option to ``mkisofs``, so it |
| 558 |
might take a bit of time to execute. However, the result is as accurate |
| 559 |
as we can get, since it takes into account all of the ISO overhead, the |
| 560 |
true cost of directories in the structure, etc, etc. |
| 561 |
|
| 562 |
Returns: |
| 563 |
Estimated size of the image, in bytes |
| 564 |
|
| 565 |
Raises: |
| 566 |
IOError: If there is a problem calling ``mkisofs`` |
| 567 |
ValueError: If there are no filesystem entries in the image |
| 568 |
""" |
| 569 |
if len(list(self.entries.keys())) == 0: |
| 570 |
raise ValueError("Image does not contain any entries.") |
| 571 |
return self._getEstimatedSize(self.entries) |
| 572 |
|
| 573 |
def _getEstimatedSize(self, entries): |
| 574 |
""" |
| 575 |
Returns the estimated size (in bytes) for the passed-in entries dictionary. |
| 576 |
Returns: |
| 577 |
Estimated size of the image, in bytes |
| 578 |
Raises: |
| 579 |
IOError: If there is a problem calling ``mkisofs`` |
| 580 |
""" |
| 581 |
args = self._buildSizeArgs(entries) |
| 582 |
command = resolveCommand(MKISOFS_COMMAND) |
| 583 |
(result, output) = executeCommand(command, args, returnOutput=True, ignoreStderr=True) |
| 584 |
if result != 0: |
| 585 |
raise OSError("Error (%d) executing mkisofs command to estimate size." % result) |
| 586 |
if len(output) != 1: |
| 587 |
raise OSError("Unable to parse mkisofs output.") |
| 588 |
try: |
| 589 |
sectors = float(output[0]) |
| 590 |
return convertSize(sectors, UNIT_SECTORS, UNIT_BYTES) |
| 591 |
except Exception: |
| 592 |
raise OSError("Unable to parse mkisofs output.") |
| 593 |
|
| 594 |
def writeImage(self, imagePath): |
| 595 |
""" |
| 596 |
Writes this image to disk using the image path. |
| 597 |
|
| 598 |
Args: |
| 599 |
imagePath (String representing a path on disk): Path to write image out as |
| 600 |
Raises: |
| 601 |
IOError: If there is an error writing the image to disk |
| 602 |
ValueError: If there are no filesystem entries in the image |
| 603 |
ValueError: If a path cannot be encoded properly |
| 604 |
""" |
| 605 |
imagePath = encodePath(imagePath) |
| 606 |
if len(list(self.entries.keys())) == 0: |
| 607 |
raise ValueError("Image does not contain any entries.") |
| 608 |
args = self._buildWriteArgs(self.entries, imagePath) |
| 609 |
command = resolveCommand(MKISOFS_COMMAND) |
| 610 |
(result, _) = executeCommand(command, args, returnOutput=False) |
| 611 |
if result != 0: |
| 612 |
raise OSError("Error (%d) executing mkisofs command to build image." % result) |
| 613 |
|
| 614 |
######################################### |
| 615 |
# Methods used to build mkisofs commands |
| 616 |
######################################### |
| 617 |
|
| 618 |
@staticmethod |
| 619 |
def _buildDirEntries(entries): |
| 620 |
""" |
| 621 |
Uses an entries dictionary to build a list of directory locations for use |
| 622 |
by ``mkisofs``. |
| 623 |
|
| 624 |
We build a list of entries that can be passed to ``mkisofs``. Each entry is |
| 625 |
either raw (if no graft point was configured) or in graft-point form as |
| 626 |
described above (if a graft point was configured). The dictionary keys |
| 627 |
are the path names, and the values are the graft points, if any. |
| 628 |
|
| 629 |
Args: |
| 630 |
entries: Dictionary of image entries (i.e. self.entries) |
| 631 |
|
| 632 |
Returns: |
| 633 |
List of directory locations for use by ``mkisofs`` |
| 634 |
""" |
| 635 |
dirEntries = [] |
| 636 |
for key in list(entries.keys()): |
| 637 |
if entries[key] is None: |
| 638 |
dirEntries.append(key) |
| 639 |
else: |
| 640 |
dirEntries.append("%s/=%s" % (entries[key].strip("/"), key)) |
| 641 |
return dirEntries |
| 642 |
|
| 643 |
def _buildGeneralArgs(self): |
| 644 |
""" |
| 645 |
Builds a list of general arguments to be passed to a ``mkisofs`` command. |
| 646 |
|
| 647 |
The various instance variables (``applicationId``, etc.) are filled into |
| 648 |
the list of arguments if they are set. |
| 649 |
By default, we will build a RockRidge disc. If you decide to change |
| 650 |
this, think hard about whether you know what you're doing. This option |
| 651 |
is not well-tested. |
| 652 |
|
| 653 |
Returns: |
| 654 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 655 |
""" |
| 656 |
args = [] |
| 657 |
if self.applicationId is not None: |
| 658 |
args.append("-A") |
| 659 |
args.append(self.applicationId) |
| 660 |
if self.biblioFile is not None: |
| 661 |
args.append("-biblio") |
| 662 |
args.append(self.biblioFile) |
| 663 |
if self.publisherId is not None: |
| 664 |
args.append("-publisher") |
| 665 |
args.append(self.publisherId) |
| 666 |
if self.preparerId is not None: |
| 667 |
args.append("-p") |
| 668 |
args.append(self.preparerId) |
| 669 |
if self.volumeId is not None: |
| 670 |
args.append("-V") |
| 671 |
args.append(self.volumeId) |
| 672 |
return args |
| 673 |
|
| 674 |
def _buildSizeArgs(self, entries): |
| 675 |
""" |
| 676 |
Builds a list of arguments to be passed to a ``mkisofs`` command. |
| 677 |
|
| 678 |
The various instance variables (``applicationId``, etc.) are filled into |
| 679 |
the list of arguments if they are set. The command will be built to just |
| 680 |
return size output (a simple count of sectors via the ``-print-size`` option), |
| 681 |
rather than an image file on disk. |
| 682 |
|
| 683 |
By default, we will build a RockRidge disc. If you decide to change |
| 684 |
this, think hard about whether you know what you're doing. This option |
| 685 |
is not well-tested. |
| 686 |
|
| 687 |
Args: |
| 688 |
entries: Dictionary of image entries (i.e. self.entries) |
| 689 |
|
| 690 |
Returns: |
| 691 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 692 |
""" |
| 693 |
args = self._buildGeneralArgs() |
| 694 |
args.append("-print-size") |
| 695 |
args.append("-graft-points") |
| 696 |
if self.useRockRidge: |
| 697 |
args.append("-r") |
| 698 |
if self.device is not None and self.boundaries is not None: |
| 699 |
args.append("-C") |
| 700 |
args.append("%d,%d" % (self.boundaries[0], self.boundaries[1])) |
| 701 |
args.append("-M") |
| 702 |
args.append(self.device) |
| 703 |
args.extend(self._buildDirEntries(entries)) |
| 704 |
return args |
| 705 |
|
| 706 |
def _buildWriteArgs(self, entries, imagePath): |
| 707 |
""" |
| 708 |
Builds a list of arguments to be passed to a ``mkisofs`` command. |
| 709 |
|
| 710 |
The various instance variables (``applicationId``, etc.) are filled into |
| 711 |
the list of arguments if they are set. The command will be built to write |
| 712 |
an image to disk. |
| 713 |
|
| 714 |
By default, we will build a RockRidge disc. If you decide to change |
| 715 |
this, think hard about whether you know what you're doing. This option |
| 716 |
is not well-tested. |
| 717 |
|
| 718 |
Args: |
| 719 |
entries: Dictionary of image entries (i.e. self.entries) |
| 720 |
|
| 721 |
imagePath (String representing a path on disk): Path to write image out as |
| 722 |
Returns: |
| 723 |
List suitable for passing to :any:`util.executeCommand` as ``args`` |
| 724 |
""" |
| 725 |
args = self._buildGeneralArgs() |
| 726 |
args.append("-graft-points") |
| 727 |
if self.useRockRidge: |
| 728 |
args.append("-r") |
| 729 |
args.append("-o") |
| 730 |
args.append(imagePath) |
| 731 |
if self.device is not None and self.boundaries is not None: |
| 732 |
args.append("-C") |
| 733 |
args.append("%d,%d" % (self.boundaries[0], self.boundaries[1])) |
| 734 |
args.append("-M") |
| 735 |
args.append(self.device) |
| 736 |
args.extend(self._buildDirEntries(entries)) |
| 737 |
return args |