Debian Codegraph @

src/CedarBackup3/extend/mbox.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) 2006-2007,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Official Cedar Backup Extensions
29 # Purpose : Provides an extension to back up mbox email files.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to back up mbox email files.
39
40 Backing up email
41 ================
42
43 Email folders (often stored as mbox flatfiles) are not well-suited being backed
44 up with an incremental backup like the one offered by Cedar Backup. This is
45 because mbox files often change on a daily basis, forcing the incremental
46 backup process to back them up every day in order to avoid losing data. This
47 can result in quite a bit of wasted space when backing up large folders. (Note
48 that the alternative maildir format does not share this problem, since it
49 typically uses one file per message.)
50
51 One solution to this problem is to design a smarter incremental backup process,
52 which backs up baseline content on the first day of the week, and then backs up
53 only new messages added to that folder on every other day of the week. This way,
54 the backup for any single day is only as large as the messages placed into the
55 folder on that day. The backup isn't as "perfect" as the incremental backup
56 process, because it doesn't preserve information about messages deleted from
57 the backed-up folder. However, it should be much more space-efficient, and
58 in a recovery situation, it seems better to restore too much data rather
59 than too little.
60
61 What is this extension?
62 =======================
63
64 This is a Cedar Backup extension used to back up mbox email files via the Cedar
65 Backup command line. Individual mbox files or directories containing mbox
66 files can be backed up using the same collect modes allowed for filesystems in
67 the standard Cedar Backup collect action: weekly, daily, incremental. It
68 implements the "smart" incremental backup process discussed above, using
69 functionality provided by the ``grepmail`` utility.
70
71 This extension requires a new configuration section <mbox> and is intended to
72 be run either immediately before or immediately after the standard collect
73 action. Aside from its own configuration, it requires the options and collect
74 configuration sections in the standard Cedar Backup configuration file.
75
76 The mbox action is conceptually similar to the standard collect action,
77 except that mbox directories are not collected recursively. This implies
78 some configuration changes (i.e. there's no need for global exclusions or an
79 ignore file). If you back up a directory, all of the mbox files in that
80 directory are backed up into a single tar file using the indicated
81 compression method.
82
83 :author: Kenneth J. Pronovici <[email protected]>
84 """
85
86 ########################################################################
87 # Imported modules
88 ########################################################################
89
90 import datetime
91 import logging
92 import os
93 import pickle # ruff: ignore[suspicious-pickle-import] # we operate on trusted data, so pickle is ok
94 import posixpath
95 import tempfile
96 from bz2 import BZ2File
97 from functools import total_ordering
98 from gzip import GzipFile
99
100 from CedarBackup3.config import VALID_COLLECT_MODES, VALID_COMPRESS_MODES
101 from CedarBackup3.filesystem import BackupFileList, FilesystemList
102 from CedarBackup3.util import (
103 ObjectTypeList,
104 RegexList,
105 UnorderedList,
106 buildNormalizedPath,
107 changeOwnership,
108 encodePath,
109 executeCommand,
110 isStartOfWeek,
111 pathJoin,
112 resolveCommand,
113 )
114 from CedarBackup3.xmlutil import (
115 addContainerNode,
116 addStringNode,
117 createInputDom,
118 isElement,
119 readChildren,
120 readFirstChild,
121 readString,
122 readStringList,
123 )
124
125 ########################################################################
126 # Module-wide constants and variables
127 ########################################################################
128
129 logger = logging.getLogger("CedarBackup3.log.extend.mbox")
130
131 GREPMAIL_COMMAND = ["grepmail"]
132 REVISION_PATH_EXTENSION = "mboxlast"
133
134
135 ########################################################################
136 # MboxFile class definition
137 ########################################################################
138
139
140 @total_ordering
141 class MboxFile:
142 """
143 Class representing mbox file configuration..
144
145 The following restrictions exist on data in this class:
146
147 - The absolute path must be absolute.
148 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
149 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
150
151 """
152
153 def __init__(self, absolutePath=None, collectMode=None, compressMode=None):
154 """
155 Constructor for the ``MboxFile`` class.
156
157 You should never directly instantiate this class.
158
159 Args:
160 absolutePath: Absolute path to an mbox file on disk
161 collectMode: Overridden collect mode for this directory
162 compressMode: Overridden compression mode for this directory
163 """
164 self._absolutePath = None
165 self._collectMode = None
166 self._compressMode = None
167 self.absolutePath = absolutePath
168 self.collectMode = collectMode
169 self.compressMode = compressMode
170
171 def __repr__(self):
172 """
173 Official string representation for class instance.
174 """
175 return "MboxFile(%s, %s, %s)" % (self.absolutePath, self.collectMode, self.compressMode)
176
177 def __str__(self):
178 """
179 Informal string representation for class instance.
180 """
181 return self.__repr__()
182
183 def __eq__(self, other):
184 """Equals operator, iplemented in terms of original Python 2 compare operator."""
185 return self.__cmp__(other) == 0
186
187 def __lt__(self, other):
188 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
189 return self.__cmp__(other) < 0
190
191 def __gt__(self, other):
192 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
193 return self.__cmp__(other) > 0
194
195 def __cmp__(self, other):
196 """
197 Original Python 2 comparison operator.
198 Args:
199 other: Other object to compare to
200 Returns:
201 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
202 """
203 if other is None:
204 return 1
205 if self.absolutePath != other.absolutePath:
206 if str(self.absolutePath or "") < str(other.absolutePath or ""):
207 return -1
208 else:
209 return 1
210 if self.collectMode != other.collectMode:
211 if str(self.collectMode or "") < str(other.collectMode or ""):
212 return -1
213 else:
214 return 1
215 if self.compressMode != other.compressMode:
216 if str(self.compressMode or "") < str(other.compressMode or ""):
217 return -1
218 else:
219 return 1
220 return 0
221
222 def _setAbsolutePath(self, value):
223 """
224 Property target used to set the absolute path.
225 The value must be an absolute path if it is not ``None``.
226 It does not have to exist on disk at the time of assignment.
227 Raises:
228 ValueError: If the value is not an absolute path
229 ValueError: If the value cannot be encoded properly
230 """
231 if value is not None:
232 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
233 raise ValueError("Absolute path must be, er, an absolute path.")
234 self._absolutePath = encodePath(value)
235
236 def _getAbsolutePath(self):
237 """
238 Property target used to get the absolute path.
239 """
240 return self._absolutePath
241
242 def _setCollectMode(self, value):
243 """
244 Property target used to set the collect mode.
245 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
246 Raises:
247 ValueError: If the value is not valid
248 """
249 if value is not None:
250 if value not in VALID_COLLECT_MODES:
251 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
252 self._collectMode = value
253
254 def _getCollectMode(self):
255 """
256 Property target used to get the collect mode.
257 """
258 return self._collectMode
259
260 def _setCompressMode(self, value):
261 """
262 Property target used to set the compress mode.
263 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
264 Raises:
265 ValueError: If the value is not valid
266 """
267 if value is not None:
268 if value not in VALID_COMPRESS_MODES:
269 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
270 self._compressMode = value
271
272 def _getCompressMode(self):
273 """
274 Property target used to get the compress mode.
275 """
276 return self._compressMode
277
278 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, doc="Absolute path to the mbox file.")
279 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this mbox file.")
280 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Overridden compress mode for this mbox file.")
281
282
283 ########################################################################
284 # MboxDir class definition
285 ########################################################################
286
287
288 @total_ordering
289 class MboxDir:
290 """
291 Class representing mbox directory configuration..
292
293 The following restrictions exist on data in this class:
294
295 - The absolute path must be absolute.
296 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
297 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
298
299 Unlike collect directory configuration, this is the only place exclusions
300 are allowed (no global exclusions at the <mbox> configuration level). Also,
301 we only allow relative exclusions and there is no configured ignore file.
302 This is because mbox directory backups are not recursive.
303
304 """
305
306 def __init__(self, absolutePath=None, collectMode=None, compressMode=None, relativeExcludePaths=None, excludePatterns=None):
307 """
308 Constructor for the ``MboxDir`` class.
309
310 You should never directly instantiate this class.
311
312 Args:
313 absolutePath: Absolute path to a mbox file on disk
314 collectMode: Overridden collect mode for this directory
315 compressMode: Overridden compression mode for this directory
316 relativeExcludePaths: List of relative paths to exclude
317 excludePatterns: List of regular expression patterns to exclude
318 """
319 self._absolutePath = None
320 self._collectMode = None
321 self._compressMode = None
322 self._relativeExcludePaths = None
323 self._excludePatterns = None
324 self.absolutePath = absolutePath
325 self.collectMode = collectMode
326 self.compressMode = compressMode
327 self.relativeExcludePaths = relativeExcludePaths
328 self.excludePatterns = excludePatterns
329
330 def __repr__(self):
331 """
332 Official string representation for class instance.
333 """
334 return "MboxDir(%s, %s, %s, %s, %s)" % (
335 self.absolutePath,
336 self.collectMode,
337 self.compressMode,
338 self.relativeExcludePaths,
339 self.excludePatterns,
340 )
341
342 def __str__(self):
343 """
344 Informal string representation for class instance.
345 """
346 return self.__repr__()
347
348 def __eq__(self, other):
349 """Equals operator, iplemented in terms of original Python 2 compare operator."""
350 return self.__cmp__(other) == 0
351
352 def __lt__(self, other):
353 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
354 return self.__cmp__(other) < 0
355
356 def __gt__(self, other):
357 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
358 return self.__cmp__(other) > 0
359
360 def __cmp__(self, other):
361 """
362 Original Python 2 comparison operator.
363 Args:
364 other: Other object to compare to
365 Returns:
366 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
367 """
368 if other is None:
369 return 1
370 if self.absolutePath != other.absolutePath:
371 if str(self.absolutePath or "") < str(other.absolutePath or ""):
372 return -1
373 else:
374 return 1
375 if self.collectMode != other.collectMode:
376 if str(self.collectMode or "") < str(other.collectMode or ""):
377 return -1
378 else:
379 return 1
380 if self.compressMode != other.compressMode:
381 if str(self.compressMode or "") < str(other.compressMode or ""):
382 return -1
383 else:
384 return 1
385 if self.relativeExcludePaths != other.relativeExcludePaths:
386 if self.relativeExcludePaths < other.relativeExcludePaths:
387 return -1
388 else:
389 return 1
390 if self.excludePatterns != other.excludePatterns:
391 if self.excludePatterns < other.excludePatterns:
392 return -1
393 else:
394 return 1
395 return 0
396
397 def _setAbsolutePath(self, value):
398 """
399 Property target used to set the absolute path.
400 The value must be an absolute path if it is not ``None``.
401 It does not have to exist on disk at the time of assignment.
402 Raises:
403 ValueError: If the value is not an absolute path
404 ValueError: If the value cannot be encoded properly
405 """
406 if value is not None:
407 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
408 raise ValueError("Absolute path must be, er, an absolute path.")
409 self._absolutePath = encodePath(value)
410
411 def _getAbsolutePath(self):
412 """
413 Property target used to get the absolute path.
414 """
415 return self._absolutePath
416
417 def _setCollectMode(self, value):
418 """
419 Property target used to set the collect mode.
420 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
421 Raises:
422 ValueError: If the value is not valid
423 """
424 if value is not None:
425 if value not in VALID_COLLECT_MODES:
426 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
427 self._collectMode = value
428
429 def _getCollectMode(self):
430 """
431 Property target used to get the collect mode.
432 """
433 return self._collectMode
434
435 def _setCompressMode(self, value):
436 """
437 Property target used to set the compress mode.
438 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
439 Raises:
440 ValueError: If the value is not valid
441 """
442 if value is not None:
443 if value not in VALID_COMPRESS_MODES:
444 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
445 self._compressMode = value
446
447 def _getCompressMode(self):
448 """
449 Property target used to get the compress mode.
450 """
451 return self._compressMode
452
453 def _setRelativeExcludePaths(self, value):
454 """
455 Property target used to set the relative exclude paths list.
456 Elements do not have to exist on disk at the time of assignment.
457 """
458 if value is None:
459 self._relativeExcludePaths = None
460 else:
461 try:
462 saved = self._relativeExcludePaths
463 self._relativeExcludePaths = UnorderedList()
464 self._relativeExcludePaths.extend(value)
465 except Exception as e:
466 self._relativeExcludePaths = saved
467 raise e
468
469 def _getRelativeExcludePaths(self):
470 """
471 Property target used to get the relative exclude paths list.
472 """
473 return self._relativeExcludePaths
474
475 def _setExcludePatterns(self, value):
476 """
477 Property target used to set the exclude patterns list.
478 """
479 if value is None:
480 self._excludePatterns = None
481 else:
482 try:
483 saved = self._excludePatterns
484 self._excludePatterns = RegexList()
485 self._excludePatterns.extend(value)
486 except Exception as e:
487 self._excludePatterns = saved
488 raise e
489
490 def _getExcludePatterns(self):
491 """
492 Property target used to get the exclude patterns list.
493 """
494 return self._excludePatterns
495
496 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, doc="Absolute path to the mbox directory.")
497 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this mbox directory.")
498 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Overridden compress mode for this mbox directory.")
499 relativeExcludePaths = property(_getRelativeExcludePaths, _setRelativeExcludePaths, None, "List of relative paths to exclude.")
500 excludePatterns = property(_getExcludePatterns, _setExcludePatterns, None, "List of regular expression patterns to exclude.")
501
502
503 ########################################################################
504 # MboxConfig class definition
505 ########################################################################
506
507
508 @total_ordering
509 class MboxConfig:
510 """
511 Class representing mbox configuration.
512
513 Mbox configuration is used for backing up mbox email files.
514
515 The following restrictions exist on data in this class:
516
517 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
518 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
519 - The ``mboxFiles`` list must be a list of ``MboxFile`` objects
520 - The ``mboxDirs`` list must be a list of ``MboxDir`` objects
521
522 For the ``mboxFiles`` and ``mboxDirs`` lists, validation is accomplished
523 through the :any:`util.ObjectTypeList` list implementation that overrides common
524 list methods and transparently ensures that each element is of the proper
525 type.
526
527 Unlike collect configuration, no global exclusions are allowed on this
528 level. We only allow relative exclusions at the mbox directory level.
529 Also, there is no configured ignore file. This is because mbox directory
530 backups are not recursive.
531
532 *Note:* Lists within this class are "unordered" for equality comparisons.
533
534 """
535
536 def __init__(self, collectMode=None, compressMode=None, mboxFiles=None, mboxDirs=None):
537 """
538 Constructor for the ``MboxConfig`` class.
539
540 Args:
541 collectMode: Default collect mode
542 compressMode: Default compress mode
543 mboxFiles: List of mbox files to back up
544 mboxDirs: List of mbox directories to back up
545
546 Raises:
547 ValueError: If one of the values is invalid
548 """
549 self._collectMode = None
550 self._compressMode = None
551 self._mboxFiles = None
552 self._mboxDirs = None
553 self.collectMode = collectMode
554 self.compressMode = compressMode
555 self.mboxFiles = mboxFiles
556 self.mboxDirs = mboxDirs
557
558 def __repr__(self):
559 """
560 Official string representation for class instance.
561 """
562 return "MboxConfig(%s, %s, %s, %s)" % (self.collectMode, self.compressMode, self.mboxFiles, self.mboxDirs)
563
564 def __str__(self):
565 """
566 Informal string representation for class instance.
567 """
568 return self.__repr__()
569
570 def __eq__(self, other):
571 """Equals operator, iplemented in terms of original Python 2 compare operator."""
572 return self.__cmp__(other) == 0
573
574 def __lt__(self, other):
575 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
576 return self.__cmp__(other) < 0
577
578 def __gt__(self, other):
579 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
580 return self.__cmp__(other) > 0
581
582 def __cmp__(self, other):
583 """
584 Original Python 2 comparison operator.
585 Lists within this class are "unordered" for equality comparisons.
586 Args:
587 other: Other object to compare to
588 Returns:
589 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
590 """
591 if other is None:
592 return 1
593 if self.collectMode != other.collectMode:
594 if str(self.collectMode or "") < str(other.collectMode or ""):
595 return -1
596 else:
597 return 1
598 if self.compressMode != other.compressMode:
599 if str(self.compressMode or "") < str(other.compressMode or ""):
600 return -1
601 else:
602 return 1
603 if self.mboxFiles != other.mboxFiles:
604 if self.mboxFiles < other.mboxFiles:
605 return -1
606 else:
607 return 1
608 if self.mboxDirs != other.mboxDirs:
609 if self.mboxDirs < other.mboxDirs:
610 return -1
611 else:
612 return 1
613 return 0
614
615 def _setCollectMode(self, value):
616 """
617 Property target used to set the collect mode.
618 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
619 Raises:
620 ValueError: If the value is not valid
621 """
622 if value is not None:
623 if value not in VALID_COLLECT_MODES:
624 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
625 self._collectMode = value
626
627 def _getCollectMode(self):
628 """
629 Property target used to get the collect mode.
630 """
631 return self._collectMode
632
633 def _setCompressMode(self, value):
634 """
635 Property target used to set the compress mode.
636 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
637 Raises:
638 ValueError: If the value is not valid
639 """
640 if value is not None:
641 if value not in VALID_COMPRESS_MODES:
642 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
643 self._compressMode = value
644
645 def _getCompressMode(self):
646 """
647 Property target used to get the compress mode.
648 """
649 return self._compressMode
650
651 def _setMboxFiles(self, value):
652 """
653 Property target used to set the mboxFiles list.
654 Either the value must be ``None`` or each element must be an ``MboxFile``.
655 Raises:
656 ValueError: If the value is not an ``MboxFile``
657 """
658 if value is None:
659 self._mboxFiles = None
660 else:
661 try:
662 saved = self._mboxFiles
663 self._mboxFiles = ObjectTypeList(MboxFile, "MboxFile")
664 self._mboxFiles.extend(value)
665 except Exception as e:
666 self._mboxFiles = saved
667 raise e
668
669 def _getMboxFiles(self):
670 """
671 Property target used to get the mboxFiles list.
672 """
673 return self._mboxFiles
674
675 def _setMboxDirs(self, value):
676 """
677 Property target used to set the mboxDirs list.
678 Either the value must be ``None`` or each element must be an ``MboxDir``.
679 Raises:
680 ValueError: If the value is not an ``MboxDir``
681 """
682 if value is None:
683 self._mboxDirs = None
684 else:
685 try:
686 saved = self._mboxDirs
687 self._mboxDirs = ObjectTypeList(MboxDir, "MboxDir")
688 self._mboxDirs.extend(value)
689 except Exception as e:
690 self._mboxDirs = saved
691 raise e
692
693 def _getMboxDirs(self):
694 """
695 Property target used to get the mboxDirs list.
696 """
697 return self._mboxDirs
698
699 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Default collect mode.")
700 compressMode = property(_getCompressMode, _setCompressMode, None, doc="Default compress mode.")
701 mboxFiles = property(_getMboxFiles, _setMboxFiles, None, doc="List of mbox files to back up.")
702 mboxDirs = property(_getMboxDirs, _setMboxDirs, None, doc="List of mbox directories to back up.")
703
704
705 ########################################################################
706 # LocalConfig class definition
707 ########################################################################
708
709
710 @total_ordering
711 class LocalConfig:
712 """
713 Class representing this extension's configuration document.
714
715 This is not a general-purpose configuration object like the main Cedar
716 Backup configuration object. Instead, it just knows how to parse and emit
717 Mbox-specific configuration values. Third parties who need to read and
718 write configuration related to this extension should access it through the
719 constructor, ``validate`` and ``addConfig`` methods.
720
721 *Note:* Lists within this class are "unordered" for equality comparisons.
722
723 """
724
725 def __init__(self, xmlData=None, xmlPath=None, validate=True):
726 """
727 Initializes a configuration object.
728
729 If you initialize the object without passing either ``xmlData`` or
730 ``xmlPath`` then configuration will be empty and will be invalid until it
731 is filled in properly.
732
733 No reference to the original XML data or original path is saved off by
734 this class. Once the data has been parsed (successfully or not) this
735 original information is discarded.
736
737 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
738 method will be called (with its default arguments) against configuration
739 after successfully parsing any passed-in XML. Keep in mind that even if
740 ``validate`` is ``False``, it might not be possible to parse the passed-in
741 XML document if lower-level validations fail.
742
743 *Note:* It is strongly suggested that the ``validate`` option always be set
744 to ``True`` (the default) unless there is a specific need to read in
745 invalid configuration from disk.
746
747 Args:
748 xmlData (String data): XML data representing configuration
749 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
750 validate (Boolean true/false): Validate the document after parsing it
751 Raises:
752 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
753 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
754 ValueError: If the parsed configuration document is not valid
755 """
756 self._mbox = None
757 self.mbox = None
758 if xmlData is not None and xmlPath is not None:
759 raise ValueError("Use either xmlData or xmlPath, but not both.")
760 if xmlData is not None:
761 self._parseXmlData(xmlData)
762 if validate:
763 self.validate()
764 elif xmlPath is not None:
765 with open(xmlPath) as f:
766 xmlData = f.read()
767 self._parseXmlData(xmlData)
768 if validate:
769 self.validate()
770
771 def __repr__(self):
772 """
773 Official string representation for class instance.
774 """
775 return "LocalConfig(%s)" % (self.mbox)
776
777 def __str__(self):
778 """
779 Informal string representation for class instance.
780 """
781 return self.__repr__()
782
783 def __eq__(self, other):
784 """Equals operator, iplemented in terms of original Python 2 compare operator."""
785 return self.__cmp__(other) == 0
786
787 def __lt__(self, other):
788 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
789 return self.__cmp__(other) < 0
790
791 def __gt__(self, other):
792 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
793 return self.__cmp__(other) > 0
794
795 def __cmp__(self, other):
796 """
797 Original Python 2 comparison operator.
798 Lists within this class are "unordered" for equality comparisons.
799 Args:
800 other: Other object to compare to
801 Returns:
802 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
803 """
804 if other is None:
805 return 1
806 if self.mbox != other.mbox:
807 if self.mbox < other.mbox:
808 return -1
809 else:
810 return 1
811 return 0
812
813 def _setMbox(self, value):
814 """
815 Property target used to set the mbox configuration value.
816 If not ``None``, the value must be a ``MboxConfig`` object.
817 Raises:
818 ValueError: If the value is not a ``MboxConfig``
819 """
820 if value is None:
821 self._mbox = None
822 else:
823 if not isinstance(value, MboxConfig):
824 raise ValueError("Value must be a ``MboxConfig`` object.")
825 self._mbox = value
826
827 def _getMbox(self):
828 """
829 Property target used to get the mbox configuration value.
830 """
831 return self._mbox
832
833 mbox = property(_getMbox, _setMbox, None, "Mbox configuration in terms of a ``MboxConfig`` object.")
834
835 def validate(self):
836 """
837 Validates configuration represented by the object.
838
839 Mbox configuration must be filled in. Within that, the collect mode and
840 compress mode are both optional, but the list of repositories must
841 contain at least one entry.
842
843 Each configured file or directory must contain an absolute path, and then
844 must be either able to take collect mode and compress mode configuration
845 from the parent ``MboxConfig`` object, or must set each value on its own.
846
847 Raises:
848 ValueError: If one of the validations fails
849 """
850 if self.mbox is None:
851 raise ValueError("Mbox section is required.")
852 if (self.mbox.mboxFiles is None or len(self.mbox.mboxFiles) < 1) and (
853 self.mbox.mboxDirs is None or len(self.mbox.mboxDirs) < 1
854 ):
855 raise ValueError("At least one mbox file or directory must be configured.")
856 if self.mbox.mboxFiles is not None:
857 for mboxFile in self.mbox.mboxFiles:
858 if mboxFile.absolutePath is None:
859 raise ValueError("Each mbox file must set an absolute path.")
860 if self.mbox.collectMode is None and mboxFile.collectMode is None:
861 raise ValueError("Collect mode must either be set in parent mbox section or individual mbox file.")
862 if self.mbox.compressMode is None and mboxFile.compressMode is None:
863 raise ValueError("Compress mode must either be set in parent mbox section or individual mbox file.")
864 if self.mbox.mboxDirs is not None:
865 for mboxDir in self.mbox.mboxDirs:
866 if mboxDir.absolutePath is None:
867 raise ValueError("Each mbox directory must set an absolute path.")
868 if self.mbox.collectMode is None and mboxDir.collectMode is None:
869 raise ValueError("Collect mode must either be set in parent mbox section or individual mbox directory.")
870 if self.mbox.compressMode is None and mboxDir.compressMode is None:
871 raise ValueError("Compress mode must either be set in parent mbox section or individual mbox directory.")
872
873 def addConfig(self, xmlDom, parentNode):
874 """
875 Adds an <mbox> configuration section as the next child of a parent.
876
877 Third parties should use this function to write configuration related to
878 this extension.
879
880 We add the following fields to the document::
881
882 collectMode //cb_config/mbox/collectMode
883 compressMode //cb_config/mbox/compressMode
884
885 We also add groups of the following items, one list element per
886 item::
887
888 mboxFiles //cb_config/mbox/file
889 mboxDirs //cb_config/mbox/dir
890
891 The mbox files and mbox directories are added by ``_addMboxFile`` and
892 ``_addMboxDir``.
893
894 Args:
895 xmlDom: DOM tree as from ``impl.createDocument()``
896 parentNode: Parent that the section should be appended to
897 """
898 if self.mbox is not None:
899 sectionNode = addContainerNode(xmlDom, parentNode, "mbox")
900 addStringNode(xmlDom, sectionNode, "collect_mode", self.mbox.collectMode)
901 addStringNode(xmlDom, sectionNode, "compress_mode", self.mbox.compressMode)
902 if self.mbox.mboxFiles is not None:
903 for mboxFile in self.mbox.mboxFiles:
904 LocalConfig._addMboxFile(xmlDom, sectionNode, mboxFile)
905 if self.mbox.mboxDirs is not None:
906 for mboxDir in self.mbox.mboxDirs:
907 LocalConfig._addMboxDir(xmlDom, sectionNode, mboxDir)
908
909 def _parseXmlData(self, xmlData):
910 """
911 Internal method to parse an XML string into the object.
912
913 This method parses the XML document into a DOM tree (``xmlDom``) and then
914 calls a static method to parse the mbox configuration section.
915
916 Args:
917 xmlData (String data): XML data to be parsed
918 Raises:
919 ValueError: If the XML cannot be successfully parsed
920 """
921 (_, parentNode) = createInputDom(xmlData)
922 self._mbox = LocalConfig._parseMbox(parentNode)
923
924 @staticmethod
925 def _parseMbox(parent):
926 """
927 Parses an mbox configuration section.
928
929 We read the following individual fields::
930
931 collectMode //cb_config/mbox/collect_mode
932 compressMode //cb_config/mbox/compress_mode
933
934 We also read groups of the following item, one list element per
935 item::
936
937 mboxFiles //cb_config/mbox/file
938 mboxDirs //cb_config/mbox/dir
939
940 The mbox files are parsed by :any:`_parseMboxFiles` and the mbox
941 directories are parsed by :any:`_parseMboxDirs`.
942
943 Args:
944 parent: Parent node to search beneath
945
946 Returns:
947 ``MboxConfig`` object or ``None`` if the section does not exist
948 Raises:
949 ValueError: If some filled-in value is invalid
950 """
951 mbox = None
952 section = readFirstChild(parent, "mbox")
953 if section is not None:
954 mbox = MboxConfig()
955 mbox.collectMode = readString(section, "collect_mode")
956 mbox.compressMode = readString(section, "compress_mode")
957 mbox.mboxFiles = LocalConfig._parseMboxFiles(section)
958 mbox.mboxDirs = LocalConfig._parseMboxDirs(section)
959 return mbox
960
961 @staticmethod
962 def _parseMboxFiles(parent):
963 """
964 Reads a list of ``MboxFile`` objects from immediately beneath the parent.
965
966 We read the following individual fields::
967
968 absolutePath abs_path
969 collectMode collect_mode
970 compressMode compess_mode
971
972 Args:
973 parent: Parent node to search beneath
974
975 Returns:
976 List of ``MboxFile`` objects or ``None`` if none are found
977 Raises:
978 ValueError: If some filled-in value is invalid
979 """
980 lst = []
981 for entry in readChildren(parent, "file"):
982 if isElement(entry):
983 mboxFile = MboxFile()
984 mboxFile.absolutePath = readString(entry, "abs_path")
985 mboxFile.collectMode = readString(entry, "collect_mode")
986 mboxFile.compressMode = readString(entry, "compress_mode")
987 lst.append(mboxFile)
988 if not lst:
989 lst = None
990 return lst
991
992 @staticmethod
993 def _parseMboxDirs(parent):
994 """
995 Reads a list of ``MboxDir`` objects from immediately beneath the parent.
996
997 We read the following individual fields::
998
999 absolutePath abs_path
1000 collectMode collect_mode
1001 compressMode compess_mode
1002
1003 We also read groups of the following items, one list element per
1004 item::
1005
1006 relativeExcludePaths exclude/rel_path
1007 excludePatterns exclude/pattern
1008
1009 The exclusions are parsed by :any:`_parseExclusions`.
1010
1011 Args:
1012 parent: Parent node to search beneath
1013
1014 Returns:
1015 List of ``MboxDir`` objects or ``None`` if none are found
1016 Raises:
1017 ValueError: If some filled-in value is invalid
1018 """
1019 lst = []
1020 for entry in readChildren(parent, "dir"):
1021 if isElement(entry):
1022 mboxDir = MboxDir()
1023 mboxDir.absolutePath = readString(entry, "abs_path")
1024 mboxDir.collectMode = readString(entry, "collect_mode")
1025 mboxDir.compressMode = readString(entry, "compress_mode")
1026 (mboxDir.relativeExcludePaths, mboxDir.excludePatterns) = LocalConfig._parseExclusions(entry)
1027 lst.append(mboxDir)
1028 if not lst:
1029 lst = None
1030 return lst
1031
1032 @staticmethod
1033 def _parseExclusions(parentNode):
1034 """
1035 Reads exclusions data from immediately beneath the parent.
1036
1037 We read groups of the following items, one list element per item::
1038
1039 relative exclude/rel_path
1040 patterns exclude/pattern
1041
1042 If there are none of some pattern (i.e. no relative path items) then
1043 ``None`` will be returned for that item in the tuple.
1044
1045 Args:
1046 parentNode: Parent node to search beneath
1047
1048 Returns:
1049 Tuple of (relative, patterns) exclusions
1050 """
1051 section = readFirstChild(parentNode, "exclude")
1052 if section is None:
1053 return (None, None)
1054 else:
1055 relative = readStringList(section, "rel_path")
1056 patterns = readStringList(section, "pattern")
1057 return (relative, patterns)
1058
1059 @staticmethod
1060 def _addMboxFile(xmlDom, parentNode, mboxFile):
1061 """
1062 Adds an mbox file container as the next child of a parent.
1063
1064 We add the following fields to the document::
1065
1066 absolutePath file/abs_path
1067 collectMode file/collect_mode
1068 compressMode file/compress_mode
1069
1070 The <file> node itself is created as the next child of the parent node.
1071 This method only adds one mbox file node. The parent must loop for each
1072 mbox file in the ``MboxConfig`` object.
1073
1074 If ``mboxFile`` is ``None``, this method call will be a no-op.
1075
1076 Args:
1077 xmlDom: DOM tree as from ``impl.createDocument()``
1078 parentNode: Parent that the section should be appended to
1079 mboxFile: MboxFile to be added to the document
1080 """
1081 if mboxFile is not None:
1082 sectionNode = addContainerNode(xmlDom, parentNode, "file")
1083 addStringNode(xmlDom, sectionNode, "abs_path", mboxFile.absolutePath)
1084 addStringNode(xmlDom, sectionNode, "collect_mode", mboxFile.collectMode)
1085 addStringNode(xmlDom, sectionNode, "compress_mode", mboxFile.compressMode)
1086
1087 @staticmethod
1088 def _addMboxDir(xmlDom, parentNode, mboxDir):
1089 """
1090 Adds an mbox directory container as the next child of a parent.
1091
1092 We add the following fields to the document::
1093
1094 absolutePath dir/abs_path
1095 collectMode dir/collect_mode
1096 compressMode dir/compress_mode
1097
1098 We also add groups of the following items, one list element per item::
1099
1100 relativeExcludePaths dir/exclude/rel_path
1101 excludePatterns dir/exclude/pattern
1102
1103 The <dir> node itself is created as the next child of the parent node.
1104 This method only adds one mbox directory node. The parent must loop for
1105 each mbox directory in the ``MboxConfig`` object.
1106
1107 If ``mboxDir`` is ``None``, this method call will be a no-op.
1108
1109 Args:
1110 xmlDom: DOM tree as from ``impl.createDocument()``
1111 parentNode: Parent that the section should be appended to
1112 mboxDir: MboxDir to be added to the document
1113 """
1114 if mboxDir is not None:
1115 sectionNode = addContainerNode(xmlDom, parentNode, "dir")
1116 addStringNode(xmlDom, sectionNode, "abs_path", mboxDir.absolutePath)
1117 addStringNode(xmlDom, sectionNode, "collect_mode", mboxDir.collectMode)
1118 addStringNode(xmlDom, sectionNode, "compress_mode", mboxDir.compressMode)
1119 if (mboxDir.relativeExcludePaths is not None and mboxDir.relativeExcludePaths != []) or (
1120 mboxDir.excludePatterns is not None and mboxDir.excludePatterns != []
1121 ):
1122 excludeNode = addContainerNode(xmlDom, sectionNode, "exclude")
1123 if mboxDir.relativeExcludePaths is not None:
1124 for relativePath in mboxDir.relativeExcludePaths:
1125 addStringNode(xmlDom, excludeNode, "rel_path", relativePath)
1126 if mboxDir.excludePatterns is not None:
1127 for pattern in mboxDir.excludePatterns:
1128 addStringNode(xmlDom, excludeNode, "pattern", pattern)
1129
1130
1131 ########################################################################
1132 # Public functions
1133 ########################################################################
1134
1135 ###########################
1136 # executeAction() function
1137 ###########################
1138
1139
1140 def executeAction(configPath, options, config):
1141 """
1142 Executes the mbox backup action.
1143
1144 Args:
1145 configPath (String representing a path on disk): Path to configuration file on disk
1146 options (Options object): Program command-line options
1147 config (Config object): Program configuration
1148 Raises:
1149 ValueError: Under many generic error conditions
1150 IOError: If a backup could not be written for some reason
1151 """
1152 logger.debug("Executing mbox extended action.")
1153 newRevision = datetime.datetime.today() # mark here so all actions are after this date/time
1154 if config.options is None or config.collect is None:
1155 raise ValueError("Cedar Backup configuration is not properly filled in.")
1156 local = LocalConfig(xmlPath=configPath)
1157 todayIsStart = isStartOfWeek(config.options.startingDay)
1158 fullBackup = options.full or todayIsStart
1159 logger.debug("Full backup flag is [%s]", fullBackup)
1160 if local.mbox.mboxFiles is not None:
1161 for mboxFile in local.mbox.mboxFiles:
1162 logger.debug("Working with mbox file [%s]", mboxFile.absolutePath)
1163 collectMode = _getCollectMode(local, mboxFile)
1164 compressMode = _getCompressMode(local, mboxFile)
1165 lastRevision = _loadLastRevision(config, mboxFile, fullBackup, collectMode)
1166 if fullBackup or (collectMode in ["daily", "incr"]) or (collectMode == "weekly" and todayIsStart):
1167 logger.debug("Mbox file meets criteria to be backed up today.")
1168 _backupMboxFile(config, mboxFile.absolutePath, fullBackup, collectMode, compressMode, lastRevision, newRevision)
1169 else:
1170 logger.debug("Mbox file will not be backed up, per collect mode.")
1171 if collectMode == "incr":
1172 _writeNewRevision(config, mboxFile, newRevision)
1173 if local.mbox.mboxDirs is not None:
1174 for mboxDir in local.mbox.mboxDirs:
1175 logger.debug("Working with mbox directory [%s]", mboxDir.absolutePath)
1176 collectMode = _getCollectMode(local, mboxDir)
1177 compressMode = _getCompressMode(local, mboxDir)
1178 lastRevision = _loadLastRevision(config, mboxDir, fullBackup, collectMode)
1179 (excludePaths, excludePatterns) = _getExclusions(mboxDir)
1180 if fullBackup or (collectMode in ["daily", "incr"]) or (collectMode == "weekly" and todayIsStart):
1181 logger.debug("Mbox directory meets criteria to be backed up today.")
1182 _backupMboxDir(
1183 config,
1184 mboxDir.absolutePath,
1185 fullBackup,
1186 collectMode,
1187 compressMode,
1188 lastRevision,
1189 newRevision,
1190 excludePaths,
1191 excludePatterns,
1192 )
1193 else:
1194 logger.debug("Mbox directory will not be backed up, per collect mode.")
1195 if collectMode == "incr":
1196 _writeNewRevision(config, mboxDir, newRevision)
1197 logger.info("Executed the mbox extended action successfully.")
1198
1199
1200 def _getCollectMode(local, item):
1201 """
1202 Gets the collect mode that should be used for an mbox file or directory.
1203 Use file- or directory-specific value if possible, otherwise take from mbox section.
1204 Args:
1205 local: LocalConfig object
1206 item: Mbox file or directory
1207 Returns:
1208 Collect mode to use
1209 """
1210 if item.collectMode is None:
1211 collectMode = local.mbox.collectMode
1212 else:
1213 collectMode = item.collectMode
1214 logger.debug("Collect mode is [%s]", collectMode)
1215 return collectMode
1216
1217
1218 def _getCompressMode(local, item):
1219 """
1220 Gets the compress mode that should be used for an mbox file or directory.
1221 Use file- or directory-specific value if possible, otherwise take from mbox section.
1222 Args:
1223 local: LocalConfig object
1224 item: Mbox file or directory
1225 Returns:
1226 Compress mode to use
1227 """
1228 if item.compressMode is None:
1229 compressMode = local.mbox.compressMode
1230 else:
1231 compressMode = item.compressMode
1232 logger.debug("Compress mode is [%s]", compressMode)
1233 return compressMode
1234
1235
1236 def _getRevisionPath(config, item):
1237 """
1238 Gets the path to the revision file associated with a repository.
1239 Args:
1240 config: Cedar Backup configuration
1241 item: Mbox file or directory
1242 Returns:
1243 Absolute path to the revision file associated with the repository
1244 """
1245 normalized = buildNormalizedPath(item.absolutePath)
1246 filename = "%s.%s" % (normalized, REVISION_PATH_EXTENSION)
1247 revisionPath = pathJoin(config.options.workingDir, filename)
1248 logger.debug("Revision file path is [%s]", revisionPath)
1249 return revisionPath
1250
1251
1252 def _loadLastRevision(config, item, fullBackup, collectMode):
1253 """
1254 Loads the last revision date for this item from disk and returns it.
1255
1256 If this is a full backup, or if the revision file cannot be loaded for some
1257 reason, then ``None`` is returned. This indicates that there is no previous
1258 revision, so the entire mail file or directory should be backed up.
1259
1260 *Note:* We write the actual revision object to disk via pickle, so we don't
1261 deal with the datetime precision or format at all. Whatever's in the object
1262 is what we write.
1263
1264 Args:
1265 config: Cedar Backup configuration
1266 item: Mbox file or directory
1267 fullBackup: Indicates whether this is a full backup
1268 collectMode: Indicates the collect mode for this item
1269
1270 Returns:
1271 Revision date as a datetime.datetime object or ``None``
1272 """
1273 revisionPath = _getRevisionPath(config, item)
1274 if fullBackup:
1275 revisionDate = None
1276 logger.debug("Revision file ignored because this is a full backup.")
1277 elif collectMode in ["weekly", "daily"]:
1278 revisionDate = None
1279 logger.debug("No revision file based on collect mode [%s].", collectMode)
1280 else:
1281 logger.debug("Revision file will be used for non-full incremental backup.")
1282 if not os.path.isfile(revisionPath):
1283 revisionDate = None
1284 logger.debug("Revision file [%s] does not exist on disk.", revisionPath)
1285 else:
1286 try:
1287 with open(revisionPath, "rb") as f:
1288 revisionDate = pickle.load(f, fix_imports=True) # ruff: ignore[suspicious-pickle-usage] # this is trusted data, so pickle is ok
1289 logger.debug("Loaded revision file [%s] from disk: [%s]", revisionPath, revisionDate)
1290 except Exception as e:
1291 revisionDate = None
1292 logger.error("Failed loading revision file [%s] from disk: %s", revisionPath, e)
1293 return revisionDate
1294
1295
1296 def _writeNewRevision(config, item, newRevision):
1297 """
1298 Writes new revision information to disk.
1299
1300 If we can't write the revision file successfully for any reason, we'll log
1301 the condition but won't throw an exception.
1302
1303 *Note:* We write the actual revision object to disk via pickle, so we don't
1304 deal with the datetime precision or format at all. Whatever's in the object
1305 is what we write.
1306
1307 Args:
1308 config: Cedar Backup configuration
1309 item: Mbox file or directory
1310 newRevision: Revision date as a datetime.datetime object
1311 """
1312 revisionPath = _getRevisionPath(config, item)
1313 try:
1314 with open(revisionPath, "wb") as f:
1315 pickle.dump(newRevision, f, 0, fix_imports=True) # be compatible with Python 2
1316 changeOwnership(revisionPath, config.options.backupUser, config.options.backupGroup)
1317 logger.debug("Wrote new revision file [%s] to disk: [%s]", revisionPath, newRevision)
1318 except Exception as e:
1319 logger.error("Failed to write revision file [%s] to disk: %s", revisionPath, e)
1320
1321
1322 def _getExclusions(mboxDir):
1323 """
1324 Gets exclusions (file and patterns) associated with an mbox directory.
1325
1326 The returned files value is a list of absolute paths to be excluded from the
1327 backup for a given directory. It is derived from the mbox directory's
1328 relative exclude paths.
1329
1330 The returned patterns value is a list of patterns to be excluded from the
1331 backup for a given directory. It is derived from the mbox directory's list
1332 of patterns.
1333
1334 Args:
1335 mboxDir: Mbox directory object
1336
1337 Returns:
1338 Tuple (files, patterns) indicating what to exclude
1339 """
1340 paths = []
1341 if mboxDir.relativeExcludePaths is not None:
1342 for relativePath in mboxDir.relativeExcludePaths:
1343 paths.append(pathJoin(mboxDir.absolutePath, relativePath))
1344 patterns = []
1345 if mboxDir.excludePatterns is not None:
1346 patterns.extend(mboxDir.excludePatterns)
1347 logger.debug("Exclude paths: %s", paths)
1348 logger.debug("Exclude patterns: %s", patterns)
1349 return (paths, patterns)
1350
1351
1352 def _getBackupPath(config, mboxPath, compressMode, newRevision, targetDir=None):
1353 """
1354 Gets the backup file path (including correct extension) associated with an mbox path.
1355
1356 We assume that if the target directory is passed in, that we're backing up a
1357 directory. Under these circumstances, we'll just use the basename of the
1358 individual path as the output file.
1359
1360 *Note:* The backup path only contains the current date in YYYYMMDD format,
1361 but that's OK because the index information (stored elsewhere) is the actual
1362 date object.
1363
1364 Args:
1365 config: Cedar Backup configuration
1366 mboxPath: Path to the indicated mbox file or directory
1367 compressMode: Compress mode to use for this mbox path
1368 newRevision: Revision this backup path represents
1369 targetDir: Target directory in which the path should exist
1370
1371 Returns:
1372 Absolute path to the backup file associated with the repository
1373 """
1374 if targetDir is None:
1375 normalizedPath = buildNormalizedPath(mboxPath)
1376 revisionDate = newRevision.strftime("%Y%m%d")
1377 filename = "mbox-%s-%s" % (revisionDate, normalizedPath)
1378 else:
1379 filename = os.path.basename(mboxPath)
1380 if compressMode == "gzip":
1381 filename = "%s.gz" % filename
1382 elif compressMode == "bzip2":
1383 filename = "%s.bz2" % filename
1384 if targetDir is None:
1385 backupPath = pathJoin(config.collect.targetDir, filename)
1386 else:
1387 backupPath = pathJoin(targetDir, filename)
1388 logger.debug("Backup file path is [%s]", backupPath)
1389 return backupPath
1390
1391
1392 def _getTarfilePath(config, mboxPath, compressMode, newRevision):
1393 """
1394 Gets the tarfile backup file path (including correct extension) associated
1395 with an mbox path.
1396
1397 Along with the path, the tar archive mode is returned in a form that can
1398 be used with :any:`BackupFileList.generateTarfile`.
1399
1400 *Note:* The tarfile path only contains the current date in YYYYMMDD format,
1401 but that's OK because the index information (stored elsewhere) is the actual
1402 date object.
1403
1404 Args:
1405 config: Cedar Backup configuration
1406 mboxPath: Path to the indicated mbox file or directory
1407 compressMode: Compress mode to use for this mbox path
1408 newRevision: Revision this backup path represents
1409
1410 Returns:
1411 Tuple of (absolute path to tarfile, tar archive mode)
1412 """
1413 normalizedPath = buildNormalizedPath(mboxPath)
1414 revisionDate = newRevision.strftime("%Y%m%d")
1415 filename = "mbox-%s-%s.tar" % (revisionDate, normalizedPath)
1416 if compressMode == "gzip":
1417 filename = "%s.gz" % filename
1418 archiveMode = "targz"
1419 elif compressMode == "bzip2":
1420 filename = "%s.bz2" % filename
1421 archiveMode = "tarbz2"
1422 else:
1423 archiveMode = "tar"
1424 tarfilePath = pathJoin(config.collect.targetDir, filename)
1425 logger.debug("Tarfile path is [%s]", tarfilePath)
1426 return (tarfilePath, archiveMode)
1427
1428
1429 def _getOutputFile(backupPath, compressMode):
1430 """
1431 Opens the output file used for saving backup information.
1432
1433 If the compress mode is "gzip", we'll open a ``GzipFile``, and if the
1434 compress mode is "bzip2", we'll open a ``BZ2File``. Otherwise, we'll just
1435 return an object from the normal ``open()`` method.
1436
1437 Args:
1438 backupPath: Path to file to open
1439 compressMode: Compress mode of file ("none", "gzip", "bzip")
1440
1441 Returns:
1442 Output file object, opened in binary mode for use with executeCommand()
1443 """
1444 if compressMode == "gzip":
1445 return GzipFile(backupPath, "wb")
1446 elif compressMode == "bzip2":
1447 return BZ2File(backupPath, "wb")
1448 else:
1449 return open(backupPath, "wb")
1450
1451
1452 def _backupMboxFile(config, absolutePath, fullBackup, collectMode, compressMode, lastRevision, newRevision, targetDir=None):
1453 """
1454 Backs up an individual mbox file.
1455
1456 Args:
1457 config: Cedar Backup configuration
1458 absolutePath: Path to mbox file to back up
1459 fullBackup: Indicates whether this should be a full backup
1460 collectMode: Indicates the collect mode for this item
1461 compressMode: Compress mode of file ("none", "gzip", "bzip")
1462 lastRevision: Date of last backup as datetime.datetime
1463 newRevision: Date of new (current) backup as datetime.datetime
1464 targetDir: Target directory to write the backed-up file into
1465
1466 Raises:
1467 ValueError: If some value is missing or invalid
1468 IOError: If there is a problem backing up the mbox file
1469 """
1470 if fullBackup or collectMode != "incr" or lastRevision is None:
1471 args = ["-a", "-u", absolutePath] # remove duplicates but fetch entire mailbox
1472 else:
1473 revisionDate = lastRevision.strftime("%Y-%m-%dT%H:%M:%S") # ISO-8601 format; grepmail calls Date::Parse::str2time()
1474 args = ["-a", "-u", "-d", "since %s" % revisionDate, absolutePath]
1475 command = resolveCommand(GREPMAIL_COMMAND)
1476 backupPath = _getBackupPath(config, absolutePath, compressMode, newRevision, targetDir=targetDir)
1477 with _getOutputFile(backupPath, compressMode) as outputFile:
1478 result = executeCommand(command, args, returnOutput=False, ignoreStderr=True, doNotLog=True, outputFile=outputFile)[0]
1479 if result != 0:
1480 raise OSError("Error [%d] executing grepmail on [%s]." % (result, absolutePath))
1481 logger.debug("Completed backing up mailbox [%s].", absolutePath)
1482 return backupPath
1483
1484
1485 def _backupMboxDir(
1486 config, absolutePath, fullBackup, collectMode, compressMode, lastRevision, newRevision, excludePaths, excludePatterns
1487 ):
1488 """
1489 Backs up a directory containing mbox files.
1490
1491 Args:
1492 config: Cedar Backup configuration
1493 absolutePath: Path to mbox directory to back up
1494 fullBackup: Indicates whether this should be a full backup
1495 collectMode: Indicates the collect mode for this item
1496 compressMode: Compress mode of file ("none", "gzip", "bzip")
1497 lastRevision: Date of last backup as datetime.datetime
1498 newRevision: Date of new (current) backup as datetime.datetime
1499 excludePaths: List of absolute paths to exclude
1500 excludePatterns: List of patterns to exclude
1501
1502 Raises:
1503 ValueError: If some value is missing or invalid
1504 IOError: If there is a problem backing up the mbox file
1505 """
1506 try:
1507 tmpdir = tempfile.mkdtemp(dir=config.options.workingDir)
1508 mboxList = FilesystemList()
1509 mboxList.excludeDirs = True
1510 mboxList.excludePaths = excludePaths
1511 mboxList.excludePatterns = excludePatterns
1512 mboxList.addDirContents(absolutePath, recursive=False)
1513 tarList = BackupFileList()
1514 for item in mboxList:
1515 backupPath = _backupMboxFile(
1516 config,
1517 item,
1518 fullBackup,
1519 collectMode,
1520 "none", # no need to compress inside compressed tar
1521 lastRevision,
1522 newRevision,
1523 targetDir=tmpdir,
1524 )
1525 tarList.addFile(backupPath)
1526 (tarfilePath, archiveMode) = _getTarfilePath(config, absolutePath, compressMode, newRevision)
1527 tarList.generateTarfile(tarfilePath, archiveMode, ignore=True, flat=True)
1528 changeOwnership(tarfilePath, config.options.backupUser, config.options.backupGroup)
1529 logger.debug("Completed backing up directory [%s].", absolutePath)
1530 finally:
1531 try:
1532 for cleanitem in tarList:
1533 if os.path.exists(cleanitem):
1534 try:
1535 os.remove(cleanitem)
1536 except:
1537 pass
1538 except:
1539 pass
1540 try:
1541 os.rmdir(tmpdir)
1542 except:
1543 pass