Home | Trees | Indices | Help |
|
---|
|
1 # -*- coding: iso-8859-1 -*- 2 # vim: set ft=python ts=3 sw=3 expandtab: 3 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 4 # 5 # C E D A R 6 # S O L U T I O N S "Software done right." 7 # S O F T W A R E 8 # 9 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 10 # 11 # Copyright (c) 2007,2010 Kenneth J. Pronovici. 12 # All rights reserved. 13 # 14 # This program is free software; you can redistribute it and/or 15 # modify it under the terms of the GNU General Public License, 16 # Version 2, as published by the Free Software Foundation. 17 # 18 # This program is distributed in the hope that it will be useful, 19 # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 21 # 22 # Copies of the GNU General Public License are available from 23 # the Free Software Foundation website, http://www.gnu.org/. 24 # 25 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 26 # 27 # Author : Kenneth J. Pronovici <pronovic@ieee.org> 28 # Language : Python (>= 2.5) 29 # Project : Cedar Backup, release 2 30 # Revision : $Id: util.py 1006 2010-07-07 21:03:57Z pronovic $ 31 # Purpose : Implements action-related utilities 32 # 33 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 34 35 ######################################################################## 36 # Module documentation 37 ######################################################################## 38 39 """ 40 Implements action-related utilities 41 @sort: findDailyDirs 42 @author: Kenneth J. Pronovici <pronovic@ieee.org> 43 """ 44 45 46 ######################################################################## 47 # Imported modules 48 ######################################################################## 49 50 # System modules 51 import os 52 import time 53 import tempfile 54 import logging 55 56 # Cedar Backup modules 57 from CedarBackup2.filesystem import FilesystemList 58 from CedarBackup2.util import changeOwnership 59 from CedarBackup2.util import deviceMounted 60 from CedarBackup2.writers.util import readMediaLabel 61 from CedarBackup2.writers.cdwriter import CdWriter 62 from CedarBackup2.writers.dvdwriter import DvdWriter 63 from CedarBackup2.writers.cdwriter import MEDIA_CDR_74, MEDIA_CDR_80, MEDIA_CDRW_74, MEDIA_CDRW_80 64 from CedarBackup2.writers.dvdwriter import MEDIA_DVDPLUSR, MEDIA_DVDPLUSRW 65 from CedarBackup2.config import DEFAULT_MEDIA_TYPE, DEFAULT_DEVICE_TYPE, REWRITABLE_MEDIA_TYPES 66 from CedarBackup2.actions.constants import INDICATOR_PATTERN 67 68 69 ######################################################################## 70 # Module-wide constants and variables 71 ######################################################################## 72 73 logger = logging.getLogger("CedarBackup2.log.actions.util") 74 MEDIA_LABEL_PREFIX = "CEDAR BACKUP" 75 76 77 ######################################################################## 78 # Public utility functions 79 ######################################################################## 80 81 ########################### 82 # findDailyDirs() function 83 ########################### 8486 """ 87 Returns a list of all daily staging directories that do not contain 88 the indicated indicator file. 89 90 @param stagingDir: Configured staging directory (config.targetDir) 91 92 @return: List of absolute paths to daily staging directories. 93 """ 94 results = FilesystemList() 95 yearDirs = FilesystemList() 96 yearDirs.excludeFiles = True 97 yearDirs.excludeLinks = True 98 yearDirs.addDirContents(path=stagingDir, recursive=False, addSelf=False) 99 for yearDir in yearDirs: 100 monthDirs = FilesystemList() 101 monthDirs.excludeFiles = True 102 monthDirs.excludeLinks = True 103 monthDirs.addDirContents(path=yearDir, recursive=False, addSelf=False) 104 for monthDir in monthDirs: 105 dailyDirs = FilesystemList() 106 dailyDirs.excludeFiles = True 107 dailyDirs.excludeLinks = True 108 dailyDirs.addDirContents(path=monthDir, recursive=False, addSelf=False) 109 for dailyDir in dailyDirs: 110 if os.path.exists(os.path.join(dailyDir, indicatorFile)): 111 logger.debug("Skipping directory [%s]; contains %s." % (dailyDir, indicatorFile)) 112 else: 113 logger.debug("Adding [%s] to list of daily directories." % dailyDir) 114 results.append(dailyDir) # just put it in the list, no fancy operations 115 return results116 117 118 ########################### 119 # createWriter() function 120 ########################### 121123 """ 124 Creates a writer object based on current configuration. 125 126 This function creates and returns a writer based on configuration. This is 127 done to abstract action functionality from knowing what kind of writer is in 128 use. Since all writers implement the same interface, there's no need for 129 actions to care which one they're working with. 130 131 Currently, the C{cdwriter} and C{dvdwriter} device types are allowed. An 132 exception will be raised if any other device type is used. 133 134 This function also checks to make sure that the device isn't mounted before 135 creating a writer object for it. Experience shows that sometimes if the 136 device is mounted, we have problems with the backup. We may as well do the 137 check here first, before instantiating the writer. 138 139 @param config: Config object. 140 141 @return: Writer that can be used to write a directory to some media. 142 143 @raise ValueError: If there is a problem getting the writer. 144 @raise IOError: If there is a problem creating the writer object. 145 """ 146 devicePath = config.store.devicePath 147 deviceScsiId = config.store.deviceScsiId 148 driveSpeed = config.store.driveSpeed 149 noEject = config.store.noEject 150 refreshMediaDelay = config.store.refreshMediaDelay 151 deviceType = _getDeviceType(config) 152 mediaType = _getMediaType(config) 153 if deviceMounted(devicePath): 154 raise IOError("Device [%s] is currently mounted." % (devicePath)) 155 if deviceType == "cdwriter": 156 return CdWriter(devicePath, deviceScsiId, driveSpeed, mediaType, noEject, refreshMediaDelay) 157 elif deviceType == "dvdwriter": 158 return DvdWriter(devicePath, deviceScsiId, driveSpeed, mediaType, noEject, refreshMediaDelay) 159 else: 160 raise ValueError("Device type [%s] is invalid." % deviceType)161 162 163 ################################ 164 # writeIndicatorFile() function 165 ################################ 166168 """ 169 Writes an indicator file into a target directory. 170 @param targetDir: Target directory in which to write indicator 171 @param indicatorFile: Name of the indicator file 172 @param backupUser: User that indicator file should be owned by 173 @param backupGroup: Group that indicator file should be owned by 174 @raise IOException: If there is a problem writing the indicator file 175 """ 176 filename = os.path.join(targetDir, indicatorFile) 177 logger.debug("Writing indicator file [%s]." % filename) 178 try: 179 open(filename, "w").write("") 180 changeOwnership(filename, backupUser, backupGroup) 181 except Exception, e: 182 logger.error("Error writing [%s]: %s" % (filename, e)) 183 raise e184 185 186 ############################ 187 # getBackupFiles() function 188 ############################ 189191 """ 192 Gets a list of backup files in a target directory. 193 194 Files that match INDICATOR_PATTERN (i.e. C{"cback.store"}, C{"cback.stage"}, 195 etc.) are assumed to be indicator files and are ignored. 196 197 @param targetDir: Directory to look in 198 199 @return: List of backup files in the directory 200 201 @raise ValueError: If the target directory does not exist 202 """ 203 if not os.path.isdir(targetDir): 204 raise ValueError("Target directory [%s] is not a directory or does not exist." % targetDir) 205 fileList = FilesystemList() 206 fileList.excludeDirs = True 207 fileList.excludeLinks = True 208 fileList.excludeBasenamePatterns = INDICATOR_PATTERN 209 fileList.addDirContents(targetDir) 210 return fileList211 212 213 #################### 214 # checkMediaState() 215 #################### 216218 """ 219 Checks state of the media in the backup device to confirm whether it has 220 been initialized for use with Cedar Backup. 221 222 We can tell whether the media has been initialized by looking at its media 223 label. If the media label starts with MEDIA_LABEL_PREFIX, then it has been 224 initialized. 225 226 The check varies depending on whether the media is rewritable or not. For 227 non-rewritable media, we also accept a C{None} media label, since this kind 228 of media cannot safely be initialized. 229 230 @param storeConfig: Store configuration 231 232 @raise ValueError: If media is not initialized. 233 """ 234 mediaLabel = readMediaLabel(storeConfig.devicePath) 235 if storeConfig.mediaType in REWRITABLE_MEDIA_TYPES: 236 if mediaLabel is None: 237 raise ValueError("Media has not been initialized: no media label available") 238 elif not mediaLabel.startswith(MEDIA_LABEL_PREFIX): 239 raise ValueError("Media has not been initialized: unrecognized media label [%s]" % mediaLabel) 240 else: 241 if mediaLabel is None: 242 logger.info("Media has no media label; assuming OK since media is not rewritable.") 243 elif not mediaLabel.startswith(MEDIA_LABEL_PREFIX): 244 raise ValueError("Media has not been initialized: unrecognized media label [%s]" % mediaLabel)245 246 247 ######################### 248 # initializeMediaState() 249 ######################### 250252 """ 253 Initializes state of the media in the backup device so Cedar Backup can 254 recognize it. 255 256 This is done by writing an mostly-empty image (it contains a "Cedar Backup" 257 directory) to the media with a known media label. 258 259 @note: Only rewritable media (CD-RW, DVD+RW) can be initialized. It 260 doesn't make any sense to initialize media that cannot be rewritten (CD-R, 261 DVD+R), since Cedar Backup would then not be able to use that media for a 262 backup. 263 264 @param config: Cedar Backup configuration 265 266 @raise ValueError: If media could not be initialized. 267 @raise ValueError: If the configured media type is not rewritable 268 """ 269 if not config.store.mediaType in REWRITABLE_MEDIA_TYPES: 270 raise ValueError("Only rewritable media types can be initialized.") 271 mediaLabel = buildMediaLabel() 272 writer = createWriter(config) 273 writer.initializeImage(True, config.options.workingDir, mediaLabel) # always create a new disc 274 tempdir = tempfile.mkdtemp(dir=config.options.workingDir) 275 try: 276 writer.addImageEntry(tempdir, "CedarBackup") 277 writer.writeImage() 278 finally: 279 if os.path.exists(tempdir): 280 try: 281 os.rmdir(tempdir) 282 except: pass283 284 285 #################### 286 # buildMediaLabel() 287 #################### 288290 """ 291 Builds a media label to be used on Cedar Backup media. 292 @return: Media label as a string. 293 """ 294 currentDate = time.strftime("%d-%b-%Y").upper() 295 return "%s %s" % (MEDIA_LABEL_PREFIX, currentDate)296 297 298 ######################################################################## 299 # Private attribute "getter" functions 300 ######################################################################## 301 302 ############################ 303 # _getDeviceType() function 304 ############################ 305307 """ 308 Gets the device type that should be used for storing. 309 310 Use the configured device type if not C{None}, otherwise use 311 L{config.DEFAULT_DEVICE_TYPE}. 312 313 @param config: Config object. 314 @return: Device type to be used. 315 """ 316 if config.store.deviceType is None: 317 deviceType = DEFAULT_DEVICE_TYPE 318 else: 319 deviceType = config.store.deviceType 320 logger.debug("Device type is [%s]" % deviceType) 321 return deviceType322 323 324 ########################### 325 # _getMediaType() function 326 ########################### 327329 """ 330 Gets the media type that should be used for storing. 331 332 Use the configured media type if not C{None}, otherwise use 333 C{DEFAULT_MEDIA_TYPE}. 334 335 Once we figure out what configuration value to use, we return a media type 336 value that is valid in one of the supported writers:: 337 338 MEDIA_CDR_74 339 MEDIA_CDRW_74 340 MEDIA_CDR_80 341 MEDIA_CDRW_80 342 MEDIA_DVDPLUSR 343 MEDIA_DVDPLUSRW 344 345 @param config: Config object. 346 347 @return: Media type to be used as a writer media type value. 348 @raise ValueError: If the media type is not valid. 349 """ 350 if config.store.mediaType is None: 351 mediaType = DEFAULT_MEDIA_TYPE 352 else: 353 mediaType = config.store.mediaType 354 if mediaType == "cdr-74": 355 logger.debug("Media type is MEDIA_CDR_74.") 356 return MEDIA_CDR_74 357 elif mediaType == "cdrw-74": 358 logger.debug("Media type is MEDIA_CDRW_74.") 359 return MEDIA_CDRW_74 360 elif mediaType == "cdr-80": 361 logger.debug("Media type is MEDIA_CDR_80.") 362 return MEDIA_CDR_80 363 elif mediaType == "cdrw-80": 364 logger.debug("Media type is MEDIA_CDRW_80.") 365 return MEDIA_CDRW_80 366 elif mediaType == "dvd+r": 367 logger.debug("Media type is MEDIA_DVDPLUSR.") 368 return MEDIA_DVDPLUSR 369 elif mediaType == "dvd+rw": 370 logger.debug("Media type is MEDIA_DVDPLUSRW.") 371 return MEDIA_DVDPLUSRW 372 else: 373 raise ValueError("Media type [%s] is not valid." % mediaType)374
Home | Trees | Indices | Help |
|
---|
Generated by Epydoc 3.0.1 on Tue Oct 19 20:56:47 2010 | http://epydoc.sourceforge.net |