| 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,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 : Implements action-related utilities |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Module documentation |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Implements action-related utilities |
| 39 |
:author: Kenneth J. Pronovici <[email protected]> |
| 40 |
""" |
| 41 |
|
| 42 |
|
| 43 |
######################################################################## |
| 44 |
# Imported modules |
| 45 |
######################################################################## |
| 46 |
|
| 47 |
import logging |
| 48 |
import os |
| 49 |
import tempfile |
| 50 |
import time |
| 51 |
|
| 52 |
from CedarBackup3.actions.constants import INDICATOR_PATTERN |
| 53 |
from CedarBackup3.config import DEFAULT_DEVICE_TYPE, DEFAULT_MEDIA_TYPE, REWRITABLE_MEDIA_TYPES |
| 54 |
from CedarBackup3.filesystem import FilesystemList |
| 55 |
from CedarBackup3.util import changeOwnership, deviceMounted, pathJoin |
| 56 |
from CedarBackup3.writers.cdwriter import MEDIA_CDR_74, MEDIA_CDR_80, MEDIA_CDRW_74, MEDIA_CDRW_80, CdWriter |
| 57 |
from CedarBackup3.writers.dvdwriter import MEDIA_DVDPLUSR, MEDIA_DVDPLUSRW, DvdWriter |
| 58 |
from CedarBackup3.writers.util import readMediaLabel |
| 59 |
|
| 60 |
######################################################################## |
| 61 |
# Module-wide constants and variables |
| 62 |
######################################################################## |
| 63 |
|
| 64 |
logger = logging.getLogger("CedarBackup3.log.actions.util") |
| 65 |
MEDIA_LABEL_PREFIX = "CEDAR BACKUP" |
| 66 |
|
| 67 |
|
| 68 |
######################################################################## |
| 69 |
# Public utility functions |
| 70 |
######################################################################## |
| 71 |
|
| 72 |
########################### |
| 73 |
# findDailyDirs() function |
| 74 |
########################### |
| 75 |
|
| 76 |
|
| 77 |
def findDailyDirs(stagingDir, indicatorFile): |
| 78 |
""" |
| 79 |
Returns a list of all daily staging directories that do not contain |
| 80 |
the indicated indicator file. |
| 81 |
Returns: |
| 82 |
List of absolute paths to daily staging directories |
| 83 |
""" |
| 84 |
results = FilesystemList() |
| 85 |
yearDirs = FilesystemList() |
| 86 |
yearDirs.excludeFiles = True |
| 87 |
yearDirs.excludeLinks = True |
| 88 |
yearDirs.addDirContents(path=stagingDir, recursive=False, addSelf=False) |
| 89 |
for yearDir in yearDirs: |
| 90 |
monthDirs = FilesystemList() |
| 91 |
monthDirs.excludeFiles = True |
| 92 |
monthDirs.excludeLinks = True |
| 93 |
monthDirs.addDirContents(path=yearDir, recursive=False, addSelf=False) |
| 94 |
for monthDir in monthDirs: |
| 95 |
dailyDirs = FilesystemList() |
| 96 |
dailyDirs.excludeFiles = True |
| 97 |
dailyDirs.excludeLinks = True |
| 98 |
dailyDirs.addDirContents(path=monthDir, recursive=False, addSelf=False) |
| 99 |
for dailyDir in dailyDirs: |
| 100 |
if os.path.exists(pathJoin(dailyDir, indicatorFile)): |
| 101 |
logger.debug("Skipping directory [%s]; contains %s.", dailyDir, indicatorFile) |
| 102 |
else: |
| 103 |
logger.debug("Adding [%s] to list of daily directories.", dailyDir) |
| 104 |
results.append(dailyDir) # just put it in the list, no fancy operations |
| 105 |
return results |
| 106 |
|
| 107 |
|
| 108 |
########################### |
| 109 |
# createWriter() function |
| 110 |
########################### |
| 111 |
|
| 112 |
|
| 113 |
def createWriter(config): |
| 114 |
""" |
| 115 |
Creates a writer object based on current configuration. |
| 116 |
|
| 117 |
This function creates and returns a writer based on configuration. This is |
| 118 |
done to abstract action functionality from knowing what kind of writer is in |
| 119 |
use. Since all writers implement the same interface, there's no need for |
| 120 |
actions to care which one they're working with. |
| 121 |
|
| 122 |
Currently, the ``cdwriter`` and ``dvdwriter`` device types are allowed. An |
| 123 |
exception will be raised if any other device type is used. |
| 124 |
|
| 125 |
This function also checks to make sure that the device isn't mounted before |
| 126 |
creating a writer object for it. Experience shows that sometimes if the |
| 127 |
device is mounted, we have problems with the backup. We may as well do the |
| 128 |
check here first, before instantiating the writer. |
| 129 |
|
| 130 |
Args: |
| 131 |
config: Config object |
| 132 |
|
| 133 |
Returns: |
| 134 |
Writer that can be used to write a directory to some media |
| 135 |
|
| 136 |
Raises: |
| 137 |
ValueError: If there is a problem getting the writer |
| 138 |
IOError: If there is a problem creating the writer object |
| 139 |
""" |
| 140 |
devicePath = config.store.devicePath |
| 141 |
deviceScsiId = config.store.deviceScsiId |
| 142 |
driveSpeed = config.store.driveSpeed |
| 143 |
noEject = config.store.noEject |
| 144 |
refreshMediaDelay = config.store.refreshMediaDelay |
| 145 |
ejectDelay = config.store.ejectDelay |
| 146 |
deviceType = _getDeviceType(config) |
| 147 |
mediaType = _getMediaType(config) |
| 148 |
if deviceMounted(devicePath): |
| 149 |
raise OSError("Device [%s] is currently mounted." % (devicePath)) |
| 150 |
if deviceType == "cdwriter": |
| 151 |
return CdWriter(devicePath, deviceScsiId, driveSpeed, mediaType, noEject, refreshMediaDelay, ejectDelay) |
| 152 |
elif deviceType == "dvdwriter": |
| 153 |
return DvdWriter(devicePath, deviceScsiId, driveSpeed, mediaType, noEject, refreshMediaDelay, ejectDelay) |
| 154 |
else: |
| 155 |
raise ValueError("Device type [%s] is invalid." % deviceType) |
| 156 |
|
| 157 |
|
| 158 |
################################ |
| 159 |
# writeIndicatorFile() function |
| 160 |
################################ |
| 161 |
|
| 162 |
|
| 163 |
def writeIndicatorFile(targetDir, indicatorFile, backupUser, backupGroup): |
| 164 |
""" |
| 165 |
Writes an indicator file into a target directory. |
| 166 |
Args: |
| 167 |
targetDir: Target directory in which to write indicator |
| 168 |
indicatorFile: Name of the indicator file |
| 169 |
backupUser: User that indicator file should be owned by |
| 170 |
backupGroup: Group that indicator file should be owned by |
| 171 |
Raises: |
| 172 |
IOException: If there is a problem writing the indicator file |
| 173 |
""" |
| 174 |
filename = pathJoin(targetDir, indicatorFile) |
| 175 |
logger.debug("Writing indicator file [%s].", filename) |
| 176 |
try: |
| 177 |
with open(filename, "w") as f: |
| 178 |
f.write("") |
| 179 |
changeOwnership(filename, backupUser, backupGroup) |
| 180 |
except Exception as e: |
| 181 |
logger.error("Error writing [%s]: %s", filename, e) |
| 182 |
raise e |
| 183 |
|
| 184 |
|
| 185 |
############################ |
| 186 |
# getBackupFiles() function |
| 187 |
############################ |
| 188 |
|
| 189 |
|
| 190 |
def getBackupFiles(targetDir): |
| 191 |
""" |
| 192 |
Gets a list of backup files in a target directory. |
| 193 |
|
| 194 |
Files that match INDICATOR_PATTERN (i.e. ``"cback.store"``, ``"cback.stage"``, |
| 195 |
etc.) are assumed to be indicator files and are ignored. |
| 196 |
|
| 197 |
Args: |
| 198 |
targetDir: Directory to look in |
| 199 |
|
| 200 |
Returns: |
| 201 |
List of backup files in the directory |
| 202 |
|
| 203 |
Raises: |
| 204 |
ValueError: If the target directory does not exist |
| 205 |
""" |
| 206 |
if not os.path.isdir(targetDir): |
| 207 |
raise ValueError("Target directory [%s] is not a directory or does not exist." % targetDir) |
| 208 |
fileList = FilesystemList() |
| 209 |
fileList.excludeDirs = True |
| 210 |
fileList.excludeLinks = True |
| 211 |
fileList.excludeBasenamePatterns = INDICATOR_PATTERN |
| 212 |
fileList.addDirContents(targetDir) |
| 213 |
return fileList |
| 214 |
|
| 215 |
|
| 216 |
#################### |
| 217 |
# checkMediaState() |
| 218 |
#################### |
| 219 |
|
| 220 |
|
| 221 |
def checkMediaState(storeConfig): |
| 222 |
""" |
| 223 |
Checks state of the media in the backup device to confirm whether it has |
| 224 |
been initialized for use with Cedar Backup. |
| 225 |
|
| 226 |
We can tell whether the media has been initialized by looking at its media |
| 227 |
label. If the media label starts with MEDIA_LABEL_PREFIX, then it has been |
| 228 |
initialized. |
| 229 |
|
| 230 |
The check varies depending on whether the media is rewritable or not. For |
| 231 |
non-rewritable media, we also accept a ``None`` media label, since this kind |
| 232 |
of media cannot safely be initialized. |
| 233 |
|
| 234 |
Args: |
| 235 |
storeConfig: Store configuration |
| 236 |
|
| 237 |
Raises: |
| 238 |
ValueError: If media is not initialized |
| 239 |
""" |
| 240 |
mediaLabel = readMediaLabel(storeConfig.devicePath) |
| 241 |
if storeConfig.mediaType in REWRITABLE_MEDIA_TYPES: |
| 242 |
if mediaLabel is None: |
| 243 |
raise ValueError("Media has not been initialized: no media label available") |
| 244 |
elif not mediaLabel.startswith(MEDIA_LABEL_PREFIX): |
| 245 |
raise ValueError("Media has not been initialized: unrecognized media label [%s]" % mediaLabel) |
| 246 |
else: |
| 247 |
if mediaLabel is None: |
| 248 |
logger.info("Media has no media label; assuming OK since media is not rewritable.") |
| 249 |
elif not mediaLabel.startswith(MEDIA_LABEL_PREFIX): |
| 250 |
raise ValueError("Media has not been initialized: unrecognized media label [%s]" % mediaLabel) |
| 251 |
|
| 252 |
|
| 253 |
######################### |
| 254 |
# initializeMediaState() |
| 255 |
######################### |
| 256 |
|
| 257 |
|
| 258 |
def initializeMediaState(config): |
| 259 |
""" |
| 260 |
Initializes state of the media in the backup device so Cedar Backup can |
| 261 |
recognize it. |
| 262 |
|
| 263 |
This is done by writing an mostly-empty image (it contains a "Cedar Backup" |
| 264 |
directory) to the media with a known media label. |
| 265 |
|
| 266 |
*Note:* Only rewritable media (CD-RW, DVD+RW) can be initialized. It |
| 267 |
doesn't make any sense to initialize media that cannot be rewritten (CD-R, |
| 268 |
DVD+R), since Cedar Backup would then not be able to use that media for a |
| 269 |
backup. |
| 270 |
|
| 271 |
Args: |
| 272 |
config: Cedar Backup configuration |
| 273 |
|
| 274 |
Raises: |
| 275 |
ValueError: If media could not be initialized |
| 276 |
ValueError: If the configured media type is not rewritable |
| 277 |
""" |
| 278 |
if config.store.mediaType not in REWRITABLE_MEDIA_TYPES: |
| 279 |
raise ValueError("Only rewritable media types can be initialized.") |
| 280 |
mediaLabel = buildMediaLabel() |
| 281 |
writer = createWriter(config) |
| 282 |
writer.refreshMedia() |
| 283 |
writer.initializeImage(True, config.options.workingDir, mediaLabel) # always create a new disc |
| 284 |
tempdir = tempfile.mkdtemp(dir=config.options.workingDir) |
| 285 |
try: |
| 286 |
writer.addImageEntry(tempdir, "CedarBackup") |
| 287 |
writer.writeImage() |
| 288 |
finally: |
| 289 |
if os.path.exists(tempdir): |
| 290 |
try: |
| 291 |
os.rmdir(tempdir) |
| 292 |
except: |
| 293 |
pass |
| 294 |
|
| 295 |
|
| 296 |
#################### |
| 297 |
# buildMediaLabel() |
| 298 |
#################### |
| 299 |
|
| 300 |
|
| 301 |
def buildMediaLabel(): |
| 302 |
""" |
| 303 |
Builds a media label to be used on Cedar Backup media. |
| 304 |
Returns: |
| 305 |
Media label as a string |
| 306 |
""" |
| 307 |
currentDate = time.strftime("%d-%b-%Y").upper() |
| 308 |
return "%s %s" % (MEDIA_LABEL_PREFIX, currentDate) |
| 309 |
|
| 310 |
|
| 311 |
######################################################################## |
| 312 |
# Private attribute "getter" functions |
| 313 |
######################################################################## |
| 314 |
|
| 315 |
############################ |
| 316 |
# _getDeviceType() function |
| 317 |
############################ |
| 318 |
|
| 319 |
|
| 320 |
def _getDeviceType(config): |
| 321 |
""" |
| 322 |
Gets the device type that should be used for storing. |
| 323 |
|
| 324 |
Use the configured device type if not ``None``, otherwise use |
| 325 |
:any:`config.DEFAULT_DEVICE_TYPE`. |
| 326 |
|
| 327 |
Args: |
| 328 |
config: Config object |
| 329 |
Returns: |
| 330 |
Device type to be used |
| 331 |
""" |
| 332 |
if config.store.deviceType is None: |
| 333 |
deviceType = DEFAULT_DEVICE_TYPE |
| 334 |
else: |
| 335 |
deviceType = config.store.deviceType |
| 336 |
logger.debug("Device type is [%s]", deviceType) |
| 337 |
return deviceType |
| 338 |
|
| 339 |
|
| 340 |
########################### |
| 341 |
# _getMediaType() function |
| 342 |
########################### |
| 343 |
|
| 344 |
|
| 345 |
def _getMediaType(config): |
| 346 |
""" |
| 347 |
Gets the media type that should be used for storing. |
| 348 |
|
| 349 |
Use the configured media type if not ``None``, otherwise use |
| 350 |
``DEFAULT_MEDIA_TYPE``. |
| 351 |
|
| 352 |
Once we figure out what configuration value to use, we return a media type |
| 353 |
value that is valid in one of the supported writers:: |
| 354 |
|
| 355 |
MEDIA_CDR_74 |
| 356 |
MEDIA_CDRW_74 |
| 357 |
MEDIA_CDR_80 |
| 358 |
MEDIA_CDRW_80 |
| 359 |
MEDIA_DVDPLUSR |
| 360 |
MEDIA_DVDPLUSRW |
| 361 |
|
| 362 |
Args: |
| 363 |
config: Config object |
| 364 |
|
| 365 |
Returns: |
| 366 |
Media type to be used as a writer media type value |
| 367 |
Raises: |
| 368 |
ValueError: If the media type is not valid |
| 369 |
""" |
| 370 |
if config.store.mediaType is None: |
| 371 |
mediaType = DEFAULT_MEDIA_TYPE |
| 372 |
else: |
| 373 |
mediaType = config.store.mediaType |
| 374 |
if mediaType == "cdr-74": |
| 375 |
logger.debug("Media type is MEDIA_CDR_74.") |
| 376 |
return MEDIA_CDR_74 |
| 377 |
elif mediaType == "cdrw-74": |
| 378 |
logger.debug("Media type is MEDIA_CDRW_74.") |
| 379 |
return MEDIA_CDRW_74 |
| 380 |
elif mediaType == "cdr-80": |
| 381 |
logger.debug("Media type is MEDIA_CDR_80.") |
| 382 |
return MEDIA_CDR_80 |
| 383 |
elif mediaType == "cdrw-80": |
| 384 |
logger.debug("Media type is MEDIA_CDRW_80.") |
| 385 |
return MEDIA_CDRW_80 |
| 386 |
elif mediaType == "dvd+r": |
| 387 |
logger.debug("Media type is MEDIA_DVDPLUSR.") |
| 388 |
return MEDIA_DVDPLUSR |
| 389 |
elif mediaType == "dvd+rw": |
| 390 |
logger.debug("Media type is MEDIA_DVDPLUSRW.") |
| 391 |
return MEDIA_DVDPLUSRW |
| 392 |
else: |
| 393 |
raise ValueError("Media type [%s] is not valid." % mediaType) |