| 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) 2014-2016,2020 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 : Cedar Backup tool to synchronize an Amazon S3 bucket. |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Notes |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Synchonizes a local directory with an Amazon S3 bucket. |
| 39 |
|
| 40 |
No configuration is required; all necessary information is taken from the |
| 41 |
command-line. The only thing configuration would help with is the path |
| 42 |
resolver interface, and it doesn't seem worth it to require configuration just |
| 43 |
to get that. |
| 44 |
|
| 45 |
:author: Kenneth J. Pronovici <[email protected]> |
| 46 |
""" |
| 47 |
|
| 48 |
######################################################################## |
| 49 |
# Imported modules and constants |
| 50 |
######################################################################## |
| 51 |
|
| 52 |
# Note: getopt is "soft deprecated" only and is safe to use; see: https://github.com/python/cpython/pull/105735 |
| 53 |
|
| 54 |
import getopt |
| 55 |
import json |
| 56 |
import logging |
| 57 |
import os |
| 58 |
import sys |
| 59 |
import warnings |
| 60 |
from functools import total_ordering |
| 61 |
from pathlib import Path |
| 62 |
|
| 63 |
import chardet |
| 64 |
|
| 65 |
from CedarBackup3.cli import DEFAULT_LOGFILE, DEFAULT_MODE, DEFAULT_OWNERSHIP, setupLogging |
| 66 |
from CedarBackup3.filesystem import FilesystemList |
| 67 |
from CedarBackup3.release import AUTHOR, EMAIL, VERSION |
| 68 |
from CedarBackup3.util import Diagnostics, encodePath, executeCommand, splitCommandLine |
| 69 |
|
| 70 |
######################################################################## |
| 71 |
# Module-wide constants and variables |
| 72 |
######################################################################## |
| 73 |
|
| 74 |
logger = logging.getLogger("CedarBackup3.log.tools.amazons3") |
| 75 |
|
| 76 |
AWS_COMMAND = ["aws"] |
| 77 |
|
| 78 |
SHORT_SWITCHES = "hVbql:o:m:OdsDvuw" |
| 79 |
LONG_SWITCHES = [ |
| 80 |
"help", |
| 81 |
"version", |
| 82 |
"verbose", |
| 83 |
"quiet", |
| 84 |
"logfile=", |
| 85 |
"owner=", |
| 86 |
"mode=", |
| 87 |
"output", |
| 88 |
"debug", |
| 89 |
"stack", |
| 90 |
"diagnostics", |
| 91 |
"verifyOnly", |
| 92 |
"uploadOnly", |
| 93 |
"ignoreWarnings", |
| 94 |
] |
| 95 |
|
| 96 |
|
| 97 |
####################################################################### |
| 98 |
# Options class |
| 99 |
####################################################################### |
| 100 |
|
| 101 |
|
| 102 |
@total_ordering |
| 103 |
class Options: |
| 104 |
###################### |
| 105 |
# Class documentation |
| 106 |
###################### |
| 107 |
|
| 108 |
""" |
| 109 |
Class representing command-line options for the cback3-amazons3-sync script. |
| 110 |
|
| 111 |
The ``Options`` class is a Python object representation of the command-line |
| 112 |
options of the cback3-amazons3-sync script. |
| 113 |
|
| 114 |
The object representation is two-way: a command line string or a list of |
| 115 |
command line arguments can be used to create an ``Options`` object, and then |
| 116 |
changes to the object can be propogated back to a list of command-line |
| 117 |
arguments or to a command-line string. An ``Options`` object can even be |
| 118 |
created from scratch programmatically (if you have a need for that). |
| 119 |
|
| 120 |
There are two main levels of validation in the ``Options`` class. The first |
| 121 |
is field-level validation. Field-level validation comes into play when a |
| 122 |
given field in an object is assigned to or updated. We use Python's |
| 123 |
``property`` functionality to enforce specific validations on field values, |
| 124 |
and in some places we even use customized list classes to enforce |
| 125 |
validations on list members. You should expect to catch a ``ValueError`` |
| 126 |
exception when making assignments to fields if you are programmatically |
| 127 |
filling an object. |
| 128 |
|
| 129 |
The second level of validation is post-completion validation. Certain |
| 130 |
validations don't make sense until an object representation of options is |
| 131 |
fully "complete". We don't want these validations to apply all of the time, |
| 132 |
because it would make building up a valid object from scratch a real pain. |
| 133 |
For instance, we might have to do things in the right order to keep from |
| 134 |
throwing exceptions, etc. |
| 135 |
|
| 136 |
All of these post-completion validations are encapsulated in the |
| 137 |
:any:`Options.validate` method. This method can be called at any time by a |
| 138 |
client, and will always be called immediately after creating a ``Options`` |
| 139 |
object from a command line and before exporting a ``Options`` object back to |
| 140 |
a command line. This way, we get acceptable ease-of-use but we also don't |
| 141 |
accept or emit invalid command lines. |
| 142 |
|
| 143 |
*Note:* Lists within this class are "unordered" for equality comparisons. |
| 144 |
|
| 145 |
""" |
| 146 |
|
| 147 |
############## |
| 148 |
# Constructor |
| 149 |
############## |
| 150 |
|
| 151 |
def __init__(self, argumentList=None, argumentString=None, validate=True): |
| 152 |
""" |
| 153 |
Initializes an options object. |
| 154 |
|
| 155 |
If you initialize the object without passing either ``argumentList`` or |
| 156 |
``argumentString``, the object will be empty and will be invalid until it |
| 157 |
is filled in properly. |
| 158 |
|
| 159 |
No reference to the original arguments is saved off by this class. Once |
| 160 |
the data has been parsed (successfully or not) this original information |
| 161 |
is discarded. |
| 162 |
|
| 163 |
The argument list is assumed to be a list of arguments, not including the |
| 164 |
name of the command, something like ``sys.argv[1:]``. If you pass |
| 165 |
``sys.argv`` instead, things are not going to work. |
| 166 |
|
| 167 |
The argument string will be parsed into an argument list by the |
| 168 |
:any:`util.splitCommandLine` function (see the documentation for that |
| 169 |
function for some important notes about its limitations). There is an |
| 170 |
assumption that the resulting list will be equivalent to ``sys.argv[1:]``, |
| 171 |
just like ``argumentList``. |
| 172 |
|
| 173 |
Unless the ``validate`` argument is ``False``, the :any:`Options.validate` |
| 174 |
method will be called (with its default arguments) after successfully |
| 175 |
parsing any passed-in command line. This validation ensures that |
| 176 |
appropriate actions, etc. have been specified. Keep in mind that even if |
| 177 |
``validate`` is ``False``, it might not be possible to parse the passed-in |
| 178 |
command line, so an exception might still be raised. |
| 179 |
|
| 180 |
*Note:* The command line format is specified by the ``_usage`` function. |
| 181 |
Call ``_usage`` to see a usage statement for the cback3-amazons3-sync script. |
| 182 |
|
| 183 |
*Note:* It is strongly suggested that the ``validate`` option always be set |
| 184 |
to ``True`` (the default) unless there is a specific need to read in |
| 185 |
invalid command line arguments. |
| 186 |
|
| 187 |
Args: |
| 188 |
argumentList (List of arguments, i.e. ``sys.argv``): Command line for a program |
| 189 |
argumentString (String, i.e. "cback3-amazons3-sync --verbose stage store"): Command line for a program |
| 190 |
validate (Boolean true/false): Validate the command line after parsing it |
| 191 |
Raises: |
| 192 |
getopt.GetoptError: If the command-line arguments could not be parsed |
| 193 |
ValueError: If the command-line arguments are invalid |
| 194 |
""" |
| 195 |
self._help = False |
| 196 |
self._version = False |
| 197 |
self._verbose = False |
| 198 |
self._quiet = False |
| 199 |
self._logfile = None |
| 200 |
self._owner = None |
| 201 |
self._mode = None |
| 202 |
self._output = False |
| 203 |
self._debug = False |
| 204 |
self._stacktrace = False |
| 205 |
self._diagnostics = False |
| 206 |
self._verifyOnly = False |
| 207 |
self._uploadOnly = False |
| 208 |
self._ignoreWarnings = False |
| 209 |
self._sourceDir = None |
| 210 |
self._s3BucketUrl = None |
| 211 |
if argumentList is not None and argumentString is not None: |
| 212 |
raise ValueError("Use either argumentList or argumentString, but not both.") |
| 213 |
if argumentString is not None: |
| 214 |
argumentList = splitCommandLine(argumentString) |
| 215 |
if argumentList is not None: |
| 216 |
self._parseArgumentList(argumentList) |
| 217 |
if validate: |
| 218 |
self.validate() |
| 219 |
|
| 220 |
######################### |
| 221 |
# String representations |
| 222 |
######################### |
| 223 |
|
| 224 |
def __repr__(self): |
| 225 |
""" |
| 226 |
Official string representation for class instance. |
| 227 |
""" |
| 228 |
return self.buildArgumentString(validate=False) |
| 229 |
|
| 230 |
def __str__(self): |
| 231 |
""" |
| 232 |
Informal string representation for class instance. |
| 233 |
""" |
| 234 |
return self.__repr__() |
| 235 |
|
| 236 |
############################# |
| 237 |
# Standard comparison method |
| 238 |
############################# |
| 239 |
|
| 240 |
def __eq__(self, other): |
| 241 |
"""Equals operator, iplemented in terms of original Python 2 compare operator.""" |
| 242 |
return self.__cmp__(other) == 0 |
| 243 |
|
| 244 |
def __lt__(self, other): |
| 245 |
"""Less-than operator, iplemented in terms of original Python 2 compare operator.""" |
| 246 |
return self.__cmp__(other) < 0 |
| 247 |
|
| 248 |
def __gt__(self, other): |
| 249 |
"""Greater-than operator, iplemented in terms of original Python 2 compare operator.""" |
| 250 |
return self.__cmp__(other) > 0 |
| 251 |
|
| 252 |
def __cmp__(self, other): |
| 253 |
""" |
| 254 |
Original Python 2 comparison operator. |
| 255 |
Lists within this class are "unordered" for equality comparisons. |
| 256 |
Args: |
| 257 |
other: Other object to compare to |
| 258 |
Returns: |
| 259 |
-1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other |
| 260 |
""" |
| 261 |
if other is None: |
| 262 |
return 1 |
| 263 |
if self.help != other.help: |
| 264 |
if self.help < other.help: |
| 265 |
return -1 |
| 266 |
else: |
| 267 |
return 1 |
| 268 |
if self.version != other.version: |
| 269 |
if self.version < other.version: |
| 270 |
return -1 |
| 271 |
else: |
| 272 |
return 1 |
| 273 |
if self.verbose != other.verbose: |
| 274 |
if self.verbose < other.verbose: |
| 275 |
return -1 |
| 276 |
else: |
| 277 |
return 1 |
| 278 |
if self.quiet != other.quiet: |
| 279 |
if self.quiet < other.quiet: |
| 280 |
return -1 |
| 281 |
else: |
| 282 |
return 1 |
| 283 |
if self.logfile != other.logfile: |
| 284 |
if str(self.logfile or "") < str(other.logfile or ""): |
| 285 |
return -1 |
| 286 |
else: |
| 287 |
return 1 |
| 288 |
if self.owner != other.owner: |
| 289 |
if str(self.owner or "") < str(other.owner or ""): |
| 290 |
return -1 |
| 291 |
else: |
| 292 |
return 1 |
| 293 |
if self.mode != other.mode: |
| 294 |
if int(self.mode or 0) < int(other.mode or 0): |
| 295 |
return -1 |
| 296 |
else: |
| 297 |
return 1 |
| 298 |
if self.output != other.output: |
| 299 |
if self.output < other.output: |
| 300 |
return -1 |
| 301 |
else: |
| 302 |
return 1 |
| 303 |
if self.debug != other.debug: |
| 304 |
if self.debug < other.debug: |
| 305 |
return -1 |
| 306 |
else: |
| 307 |
return 1 |
| 308 |
if self.stacktrace != other.stacktrace: |
| 309 |
if self.stacktrace < other.stacktrace: |
| 310 |
return -1 |
| 311 |
else: |
| 312 |
return 1 |
| 313 |
if self.diagnostics != other.diagnostics: |
| 314 |
if self.diagnostics < other.diagnostics: |
| 315 |
return -1 |
| 316 |
else: |
| 317 |
return 1 |
| 318 |
if self.verifyOnly != other.verifyOnly: |
| 319 |
if self.verifyOnly < other.verifyOnly: |
| 320 |
return -1 |
| 321 |
else: |
| 322 |
return 1 |
| 323 |
if self.uploadOnly != other.uploadOnly: |
| 324 |
if self.uploadOnly < other.uploadOnly: |
| 325 |
return -1 |
| 326 |
else: |
| 327 |
return 1 |
| 328 |
if self.ignoreWarnings != other.ignoreWarnings: |
| 329 |
if self.ignoreWarnings < other.ignoreWarnings: |
| 330 |
return -1 |
| 331 |
else: |
| 332 |
return 1 |
| 333 |
if self.sourceDir != other.sourceDir: |
| 334 |
if str(self.sourceDir or "") < str(other.sourceDir or ""): |
| 335 |
return -1 |
| 336 |
else: |
| 337 |
return 1 |
| 338 |
if self.s3BucketUrl != other.s3BucketUrl: |
| 339 |
if str(self.s3BucketUrl or "") < str(other.s3BucketUrl or ""): |
| 340 |
return -1 |
| 341 |
else: |
| 342 |
return 1 |
| 343 |
return 0 |
| 344 |
|
| 345 |
############# |
| 346 |
# Properties |
| 347 |
############# |
| 348 |
|
| 349 |
def _setHelp(self, value): |
| 350 |
""" |
| 351 |
Property target used to set the help flag. |
| 352 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 353 |
""" |
| 354 |
if value: |
| 355 |
self._help = True |
| 356 |
else: |
| 357 |
self._help = False |
| 358 |
|
| 359 |
def _getHelp(self): |
| 360 |
""" |
| 361 |
Property target used to get the help flag. |
| 362 |
""" |
| 363 |
return self._help |
| 364 |
|
| 365 |
def _setVersion(self, value): |
| 366 |
""" |
| 367 |
Property target used to set the version flag. |
| 368 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 369 |
""" |
| 370 |
if value: |
| 371 |
self._version = True |
| 372 |
else: |
| 373 |
self._version = False |
| 374 |
|
| 375 |
def _getVersion(self): |
| 376 |
""" |
| 377 |
Property target used to get the version flag. |
| 378 |
""" |
| 379 |
return self._version |
| 380 |
|
| 381 |
def _setVerbose(self, value): |
| 382 |
""" |
| 383 |
Property target used to set the verbose flag. |
| 384 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 385 |
""" |
| 386 |
if value: |
| 387 |
self._verbose = True |
| 388 |
else: |
| 389 |
self._verbose = False |
| 390 |
|
| 391 |
def _getVerbose(self): |
| 392 |
""" |
| 393 |
Property target used to get the verbose flag. |
| 394 |
""" |
| 395 |
return self._verbose |
| 396 |
|
| 397 |
def _setQuiet(self, value): |
| 398 |
""" |
| 399 |
Property target used to set the quiet flag. |
| 400 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 401 |
""" |
| 402 |
if value: |
| 403 |
self._quiet = True |
| 404 |
else: |
| 405 |
self._quiet = False |
| 406 |
|
| 407 |
def _getQuiet(self): |
| 408 |
""" |
| 409 |
Property target used to get the quiet flag. |
| 410 |
""" |
| 411 |
return self._quiet |
| 412 |
|
| 413 |
def _setLogfile(self, value): |
| 414 |
""" |
| 415 |
Property target used to set the logfile parameter. |
| 416 |
Raises: |
| 417 |
ValueError: If the value cannot be encoded properly |
| 418 |
""" |
| 419 |
if value is not None: |
| 420 |
if len(value) < 1: |
| 421 |
raise ValueError("The logfile parameter must be a non-empty string.") |
| 422 |
self._logfile = encodePath(value) |
| 423 |
|
| 424 |
def _getLogfile(self): |
| 425 |
""" |
| 426 |
Property target used to get the logfile parameter. |
| 427 |
""" |
| 428 |
return self._logfile |
| 429 |
|
| 430 |
def _setOwner(self, value): |
| 431 |
""" |
| 432 |
Property target used to set the owner parameter. |
| 433 |
If not ``None``, the owner must be a ``(user,group)`` tuple or list. |
| 434 |
Strings (and inherited children of strings) are explicitly disallowed. |
| 435 |
The value will be normalized to a tuple. |
| 436 |
Raises: |
| 437 |
ValueError: If the value is not valid |
| 438 |
""" |
| 439 |
if value is None: |
| 440 |
self._owner = None |
| 441 |
else: |
| 442 |
if isinstance(value, str): |
| 443 |
raise ValueError("Must specify user and group tuple for owner parameter.") |
| 444 |
if len(value) != 2: |
| 445 |
raise ValueError("Must specify user and group tuple for owner parameter.") |
| 446 |
if len(value[0]) < 1 or len(value[1]) < 1: |
| 447 |
raise ValueError("User and group tuple values must be non-empty strings.") |
| 448 |
self._owner = (value[0], value[1]) |
| 449 |
|
| 450 |
def _getOwner(self): |
| 451 |
""" |
| 452 |
Property target used to get the owner parameter. |
| 453 |
The parameter is a tuple of ``(user, group)``. |
| 454 |
""" |
| 455 |
return self._owner |
| 456 |
|
| 457 |
def _setMode(self, value): |
| 458 |
""" |
| 459 |
Property target used to set the mode parameter. |
| 460 |
""" |
| 461 |
if value is None: |
| 462 |
self._mode = None |
| 463 |
else: |
| 464 |
try: |
| 465 |
if isinstance(value, str): |
| 466 |
value = int(value, 8) |
| 467 |
else: |
| 468 |
value = int(value) |
| 469 |
except TypeError: |
| 470 |
raise ValueError("Mode must be an octal integer >= 0, i.e. 644.") |
| 471 |
if value < 0: |
| 472 |
raise ValueError("Mode must be an octal integer >= 0. i.e. 644.") |
| 473 |
self._mode = value |
| 474 |
|
| 475 |
def _getMode(self): |
| 476 |
""" |
| 477 |
Property target used to get the mode parameter. |
| 478 |
""" |
| 479 |
return self._mode |
| 480 |
|
| 481 |
def _setOutput(self, value): |
| 482 |
""" |
| 483 |
Property target used to set the output flag. |
| 484 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 485 |
""" |
| 486 |
if value: |
| 487 |
self._output = True |
| 488 |
else: |
| 489 |
self._output = False |
| 490 |
|
| 491 |
def _getOutput(self): |
| 492 |
""" |
| 493 |
Property target used to get the output flag. |
| 494 |
""" |
| 495 |
return self._output |
| 496 |
|
| 497 |
def _setDebug(self, value): |
| 498 |
""" |
| 499 |
Property target used to set the debug flag. |
| 500 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 501 |
""" |
| 502 |
if value: |
| 503 |
self._debug = True |
| 504 |
else: |
| 505 |
self._debug = False |
| 506 |
|
| 507 |
def _getDebug(self): |
| 508 |
""" |
| 509 |
Property target used to get the debug flag. |
| 510 |
""" |
| 511 |
return self._debug |
| 512 |
|
| 513 |
def _setStacktrace(self, value): |
| 514 |
""" |
| 515 |
Property target used to set the stacktrace flag. |
| 516 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 517 |
""" |
| 518 |
if value: |
| 519 |
self._stacktrace = True |
| 520 |
else: |
| 521 |
self._stacktrace = False |
| 522 |
|
| 523 |
def _getStacktrace(self): |
| 524 |
""" |
| 525 |
Property target used to get the stacktrace flag. |
| 526 |
""" |
| 527 |
return self._stacktrace |
| 528 |
|
| 529 |
def _setDiagnostics(self, value): |
| 530 |
""" |
| 531 |
Property target used to set the diagnostics flag. |
| 532 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 533 |
""" |
| 534 |
if value: |
| 535 |
self._diagnostics = True |
| 536 |
else: |
| 537 |
self._diagnostics = False |
| 538 |
|
| 539 |
def _getDiagnostics(self): |
| 540 |
""" |
| 541 |
Property target used to get the diagnostics flag. |
| 542 |
""" |
| 543 |
return self._diagnostics |
| 544 |
|
| 545 |
def _setVerifyOnly(self, value): |
| 546 |
""" |
| 547 |
Property target used to set the verifyOnly flag. |
| 548 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 549 |
""" |
| 550 |
if value: |
| 551 |
self._verifyOnly = True |
| 552 |
else: |
| 553 |
self._verifyOnly = False |
| 554 |
|
| 555 |
def _getVerifyOnly(self): |
| 556 |
""" |
| 557 |
Property target used to get the verifyOnly flag. |
| 558 |
""" |
| 559 |
return self._verifyOnly |
| 560 |
|
| 561 |
def _setUploadOnly(self, value): |
| 562 |
""" |
| 563 |
Property target used to set the uploadOnly flag. |
| 564 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 565 |
""" |
| 566 |
if value: |
| 567 |
self._uploadOnly = True |
| 568 |
else: |
| 569 |
self._uploadOnly = False |
| 570 |
|
| 571 |
def _getUploadOnly(self): |
| 572 |
""" |
| 573 |
Property target used to get the uploadOnly flag. |
| 574 |
""" |
| 575 |
return self._uploadOnly |
| 576 |
|
| 577 |
def _setIgnoreWarnings(self, value): |
| 578 |
""" |
| 579 |
Property target used to set the ignoreWarnings flag. |
| 580 |
No validations, but we normalize the value to ``True`` or ``False``. |
| 581 |
""" |
| 582 |
if value: |
| 583 |
self._ignoreWarnings = True |
| 584 |
else: |
| 585 |
self._ignoreWarnings = False |
| 586 |
|
| 587 |
def _getIgnoreWarnings(self): |
| 588 |
""" |
| 589 |
Property target used to get the ignoreWarnings flag. |
| 590 |
""" |
| 591 |
return self._ignoreWarnings |
| 592 |
|
| 593 |
def _setSourceDir(self, value): |
| 594 |
""" |
| 595 |
Property target used to set the sourceDir parameter. |
| 596 |
""" |
| 597 |
if value is not None: |
| 598 |
if len(value) < 1: |
| 599 |
raise ValueError("The sourceDir parameter must be a non-empty string.") |
| 600 |
self._sourceDir = value |
| 601 |
|
| 602 |
def _getSourceDir(self): |
| 603 |
""" |
| 604 |
Property target used to get the sourceDir parameter. |
| 605 |
""" |
| 606 |
return self._sourceDir |
| 607 |
|
| 608 |
def _setS3BucketUrl(self, value): |
| 609 |
""" |
| 610 |
Property target used to set the s3BucketUrl parameter. |
| 611 |
""" |
| 612 |
if value is not None: |
| 613 |
if len(value) < 1: |
| 614 |
raise ValueError("The s3BucketUrl parameter must be a non-empty string.") |
| 615 |
self._s3BucketUrl = value |
| 616 |
|
| 617 |
def _getS3BucketUrl(self): |
| 618 |
""" |
| 619 |
Property target used to get the s3BucketUrl parameter. |
| 620 |
""" |
| 621 |
return self._s3BucketUrl |
| 622 |
|
| 623 |
help = property(_getHelp, _setHelp, None, "Command-line help (``-h,--help``) flag.") |
| 624 |
version = property(_getVersion, _setVersion, None, "Command-line version (``-V,--version``) flag.") |
| 625 |
verbose = property(_getVerbose, _setVerbose, None, "Command-line verbose (``-b,--verbose``) flag.") |
| 626 |
quiet = property(_getQuiet, _setQuiet, None, "Command-line quiet (``-q,--quiet``) flag.") |
| 627 |
logfile = property(_getLogfile, _setLogfile, None, "Command-line logfile (``-l,--logfile``) parameter.") |
| 628 |
owner = property(_getOwner, _setOwner, None, "Command-line owner (``-o,--owner``) parameter, as tuple ``(user,group)``.") |
| 629 |
mode = property(_getMode, _setMode, None, "Command-line mode (``-m,--mode``) parameter.") |
| 630 |
output = property(_getOutput, _setOutput, None, "Command-line output (``-O,--output``) flag.") |
| 631 |
debug = property(_getDebug, _setDebug, None, "Command-line debug (``-d,--debug``) flag.") |
| 632 |
stacktrace = property(_getStacktrace, _setStacktrace, None, "Command-line stacktrace (``-s,--stack``) flag.") |
| 633 |
diagnostics = property(_getDiagnostics, _setDiagnostics, None, "Command-line diagnostics (``-D,--diagnostics``) flag.") |
| 634 |
verifyOnly = property(_getVerifyOnly, _setVerifyOnly, None, "Command-line verifyOnly (``-v,--verifyOnly``) flag.") |
| 635 |
uploadOnly = property(_getUploadOnly, _setUploadOnly, None, "Command-line uploadOnly (``-u,--uploadOnly``) flag.") |
| 636 |
ignoreWarnings = property( |
| 637 |
_getIgnoreWarnings, _setIgnoreWarnings, None, "Command-line ignoreWarnings (``-w,--ignoreWarnings``) flag" |
| 638 |
) |
| 639 |
sourceDir = property(_getSourceDir, _setSourceDir, None, "Command-line sourceDir, source of sync.") |
| 640 |
s3BucketUrl = property(_getS3BucketUrl, _setS3BucketUrl, None, "Command-line s3BucketUrl, target of sync.") |
| 641 |
|
| 642 |
################## |
| 643 |
# Utility methods |
| 644 |
################## |
| 645 |
|
| 646 |
def validate(self): |
| 647 |
""" |
| 648 |
Validates command-line options represented by the object. |
| 649 |
|
| 650 |
Unless ``--help`` or ``--version`` are supplied, at least one action must |
| 651 |
be specified. Other validations (as for allowed values for particular |
| 652 |
options) will be taken care of at assignment time by the properties |
| 653 |
functionality. |
| 654 |
|
| 655 |
*Note:* The command line format is specified by the ``_usage`` function. |
| 656 |
Call ``_usage`` to see a usage statement for the cback3-amazons3-sync script. |
| 657 |
|
| 658 |
Raises: |
| 659 |
ValueError: If one of the validations fails |
| 660 |
""" |
| 661 |
if not self.help and not self.version and not self.diagnostics: |
| 662 |
if self.sourceDir is None or self.s3BucketUrl is None: |
| 663 |
raise ValueError("Source directory and S3 bucket URL are both required.") |
| 664 |
|
| 665 |
def buildArgumentList(self, validate=True): |
| 666 |
""" |
| 667 |
Extracts options into a list of command line arguments. |
| 668 |
|
| 669 |
The original order of the various arguments (if, indeed, the object was |
| 670 |
initialized with a command-line) is not preserved in this generated |
| 671 |
argument list. Besides that, the argument list is normalized to use the |
| 672 |
long option names (i.e. --version rather than -V). The resulting list |
| 673 |
will be suitable for passing back to the constructor in the |
| 674 |
``argumentList`` parameter. Unlike :any:`buildArgumentString`, string |
| 675 |
arguments are not quoted here, because there is no need for it. |
| 676 |
|
| 677 |
Unless the ``validate`` parameter is ``False``, the :any:`Options.validate` |
| 678 |
method will be called (with its default arguments) against the |
| 679 |
options before extracting the command line. If the options are not valid, |
| 680 |
then an argument list will not be extracted. |
| 681 |
|
| 682 |
*Note:* It is strongly suggested that the ``validate`` option always be set |
| 683 |
to ``True`` (the default) unless there is a specific need to extract an |
| 684 |
invalid command line. |
| 685 |
|
| 686 |
Args: |
| 687 |
validate (Boolean true/false): Validate the options before extracting the command line |
| 688 |
Returns: |
| 689 |
List representation of command-line arguments |
| 690 |
Raises: |
| 691 |
ValueError: If options within the object are invalid |
| 692 |
""" |
| 693 |
if validate: |
| 694 |
self.validate() |
| 695 |
argumentList = [] |
| 696 |
if self._help: |
| 697 |
argumentList.append("--help") |
| 698 |
if self.version: |
| 699 |
argumentList.append("--version") |
| 700 |
if self.verbose: |
| 701 |
argumentList.append("--verbose") |
| 702 |
if self.quiet: |
| 703 |
argumentList.append("--quiet") |
| 704 |
if self.logfile is not None: |
| 705 |
argumentList.append("--logfile") |
| 706 |
argumentList.append(self.logfile) |
| 707 |
if self.owner is not None: |
| 708 |
argumentList.append("--owner") |
| 709 |
argumentList.append("%s:%s" % (self.owner[0], self.owner[1])) |
| 710 |
if self.mode is not None: |
| 711 |
argumentList.append("--mode") |
| 712 |
argumentList.append("%o" % self.mode) |
| 713 |
if self.output: |
| 714 |
argumentList.append("--output") |
| 715 |
if self.debug: |
| 716 |
argumentList.append("--debug") |
| 717 |
if self.stacktrace: |
| 718 |
argumentList.append("--stack") |
| 719 |
if self.diagnostics: |
| 720 |
argumentList.append("--diagnostics") |
| 721 |
if self.verifyOnly: |
| 722 |
argumentList.append("--verifyOnly") |
| 723 |
if self.uploadOnly: |
| 724 |
argumentList.append("--uploadOnly") |
| 725 |
if self.ignoreWarnings: |
| 726 |
argumentList.append("--ignoreWarnings") |
| 727 |
if self.sourceDir is not None: |
| 728 |
argumentList.append(self.sourceDir) |
| 729 |
if self.s3BucketUrl is not None: |
| 730 |
argumentList.append(self.s3BucketUrl) |
| 731 |
return argumentList |
| 732 |
|
| 733 |
def buildArgumentString(self, validate=True): |
| 734 |
""" |
| 735 |
Extracts options into a string of command-line arguments. |
| 736 |
|
| 737 |
The original order of the various arguments (if, indeed, the object was |
| 738 |
initialized with a command-line) is not preserved in this generated |
| 739 |
argument string. Besides that, the argument string is normalized to use |
| 740 |
the long option names (i.e. --version rather than -V) and to quote all |
| 741 |
string arguments with double quotes (``"``). The resulting string will be |
| 742 |
suitable for passing back to the constructor in the ``argumentString`` |
| 743 |
parameter. |
| 744 |
|
| 745 |
Unless the ``validate`` parameter is ``False``, the :any:`Options.validate` |
| 746 |
method will be called (with its default arguments) against the options |
| 747 |
before extracting the command line. If the options are not valid, then |
| 748 |
an argument string will not be extracted. |
| 749 |
|
| 750 |
*Note:* It is strongly suggested that the ``validate`` option always be set |
| 751 |
to ``True`` (the default) unless there is a specific need to extract an |
| 752 |
invalid command line. |
| 753 |
|
| 754 |
Args: |
| 755 |
validate (Boolean true/false): Validate the options before extracting the command line |
| 756 |
Returns: |
| 757 |
String representation of command-line arguments |
| 758 |
Raises: |
| 759 |
ValueError: If options within the object are invalid |
| 760 |
""" |
| 761 |
if validate: |
| 762 |
self.validate() |
| 763 |
argumentString = "" |
| 764 |
if self._help: |
| 765 |
argumentString += "--help " |
| 766 |
if self.version: |
| 767 |
argumentString += "--version " |
| 768 |
if self.verbose: |
| 769 |
argumentString += "--verbose " |
| 770 |
if self.quiet: |
| 771 |
argumentString += "--quiet " |
| 772 |
if self.logfile is not None: |
| 773 |
argumentString += '--logfile "%s" ' % self.logfile |
| 774 |
if self.owner is not None: |
| 775 |
argumentString += '--owner "%s:%s" ' % (self.owner[0], self.owner[1]) |
| 776 |
if self.mode is not None: |
| 777 |
argumentString += "--mode %o " % self.mode |
| 778 |
if self.output: |
| 779 |
argumentString += "--output " |
| 780 |
if self.debug: |
| 781 |
argumentString += "--debug " |
| 782 |
if self.stacktrace: |
| 783 |
argumentString += "--stack " |
| 784 |
if self.diagnostics: |
| 785 |
argumentString += "--diagnostics " |
| 786 |
if self.verifyOnly: |
| 787 |
argumentString += "--verifyOnly " |
| 788 |
if self.uploadOnly: |
| 789 |
argumentString += "--uploadOnly " |
| 790 |
if self.ignoreWarnings: |
| 791 |
argumentString += "--ignoreWarnings " |
| 792 |
if self.sourceDir is not None: |
| 793 |
argumentString += '"%s" ' % self.sourceDir |
| 794 |
if self.s3BucketUrl is not None: |
| 795 |
argumentString += '"%s" ' % self.s3BucketUrl |
| 796 |
return argumentString |
| 797 |
|
| 798 |
def _parseArgumentList(self, argumentList): |
| 799 |
""" |
| 800 |
Internal method to parse a list of command-line arguments. |
| 801 |
|
| 802 |
Most of the validation we do here has to do with whether the arguments |
| 803 |
can be parsed and whether any values which exist are valid. We don't do |
| 804 |
any validation as to whether required elements exist or whether elements |
| 805 |
exist in the proper combination (instead, that's the job of the |
| 806 |
:any:`validate` method). |
| 807 |
|
| 808 |
For any of the options which supply parameters, if the option is |
| 809 |
duplicated with long and short switches (i.e. ``-l`` and a ``--logfile``) |
| 810 |
then the long switch is used. If the same option is duplicated with the |
| 811 |
same switch (long or short), then the last entry on the command line is |
| 812 |
used. |
| 813 |
|
| 814 |
Args: |
| 815 |
argumentList (List of arguments to a command, i.e. ``sys.argv[1:]``): List of arguments to a command |
| 816 |
Raises: |
| 817 |
ValueError: If the argument list cannot be successfully parsed |
| 818 |
""" |
| 819 |
switches = {} |
| 820 |
opts, remaining = getopt.getopt(argumentList, SHORT_SWITCHES, LONG_SWITCHES) |
| 821 |
for o, a in opts: # push the switches into a hash |
| 822 |
switches[o] = a |
| 823 |
if "-h" in switches or "--help" in switches: |
| 824 |
self.help = True |
| 825 |
if "-V" in switches or "--version" in switches: |
| 826 |
self.version = True |
| 827 |
if "-b" in switches or "--verbose" in switches: |
| 828 |
self.verbose = True |
| 829 |
if "-q" in switches or "--quiet" in switches: |
| 830 |
self.quiet = True |
| 831 |
if "-l" in switches: |
| 832 |
self.logfile = switches["-l"] |
| 833 |
if "--logfile" in switches: |
| 834 |
self.logfile = switches["--logfile"] |
| 835 |
if "-o" in switches: |
| 836 |
self.owner = switches["-o"].split(":", 1) |
| 837 |
if "--owner" in switches: |
| 838 |
self.owner = switches["--owner"].split(":", 1) |
| 839 |
if "-m" in switches: |
| 840 |
self.mode = switches["-m"] |
| 841 |
if "--mode" in switches: |
| 842 |
self.mode = switches["--mode"] |
| 843 |
if "-O" in switches or "--output" in switches: |
| 844 |
self.output = True |
| 845 |
if "-d" in switches or "--debug" in switches: |
| 846 |
self.debug = True |
| 847 |
if "-s" in switches or "--stack" in switches: |
| 848 |
self.stacktrace = True |
| 849 |
if "-D" in switches or "--diagnostics" in switches: |
| 850 |
self.diagnostics = True |
| 851 |
if "-v" in switches or "--verifyOnly" in switches: |
| 852 |
self.verifyOnly = True |
| 853 |
if "-u" in switches or "--uploadOnly" in switches: |
| 854 |
self.uploadOnly = True |
| 855 |
if "-w" in switches or "--ignoreWarnings" in switches: |
| 856 |
self.ignoreWarnings = True |
| 857 |
try: |
| 858 |
(self.sourceDir, self.s3BucketUrl) = remaining |
| 859 |
except ValueError: |
| 860 |
pass |
| 861 |
|
| 862 |
|
| 863 |
####################################################################### |
| 864 |
# Public functions |
| 865 |
####################################################################### |
| 866 |
|
| 867 |
################# |
| 868 |
# cli() function |
| 869 |
################# |
| 870 |
|
| 871 |
|
| 872 |
def cli(): |
| 873 |
""" |
| 874 |
Implements the command-line interface for the ``cback3-amazons3-sync`` script. |
| 875 |
|
| 876 |
Essentially, this is the "main routine" for the cback3-amazons3-sync script. It does |
| 877 |
all of the argument processing for the script, and then also implements the |
| 878 |
tool functionality. |
| 879 |
|
| 880 |
This function looks pretty similiar to ``CedarBackup3.cli.cli()``. It's not |
| 881 |
easy to refactor this code to make it reusable and also readable, so I've |
| 882 |
decided to just live with the duplication. |
| 883 |
|
| 884 |
A different error code is returned for each type of failure: |
| 885 |
|
| 886 |
- ``1``: The Python interpreter version is not supported |
| 887 |
- ``2``: Error processing command-line arguments |
| 888 |
- ``3``: Error configuring logging |
| 889 |
- ``5``: Backup was interrupted with a CTRL-C or similar |
| 890 |
- ``6``: Error executing other parts of the script |
| 891 |
|
| 892 |
*Note:* This script uses print rather than logging to the INFO level, because |
| 893 |
it is interactive. Underlying Cedar Backup functionality uses the logging |
| 894 |
mechanism exclusively. |
| 895 |
|
| 896 |
Returns: |
| 897 |
Error code as described above |
| 898 |
""" |
| 899 |
try: |
| 900 |
if list(map(int, [sys.version_info[0], sys.version_info[1]])) < [3, 8]: |
| 901 |
sys.stderr.write("Python 3 version 3.8 or greater required.\n") |
| 902 |
return 1 |
| 903 |
except: |
| 904 |
# sys.version_info isn't available before 2.0 |
| 905 |
sys.stderr.write("Python 3 version 3.8 or greater required.\n") |
| 906 |
return 1 |
| 907 |
|
| 908 |
try: |
| 909 |
options = Options(argumentList=sys.argv[1:]) |
| 910 |
except Exception as e: |
| 911 |
_usage() |
| 912 |
sys.stderr.write(" *** Error: %s\n" % e) |
| 913 |
return 2 |
| 914 |
|
| 915 |
if options.help: |
| 916 |
_usage() |
| 917 |
return 0 |
| 918 |
if options.version: |
| 919 |
_version() |
| 920 |
return 0 |
| 921 |
if options.diagnostics: |
| 922 |
_diagnostics() |
| 923 |
return 0 |
| 924 |
|
| 925 |
if options.stacktrace: |
| 926 |
logfile = setupLogging(options) |
| 927 |
else: |
| 928 |
try: |
| 929 |
logfile = setupLogging(options) |
| 930 |
except Exception as e: |
| 931 |
sys.stderr.write("Error setting up logging: %s\n" % e) |
| 932 |
return 3 |
| 933 |
|
| 934 |
logger.info("Cedar Backup Amazon S3 sync run started.") |
| 935 |
logger.info("Options were [%s]", options) |
| 936 |
logger.info("Logfile is [%s]", logfile) |
| 937 |
Diagnostics().logDiagnostics(method=logger.info) |
| 938 |
|
| 939 |
if options.stacktrace: |
| 940 |
_executeAction(options) |
| 941 |
else: |
| 942 |
try: |
| 943 |
_executeAction(options) |
| 944 |
except KeyboardInterrupt: |
| 945 |
logger.error("Backup interrupted.") |
| 946 |
logger.info("Cedar Backup Amazon S3 sync run completed with status 5.") |
| 947 |
return 5 |
| 948 |
except Exception as e: |
| 949 |
logger.error("Error executing backup: %s", e) |
| 950 |
logger.info("Cedar Backup Amazon S3 sync run completed with status 6.") |
| 951 |
return 6 |
| 952 |
|
| 953 |
logger.info("Cedar Backup Amazon S3 sync run completed with status 0.") |
| 954 |
return 0 |
| 955 |
|
| 956 |
|
| 957 |
####################################################################### |
| 958 |
# Utility functions |
| 959 |
####################################################################### |
| 960 |
|
| 961 |
#################### |
| 962 |
# _usage() function |
| 963 |
#################### |
| 964 |
|
| 965 |
|
| 966 |
def _usage(fd=sys.stderr): |
| 967 |
""" |
| 968 |
Prints usage information for the cback3-amazons3-sync script. |
| 969 |
Args: |
| 970 |
fd: File descriptor used to print information |
| 971 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 972 |
""" |
| 973 |
fd.write("\n") |
| 974 |
fd.write(" Usage: cback3-amazons3-sync [switches] sourceDir s3bucketUrl\n") |
| 975 |
fd.write("\n") |
| 976 |
fd.write(" Cedar Backup Amazon S3 sync tool.\n") |
| 977 |
fd.write("\n") |
| 978 |
fd.write(" This Cedar Backup utility synchronizes a local directory to an Amazon S3\n") |
| 979 |
fd.write(" bucket. After the sync is complete, a validation step is taken. An\n") |
| 980 |
fd.write(" error is reported if the contents of the bucket do not match the\n") |
| 981 |
fd.write(" source directory, or if the indicated size for any file differs.\n") |
| 982 |
fd.write(" This tool is a wrapper over the AWS CLI command-line tool.\n") |
| 983 |
fd.write("\n") |
| 984 |
fd.write(" The following arguments are required:\n") |
| 985 |
fd.write("\n") |
| 986 |
fd.write(" sourceDir The local source directory on disk (must exist)\n") |
| 987 |
fd.write(" s3BucketUrl The URL to the target Amazon S3 bucket\n") |
| 988 |
fd.write("\n") |
| 989 |
fd.write(" The following switches are accepted:\n") |
| 990 |
fd.write("\n") |
| 991 |
fd.write(" -h, --help Display this usage/help listing\n") |
| 992 |
fd.write(" -V, --version Display version information\n") |
| 993 |
fd.write(" -b, --verbose Print verbose output as well as logging to disk\n") |
| 994 |
fd.write(" -q, --quiet Run quietly (display no output to the screen)\n") |
| 995 |
fd.write(" -l, --logfile Path to logfile (default: %s)\n" % DEFAULT_LOGFILE) |
| 996 |
fd.write( |
| 997 |
" -o, --owner Logfile ownership, user:group (default: %s:%s)\n" % (DEFAULT_OWNERSHIP[0], DEFAULT_OWNERSHIP[1]) |
| 998 |
) |
| 999 |
fd.write(" -m, --mode Octal logfile permissions mode (default: %o)\n" % DEFAULT_MODE) |
| 1000 |
fd.write(" -O, --output Record some sub-command (i.e. aws) output to the log\n") |
| 1001 |
fd.write(" -d, --debug Write debugging information to the log (implies --output)\n") |
| 1002 |
fd.write( |
| 1003 |
" -s, --stack Dump Python stack trace instead of swallowing exceptions\n" |
| 1004 |
) # exactly 80 characters in width! |
| 1005 |
fd.write(" -D, --diagnostics Print runtime diagnostics to the screen and exit\n") |
| 1006 |
fd.write(" -v, --verifyOnly Only verify the S3 bucket contents, do not make changes\n") |
| 1007 |
fd.write(" -u, --uploadOnly Only upload new data, do not remove files in the S3 bucket\n") |
| 1008 |
fd.write(" -w, --ignoreWarnings Ignore warnings about problematic filename encodings\n") |
| 1009 |
fd.write("\n") |
| 1010 |
fd.write(" Typical usage would be something like:\n") |
| 1011 |
fd.write("\n") |
| 1012 |
fd.write(" cback3-amazons3-sync /home/myuser s3://example.com-backup/myuser\n") |
| 1013 |
fd.write("\n") |
| 1014 |
fd.write(" This will sync the contents of /home/myuser into the indicated bucket.\n") |
| 1015 |
fd.write("\n") |
| 1016 |
|
| 1017 |
|
| 1018 |
###################### |
| 1019 |
# _version() function |
| 1020 |
###################### |
| 1021 |
|
| 1022 |
|
| 1023 |
def _version(fd=sys.stdout): |
| 1024 |
""" |
| 1025 |
Prints version information for the cback3-amazons3-sync script. |
| 1026 |
Args: |
| 1027 |
fd: File descriptor used to print information |
| 1028 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 1029 |
""" |
| 1030 |
fd.write("\n") |
| 1031 |
fd.write(" Cedar Backup Amazon S3 sync tool.\n") |
| 1032 |
fd.write(" Included with Cedar Backup version %s.\n" % VERSION) |
| 1033 |
fd.write("\n") |
| 1034 |
fd.write(" Copyright (c) %s <%s>.\n" % (AUTHOR, EMAIL)) |
| 1035 |
fd.write(" See NOTICE for a list of included code and other contributors.\n") |
| 1036 |
fd.write(" This is free software; there is NO warranty. See the\n") |
| 1037 |
fd.write(" GNU General Public License version 2 for copying conditions.\n") |
| 1038 |
fd.write("\n") |
| 1039 |
fd.write(" Use the --help option for usage information.\n") |
| 1040 |
fd.write("\n") |
| 1041 |
|
| 1042 |
|
| 1043 |
########################## |
| 1044 |
# _diagnostics() function |
| 1045 |
########################## |
| 1046 |
|
| 1047 |
|
| 1048 |
def _diagnostics(fd=sys.stdout): |
| 1049 |
""" |
| 1050 |
Prints runtime diagnostics information. |
| 1051 |
Args: |
| 1052 |
fd: File descriptor used to print information |
| 1053 |
*Note:* The ``fd`` is used rather than ``print`` to facilitate unit testing. |
| 1054 |
""" |
| 1055 |
fd.write("\n") |
| 1056 |
fd.write("Diagnostics:\n") |
| 1057 |
fd.write("\n") |
| 1058 |
Diagnostics().printDiagnostics(fd=fd, prefix=" ") |
| 1059 |
fd.write("\n") |
| 1060 |
|
| 1061 |
|
| 1062 |
############################ |
| 1063 |
# _executeAction() function |
| 1064 |
############################ |
| 1065 |
|
| 1066 |
|
| 1067 |
def _executeAction(options): |
| 1068 |
""" |
| 1069 |
Implements the guts of the cback3-amazons3-sync tool. |
| 1070 |
|
| 1071 |
Args: |
| 1072 |
options (Options object): Program command-line options |
| 1073 |
Raises: |
| 1074 |
Exception: Under many generic error conditions |
| 1075 |
""" |
| 1076 |
sourceFiles = _buildSourceFiles(options.sourceDir) |
| 1077 |
if not options.ignoreWarnings: |
| 1078 |
_checkSourceFiles(options.sourceDir, sourceFiles) |
| 1079 |
if not options.verifyOnly: |
| 1080 |
_synchronizeBucket(options.sourceDir, options.s3BucketUrl, options.uploadOnly) |
| 1081 |
_verifyBucketContents(options.sourceDir, sourceFiles, options.s3BucketUrl) |
| 1082 |
|
| 1083 |
|
| 1084 |
################################ |
| 1085 |
# _buildSourceFiles() function |
| 1086 |
################################ |
| 1087 |
|
| 1088 |
|
| 1089 |
def _buildSourceFiles(sourceDir): |
| 1090 |
""" |
| 1091 |
Build a list of files in a source directory |
| 1092 |
Args: |
| 1093 |
sourceDir: Local source directory |
| 1094 |
Returns: |
| 1095 |
FilesystemList with contents of source directory |
| 1096 |
""" |
| 1097 |
if not os.path.isdir(sourceDir): |
| 1098 |
raise ValueError("Source directory does not exist on disk.") |
| 1099 |
sourceFiles = FilesystemList() |
| 1100 |
sourceFiles.addDirContents(sourceDir) |
| 1101 |
return sourceFiles |
| 1102 |
|
| 1103 |
|
| 1104 |
############################### |
| 1105 |
# _checkSourceFiles() function |
| 1106 |
############################### |
| 1107 |
|
| 1108 |
|
| 1109 |
def _checkSourceFiles(sourceDir, sourceFiles): # ruff: ignore[unused-function-argument] |
| 1110 |
""" |
| 1111 |
Check source files, trying to guess which ones will have encoding problems. |
| 1112 |
Args: |
| 1113 |
sourceDir: Local source directory |
| 1114 |
sourceDir: Local source directory |
| 1115 |
@raises ValueError: If a problem file is found |
| 1116 |
@see U{http://opensourcehacker.com/2011/09/16/fix-linux-filename-encodings-with-python/} |
| 1117 |
@see U{http://serverfault.com/questions/82821/how-to-tell-the-language-encoding-of-a-filename-on-linux} |
| 1118 |
@see U{http://randysofia.com/2014/06/06/aws-cli-and-your-locale/} |
| 1119 |
""" |
| 1120 |
with warnings.catch_warnings(): |
| 1121 |
encoding = Diagnostics().encoding |
| 1122 |
|
| 1123 |
# Note: this was difficult to fully test. As of the original Python 2 |
| 1124 |
# implementation, I had a bunch of files on disk that had inconsistent |
| 1125 |
# encodings, so I was able to prove that the check warned about these |
| 1126 |
# files initially, and then didn't warn after I fixed them. I didn't |
| 1127 |
# save off those files for a unit test (ugh) so by the time of the Python |
| 1128 |
# 3 conversion -- which is subtly different because of the different way |
| 1129 |
# Python 3 handles unicode strings -- I had to contrive some tests. I |
| 1130 |
# think the tests I wrote are consistent with the earlier problems, and I |
| 1131 |
# do get the same result for those tests in both CedarBackup 2 and Cedar |
| 1132 |
# Backup 3. However, I can't be certain the implementation is |
| 1133 |
# equivalent. If someone runs into a situation that this code doesn't |
| 1134 |
# handle, you may need to revisit the implementation. |
| 1135 |
|
| 1136 |
failed = False |
| 1137 |
for entry in sourceFiles: |
| 1138 |
path = bytes(Path(entry)) |
| 1139 |
result = chardet.detect(path) |
| 1140 |
source = path.decode(result["encoding"]) |
| 1141 |
try: |
| 1142 |
target = path.decode(encoding) |
| 1143 |
if source != target: |
| 1144 |
logger.error("Inconsistent encoding for [%s]: got %s, but need %s", path, result["encoding"], encoding) |
| 1145 |
failed = True |
| 1146 |
except Exception: |
| 1147 |
logger.error("Inconsistent encoding for [%s]: got %s, but need %s", path, result["encoding"], encoding) |
| 1148 |
failed = True |
| 1149 |
|
| 1150 |
if not failed: |
| 1151 |
logger.info("Completed checking source filename encoding (no problems found).") |
| 1152 |
else: |
| 1153 |
logger.error("Some filenames have inconsistent encodings and will likely cause sync problems.") |
| 1154 |
logger.error("You may be able to fix this by setting a more sensible locale in your environment.") |
| 1155 |
logger.error("Aternately, you can rename the problem files to be valid in the indicated locale.") |
| 1156 |
logger.error("To ignore this warning and proceed anyway, use --ignoreWarnings") |
| 1157 |
raise ValueError("Some filenames have inconsistent encodings and will likely cause sync problems.") |
| 1158 |
|
| 1159 |
|
| 1160 |
################################ |
| 1161 |
# _synchronizeBucket() function |
| 1162 |
################################ |
| 1163 |
|
| 1164 |
|
| 1165 |
def _synchronizeBucket(sourceDir, s3BucketUrl, uploadOnly): |
| 1166 |
""" |
| 1167 |
Synchronize a local directory to an Amazon S3 bucket. |
| 1168 |
Args: |
| 1169 |
sourceDir: Local source directory |
| 1170 |
s3BucketUrl: Target S3 bucket URL |
| 1171 |
""" |
| 1172 |
# Since at least early 2015, 'aws s3 sync' is always recursive and the |
| 1173 |
# --recursive option is useless. They eventually removed it and now using |
| 1174 |
# it causes an error. See: https://github.com/aws/aws-cli/issues/1170 |
| 1175 |
logger.info("Synchronizing local source directory up to Amazon S3.") |
| 1176 |
args = ["s3", "sync", sourceDir, s3BucketUrl] |
| 1177 |
if uploadOnly: |
| 1178 |
logger.info("Sync process will only upload new data, never removing files in S3") |
| 1179 |
else: |
| 1180 |
logger.info("This will be a full sync process, removing any S3 files that do not exist in the source") |
| 1181 |
args += ["--delete"] |
| 1182 |
result = executeCommand(AWS_COMMAND, args, returnOutput=False)[0] |
| 1183 |
if result != 0: |
| 1184 |
raise OSError("Error [%d] calling AWS CLI synchronize bucket." % result) |
| 1185 |
|
| 1186 |
|
| 1187 |
################################### |
| 1188 |
# _verifyBucketContents() function |
| 1189 |
################################### |
| 1190 |
|
| 1191 |
|
| 1192 |
def _verifyBucketContents(sourceDir, sourceFiles, s3BucketUrl): |
| 1193 |
""" |
| 1194 |
Verify that a source directory is equivalent to an Amazon S3 bucket. |
| 1195 |
Args: |
| 1196 |
sourceDir: Local source directory |
| 1197 |
sourceFiles: Filesystem list containing contents of source directory |
| 1198 |
s3BucketUrl: Target S3 bucket URL |
| 1199 |
""" |
| 1200 |
# As of this writing, the documentation for the S3 API that we're using |
| 1201 |
# below says that up to 1000 elements at a time are returned, and that we |
| 1202 |
# have to manually handle pagination by looking for the IsTruncated element. |
| 1203 |
# However, in practice, this is not true. I have been testing with |
| 1204 |
# "aws-cli/1.4.4 Python/2.7.3 Linux/3.2.0-4-686-pae", installed through PIP. |
| 1205 |
# No matter how many items exist in my bucket and prefix, I get back a |
| 1206 |
# single JSON result. I've tested with buckets containing nearly 6000 |
| 1207 |
# elements. |
| 1208 |
# |
| 1209 |
# If I turn on debugging, it's clear that underneath, something in the API |
| 1210 |
# is executing multiple list-object requests against AWS, and stiching |
| 1211 |
# results together to give me back the final JSON result. The debug output |
| 1212 |
# clearly incldues multiple requests, and each XML response (except for the |
| 1213 |
# final one) contains <IsTruncated>true</IsTruncated>. |
| 1214 |
# |
| 1215 |
# This feature is not mentioned in the offical changelog for any of the |
| 1216 |
# releases going back to 1.0.0. It appears to happen in the botocore |
| 1217 |
# library, but I'll admit I can't actually find the code that implements it. |
| 1218 |
# For now, all I can do is rely on this behavior and hope that the |
| 1219 |
# documentation is out-of-date. I'm not going to write code that tries to |
| 1220 |
# parse out IsTruncated if I can't actually test that code. |
| 1221 |
|
| 1222 |
(bucket, prefix) = s3BucketUrl.replace("s3://", "").split("/", 1) |
| 1223 |
|
| 1224 |
query = "Contents[].{Key: Key, Size: Size}" |
| 1225 |
args = ["s3api", "list-objects", "--bucket", bucket, "--prefix", prefix, "--query", query] |
| 1226 |
(result, data) = executeCommand(AWS_COMMAND, args, returnOutput=True) |
| 1227 |
if result != 0: |
| 1228 |
raise OSError("Error [%d] calling AWS CLI verify bucket contents." % result) |
| 1229 |
|
| 1230 |
contents = {} |
| 1231 |
for entry in json.loads("".join(data)): |
| 1232 |
key = entry["Key"].replace(prefix, "") |
| 1233 |
size = int(entry["Size"]) |
| 1234 |
contents[key] = size |
| 1235 |
|
| 1236 |
failed = False |
| 1237 |
for entry in sourceFiles: |
| 1238 |
if os.path.isfile(entry): |
| 1239 |
key = entry.replace(sourceDir, "") |
| 1240 |
size = int(os.stat(entry).st_size) |
| 1241 |
if key not in contents: |
| 1242 |
logger.error("File was apparently not uploaded: [%s]", entry) |
| 1243 |
failed = True |
| 1244 |
else: |
| 1245 |
if size != contents[key]: |
| 1246 |
logger.error("File size differs [%s]: expected %s bytes but got %s bytes", entry, size, contents[key]) |
| 1247 |
failed = True |
| 1248 |
|
| 1249 |
if not failed: |
| 1250 |
logger.info("Completed verifying Amazon S3 bucket contents (no problems found).") |
| 1251 |
else: |
| 1252 |
logger.error("There were differences between source directory and target S3 bucket.") |
| 1253 |
raise ValueError("There were differences between source directory and target S3 bucket.") |
| 1254 |
|
| 1255 |
|
| 1256 |
######################################################################### |
| 1257 |
# Main routine |
| 1258 |
######################################################################## |
| 1259 |
|
| 1260 |
if __name__ == "__main__": |
| 1261 |
sys.exit(cli()) |