Debian Codegraph @

src/CedarBackup3/extend/amazons3.py

raw
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-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 : Official Cedar Backup Extensions
29 # Purpose : "Store" type extension that writes data to Amazon S3.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Store-type extension that writes data to Amazon S3.
39
40 This extension requires a new configuration section <amazons3> and is intended
41 to be run immediately after the standard stage action, replacing the standard
42 store action. Aside from its own configuration, it requires the options and
43 staging configuration sections in the standard Cedar Backup configuration file.
44 Since it is intended to replace the store action, it does not rely on any store
45 configuration.
46
47 The underlying functionality relies on the U{AWS CLI interface
48 <http://aws.amazon.com/documentation/cli/>}. Before you use this extension,
49 you need to set up your Amazon S3 account and configure the AWS CLI connection
50 per Amazon's documentation. The extension assumes that the backup is being
51 executed as root, and switches over to the configured backup user to
52 communicate with AWS. So, make sure you configure AWS CLI as the backup user
53 and not root.
54
55 You can optionally configure Cedar Backup to encrypt data before sending it
56 to S3. To do that, provide a complete command line using the ``${input``} and
57 ``${output``} variables to represent the original input file and the encrypted
58 output file. This command will be executed as the backup user.
59
60 For instance, you can use something like this with GPG::
61
62 /usr/bin/gpg -c --no-use-agent --batch --yes --passphrase-file /home/backup/.passphrase -o ${output} ${input}
63
64 The GPG mechanism depends on a strong passphrase for security. One way to
65 generate a strong passphrase is using your system random number generator, i.e.::
66
67 dd if=/dev/urandom count=20 bs=1 | xxd -ps
68
69 (See U{StackExchange <http://security.stackexchange.com/questions/14867/gpg-encryption-security>}
70 for more details about that advice.) If you decide to use encryption, make sure
71 you save off the passphrase in a safe place, so you can get at your backup data
72 later if you need to. And obviously, make sure to set permissions on the
73 passphrase file so it can only be read by the backup user.
74
75 This extension was written for and tested on Linux. It will throw an exception
76 if run on Windows.
77
78 :author: Kenneth J. Pronovici <[email protected]>
79 """
80
81 ########################################################################
82 # Imported modules
83 ########################################################################
84
85 import datetime
86 import json
87 import logging
88 import os
89 import shutil
90 import sys
91 import tempfile
92 from functools import total_ordering
93
94 from CedarBackup3.actions.constants import DIR_TIME_FORMAT, STAGE_INDICATOR
95 from CedarBackup3.actions.util import writeIndicatorFile
96 from CedarBackup3.config import ByteQuantity, addByteQuantityNode, readByteQuantity
97 from CedarBackup3.filesystem import BackupFileList, FilesystemList
98 from CedarBackup3.util import (
99 UNIT_BYTES,
100 changeOwnership,
101 displayBytes,
102 executeCommand,
103 isRunningAsRoot,
104 isStartOfWeek,
105 pathJoin,
106 resolveCommand,
107 )
108 from CedarBackup3.xmlutil import (
109 addBooleanNode,
110 addContainerNode,
111 addStringNode,
112 createInputDom,
113 readBoolean,
114 readFirstChild,
115 readString,
116 )
117
118 ########################################################################
119 # Module-wide constants and variables
120 ########################################################################
121
122 logger = logging.getLogger("CedarBackup3.log.extend.amazons3")
123
124 SU_COMMAND = ["su"]
125 AWS_COMMAND = ["aws"]
126
127 STORE_INDICATOR = "cback.amazons3"
128
129
130 ########################################################################
131 # AmazonS3Config class definition
132 ########################################################################
133
134
135 @total_ordering
136 class AmazonS3Config:
137 """
138 Class representing Amazon S3 configuration.
139
140 Amazon S3 configuration is used for storing backup data in Amazon's S3 cloud
141 storage using the ``s3cmd`` tool.
142
143 The following restrictions exist on data in this class:
144
145 - The s3Bucket value must be a non-empty string
146 - The encryptCommand value, if set, must be a non-empty string
147 - The full backup size limit, if set, must be a ByteQuantity >= 0
148 - The incremental backup size limit, if set, must be a ByteQuantity >= 0
149
150 """
151
152 def __init__(
153 self, warnMidnite=None, s3Bucket=None, encryptCommand=None, fullBackupSizeLimit=None, incrementalBackupSizeLimit=None
154 ):
155 """
156 Constructor for the ``AmazonS3Config`` class.
157
158 Args:
159 warnMidnite: Whether to generate warnings for crossing midnite
160 s3Bucket: Name of the Amazon S3 bucket in which to store the data
161 encryptCommand: Command used to encrypt backup data before upload to S3
162 fullBackupSizeLimit: Maximum size of a full backup, a ByteQuantity
163 incrementalBackupSizeLimit: Maximum size of an incremental backup, a ByteQuantity
164
165 Raises:
166 ValueError: If one of the values is invalid
167 """
168 self._warnMidnite = None
169 self._s3Bucket = None
170 self._encryptCommand = None
171 self._fullBackupSizeLimit = None
172 self._incrementalBackupSizeLimit = None
173 self.warnMidnite = warnMidnite
174 self.s3Bucket = s3Bucket
175 self.encryptCommand = encryptCommand
176 self.fullBackupSizeLimit = fullBackupSizeLimit
177 self.incrementalBackupSizeLimit = incrementalBackupSizeLimit
178
179 def __repr__(self):
180 """
181 Official string representation for class instance.
182 """
183 return "AmazonS3Config(%s, %s, %s, %s, %s)" % (
184 self.warnMidnite,
185 self.s3Bucket,
186 self.encryptCommand,
187 self.fullBackupSizeLimit,
188 self.incrementalBackupSizeLimit,
189 )
190
191 def __str__(self):
192 """
193 Informal string representation for class instance.
194 """
195 return self.__repr__()
196
197 def __eq__(self, other):
198 """Equals operator, iplemented in terms of original Python 2 compare operator."""
199 return self.__cmp__(other) == 0
200
201 def __lt__(self, other):
202 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
203 return self.__cmp__(other) < 0
204
205 def __gt__(self, other):
206 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
207 return self.__cmp__(other) > 0
208
209 def __cmp__(self, other):
210 """
211 Original Python 2 comparison operator.
212 Args:
213 other: Other object to compare to
214 Returns:
215 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
216 """
217 if other is None:
218 return 1
219 if self.warnMidnite != other.warnMidnite:
220 if self.warnMidnite < other.warnMidnite:
221 return -1
222 else:
223 return 1
224 if self.s3Bucket != other.s3Bucket:
225 if str(self.s3Bucket or "") < str(other.s3Bucket or ""):
226 return -1
227 else:
228 return 1
229 if self.encryptCommand != other.encryptCommand:
230 if str(self.encryptCommand or "") < str(other.encryptCommand or ""):
231 return -1
232 else:
233 return 1
234 if self.fullBackupSizeLimit != other.fullBackupSizeLimit:
235 if (self.fullBackupSizeLimit or ByteQuantity()) < (other.fullBackupSizeLimit or ByteQuantity()):
236 return -1
237 else:
238 return 1
239 if self.incrementalBackupSizeLimit != other.incrementalBackupSizeLimit:
240 if (self.incrementalBackupSizeLimit or ByteQuantity()) < (other.incrementalBackupSizeLimit or ByteQuantity()):
241 return -1
242 else:
243 return 1
244 return 0
245
246 def _setWarnMidnite(self, value):
247 """
248 Property target used to set the midnite warning flag.
249 No validations, but we normalize the value to ``True`` or ``False``.
250 """
251 if value:
252 self._warnMidnite = True
253 else:
254 self._warnMidnite = False
255
256 def _getWarnMidnite(self):
257 """
258 Property target used to get the midnite warning flag.
259 """
260 return self._warnMidnite
261
262 def _setS3Bucket(self, value):
263 """
264 Property target used to set the S3 bucket.
265 """
266 if value is not None:
267 if len(value) < 1:
268 raise ValueError("S3 bucket must be non-empty string.")
269 self._s3Bucket = value
270
271 def _getS3Bucket(self):
272 """
273 Property target used to get the S3 bucket.
274 """
275 return self._s3Bucket
276
277 def _setEncryptCommand(self, value):
278 """
279 Property target used to set the encrypt command.
280 """
281 if value is not None:
282 if len(value) < 1:
283 raise ValueError("Encrypt command must be non-empty string.")
284 self._encryptCommand = value
285
286 def _getEncryptCommand(self):
287 """
288 Property target used to get the encrypt command.
289 """
290 return self._encryptCommand
291
292 def _setFullBackupSizeLimit(self, value):
293 """
294 Property target used to set the full backup size limit.
295 The value must be an integer >= 0.
296 Raises:
297 ValueError: If the value is not valid
298 """
299 if value is None:
300 self._fullBackupSizeLimit = None
301 else:
302 if isinstance(value, ByteQuantity):
303 self._fullBackupSizeLimit = value
304 else:
305 self._fullBackupSizeLimit = ByteQuantity(value, UNIT_BYTES)
306
307 def _getFullBackupSizeLimit(self):
308 """
309 Property target used to get the full backup size limit.
310 """
311 return self._fullBackupSizeLimit
312
313 def _setIncrementalBackupSizeLimit(self, value):
314 """
315 Property target used to set the incremental backup size limit.
316 The value must be an integer >= 0.
317 Raises:
318 ValueError: If the value is not valid
319 """
320 if value is None:
321 self._incrementalBackupSizeLimit = None
322 else:
323 if isinstance(value, ByteQuantity):
324 self._incrementalBackupSizeLimit = value
325 else:
326 self._incrementalBackupSizeLimit = ByteQuantity(value, UNIT_BYTES)
327
328 def _getIncrementalBackupSizeLimit(self):
329 """
330 Property target used to get the incremental backup size limit.
331 """
332 return self._incrementalBackupSizeLimit
333
334 warnMidnite = property(_getWarnMidnite, _setWarnMidnite, None, "Whether to generate warnings for crossing midnite.")
335 s3Bucket = property(_getS3Bucket, _setS3Bucket, None, doc="Amazon S3 Bucket in which to store data")
336 encryptCommand = property(_getEncryptCommand, _setEncryptCommand, None, doc="Command used to encrypt data before upload to S3")
337 fullBackupSizeLimit = property(
338 _getFullBackupSizeLimit, _setFullBackupSizeLimit, None, doc="Maximum size of a full backup, as a ByteQuantity"
339 )
340 incrementalBackupSizeLimit = property(
341 _getIncrementalBackupSizeLimit,
342 _setIncrementalBackupSizeLimit,
343 None,
344 doc="Maximum size of an incremental backup, as a ByteQuantity",
345 )
346
347
348 ########################################################################
349 # LocalConfig class definition
350 ########################################################################
351
352
353 @total_ordering
354 class LocalConfig:
355 """
356 Class representing this extension's configuration document.
357
358 This is not a general-purpose configuration object like the main Cedar
359 Backup configuration object. Instead, it just knows how to parse and emit
360 amazons3-specific configuration values. Third parties who need to read and
361 write configuration related to this extension should access it through the
362 constructor, ``validate`` and ``addConfig`` methods.
363
364 *Note:* Lists within this class are "unordered" for equality comparisons.
365
366 """
367
368 def __init__(self, xmlData=None, xmlPath=None, validate=True):
369 """
370 Initializes a configuration object.
371
372 If you initialize the object without passing either ``xmlData`` or
373 ``xmlPath`` then configuration will be empty and will be invalid until it
374 is filled in properly.
375
376 No reference to the original XML data or original path is saved off by
377 this class. Once the data has been parsed (successfully or not) this
378 original information is discarded.
379
380 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
381 method will be called (with its default arguments) against configuration
382 after successfully parsing any passed-in XML. Keep in mind that even if
383 ``validate`` is ``False``, it might not be possible to parse the passed-in
384 XML document if lower-level validations fail.
385
386 *Note:* It is strongly suggested that the ``validate`` option always be set
387 to ``True`` (the default) unless there is a specific need to read in
388 invalid configuration from disk.
389
390 Args:
391 xmlData (String data): XML data representing configuration
392 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
393 validate (Boolean true/false): Validate the document after parsing it
394 Raises:
395 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
396 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
397 ValueError: If the parsed configuration document is not valid
398 """
399 self._amazons3 = None
400 self.amazons3 = None
401 if xmlData is not None and xmlPath is not None:
402 raise ValueError("Use either xmlData or xmlPath, but not both.")
403 if xmlData is not None:
404 self._parseXmlData(xmlData)
405 if validate:
406 self.validate()
407 elif xmlPath is not None:
408 with open(xmlPath) as f:
409 xmlData = f.read()
410 self._parseXmlData(xmlData)
411 if validate:
412 self.validate()
413
414 def __repr__(self):
415 """
416 Official string representation for class instance.
417 """
418 return "LocalConfig(%s)" % (self.amazons3)
419
420 def __str__(self):
421 """
422 Informal string representation for class instance.
423 """
424 return self.__repr__()
425
426 def __eq__(self, other):
427 """Equals operator, iplemented in terms of original Python 2 compare operator."""
428 return self.__cmp__(other) == 0
429
430 def __lt__(self, other):
431 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
432 return self.__cmp__(other) < 0
433
434 def __gt__(self, other):
435 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
436 return self.__cmp__(other) > 0
437
438 def __cmp__(self, other):
439 """
440 Original Python 2 comparison operator.
441 Lists within this class are "unordered" for equality comparisons.
442 Args:
443 other: Other object to compare to
444 Returns:
445 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
446 """
447 if other is None:
448 return 1
449 if self.amazons3 != other.amazons3:
450 if self.amazons3 < other.amazons3:
451 return -1
452 else:
453 return 1
454 return 0
455
456 def _setAmazonS3(self, value):
457 """
458 Property target used to set the amazons3 configuration value.
459 If not ``None``, the value must be a ``AmazonS3Config`` object.
460 Raises:
461 ValueError: If the value is not a ``AmazonS3Config``
462 """
463 if value is None:
464 self._amazons3 = None
465 else:
466 if not isinstance(value, AmazonS3Config):
467 raise ValueError("Value must be a ``AmazonS3Config`` object.")
468 self._amazons3 = value
469
470 def _getAmazonS3(self):
471 """
472 Property target used to get the amazons3 configuration value.
473 """
474 return self._amazons3
475
476 amazons3 = property(_getAmazonS3, _setAmazonS3, None, "AmazonS3 configuration in terms of a ``AmazonS3Config`` object.")
477
478 def validate(self):
479 """
480 Validates configuration represented by the object.
481
482 AmazonS3 configuration must be filled in. Within that, the s3Bucket target must be filled in
483
484 Raises:
485 ValueError: If one of the validations fails
486 """
487 if self.amazons3 is None:
488 raise ValueError("AmazonS3 section is required.")
489 if self.amazons3.s3Bucket is None:
490 raise ValueError("AmazonS3 s3Bucket must be set.")
491
492 def addConfig(self, xmlDom, parentNode):
493 """
494 Adds an <amazons3> configuration section as the next child of a parent.
495
496 Third parties should use this function to write configuration related to
497 this extension.
498
499 We add the following fields to the document::
500
501 warnMidnite //cb_config/amazons3/warn_midnite
502 s3Bucket //cb_config/amazons3/s3_bucket
503 encryptCommand //cb_config/amazons3/encrypt
504 fullBackupSizeLimit //cb_config/amazons3/full_size_limit
505 incrementalBackupSizeLimit //cb_config/amazons3/incr_size_limit
506
507 Args:
508 xmlDom: DOM tree as from ``impl.createDocument()``
509 parentNode: Parent that the section should be appended to
510 """
511 if self.amazons3 is not None:
512 sectionNode = addContainerNode(xmlDom, parentNode, "amazons3")
513 addBooleanNode(xmlDom, sectionNode, "warn_midnite", self.amazons3.warnMidnite)
514 addStringNode(xmlDom, sectionNode, "s3_bucket", self.amazons3.s3Bucket)
515 addStringNode(xmlDom, sectionNode, "encrypt", self.amazons3.encryptCommand)
516 addByteQuantityNode(xmlDom, sectionNode, "full_size_limit", self.amazons3.fullBackupSizeLimit)
517 addByteQuantityNode(xmlDom, sectionNode, "incr_size_limit", self.amazons3.incrementalBackupSizeLimit)
518
519 def _parseXmlData(self, xmlData):
520 """
521 Internal method to parse an XML string into the object.
522
523 This method parses the XML document into a DOM tree (``xmlDom``) and then
524 calls a static method to parse the amazons3 configuration section.
525
526 Args:
527 xmlData (String data): XML data to be parsed
528 Raises:
529 ValueError: If the XML cannot be successfully parsed
530 """
531 (_, parentNode) = createInputDom(xmlData)
532 self._amazons3 = LocalConfig._parseAmazonS3(parentNode)
533
534 @staticmethod
535 def _parseAmazonS3(parent):
536 """
537 Parses an amazons3 configuration section.
538
539 We read the following individual fields::
540
541 warnMidnite //cb_config/amazons3/warn_midnite
542 s3Bucket //cb_config/amazons3/s3_bucket
543 encryptCommand //cb_config/amazons3/encrypt
544 fullBackupSizeLimit //cb_config/amazons3/full_size_limit
545 incrementalBackupSizeLimit //cb_config/amazons3/incr_size_limit
546
547 Args:
548 parent: Parent node to search beneath
549
550 Returns:
551 ``AmazonS3Config`` object or ``None`` if the section does not exist
552 Raises:
553 ValueError: If some filled-in value is invalid
554 """
555 amazons3 = None
556 section = readFirstChild(parent, "amazons3")
557 if section is not None:
558 amazons3 = AmazonS3Config()
559 amazons3.warnMidnite = readBoolean(section, "warn_midnite")
560 amazons3.s3Bucket = readString(section, "s3_bucket")
561 amazons3.encryptCommand = readString(section, "encrypt")
562 amazons3.fullBackupSizeLimit = readByteQuantity(section, "full_size_limit")
563 amazons3.incrementalBackupSizeLimit = readByteQuantity(section, "incr_size_limit")
564 return amazons3
565
566
567 ########################################################################
568 # Public functions
569 ########################################################################
570
571 ###########################
572 # executeAction() function
573 ###########################
574
575
576 def executeAction(configPath, options, config):
577 """
578 Executes the amazons3 backup action.
579
580 Args:
581 configPath (String representing a path on disk): Path to configuration file on disk
582 options (Options object): Program command-line options
583 config (Config object): Program configuration
584 Raises:
585 ValueError: Under many generic error conditions
586 IOError: If there are I/O problems reading or writing files
587 """
588 logger.debug("Executing amazons3 extended action.")
589 if not isRunningAsRoot():
590 logger.error("Error: the amazons3 extended action must be run as root.")
591 raise ValueError("The amazons3 extended action must be run as root.")
592 if sys.platform == "win32":
593 logger.error("Error: the amazons3 extended action is not supported on Windows.")
594 raise ValueError("The amazons3 extended action is not supported on Windows.")
595 if config.options is None or config.stage is None:
596 raise ValueError("Cedar Backup configuration is not properly filled in.")
597 local = LocalConfig(xmlPath=configPath)
598 stagingDirs = _findCorrectDailyDir(options, config, local)
599 _applySizeLimits(options, config, local, stagingDirs)
600 _writeToAmazonS3(config, local, stagingDirs)
601 _writeStoreIndicator(config, stagingDirs)
602 logger.info("Executed the amazons3 extended action successfully.")
603
604
605 ########################################################################
606 # Private utility functions
607 ########################################################################
608
609 #########################
610 # _findCorrectDailyDir()
611 #########################
612
613
614 def _findCorrectDailyDir(options, config, local):
615 """
616 Finds the correct daily staging directory to be written to Amazon S3.
617
618 This is substantially similar to the same function in store.py. The
619 main difference is that it doesn't rely on store configuration at all.
620
621 Args:
622 options: Options object
623 config: Config object
624 local: Local config object
625
626 Returns:
627 Correct staging dir, as a dict mapping directory to date suffix
628 Raises:
629 IOError: If the staging directory cannot be found
630 """
631 oneDay = datetime.timedelta(days=1)
632 today = datetime.date.today()
633 yesterday = today - oneDay
634 tomorrow = today + oneDay
635 todayDate = today.strftime(DIR_TIME_FORMAT)
636 yesterdayDate = yesterday.strftime(DIR_TIME_FORMAT)
637 tomorrowDate = tomorrow.strftime(DIR_TIME_FORMAT)
638 todayPath = pathJoin(config.stage.targetDir, todayDate)
639 yesterdayPath = pathJoin(config.stage.targetDir, yesterdayDate)
640 tomorrowPath = pathJoin(config.stage.targetDir, tomorrowDate)
641 todayStageInd = pathJoin(todayPath, STAGE_INDICATOR)
642 yesterdayStageInd = pathJoin(yesterdayPath, STAGE_INDICATOR)
643 tomorrowStageInd = pathJoin(tomorrowPath, STAGE_INDICATOR)
644 todayStoreInd = pathJoin(todayPath, STORE_INDICATOR)
645 yesterdayStoreInd = pathJoin(yesterdayPath, STORE_INDICATOR)
646 tomorrowStoreInd = pathJoin(tomorrowPath, STORE_INDICATOR)
647 if options.full:
648 if os.path.isdir(todayPath) and os.path.exists(todayStageInd):
649 logger.info("Amazon S3 process will use current day's staging directory [%s]", todayPath)
650 return {todayPath: todayDate}
651 raise OSError("Unable to find staging directory to process (only tried today due to full option).")
652 else:
653 if os.path.isdir(todayPath) and os.path.exists(todayStageInd) and not os.path.exists(todayStoreInd):
654 logger.info("Amazon S3 process will use current day's staging directory [%s]", todayPath)
655 return {todayPath: todayDate}
656 elif os.path.isdir(yesterdayPath) and os.path.exists(yesterdayStageInd) and not os.path.exists(yesterdayStoreInd):
657 logger.info("Amazon S3 process will use previous day's staging directory [%s]", yesterdayPath)
658 if local.amazons3.warnMidnite:
659 logger.warning("Warning: Amazon S3 process crossed midnite boundary to find data.")
660 return {yesterdayPath: yesterdayDate}
661 elif os.path.isdir(tomorrowPath) and os.path.exists(tomorrowStageInd) and not os.path.exists(tomorrowStoreInd):
662 logger.info("Amazon S3 process will use next day's staging directory [%s]", tomorrowPath)
663 if local.amazons3.warnMidnite:
664 logger.warning("Warning: Amazon S3 process crossed midnite boundary to find data.")
665 return {tomorrowPath: tomorrowDate}
666 raise OSError("Unable to find unused staging directory to process (tried today, yesterday, tomorrow).")
667
668
669 ##############################
670 # _applySizeLimits() function
671 ##############################
672
673
674 def _applySizeLimits(options, config, local, stagingDirs):
675 """
676 Apply size limits, throwing an exception if any limits are exceeded.
677
678 Size limits are optional. If a limit is set to None, it does not apply.
679 The full size limit applies if the full option is set or if today is the
680 start of the week. The incremental size limit applies otherwise. Limits
681 are applied to the total size of all the relevant staging directories.
682
683 Args:
684 options: Options object
685 config: Config object
686 local: Local config object
687 stagingDirs: Dictionary mapping directory path to date suffix
688
689 Raises:
690 ValueError: Under many generic error conditions
691 ValueError: If a size limit has been exceeded
692 """
693 if options.full or isStartOfWeek(config.options.startingDay):
694 logger.debug("Using Amazon S3 size limit for full backups.")
695 limit = local.amazons3.fullBackupSizeLimit
696 else:
697 logger.debug("Using Amazon S3 size limit for incremental backups.")
698 limit = local.amazons3.incrementalBackupSizeLimit
699 if limit is None:
700 logger.debug("No Amazon S3 size limit will be applied.")
701 else:
702 logger.debug("Amazon S3 size limit is: %s", limit)
703 contents = BackupFileList()
704 for stagingDir in stagingDirs:
705 contents.addDirContents(stagingDir)
706 total = contents.totalSize()
707 logger.debug("Amazon S3 backup size is: %s", displayBytes(total))
708 if total > limit:
709 logger.error("Amazon S3 size limit exceeded: %s > %s", displayBytes(total), limit)
710 raise ValueError("Amazon S3 size limit exceeded: %s > %s" % (displayBytes(total), limit))
711 else:
712 logger.info("Total size does not exceed Amazon S3 size limit, so backup can continue.")
713
714
715 ##############################
716 # _writeToAmazonS3() function
717 ##############################
718
719
720 def _writeToAmazonS3(config, local, stagingDirs):
721 """
722 Writes the indicated staging directories to an Amazon S3 bucket.
723
724 Each of the staging directories listed in ``stagingDirs`` will be written to
725 the configured Amazon S3 bucket from local configuration. The directories
726 will be placed into the image at the root by date, so staging directory
727 ``/opt/stage/2005/02/10`` will be placed into the S3 bucket at ``/2005/02/10``.
728 If an encrypt commmand is provided, the files will be encrypted first.
729
730 Args:
731 config: Config object
732 local: Local config object
733 stagingDirs: Dictionary mapping directory path to date suffix
734
735 Raises:
736 ValueError: Under many generic error conditions
737 IOError: If there is a problem writing to Amazon S3
738 """
739 for stagingDir in list(stagingDirs.keys()):
740 logger.debug("Storing stage directory to Amazon S3 [%s].", stagingDir)
741 dateSuffix = stagingDirs[stagingDir]
742 s3BucketUrl = "s3://%s/%s" % (local.amazons3.s3Bucket, dateSuffix)
743 logger.debug("S3 bucket URL is [%s]", s3BucketUrl)
744 _clearExistingBackup(config, s3BucketUrl)
745 if local.amazons3.encryptCommand is None:
746 logger.debug("Encryption is disabled; files will be uploaded in cleartext.")
747 _uploadStagingDir(config, stagingDir, s3BucketUrl)
748 _verifyUpload(config, stagingDir, s3BucketUrl)
749 else:
750 logger.debug("Encryption is enabled; files will be uploaded after being encrypted.")
751 encryptedDir = tempfile.mkdtemp(dir=config.options.workingDir)
752 changeOwnership(encryptedDir, config.options.backupUser, config.options.backupGroup)
753 try:
754 _encryptStagingDir(config, local, stagingDir, encryptedDir)
755 _uploadStagingDir(config, encryptedDir, s3BucketUrl)
756 _verifyUpload(config, encryptedDir, s3BucketUrl)
757 finally:
758 if os.path.exists(encryptedDir):
759 shutil.rmtree(encryptedDir)
760
761
762 ##################################
763 # _writeStoreIndicator() function
764 ##################################
765
766
767 def _writeStoreIndicator(config, stagingDirs):
768 """
769 Writes a store indicator file into staging directories.
770 Args:
771 config: Config object
772 stagingDirs: Dictionary mapping directory path to date suffix
773 """
774 for stagingDir in list(stagingDirs.keys()):
775 writeIndicatorFile(stagingDir, STORE_INDICATOR, config.options.backupUser, config.options.backupGroup)
776
777
778 ##################################
779 # _clearExistingBackup() function
780 ##################################
781
782
783 def _clearExistingBackup(config, s3BucketUrl):
784 """
785 Clear any existing backup files for an S3 bucket URL.
786 Args:
787 config: Config object
788 s3BucketUrl: S3 bucket URL associated with the staging directory
789 """
790 suCommand = resolveCommand(SU_COMMAND)
791 awsCommand = resolveCommand(AWS_COMMAND)
792 actualCommand = "%s s3 rm --recursive %s/" % (awsCommand[0], s3BucketUrl)
793 result = executeCommand(suCommand, [config.options.backupUser, "-c", actualCommand])[0]
794 if result != 0:
795 raise OSError("Error [%d] calling AWS CLI to clear existing backup for [%s]." % (result, s3BucketUrl))
796 logger.debug("Completed clearing any existing backup in S3 for [%s]", s3BucketUrl)
797
798
799 ###############################
800 # _uploadStagingDir() function
801 ###############################
802
803
804 def _uploadStagingDir(config, stagingDir, s3BucketUrl):
805 """
806 Upload the contents of a staging directory out to the Amazon S3 cloud.
807 Args:
808 config: Config object
809 stagingDir: Staging directory to upload
810 s3BucketUrl: S3 bucket URL associated with the staging directory
811 """
812 # The version of awscli in Debian stretch (1.11.13-1) has a problem
813 # uploading empty files, due to running with Python 3 rather than Python 2
814 # as the upstream maintainers intended. To work around this, I'm explicitly
815 # excluding files like cback.stage, cback.collect, etc. which should be the
816 # only empty files we ever try to copy. See: https://github.com/aws/aws-cli/issues/2403
817 suCommand = resolveCommand(SU_COMMAND)
818 awsCommand = resolveCommand(AWS_COMMAND)
819 actualCommand = '%s s3 cp --recursive --exclude "*cback.*" %s/ %s/' % (awsCommand[0], stagingDir, s3BucketUrl)
820 result = executeCommand(suCommand, [config.options.backupUser, "-c", actualCommand])[0]
821 if result != 0:
822 raise OSError("Error [%d] calling AWS CLI to upload staging directory to [%s]." % (result, s3BucketUrl))
823 logger.debug("Completed uploading staging dir [%s] to [%s]", stagingDir, s3BucketUrl)
824
825
826 ###########################
827 # _verifyUpload() function
828 ###########################
829
830
831 def _verifyUpload(config, stagingDir, s3BucketUrl):
832 """
833 Verify that a staging directory was properly uploaded to the Amazon S3 cloud.
834 Args:
835 config: Config object
836 stagingDir: Staging directory to verify
837 s3BucketUrl: S3 bucket URL associated with the staging directory
838 """
839 (bucket, prefix) = s3BucketUrl.replace("s3://", "").split("/", 1)
840 suCommand = resolveCommand(SU_COMMAND)
841 awsCommand = resolveCommand(AWS_COMMAND)
842 query = "Contents[].{Key: Key, Size: Size}"
843 actualCommand = "%s s3api list-objects --bucket %s --prefix %s --query '%s'" % (awsCommand[0], bucket, prefix, query)
844 (result, data) = executeCommand(suCommand, [config.options.backupUser, "-c", actualCommand], returnOutput=True)
845 if result != 0:
846 raise OSError("Error [%d] calling AWS CLI verify upload to [%s]." % (result, s3BucketUrl))
847 contents = {}
848 for entry in json.loads("".join(data)):
849 key = entry["Key"].replace(prefix, "")
850 size = int(entry["Size"])
851 contents[key] = size
852 files = FilesystemList()
853 files.excludeBasenamePatterns = [r"cback\..*"] # because these are excluded from the upload
854 files.addDirContents(stagingDir)
855 for entry in files:
856 if os.path.isfile(entry):
857 key = entry.replace(stagingDir, "")
858 size = int(os.stat(entry).st_size)
859 if key not in contents:
860 raise OSError("File was apparently not uploaded: [%s]" % entry)
861 else:
862 if size != contents[key]:
863 raise OSError("File size differs [%s], expected %s bytes but got %s bytes" % (entry, size, contents[key]))
864 logger.debug("Completed verifying upload from [%s] to [%s].", stagingDir, s3BucketUrl)
865
866
867 ################################
868 # _encryptStagingDir() function
869 ################################
870
871
872 def _encryptStagingDir(config, local, stagingDir, encryptedDir):
873 """
874 Encrypt a staging directory, creating a new directory in the process.
875 Args:
876 config: Config object
877 stagingDir: Staging directory to use as source
878 encryptedDir: Target directory into which encrypted files should be written
879 """
880 suCommand = resolveCommand(SU_COMMAND)
881 files = FilesystemList()
882 files.addDirContents(stagingDir)
883 for cleartext in files:
884 if os.path.isfile(cleartext):
885 encrypted = "%s%s" % (encryptedDir, cleartext.replace(stagingDir, ""))
886 if int(os.stat(cleartext).st_size) == 0:
887 with open(encrypted, "a") as f:
888 f.close() # don't bother encrypting empty files
889 else:
890 actualCommand = local.amazons3.encryptCommand.replace("${input}", cleartext).replace("${output}", encrypted)
891 subdir = os.path.dirname(encrypted)
892 if not os.path.isdir(subdir):
893 os.makedirs(subdir)
894 changeOwnership(subdir, config.options.backupUser, config.options.backupGroup)
895 result = executeCommand(suCommand, [config.options.backupUser, "-c", actualCommand])[0]
896 if result != 0:
897 raise OSError("Error [%d] encrypting [%s]." % (result, cleartext))
898 logger.debug("Completed encrypting staging directory [%s] into [%s]", stagingDir, encryptedDir)