| 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 : Spans staged data among multiple discs |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Notes |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Spans staged data among multiple discs |
| 39 |
|
| 40 |
This is the Cedar Backup span tool. It is intended for use by people who stage |
| 41 |
more data than can fit on a single disc. It allows a user to split staged data |
| 42 |
among more than one disc. It can't be an extension because it requires user |
| 43 |
input when switching media. |
| 44 |
|
| 45 |
Most configuration is taken from the Cedar Backup configuration file, |
| 46 |
specifically the store section. A few pieces of configuration are taken |
| 47 |
directly from the user. |
| 48 |
|
| 49 |
:author: Kenneth J. Pronovici <[email protected]> |
| 50 |
""" |
| 51 |
|
| 52 |
######################################################################## |
| 53 |
# Imported modules and constants |
| 54 |
######################################################################## |
| 55 |
|
| 56 |
import logging |
| 57 |
import os |
| 58 |
import sys |
| 59 |
import tempfile |
| 60 |
|
| 61 |
from CedarBackup3.actions.constants import STORE_INDICATOR |
| 62 |
from CedarBackup3.actions.store import writeIndicatorFile |
| 63 |
from CedarBackup3.actions.util import createWriter, findDailyDirs |
| 64 |
from CedarBackup3.cli import ( |
| 65 |
DEFAULT_CONFIG, |
| 66 |
DEFAULT_LOGFILE, |
| 67 |
DEFAULT_MODE, |
| 68 |
DEFAULT_OWNERSHIP, |
| 69 |
Options, |
| 70 |
setupLogging, |
| 71 |
setupPathResolver, |
| 72 |
) |
| 73 |
from CedarBackup3.config import Config |
| 74 |
from CedarBackup3.filesystem import BackupFileList, compareDigestMaps, normalizeDir |
| 75 |
from CedarBackup3.release import AUTHOR, EMAIL, VERSION |
| 76 |
from CedarBackup3.util import UNIT_BYTES, UNIT_SECTORS, Diagnostics, convertSize, displayBytes, mount, unmount |
| 77 |
|
| 78 |
######################################################################## |
| 79 |
# Module-wide constants and variables |
| 80 |
######################################################################## |
| 81 |
|
| 82 |
logger = logging.getLogger("CedarBackup3.log.tools.span") |
| 83 |
|
| 84 |
|
| 85 |
####################################################################### |
| 86 |
# SpanOptions class |
| 87 |
####################################################################### |
| 88 |
|
| 89 |
|
| 90 |
class SpanOptions(Options): |
| 91 |
""" |
| 92 |
Tool-specific command-line options. |
| 93 |
|
| 94 |
Most of the cback3 command-line options are exactly what we need here -- |
| 95 |
logfile path, permissions, verbosity, etc. However, we need to make a few |
| 96 |
tweaks since we don't accept any actions. |
| 97 |
|
| 98 |
Also, a few extra command line options that we accept are really ignored |
| 99 |
underneath. I just don't care about that for a tool like this. |
| 100 |
""" |
| 101 |
|
| 102 |
def validate(self): |
| 103 |
""" |
| 104 |
Validates command-line options represented by the object. |
| 105 |
There are no validations here, because we don't use any actions. |
| 106 |
Raises: |
| 107 |
ValueError: If one of the validations fails |
| 108 |
""" |
| 109 |
|
| 110 |
|
| 111 |
####################################################################### |
| 112 |
# Public functions |
| 113 |
####################################################################### |
| 114 |
|
| 115 |
################# |
| 116 |
# cli() function |
| 117 |
################# |
| 118 |
|
| 119 |
|
| 120 |
def cli(): |
| 121 |
""" |
| 122 |
Implements the command-line interface for the ``cback3-span`` script. |
| 123 |
|
| 124 |
Essentially, this is the "main routine" for the cback3-span script. It does |
| 125 |
all of the argument processing for the script, and then also implements the |
| 126 |
tool functionality. |
| 127 |
|
| 128 |
This function looks pretty similiar to ``CedarBackup3.cli.cli()``. It's not |
| 129 |
easy to refactor this code to make it reusable and also readable, so I've |
| 130 |
decided to just live with the duplication. |
| 131 |
|
| 132 |
A different error code is returned for each type of failure: |
| 133 |
|
| 134 |
- ``1``: The Python interpreter version is not supported |
| 135 |
- ``2``: Error processing command-line arguments |
| 136 |
- ``3``: Error configuring logging |
| 137 |
- ``4``: Error parsing indicated configuration file |
| 138 |
- ``5``: Backup was interrupted with a CTRL-C or similar |
| 139 |
- ``6``: Error executing other parts of the script |
| 140 |
|
| 141 |
*Note:* This script uses print rather than logging to the INFO level, because |
| 142 |
it is interactive. Underlying Cedar Backup functionality uses the logging |
| 143 |
mechanism exclusively. |
| 144 |
|
| 145 |
Returns: |
| 146 |
Error code as described above |
| 147 |
""" |
| 148 |
try: |
| 149 |
if list(map(int, [sys.version_info[0], sys.version_info[1]])) < [3, 8]: |
| 150 |
sys.stderr.write("Python 3 version 3.8 or greater required.\n") |
| 151 |
return 1 |
| 152 |
except: |
| 153 |
# sys.version_info isn't available before 2.0 |
| 154 |
sys.stderr.write("Python 3 version 3.8 or greater required.\n") |
| 155 |
return 1 |
| 156 |
|
| 157 |
try: |
| 158 |
options = SpanOptions(argumentList=sys.argv[1:]) |
| 159 |
except Exception as e: |
| 160 |
_usage() |
| 161 |
sys.stderr.write(" *** Error: %s\n" % e) |
| 162 |
return 2 |
| 163 |
|
| 164 |
if options.help: |
| 165 |
_usage() |
| 166 |
return 0 |
| 167 |
if options.version: |
| 168 |
_version() |
| 169 |
return 0 |
| 170 |
if options.diagnostics: |
| 171 |
_diagnostics() |
| 172 |
return 0 |
| 173 |
|
| 174 |
if options.stacktrace: |
| 175 |
logfile = setupLogging(options) |
| 176 |
else: |
| 177 |
try: |
| 178 |
logfile = setupLogging(options) |
| 179 |
except Exception as e: |
| 180 |
sys.stderr.write("Error setting up logging: %s\n" % e) |
| 181 |
return 3 |
| 182 |
|
| 183 |
logger.info("Cedar Backup 'span' utility run started.") |
| 184 |
logger.info("Options were [%s]", options) |
| 185 |
logger.info("Logfile is [%s]", logfile) |
| 186 |
|
| 187 |
if options.config is None: |
| 188 |
logger.debug("Using default configuration file.") |
| 189 |
configPath = DEFAULT_CONFIG |
| 190 |
else: |
| 191 |
logger.debug("Using user-supplied configuration file.") |
| 192 |
configPath = options.config |
| 193 |
|
| 194 |
try: |
| 195 |
logger.info("Configuration path is [%s]", configPath) |
| 196 |
config = Config(xmlPath=configPath) |
| 197 |
setupPathResolver(config) |
| 198 |
except Exception as e: |
| 199 |
logger.error("Error reading or handling configuration: %s", e) |
| 200 |
logger.info("Cedar Backup 'span' utility run completed with status 4.") |
| 201 |
return 4 |
| 202 |
|
| 203 |
if options.stacktrace: |
| 204 |
_executeAction(options, config) |
| 205 |
else: |
| 206 |
try: |
| 207 |
_executeAction(options, config) |
| 208 |
except KeyboardInterrupt: |
| 209 |
logger.error("Backup interrupted.") |
| 210 |
logger.info("Cedar Backup 'span' utility run completed with status 5.") |
| 211 |
return 5 |
| 212 |
except Exception as e: |
| 213 |
logger.error("Error executing backup: %s", e) |
| 214 |
logger.info("Cedar Backup 'span' utility run completed with status 6.") |
| 215 |
return 6 |
| 216 |
|
| 217 |
logger.info("Cedar Backup 'span' utility run completed with status 0.") |
| 218 |
return 0 |
| 219 |
|
| 220 |
|
| 221 |
####################################################################### |
| 222 |
# Utility functions |
| 223 |
####################################################################### |
| 224 |
|
| 225 |
#################### |
| 226 |
# _usage() function |
| 227 |
#################### |
| 228 |
|
| 229 |
|
| 230 |
def _usage(fd=sys.stderr): |
| 231 |
""" |
| 232 |
Prints usage information for the cback3-span script. |
| 233 |
Args: |
| 234 |
fd: File descriptor used to print information |
| 235 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 236 |
""" |
| 237 |
fd.write("\n") |
| 238 |
fd.write(" Usage: cback3-span [switches]\n") |
| 239 |
fd.write("\n") |
| 240 |
fd.write(" Cedar Backup 'span' tool.\n") |
| 241 |
fd.write("\n") |
| 242 |
fd.write(" This Cedar Backup utility spans staged data between multiple discs.\n") |
| 243 |
fd.write(" It is a utility, not an extension, and requires user interaction.\n") |
| 244 |
fd.write("\n") |
| 245 |
fd.write(" The following switches are accepted, mostly to set up underlying\n") |
| 246 |
fd.write(" Cedar Backup functionality:\n") |
| 247 |
fd.write("\n") |
| 248 |
fd.write(" -h, --help Display this usage/help listing\n") |
| 249 |
fd.write(" -V, --version Display version information\n") |
| 250 |
fd.write(" -b, --verbose Print verbose output as well as logging to disk\n") |
| 251 |
fd.write(" -c, --config Path to config file (default: %s)\n" % DEFAULT_CONFIG) |
| 252 |
fd.write(" -l, --logfile Path to logfile (default: %s)\n" % DEFAULT_LOGFILE) |
| 253 |
fd.write(" -o, --owner Logfile ownership, user:group (default: %s:%s)\n" % (DEFAULT_OWNERSHIP[0], DEFAULT_OWNERSHIP[1])) |
| 254 |
fd.write(" -m, --mode Octal logfile permissions mode (default: %o)\n" % DEFAULT_MODE) |
| 255 |
fd.write(" -O, --output Record some sub-command (i.e. tar) output to the log\n") |
| 256 |
fd.write(" -d, --debug Write debugging information to the log (implies --output)\n") |
| 257 |
fd.write(" -s, --stack Dump a Python stack trace instead of swallowing exceptions\n") |
| 258 |
fd.write("\n") |
| 259 |
|
| 260 |
|
| 261 |
###################### |
| 262 |
# _version() function |
| 263 |
###################### |
| 264 |
|
| 265 |
|
| 266 |
def _version(fd=sys.stdout): |
| 267 |
""" |
| 268 |
Prints version information for the cback3-span script. |
| 269 |
Args: |
| 270 |
fd: File descriptor used to print information |
| 271 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 272 |
""" |
| 273 |
fd.write("\n") |
| 274 |
fd.write(" Cedar Backup 'span' tool.\n") |
| 275 |
fd.write(" Included with Cedar Backup version %s.\n" % VERSION) |
| 276 |
fd.write("\n") |
| 277 |
fd.write(" Copyright (c) %s <%s>.\n" % (AUTHOR, EMAIL)) |
| 278 |
fd.write(" See NOTICE for a list of included code and other contributors.\n") |
| 279 |
fd.write(" This is free software; there is NO warranty. See the\n") |
| 280 |
fd.write(" GNU General Public License version 2 for copying conditions.\n") |
| 281 |
fd.write("\n") |
| 282 |
fd.write(" Use the --help option for usage information.\n") |
| 283 |
fd.write("\n") |
| 284 |
|
| 285 |
|
| 286 |
########################## |
| 287 |
# _diagnostics() function |
| 288 |
########################## |
| 289 |
|
| 290 |
|
| 291 |
def _diagnostics(fd=sys.stdout): |
| 292 |
""" |
| 293 |
Prints runtime diagnostics information. |
| 294 |
Args: |
| 295 |
fd: File descriptor used to print information |
| 296 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 297 |
""" |
| 298 |
fd.write("\n") |
| 299 |
fd.write("Diagnostics:\n") |
| 300 |
fd.write("\n") |
| 301 |
Diagnostics().printDiagnostics(fd=fd, prefix=" ") |
| 302 |
fd.write("\n") |
| 303 |
|
| 304 |
|
| 305 |
############################ |
| 306 |
# _executeAction() function |
| 307 |
############################ |
| 308 |
|
| 309 |
|
| 310 |
def _executeAction(options, config): # ruff: ignore[unused-function-argument] |
| 311 |
""" |
| 312 |
Implements the guts of the cback3-span tool. |
| 313 |
|
| 314 |
Args: |
| 315 |
options (SpanOptions object): Program command-line options |
| 316 |
config (Config object): Program configuration |
| 317 |
Raises: |
| 318 |
Exception: Under many generic error conditions |
| 319 |
""" |
| 320 |
print() |
| 321 |
print("================================================") |
| 322 |
print(" Cedar Backup 'span' tool") |
| 323 |
print("================================================") |
| 324 |
print() |
| 325 |
print("This the Cedar Backup span tool. It is used to split up staging") |
| 326 |
print("data when that staging data does not fit onto a single disc.") |
| 327 |
print() |
| 328 |
print("This utility operates using Cedar Backup configuration. Configuration") |
| 329 |
print("specifies which staging directory to look at and which writer device") |
| 330 |
print("and media type to use.") |
| 331 |
print() |
| 332 |
if not _getYesNoAnswer("Continue?", default="Y"): |
| 333 |
return |
| 334 |
print("===") |
| 335 |
|
| 336 |
print() |
| 337 |
print("Cedar Backup store configuration looks like this:") |
| 338 |
print() |
| 339 |
print(" Source Directory...: %s" % config.store.sourceDir) |
| 340 |
print(" Media Type.........: %s" % config.store.mediaType) |
| 341 |
print(" Device Type........: %s" % config.store.deviceType) |
| 342 |
print(" Device Path........: %s" % config.store.devicePath) |
| 343 |
print(" Device SCSI ID.....: %s" % config.store.deviceScsiId) |
| 344 |
print(" Drive Speed........: %s" % config.store.driveSpeed) |
| 345 |
print(" Check Data Flag....: %s" % config.store.checkData) |
| 346 |
print(" No Eject Flag......: %s" % config.store.noEject) |
| 347 |
print() |
| 348 |
if not _getYesNoAnswer("Is this OK?", default="Y"): |
| 349 |
return |
| 350 |
print("===") |
| 351 |
|
| 352 |
(writer, mediaCapacity) = _getWriter(config) |
| 353 |
|
| 354 |
print() |
| 355 |
print("Please wait, indexing the source directory (this may take a while)...") |
| 356 |
(dailyDirs, fileList) = _findDailyDirs(config.store.sourceDir) |
| 357 |
print("===") |
| 358 |
|
| 359 |
print() |
| 360 |
print("The following daily staging directories have not yet been written to disc:") |
| 361 |
print() |
| 362 |
for dailyDir in dailyDirs: |
| 363 |
print(" %s" % dailyDir) |
| 364 |
|
| 365 |
totalSize = fileList.totalSize() |
| 366 |
print() |
| 367 |
print("The total size of the data in these directories is %s." % displayBytes(totalSize)) |
| 368 |
print() |
| 369 |
if not _getYesNoAnswer("Continue?", default="Y"): |
| 370 |
return |
| 371 |
print("===") |
| 372 |
|
| 373 |
print() |
| 374 |
print("Based on configuration, the capacity of your media is %s." % displayBytes(mediaCapacity)) |
| 375 |
|
| 376 |
print() |
| 377 |
print("Since estimates are not perfect and there is some uncertainly in") |
| 378 |
print('media capacity calculations, it is good to have a "cushion",') |
| 379 |
print("a percentage of capacity to set aside. The cushion reduces the") |
| 380 |
print("capacity of your media, so a 1.5% cushion leaves 98.5% remaining.") |
| 381 |
print() |
| 382 |
cushion = _getFloat("What cushion percentage?", default=4.5) |
| 383 |
print("===") |
| 384 |
|
| 385 |
realCapacity = ((100.0 - cushion) / 100.0) * mediaCapacity |
| 386 |
minimumDiscs = (totalSize / realCapacity) + 1 |
| 387 |
print() |
| 388 |
print("The real capacity, taking into account the %.2f%% cushion, is %s." % (cushion, displayBytes(realCapacity))) |
| 389 |
print("It will take at least %d disc(s) to store your %s of data." % (minimumDiscs, displayBytes(totalSize))) |
| 390 |
print() |
| 391 |
if not _getYesNoAnswer("Continue?", default="Y"): |
| 392 |
return |
| 393 |
print("===") |
| 394 |
|
| 395 |
happy = False |
| 396 |
while not happy: |
| 397 |
print() |
| 398 |
print("Which algorithm do you want to use to span your data across") |
| 399 |
print("multiple discs?") |
| 400 |
print() |
| 401 |
print("The following algorithms are available:") |
| 402 |
print() |
| 403 |
print(' first....: The "first-fit" algorithm') |
| 404 |
print(' best.....: The "best-fit" algorithm') |
| 405 |
print(' worst....: The "worst-fit" algorithm') |
| 406 |
print(' alternate: The "alternate-fit" algorithm') |
| 407 |
print() |
| 408 |
print("If you don't like the results you will have a chance to try a") |
| 409 |
print("different one later.") |
| 410 |
print() |
| 411 |
algorithm = _getChoiceAnswer("Which algorithm?", "worst", ["first", "best", "worst", "alternate"]) |
| 412 |
print("===") |
| 413 |
|
| 414 |
print() |
| 415 |
print("Please wait, generating file lists (this may take a while)...") |
| 416 |
spanSet = fileList.generateSpan(capacity=realCapacity, algorithm="%s_fit" % algorithm) |
| 417 |
print("===") |
| 418 |
|
| 419 |
print() |
| 420 |
print('Using the "%s-fit" algorithm, Cedar Backup can split your data' % algorithm) |
| 421 |
print("into %d discs." % len(spanSet)) |
| 422 |
print() |
| 423 |
counter = 0 |
| 424 |
for item in spanSet: |
| 425 |
counter += 1 # ruff: ignore[enumerate-for-loop] |
| 426 |
print( |
| 427 |
"Disc %d: %d files, %s, %.2f%% utilization" |
| 428 |
% (counter, len(item.fileList), displayBytes(item.size), item.utilization) |
| 429 |
) |
| 430 |
print() |
| 431 |
if _getYesNoAnswer("Accept this solution?", default="Y"): |
| 432 |
happy = True |
| 433 |
print("===") |
| 434 |
|
| 435 |
counter = 0 |
| 436 |
for spanItem in spanSet: |
| 437 |
counter += 1 # ruff: ignore[enumerate-for-loop] |
| 438 |
if counter == 1: |
| 439 |
print() |
| 440 |
_getReturn("Please place the first disc in your backup device.\nPress return when ready.") |
| 441 |
print("===") |
| 442 |
else: |
| 443 |
print() |
| 444 |
_getReturn("Please replace the disc in your backup device.\nPress return when ready.") |
| 445 |
print("===") |
| 446 |
_writeDisc(config, writer, spanItem) |
| 447 |
|
| 448 |
_writeStoreIndicator(config, dailyDirs) |
| 449 |
|
| 450 |
print() |
| 451 |
print("Completed writing all discs.") |
| 452 |
|
| 453 |
|
| 454 |
############################ |
| 455 |
# _findDailyDirs() function |
| 456 |
############################ |
| 457 |
|
| 458 |
|
| 459 |
def _findDailyDirs(stagingDir): |
| 460 |
""" |
| 461 |
Returns a list of all daily staging directories that have not yet been |
| 462 |
stored. |
| 463 |
|
| 464 |
The store indicator file ``cback.store`` will be written to a daily staging |
| 465 |
directory once that directory is written to disc. So, this function looks |
| 466 |
at each daily staging directory within the configured staging directory, and |
| 467 |
returns a list of those which do not contain the indicator file. |
| 468 |
|
| 469 |
Returned is a tuple containing two items: a list of daily staging |
| 470 |
directories, and a BackupFileList containing all files among those staging |
| 471 |
directories. |
| 472 |
|
| 473 |
Args: |
| 474 |
stagingDir: Configured staging directory |
| 475 |
|
| 476 |
Returns: |
| 477 |
Tuple (staging dirs, backup file list) |
| 478 |
""" |
| 479 |
results = findDailyDirs(stagingDir, STORE_INDICATOR) |
| 480 |
fileList = BackupFileList() |
| 481 |
for item in results: |
| 482 |
fileList.addDirContents(item) |
| 483 |
return (results, fileList) |
| 484 |
|
| 485 |
|
| 486 |
################################## |
| 487 |
# _writeStoreIndicator() function |
| 488 |
################################## |
| 489 |
|
| 490 |
|
| 491 |
def _writeStoreIndicator(config, dailyDirs): |
| 492 |
""" |
| 493 |
Writes a store indicator file into daily directories. |
| 494 |
|
| 495 |
Args: |
| 496 |
config: Config object |
| 497 |
dailyDirs: List of daily directories |
| 498 |
""" |
| 499 |
for dailyDir in dailyDirs: |
| 500 |
writeIndicatorFile(dailyDir, STORE_INDICATOR, config.options.backupUser, config.options.backupGroup) |
| 501 |
|
| 502 |
|
| 503 |
######################## |
| 504 |
# _getWriter() function |
| 505 |
######################## |
| 506 |
|
| 507 |
|
| 508 |
def _getWriter(config): |
| 509 |
""" |
| 510 |
Gets a writer and media capacity from store configuration. |
| 511 |
Returned is a writer and a media capacity in bytes. |
| 512 |
Args: |
| 513 |
config: Cedar Backup configuration |
| 514 |
Returns: |
| 515 |
Tuple of (writer, mediaCapacity) |
| 516 |
""" |
| 517 |
writer = createWriter(config) |
| 518 |
mediaCapacity = convertSize(writer.media.capacity, UNIT_SECTORS, UNIT_BYTES) |
| 519 |
return (writer, mediaCapacity) |
| 520 |
|
| 521 |
|
| 522 |
######################## |
| 523 |
# _writeDisc() function |
| 524 |
######################## |
| 525 |
|
| 526 |
|
| 527 |
def _writeDisc(config, writer, spanItem): |
| 528 |
""" |
| 529 |
Writes a span item to disc. |
| 530 |
Args: |
| 531 |
config: Cedar Backup configuration |
| 532 |
writer: Writer to use |
| 533 |
spanItem: Span item to write |
| 534 |
""" |
| 535 |
print() |
| 536 |
_discInitializeImage(config, writer, spanItem) |
| 537 |
_discWriteImage(config, writer) |
| 538 |
_discConsistencyCheck(config, writer, spanItem) |
| 539 |
print("Write process is complete.") |
| 540 |
print("===") |
| 541 |
|
| 542 |
|
| 543 |
def _discInitializeImage(config, writer, spanItem): |
| 544 |
""" |
| 545 |
Initialize an ISO image for a span item. |
| 546 |
Args: |
| 547 |
config: Cedar Backup configuration |
| 548 |
writer: Writer to use |
| 549 |
spanItem: Span item to write |
| 550 |
""" |
| 551 |
complete = False |
| 552 |
while not complete: |
| 553 |
try: |
| 554 |
print("Initializing image...") |
| 555 |
writer.initializeImage(newDisc=True, tmpdir=config.options.workingDir) |
| 556 |
for path in spanItem.fileList: |
| 557 |
graftPoint = os.path.dirname(path.replace(config.store.sourceDir, "", 1)) |
| 558 |
writer.addImageEntry(path, graftPoint) |
| 559 |
complete = True |
| 560 |
except KeyboardInterrupt as e: |
| 561 |
raise e |
| 562 |
except Exception as e: |
| 563 |
logger.error("Failed to initialize image: %s", e) |
| 564 |
if not _getYesNoAnswer("Retry initialization step?", default="Y"): |
| 565 |
raise e |
| 566 |
print("Ok, attempting retry.") |
| 567 |
print("===") |
| 568 |
print("Completed initializing image.") |
| 569 |
|
| 570 |
|
| 571 |
def _discWriteImage(config, writer): # ruff: ignore[unused-function-argument] |
| 572 |
""" |
| 573 |
Writes a ISO image for a span item. |
| 574 |
Args: |
| 575 |
config: Cedar Backup configuration |
| 576 |
writer: Writer to use |
| 577 |
""" |
| 578 |
complete = False |
| 579 |
while not complete: |
| 580 |
try: |
| 581 |
print("Writing image to disc...") |
| 582 |
writer.writeImage() |
| 583 |
complete = True |
| 584 |
except KeyboardInterrupt as e: |
| 585 |
raise e |
| 586 |
except Exception as e: |
| 587 |
logger.error("Failed to write image: %s", e) |
| 588 |
if not _getYesNoAnswer("Retry this step?", default="Y"): |
| 589 |
raise e |
| 590 |
print("Ok, attempting retry.") |
| 591 |
_getReturn("Please replace media if needed.\nPress return when ready.") |
| 592 |
print("===") |
| 593 |
print("Completed writing image.") |
| 594 |
|
| 595 |
|
| 596 |
def _discConsistencyCheck(config, writer, spanItem): |
| 597 |
""" |
| 598 |
Run a consistency check on an ISO image for a span item. |
| 599 |
Args: |
| 600 |
config: Cedar Backup configuration |
| 601 |
writer: Writer to use |
| 602 |
spanItem: Span item to write |
| 603 |
""" |
| 604 |
if config.store.checkData: |
| 605 |
complete = False |
| 606 |
while not complete: |
| 607 |
try: |
| 608 |
print("Running consistency check...") |
| 609 |
_consistencyCheck(config, spanItem.fileList) |
| 610 |
complete = True |
| 611 |
except KeyboardInterrupt as e: |
| 612 |
raise e |
| 613 |
except Exception as e: |
| 614 |
logger.error("Consistency check failed: %s", e) |
| 615 |
if not _getYesNoAnswer("Retry the consistency check?", default="Y"): |
| 616 |
raise e |
| 617 |
if _getYesNoAnswer("Rewrite the disc first?", default="N"): |
| 618 |
print("Ok, attempting retry.") |
| 619 |
_getReturn("Please replace the disc in your backup device.\nPress return when ready.") |
| 620 |
print("===") |
| 621 |
_discWriteImage(config, writer) |
| 622 |
else: |
| 623 |
print("Ok, attempting retry.") |
| 624 |
print("===") |
| 625 |
print("Completed consistency check.") |
| 626 |
|
| 627 |
|
| 628 |
############################### |
| 629 |
# _consistencyCheck() function |
| 630 |
############################### |
| 631 |
|
| 632 |
|
| 633 |
def _consistencyCheck(config, fileList): |
| 634 |
""" |
| 635 |
Runs a consistency check against media in the backup device. |
| 636 |
|
| 637 |
The function mounts the device at a temporary mount point in the working |
| 638 |
directory, and then compares the passed-in file list's digest map with the |
| 639 |
one generated from the disc. The two lists should be identical. |
| 640 |
|
| 641 |
If no exceptions are thrown, there were no problems with the consistency |
| 642 |
check. |
| 643 |
|
| 644 |
@warning: The implementation of this function is very UNIX-specific. |
| 645 |
|
| 646 |
Args: |
| 647 |
config: Config object |
| 648 |
fileList: BackupFileList whose contents to check against |
| 649 |
|
| 650 |
Raises: |
| 651 |
ValueError: If the check fails |
| 652 |
IOError: If there is a problem working with the media |
| 653 |
""" |
| 654 |
logger.debug("Running consistency check.") |
| 655 |
mountPoint = tempfile.mkdtemp(dir=config.options.workingDir) |
| 656 |
try: |
| 657 |
mount(config.store.devicePath, mountPoint, "iso9660") |
| 658 |
discList = BackupFileList() |
| 659 |
discList.addDirContents(mountPoint) |
| 660 |
sourceList = BackupFileList() |
| 661 |
sourceList.extend(fileList) |
| 662 |
discListDigest = discList.generateDigestMap(stripPrefix=normalizeDir(mountPoint)) |
| 663 |
sourceListDigest = sourceList.generateDigestMap(stripPrefix=normalizeDir(config.store.sourceDir)) |
| 664 |
compareDigestMaps(sourceListDigest, discListDigest, verbose=True) |
| 665 |
logger.info("Consistency check completed. No problems found.") |
| 666 |
finally: |
| 667 |
unmount(mountPoint, True, 5, 1) # try 5 times, and remove mount point when done |
| 668 |
|
| 669 |
|
| 670 |
######################################################################### |
| 671 |
# User interface utilities |
| 672 |
######################################################################## |
| 673 |
|
| 674 |
|
| 675 |
def _getYesNoAnswer(prompt, default): |
| 676 |
""" |
| 677 |
Get a yes/no answer from the user. |
| 678 |
The default will be placed at the end of the prompt. |
| 679 |
A "Y" or "y" is considered yes, anything else no. |
| 680 |
A blank (empty) response results in the default. |
| 681 |
Args: |
| 682 |
prompt: Prompt to show |
| 683 |
default: Default to set if the result is blank |
| 684 |
Returns: |
| 685 |
Boolean true/false corresponding to Y/N |
| 686 |
""" |
| 687 |
if default == "Y": |
| 688 |
prompt = "%s [Y/n]: " % prompt |
| 689 |
else: |
| 690 |
prompt = "%s [y/N]: " % prompt |
| 691 |
answer = input(prompt) |
| 692 |
if answer in [None, ""]: |
| 693 |
answer = default |
| 694 |
return answer[0] in ["Y", "y"] |
| 695 |
|
| 696 |
|
| 697 |
def _getChoiceAnswer(prompt, default, validChoices): |
| 698 |
""" |
| 699 |
Get a particular choice from the user. |
| 700 |
The default will be placed at the end of the prompt. |
| 701 |
The function loops until getting a valid choice. |
| 702 |
A blank (empty) response results in the default. |
| 703 |
Args: |
| 704 |
prompt: Prompt to show |
| 705 |
default: Default to set if the result is None or blank |
| 706 |
validChoices: List of valid choices (strings) |
| 707 |
Returns: |
| 708 |
Valid choice from user |
| 709 |
""" |
| 710 |
prompt = "%s [%s]: " % (prompt, default) |
| 711 |
answer = input(prompt) |
| 712 |
if answer in [None, ""]: |
| 713 |
answer = default |
| 714 |
while answer not in validChoices: |
| 715 |
print("Choice must be one of %s" % validChoices) |
| 716 |
answer = input(prompt) |
| 717 |
return answer |
| 718 |
|
| 719 |
|
| 720 |
def _getFloat(prompt, default): |
| 721 |
""" |
| 722 |
Get a floating point number from the user. |
| 723 |
The default will be placed at the end of the prompt. |
| 724 |
The function loops until getting a valid floating point number. |
| 725 |
A blank (empty) response results in the default. |
| 726 |
Args: |
| 727 |
prompt: Prompt to show |
| 728 |
default: Default to set if the result is None or blank |
| 729 |
Returns: |
| 730 |
Floating point number from user |
| 731 |
""" |
| 732 |
prompt = "%s [%.2f]: " % (prompt, default) |
| 733 |
while True: |
| 734 |
answer = input(prompt) |
| 735 |
if answer in [None, ""]: |
| 736 |
return default |
| 737 |
else: |
| 738 |
try: |
| 739 |
return float(answer) |
| 740 |
except ValueError: |
| 741 |
print("Enter a floating point number.") |
| 742 |
|
| 743 |
|
| 744 |
def _getReturn(prompt): |
| 745 |
""" |
| 746 |
Get a return key from the user. |
| 747 |
Args: |
| 748 |
prompt: Prompt to show |
| 749 |
""" |
| 750 |
input(prompt) |
| 751 |
|
| 752 |
|
| 753 |
######################################################################### |
| 754 |
# Main routine |
| 755 |
######################################################################## |
| 756 |
|
| 757 |
if __name__ == "__main__": |
| 758 |
sys.exit(cli()) |