Debian Codegraph @

src/CedarBackup3/writers/dvdwriter.py

raw
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) 2007-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 DVD writer devices.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides functionality related to DVD writer devices.
39
40 Module Attributes
41 =================
42
43 Attributes:
44 MEDIA_DVDPLUSR: Constant representing DVD+R media
45 MEDIA_DVDPLUSRW: Constant representing DVD+RW media
46
47 :author: Kenneth J. Pronovici <[email protected]>
48 :author: Dmitry Rutsky <[email protected]>
49 """
50
51 ########################################################################
52 # Imported modules
53 ########################################################################
54
55 import logging
56 import os
57 import posixpath
58 import re
59 import tempfile
60 import time
61
62 from CedarBackup3.util import (
63 UNIT_BYTES,
64 UNIT_GBYTES,
65 UNIT_SECTORS,
66 convertSize,
67 displayBytes,
68 encodePath,
69 executeCommand,
70 resolveCommand,
71 )
72 from CedarBackup3.writers.util import IsoImage, validateDevice, validateDriveSpeed
73
74 ########################################################################
75 # Module-wide constants and variables
76 ########################################################################
77
78 logger = logging.getLogger("CedarBackup3.log.writers.dvdwriter")
79
80 MEDIA_DVDPLUSR = 1
81 MEDIA_DVDPLUSRW = 2
82
83 GROWISOFS_COMMAND = ["growisofs"]
84 EJECT_COMMAND = ["eject"]
85
86
87 ########################################################################
88 # MediaDefinition class definition
89 ########################################################################
90
91
92 class MediaDefinition:
93 """
94 Class encapsulating information about DVD media definitions.
95
96 The following media types are accepted:
97
98 - ``MEDIA_DVDPLUSR``: DVD+R media (4.4 GB capacity)
99 - ``MEDIA_DVDPLUSRW``: DVD+RW media (4.4 GB capacity)
100
101 Note that the capacity attribute returns capacity in terms of ISO sectors
102 (``util.ISO_SECTOR_SIZE)``. This is for compatibility with the CD writer
103 functionality.
104
105 The capacities are 4.4 GB because Cedar Backup deals in "true" gigabytes
106 of 1024*1024*1024 bytes per gigabyte.
107
108 """
109
110 def __init__(self, mediaType):
111 """
112 Creates a media definition for the indicated media type.
113 Args:
114 mediaType: Type of the media, as discussed above
115 Raises:
116 ValueError: If the media type is unknown or unsupported
117 """
118 self._mediaType = None
119 self._rewritable = False
120 self._capacity = 0.0
121 self._setValues(mediaType)
122
123 def _setValues(self, mediaType):
124 """
125 Sets values based on media type.
126 Args:
127 mediaType: Type of the media, as discussed above
128 Raises:
129 ValueError: If the media type is unknown or unsupported
130 """
131 if mediaType not in [MEDIA_DVDPLUSR, MEDIA_DVDPLUSRW]:
132 raise ValueError("Invalid media type %d." % mediaType)
133 self._mediaType = mediaType
134 if self._mediaType == MEDIA_DVDPLUSR:
135 self._rewritable = False
136 self._capacity = convertSize(4.4, UNIT_GBYTES, UNIT_SECTORS) # 4.4 "true" GB = 4.7 "marketing" GB
137 elif self._mediaType == MEDIA_DVDPLUSRW:
138 self._rewritable = True
139 self._capacity = convertSize(4.4, UNIT_GBYTES, UNIT_SECTORS) # 4.4 "true" GB = 4.7 "marketing" GB
140
141 def _getMediaType(self):
142 """
143 Property target used to get the media type value.
144 """
145 return self._mediaType
146
147 def _getRewritable(self):
148 """
149 Property target used to get the rewritable flag value.
150 """
151 return self._rewritable
152
153 def _getCapacity(self):
154 """
155 Property target used to get the capacity value.
156 """
157 return self._capacity
158
159 mediaType = property(_getMediaType, None, None, doc="Configured media type.")
160 rewritable = property(_getRewritable, None, None, doc="Boolean indicating whether the media is rewritable.")
161 capacity = property(_getCapacity, None, None, doc="Total capacity of media in 2048-byte sectors.")
162
163
164 ########################################################################
165 # MediaCapacity class definition
166 ########################################################################
167
168
169 class MediaCapacity:
170 """
171 Class encapsulating information about DVD media capacity.
172
173 Space used and space available do not include any information about media
174 lead-in or other overhead.
175
176 """
177
178 def __init__(self, bytesUsed, bytesAvailable):
179 """
180 Initializes a capacity object.
181
182 Raises:
183 ValueError: If the bytes used and available values are not floats
184 """
185 self._bytesUsed = float(bytesUsed)
186 self._bytesAvailable = float(bytesAvailable)
187
188 def __str__(self):
189 """
190 Informal string representation for class instance.
191 """
192 return "utilized %s of %s (%.2f%%)" % (displayBytes(self.bytesUsed), displayBytes(self.totalCapacity), self.utilized)
193
194 def _getBytesUsed(self):
195 """
196 Property target used to get the bytes-used value.
197 """
198 return self._bytesUsed
199
200 def _getBytesAvailable(self):
201 """
202 Property target available to get the bytes-available value.
203 """
204 return self._bytesAvailable
205
206 def _getTotalCapacity(self):
207 """
208 Property target to get the total capacity (used + available).
209 """
210 return self.bytesUsed + self.bytesAvailable
211
212 def _getUtilized(self):
213 """
214 Property target to get the percent of capacity which is utilized.
215 """
216 if self.bytesAvailable <= 0.0:
217 return 100.0
218 elif self.bytesUsed <= 0.0:
219 return 0.0
220 return (self.bytesUsed / self.totalCapacity) * 100.0
221
222 bytesUsed = property(_getBytesUsed, None, None, doc="Space used on disc, in bytes.")
223 bytesAvailable = property(_getBytesAvailable, None, None, doc="Space available on disc, in bytes.")
224 totalCapacity = property(_getTotalCapacity, None, None, doc="Total capacity of the disc, in bytes.")
225 utilized = property(_getUtilized, None, None, "Percentage of the total capacity which is utilized.")
226
227
228 ########################################################################
229 # _ImageProperties class definition
230 ########################################################################
231
232
233 class _ImageProperties:
234 """
235 Simple value object to hold image properties for ``DvdWriter``.
236 """
237
238 def __init__(self):
239 self.newDisc = False
240 self.tmpdir = None
241 self.mediaLabel = None
242 self.entries = None # dict mapping path to graft point
243
244
245 ########################################################################
246 # DvdWriter class definition
247 ########################################################################
248
249
250 class DvdWriter:
251 ######################
252 # Class documentation
253 ######################
254
255 """
256 Class representing a device that knows how to write some kinds of DVD media.
257
258 **Summary**
259
260 This is a class representing a device that knows how to write some kinds
261 of DVD media. It provides common operations for the device, such as
262 ejecting the media and writing data to the media.
263
264 This class is implemented in terms of the ``eject`` and ``growisofs``
265 utilities, all of which should be available on most UN*X platforms.
266
267 **Image Writer Interface**
268
269 The following methods make up the "image writer" interface shared
270 with other kinds of writers::
271
272 __init__
273 initializeImage()
274 addImageEntry()
275 writeImage()
276 setImageNewDisc()
277 retrieveCapacity()
278 getEstimatedImageSize()
279
280 Only these methods will be used by other Cedar Backup functionality
281 that expects a compatible image writer.
282
283 The media attribute is also assumed to be available.
284
285 Unlike the ``CdWriter``, the ``DvdWriter`` can only operate in terms of
286 filesystem devices, not SCSI devices. So, although the constructor
287 interface accepts a SCSI device parameter for the sake of compatibility,
288 it's not used.
289
290 **Media Types**
291
292 This class knows how to write to DVD+R and DVD+RW media, represented
293 by the following constants:
294
295 - ``MEDIA_DVDPLUSR``: DVD+R media (4.4 GB capacity)
296 - ``MEDIA_DVDPLUSRW``: DVD+RW media (4.4 GB capacity)
297
298 The difference is that DVD+RW media can be rewritten, while DVD+R media
299 cannot be (although at present, ``DvdWriter`` does not really
300 differentiate between rewritable and non-rewritable media).
301
302 The capacities are 4.4 GB because Cedar Backup deals in "true" gigabytes
303 of 1024*1024*1024 bytes per gigabyte.
304
305 The underlying ``growisofs`` utility does support other kinds of media
306 (including DVD-R, DVD-RW and BlueRay) which work somewhat differently
307 than standard DVD+R and DVD+RW media. I don't support these other kinds
308 of media because I haven't had any opportunity to work with them. The
309 same goes for dual-layer media of any type.
310
311 **Device Attributes vs. Media Attributes**
312
313 As with the cdwriter functionality, a given dvdwriter instance has two
314 different kinds of attributes associated with it. I call these device
315 attributes and media attributes.
316
317 Device attributes are things which can be determined without looking at
318 the media. Media attributes are attributes which vary depending on the
319 state of the media. In general, device attributes are available via
320 instance variables and are constant over the life of an object, while
321 media attributes can be retrieved through method calls.
322
323 Compared to cdwriters, dvdwriters have very few attributes. This is due
324 to differences between the way ``growisofs`` works relative to
325 ``cdrecord``.
326
327 **Media Capacity**
328
329 One major difference between the ``cdrecord``/``mkisofs`` utilities used by
330 the cdwriter class and the ``growisofs`` utility used here is that the
331 process of estimating remaining capacity and image size is more
332 straightforward with ``cdrecord``/``mkisofs`` than with ``growisofs``.
333
334 In this class, remaining capacity is calculated by asking doing a dry run
335 of ``growisofs`` and grabbing some information from the output of that
336 command. Image size is estimated by asking the ``IsoImage`` class for an
337 estimate and then adding on a "fudge factor" determined through
338 experimentation.
339
340 **Testing**
341
342 It's rather difficult to test this code in an automated fashion, even if
343 you have access to a physical DVD writer drive. It's even more difficult
344 to test it if you are running on some build daemon (think of a Debian
345 autobuilder) which can't be expected to have any hardware or any media
346 that you could write to.
347
348 Because of this, some of the implementation below is in terms of static
349 methods that are supposed to take defined actions based on their
350 arguments. Public methods are then implemented in terms of a series of
351 calls to simplistic static methods. This way, we can test as much as
352 possible of the "difficult" functionality via testing the static methods,
353 while hoping that if the static methods are called appropriately, things
354 will work properly. It's not perfect, but it's much better than no
355 testing at all.
356
357 """
358
359 ##############
360 # Constructor
361 ##############
362
363 def __init__(
364 self,
365 device,
366 scsiId=None,
367 driveSpeed=None,
368 mediaType=MEDIA_DVDPLUSRW,
369 noEject=False,
370 refreshMediaDelay=0,
371 ejectDelay=0,
372 unittest=False,
373 ):
374 """
375 Initializes a DVD writer object.
376
377 Since ``growisofs`` can only address devices using the device path (i.e.
378 ``/dev/dvd``), the hardware id will always be set based on the device. If
379 passed in, it will be saved for reference purposes only.
380
381 We have no way to query the device to ask whether it has a tray or can be
382 safely opened and closed. So, the ``noEject`` flag is used to set these
383 values. If ``noEject=False``, then we assume a tray exists and open/close
384 is safe. If ``noEject=True``, then we assume that there is no tray and
385 open/close is not safe.
386
387 The SCSI id, if provided, is in the form ``[<method>:]scsibus,target,lun``.
388
389 *Note:* The ``unittest`` parameter should never be set to ``True``
390 outside of Cedar Backup code. It is intended for use in unit testing
391 Cedar Backup internals and has no other sensible purpose.
392
393 Args:
394 device: Absolute path to the writer filesystem device, like ``/dev/dvd``
395 scsiId: SCSI id for the device (optional, for reference only)
396 driveSpeed: Speed at which the drive writes, like 2 for a 2x device, or None for device default
397 mediaType: Type of the media that is assumed to be in the drive
398 noEject (Boolean true/false): Tells Cedar Backup that the device cannot safely be ejected
399 refreshMediaDelay (Integer >= 0): Refresh media delay to use, if any
400 ejectDelay (Integer >= 0): Eject delay to use, if any
401 unittest (Boolean true/false): Turns off certain validations, for use in unit testing
402 Raises:
403 ValueError: If the device is not valid for some reason
404 ValueError: If the SCSI id is not in a valid form
405 ValueError: If the drive speed is not an integer >= 1
406 """
407 if scsiId is not None:
408 logger.warning("SCSI id [%s] will be ignored by DvdWriter.", scsiId)
409 self._image = None # optionally filled in by initializeImage()
410 self._device = validateDevice(device, unittest)
411 self._scsiId = scsiId # not validated, because it's just for reference
412 self._driveSpeed = validateDriveSpeed(driveSpeed)
413 self._media = MediaDefinition(mediaType)
414 self._refreshMediaDelay = refreshMediaDelay
415 self._ejectDelay = ejectDelay
416 if noEject:
417 self._deviceHasTray = False
418 self._deviceCanEject = False
419 else:
420 self._deviceHasTray = True # just assume
421 self._deviceCanEject = True # just assume
422
423 #############
424 # Properties
425 #############
426
427 def _getDevice(self):
428 """
429 Property target used to get the device value.
430 """
431 return self._device
432
433 def _getScsiId(self):
434 """
435 Property target used to get the SCSI id value.
436 """
437 return self._scsiId
438
439 def _getHardwareId(self):
440 """
441 Property target used to get the hardware id value.
442 """
443 return self._device
444
445 def _getDriveSpeed(self):
446 """
447 Property target used to get the drive speed.
448 """
449 return self._driveSpeed
450
451 def _getMedia(self):
452 """
453 Property target used to get the media description.
454 """
455 return self._media
456
457 def _getDeviceHasTray(self):
458 """
459 Property target used to get the device-has-tray flag.
460 """
461 return self._deviceHasTray
462
463 def _getDeviceCanEject(self):
464 """
465 Property target used to get the device-can-eject flag.
466 """
467 return self._deviceCanEject
468
469 def _getRefreshMediaDelay(self):
470 """
471 Property target used to get the configured refresh media delay, in seconds.
472 """
473 return self._refreshMediaDelay
474
475 def _getEjectDelay(self):
476 """
477 Property target used to get the configured eject delay, in seconds.
478 """
479 return self._ejectDelay
480
481 device = property(_getDevice, None, None, doc="Filesystem device name for this writer.")
482 scsiId = property(_getScsiId, None, None, doc="SCSI id for the device (saved for reference only).")
483 hardwareId = property(_getHardwareId, None, None, doc="Hardware id for this writer (always the device path).")
484 driveSpeed = property(_getDriveSpeed, None, None, doc="Speed at which the drive writes.")
485 media = property(_getMedia, None, None, doc="Definition of media that is expected to be in the device.")
486 deviceHasTray = property(_getDeviceHasTray, None, None, doc="Indicates whether the device has a media tray.")
487 deviceCanEject = property(_getDeviceCanEject, None, None, doc="Indicates whether the device supports ejecting its media.")
488 refreshMediaDelay = property(_getRefreshMediaDelay, None, None, doc="Refresh media delay, in seconds.")
489 ejectDelay = property(_getEjectDelay, None, None, doc="Eject delay, in seconds.")
490
491 #################################################
492 # Methods related to device and media attributes
493 #################################################
494
495 def isRewritable(self):
496 """Indicates whether the media is rewritable per configuration."""
497 return self._media.rewritable
498
499 def retrieveCapacity(self, entireDisc=False):
500 """
501 Retrieves capacity for the current media in terms of a ``MediaCapacity``
502 object.
503
504 If ``entireDisc`` is passed in as ``True``, the capacity will be for the
505 entire disc, as if it were to be rewritten from scratch. The same will
506 happen if the disc can't be read for some reason. Otherwise, the capacity
507 will be calculated by subtracting the sectors currently used on the disc,
508 as reported by ``growisofs`` itself.
509
510 Args:
511 entireDisc (Boolean true/false): Indicates whether to return capacity for entire disc
512 Returns:
513 ``MediaCapacity`` object describing the capacity of the media
514
515 Raises:
516 ValueError: If there is a problem parsing the ``growisofs`` output
517 IOError: If the media could not be read for some reason
518 """
519 sectorsUsed = 0.0
520 if not entireDisc:
521 sectorsUsed = self._retrieveSectorsUsed()
522 sectorsAvailable = self._media.capacity - sectorsUsed # both are in sectors
523 bytesUsed = convertSize(sectorsUsed, UNIT_SECTORS, UNIT_BYTES)
524 bytesAvailable = convertSize(sectorsAvailable, UNIT_SECTORS, UNIT_BYTES)
525 return MediaCapacity(bytesUsed, bytesAvailable)
526
527 #######################################################
528 # Methods used for working with the internal ISO image
529 #######################################################
530
531 def initializeImage(self, newDisc, tmpdir, mediaLabel=None):
532 """
533 Initializes the writer's associated ISO image.
534
535 This method initializes the ``image`` instance variable so that the caller
536 can use the ``addImageEntry`` method. Once entries have been added, the
537 ``writeImage`` method can be called with no arguments.
538
539 Args:
540 newDisc (Boolean true/false): Indicates whether the disc should be re-initialized
541 tmpdir (String representing a directory path on disk): Temporary directory to use if needed
542 mediaLabel (String, no more than 25 characters long): Media label to be applied to the image, if any
543
544 """
545 self._image = _ImageProperties()
546 self._image.newDisc = newDisc
547 self._image.tmpdir = encodePath(tmpdir)
548 self._image.mediaLabel = mediaLabel
549 self._image.entries = {} # mapping from path to graft point (if any)
550
551 def addImageEntry(self, path, graftPoint):
552 """
553 Adds a filepath entry to the writer's associated ISO image.
554
555 The contents of the filepath -- but not the path itself -- will be added
556 to the image at the indicated graft point. If you don't want to use a
557 graft point, just pass ``None``.
558
559 *Note:* Before calling this method, you must call :any:`initializeImage`.
560
561 Args:
562 path (String representing a path on disk): File or directory to be added to the image
563 graftPoint (String representing a graft point path, as described above): Graft point to be used when adding this entry
564 Raises:
565 ValueError: If initializeImage() was not previously called
566 ValueError: If the path is not a valid file or directory
567 """
568 if self._image is None:
569 raise ValueError("Must call initializeImage() before using this method.")
570 if not os.path.exists(path):
571 raise ValueError("Path [%s] does not exist." % path)
572 self._image.entries[path] = graftPoint
573
574 def setImageNewDisc(self, newDisc):
575 """
576 Resets (overrides) the newDisc flag on the internal image.
577 Args:
578 newDisc: New disc flag to set
579 Raises:
580 ValueError: If initializeImage() was not previously called
581 """
582 if self._image is None:
583 raise ValueError("Must call initializeImage() before using this method.")
584 self._image.newDisc = newDisc
585
586 def getEstimatedImageSize(self):
587 """
588 Gets the estimated size of the image associated with the writer.
589
590 This is an estimate and is conservative. The actual image could be as
591 much as 450 blocks (sectors) smaller under some circmstances.
592
593 Returns:
594 Estimated size of the image, in bytes
595
596 Raises:
597 IOError: If there is a problem calling ``mkisofs``
598 ValueError: If initializeImage() was not previously called
599 """
600 if self._image is None:
601 raise ValueError("Must call initializeImage() before using this method.")
602 return DvdWriter._getEstimatedImageSize(self._image.entries)
603
604 ######################################
605 # Methods which expose device actions
606 ######################################
607
608 def openTray(self):
609 """
610 Opens the device's tray and leaves it open.
611
612 This only works if the device has a tray and supports ejecting its media.
613 We have no way to know if the tray is currently open or closed, so we
614 just send the appropriate command and hope for the best. If the device
615 does not have a tray or does not support ejecting its media, then we do
616 nothing.
617
618 Starting with Debian wheezy on my backup hardware, I started seeing
619 consistent problems with the eject command. I couldn't tell whether
620 these problems were due to the device management system or to the new
621 kernel (3.2.0). Initially, I saw simple eject failures, possibly because
622 I was opening and closing the tray too quickly. I worked around that
623 behavior with the new ejectDelay flag.
624
625 Later, I sometimes ran into issues after writing an image to a disc:
626 eject would give errors like "unable to eject, last error: Inappropriate
627 ioctl for device". Various sources online (like Ubuntu bug #875543)
628 suggested that the drive was being locked somehow, and that the
629 workaround was to run 'eject -i off' to unlock it. Sure enough, that
630 fixed the problem for me, so now it's a normal error-handling strategy.
631
632 Raises:
633 IOError: If there is an error talking to the device
634 """
635 if self._deviceHasTray and self._deviceCanEject:
636 command = resolveCommand(EJECT_COMMAND)
637 args = [self.device]
638 result = executeCommand(command, args)[0]
639 if result != 0:
640 logger.debug("Eject failed; attempting kludge of unlocking the tray before retrying.")
641 self.unlockTray()
642 result = executeCommand(command, args)[0]
643 if result != 0:
644 raise OSError("Error (%d) executing eject command to open tray (failed even after unlocking tray)." % result)
645 logger.debug("Kludge was apparently successful.")
646 if self.ejectDelay is not None:
647 logger.debug("Per configuration, sleeping %d seconds after opening tray.", self.ejectDelay)
648 time.sleep(self.ejectDelay)
649
650 def unlockTray(self):
651 """
652 Unlocks the device's tray via 'eject -i off'.
653 Raises:
654 IOError: If there is an error talking to the device
655 """
656 command = resolveCommand(EJECT_COMMAND)
657 args = ["-i", "off", self.device]
658 result = executeCommand(command, args)[0]
659 if result != 0:
660 raise OSError("Error (%d) executing eject command to unlock tray." % result)
661
662 def closeTray(self):
663 """
664 Closes the device's tray.
665
666 This only works if the device has a tray and supports ejecting its media.
667 We have no way to know if the tray is currently open or closed, so we
668 just send the appropriate command and hope for the best. If the device
669 does not have a tray or does not support ejecting its media, then we do
670 nothing.
671
672 Raises:
673 IOError: If there is an error talking to the device
674 """
675 if self._deviceHasTray and self._deviceCanEject:
676 command = resolveCommand(EJECT_COMMAND)
677 args = ["-t", self.device]
678 result = executeCommand(command, args)[0]
679 if result != 0:
680 raise OSError("Error (%d) executing eject command to close tray." % result)
681
682 def refreshMedia(self):
683 """
684 Opens and then immediately closes the device's tray, to refresh the
685 device's idea of the media.
686
687 Sometimes, a device gets confused about the state of its media. Often,
688 all it takes to solve the problem is to eject the media and then
689 immediately reload it. (There are also configurable eject and refresh
690 media delays which can be applied, for situations where this makes a
691 difference.)
692
693 This only works if the device has a tray and supports ejecting its media.
694 We have no way to know if the tray is currently open or closed, so we
695 just send the appropriate command and hope for the best. If the device
696 does not have a tray or does not support ejecting its media, then we do
697 nothing. The configured delays still apply, though.
698
699 Raises:
700 IOError: If there is an error talking to the device
701 """
702 self.openTray()
703 self.closeTray()
704 self.unlockTray() # on some systems, writing a disc leaves the tray locked, yikes!
705 if self.refreshMediaDelay is not None:
706 logger.debug("Per configuration, sleeping %d seconds to stabilize media state.", self.refreshMediaDelay)
707 time.sleep(self.refreshMediaDelay)
708 logger.debug("Media refresh complete; hopefully media state is stable now.")
709
710 def writeImage(self, imagePath=None, newDisc=False, writeMulti=True):
711 """
712 Writes an ISO image to the media in the device.
713
714 If ``newDisc`` is passed in as ``True``, we assume that the entire disc
715 will be re-created from scratch. Note that unlike ``CdWriter``,
716 ``DvdWriter`` does not blank rewritable media before reusing it; however,
717 ``growisofs`` is called such that the media will be re-initialized as
718 needed.
719
720 If ``imagePath`` is passed in as ``None``, then the existing image
721 configured with ``initializeImage()`` will be used. Under these
722 circumstances, the passed-in ``newDisc`` flag will be ignored and the
723 value passed in to ``initializeImage()`` will apply instead.
724
725 The ``writeMulti`` argument is ignored. It exists for compatibility with
726 the Cedar Backup image writer interface.
727
728 *Note:* The image size indicated in the log ("Image size will be...") is
729 an estimate. The estimate is conservative and is probably larger than
730 the actual space that ``dvdwriter`` will use.
731
732 Args:
733 imagePath (String representing a path on disk): Path to an ISO image on disk, or ``None`` to use writer's image
734 newDisc (Boolean true/false): Indicates whether the disc should be re-initialized
735 writeMulti (Boolean true/false): Unused
736 Raises:
737 ValueError: If the image path is not absolute
738 ValueError: If some path cannot be encoded properly
739 IOError: If the media could not be written to for some reason
740 ValueError: If no image is passed in and initializeImage() was not previously called
741 """
742 if not writeMulti:
743 logger.warning("writeMulti value of [%s] ignored.", writeMulti)
744 if imagePath is None:
745 if self._image is None:
746 raise ValueError("Must call initializeImage() before using this method with no image path.")
747 size = self.getEstimatedImageSize()
748 logger.info("Image size will be %s (estimated).", displayBytes(size))
749 available = self.retrieveCapacity(entireDisc=self._image.newDisc).bytesAvailable
750 if size > available:
751 logger.error("Image [%s] does not fit in available capacity [%s].", displayBytes(size), displayBytes(available))
752 raise OSError("Media does not contain enough capacity to store image.")
753 self._writeImage(self._image.newDisc, None, self._image.entries, self._image.mediaLabel)
754 else:
755 if not (os.path.isabs(imagePath) or posixpath.isabs(imagePath)): # Python 3.13+ does not treat / as absolute on Windows
756 raise ValueError("Image path must be absolute.")
757 imagePath = encodePath(imagePath)
758 self._writeImage(newDisc, imagePath, None)
759
760 ##################################################################
761 # Utility methods for dealing with growisofs and dvd+rw-mediainfo
762 ##################################################################
763
764 def _writeImage(self, newDisc, imagePath, entries, mediaLabel=None):
765 """
766 Writes an image to disc using either an entries list or an ISO image on
767 disk.
768
769 Callers are assumed to have done validation on paths, etc. before calling
770 this method.
771
772 Args:
773 newDisc: Indicates whether the disc should be re-initialized
774 imagePath: Path to an ISO image on disk, or c{None} to use ``entries``
775 entries: Mapping from path to graft point, or ``None`` to use ``imagePath``
776
777 Raises:
778 IOError: If the media could not be written to for some reason
779 """
780 command = resolveCommand(GROWISOFS_COMMAND)
781 args = DvdWriter._buildWriteArgs(newDisc, self.hardwareId, self._driveSpeed, imagePath, entries, mediaLabel, dryRun=False)
782 (result, output) = executeCommand(command, args, returnOutput=True)
783 if result != 0:
784 DvdWriter._searchForOverburn(output) # throws own exception if overburn condition is found
785 raise OSError("Error (%d) executing command to write disc." % result)
786 self.refreshMedia()
787
788 @staticmethod
789 def _getEstimatedImageSize(entries):
790 """
791 Gets the estimated size of a set of image entries.
792
793 This is implemented in terms of the ``IsoImage`` class. The returned
794 value is calculated by adding a "fudge factor" to the value from
795 ``IsoImage``. This fudge factor was determined by experimentation and is
796 conservative -- the actual image could be as much as 450 blocks smaller
797 under some circumstances.
798
799 Args:
800 entries: Dictionary mapping path to graft point
801
802 Returns:
803 Total estimated size of image, in bytes
804
805 Raises:
806 ValueError: If there are no entries in the dictionary
807 ValueError: If any path in the dictionary does not exist
808 IOError: If there is a problem calling ``mkisofs``
809 """
810 fudgeFactor = convertSize(2500.0, UNIT_SECTORS, UNIT_BYTES) # determined through experimentation
811 if len(list(entries.keys())) == 0:
812 raise ValueError("Must add at least one entry with addImageEntry().")
813 image = IsoImage()
814 for path in list(entries.keys()):
815 image.addEntry(path, entries[path], override=False, contentsOnly=True)
816 return image.getEstimatedSize() + fudgeFactor
817
818 def _retrieveSectorsUsed(self):
819 """
820 Retrieves the number of sectors used on the current media.
821
822 This is a little ugly. We need to call growisofs in "dry-run" mode and
823 parse some information from its output. However, to do that, we need to
824 create a dummy file that we can pass to the command -- and we have to
825 make sure to remove it later.
826
827 Once growisofs has been run, then we call ``_parseSectorsUsed`` to parse
828 the output and calculate the number of sectors used on the media.
829
830 Returns:
831 Number of sectors used on the media
832 """
833 tempdir = tempfile.mkdtemp()
834 try:
835 entries = {tempdir: None}
836 args = DvdWriter._buildWriteArgs(False, self.hardwareId, self.driveSpeed, None, entries, None, dryRun=True)
837 command = resolveCommand(GROWISOFS_COMMAND)
838 (result, output) = executeCommand(command, args, returnOutput=True)
839 if result != 0:
840 logger.debug("Error (%d) calling growisofs to read sectors used.", result)
841 logger.warning("Unable to read disc (might not be initialized); returning zero sectors used.")
842 return 0.0
843 sectorsUsed = DvdWriter._parseSectorsUsed(output)
844 logger.debug("Determined sectors used as %s", sectorsUsed)
845 return sectorsUsed
846 finally:
847 if os.path.exists(tempdir):
848 try:
849 os.rmdir(tempdir)
850 except:
851 pass
852
853 @staticmethod
854 def _parseSectorsUsed(output):
855 """
856 Parse sectors used information out of ``growisofs`` output.
857
858 The first line of a growisofs run looks something like this::
859
860 Executing 'mkisofs -C 973744,1401056 -M /dev/fd/3 -r -graft-points music4/=music | builtin_dd of=/dev/cdrom obs=32k seek=87566'
861
862 Dmitry has determined that the seek value in this line gives us
863 information about how much data has previously been written to the media.
864 That value multiplied by 16 yields the number of sectors used.
865
866 If the seek line cannot be found in the output, then sectors used of zero
867 is assumed.
868
869 Returns:
870 Sectors used on the media, as a floating point number
871
872 Raises:
873 ValueError: If the output cannot be parsed properly
874 """
875 if output is not None:
876 pattern = re.compile(r"(^)(.*)(seek=)(.*)('$)")
877 for line in output:
878 match = pattern.search(line)
879 if match is not None:
880 try:
881 return float(match.group(4).strip()) * 16.0
882 except ValueError:
883 raise ValueError("Unable to parse sectors used out of growisofs output.")
884 logger.warning("Unable to read disc (might not be initialized); returning zero sectors used.")
885 return 0.0
886
887 @staticmethod
888 def _searchForOverburn(output):
889 """
890 Search for an "overburn" error message in ``growisofs`` output.
891
892 The ``growisofs`` command returns a non-zero exit code and puts a message
893 into the output -- even on a dry run -- if there is not enough space on
894 the media. This is called an "overburn" condition.
895
896 The error message looks like this::
897
898 :-( /dev/cdrom: 894048 blocks are free, 2033746 to be written!
899
900 This method looks for the overburn error message anywhere in the output.
901 If a matching error message is found, an ``IOError`` exception is raised
902 containing relevant information about the problem. Otherwise, the method
903 call returns normally.
904
905 Args:
906 output: List of output lines to search, as from ``executeCommand``
907
908 Raises:
909 IOError: If an overburn condition is found
910 """
911 if output is None:
912 return
913 pattern = re.compile(r"(^)(:-[(])(\s*.*:\s*)(.* )(blocks are free, )(.* )(to be written!)")
914 for line in output:
915 match = pattern.search(line)
916 if match is not None:
917 try:
918 available = convertSize(float(match.group(4).strip()), UNIT_SECTORS, UNIT_BYTES)
919 size = convertSize(float(match.group(6).strip()), UNIT_SECTORS, UNIT_BYTES)
920 logger.error("Image [%s] does not fit in available capacity [%s].", displayBytes(size), displayBytes(available))
921 except ValueError:
922 logger.error("Image does not fit in available capacity (no useful capacity info available).")
923 raise OSError("Media does not contain enough capacity to store image.")
924
925 @staticmethod
926 def _buildWriteArgs(newDisc, hardwareId, driveSpeed, imagePath, entries, mediaLabel=None, dryRun=False):
927 """
928 Builds a list of arguments to be passed to a ``growisofs`` command.
929
930 The arguments will either cause ``growisofs`` to write the indicated image
931 file to disc, or will pass ``growisofs`` a list of directories or files
932 that should be written to disc.
933
934 If a new image is created, it will always be created with Rock Ridge
935 extensions (-r). A volume name will be applied (-V) if ``mediaLabel`` is
936 not ``None``.
937
938 Args:
939 newDisc: Indicates whether the disc should be re-initialized
940 hardwareId: Hardware id for the device
941 driveSpeed: Speed at which the drive writes
942 imagePath: Path to an ISO image on disk, or c{None} to use ``entries``
943 entries: Mapping from path to graft point, or ``None`` to use ``imagePath``
944 mediaLabel: Media label to set on the image, if any
945 dryRun: Says whether to make this a dry run (for checking capacity)
946
947 *Note:* If we write an existing image to disc, then the mediaLabel is
948 ignored. The media label is an attribute of the image, and should be set
949 on the image when it is created.
950
951 *Note:* We always pass the undocumented option ``-use-the-force-like=tty``
952 to growisofs. Without this option, growisofs will refuse to execute
953 certain actions when running from cron. A good example is -Z, which
954 happily overwrites an existing DVD from the command-line, but fails when
955 run from cron. It took a while to figure that out, since it worked every
956 time I tested it by hand. :(
957
958 Returns:
959 List suitable for passing to :any:`util.executeCommand` as ``args``
960
961 Raises:
962 ValueError: If caller does not pass one or the other of imagePath or entries
963 """
964 args = []
965 if (imagePath is None and entries is None) or (imagePath is not None and entries is not None):
966 raise ValueError("Must use either imagePath or entries.")
967 args.append("-use-the-force-luke=tty") # tell growisofs to let us run from cron
968 if dryRun:
969 args.append("-dry-run")
970 if driveSpeed is not None:
971 args.append("-speed=%d" % driveSpeed)
972 if newDisc:
973 args.append("-Z")
974 else:
975 args.append("-M")
976 if imagePath is not None:
977 args.append("%s=%s" % (hardwareId, imagePath))
978 else:
979 args.append(hardwareId)
980 if mediaLabel is not None:
981 args.append("-V")
982 args.append(mediaLabel)
983 args.append("-r") # Rock Ridge extensions with sane ownership and permissions
984 args.append("-graft-points")
985 keys = list(entries.keys())
986 keys.sort() # just so we get consistent results
987 for key in keys:
988 # Same syntax as when calling mkisofs in IsoImage
989 if entries[key] is None:
990 args.append(key)
991 else:
992 args.append("%s/=%s" % (entries[key].strip("/"), key))
993 return args