| 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 : Implements the standard 'store' action. |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Module documentation |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Implements the standard 'store' action. |
| 39 |
:author: Kenneth J. Pronovici <[email protected]> |
| 40 |
:author: Dmitry Rutsky <[email protected]> |
| 41 |
""" |
| 42 |
|
| 43 |
|
| 44 |
######################################################################## |
| 45 |
# Imported modules |
| 46 |
######################################################################## |
| 47 |
|
| 48 |
import datetime |
| 49 |
import logging |
| 50 |
import os |
| 51 |
import sys |
| 52 |
import tempfile |
| 53 |
|
| 54 |
from CedarBackup3.actions.constants import DIR_TIME_FORMAT, STAGE_INDICATOR, STORE_INDICATOR |
| 55 |
from CedarBackup3.actions.util import buildMediaLabel, checkMediaState, createWriter, writeIndicatorFile |
| 56 |
from CedarBackup3.filesystem import compareContents |
| 57 |
from CedarBackup3.util import displayBytes, isStartOfWeek, mount, pathJoin, unmount |
| 58 |
|
| 59 |
######################################################################## |
| 60 |
# Module-wide constants and variables |
| 61 |
######################################################################## |
| 62 |
|
| 63 |
logger = logging.getLogger("CedarBackup3.log.actions.store") |
| 64 |
|
| 65 |
|
| 66 |
######################################################################## |
| 67 |
# Public functions |
| 68 |
######################################################################## |
| 69 |
|
| 70 |
########################## |
| 71 |
# executeStore() function |
| 72 |
########################## |
| 73 |
|
| 74 |
|
| 75 |
def executeStore(configPath, options, config): # ruff: ignore[unused-function-argument] |
| 76 |
""" |
| 77 |
Executes the store backup action. |
| 78 |
|
| 79 |
*Note:* The rebuild action and the store action are very similar. The |
| 80 |
main difference is that while store only stores a single day's staging |
| 81 |
directory, the rebuild action operates on multiple staging directories. |
| 82 |
|
| 83 |
*Note:* When the store action is complete, we will write a store indicator to |
| 84 |
the daily staging directory we used, so it's obvious that the store action |
| 85 |
has completed. |
| 86 |
|
| 87 |
Args: |
| 88 |
configPath (String representing a path on disk): Path to configuration file on disk |
| 89 |
options (Options object): Program command-line options |
| 90 |
config (Config object): Program configuration |
| 91 |
Raises: |
| 92 |
ValueError: Under many generic error conditions |
| 93 |
IOError: If there are problems reading or writing files |
| 94 |
""" |
| 95 |
logger.debug("Executing the 'store' action.") |
| 96 |
if sys.platform == "darwin": |
| 97 |
logger.warning("Warning: the store action is not fully supported on Mac OS X.") |
| 98 |
logger.warning("See the Cedar Backup software manual for further information.") |
| 99 |
if config.options is None or config.store is None: |
| 100 |
raise ValueError("Store configuration is not properly filled in.") |
| 101 |
if config.store.checkMedia: |
| 102 |
checkMediaState(config.store) # raises exception if media is not initialized |
| 103 |
rebuildMedia = options.full |
| 104 |
logger.debug("Rebuild media flag [%s]", rebuildMedia) |
| 105 |
todayIsStart = isStartOfWeek(config.options.startingDay) |
| 106 |
stagingDirs = _findCorrectDailyDir(options, config) |
| 107 |
writeImageBlankSafe(config, rebuildMedia, todayIsStart, config.store.blankBehavior, stagingDirs) |
| 108 |
if config.store.checkData: |
| 109 |
if sys.platform == "darwin": |
| 110 |
logger.warning("Warning: consistency check cannot be run successfully on Mac OS X.") |
| 111 |
logger.warning("See the Cedar Backup software manual for further information.") |
| 112 |
else: |
| 113 |
logger.debug("Running consistency check of media.") |
| 114 |
consistencyCheck(config, stagingDirs) |
| 115 |
writeStoreIndicator(config, stagingDirs) |
| 116 |
logger.info("Executed the 'store' action successfully.") |
| 117 |
|
| 118 |
|
| 119 |
######################## |
| 120 |
# writeImage() function |
| 121 |
######################## |
| 122 |
|
| 123 |
|
| 124 |
def writeImage(config, newDisc, stagingDirs): |
| 125 |
""" |
| 126 |
Builds and writes an ISO image containing the indicated stage directories. |
| 127 |
|
| 128 |
The generated image will contain each of the staging directories listed in |
| 129 |
``stagingDirs``. The directories will be placed into the image at the root by |
| 130 |
date, so staging directory ``/opt/stage/2005/02/10`` will be placed into the |
| 131 |
disc at ``/2005/02/10``. |
| 132 |
|
| 133 |
*Note:* This function is implemented in terms of :any:`writeImageBlankSafe`. The |
| 134 |
``newDisc`` flag is passed in for both ``rebuildMedia`` and ``todayIsStart``. |
| 135 |
|
| 136 |
Args: |
| 137 |
config: Config object |
| 138 |
newDisc: Indicates whether the disc should be re-initialized |
| 139 |
stagingDirs: Dictionary mapping directory path to date suffix |
| 140 |
|
| 141 |
Raises: |
| 142 |
ValueError: Under many generic error conditions |
| 143 |
IOError: If there is a problem writing the image to disc |
| 144 |
""" |
| 145 |
writeImageBlankSafe(config, newDisc, newDisc, None, stagingDirs) |
| 146 |
|
| 147 |
|
| 148 |
################################# |
| 149 |
# writeImageBlankSafe() function |
| 150 |
################################# |
| 151 |
|
| 152 |
|
| 153 |
def writeImageBlankSafe(config, rebuildMedia, todayIsStart, blankBehavior, stagingDirs): |
| 154 |
""" |
| 155 |
Builds and writes an ISO image containing the indicated stage directories. |
| 156 |
|
| 157 |
The generated image will contain each of the staging directories listed in |
| 158 |
``stagingDirs``. The directories will be placed into the image at the root by |
| 159 |
date, so staging directory ``/opt/stage/2005/02/10`` will be placed into the |
| 160 |
disc at ``/2005/02/10``. The media will always be written with a media |
| 161 |
label specific to Cedar Backup. |
| 162 |
|
| 163 |
This function is similar to :any:`writeImage`, but tries to implement a smarter |
| 164 |
blanking strategy. |
| 165 |
|
| 166 |
First, the media is always blanked if the ``rebuildMedia`` flag is true. |
| 167 |
Then, if ``rebuildMedia`` is false, blanking behavior and ``todayIsStart`` |
| 168 |
come into effect:: |
| 169 |
|
| 170 |
If no blanking behavior is specified, and it is the start of the week, |
| 171 |
the disc will be blanked |
| 172 |
|
| 173 |
If blanking behavior is specified, and either the blank mode is "daily" |
| 174 |
or the blank mode is "weekly" and it is the start of the week, then |
| 175 |
the disc will be blanked if it looks like the weekly backup will not |
| 176 |
fit onto the media. |
| 177 |
|
| 178 |
Otherwise, the disc will not be blanked |
| 179 |
|
| 180 |
How do we decide whether the weekly backup will fit onto the media? That is |
| 181 |
what the blanking factor is used for. The following formula is used:: |
| 182 |
|
| 183 |
will backup fit? = (bytes available / (1 + bytes required) <= blankFactor |
| 184 |
|
| 185 |
The blanking factor will vary from setup to setup, and will probably |
| 186 |
require some experimentation to get it right. |
| 187 |
|
| 188 |
Args: |
| 189 |
config: Config object |
| 190 |
rebuildMedia: Indicates whether media should be rebuilt |
| 191 |
todayIsStart: Indicates whether today is the starting day of the week |
| 192 |
blankBehavior: Blank behavior from configuration, or ``None`` to use default behavior |
| 193 |
stagingDirs: Dictionary mapping directory path to date suffix |
| 194 |
|
| 195 |
Raises: |
| 196 |
ValueError: Under many generic error conditions |
| 197 |
IOError: If there is a problem writing the image to disc |
| 198 |
""" |
| 199 |
mediaLabel = buildMediaLabel() |
| 200 |
writer = createWriter(config) |
| 201 |
writer.initializeImage(True, config.options.workingDir, mediaLabel) # default value for newDisc |
| 202 |
for stageDir in list(stagingDirs.keys()): |
| 203 |
logger.debug("Adding stage directory [%s].", stageDir) |
| 204 |
dateSuffix = stagingDirs[stageDir] |
| 205 |
writer.addImageEntry(stageDir, dateSuffix) |
| 206 |
newDisc = _getNewDisc(writer, rebuildMedia, todayIsStart, blankBehavior) |
| 207 |
writer.setImageNewDisc(newDisc) |
| 208 |
writer.writeImage() |
| 209 |
|
| 210 |
|
| 211 |
def _getNewDisc(writer, rebuildMedia, todayIsStart, blankBehavior): |
| 212 |
""" |
| 213 |
Gets a value for the newDisc flag based on blanking factor rules. |
| 214 |
|
| 215 |
The blanking factor rules are described above by :any:`writeImageBlankSafe`. |
| 216 |
|
| 217 |
Args: |
| 218 |
writer: Previously configured image writer containing image entries |
| 219 |
rebuildMedia: Indicates whether media should be rebuilt |
| 220 |
todayIsStart: Indicates whether today is the starting day of the week |
| 221 |
blankBehavior: Blank behavior from configuration, or ``None`` to use default behavior |
| 222 |
|
| 223 |
Returns: |
| 224 |
newDisc flag to be set on writer |
| 225 |
""" |
| 226 |
newDisc = False |
| 227 |
if rebuildMedia: |
| 228 |
newDisc = True |
| 229 |
logger.debug("Setting new disc flag based on rebuildMedia flag.") |
| 230 |
else: |
| 231 |
if blankBehavior is None: |
| 232 |
logger.debug("Default media blanking behavior is in effect.") |
| 233 |
if todayIsStart: |
| 234 |
newDisc = True |
| 235 |
logger.debug("Setting new disc flag based on todayIsStart.") |
| 236 |
else: |
| 237 |
# note: validation says we can assume that behavior is fully filled in if it exists at all |
| 238 |
logger.debug("Optimized media blanking behavior is in effect based on configuration.") |
| 239 |
if blankBehavior.blankMode == "daily" or (blankBehavior.blankMode == "weekly" and todayIsStart): |
| 240 |
logger.debug("New disc flag will be set based on blank factor calculation.") |
| 241 |
blankFactor = float(blankBehavior.blankFactor) |
| 242 |
logger.debug("Configured blanking factor: %.2f", blankFactor) |
| 243 |
available = writer.retrieveCapacity().bytesAvailable |
| 244 |
logger.debug("Bytes available: %s", displayBytes(available)) |
| 245 |
required = writer.getEstimatedImageSize() |
| 246 |
logger.debug("Bytes required: %s", displayBytes(required)) |
| 247 |
ratio = available / (1.0 + required) |
| 248 |
logger.debug("Calculated ratio: %.2f", ratio) |
| 249 |
newDisc = ratio <= blankFactor |
| 250 |
logger.debug("%.2f <= %.2f ? %s", ratio, blankFactor, newDisc) |
| 251 |
else: |
| 252 |
logger.debug("No blank factor calculation is required based on configuration.") |
| 253 |
logger.debug("New disc flag [%s].", newDisc) |
| 254 |
return newDisc |
| 255 |
|
| 256 |
|
| 257 |
################################# |
| 258 |
# writeStoreIndicator() function |
| 259 |
################################# |
| 260 |
|
| 261 |
|
| 262 |
def writeStoreIndicator(config, stagingDirs): |
| 263 |
""" |
| 264 |
Writes a store indicator file into staging directories. |
| 265 |
|
| 266 |
The store indicator is written into each of the staging directories when |
| 267 |
either a store or rebuild action has written the staging directory to disc. |
| 268 |
|
| 269 |
Args: |
| 270 |
config: Config object |
| 271 |
stagingDirs: Dictionary mapping directory path to date suffix |
| 272 |
""" |
| 273 |
for stagingDir in list(stagingDirs.keys()): |
| 274 |
writeIndicatorFile(stagingDir, STORE_INDICATOR, config.options.backupUser, config.options.backupGroup) |
| 275 |
|
| 276 |
|
| 277 |
############################## |
| 278 |
# consistencyCheck() function |
| 279 |
############################## |
| 280 |
|
| 281 |
|
| 282 |
def consistencyCheck(config, stagingDirs): |
| 283 |
""" |
| 284 |
Runs a consistency check against media in the backup device. |
| 285 |
|
| 286 |
It seems that sometimes, it's possible to create a corrupted multisession |
| 287 |
disc (i.e. one that cannot be read) although no errors were encountered |
| 288 |
while writing the disc. This consistency check makes sure that the data |
| 289 |
read from disc matches the data that was used to create the disc. |
| 290 |
|
| 291 |
The function mounts the device at a temporary mount point in the working |
| 292 |
directory, and then compares the indicated staging directories in the |
| 293 |
staging directory and on the media. The comparison is done via |
| 294 |
functionality in ``filesystem.py``. |
| 295 |
|
| 296 |
If no exceptions are thrown, there were no problems with the consistency |
| 297 |
check. A positive confirmation of "no problems" is also written to the log |
| 298 |
with ``info`` priority. |
| 299 |
|
| 300 |
@warning: The implementation of this function is very UNIX-specific. |
| 301 |
|
| 302 |
Args: |
| 303 |
config: Config object |
| 304 |
stagingDirs: Dictionary mapping directory path to date suffix |
| 305 |
|
| 306 |
Raises: |
| 307 |
ValueError: If the two directories are not equivalent |
| 308 |
IOError: If there is a problem working with the media |
| 309 |
""" |
| 310 |
logger.debug("Running consistency check.") |
| 311 |
mountPoint = tempfile.mkdtemp(dir=config.options.workingDir) |
| 312 |
try: |
| 313 |
mount(config.store.devicePath, mountPoint, "iso9660") |
| 314 |
for stagingDir in list(stagingDirs.keys()): |
| 315 |
discDir = pathJoin(mountPoint, stagingDirs[stagingDir]) |
| 316 |
logger.debug("Checking [%s] vs. [%s].", stagingDir, discDir) |
| 317 |
compareContents(stagingDir, discDir, verbose=True) |
| 318 |
logger.info("Consistency check completed for [%s]. No problems found.", stagingDir) |
| 319 |
finally: |
| 320 |
unmount(mountPoint, True, 5, 1) # try 5 times, and remove mount point when done |
| 321 |
|
| 322 |
|
| 323 |
######################################################################## |
| 324 |
# Private utility functions |
| 325 |
######################################################################## |
| 326 |
|
| 327 |
######################### |
| 328 |
# _findCorrectDailyDir() |
| 329 |
######################### |
| 330 |
|
| 331 |
|
| 332 |
def _findCorrectDailyDir(options, config): |
| 333 |
""" |
| 334 |
Finds the correct daily staging directory to be written to disk. |
| 335 |
|
| 336 |
In Cedar Backup v1.0, we assumed that the correct staging directory matched |
| 337 |
the current date. However, that has problems. In particular, it breaks |
| 338 |
down if collect is on one side of midnite and stage is on the other, or if |
| 339 |
certain processes span midnite. |
| 340 |
|
| 341 |
For v2.0, I'm trying to be smarter. I'll first check the current day. If |
| 342 |
that directory is found, it's good enough. If it's not found, I'll look for |
| 343 |
a valid directory from the day before or day after I{which has not yet been |
| 344 |
staged, according to the stage indicator file}. The first one I find, I'll |
| 345 |
use. If I use a directory other than for the current day *and* |
| 346 |
``config.store.warnMidnite`` is set, a warning will be put in the log. |
| 347 |
|
| 348 |
There is one exception to this rule. If the ``options.full`` flag is set, |
| 349 |
then the special "span midnite" logic will be disabled and any existing |
| 350 |
store indicator will be ignored. I did this because I think that most users |
| 351 |
who run ``cback3 --full store`` twice in a row expect the command to generate |
| 352 |
two identical discs. With the other rule in place, running that command |
| 353 |
twice in a row could result in an error ("no unstored directory exists") or |
| 354 |
could even cause a completely unexpected directory to be written to disc (if |
| 355 |
some previous day's contents had not yet been written). |
| 356 |
|
| 357 |
*Note:* This code is probably longer and more verbose than it needs to be, |
| 358 |
but at least it's straightforward. |
| 359 |
|
| 360 |
Args: |
| 361 |
options: Options object |
| 362 |
config: Config object |
| 363 |
|
| 364 |
Returns: |
| 365 |
Correct staging dir, as a dict mapping directory to date suffix |
| 366 |
Raises: |
| 367 |
IOError: If the staging directory cannot be found |
| 368 |
""" |
| 369 |
oneDay = datetime.timedelta(days=1) |
| 370 |
today = datetime.date.today() |
| 371 |
yesterday = today - oneDay |
| 372 |
tomorrow = today + oneDay |
| 373 |
todayDate = today.strftime(DIR_TIME_FORMAT) |
| 374 |
yesterdayDate = yesterday.strftime(DIR_TIME_FORMAT) |
| 375 |
tomorrowDate = tomorrow.strftime(DIR_TIME_FORMAT) |
| 376 |
todayPath = pathJoin(config.stage.targetDir, todayDate) |
| 377 |
yesterdayPath = pathJoin(config.stage.targetDir, yesterdayDate) |
| 378 |
tomorrowPath = pathJoin(config.stage.targetDir, tomorrowDate) |
| 379 |
todayStageInd = pathJoin(todayPath, STAGE_INDICATOR) |
| 380 |
yesterdayStageInd = pathJoin(yesterdayPath, STAGE_INDICATOR) |
| 381 |
tomorrowStageInd = pathJoin(tomorrowPath, STAGE_INDICATOR) |
| 382 |
todayStoreInd = pathJoin(todayPath, STORE_INDICATOR) |
| 383 |
yesterdayStoreInd = pathJoin(yesterdayPath, STORE_INDICATOR) |
| 384 |
tomorrowStoreInd = pathJoin(tomorrowPath, STORE_INDICATOR) |
| 385 |
if options.full: |
| 386 |
if os.path.isdir(todayPath) and os.path.exists(todayStageInd): |
| 387 |
logger.info("Store process will use current day's stage directory [%s]", todayPath) |
| 388 |
return {todayPath: todayDate} |
| 389 |
raise OSError("Unable to find staging directory to store (only tried today due to full option).") |
| 390 |
else: |
| 391 |
if os.path.isdir(todayPath) and os.path.exists(todayStageInd) and not os.path.exists(todayStoreInd): |
| 392 |
logger.info("Store process will use current day's stage directory [%s]", todayPath) |
| 393 |
return {todayPath: todayDate} |
| 394 |
elif os.path.isdir(yesterdayPath) and os.path.exists(yesterdayStageInd) and not os.path.exists(yesterdayStoreInd): |
| 395 |
logger.info("Store process will use previous day's stage directory [%s]", yesterdayPath) |
| 396 |
if config.store.warnMidnite: |
| 397 |
logger.warning("Warning: store process crossed midnite boundary to find data.") |
| 398 |
return {yesterdayPath: yesterdayDate} |
| 399 |
elif os.path.isdir(tomorrowPath) and os.path.exists(tomorrowStageInd) and not os.path.exists(tomorrowStoreInd): |
| 400 |
logger.info("Store process will use next day's stage directory [%s]", tomorrowPath) |
| 401 |
if config.store.warnMidnite: |
| 402 |
logger.warning("Warning: store process crossed midnite boundary to find data.") |
| 403 |
return {tomorrowPath: tomorrowDate} |
| 404 |
raise OSError("Unable to find unused staging directory to store (tried today, yesterday, tomorrow).") |