Debian Codegraph @

src/CedarBackup3/config.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) 2004-2008,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Cedar Backup, release 3
29 # Purpose : Provides configuration-related objects.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides configuration-related objects.
39
40 Summary
41 =======
42
43 Cedar Backup stores all of its configuration in an XML document typically
44 called ``cback3.conf``. The standard location for this document is in
45 ``/etc``, but users can specify a different location if they want to.
46
47 The ``Config`` class is a Python object representation of a Cedar Backup XML
48 configuration file. The representation is two-way: XML data can be used to
49 create a ``Config`` object, and then changes to the object can be propogated
50 back to disk. A ``Config`` object can even be used to create a configuration
51 file from scratch programmatically.
52
53 The ``Config`` class is intended to be the only Python-language interface to
54 Cedar Backup configuration on disk. Cedar Backup will use the class as its
55 internal representation of configuration, and applications external to Cedar
56 Backup itself (such as a hypothetical third-party configuration tool written
57 in Python or a third party extension module) should also use the class when
58 they need to read and write configuration files.
59
60 Backwards Compatibility
61 =======================
62
63 The configuration file format has changed between Cedar Backup 1.x and Cedar
64 Backup 2.x. Any Cedar Backup 1.x configuration file is also a valid Cedar
65 Backup 2.x configuration file. However, it doesn't work to go the other
66 direction, as the 2.x configuration files contains additional configuration
67 is not accepted by older versions of the software.
68
69 XML Configuration Structure
70 ===========================
71
72 A ``Config`` object can either be created "empty", or can be created based on
73 XML input (either in the form of a string or read in from a file on disk).
74 Generally speaking, the XML input *must* result in a ``Config`` object which
75 passes the validations laid out below in the *Validation* section.
76
77 An XML configuration file is composed of seven sections:
78
79 - *reference*: specifies reference information about the file (author, revision, etc)
80 - *extensions*: specifies mappings to Cedar Backup extensions (external code)
81 - *options*: specifies global configuration options
82 - *peers*: specifies the set of peers in a master's backup pool
83 - *collect*: specifies configuration related to the collect action
84 - *stage*: specifies configuration related to the stage action
85 - *store*: specifies configuration related to the store action
86 - *purge*: specifies configuration related to the purge action
87
88 Each section is represented by an class in this module, and then the overall
89 ``Config`` class is a composition of the various other classes.
90
91 Any configuration section that is missing in the XML document (or has not
92 been filled into an "empty" document) will just be set to ``None`` in the
93 object representation. The same goes for individual fields within each
94 configuration section. Keep in mind that the document might not be
95 completely valid if some sections or fields aren't filled in - but that
96 won't matter until validation takes place (see the *Validation* section
97 below).
98
99 Unicode vs. String Data
100 =======================
101
102 By default, all string data that comes out of XML documents in Python is
103 unicode data (i.e. ``u"whatever"``). This is fine for many things, but when
104 it comes to filesystem paths, it can cause us some problems. We really want
105 strings to be encoded in the filesystem encoding rather than being unicode.
106 So, most elements in configuration which represent filesystem paths are
107 coverted to plain strings using :any:`util.encodePath`. The main exception is
108 the various ``absoluteExcludePath`` and ``relativeExcludePath`` lists. These
109 are *not* converted, because they are generally only used for filtering,
110 not for filesystem operations.
111
112 Validation
113 ==========
114
115 There are two main levels of validation in the ``Config`` class and its
116 children. The first is field-level validation. Field-level validation
117 comes into play when a given field in an object is assigned to or updated.
118 We use Python's ``property`` functionality to enforce specific validations on
119 field values, and in some places we even use customized list classes to
120 enforce validations on list members. You should expect to catch a
121 ``ValueError`` exception when making assignments to configuration class
122 fields.
123
124 The second level of validation is post-completion validation. Certain
125 validations don't make sense until a document is fully "complete". We don't
126 want these validations to apply all of the time, because it would make
127 building up a document from scratch a real pain. For instance, we might
128 have to do things in the right order to keep from throwing exceptions, etc.
129
130 All of these post-completion validations are encapsulated in the
131 :any:`Config.validate` method. This method can be called at any time by a
132 client, and will always be called immediately after creating a ``Config``
133 object from XML data and before exporting a ``Config`` object to XML. This
134 way, we get decent ease-of-use but we also don't accept or emit invalid
135 configuration files.
136
137 The :any:`Config.validate` implementation actually takes two passes to
138 completely validate a configuration document. The first pass at validation
139 is to ensure that the proper sections are filled into the document. There
140 are default requirements, but the caller has the opportunity to override
141 these defaults.
142
143 The second pass at validation ensures that any filled-in section contains
144 valid data. Any section which is not set to ``None`` is validated according
145 to the rules for that section (see below).
146
147 *Reference Validations*
148
149 No validations.
150
151 *Extensions Validations*
152
153 The list of actions may be either ``None`` or an empty list ``[]`` if desired.
154 Each extended action must include a name, a module and a function. Then, an
155 extended action must include either an index or dependency information.
156 Which one is required depends on which order mode is configured.
157
158 *Options Validations*
159
160 All fields must be filled in except the rsh command. The rcp and rsh
161 commands are used as default values for all remote peers. Remote peers can
162 also rely on the backup user as the default remote user name if they choose.
163
164 *Peers Validations*
165
166 Local peers must be completely filled in, including both name and collect
167 directory. Remote peers must also fill in the name and collect directory,
168 but can leave the remote user and rcp command unset. In this case, the
169 remote user is assumed to match the backup user from the options section and
170 rcp command is taken directly from the options section.
171
172 *Collect Validations*
173
174 The target directory must be filled in. The collect mode, archive mode and
175 ignore file are all optional. The list of absolute paths to exclude and
176 patterns to exclude may be either ``None`` or an empty list ``[]`` if desired.
177
178 Each collect directory entry must contain an absolute path to collect, and
179 then must either be able to take collect mode, archive mode and ignore file
180 configuration from the parent ``CollectConfig`` object, or must set each
181 value on its own. The list of absolute paths to exclude, relative paths to
182 exclude and patterns to exclude may be either ``None`` or an empty list ``[]``
183 if desired. Any list of absolute paths to exclude or patterns to exclude
184 will be combined with the same list in the ``CollectConfig`` object to make
185 the complete list for a given directory.
186
187 *Stage Validations*
188
189 The target directory must be filled in. There must be at least one peer
190 (remote or local) between the two lists of peers. A list with no entries
191 can be either ``None`` or an empty list ``[]`` if desired.
192
193 If a set of peers is provided, this configuration completely overrides
194 configuration in the peers configuration section, and the same validations
195 apply.
196
197 *Store Validations*
198
199 The device type and drive speed are optional, and all other values are
200 required (missing booleans will be set to defaults, which is OK).
201
202 The image writer functionality in the ``writer`` module is supposed to be
203 able to handle a device speed of ``None``. Any caller which needs a "real"
204 (non-``None``) value for the device type can use ``DEFAULT_DEVICE_TYPE``,
205 which is guaranteed to be sensible.
206
207 *Purge Validations*
208
209 The list of purge directories may be either ``None`` or an empty list ``[]``
210 if desired. All purge directories must contain a path and a retain days
211 value.
212
213 Module Attributes
214 =================
215
216 Attributes:
217 DEFAULT_DEVICE_TYPE: The default device type
218 DEFAULT_MEDIA_TYPE: The default media type
219 VALID_DEVICE_TYPES: List of valid device types
220 VALID_MEDIA_TYPES: List of valid media types
221 VALID_COLLECT_MODES: List of valid collect modes
222 VALID_COMPRESS_MODES: List of valid compress modes
223 VALID_ARCHIVE_MODES: List of valid archive modes
224 VALID_ORDER_MODES: List of valid extension order modes
225
226 :author: Kenneth J. Pronovici <[email protected]>
227 """
228
229 ########################################################################
230 # Imported modules
231 ########################################################################
232
233 import logging
234 import os
235 import posixpath
236 import re
237 from functools import total_ordering
238
239 from CedarBackup3.util import (
240 UNIT_BYTES,
241 UNIT_GBYTES,
242 UNIT_KBYTES,
243 UNIT_MBYTES,
244 AbsolutePathList,
245 ObjectTypeList,
246 RegexList,
247 RegexMatchList,
248 UnorderedList,
249 checkUnique,
250 convertSize,
251 displayBytes,
252 encodePath,
253 parseCommaSeparatedString,
254 )
255 from CedarBackup3.writers.util import validateDriveSpeed, validateScsiId
256 from CedarBackup3.xmlutil import (
257 addBooleanNode,
258 addContainerNode,
259 addIntegerNode,
260 addStringNode,
261 createInputDom,
262 createOutputDom,
263 isElement,
264 readBoolean,
265 readChildren,
266 readFirstChild,
267 readInteger,
268 readString,
269 readStringList,
270 serializeDom,
271 )
272
273 ########################################################################
274 # Module-wide constants and variables
275 ########################################################################
276
277 logger = logging.getLogger("CedarBackup3.log.config")
278
279 DEFAULT_DEVICE_TYPE = "cdwriter"
280 DEFAULT_MEDIA_TYPE = "cdrw-74"
281
282 VALID_DEVICE_TYPES = ["cdwriter", "dvdwriter"]
283 VALID_CD_MEDIA_TYPES = ["cdr-74", "cdrw-74", "cdr-80", "cdrw-80"]
284 VALID_DVD_MEDIA_TYPES = ["dvd+r", "dvd+rw"]
285 VALID_MEDIA_TYPES = VALID_CD_MEDIA_TYPES + VALID_DVD_MEDIA_TYPES
286 VALID_COLLECT_MODES = ["daily", "weekly", "incr"]
287 VALID_ARCHIVE_MODES = ["tar", "targz", "tarbz2"]
288 VALID_COMPRESS_MODES = ["none", "gzip", "bzip2"]
289 VALID_ORDER_MODES = ["index", "dependency"]
290 VALID_BLANK_MODES = ["daily", "weekly"]
291 VALID_BYTE_UNITS = [UNIT_BYTES, UNIT_KBYTES, UNIT_MBYTES, UNIT_GBYTES]
292 VALID_FAILURE_MODES = ["none", "all", "daily", "weekly"]
293
294 REWRITABLE_MEDIA_TYPES = ["cdrw-74", "cdrw-80", "dvd+rw"]
295
296 ACTION_NAME_REGEX = r"^[a-z0-9]*$"
297
298
299 ########################################################################
300 # ByteQuantity class definition
301 ########################################################################
302
303
304 @total_ordering
305 class ByteQuantity:
306 """
307 Class representing a byte quantity.
308
309 A byte quantity has both a quantity and a byte-related unit. Units are
310 maintained using the constants from util.py. If no units are provided,
311 ``UNIT_BYTES`` is assumed.
312
313 The quantity is maintained internally as a string so that issues of
314 precision can be avoided. It really isn't possible to store a floating
315 point number here while being able to losslessly translate back and forth
316 between XML and object representations. (Perhaps the Python 2.4 Decimal
317 class would have been an option, but I originally wanted to stay compatible
318 with Python 2.3.)
319
320 Even though the quantity is maintained as a string, the string must be in a
321 valid floating point positive number. Technically, any floating point
322 string format supported by Python is allowble. However, it does not make
323 sense to have a negative quantity of bytes in this context.
324
325 """
326
327 def __init__(self, quantity=None, units=None):
328 """
329 Constructor for the ``ByteQuantity`` class.
330
331 Args:
332 quantity: Quantity of bytes, something interpretable as a float
333 units: Unit of bytes, one of VALID_BYTE_UNITS
334
335 Raises:
336 ValueError: If one of the values is invalid
337 """
338 self._quantity = None
339 self._units = None
340 self.quantity = quantity
341 self.units = units
342
343 def __repr__(self):
344 """
345 Official string representation for class instance.
346 """
347 return "ByteQuantity(%s, %s)" % (self.quantity, self.units)
348
349 def __str__(self):
350 """
351 Informal string representation for class instance.
352 """
353 return "%s" % displayBytes(self.bytes)
354
355 def __eq__(self, other):
356 """Equals operator, implemented in terms of Python 2-style compare operator."""
357 return self.__cmp__(other) == 0
358
359 def __lt__(self, other):
360 """Less-than operator, implemented in terms of Python 2-style compare operator."""
361 return self.__cmp__(other) < 0
362
363 def __gt__(self, other):
364 """Greater-than operator, implemented in terms of Python 2-style compare operator."""
365 return self.__cmp__(other) > 0
366
367 def __cmp__(self, other):
368 """
369 Python 2-style comparison operator.
370 Args:
371 other: Other object to compare to
372 Returns:
373 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
374 """
375 if other is None:
376 return 1
377 elif isinstance(other, ByteQuantity):
378 if self.bytes != other.bytes:
379 if self.bytes < other.bytes:
380 return -1
381 else:
382 return 1
383 return 0
384 else:
385 return self.__cmp__(ByteQuantity(other, UNIT_BYTES)) # will fail if other can't be coverted to float
386
387 def _setQuantity(self, value):
388 """
389 Property target used to set the quantity
390 The value must be interpretable as a float if it is not None
391 Raises:
392 ValueError: If the value is an empty string
393 ValueError: If the value is not a valid floating point number
394 ValueError: If the value is less than zero
395 """
396 if value is None:
397 self._quantity = None
398 else:
399 try:
400 floatValue = float(value) # allow integer, float, string, etc.
401 except:
402 raise ValueError("Quantity must be interpretable as a float")
403 if floatValue < 0.0:
404 raise ValueError("Quantity cannot be negative.")
405 self._quantity = str(value) # keep around string
406
407 def _getQuantity(self):
408 """
409 Property target used to get the quantity.
410 """
411 return self._quantity
412
413 def _setUnits(self, value):
414 """
415 Property target used to set the units value.
416 If not ``None``, the units value must be one of the values in :any:`VALID_BYTE_UNITS`.
417 Raises:
418 ValueError: If the value is not valid
419 """
420 if value is None:
421 self._units = UNIT_BYTES
422 else:
423 if value not in VALID_BYTE_UNITS:
424 raise ValueError("Units value must be one of %s." % VALID_BYTE_UNITS)
425 self._units = value
426
427 def _getUnits(self):
428 """
429 Property target used to get the units value.
430 """
431 return self._units
432
433 def _getBytes(self):
434 """
435 Property target used to return the byte quantity as a floating point number.
436 If there is no quantity set, then a value of 0.0 is returned.
437 """
438 if self.quantity is not None and self.units is not None:
439 return convertSize(self.quantity, self.units, UNIT_BYTES)
440 return 0.0
441
442 quantity = property(_getQuantity, _setQuantity, None, doc="Byte quantity, as a string")
443 units = property(_getUnits, _setUnits, None, doc="Units for byte quantity, for instance UNIT_BYTES")
444 bytes = property(_getBytes, None, None, doc="Byte quantity, as a floating point number.")
445
446
447 ########################################################################
448 # ActionDependencies class definition
449 ########################################################################
450
451
452 @total_ordering
453 class ActionDependencies:
454 """
455 Class representing dependencies associated with an extended action.
456
457 Execution ordering for extended actions is done in one of two ways: either by using
458 index values (lower index gets run first) or by having the extended action specify
459 dependencies in terms of other named actions. This class encapsulates the dependency
460 information for an extended action.
461
462 The following restrictions exist on data in this class:
463
464 - Any action name must be a non-empty string matching ``ACTION_NAME_REGEX``
465
466 """
467
468 def __init__(self, beforeList=None, afterList=None):
469 """
470 Constructor for the ``ActionDependencies`` class.
471
472 Args:
473 beforeList: List of named actions that this action must be run before
474 afterList: List of named actions that this action must be run after
475
476 Raises:
477 ValueError: If one of the values is invalid
478 """
479 self._beforeList = None
480 self._afterList = None
481 self.beforeList = beforeList
482 self.afterList = afterList
483
484 def __repr__(self):
485 """
486 Official string representation for class instance.
487 """
488 return "ActionDependencies(%s, %s)" % (self.beforeList, self.afterList)
489
490 def __str__(self):
491 """
492 Informal string representation for class instance.
493 """
494 return self.__repr__()
495
496 def __eq__(self, other):
497 """Equals operator, implemented in terms of original Python 2 compare operator."""
498 return self.__cmp__(other) == 0
499
500 def __lt__(self, other):
501 """Less-than operator, implemented in terms of original Python 2 compare operator."""
502 return self.__cmp__(other) < 0
503
504 def __gt__(self, other):
505 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
506 return self.__cmp__(other) > 0
507
508 def __cmp__(self, other):
509 """
510 Original Python 2 comparison operator.
511 Args:
512 other: Other object to compare to
513 Returns:
514 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
515 """
516 if other is None:
517 return 1
518 if self.beforeList != other.beforeList:
519 if self.beforeList < other.beforeList:
520 return -1
521 else:
522 return 1
523 if self.afterList != other.afterList:
524 if self.afterList < other.afterList:
525 return -1
526 else:
527 return 1
528 return 0
529
530 def _setBeforeList(self, value):
531 """
532 Property target used to set the "run before" list.
533 Either the value must be ``None`` or each element must be a string matching ACTION_NAME_REGEX.
534 Raises:
535 ValueError: If the value does not match the regular expression
536 """
537 if value is None:
538 self._beforeList = None
539 else:
540 try:
541 saved = self._beforeList
542 self._beforeList = RegexMatchList(ACTION_NAME_REGEX, emptyAllowed=False, prefix="Action name")
543 self._beforeList.extend(value)
544 except Exception as e:
545 self._beforeList = saved
546 raise e
547
548 def _getBeforeList(self):
549 """
550 Property target used to get the "run before" list.
551 """
552 return self._beforeList
553
554 def _setAfterList(self, value):
555 """
556 Property target used to set the "run after" list.
557 Either the value must be ``None`` or each element must be a string matching ACTION_NAME_REGEX.
558 Raises:
559 ValueError: If the value does not match the regular expression
560 """
561 if value is None:
562 self._afterList = None
563 else:
564 try:
565 saved = self._afterList
566 self._afterList = RegexMatchList(ACTION_NAME_REGEX, emptyAllowed=False, prefix="Action name")
567 self._afterList.extend(value)
568 except Exception as e:
569 self._afterList = saved
570 raise e
571
572 def _getAfterList(self):
573 """
574 Property target used to get the "run after" list.
575 """
576 return self._afterList
577
578 beforeList = property(_getBeforeList, _setBeforeList, None, "List of named actions that this action must be run before.")
579 afterList = property(_getAfterList, _setAfterList, None, "List of named actions that this action must be run after.")
580
581
582 ########################################################################
583 # ActionHook class definition
584 ########################################################################
585
586
587 @total_ordering
588 class ActionHook:
589 """
590 Class representing a hook associated with an action.
591
592 A hook associated with an action is a shell command to be executed either
593 before or after a named action is executed.
594
595 The following restrictions exist on data in this class:
596
597 - The action name must be a non-empty string matching ``ACTION_NAME_REGEX``
598 - The shell command must be a non-empty string.
599
600 The internal ``before`` and ``after`` instance variables are always set to
601 False in this parent class.
602
603 """
604
605 def __init__(self, action=None, command=None):
606 """
607 Constructor for the ``ActionHook`` class.
608
609 Args:
610 action: Action this hook is associated with
611 command: Shell command to execute
612
613 Raises:
614 ValueError: If one of the values is invalid
615 """
616 self._action = None
617 self._command = None
618 self._before = False
619 self._after = False
620 self.action = action
621 self.command = command
622
623 def __repr__(self):
624 """
625 Official string representation for class instance.
626 """
627 return "ActionHook(%s, %s, %s, %s)" % (self.action, self.command, self.before, self.after)
628
629 def __str__(self):
630 """
631 Informal string representation for class instance.
632 """
633 return self.__repr__()
634
635 def __eq__(self, other):
636 """Equals operator, implemented in terms of original Python 2 compare operator."""
637 return self.__cmp__(other) == 0
638
639 def __lt__(self, other):
640 """Less-than operator, implemented in terms of original Python 2 compare operator."""
641 return self.__cmp__(other) < 0
642
643 def __gt__(self, other):
644 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
645 return self.__cmp__(other) > 0
646
647 def __cmp__(self, other):
648 """
649 Original Python 2 comparison operator.
650 Args:
651 other: Other object to compare to
652 Returns:
653 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
654 """
655 if other is None:
656 return 1
657 if self.action != other.action:
658 if str(self.action or "") < str(other.action or ""):
659 return -1
660 else:
661 return 1
662 if self.command != other.command:
663 if str(self.command or "") < str(other.command or ""):
664 return -1
665 else:
666 return 1
667 if self.before != other.before:
668 if self.before < other.before:
669 return -1
670 else:
671 return 1
672 if self.after != other.after:
673 if self.after < other.after:
674 return -1
675 else:
676 return 1
677 return 0
678
679 def _setAction(self, value):
680 """
681 Property target used to set the action name.
682 The value must be a non-empty string if it is not ``None``.
683 It must also consist only of lower-case letters and digits.
684 Raises:
685 ValueError: If the value is an empty string
686 """
687 pattern = re.compile(ACTION_NAME_REGEX)
688 if value is not None:
689 if len(value) < 1:
690 raise ValueError("The action name must be a non-empty string.")
691 if not pattern.search(value):
692 raise ValueError("The action name must consist of only lower-case letters and digits.")
693 self._action = value
694
695 def _getAction(self):
696 """
697 Property target used to get the action name.
698 """
699 return self._action
700
701 def _setCommand(self, value):
702 """
703 Property target used to set the command.
704 The value must be a non-empty string if it is not ``None``.
705 Raises:
706 ValueError: If the value is an empty string
707 """
708 if value is not None:
709 if len(value) < 1:
710 raise ValueError("The command must be a non-empty string.")
711 self._command = value
712
713 def _getCommand(self):
714 """
715 Property target used to get the command.
716 """
717 return self._command
718
719 def _getBefore(self):
720 """
721 Property target used to get the before flag.
722 """
723 return self._before
724
725 def _getAfter(self):
726 """
727 Property target used to get the after flag.
728 """
729 return self._after
730
731 action = property(_getAction, _setAction, None, "Action this hook is associated with.")
732 command = property(_getCommand, _setCommand, None, "Shell command to execute.")
733 before = property(_getBefore, None, None, "Indicates whether command should be executed before action.")
734 after = property(_getAfter, None, None, "Indicates whether command should be executed after action.")
735
736
737 @total_ordering
738 class PreActionHook(ActionHook):
739 """
740 Class representing a pre-action hook associated with an action.
741
742 A hook associated with an action is a shell command to be executed either
743 before or after a named action is executed. In this case, a pre-action hook
744 is executed before the named action.
745
746 The following restrictions exist on data in this class:
747
748 - The action name must be a non-empty string consisting of lower-case letters and digits.
749 - The shell command must be a non-empty string.
750
751 The internal ``before`` instance variable is always set to True in this
752 class.
753
754 """
755
756 def __init__(self, action=None, command=None):
757 """
758 Constructor for the ``PreActionHook`` class.
759
760 Args:
761 action: Action this hook is associated with
762 command: Shell command to execute
763
764 Raises:
765 ValueError: If one of the values is invalid
766 """
767 ActionHook.__init__(self, action, command)
768 self._before = True
769
770 def __repr__(self):
771 """
772 Official string representation for class instance.
773 """
774 return "PreActionHook(%s, %s, %s, %s)" % (self.action, self.command, self.before, self.after)
775
776
777 @total_ordering
778 class PostActionHook(ActionHook):
779 """
780 Class representing a pre-action hook associated with an action.
781
782 A hook associated with an action is a shell command to be executed either
783 before or after a named action is executed. In this case, a post-action hook
784 is executed after the named action.
785
786 The following restrictions exist on data in this class:
787
788 - The action name must be a non-empty string consisting of lower-case letters and digits.
789 - The shell command must be a non-empty string.
790
791 The internal ``before`` instance variable is always set to True in this
792 class.
793
794 """
795
796 def __init__(self, action=None, command=None):
797 """
798 Constructor for the ``PostActionHook`` class.
799
800 Args:
801 action: Action this hook is associated with
802 command: Shell command to execute
803
804 Raises:
805 ValueError: If one of the values is invalid
806 """
807 ActionHook.__init__(self, action, command)
808 self._after = True
809
810 def __repr__(self):
811 """
812 Official string representation for class instance.
813 """
814 return "PostActionHook(%s, %s, %s, %s)" % (self.action, self.command, self.before, self.after)
815
816
817 ########################################################################
818 # BlankBehavior class definition
819 ########################################################################
820
821
822 @total_ordering
823 class BlankBehavior:
824 """
825 Class representing optimized store-action media blanking behavior.
826
827 The following restrictions exist on data in this class:
828
829 - The blanking mode must be a one of the values in ``VALID_BLANK_MODES``
830 - The blanking factor must be a positive floating point number
831
832 """
833
834 def __init__(self, blankMode=None, blankFactor=None):
835 """
836 Constructor for the ``BlankBehavior`` class.
837
838 Args:
839 blankMode: Blanking mode
840 blankFactor: Blanking factor
841
842 Raises:
843 ValueError: If one of the values is invalid
844 """
845 self._blankMode = None
846 self._blankFactor = None
847 self.blankMode = blankMode
848 self.blankFactor = blankFactor
849
850 def __repr__(self):
851 """
852 Official string representation for class instance.
853 """
854 return "BlankBehavior(%s, %s)" % (self.blankMode, self.blankFactor)
855
856 def __str__(self):
857 """
858 Informal string representation for class instance.
859 """
860 return self.__repr__()
861
862 def __eq__(self, other):
863 """Equals operator, implemented in terms of original Python 2 compare operator."""
864 return self.__cmp__(other) == 0
865
866 def __lt__(self, other):
867 """Less-than operator, implemented in terms of original Python 2 compare operator."""
868 return self.__cmp__(other) < 0
869
870 def __gt__(self, other):
871 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
872 return self.__cmp__(other) > 0
873
874 def __cmp__(self, other):
875 """
876 Original Python 2 comparison operator.
877 Args:
878 other: Other object to compare to
879 Returns:
880 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
881 """
882 if other is None:
883 return 1
884 if self.blankMode != other.blankMode:
885 if str(self.blankMode or "") < str(other.blankMode or ""):
886 return -1
887 else:
888 return 1
889 if self.blankFactor != other.blankFactor:
890 if float(self.blankFactor or 0.0) < float(other.blankFactor or 0.0):
891 return -1
892 else:
893 return 1
894 return 0
895
896 def _setBlankMode(self, value):
897 """
898 Property target used to set the blanking mode.
899 The value must be one of ``VALID_BLANK_MODES``.
900 Raises:
901 ValueError: If the value is not valid
902 """
903 if value is not None:
904 if value not in VALID_BLANK_MODES:
905 raise ValueError("Blanking mode must be one of %s." % VALID_BLANK_MODES)
906 self._blankMode = value
907
908 def _getBlankMode(self):
909 """
910 Property target used to get the blanking mode.
911 """
912 return self._blankMode
913
914 def _setBlankFactor(self, value):
915 """
916 Property target used to set the blanking factor.
917 The value must be a non-empty string if it is not ``None``.
918 Raises:
919 ValueError: If the value is an empty string
920 ValueError: If the value is not a valid floating point number
921 ValueError: If the value is less than zero
922 """
923 if value is not None:
924 if len(value) < 1:
925 raise ValueError("Blanking factor must be a non-empty string.")
926 floatValue = float(value)
927 if floatValue < 0.0:
928 raise ValueError("Blanking factor cannot be negative.")
929 self._blankFactor = value # keep around string
930
931 def _getBlankFactor(self):
932 """
933 Property target used to get the blanking factor.
934 """
935 return self._blankFactor
936
937 blankMode = property(_getBlankMode, _setBlankMode, None, "Blanking mode")
938 blankFactor = property(_getBlankFactor, _setBlankFactor, None, "Blanking factor")
939
940
941 ########################################################################
942 # ExtendedAction class definition
943 ########################################################################
944
945
946 @total_ordering
947 class ExtendedAction:
948 """
949 Class representing an extended action.
950
951 Essentially, an extended action needs to allow the following to happen::
952
953 exec("from %s import %s" % (module, function))
954 exec("%s(action, configPath")" % function)
955
956 The following restrictions exist on data in this class:
957
958 - The action name must be a non-empty string consisting of lower-case letters and digits.
959 - The module must be a non-empty string and a valid Python identifier.
960 - The function must be an on-empty string and a valid Python identifier.
961 - If set, the index must be a positive integer.
962 - If set, the dependencies attribute must be an ``ActionDependencies`` object.
963
964 """
965
966 def __init__(self, name=None, module=None, function=None, index=None, dependencies=None):
967 """
968 Constructor for the ``ExtendedAction`` class.
969
970 Args:
971 name: Name of the extended action
972 module: Name of the module containing the extended action function
973 function: Name of the extended action function
974 index: Index of action, used for execution ordering
975 dependencies: Dependencies for action, used for execution ordering
976
977 Raises:
978 ValueError: If one of the values is invalid
979 """
980 self._name = None
981 self._module = None
982 self._function = None
983 self._index = None
984 self._dependencies = None
985 self.name = name
986 self.module = module
987 self.function = function
988 self.index = index
989 self.dependencies = dependencies
990
991 def __repr__(self):
992 """
993 Official string representation for class instance.
994 """
995 return "ExtendedAction(%s, %s, %s, %s, %s)" % (self.name, self.module, self.function, self.index, self.dependencies)
996
997 def __str__(self):
998 """
999 Informal string representation for class instance.
1000 """
1001 return self.__repr__()
1002
1003 def __eq__(self, other):
1004 """Equals operator, implemented in terms of original Python 2 compare operator."""
1005 return self.__cmp__(other) == 0
1006
1007 def __lt__(self, other):
1008 """Less-than operator, implemented in terms of original Python 2 compare operator."""
1009 return self.__cmp__(other) < 0
1010
1011 def __gt__(self, other):
1012 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
1013 return self.__cmp__(other) > 0
1014
1015 def __cmp__(self, other):
1016 """
1017 Original Python 2 comparison operator.
1018 Args:
1019 other: Other object to compare to
1020 Returns:
1021 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
1022 """
1023 if other is None:
1024 return 1
1025 if self.name != other.name:
1026 if str(self.name or "") < str(other.name or ""):
1027 return -1
1028 else:
1029 return 1
1030 if self.module != other.module:
1031 if str(self.module or "") < str(other.module or ""):
1032 return -1
1033 else:
1034 return 1
1035 if self.function != other.function:
1036 if str(self.function or "") < str(other.function or ""):
1037 return -1
1038 else:
1039 return 1
1040 if self.index != other.index:
1041 if int(self.index or 0) < int(other.index or 0):
1042 return -1
1043 else:
1044 return 1
1045 if self.dependencies != other.dependencies:
1046 if self.dependencies < other.dependencies:
1047 return -1
1048 else:
1049 return 1
1050 return 0
1051
1052 def _setName(self, value):
1053 """
1054 Property target used to set the action name.
1055 The value must be a non-empty string if it is not ``None``.
1056 It must also consist only of lower-case letters and digits.
1057 Raises:
1058 ValueError: If the value is an empty string
1059 """
1060 pattern = re.compile(ACTION_NAME_REGEX)
1061 if value is not None:
1062 if len(value) < 1:
1063 raise ValueError("The action name must be a non-empty string.")
1064 if not pattern.search(value):
1065 raise ValueError("The action name must consist of only lower-case letters and digits.")
1066 self._name = value
1067
1068 def _getName(self):
1069 """
1070 Property target used to get the action name.
1071 """
1072 return self._name
1073
1074 def _setModule(self, value):
1075 """
1076 Property target used to set the module name.
1077 The value must be a non-empty string if it is not ``None``.
1078 It must also be a valid Python identifier.
1079 Raises:
1080 ValueError: If the value is an empty string
1081 """
1082 pattern = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)(\.[A-Za-z_][A-Za-z0-9_]*)*$")
1083 if value is not None:
1084 if len(value) < 1:
1085 raise ValueError("The module name must be a non-empty string.")
1086 if not pattern.search(value):
1087 raise ValueError("The module name must be a valid Python identifier.")
1088 self._module = value
1089
1090 def _getModule(self):
1091 """
1092 Property target used to get the module name.
1093 """
1094 return self._module
1095
1096 def _setFunction(self, value):
1097 """
1098 Property target used to set the function name.
1099 The value must be a non-empty string if it is not ``None``.
1100 It must also be a valid Python identifier.
1101 Raises:
1102 ValueError: If the value is an empty string
1103 """
1104 pattern = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
1105 if value is not None:
1106 if len(value) < 1:
1107 raise ValueError("The function name must be a non-empty string.")
1108 if not pattern.search(value):
1109 raise ValueError("The function name must be a valid Python identifier.")
1110 self._function = value
1111
1112 def _getFunction(self):
1113 """
1114 Property target used to get the function name.
1115 """
1116 return self._function
1117
1118 def _setIndex(self, value):
1119 """
1120 Property target used to set the action index.
1121 The value must be an integer >= 0.
1122 Raises:
1123 ValueError: If the value is not valid
1124 """
1125 if value is None:
1126 self._index = None
1127 else:
1128 try:
1129 value = int(value)
1130 except TypeError:
1131 raise ValueError("Action index value must be an integer >= 0.")
1132 if value < 0:
1133 raise ValueError("Action index value must be an integer >= 0.")
1134 self._index = value
1135
1136 def _getIndex(self):
1137 """
1138 Property target used to get the action index.
1139 """
1140 return self._index
1141
1142 def _setDependencies(self, value):
1143 """
1144 Property target used to set the action dependencies information.
1145 If not ``None``, the value must be a ``ActionDependecies`` object.
1146 Raises:
1147 ValueError: If the value is not a ``ActionDependencies`` object
1148 """
1149 if value is None:
1150 self._dependencies = None
1151 else:
1152 if not isinstance(value, ActionDependencies):
1153 raise ValueError("Value must be a ``ActionDependencies`` object.")
1154 self._dependencies = value
1155
1156 def _getDependencies(self):
1157 """
1158 Property target used to get action dependencies information.
1159 """
1160 return self._dependencies
1161
1162 name = property(_getName, _setName, None, "Name of the extended action.")
1163 module = property(_getModule, _setModule, None, "Name of the module containing the extended action function.")
1164 function = property(_getFunction, _setFunction, None, "Name of the extended action function.")
1165 index = property(_getIndex, _setIndex, None, "Index of action, used for execution ordering.")
1166 dependencies = property(_getDependencies, _setDependencies, None, "Dependencies for action, used for execution ordering.")
1167
1168
1169 ########################################################################
1170 # CommandOverride class definition
1171 ########################################################################
1172
1173
1174 @total_ordering
1175 class CommandOverride:
1176 """
1177 Class representing a piece of Cedar Backup command override configuration.
1178
1179 The following restrictions exist on data in this class:
1180
1181 - The absolute path must be absolute
1182
1183 *Note:* Lists within this class are "unordered" for equality comparisons.
1184
1185 """
1186
1187 def __init__(self, command=None, absolutePath=None):
1188 """
1189 Constructor for the ``CommandOverride`` class.
1190
1191 Args:
1192 command: Name of command to be overridden
1193 absolutePath: Absolute path of the overrridden command
1194
1195 Raises:
1196 ValueError: If one of the values is invalid
1197 """
1198 self._command = None
1199 self._absolutePath = None
1200 self.command = command
1201 self.absolutePath = absolutePath
1202
1203 def __repr__(self):
1204 """
1205 Official string representation for class instance.
1206 """
1207 return "CommandOverride(%s, %s)" % (self.command, self.absolutePath)
1208
1209 def __str__(self):
1210 """
1211 Informal string representation for class instance.
1212 """
1213 return self.__repr__()
1214
1215 def __eq__(self, other):
1216 """Equals operator, implemented in terms of original Python 2 compare operator."""
1217 return self.__cmp__(other) == 0
1218
1219 def __lt__(self, other):
1220 """Less-than operator, implemented in terms of original Python 2 compare operator."""
1221 return self.__cmp__(other) < 0
1222
1223 def __gt__(self, other):
1224 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
1225 return self.__cmp__(other) > 0
1226
1227 def __cmp__(self, other):
1228 """
1229 Original Python 2 comparison operator.
1230 Args:
1231 other: Other object to compare to
1232 Returns:
1233 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
1234 """
1235 if other is None:
1236 return 1
1237 if self.command != other.command:
1238 if str(self.command or "") < str(other.command or ""):
1239 return -1
1240 else:
1241 return 1
1242 if self.absolutePath != other.absolutePath:
1243 if str(self.absolutePath or "") < str(other.absolutePath or ""):
1244 return -1
1245 else:
1246 return 1
1247 return 0
1248
1249 def _setCommand(self, value):
1250 """
1251 Property target used to set the command.
1252 The value must be a non-empty string if it is not ``None``.
1253 Raises:
1254 ValueError: If the value is an empty string
1255 """
1256 if value is not None:
1257 if len(value) < 1:
1258 raise ValueError("The command must be a non-empty string.")
1259 self._command = value
1260
1261 def _getCommand(self):
1262 """
1263 Property target used to get the command.
1264 """
1265 return self._command
1266
1267 def _setAbsolutePath(self, value):
1268 """
1269 Property target used to set the absolute path.
1270 The value must be an absolute path if it is not ``None``.
1271 It does not have to exist on disk at the time of assignment.
1272 Raises:
1273 ValueError: If the value is not an absolute path
1274 ValueError: If the value cannot be encoded properly
1275 """
1276 if value is not None:
1277 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
1278 raise ValueError("Not an absolute path: [%s]" % value)
1279 self._absolutePath = encodePath(value)
1280
1281 def _getAbsolutePath(self):
1282 """
1283 Property target used to get the absolute path.
1284 """
1285 return self._absolutePath
1286
1287 command = property(_getCommand, _setCommand, None, doc="Name of command to be overridden.")
1288 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, doc="Absolute path of the overrridden command.")
1289
1290
1291 ########################################################################
1292 # CollectFile class definition
1293 ########################################################################
1294
1295
1296 @total_ordering
1297 class CollectFile:
1298 """
1299 Class representing a Cedar Backup collect file.
1300
1301 The following restrictions exist on data in this class:
1302
1303 - Absolute paths must be absolute
1304 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
1305 - The archive mode must be one of the values in :any:`VALID_ARCHIVE_MODES`.
1306
1307 """
1308
1309 def __init__(self, absolutePath=None, collectMode=None, archiveMode=None):
1310 """
1311 Constructor for the ``CollectFile`` class.
1312
1313 Args:
1314 absolutePath: Absolute path of the file to collect
1315 collectMode: Overridden collect mode for this file
1316 archiveMode: Overridden archive mode for this file
1317
1318 Raises:
1319 ValueError: If one of the values is invalid
1320 """
1321 self._absolutePath = None
1322 self._collectMode = None
1323 self._archiveMode = None
1324 self.absolutePath = absolutePath
1325 self.collectMode = collectMode
1326 self.archiveMode = archiveMode
1327
1328 def __repr__(self):
1329 """
1330 Official string representation for class instance.
1331 """
1332 return "CollectFile(%s, %s, %s)" % (self.absolutePath, self.collectMode, self.archiveMode)
1333
1334 def __str__(self):
1335 """
1336 Informal string representation for class instance.
1337 """
1338 return self.__repr__()
1339
1340 def __eq__(self, other):
1341 """Equals operator, implemented in terms of original Python 2 compare operator."""
1342 return self.__cmp__(other) == 0
1343
1344 def __lt__(self, other):
1345 """Less-than operator, implemented in terms of original Python 2 compare operator."""
1346 return self.__cmp__(other) < 0
1347
1348 def __gt__(self, other):
1349 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
1350 return self.__cmp__(other) > 0
1351
1352 def __cmp__(self, other):
1353 """
1354 Original Python 2 comparison operator.
1355 Args:
1356 other: Other object to compare to
1357 Returns:
1358 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
1359 """
1360 if other is None:
1361 return 1
1362 if self.absolutePath != other.absolutePath:
1363 if str(self.absolutePath or "") < str(other.absolutePath or ""):
1364 return -1
1365 else:
1366 return 1
1367 if self.collectMode != other.collectMode:
1368 if str(self.collectMode or "") < str(other.collectMode or ""):
1369 return -1
1370 else:
1371 return 1
1372 if self.archiveMode != other.archiveMode:
1373 if str(self.archiveMode or "") < str(other.archiveMode or ""):
1374 return -1
1375 else:
1376 return 1
1377 return 0
1378
1379 def _setAbsolutePath(self, value):
1380 """
1381 Property target used to set the absolute path.
1382 The value must be an absolute path if it is not ``None``.
1383 It does not have to exist on disk at the time of assignment.
1384 Raises:
1385 ValueError: If the value is not an absolute path
1386 ValueError: If the value cannot be encoded properly
1387 """
1388 if value is not None:
1389 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
1390 raise ValueError("Not an absolute path: [%s]" % value)
1391 self._absolutePath = encodePath(value)
1392
1393 def _getAbsolutePath(self):
1394 """
1395 Property target used to get the absolute path.
1396 """
1397 return self._absolutePath
1398
1399 def _setCollectMode(self, value):
1400 """
1401 Property target used to set the collect mode.
1402 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
1403 Raises:
1404 ValueError: If the value is not valid
1405 """
1406 if value is not None:
1407 if value not in VALID_COLLECT_MODES:
1408 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
1409 self._collectMode = value
1410
1411 def _getCollectMode(self):
1412 """
1413 Property target used to get the collect mode.
1414 """
1415 return self._collectMode
1416
1417 def _setArchiveMode(self, value):
1418 """
1419 Property target used to set the archive mode.
1420 If not ``None``, the mode must be one of the values in :any:`VALID_ARCHIVE_MODES`.
1421 Raises:
1422 ValueError: If the value is not valid
1423 """
1424 if value is not None:
1425 if value not in VALID_ARCHIVE_MODES:
1426 raise ValueError("Archive mode must be one of %s." % VALID_ARCHIVE_MODES)
1427 self._archiveMode = value
1428
1429 def _getArchiveMode(self):
1430 """
1431 Property target used to get the archive mode.
1432 """
1433 return self._archiveMode
1434
1435 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, doc="Absolute path of the file to collect.")
1436 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this file.")
1437 archiveMode = property(_getArchiveMode, _setArchiveMode, None, doc="Overridden archive mode for this file.")
1438
1439
1440 ########################################################################
1441 # CollectDir class definition
1442 ########################################################################
1443
1444
1445 @total_ordering
1446 class CollectDir:
1447 """
1448 Class representing a Cedar Backup collect directory.
1449
1450 The following restrictions exist on data in this class:
1451
1452 - Absolute paths must be absolute
1453 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
1454 - The archive mode must be one of the values in :any:`VALID_ARCHIVE_MODES`.
1455 - The ignore file must be a non-empty string.
1456
1457 For the ``absoluteExcludePaths`` list, validation is accomplished through the
1458 :any:`util.AbsolutePathList` list implementation that overrides common list
1459 methods and transparently does the absolute path validation for us.
1460
1461 *Note:* Lists within this class are "unordered" for equality comparisons.
1462
1463 """
1464
1465 def __init__(
1466 self,
1467 absolutePath=None,
1468 collectMode=None,
1469 archiveMode=None,
1470 ignoreFile=None,
1471 absoluteExcludePaths=None,
1472 relativeExcludePaths=None,
1473 excludePatterns=None,
1474 linkDepth=None,
1475 dereference=False,
1476 recursionLevel=None,
1477 ):
1478 """
1479 Constructor for the ``CollectDir`` class.
1480
1481 Args:
1482 absolutePath: Absolute path of the directory to collect
1483 collectMode: Overridden collect mode for this directory
1484 archiveMode: Overridden archive mode for this directory
1485 ignoreFile: Overidden ignore file name for this directory
1486 linkDepth: Maximum at which soft links should be followed
1487 dereference: Whether to dereference links that are followed
1488 absoluteExcludePaths: List of absolute paths to exclude
1489 relativeExcludePaths: List of relative paths to exclude
1490 excludePatterns: List of regular expression patterns to exclude
1491
1492 Raises:
1493 ValueError: If one of the values is invalid
1494 """
1495 self._absolutePath = None
1496 self._collectMode = None
1497 self._archiveMode = None
1498 self._ignoreFile = None
1499 self._linkDepth = None
1500 self._dereference = None
1501 self._recursionLevel = None
1502 self._absoluteExcludePaths = None
1503 self._relativeExcludePaths = None
1504 self._excludePatterns = None
1505 self.absolutePath = absolutePath
1506 self.collectMode = collectMode
1507 self.archiveMode = archiveMode
1508 self.ignoreFile = ignoreFile
1509 self.linkDepth = linkDepth
1510 self.dereference = dereference
1511 self.recursionLevel = recursionLevel
1512 self.absoluteExcludePaths = absoluteExcludePaths
1513 self.relativeExcludePaths = relativeExcludePaths
1514 self.excludePatterns = excludePatterns
1515
1516 def __repr__(self):
1517 """
1518 Official string representation for class instance.
1519 """
1520 return "CollectDir(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (
1521 self.absolutePath,
1522 self.collectMode,
1523 self.archiveMode,
1524 self.ignoreFile,
1525 self.absoluteExcludePaths,
1526 self.relativeExcludePaths,
1527 self.excludePatterns,
1528 self.linkDepth,
1529 self.dereference,
1530 self.recursionLevel,
1531 )
1532
1533 def __str__(self):
1534 """
1535 Informal string representation for class instance.
1536 """
1537 return self.__repr__()
1538
1539 def __eq__(self, other):
1540 """Equals operator, implemented in terms of original Python 2 compare operator."""
1541 return self.__cmp__(other) == 0
1542
1543 def __lt__(self, other):
1544 """Less-than operator, implemented in terms of original Python 2 compare operator."""
1545 return self.__cmp__(other) < 0
1546
1547 def __gt__(self, other):
1548 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
1549 return self.__cmp__(other) > 0
1550
1551 def __cmp__(self, other):
1552 """
1553 Original Python 2 comparison operator.
1554 Lists within this class are "unordered" for equality comparisons.
1555 Args:
1556 other: Other object to compare to
1557 Returns:
1558 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
1559 """
1560 if other is None:
1561 return 1
1562 if self.absolutePath != other.absolutePath:
1563 if str(self.absolutePath or "") < str(other.absolutePath or ""):
1564 return -1
1565 else:
1566 return 1
1567 if self.collectMode != other.collectMode:
1568 if str(self.collectMode or "") < str(other.collectMode or ""):
1569 return -1
1570 else:
1571 return 1
1572 if self.archiveMode != other.archiveMode:
1573 if str(self.archiveMode or "") < str(other.archiveMode or ""):
1574 return -1
1575 else:
1576 return 1
1577 if self.ignoreFile != other.ignoreFile:
1578 if str(self.ignoreFile or "") < str(other.ignoreFile or ""):
1579 return -1
1580 else:
1581 return 1
1582 if self.linkDepth != other.linkDepth:
1583 if int(self.linkDepth or 0) < int(other.linkDepth or 0):
1584 return -1
1585 else:
1586 return 1
1587 if self.dereference != other.dereference:
1588 if self.dereference < other.dereference:
1589 return -1
1590 else:
1591 return 1
1592 if self.recursionLevel != other.recursionLevel:
1593 if int(self.recursionLevel or 0) < int(other.recursionLevel or 0):
1594 return -1
1595 else:
1596 return 1
1597 if self.absoluteExcludePaths != other.absoluteExcludePaths:
1598 if self.absoluteExcludePaths < other.absoluteExcludePaths:
1599 return -1
1600 else:
1601 return 1
1602 if self.relativeExcludePaths != other.relativeExcludePaths:
1603 if self.relativeExcludePaths < other.relativeExcludePaths:
1604 return -1
1605 else:
1606 return 1
1607 if self.excludePatterns != other.excludePatterns:
1608 if self.excludePatterns < other.excludePatterns:
1609 return -1
1610 else:
1611 return 1
1612 return 0
1613
1614 def _setAbsolutePath(self, value):
1615 """
1616 Property target used to set the absolute path.
1617 The value must be an absolute path if it is not ``None``.
1618 It does not have to exist on disk at the time of assignment.
1619 Raises:
1620 ValueError: If the value is not an absolute path
1621 ValueError: If the value cannot be encoded properly
1622 """
1623 if value is not None:
1624 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
1625 raise ValueError("Not an absolute path: [%s]" % value)
1626 self._absolutePath = encodePath(value)
1627
1628 def _getAbsolutePath(self):
1629 """
1630 Property target used to get the absolute path.
1631 """
1632 return self._absolutePath
1633
1634 def _setCollectMode(self, value):
1635 """
1636 Property target used to set the collect mode.
1637 If not ``None``, the mode must be one of the values in :any:`VALID_COLLECT_MODES`.
1638 Raises:
1639 ValueError: If the value is not valid
1640 """
1641 if value is not None:
1642 if value not in VALID_COLLECT_MODES:
1643 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
1644 self._collectMode = value
1645
1646 def _getCollectMode(self):
1647 """
1648 Property target used to get the collect mode.
1649 """
1650 return self._collectMode
1651
1652 def _setArchiveMode(self, value):
1653 """
1654 Property target used to set the archive mode.
1655 If not ``None``, the mode must be one of the values in :any:`VALID_ARCHIVE_MODES`.
1656 Raises:
1657 ValueError: If the value is not valid
1658 """
1659 if value is not None:
1660 if value not in VALID_ARCHIVE_MODES:
1661 raise ValueError("Archive mode must be one of %s." % VALID_ARCHIVE_MODES)
1662 self._archiveMode = value
1663
1664 def _getArchiveMode(self):
1665 """
1666 Property target used to get the archive mode.
1667 """
1668 return self._archiveMode
1669
1670 def _setIgnoreFile(self, value):
1671 """
1672 Property target used to set the ignore file.
1673 The value must be a non-empty string if it is not ``None``.
1674 Raises:
1675 ValueError: If the value is an empty string
1676 """
1677 if value is not None:
1678 if len(value) < 1:
1679 raise ValueError("The ignore file must be a non-empty string.")
1680 self._ignoreFile = value
1681
1682 def _getIgnoreFile(self):
1683 """
1684 Property target used to get the ignore file.
1685 """
1686 return self._ignoreFile
1687
1688 def _setLinkDepth(self, value):
1689 """
1690 Property target used to set the link depth.
1691 The value must be an integer >= 0.
1692 Raises:
1693 ValueError: If the value is not valid
1694 """
1695 if value is None:
1696 self._linkDepth = None
1697 else:
1698 try:
1699 value = int(value)
1700 except TypeError:
1701 raise ValueError("Link depth value must be an integer >= 0.")
1702 if value < 0:
1703 raise ValueError("Link depth value must be an integer >= 0.")
1704 self._linkDepth = value
1705
1706 def _getLinkDepth(self):
1707 """
1708 Property target used to get the action linkDepth.
1709 """
1710 return self._linkDepth
1711
1712 def _setDereference(self, value):
1713 """
1714 Property target used to set the dereference flag.
1715 No validations, but we normalize the value to ``True`` or ``False``.
1716 """
1717 if value:
1718 self._dereference = True
1719 else:
1720 self._dereference = False
1721
1722 def _getDereference(self):
1723 """
1724 Property target used to get the dereference flag.
1725 """
1726 return self._dereference
1727
1728 def _setRecursionLevel(self, value):
1729 """
1730 Property target used to set the recursionLevel.
1731 The value must be an integer.
1732 Raises:
1733 ValueError: If the value is not valid
1734 """
1735 if value is None:
1736 self._recursionLevel = None
1737 else:
1738 try:
1739 value = int(value)
1740 except TypeError:
1741 raise ValueError("Recusion level value must be an integer.")
1742 self._recursionLevel = value
1743
1744 def _getRecursionLevel(self):
1745 """
1746 Property target used to get the action recursionLevel.
1747 """
1748 return self._recursionLevel
1749
1750 def _setAbsoluteExcludePaths(self, value):
1751 """
1752 Property target used to set the absolute exclude paths list.
1753 Either the value must be ``None`` or each element must be an absolute path.
1754 Elements do not have to exist on disk at the time of assignment.
1755 Raises:
1756 ValueError: If the value is not an absolute path
1757 """
1758 if value is None:
1759 self._absoluteExcludePaths = None
1760 else:
1761 try:
1762 saved = self._absoluteExcludePaths
1763 self._absoluteExcludePaths = AbsolutePathList()
1764 self._absoluteExcludePaths.extend(value)
1765 except Exception as e:
1766 self._absoluteExcludePaths = saved
1767 raise e
1768
1769 def _getAbsoluteExcludePaths(self):
1770 """
1771 Property target used to get the absolute exclude paths list.
1772 """
1773 return self._absoluteExcludePaths
1774
1775 def _setRelativeExcludePaths(self, value):
1776 """
1777 Property target used to set the relative exclude paths list.
1778 Elements do not have to exist on disk at the time of assignment.
1779 """
1780 if value is None:
1781 self._relativeExcludePaths = None
1782 else:
1783 try:
1784 saved = self._relativeExcludePaths
1785 self._relativeExcludePaths = UnorderedList()
1786 self._relativeExcludePaths.extend(value)
1787 except Exception as e:
1788 self._relativeExcludePaths = saved
1789 raise e
1790
1791 def _getRelativeExcludePaths(self):
1792 """
1793 Property target used to get the relative exclude paths list.
1794 """
1795 return self._relativeExcludePaths
1796
1797 def _setExcludePatterns(self, value):
1798 """
1799 Property target used to set the exclude patterns list.
1800 """
1801 if value is None:
1802 self._excludePatterns = None
1803 else:
1804 try:
1805 saved = self._excludePatterns
1806 self._excludePatterns = RegexList()
1807 self._excludePatterns.extend(value)
1808 except Exception as e:
1809 self._excludePatterns = saved
1810 raise e
1811
1812 def _getExcludePatterns(self):
1813 """
1814 Property target used to get the exclude patterns list.
1815 """
1816 return self._excludePatterns
1817
1818 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, doc="Absolute path of the directory to collect.")
1819 collectMode = property(_getCollectMode, _setCollectMode, None, doc="Overridden collect mode for this directory.")
1820 archiveMode = property(_getArchiveMode, _setArchiveMode, None, doc="Overridden archive mode for this directory.")
1821 ignoreFile = property(_getIgnoreFile, _setIgnoreFile, None, doc="Overridden ignore file name for this directory.")
1822 linkDepth = property(_getLinkDepth, _setLinkDepth, None, doc="Maximum at which soft links should be followed.")
1823 dereference = property(_getDereference, _setDereference, None, doc="Whether to dereference links that are followed.")
1824 recursionLevel = property(
1825 _getRecursionLevel, _setRecursionLevel, None, "Recursion level to use for recursive directory collection"
1826 )
1827 absoluteExcludePaths = property(_getAbsoluteExcludePaths, _setAbsoluteExcludePaths, None, "List of absolute paths to exclude.")
1828 relativeExcludePaths = property(_getRelativeExcludePaths, _setRelativeExcludePaths, None, "List of relative paths to exclude.")
1829 excludePatterns = property(_getExcludePatterns, _setExcludePatterns, None, "List of regular expression patterns to exclude.")
1830
1831
1832 ########################################################################
1833 # PurgeDir class definition
1834 ########################################################################
1835
1836
1837 @total_ordering
1838 class PurgeDir:
1839 """
1840 Class representing a Cedar Backup purge directory.
1841
1842 The following restrictions exist on data in this class:
1843
1844 - The absolute path must be an absolute path
1845 - The retain days value must be an integer >= 0.
1846
1847 """
1848
1849 def __init__(self, absolutePath=None, retainDays=None):
1850 """
1851 Constructor for the ``PurgeDir`` class.
1852
1853 Args:
1854 absolutePath: Absolute path of the directory to be purged
1855 retainDays: Number of days content within directory should be retained
1856
1857 Raises:
1858 ValueError: If one of the values is invalid
1859 """
1860 self._absolutePath = None
1861 self._retainDays = None
1862 self.absolutePath = absolutePath
1863 self.retainDays = retainDays
1864
1865 def __repr__(self):
1866 """
1867 Official string representation for class instance.
1868 """
1869 return "PurgeDir(%s, %s)" % (self.absolutePath, self.retainDays)
1870
1871 def __str__(self):
1872 """
1873 Informal string representation for class instance.
1874 """
1875 return self.__repr__()
1876
1877 def __eq__(self, other):
1878 """Equals operator, implemented in terms of original Python 2 compare operator."""
1879 return self.__cmp__(other) == 0
1880
1881 def __lt__(self, other):
1882 """Less-than operator, implemented in terms of original Python 2 compare operator."""
1883 return self.__cmp__(other) < 0
1884
1885 def __gt__(self, other):
1886 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
1887 return self.__cmp__(other) > 0
1888
1889 def __cmp__(self, other):
1890 """
1891 Original Python 2 comparison operator.
1892 Args:
1893 other: Other object to compare to
1894 Returns:
1895 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
1896 """
1897 if other is None:
1898 return 1
1899 if self.absolutePath != other.absolutePath:
1900 if str(self.absolutePath or "") < str(other.absolutePath or ""):
1901 return -1
1902 else:
1903 return 1
1904 if self.retainDays != other.retainDays:
1905 if int(self.retainDays or 0) < int(other.retainDays or 0):
1906 return -1
1907 else:
1908 return 1
1909 return 0
1910
1911 def _setAbsolutePath(self, value):
1912 """
1913 Property target used to set the absolute path.
1914 The value must be an absolute path if it is not ``None``.
1915 It does not have to exist on disk at the time of assignment.
1916 Raises:
1917 ValueError: If the value is not an absolute path
1918 ValueError: If the value cannot be encoded properly
1919 """
1920 if value is not None:
1921 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
1922 raise ValueError("Absolute path must, er, be an absolute path.")
1923 self._absolutePath = encodePath(value)
1924
1925 def _getAbsolutePath(self):
1926 """
1927 Property target used to get the absolute path.
1928 """
1929 return self._absolutePath
1930
1931 def _setRetainDays(self, value):
1932 """
1933 Property target used to set the retain days value.
1934 The value must be an integer >= 0.
1935 Raises:
1936 ValueError: If the value is not valid
1937 """
1938 if value is None:
1939 self._retainDays = None
1940 else:
1941 try:
1942 value = int(value)
1943 except TypeError:
1944 raise ValueError("Retain days value must be an integer >= 0.")
1945 if value < 0:
1946 raise ValueError("Retain days value must be an integer >= 0.")
1947 self._retainDays = value
1948
1949 def _getRetainDays(self):
1950 """
1951 Property target used to get the absolute path.
1952 """
1953 return self._retainDays
1954
1955 absolutePath = property(_getAbsolutePath, _setAbsolutePath, None, "Absolute path of directory to purge.")
1956 retainDays = property(_getRetainDays, _setRetainDays, None, "Number of days content within directory should be retained.")
1957
1958
1959 ########################################################################
1960 # LocalPeer class definition
1961 ########################################################################
1962
1963
1964 @total_ordering
1965 class LocalPeer:
1966 """
1967 Class representing a Cedar Backup peer.
1968
1969 The following restrictions exist on data in this class:
1970
1971 - The peer name must be a non-empty string.
1972 - The collect directory must be an absolute path.
1973 - The ignore failure mode must be one of the values in ``VALID_FAILURE_MODES``.
1974
1975 """
1976
1977 def __init__(self, name=None, collectDir=None, ignoreFailureMode=None):
1978 """
1979 Constructor for the ``LocalPeer`` class.
1980
1981 Args:
1982 name: Name of the peer, typically a valid hostname
1983 collectDir: Collect directory to stage files from on peer
1984 ignoreFailureMode: Ignore failure mode for peer
1985
1986 Raises:
1987 ValueError: If one of the values is invalid
1988 """
1989 self._name = None
1990 self._collectDir = None
1991 self._ignoreFailureMode = None
1992 self.name = name
1993 self.collectDir = collectDir
1994 self.ignoreFailureMode = ignoreFailureMode
1995
1996 def __repr__(self):
1997 """
1998 Official string representation for class instance.
1999 """
2000 return "LocalPeer(%s, %s, %s)" % (self.name, self.collectDir, self.ignoreFailureMode)
2001
2002 def __str__(self):
2003 """
2004 Informal string representation for class instance.
2005 """
2006 return self.__repr__()
2007
2008 def __eq__(self, other):
2009 """Equals operator, implemented in terms of original Python 2 compare operator."""
2010 return self.__cmp__(other) == 0
2011
2012 def __lt__(self, other):
2013 """Less-than operator, implemented in terms of original Python 2 compare operator."""
2014 return self.__cmp__(other) < 0
2015
2016 def __gt__(self, other):
2017 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
2018 return self.__cmp__(other) > 0
2019
2020 def __cmp__(self, other):
2021 """
2022 Original Python 2 comparison operator.
2023 Args:
2024 other: Other object to compare to
2025 Returns:
2026 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
2027 """
2028 if other is None:
2029 return 1
2030 if self.name != other.name:
2031 if str(self.name or "") < str(other.name or ""):
2032 return -1
2033 else:
2034 return 1
2035 if self.collectDir != other.collectDir:
2036 if str(self.collectDir or "") < str(other.collectDir or ""):
2037 return -1
2038 else:
2039 return 1
2040 if self.ignoreFailureMode != other.ignoreFailureMode:
2041 if str(self.ignoreFailureMode or "") < str(other.ignoreFailureMode or ""):
2042 return -1
2043 else:
2044 return 1
2045 return 0
2046
2047 def _setName(self, value):
2048 """
2049 Property target used to set the peer name.
2050 The value must be a non-empty string if it is not ``None``.
2051 Raises:
2052 ValueError: If the value is an empty string
2053 """
2054 if value is not None:
2055 if len(value) < 1:
2056 raise ValueError("The peer name must be a non-empty string.")
2057 self._name = value
2058
2059 def _getName(self):
2060 """
2061 Property target used to get the peer name.
2062 """
2063 return self._name
2064
2065 def _setCollectDir(self, value):
2066 """
2067 Property target used to set the collect directory.
2068 The value must be an absolute path if it is not ``None``.
2069 It does not have to exist on disk at the time of assignment.
2070 Raises:
2071 ValueError: If the value is not an absolute path
2072 ValueError: If the value cannot be encoded properly
2073 """
2074 if value is not None:
2075 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
2076 raise ValueError("Collect directory must be an absolute path.")
2077 self._collectDir = encodePath(value)
2078
2079 def _getCollectDir(self):
2080 """
2081 Property target used to get the collect directory.
2082 """
2083 return self._collectDir
2084
2085 def _setIgnoreFailureMode(self, value):
2086 """
2087 Property target used to set the ignoreFailure mode.
2088 If not ``None``, the mode must be one of the values in ``VALID_FAILURE_MODES``.
2089 Raises:
2090 ValueError: If the value is not valid
2091 """
2092 if value is not None:
2093 if value not in VALID_FAILURE_MODES:
2094 raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES)
2095 self._ignoreFailureMode = value
2096
2097 def _getIgnoreFailureMode(self):
2098 """
2099 Property target used to get the ignoreFailure mode.
2100 """
2101 return self._ignoreFailureMode
2102
2103 name = property(_getName, _setName, None, "Name of the peer, typically a valid hostname.")
2104 collectDir = property(_getCollectDir, _setCollectDir, None, "Collect directory to stage files from on peer.")
2105 ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.")
2106
2107
2108 ########################################################################
2109 # RemotePeer class definition
2110 ########################################################################
2111
2112
2113 @total_ordering
2114 class RemotePeer:
2115 """
2116 Class representing a Cedar Backup peer.
2117
2118 The following restrictions exist on data in this class:
2119
2120 - The peer name must be a non-empty string.
2121 - The collect directory must be an absolute path.
2122 - The remote user must be a non-empty string.
2123 - The rcp command must be a non-empty string.
2124 - The rsh command must be a non-empty string.
2125 - The cback command must be a non-empty string.
2126 - Any managed action name must be a non-empty string matching ``ACTION_NAME_REGEX``
2127 - The ignore failure mode must be one of the values in ``VALID_FAILURE_MODES``.
2128
2129 """
2130
2131 def __init__(
2132 self,
2133 name=None,
2134 collectDir=None,
2135 remoteUser=None,
2136 rcpCommand=None,
2137 rshCommand=None,
2138 cbackCommand=None,
2139 managed=False,
2140 managedActions=None,
2141 ignoreFailureMode=None,
2142 ):
2143 """
2144 Constructor for the ``RemotePeer`` class.
2145
2146 Args:
2147 name: Name of the peer, must be a valid hostname
2148 collectDir: Collect directory to stage files from on peer
2149 remoteUser: Name of backup user on remote peer
2150 rcpCommand: Overridden rcp-compatible copy command for peer
2151 rshCommand: Overridden rsh-compatible remote shell command for peer
2152 cbackCommand: Overridden cback-compatible command to use on remote peer
2153 managed: Indicates whether this is a managed peer
2154 managedActions: Overridden set of actions that are managed on the peer
2155 ignoreFailureMode: Ignore failure mode for peer
2156
2157 Raises:
2158 ValueError: If one of the values is invalid
2159 """
2160 self._name = None
2161 self._collectDir = None
2162 self._remoteUser = None
2163 self._rcpCommand = None
2164 self._rshCommand = None
2165 self._cbackCommand = None
2166 self._managed = None
2167 self._managedActions = None
2168 self._ignoreFailureMode = None
2169 self.name = name
2170 self.collectDir = collectDir
2171 self.remoteUser = remoteUser
2172 self.rcpCommand = rcpCommand
2173 self.rshCommand = rshCommand
2174 self.cbackCommand = cbackCommand
2175 self.managed = managed
2176 self.managedActions = managedActions
2177 self.ignoreFailureMode = ignoreFailureMode
2178
2179 def __repr__(self):
2180 """
2181 Official string representation for class instance.
2182 """
2183 return "RemotePeer(%s, %s, %s, %s, %s, %s, %s, %s, %s)" % (
2184 self.name,
2185 self.collectDir,
2186 self.remoteUser,
2187 self.rcpCommand,
2188 self.rshCommand,
2189 self.cbackCommand,
2190 self.managed,
2191 self.managedActions,
2192 self.ignoreFailureMode,
2193 )
2194
2195 def __str__(self):
2196 """
2197 Informal string representation for class instance.
2198 """
2199 return self.__repr__()
2200
2201 def __eq__(self, other):
2202 """Equals operator, implemented in terms of original Python 2 compare operator."""
2203 return self.__cmp__(other) == 0
2204
2205 def __lt__(self, other):
2206 """Less-than operator, implemented in terms of original Python 2 compare operator."""
2207 return self.__cmp__(other) < 0
2208
2209 def __gt__(self, other):
2210 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
2211 return self.__cmp__(other) > 0
2212
2213 def __cmp__(self, other):
2214 """
2215 Original Python 2 comparison operator.
2216 Args:
2217 other: Other object to compare to
2218 Returns:
2219 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
2220 """
2221 if other is None:
2222 return 1
2223 if self.name != other.name:
2224 if str(self.name or "") < str(other.name or ""):
2225 return -1
2226 else:
2227 return 1
2228 if self.collectDir != other.collectDir:
2229 if str(self.collectDir or "") < str(other.collectDir or ""):
2230 return -1
2231 else:
2232 return 1
2233 if self.remoteUser != other.remoteUser:
2234 if str(self.remoteUser or "") < str(other.remoteUser or ""):
2235 return -1
2236 else:
2237 return 1
2238 if self.rcpCommand != other.rcpCommand:
2239 if str(self.rcpCommand or "") < str(other.rcpCommand or ""):
2240 return -1
2241 else:
2242 return 1
2243 if self.rshCommand != other.rshCommand:
2244 if str(self.rshCommand or "") < str(other.rshCommand or ""):
2245 return -1
2246 else:
2247 return 1
2248 if self.cbackCommand != other.cbackCommand:
2249 if str(self.cbackCommand or "") < str(other.cbackCommand or ""):
2250 return -1
2251 else:
2252 return 1
2253 if self.managed != other.managed:
2254 if str(self.managed or "") < str(other.managed or ""):
2255 return -1
2256 else:
2257 return 1
2258 if self.managedActions != other.managedActions:
2259 if self.managedActions < other.managedActions:
2260 return -1
2261 else:
2262 return 1
2263 if self.ignoreFailureMode != other.ignoreFailureMode:
2264 if str(self.ignoreFailureMode or "") < str(other.ignoreFailureMode or ""):
2265 return -1
2266 else:
2267 return 1
2268 return 0
2269
2270 def _setName(self, value):
2271 """
2272 Property target used to set the peer name.
2273 The value must be a non-empty string if it is not ``None``.
2274 Raises:
2275 ValueError: If the value is an empty string
2276 """
2277 if value is not None:
2278 if len(value) < 1:
2279 raise ValueError("The peer name must be a non-empty string.")
2280 self._name = value
2281
2282 def _getName(self):
2283 """
2284 Property target used to get the peer name.
2285 """
2286 return self._name
2287
2288 def _setCollectDir(self, value):
2289 """
2290 Property target used to set the collect directory.
2291 The value must be an absolute path if it is not ``None``.
2292 It does not have to exist on disk at the time of assignment.
2293 Raises:
2294 ValueError: If the value is not an absolute path
2295 ValueError: If the value cannot be encoded properly
2296 """
2297 if value is not None:
2298 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
2299 raise ValueError("Collect directory must be an absolute path.")
2300 self._collectDir = encodePath(value)
2301
2302 def _getCollectDir(self):
2303 """
2304 Property target used to get the collect directory.
2305 """
2306 return self._collectDir
2307
2308 def _setRemoteUser(self, value):
2309 """
2310 Property target used to set the remote user.
2311 The value must be a non-empty string if it is not ``None``.
2312 Raises:
2313 ValueError: If the value is an empty string
2314 """
2315 if value is not None:
2316 if len(value) < 1:
2317 raise ValueError("The remote user must be a non-empty string.")
2318 self._remoteUser = value
2319
2320 def _getRemoteUser(self):
2321 """
2322 Property target used to get the remote user.
2323 """
2324 return self._remoteUser
2325
2326 def _setRcpCommand(self, value):
2327 """
2328 Property target used to set the rcp command.
2329 The value must be a non-empty string if it is not ``None``.
2330 Raises:
2331 ValueError: If the value is an empty string
2332 """
2333 if value is not None:
2334 if len(value) < 1:
2335 raise ValueError("The rcp command must be a non-empty string.")
2336 self._rcpCommand = value
2337
2338 def _getRcpCommand(self):
2339 """
2340 Property target used to get the rcp command.
2341 """
2342 return self._rcpCommand
2343
2344 def _setRshCommand(self, value):
2345 """
2346 Property target used to set the rsh command.
2347 The value must be a non-empty string if it is not ``None``.
2348 Raises:
2349 ValueError: If the value is an empty string
2350 """
2351 if value is not None:
2352 if len(value) < 1:
2353 raise ValueError("The rsh command must be a non-empty string.")
2354 self._rshCommand = value
2355
2356 def _getRshCommand(self):
2357 """
2358 Property target used to get the rsh command.
2359 """
2360 return self._rshCommand
2361
2362 def _setCbackCommand(self, value):
2363 """
2364 Property target used to set the cback command.
2365 The value must be a non-empty string if it is not ``None``.
2366 Raises:
2367 ValueError: If the value is an empty string
2368 """
2369 if value is not None:
2370 if len(value) < 1:
2371 raise ValueError("The cback command must be a non-empty string.")
2372 self._cbackCommand = value
2373
2374 def _getCbackCommand(self):
2375 """
2376 Property target used to get the cback command.
2377 """
2378 return self._cbackCommand
2379
2380 def _setManaged(self, value):
2381 """
2382 Property target used to set the managed flag.
2383 No validations, but we normalize the value to ``True`` or ``False``.
2384 """
2385 if value:
2386 self._managed = True
2387 else:
2388 self._managed = False
2389
2390 def _getManaged(self):
2391 """
2392 Property target used to get the managed flag.
2393 """
2394 return self._managed
2395
2396 def _setManagedActions(self, value):
2397 """
2398 Property target used to set the managed actions list.
2399 Elements do not have to exist on disk at the time of assignment.
2400 """
2401 if value is None:
2402 self._managedActions = None
2403 else:
2404 try:
2405 saved = self._managedActions
2406 self._managedActions = RegexMatchList(ACTION_NAME_REGEX, emptyAllowed=False, prefix="Action name")
2407 self._managedActions.extend(value)
2408 except Exception as e:
2409 self._managedActions = saved
2410 raise e
2411
2412 def _getManagedActions(self):
2413 """
2414 Property target used to get the managed actions list.
2415 """
2416 return self._managedActions
2417
2418 def _setIgnoreFailureMode(self, value):
2419 """
2420 Property target used to set the ignoreFailure mode.
2421 If not ``None``, the mode must be one of the values in ``VALID_FAILURE_MODES``.
2422 Raises:
2423 ValueError: If the value is not valid
2424 """
2425 if value is not None:
2426 if value not in VALID_FAILURE_MODES:
2427 raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES)
2428 self._ignoreFailureMode = value
2429
2430 def _getIgnoreFailureMode(self):
2431 """
2432 Property target used to get the ignoreFailure mode.
2433 """
2434 return self._ignoreFailureMode
2435
2436 name = property(_getName, _setName, None, "Name of the peer, must be a valid hostname.")
2437 collectDir = property(_getCollectDir, _setCollectDir, None, "Collect directory to stage files from on peer.")
2438 remoteUser = property(_getRemoteUser, _setRemoteUser, None, "Name of backup user on remote peer.")
2439 rcpCommand = property(_getRcpCommand, _setRcpCommand, None, "Overridden rcp-compatible copy command for peer.")
2440 rshCommand = property(_getRshCommand, _setRshCommand, None, "Overridden rsh-compatible remote shell command for peer.")
2441 cbackCommand = property(_getCbackCommand, _setCbackCommand, None, "Overridden cback-compatible command to use on remote peer.")
2442 managed = property(_getManaged, _setManaged, None, "Indicates whether this is a managed peer.")
2443 managedActions = property(
2444 _getManagedActions, _setManagedActions, None, "Overridden set of actions that are managed on the peer."
2445 )
2446 ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.")
2447
2448
2449 ########################################################################
2450 # ReferenceConfig class definition
2451 ########################################################################
2452
2453
2454 @total_ordering
2455 class ReferenceConfig:
2456 """
2457 Class representing a Cedar Backup reference configuration.
2458
2459 The reference information is just used for saving off metadata about
2460 configuration and exists mostly for backwards-compatibility with Cedar
2461 Backup 1.x.
2462
2463 """
2464
2465 def __init__(self, author=None, revision=None, description=None, generator=None):
2466 """
2467 Constructor for the ``ReferenceConfig`` class.
2468
2469 Args:
2470 author: Author of the configuration file
2471 revision: Revision of the configuration file
2472 description: Description of the configuration file
2473 generator: Tool that generated the configuration file
2474 """
2475 self._author = None
2476 self._revision = None
2477 self._description = None
2478 self._generator = None
2479 self.author = author
2480 self.revision = revision
2481 self.description = description
2482 self.generator = generator
2483
2484 def __repr__(self):
2485 """
2486 Official string representation for class instance.
2487 """
2488 return "ReferenceConfig(%s, %s, %s, %s)" % (self.author, self.revision, self.description, self.generator)
2489
2490 def __str__(self):
2491 """
2492 Informal string representation for class instance.
2493 """
2494 return self.__repr__()
2495
2496 def __eq__(self, other):
2497 """Equals operator, implemented in terms of original Python 2 compare operator."""
2498 return self.__cmp__(other) == 0
2499
2500 def __lt__(self, other):
2501 """Less-than operator, implemented in terms of original Python 2 compare operator."""
2502 return self.__cmp__(other) < 0
2503
2504 def __gt__(self, other):
2505 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
2506 return self.__cmp__(other) > 0
2507
2508 def __cmp__(self, other):
2509 """
2510 Original Python 2 comparison operator.
2511 Args:
2512 other: Other object to compare to
2513 Returns:
2514 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
2515 """
2516 if other is None:
2517 return 1
2518 if self.author != other.author:
2519 if str(self.author or "") < str(other.author or ""):
2520 return -1
2521 else:
2522 return 1
2523 if self.revision != other.revision:
2524 if str(self.revision or "") < str(other.revision or ""):
2525 return -1
2526 else:
2527 return 1
2528 if self.description != other.description:
2529 if str(self.description or "") < str(other.description or ""):
2530 return -1
2531 else:
2532 return 1
2533 if self.generator != other.generator:
2534 if str(self.generator or "") < str(other.generator or ""):
2535 return -1
2536 else:
2537 return 1
2538 return 0
2539
2540 def _setAuthor(self, value):
2541 """
2542 Property target used to set the author value.
2543 No validations.
2544 """
2545 self._author = value
2546
2547 def _getAuthor(self):
2548 """
2549 Property target used to get the author value.
2550 """
2551 return self._author
2552
2553 def _setRevision(self, value):
2554 """
2555 Property target used to set the revision value.
2556 No validations.
2557 """
2558 self._revision = value
2559
2560 def _getRevision(self):
2561 """
2562 Property target used to get the revision value.
2563 """
2564 return self._revision
2565
2566 def _setDescription(self, value):
2567 """
2568 Property target used to set the description value.
2569 No validations.
2570 """
2571 self._description = value
2572
2573 def _getDescription(self):
2574 """
2575 Property target used to get the description value.
2576 """
2577 return self._description
2578
2579 def _setGenerator(self, value):
2580 """
2581 Property target used to set the generator value.
2582 No validations.
2583 """
2584 self._generator = value
2585
2586 def _getGenerator(self):
2587 """
2588 Property target used to get the generator value.
2589 """
2590 return self._generator
2591
2592 author = property(_getAuthor, _setAuthor, None, "Author of the configuration file.")
2593 revision = property(_getRevision, _setRevision, None, "Revision of the configuration file.")
2594 description = property(_getDescription, _setDescription, None, "Description of the configuration file.")
2595 generator = property(_getGenerator, _setGenerator, None, "Tool that generated the configuration file.")
2596
2597
2598 ########################################################################
2599 # ExtensionsConfig class definition
2600 ########################################################################
2601
2602
2603 @total_ordering
2604 class ExtensionsConfig:
2605 """
2606 Class representing Cedar Backup extensions configuration.
2607
2608 Extensions configuration is used to specify "extended actions" implemented
2609 by code external to Cedar Backup. For instance, a hypothetical third party
2610 might write extension code to collect database repository data. If they
2611 write a properly-formatted extension function, they can use the extension
2612 configuration to map a command-line Cedar Backup action (i.e. "database")
2613 to their function.
2614
2615 The following restrictions exist on data in this class:
2616
2617 - If set, the order mode must be one of the values in ``VALID_ORDER_MODES``
2618 - The actions list must be a list of ``ExtendedAction`` objects.
2619
2620 """
2621
2622 def __init__(self, actions=None, orderMode=None):
2623 """
2624 Constructor for the ``ExtensionsConfig`` class.
2625 Args:
2626 actions: List of extended actions
2627 """
2628 self._orderMode = None
2629 self._actions = None
2630 self.orderMode = orderMode
2631 self.actions = actions
2632
2633 def __repr__(self):
2634 """
2635 Official string representation for class instance.
2636 """
2637 return "ExtensionsConfig(%s, %s)" % (self.orderMode, self.actions)
2638
2639 def __str__(self):
2640 """
2641 Informal string representation for class instance.
2642 """
2643 return self.__repr__()
2644
2645 def __eq__(self, other):
2646 """Equals operator, implemented in terms of original Python 2 compare operator."""
2647 return self.__cmp__(other) == 0
2648
2649 def __lt__(self, other):
2650 """Less-than operator, implemented in terms of original Python 2 compare operator."""
2651 return self.__cmp__(other) < 0
2652
2653 def __gt__(self, other):
2654 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
2655 return self.__cmp__(other) > 0
2656
2657 def __cmp__(self, other):
2658 """
2659 Original Python 2 comparison operator.
2660 Args:
2661 other: Other object to compare to
2662 Returns:
2663 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
2664 """
2665 if other is None:
2666 return 1
2667 if self.orderMode != other.orderMode:
2668 if str(self.orderMode or "") < str(other.orderMode or ""):
2669 return -1
2670 else:
2671 return 1
2672 if self.actions != other.actions:
2673 if self.actions < other.actions:
2674 return -1
2675 else:
2676 return 1
2677 return 0
2678
2679 def _setOrderMode(self, value):
2680 """
2681 Property target used to set the order mode.
2682 The value must be one of :any:`VALID_ORDER_MODES`.
2683 Raises:
2684 ValueError: If the value is not valid
2685 """
2686 if value is not None:
2687 if value not in VALID_ORDER_MODES:
2688 raise ValueError("Order mode must be one of %s." % VALID_ORDER_MODES)
2689 self._orderMode = value
2690
2691 def _getOrderMode(self):
2692 """
2693 Property target used to get the order mode.
2694 """
2695 return self._orderMode
2696
2697 def _setActions(self, value):
2698 """
2699 Property target used to set the actions list.
2700 Either the value must be ``None`` or each element must be an ``ExtendedAction``.
2701 Raises:
2702 ValueError: If the value is not a ``ExtendedAction``
2703 """
2704 if value is None:
2705 self._actions = None
2706 else:
2707 try:
2708 saved = self._actions
2709 self._actions = ObjectTypeList(ExtendedAction, "ExtendedAction")
2710 self._actions.extend(value)
2711 except Exception as e:
2712 self._actions = saved
2713 raise e
2714
2715 def _getActions(self):
2716 """
2717 Property target used to get the actions list.
2718 """
2719 return self._actions
2720
2721 orderMode = property(_getOrderMode, _setOrderMode, None, "Order mode for extensions, to control execution ordering.")
2722 actions = property(_getActions, _setActions, None, "List of extended actions.")
2723
2724
2725 ########################################################################
2726 # OptionsConfig class definition
2727 ########################################################################
2728
2729
2730 @total_ordering
2731 class OptionsConfig:
2732 """
2733 Class representing a Cedar Backup global options configuration.
2734
2735 The options section is used to store global configuration options and
2736 defaults that can be applied to other sections.
2737
2738 The following restrictions exist on data in this class:
2739
2740 - The working directory must be an absolute path.
2741 - The starting day must be a day of the week in English, i.e. ``"monday"``, ``"tuesday"``, etc.
2742 - All of the other values must be non-empty strings if they are set to something other than ``None``.
2743 - The overrides list must be a list of ``CommandOverride`` objects.
2744 - The hooks list must be a list of ``ActionHook`` objects.
2745 - The cback command must be a non-empty string.
2746 - Any managed action name must be a non-empty string matching ``ACTION_NAME_REGEX``
2747
2748 """
2749
2750 def __init__(
2751 self,
2752 startingDay=None,
2753 workingDir=None,
2754 backupUser=None,
2755 backupGroup=None,
2756 rcpCommand=None,
2757 overrides=None,
2758 hooks=None,
2759 rshCommand=None,
2760 cbackCommand=None,
2761 managedActions=None,
2762 ):
2763 """
2764 Constructor for the ``OptionsConfig`` class.
2765
2766 Args:
2767 startingDay: Day that starts the week
2768 workingDir: Working (temporary) directory to use for backups
2769 backupUser: Effective user that backups should run as
2770 backupGroup: Effective group that backups should run as
2771 rcpCommand: Default rcp-compatible copy command for staging
2772 rshCommand: Default rsh-compatible command to use for remote shells
2773 cbackCommand: Default cback-compatible command to use on managed remote peers
2774 overrides: List of configured command path overrides, if any
2775 hooks: List of configured pre- and post-action hooks
2776 managedActions: Default set of actions that are managed on remote peers
2777
2778 Raises:
2779 ValueError: If one of the values is invalid
2780 """
2781 self._startingDay = None
2782 self._workingDir = None
2783 self._backupUser = None
2784 self._backupGroup = None
2785 self._rcpCommand = None
2786 self._rshCommand = None
2787 self._cbackCommand = None
2788 self._overrides = None
2789 self._hooks = None
2790 self._managedActions = None
2791 self.startingDay = startingDay
2792 self.workingDir = workingDir
2793 self.backupUser = backupUser
2794 self.backupGroup = backupGroup
2795 self.rcpCommand = rcpCommand
2796 self.rshCommand = rshCommand
2797 self.cbackCommand = cbackCommand
2798 self.overrides = overrides
2799 self.hooks = hooks
2800 self.managedActions = managedActions
2801
2802 def __repr__(self):
2803 """
2804 Official string representation for class instance.
2805 """
2806 return "OptionsConfig(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (
2807 self.startingDay,
2808 self.workingDir,
2809 self.backupUser,
2810 self.backupGroup,
2811 self.rcpCommand,
2812 self.overrides,
2813 self.hooks,
2814 self.rshCommand,
2815 self.cbackCommand,
2816 self.managedActions,
2817 )
2818
2819 def __str__(self):
2820 """
2821 Informal string representation for class instance.
2822 """
2823 return self.__repr__()
2824
2825 def __eq__(self, other):
2826 """Equals operator, implemented in terms of original Python 2 compare operator."""
2827 return self.__cmp__(other) == 0
2828
2829 def __lt__(self, other):
2830 """Less-than operator, implemented in terms of original Python 2 compare operator."""
2831 return self.__cmp__(other) < 0
2832
2833 def __gt__(self, other):
2834 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
2835 return self.__cmp__(other) > 0
2836
2837 def __cmp__(self, other):
2838 """
2839 Original Python 2 comparison operator.
2840 Args:
2841 other: Other object to compare to
2842 Returns:
2843 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
2844 """
2845 if other is None:
2846 return 1
2847 if self.startingDay != other.startingDay:
2848 if str(self.startingDay or "") < str(other.startingDay or ""):
2849 return -1
2850 else:
2851 return 1
2852 if self.workingDir != other.workingDir:
2853 if str(self.workingDir or "") < str(other.workingDir or ""):
2854 return -1
2855 else:
2856 return 1
2857 if self.backupUser != other.backupUser:
2858 if str(self.backupUser or "") < str(other.backupUser or ""):
2859 return -1
2860 else:
2861 return 1
2862 if self.backupGroup != other.backupGroup:
2863 if str(self.backupGroup or "") < str(other.backupGroup or ""):
2864 return -1
2865 else:
2866 return 1
2867 if self.rcpCommand != other.rcpCommand:
2868 if str(self.rcpCommand or "") < str(other.rcpCommand or ""):
2869 return -1
2870 else:
2871 return 1
2872 if self.rshCommand != other.rshCommand:
2873 if str(self.rshCommand or "") < str(other.rshCommand or ""):
2874 return -1
2875 else:
2876 return 1
2877 if self.cbackCommand != other.cbackCommand:
2878 if str(self.cbackCommand or "") < str(other.cbackCommand or ""):
2879 return -1
2880 else:
2881 return 1
2882 if self.overrides != other.overrides:
2883 if self.overrides < other.overrides:
2884 return -1
2885 else:
2886 return 1
2887 if self.hooks != other.hooks:
2888 if self.hooks < other.hooks:
2889 return -1
2890 else:
2891 return 1
2892 if self.managedActions != other.managedActions:
2893 if self.managedActions < other.managedActions:
2894 return -1
2895 else:
2896 return 1
2897 return 0
2898
2899 def addOverride(self, command, absolutePath):
2900 """
2901 If no override currently exists for the command, add one.
2902 Args:
2903 command: Name of command to be overridden
2904 absolutePath: Absolute path of the overrridden command
2905 """
2906 override = CommandOverride(command, absolutePath)
2907 if self.overrides is None:
2908 self.overrides = [override]
2909 else:
2910 exists = False
2911 for obj in self.overrides:
2912 if obj.command == override.command:
2913 exists = True
2914 break
2915 if not exists:
2916 self.overrides.append(override)
2917
2918 def replaceOverride(self, command, absolutePath):
2919 """
2920 If override currently exists for the command, replace it; otherwise add it.
2921 Args:
2922 command: Name of command to be overridden
2923 absolutePath: Absolute path of the overrridden command
2924 """
2925 override = CommandOverride(command, absolutePath)
2926 if self.overrides is None:
2927 self.overrides = [override]
2928 else:
2929 exists = False
2930 for obj in self.overrides:
2931 if obj.command == override.command:
2932 exists = True
2933 obj.absolutePath = override.absolutePath
2934 break
2935 if not exists:
2936 self.overrides.append(override)
2937
2938 def _setStartingDay(self, value):
2939 """
2940 Property target used to set the starting day.
2941 If it is not ``None``, the value must be a valid English day of the week,
2942 one of ``"monday"``, ``"tuesday"``, ``"wednesday"``, etc.
2943 Raises:
2944 ValueError: If the value is not a valid day of the week
2945 """
2946 if value is not None:
2947 if value not in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]:
2948 raise ValueError('Starting day must be an English day of the week, i.e. "monday".')
2949 self._startingDay = value
2950
2951 def _getStartingDay(self):
2952 """
2953 Property target used to get the starting day.
2954 """
2955 return self._startingDay
2956
2957 def _setWorkingDir(self, value):
2958 """
2959 Property target used to set the working directory.
2960 The value must be an absolute path if it is not ``None``.
2961 It does not have to exist on disk at the time of assignment.
2962 Raises:
2963 ValueError: If the value is not an absolute path
2964 ValueError: If the value cannot be encoded properly
2965 """
2966 if value is not None:
2967 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
2968 raise ValueError("Working directory must be an absolute path.")
2969 self._workingDir = encodePath(value)
2970
2971 def _getWorkingDir(self):
2972 """
2973 Property target used to get the working directory.
2974 """
2975 return self._workingDir
2976
2977 def _setBackupUser(self, value):
2978 """
2979 Property target used to set the backup user.
2980 The value must be a non-empty string if it is not ``None``.
2981 Raises:
2982 ValueError: If the value is an empty string
2983 """
2984 if value is not None:
2985 if len(value) < 1:
2986 raise ValueError("Backup user must be a non-empty string.")
2987 self._backupUser = value
2988
2989 def _getBackupUser(self):
2990 """
2991 Property target used to get the backup user.
2992 """
2993 return self._backupUser
2994
2995 def _setBackupGroup(self, value):
2996 """
2997 Property target used to set the backup group.
2998 The value must be a non-empty string if it is not ``None``.
2999 Raises:
3000 ValueError: If the value is an empty string
3001 """
3002 if value is not None:
3003 if len(value) < 1:
3004 raise ValueError("Backup group must be a non-empty string.")
3005 self._backupGroup = value
3006
3007 def _getBackupGroup(self):
3008 """
3009 Property target used to get the backup group.
3010 """
3011 return self._backupGroup
3012
3013 def _setRcpCommand(self, value):
3014 """
3015 Property target used to set the rcp command.
3016 The value must be a non-empty string if it is not ``None``.
3017 Raises:
3018 ValueError: If the value is an empty string
3019 """
3020 if value is not None:
3021 if len(value) < 1:
3022 raise ValueError("The rcp command must be a non-empty string.")
3023 self._rcpCommand = value
3024
3025 def _getRcpCommand(self):
3026 """
3027 Property target used to get the rcp command.
3028 """
3029 return self._rcpCommand
3030
3031 def _setRshCommand(self, value):
3032 """
3033 Property target used to set the rsh command.
3034 The value must be a non-empty string if it is not ``None``.
3035 Raises:
3036 ValueError: If the value is an empty string
3037 """
3038 if value is not None:
3039 if len(value) < 1:
3040 raise ValueError("The rsh command must be a non-empty string.")
3041 self._rshCommand = value
3042
3043 def _getRshCommand(self):
3044 """
3045 Property target used to get the rsh command.
3046 """
3047 return self._rshCommand
3048
3049 def _setCbackCommand(self, value):
3050 """
3051 Property target used to set the cback command.
3052 The value must be a non-empty string if it is not ``None``.
3053 Raises:
3054 ValueError: If the value is an empty string
3055 """
3056 if value is not None:
3057 if len(value) < 1:
3058 raise ValueError("The cback command must be a non-empty string.")
3059 self._cbackCommand = value
3060
3061 def _getCbackCommand(self):
3062 """
3063 Property target used to get the cback command.
3064 """
3065 return self._cbackCommand
3066
3067 def _setOverrides(self, value):
3068 """
3069 Property target used to set the command path overrides list.
3070 Either the value must be ``None`` or each element must be a ``CommandOverride``.
3071 Raises:
3072 ValueError: If the value is not a ``CommandOverride``
3073 """
3074 if value is None:
3075 self._overrides = None
3076 else:
3077 try:
3078 saved = self._overrides
3079 self._overrides = ObjectTypeList(CommandOverride, "CommandOverride")
3080 self._overrides.extend(value)
3081 except Exception as e:
3082 self._overrides = saved
3083 raise e
3084
3085 def _getOverrides(self):
3086 """
3087 Property target used to get the command path overrides list.
3088 """
3089 return self._overrides
3090
3091 def _setHooks(self, value):
3092 """
3093 Property target used to set the pre- and post-action hooks list.
3094 Either the value must be ``None`` or each element must be an ``ActionHook``.
3095 Raises:
3096 ValueError: If the value is not a ``CommandOverride``
3097 """
3098 if value is None:
3099 self._hooks = None
3100 else:
3101 try:
3102 saved = self._hooks
3103 self._hooks = ObjectTypeList(ActionHook, "ActionHook")
3104 self._hooks.extend(value)
3105 except Exception as e:
3106 self._hooks = saved
3107 raise e
3108
3109 def _getHooks(self):
3110 """
3111 Property target used to get the command path hooks list.
3112 """
3113 return self._hooks
3114
3115 def _setManagedActions(self, value):
3116 """
3117 Property target used to set the managed actions list.
3118 Elements do not have to exist on disk at the time of assignment.
3119 """
3120 if value is None:
3121 self._managedActions = None
3122 else:
3123 try:
3124 saved = self._managedActions
3125 self._managedActions = RegexMatchList(ACTION_NAME_REGEX, emptyAllowed=False, prefix="Action name")
3126 self._managedActions.extend(value)
3127 except Exception as e:
3128 self._managedActions = saved
3129 raise e
3130
3131 def _getManagedActions(self):
3132 """
3133 Property target used to get the managed actions list.
3134 """
3135 return self._managedActions
3136
3137 startingDay = property(_getStartingDay, _setStartingDay, None, "Day that starts the week.")
3138 workingDir = property(_getWorkingDir, _setWorkingDir, None, "Working (temporary) directory to use for backups.")
3139 backupUser = property(_getBackupUser, _setBackupUser, None, "Effective user that backups should run as.")
3140 backupGroup = property(_getBackupGroup, _setBackupGroup, None, "Effective group that backups should run as.")
3141 rcpCommand = property(_getRcpCommand, _setRcpCommand, None, "Default rcp-compatible copy command for staging.")
3142 rshCommand = property(_getRshCommand, _setRshCommand, None, "Default rsh-compatible command to use for remote shells.")
3143 cbackCommand = property(
3144 _getCbackCommand, _setCbackCommand, None, "Default cback-compatible command to use on managed remote peers."
3145 )
3146 overrides = property(_getOverrides, _setOverrides, None, "List of configured command path overrides, if any.")
3147 hooks = property(_getHooks, _setHooks, None, "List of configured pre- and post-action hooks.")
3148 managedActions = property(
3149 _getManagedActions, _setManagedActions, None, "Default set of actions that are managed on remote peers."
3150 )
3151
3152
3153 ########################################################################
3154 # PeersConfig class definition
3155 ########################################################################
3156
3157
3158 @total_ordering
3159 class PeersConfig:
3160 """
3161 Class representing Cedar Backup global peer configuration.
3162
3163 This section contains a list of local and remote peers in a master's backup
3164 pool. The section is optional. If a master does not define this section,
3165 then all peers are unmanaged, and the stage configuration section must
3166 explicitly list any peer that is to be staged. If this section is
3167 configured, then peers may be managed or unmanaged, and the stage section
3168 peer configuration (if any) completely overrides this configuration.
3169
3170 The following restrictions exist on data in this class:
3171
3172 - The list of local peers must contain only ``LocalPeer`` objects
3173 - The list of remote peers must contain only ``RemotePeer`` objects
3174
3175 *Note:* Lists within this class are "unordered" for equality comparisons.
3176
3177 """
3178
3179 def __init__(self, localPeers=None, remotePeers=None):
3180 """
3181 Constructor for the ``PeersConfig`` class.
3182
3183 Args:
3184 localPeers: List of local peers
3185 remotePeers: List of remote peers
3186
3187 Raises:
3188 ValueError: If one of the values is invalid
3189 """
3190 self._localPeers = None
3191 self._remotePeers = None
3192 self.localPeers = localPeers
3193 self.remotePeers = remotePeers
3194
3195 def __repr__(self):
3196 """
3197 Official string representation for class instance.
3198 """
3199 return "PeersConfig(%s, %s)" % (self.localPeers, self.remotePeers)
3200
3201 def __str__(self):
3202 """
3203 Informal string representation for class instance.
3204 """
3205 return self.__repr__()
3206
3207 def __eq__(self, other):
3208 """Equals operator, implemented in terms of original Python 2 compare operator."""
3209 return self.__cmp__(other) == 0
3210
3211 def __lt__(self, other):
3212 """Less-than operator, implemented in terms of original Python 2 compare operator."""
3213 return self.__cmp__(other) < 0
3214
3215 def __gt__(self, other):
3216 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
3217 return self.__cmp__(other) > 0
3218
3219 def __cmp__(self, other):
3220 """
3221 Original Python 2 comparison operator.
3222 Lists within this class are "unordered" for equality comparisons.
3223 Args:
3224 other: Other object to compare to
3225 Returns:
3226 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
3227 """
3228 if other is None:
3229 return 1
3230 if self.localPeers != other.localPeers:
3231 if self.localPeers < other.localPeers:
3232 return -1
3233 else:
3234 return 1
3235 if self.remotePeers != other.remotePeers:
3236 if self.remotePeers < other.remotePeers:
3237 return -1
3238 else:
3239 return 1
3240 return 0
3241
3242 def hasPeers(self):
3243 """
3244 Indicates whether any peers are filled into this object.
3245 Returns:
3246 Boolean true if any local or remote peers are filled in, false otherwise
3247 """
3248 return (self.localPeers is not None and len(self.localPeers) > 0) or (
3249 self.remotePeers is not None and len(self.remotePeers) > 0
3250 )
3251
3252 def _setLocalPeers(self, value):
3253 """
3254 Property target used to set the local peers list.
3255 Either the value must be ``None`` or each element must be a ``LocalPeer``.
3256 Raises:
3257 ValueError: If the value is not an absolute path
3258 """
3259 if value is None:
3260 self._localPeers = None
3261 else:
3262 try:
3263 saved = self._localPeers
3264 self._localPeers = ObjectTypeList(LocalPeer, "LocalPeer")
3265 self._localPeers.extend(value)
3266 except Exception as e:
3267 self._localPeers = saved
3268 raise e
3269
3270 def _getLocalPeers(self):
3271 """
3272 Property target used to get the local peers list.
3273 """
3274 return self._localPeers
3275
3276 def _setRemotePeers(self, value):
3277 """
3278 Property target used to set the remote peers list.
3279 Either the value must be ``None`` or each element must be a ``RemotePeer``.
3280 Raises:
3281 ValueError: If the value is not a ``RemotePeer``
3282 """
3283 if value is None:
3284 self._remotePeers = None
3285 else:
3286 try:
3287 saved = self._remotePeers
3288 self._remotePeers = ObjectTypeList(RemotePeer, "RemotePeer")
3289 self._remotePeers.extend(value)
3290 except Exception as e:
3291 self._remotePeers = saved
3292 raise e
3293
3294 def _getRemotePeers(self):
3295 """
3296 Property target used to get the remote peers list.
3297 """
3298 return self._remotePeers
3299
3300 localPeers = property(_getLocalPeers, _setLocalPeers, None, "List of local peers.")
3301 remotePeers = property(_getRemotePeers, _setRemotePeers, None, "List of remote peers.")
3302
3303
3304 ########################################################################
3305 # CollectConfig class definition
3306 ########################################################################
3307
3308
3309 @total_ordering
3310 class CollectConfig:
3311 """
3312 Class representing a Cedar Backup collect configuration.
3313
3314 The following restrictions exist on data in this class:
3315
3316 - The target directory must be an absolute path.
3317 - The collect mode must be one of the values in :any:`VALID_COLLECT_MODES`.
3318 - The archive mode must be one of the values in :any:`VALID_ARCHIVE_MODES`.
3319 - The ignore file must be a non-empty string.
3320 - Each of the paths in ``absoluteExcludePaths`` must be an absolute path
3321 - The collect file list must be a list of ``CollectFile`` objects.
3322 - The collect directory list must be a list of ``CollectDir`` objects.
3323
3324 For the ``absoluteExcludePaths`` list, validation is accomplished through the
3325 :any:`util.AbsolutePathList` list implementation that overrides common list
3326 methods and transparently does the absolute path validation for us.
3327
3328 For the ``collectFiles`` and ``collectDirs`` list, validation is accomplished
3329 through the :any:`util.ObjectTypeList` list implementation that overrides common
3330 list methods and transparently ensures that each element has an appropriate
3331 type.
3332
3333 *Note:* Lists within this class are "unordered" for equality comparisons.
3334
3335 """
3336
3337 def __init__(
3338 self,
3339 targetDir=None,
3340 collectMode=None,
3341 archiveMode=None,
3342 ignoreFile=None,
3343 absoluteExcludePaths=None,
3344 excludePatterns=None,
3345 collectFiles=None,
3346 collectDirs=None,
3347 ):
3348 """
3349 Constructor for the ``CollectConfig`` class.
3350
3351 Args:
3352 targetDir: Directory to collect files into
3353 collectMode: Default collect mode
3354 archiveMode: Default archive mode for collect files
3355 ignoreFile: Default ignore file name
3356 absoluteExcludePaths: List of absolute paths to exclude
3357 excludePatterns: List of regular expression patterns to exclude
3358 collectFiles: List of collect files
3359 collectDirs: List of collect directories
3360
3361 Raises:
3362 ValueError: If one of the values is invalid
3363 """
3364 self._targetDir = None
3365 self._collectMode = None
3366 self._archiveMode = None
3367 self._ignoreFile = None
3368 self._absoluteExcludePaths = None
3369 self._excludePatterns = None
3370 self._collectFiles = None
3371 self._collectDirs = None
3372 self.targetDir = targetDir
3373 self.collectMode = collectMode
3374 self.archiveMode = archiveMode
3375 self.ignoreFile = ignoreFile
3376 self.absoluteExcludePaths = absoluteExcludePaths
3377 self.excludePatterns = excludePatterns
3378 self.collectFiles = collectFiles
3379 self.collectDirs = collectDirs
3380
3381 def __repr__(self):
3382 """
3383 Official string representation for class instance.
3384 """
3385 return "CollectConfig(%s, %s, %s, %s, %s, %s, %s, %s)" % (
3386 self.targetDir,
3387 self.collectMode,
3388 self.archiveMode,
3389 self.ignoreFile,
3390 self.absoluteExcludePaths,
3391 self.excludePatterns,
3392 self.collectFiles,
3393 self.collectDirs,
3394 )
3395
3396 def __str__(self):
3397 """
3398 Informal string representation for class instance.
3399 """
3400 return self.__repr__()
3401
3402 def __eq__(self, other):
3403 """Equals operator, implemented in terms of original Python 2 compare operator."""
3404 return self.__cmp__(other) == 0
3405
3406 def __lt__(self, other):
3407 """Less-than operator, implemented in terms of original Python 2 compare operator."""
3408 return self.__cmp__(other) < 0
3409
3410 def __gt__(self, other):
3411 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
3412 return self.__cmp__(other) > 0
3413
3414 def __cmp__(self, other):
3415 """
3416 Original Python 2 comparison operator.
3417 Lists within this class are "unordered" for equality comparisons.
3418 Args:
3419 other: Other object to compare to
3420 Returns:
3421 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
3422 """
3423 if other is None:
3424 return 1
3425 if self.targetDir != other.targetDir:
3426 if str(self.targetDir or "") < str(other.targetDir or ""):
3427 return -1
3428 else:
3429 return 1
3430 if self.collectMode != other.collectMode:
3431 if str(self.collectMode or "") < str(other.collectMode or ""):
3432 return -1
3433 else:
3434 return 1
3435 if self.archiveMode != other.archiveMode:
3436 if str(self.archiveMode or "") < str(other.archiveMode or ""):
3437 return -1
3438 else:
3439 return 1
3440 if self.ignoreFile != other.ignoreFile:
3441 if str(self.ignoreFile or "") < str(other.ignoreFile or ""):
3442 return -1
3443 else:
3444 return 1
3445 if self.absoluteExcludePaths != other.absoluteExcludePaths:
3446 if self.absoluteExcludePaths < other.absoluteExcludePaths:
3447 return -1
3448 else:
3449 return 1
3450 if self.excludePatterns != other.excludePatterns:
3451 if self.excludePatterns < other.excludePatterns:
3452 return -1
3453 else:
3454 return 1
3455 if self.collectFiles != other.collectFiles:
3456 if self.collectFiles < other.collectFiles:
3457 return -1
3458 else:
3459 return 1
3460 if self.collectDirs != other.collectDirs:
3461 if self.collectDirs < other.collectDirs:
3462 return -1
3463 else:
3464 return 1
3465 return 0
3466
3467 def _setTargetDir(self, value):
3468 """
3469 Property target used to set the target directory.
3470 The value must be an absolute path if it is not ``None``.
3471 It does not have to exist on disk at the time of assignment.
3472 Raises:
3473 ValueError: If the value is not an absolute path
3474 ValueError: If the value cannot be encoded properly
3475 """
3476 if value is not None:
3477 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
3478 raise ValueError("Target directory must be an absolute path.")
3479 self._targetDir = encodePath(value)
3480
3481 def _getTargetDir(self):
3482 """
3483 Property target used to get the target directory.
3484 """
3485 return self._targetDir
3486
3487 def _setCollectMode(self, value):
3488 """
3489 Property target used to set the collect mode.
3490 If not ``None``, the mode must be one of :any:`VALID_COLLECT_MODES`.
3491 Raises:
3492 ValueError: If the value is not valid
3493 """
3494 if value is not None:
3495 if value not in VALID_COLLECT_MODES:
3496 raise ValueError("Collect mode must be one of %s." % VALID_COLLECT_MODES)
3497 self._collectMode = value
3498
3499 def _getCollectMode(self):
3500 """
3501 Property target used to get the collect mode.
3502 """
3503 return self._collectMode
3504
3505 def _setArchiveMode(self, value):
3506 """
3507 Property target used to set the archive mode.
3508 If not ``None``, the mode must be one of :any:`VALID_ARCHIVE_MODES`.
3509 Raises:
3510 ValueError: If the value is not valid
3511 """
3512 if value is not None:
3513 if value not in VALID_ARCHIVE_MODES:
3514 raise ValueError("Archive mode must be one of %s." % VALID_ARCHIVE_MODES)
3515 self._archiveMode = value
3516
3517 def _getArchiveMode(self):
3518 """
3519 Property target used to get the archive mode.
3520 """
3521 return self._archiveMode
3522
3523 def _setIgnoreFile(self, value):
3524 """
3525 Property target used to set the ignore file.
3526 The value must be a non-empty string if it is not ``None``.
3527 Raises:
3528 ValueError: If the value is an empty string
3529 ValueError: If the value cannot be encoded properly
3530 """
3531 if value is not None:
3532 if len(value) < 1:
3533 raise ValueError("The ignore file must be a non-empty string.")
3534 self._ignoreFile = encodePath(value)
3535
3536 def _getIgnoreFile(self):
3537 """
3538 Property target used to get the ignore file.
3539 """
3540 return self._ignoreFile
3541
3542 def _setAbsoluteExcludePaths(self, value):
3543 """
3544 Property target used to set the absolute exclude paths list.
3545 Either the value must be ``None`` or each element must be an absolute path.
3546 Elements do not have to exist on disk at the time of assignment.
3547 Raises:
3548 ValueError: If the value is not an absolute path
3549 """
3550 if value is None:
3551 self._absoluteExcludePaths = None
3552 else:
3553 try:
3554 saved = self._absoluteExcludePaths
3555 self._absoluteExcludePaths = AbsolutePathList()
3556 self._absoluteExcludePaths.extend(value)
3557 except Exception as e:
3558 self._absoluteExcludePaths = saved
3559 raise e
3560
3561 def _getAbsoluteExcludePaths(self):
3562 """
3563 Property target used to get the absolute exclude paths list.
3564 """
3565 return self._absoluteExcludePaths
3566
3567 def _setExcludePatterns(self, value):
3568 """
3569 Property target used to set the exclude patterns list.
3570 """
3571 if value is None:
3572 self._excludePatterns = None
3573 else:
3574 try:
3575 saved = self._excludePatterns
3576 self._excludePatterns = RegexList()
3577 self._excludePatterns.extend(value)
3578 except Exception as e:
3579 self._excludePatterns = saved
3580 raise e
3581
3582 def _getExcludePatterns(self):
3583 """
3584 Property target used to get the exclude patterns list.
3585 """
3586 return self._excludePatterns
3587
3588 def _setCollectFiles(self, value):
3589 """
3590 Property target used to set the collect files list.
3591 Either the value must be ``None`` or each element must be a ``CollectFile``.
3592 Raises:
3593 ValueError: If the value is not a ``CollectFile``
3594 """
3595 if value is None:
3596 self._collectFiles = None
3597 else:
3598 try:
3599 saved = self._collectFiles
3600 self._collectFiles = ObjectTypeList(CollectFile, "CollectFile")
3601 self._collectFiles.extend(value)
3602 except Exception as e:
3603 self._collectFiles = saved
3604 raise e
3605
3606 def _getCollectFiles(self):
3607 """
3608 Property target used to get the collect files list.
3609 """
3610 return self._collectFiles
3611
3612 def _setCollectDirs(self, value):
3613 """
3614 Property target used to set the collect dirs list.
3615 Either the value must be ``None`` or each element must be a ``CollectDir``.
3616 Raises:
3617 ValueError: If the value is not a ``CollectDir``
3618 """
3619 if value is None:
3620 self._collectDirs = None
3621 else:
3622 try:
3623 saved = self._collectDirs
3624 self._collectDirs = ObjectTypeList(CollectDir, "CollectDir")
3625 self._collectDirs.extend(value)
3626 except Exception as e:
3627 self._collectDirs = saved
3628 raise e
3629
3630 def _getCollectDirs(self):
3631 """
3632 Property target used to get the collect dirs list.
3633 """
3634 return self._collectDirs
3635
3636 targetDir = property(_getTargetDir, _setTargetDir, None, "Directory to collect files into.")
3637 collectMode = property(_getCollectMode, _setCollectMode, None, "Default collect mode.")
3638 archiveMode = property(_getArchiveMode, _setArchiveMode, None, "Default archive mode for collect files.")
3639 ignoreFile = property(_getIgnoreFile, _setIgnoreFile, None, "Default ignore file name.")
3640 absoluteExcludePaths = property(_getAbsoluteExcludePaths, _setAbsoluteExcludePaths, None, "List of absolute paths to exclude.")
3641 excludePatterns = property(_getExcludePatterns, _setExcludePatterns, None, "List of regular expressions patterns to exclude.")
3642 collectFiles = property(_getCollectFiles, _setCollectFiles, None, "List of collect files.")
3643 collectDirs = property(_getCollectDirs, _setCollectDirs, None, "List of collect directories.")
3644
3645
3646 ########################################################################
3647 # StageConfig class definition
3648 ########################################################################
3649
3650
3651 @total_ordering
3652 class StageConfig:
3653 """
3654 Class representing a Cedar Backup stage configuration.
3655
3656 The following restrictions exist on data in this class:
3657
3658 - The target directory must be an absolute path
3659 - The list of local peers must contain only ``LocalPeer`` objects
3660 - The list of remote peers must contain only ``RemotePeer`` objects
3661
3662 *Note:* Lists within this class are "unordered" for equality comparisons.
3663
3664 """
3665
3666 def __init__(self, targetDir=None, localPeers=None, remotePeers=None):
3667 """
3668 Constructor for the ``StageConfig`` class.
3669
3670 Args:
3671 targetDir: Directory to stage files into, by peer name
3672 localPeers: List of local peers
3673 remotePeers: List of remote peers
3674
3675 Raises:
3676 ValueError: If one of the values is invalid
3677 """
3678 self._targetDir = None
3679 self._localPeers = None
3680 self._remotePeers = None
3681 self.targetDir = targetDir
3682 self.localPeers = localPeers
3683 self.remotePeers = remotePeers
3684
3685 def __repr__(self):
3686 """
3687 Official string representation for class instance.
3688 """
3689 return "StageConfig(%s, %s, %s)" % (self.targetDir, self.localPeers, self.remotePeers)
3690
3691 def __str__(self):
3692 """
3693 Informal string representation for class instance.
3694 """
3695 return self.__repr__()
3696
3697 def __eq__(self, other):
3698 """Equals operator, implemented in terms of original Python 2 compare operator."""
3699 return self.__cmp__(other) == 0
3700
3701 def __lt__(self, other):
3702 """Less-than operator, implemented in terms of original Python 2 compare operator."""
3703 return self.__cmp__(other) < 0
3704
3705 def __gt__(self, other):
3706 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
3707 return self.__cmp__(other) > 0
3708
3709 def __cmp__(self, other):
3710 """
3711 Original Python 2 comparison operator.
3712 Lists within this class are "unordered" for equality comparisons.
3713 Args:
3714 other: Other object to compare to
3715 Returns:
3716 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
3717 """
3718 if other is None:
3719 return 1
3720 if self.targetDir != other.targetDir:
3721 if str(self.targetDir or "") < str(other.targetDir or ""):
3722 return -1
3723 else:
3724 return 1
3725 if self.localPeers != other.localPeers:
3726 if self.localPeers < other.localPeers:
3727 return -1
3728 else:
3729 return 1
3730 if self.remotePeers != other.remotePeers:
3731 if self.remotePeers < other.remotePeers:
3732 return -1
3733 else:
3734 return 1
3735 return 0
3736
3737 def hasPeers(self):
3738 """
3739 Indicates whether any peers are filled into this object.
3740 Returns:
3741 Boolean true if any local or remote peers are filled in, false otherwise
3742 """
3743 return (self.localPeers is not None and len(self.localPeers) > 0) or (
3744 self.remotePeers is not None and len(self.remotePeers) > 0
3745 )
3746
3747 def _setTargetDir(self, value):
3748 """
3749 Property target used to set the target directory.
3750 The value must be an absolute path if it is not ``None``.
3751 It does not have to exist on disk at the time of assignment.
3752 Raises:
3753 ValueError: If the value is not an absolute path
3754 ValueError: If the value cannot be encoded properly
3755 """
3756 if value is not None:
3757 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
3758 raise ValueError("Target directory must be an absolute path.")
3759 self._targetDir = encodePath(value)
3760
3761 def _getTargetDir(self):
3762 """
3763 Property target used to get the target directory.
3764 """
3765 return self._targetDir
3766
3767 def _setLocalPeers(self, value):
3768 """
3769 Property target used to set the local peers list.
3770 Either the value must be ``None`` or each element must be a ``LocalPeer``.
3771 Raises:
3772 ValueError: If the value is not an absolute path
3773 """
3774 if value is None:
3775 self._localPeers = None
3776 else:
3777 try:
3778 saved = self._localPeers
3779 self._localPeers = ObjectTypeList(LocalPeer, "LocalPeer")
3780 self._localPeers.extend(value)
3781 except Exception as e:
3782 self._localPeers = saved
3783 raise e
3784
3785 def _getLocalPeers(self):
3786 """
3787 Property target used to get the local peers list.
3788 """
3789 return self._localPeers
3790
3791 def _setRemotePeers(self, value):
3792 """
3793 Property target used to set the remote peers list.
3794 Either the value must be ``None`` or each element must be a ``RemotePeer``.
3795 Raises:
3796 ValueError: If the value is not a ``RemotePeer``
3797 """
3798 if value is None:
3799 self._remotePeers = None
3800 else:
3801 try:
3802 saved = self._remotePeers
3803 self._remotePeers = ObjectTypeList(RemotePeer, "RemotePeer")
3804 self._remotePeers.extend(value)
3805 except Exception as e:
3806 self._remotePeers = saved
3807 raise e
3808
3809 def _getRemotePeers(self):
3810 """
3811 Property target used to get the remote peers list.
3812 """
3813 return self._remotePeers
3814
3815 targetDir = property(_getTargetDir, _setTargetDir, None, "Directory to stage files into, by peer name.")
3816 localPeers = property(_getLocalPeers, _setLocalPeers, None, "List of local peers.")
3817 remotePeers = property(_getRemotePeers, _setRemotePeers, None, "List of remote peers.")
3818
3819
3820 ########################################################################
3821 # StoreConfig class definition
3822 ########################################################################
3823
3824
3825 @total_ordering
3826 class StoreConfig:
3827 """
3828 Class representing a Cedar Backup store configuration.
3829
3830 The following restrictions exist on data in this class:
3831
3832 - The source directory must be an absolute path.
3833 - The media type must be one of the values in :any:`VALID_MEDIA_TYPES`.
3834 - The device type must be one of the values in :any:`VALID_DEVICE_TYPES`.
3835 - The device path must be an absolute path.
3836 - The SCSI id, if provided, must be in the form specified by :any:`validateScsiId`.
3837 - The drive speed must be an integer >= 1
3838 - The blanking behavior must be a ``BlankBehavior`` object
3839 - The refresh media delay must be an integer >= 0
3840 - The eject delay must be an integer >= 0
3841
3842 Note that although the blanking factor must be a positive floating point
3843 number, it is stored as a string. This is done so that we can losslessly go
3844 back and forth between XML and object representations of configuration.
3845
3846 """
3847
3848 def __init__(
3849 self,
3850 sourceDir=None,
3851 mediaType=None,
3852 deviceType=None,
3853 devicePath=None,
3854 deviceScsiId=None,
3855 driveSpeed=None,
3856 checkData=False,
3857 warnMidnite=False,
3858 noEject=False,
3859 checkMedia=False,
3860 blankBehavior=None,
3861 refreshMediaDelay=None,
3862 ejectDelay=None,
3863 ):
3864 """
3865 Constructor for the ``StoreConfig`` class.
3866
3867 Args:
3868 sourceDir: Directory whose contents should be written to media
3869 mediaType: Type of the media (see notes above)
3870 deviceType: Type of the device (optional, see notes above)
3871 devicePath: Filesystem device name for writer device, i.e. ``/dev/cdrw``
3872 deviceScsiId: SCSI id for writer device, i.e. ``[<method>:]scsibus,target,lun``
3873 driveSpeed: Speed of the drive, i.e. ``2`` for 2x drive, etc
3874 checkData: Whether resulting image should be validated
3875 checkMedia: Whether media should be checked before being written to
3876 warnMidnite: Whether to generate warnings for crossing midnite
3877 noEject: Indicates that the writer device should not be ejected
3878 blankBehavior: Controls optimized blanking behavior
3879 refreshMediaDelay: Delay, in seconds, to add after refreshing media
3880 ejectDelay: Delay, in seconds, to add after ejecting media before closing the tray
3881
3882 Raises:
3883 ValueError: If one of the values is invalid
3884 """
3885 self._sourceDir = None
3886 self._mediaType = None
3887 self._deviceType = None
3888 self._devicePath = None
3889 self._deviceScsiId = None
3890 self._driveSpeed = None
3891 self._checkData = None
3892 self._checkMedia = None
3893 self._warnMidnite = None
3894 self._noEject = None
3895 self._blankBehavior = None
3896 self._refreshMediaDelay = None
3897 self._ejectDelay = None
3898 self.sourceDir = sourceDir
3899 self.mediaType = mediaType
3900 self.deviceType = deviceType
3901 self.devicePath = devicePath
3902 self.deviceScsiId = deviceScsiId
3903 self.driveSpeed = driveSpeed
3904 self.checkData = checkData
3905 self.checkMedia = checkMedia
3906 self.warnMidnite = warnMidnite
3907 self.noEject = noEject
3908 self.blankBehavior = blankBehavior
3909 self.refreshMediaDelay = refreshMediaDelay
3910 self.ejectDelay = ejectDelay
3911
3912 def __repr__(self):
3913 """
3914 Official string representation for class instance.
3915 """
3916 return "StoreConfig(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (
3917 self.sourceDir,
3918 self.mediaType,
3919 self.deviceType,
3920 self.devicePath,
3921 self.deviceScsiId,
3922 self.driveSpeed,
3923 self.checkData,
3924 self.warnMidnite,
3925 self.noEject,
3926 self.checkMedia,
3927 self.blankBehavior,
3928 self.refreshMediaDelay,
3929 self.ejectDelay,
3930 )
3931
3932 def __str__(self):
3933 """
3934 Informal string representation for class instance.
3935 """
3936 return self.__repr__()
3937
3938 def __eq__(self, other):
3939 """Equals operator, implemented in terms of original Python 2 compare operator."""
3940 return self.__cmp__(other) == 0
3941
3942 def __lt__(self, other):
3943 """Less-than operator, implemented in terms of original Python 2 compare operator."""
3944 return self.__cmp__(other) < 0
3945
3946 def __gt__(self, other):
3947 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
3948 return self.__cmp__(other) > 0
3949
3950 def __cmp__(self, other):
3951 """
3952 Original Python 2 comparison operator.
3953 Args:
3954 other: Other object to compare to
3955 Returns:
3956 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
3957 """
3958 if other is None:
3959 return 1
3960 if self.sourceDir != other.sourceDir:
3961 if str(self.sourceDir or "") < str(other.sourceDir or ""):
3962 return -1
3963 else:
3964 return 1
3965 if self.mediaType != other.mediaType:
3966 if str(self.mediaType or "") < str(other.mediaType or ""):
3967 return -1
3968 else:
3969 return 1
3970 if self.deviceType != other.deviceType:
3971 if str(self.deviceType or "") < str(other.deviceType or ""):
3972 return -1
3973 else:
3974 return 1
3975 if self.devicePath != other.devicePath:
3976 if str(self.devicePath or "") < str(other.devicePath or ""):
3977 return -1
3978 else:
3979 return 1
3980 if self.deviceScsiId != other.deviceScsiId:
3981 if str(self.deviceScsiId or "") < str(other.deviceScsiId or ""):
3982 return -1
3983 else:
3984 return 1
3985 if self.driveSpeed != other.driveSpeed:
3986 if str(self.driveSpeed or "") < str(other.driveSpeed or ""):
3987 return -1
3988 else:
3989 return 1
3990 if self.checkData != other.checkData:
3991 if self.checkData < other.checkData:
3992 return -1
3993 else:
3994 return 1
3995 if self.checkMedia != other.checkMedia:
3996 if self.checkMedia < other.checkMedia:
3997 return -1
3998 else:
3999 return 1
4000 if self.warnMidnite != other.warnMidnite:
4001 if self.warnMidnite < other.warnMidnite:
4002 return -1
4003 else:
4004 return 1
4005 if self.noEject != other.noEject:
4006 if self.noEject < other.noEject:
4007 return -1
4008 else:
4009 return 1
4010 if self.blankBehavior != other.blankBehavior:
4011 if str(self.blankBehavior or "") < str(other.blankBehavior or ""):
4012 return -1
4013 else:
4014 return 1
4015 if self.refreshMediaDelay != other.refreshMediaDelay:
4016 if int(self.refreshMediaDelay or 0) < int(other.refreshMediaDelay or 0):
4017 return -1
4018 else:
4019 return 1
4020 if self.ejectDelay != other.ejectDelay:
4021 if int(self.ejectDelay or 0) < int(other.ejectDelay or 0):
4022 return -1
4023 else:
4024 return 1
4025 return 0
4026
4027 def _setSourceDir(self, value):
4028 """
4029 Property target used to set the source directory.
4030 The value must be an absolute path if it is not ``None``.
4031 It does not have to exist on disk at the time of assignment.
4032 Raises:
4033 ValueError: If the value is not an absolute path
4034 ValueError: If the value cannot be encoded properly
4035 """
4036 if value is not None:
4037 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
4038 raise ValueError("Source directory must be an absolute path.")
4039 self._sourceDir = encodePath(value)
4040
4041 def _getSourceDir(self):
4042 """
4043 Property target used to get the source directory.
4044 """
4045 return self._sourceDir
4046
4047 def _setMediaType(self, value):
4048 """
4049 Property target used to set the media type.
4050 The value must be one of :any:`VALID_MEDIA_TYPES`.
4051 Raises:
4052 ValueError: If the value is not valid
4053 """
4054 if value is not None:
4055 if value not in VALID_MEDIA_TYPES:
4056 raise ValueError("Media type must be one of %s." % VALID_MEDIA_TYPES)
4057 self._mediaType = value
4058
4059 def _getMediaType(self):
4060 """
4061 Property target used to get the media type.
4062 """
4063 return self._mediaType
4064
4065 def _setDeviceType(self, value):
4066 """
4067 Property target used to set the device type.
4068 The value must be one of :any:`VALID_DEVICE_TYPES`.
4069 Raises:
4070 ValueError: If the value is not valid
4071 """
4072 if value is not None:
4073 if value not in VALID_DEVICE_TYPES:
4074 raise ValueError("Device type must be one of %s." % VALID_DEVICE_TYPES)
4075 self._deviceType = value
4076
4077 def _getDeviceType(self):
4078 """
4079 Property target used to get the device type.
4080 """
4081 return self._deviceType
4082
4083 def _setDevicePath(self, value):
4084 """
4085 Property target used to set the device path.
4086 The value must be an absolute path if it is not ``None``.
4087 It does not have to exist on disk at the time of assignment.
4088 Raises:
4089 ValueError: If the value is not an absolute path
4090 ValueError: If the value cannot be encoded properly
4091 """
4092 if value is not None:
4093 if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows
4094 raise ValueError("Device path must be an absolute path.")
4095 self._devicePath = encodePath(value)
4096
4097 def _getDevicePath(self):
4098 """
4099 Property target used to get the device path.
4100 """
4101 return self._devicePath
4102
4103 def _setDeviceScsiId(self, value):
4104 """
4105 Property target used to set the SCSI id
4106 The SCSI id must be valid per :any:`validateScsiId`.
4107 Raises:
4108 ValueError: If the value is not valid
4109 """
4110 if value is None:
4111 self._deviceScsiId = None
4112 else:
4113 self._deviceScsiId = validateScsiId(value)
4114
4115 def _getDeviceScsiId(self):
4116 """
4117 Property target used to get the SCSI id.
4118 """
4119 return self._deviceScsiId
4120
4121 def _setDriveSpeed(self, value):
4122 """
4123 Property target used to set the drive speed.
4124 The drive speed must be valid per :any:`validateDriveSpeed`.
4125 Raises:
4126 ValueError: If the value is not valid
4127 """
4128 self._driveSpeed = validateDriveSpeed(value)
4129
4130 def _getDriveSpeed(self):
4131 """
4132 Property target used to get the drive speed.
4133 """
4134 return self._driveSpeed
4135
4136 def _setCheckData(self, value):
4137 """
4138 Property target used to set the check data flag.
4139 No validations, but we normalize the value to ``True`` or ``False``.
4140 """
4141 if value:
4142 self._checkData = True
4143 else:
4144 self._checkData = False
4145
4146 def _getCheckData(self):
4147 """
4148 Property target used to get the check data flag.
4149 """
4150 return self._checkData
4151
4152 def _setCheckMedia(self, value):
4153 """
4154 Property target used to set the check media flag.
4155 No validations, but we normalize the value to ``True`` or ``False``.
4156 """
4157 if value:
4158 self._checkMedia = True
4159 else:
4160 self._checkMedia = False
4161
4162 def _getCheckMedia(self):
4163 """
4164 Property target used to get the check media flag.
4165 """
4166 return self._checkMedia
4167
4168 def _setWarnMidnite(self, value):
4169 """
4170 Property target used to set the midnite warning flag.
4171 No validations, but we normalize the value to ``True`` or ``False``.
4172 """
4173 if value:
4174 self._warnMidnite = True
4175 else:
4176 self._warnMidnite = False
4177
4178 def _getWarnMidnite(self):
4179 """
4180 Property target used to get the midnite warning flag.
4181 """
4182 return self._warnMidnite
4183
4184 def _setNoEject(self, value):
4185 """
4186 Property target used to set the no-eject flag.
4187 No validations, but we normalize the value to ``True`` or ``False``.
4188 """
4189 if value:
4190 self._noEject = True
4191 else:
4192 self._noEject = False
4193
4194 def _getNoEject(self):
4195 """
4196 Property target used to get the no-eject flag.
4197 """
4198 return self._noEject
4199
4200 def _setBlankBehavior(self, value):
4201 """
4202 Property target used to set blanking behavior configuration.
4203 If not ``None``, the value must be a ``BlankBehavior`` object.
4204 Raises:
4205 ValueError: If the value is not a ``BlankBehavior``
4206 """
4207 if value is None:
4208 self._blankBehavior = None
4209 else:
4210 if not isinstance(value, BlankBehavior):
4211 raise ValueError("Value must be a ``BlankBehavior`` object.")
4212 self._blankBehavior = value
4213
4214 def _getBlankBehavior(self):
4215 """
4216 Property target used to get the blanking behavior configuration.
4217 """
4218 return self._blankBehavior
4219
4220 def _setRefreshMediaDelay(self, value):
4221 """
4222 Property target used to set the refreshMediaDelay.
4223 The value must be an integer >= 0.
4224 Raises:
4225 ValueError: If the value is not valid
4226 """
4227 if value is None:
4228 self._refreshMediaDelay = None
4229 else:
4230 try:
4231 value = int(value)
4232 except TypeError:
4233 raise ValueError("Action refreshMediaDelay value must be an integer >= 0.")
4234 if value < 0:
4235 raise ValueError("Action refreshMediaDelay value must be an integer >= 0.")
4236 if value == 0:
4237 value = None # normalize this out, since it's the default
4238 self._refreshMediaDelay = value
4239
4240 def _getRefreshMediaDelay(self):
4241 """
4242 Property target used to get the action refreshMediaDelay.
4243 """
4244 return self._refreshMediaDelay
4245
4246 def _setEjectDelay(self, value):
4247 """
4248 Property target used to set the ejectDelay.
4249 The value must be an integer >= 0.
4250 Raises:
4251 ValueError: If the value is not valid
4252 """
4253 if value is None:
4254 self._ejectDelay = None
4255 else:
4256 try:
4257 value = int(value)
4258 except TypeError:
4259 raise ValueError("Action ejectDelay value must be an integer >= 0.")
4260 if value < 0:
4261 raise ValueError("Action ejectDelay value must be an integer >= 0.")
4262 if value == 0:
4263 value = None # normalize this out, since it's the default
4264 self._ejectDelay = value
4265
4266 def _getEjectDelay(self):
4267 """
4268 Property target used to get the action ejectDelay.
4269 """
4270 return self._ejectDelay
4271
4272 sourceDir = property(_getSourceDir, _setSourceDir, None, "Directory whose contents should be written to media.")
4273 mediaType = property(_getMediaType, _setMediaType, None, "Type of the media (see notes above).")
4274 deviceType = property(_getDeviceType, _setDeviceType, None, "Type of the device (optional, see notes above).")
4275 devicePath = property(_getDevicePath, _setDevicePath, None, "Filesystem device name for writer device.")
4276 deviceScsiId = property(_getDeviceScsiId, _setDeviceScsiId, None, "SCSI id for writer device (optional, see notes above).")
4277 driveSpeed = property(_getDriveSpeed, _setDriveSpeed, None, "Speed of the drive.")
4278 checkData = property(_getCheckData, _setCheckData, None, "Whether resulting image should be validated.")
4279 checkMedia = property(_getCheckMedia, _setCheckMedia, None, "Whether media should be checked before being written to.")
4280 warnMidnite = property(_getWarnMidnite, _setWarnMidnite, None, "Whether to generate warnings for crossing midnite.")
4281 noEject = property(_getNoEject, _setNoEject, None, "Indicates that the writer device should not be ejected.")
4282 blankBehavior = property(_getBlankBehavior, _setBlankBehavior, None, "Controls optimized blanking behavior.")
4283 refreshMediaDelay = property(
4284 _getRefreshMediaDelay, _setRefreshMediaDelay, None, "Delay, in seconds, to add after refreshing media."
4285 )
4286 ejectDelay = property(
4287 _getEjectDelay, _setEjectDelay, None, "Delay, in seconds, to add after ejecting media before closing the tray"
4288 )
4289
4290
4291 ########################################################################
4292 # PurgeConfig class definition
4293 ########################################################################
4294
4295
4296 @total_ordering
4297 class PurgeConfig:
4298 """
4299 Class representing a Cedar Backup purge configuration.
4300
4301 The following restrictions exist on data in this class:
4302
4303 - The purge directory list must be a list of ``PurgeDir`` objects.
4304
4305 For the ``purgeDirs`` list, validation is accomplished through the
4306 :any:`util.ObjectTypeList` list implementation that overrides common list
4307 methods and transparently ensures that each element is a ``PurgeDir``.
4308
4309 *Note:* Lists within this class are "unordered" for equality comparisons.
4310
4311 """
4312
4313 def __init__(self, purgeDirs=None):
4314 """
4315 Constructor for the ``Purge`` class.
4316 Args:
4317 purgeDirs: List of purge directories
4318 Raises:
4319 ValueError: If one of the values is invalid
4320 """
4321 self._purgeDirs = None
4322 self.purgeDirs = purgeDirs
4323
4324 def __repr__(self):
4325 """
4326 Official string representation for class instance.
4327 """
4328 return "PurgeConfig(%s)" % self.purgeDirs
4329
4330 def __str__(self):
4331 """
4332 Informal string representation for class instance.
4333 """
4334 return self.__repr__()
4335
4336 def __eq__(self, other):
4337 """Equals operator, implemented in terms of original Python 2 compare operator."""
4338 return self.__cmp__(other) == 0
4339
4340 def __lt__(self, other):
4341 """Less-than operator, implemented in terms of original Python 2 compare operator."""
4342 return self.__cmp__(other) < 0
4343
4344 def __gt__(self, other):
4345 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
4346 return self.__cmp__(other) > 0
4347
4348 def __cmp__(self, other):
4349 """
4350 Original Python 2 comparison operator.
4351 Lists within this class are "unordered" for equality comparisons.
4352 Args:
4353 other: Other object to compare to
4354 Returns:
4355 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
4356 """
4357 if other is None:
4358 return 1
4359 if self.purgeDirs != other.purgeDirs:
4360 if self.purgeDirs < other.purgeDirs:
4361 return -1
4362 else:
4363 return 1
4364 return 0
4365
4366 def _setPurgeDirs(self, value):
4367 """
4368 Property target used to set the purge dirs list.
4369 Either the value must be ``None`` or each element must be a ``PurgeDir``.
4370 Raises:
4371 ValueError: If the value is not a ``PurgeDir``
4372 """
4373 if value is None:
4374 self._purgeDirs = None
4375 else:
4376 try:
4377 saved = self._purgeDirs
4378 self._purgeDirs = ObjectTypeList(PurgeDir, "PurgeDir")
4379 self._purgeDirs.extend(value)
4380 except Exception as e:
4381 self._purgeDirs = saved
4382 raise e
4383
4384 def _getPurgeDirs(self):
4385 """
4386 Property target used to get the purge dirs list.
4387 """
4388 return self._purgeDirs
4389
4390 purgeDirs = property(_getPurgeDirs, _setPurgeDirs, None, "List of directories to purge.")
4391
4392
4393 ########################################################################
4394 # Config class definition
4395 ########################################################################
4396
4397
4398 @total_ordering
4399 class Config:
4400 ######################
4401 # Class documentation
4402 ######################
4403
4404 """
4405 Class representing a Cedar Backup XML configuration document.
4406
4407 The ``Config`` class is a Python object representation of a Cedar Backup XML
4408 configuration file. It is intended to be the only Python-language interface
4409 to Cedar Backup configuration on disk for both Cedar Backup itself and for
4410 external applications.
4411
4412 The object representation is two-way: XML data can be used to create a
4413 ``Config`` object, and then changes to the object can be propogated back to
4414 disk. A ``Config`` object can even be used to create a configuration file
4415 from scratch programmatically.
4416
4417 This class and the classes it is composed from often use Python's
4418 ``property`` construct to validate input and limit access to values. Some
4419 validations can only be done once a document is considered "complete"
4420 (see module notes for more details).
4421
4422 Assignments to the various instance variables must match the expected
4423 type, i.e. ``reference`` must be a ``ReferenceConfig``. The internal check
4424 uses the built-in ``isinstance`` function, so it should be OK to use
4425 subclasses if you want to.
4426
4427 If an instance variable is not set, its value will be ``None``. When an
4428 object is initialized without using an XML document, all of the values
4429 will be ``None``. Even when an object is initialized using XML, some of
4430 the values might be ``None`` because not every section is required.
4431
4432 *Note:* Lists within this class are "unordered" for equality comparisons.
4433
4434 """
4435
4436 ##############
4437 # Constructor
4438 ##############
4439
4440 def __init__(self, xmlData=None, xmlPath=None, validate=True):
4441 """
4442 Initializes a configuration object.
4443
4444 If you initialize the object without passing either ``xmlData`` or
4445 ``xmlPath``, then configuration will be empty and will be invalid until it
4446 is filled in properly.
4447
4448 No reference to the original XML data or original path is saved off by
4449 this class. Once the data has been parsed (successfully or not) this
4450 original information is discarded.
4451
4452 Unless the ``validate`` argument is ``False``, the :any:`Config.validate`
4453 method will be called (with its default arguments) against configuration
4454 after successfully parsing any passed-in XML. Keep in mind that even if
4455 ``validate`` is ``False``, it might not be possible to parse the passed-in
4456 XML document if lower-level validations fail.
4457
4458 *Note:* It is strongly suggested that the ``validate`` option always be set
4459 to ``True`` (the default) unless there is a specific need to read in
4460 invalid configuration from disk.
4461
4462 Args:
4463 xmlData (String data): XML data representing configuration
4464 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
4465 validate (Boolean true/false): Validate the document after parsing it
4466 Raises:
4467 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
4468 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
4469 ValueError: If the parsed configuration document is not valid
4470 """
4471 self._reference = None
4472 self._extensions = None
4473 self._options = None
4474 self._peers = None
4475 self._collect = None
4476 self._stage = None
4477 self._store = None
4478 self._purge = None
4479 self.reference = None
4480 self.extensions = None
4481 self.options = None
4482 self.peers = None
4483 self.collect = None
4484 self.stage = None
4485 self.store = None
4486 self.purge = None
4487 if xmlData is not None and xmlPath is not None:
4488 raise ValueError("Use either xmlData or xmlPath, but not both.")
4489 if xmlData is not None:
4490 self._parseXmlData(xmlData)
4491 if validate:
4492 self.validate()
4493 elif xmlPath is not None:
4494 with open(xmlPath) as f:
4495 xmlData = f.read()
4496 self._parseXmlData(xmlData)
4497 if validate:
4498 self.validate()
4499
4500 #########################
4501 # String representations
4502 #########################
4503
4504 def __repr__(self):
4505 """
4506 Official string representation for class instance.
4507 """
4508 return "Config(%s, %s, %s, %s, %s, %s, %s, %s)" % (
4509 self.reference,
4510 self.extensions,
4511 self.options,
4512 self.peers,
4513 self.collect,
4514 self.stage,
4515 self.store,
4516 self.purge,
4517 )
4518
4519 def __str__(self):
4520 """
4521 Informal string representation for class instance.
4522 """
4523 return self.__repr__()
4524
4525 #############################
4526 # Standard comparison method
4527 #############################
4528
4529 def __eq__(self, other):
4530 """Equals operator, implemented in terms of original Python 2 compare operator."""
4531 return self.__cmp__(other) == 0
4532
4533 def __lt__(self, other):
4534 """Less-than operator, implemented in terms of original Python 2 compare operator."""
4535 return self.__cmp__(other) < 0
4536
4537 def __gt__(self, other):
4538 """Greater-than operator, implemented in terms of original Python 2 compare operator."""
4539 return self.__cmp__(other) > 0
4540
4541 def __cmp__(self, other):
4542 """
4543 Original Python 2 comparison operator.
4544 Lists within this class are "unordered" for equality comparisons.
4545 Args:
4546 other: Other object to compare to
4547 Returns:
4548 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
4549 """
4550 if other is None:
4551 return 1
4552 if self.reference != other.reference:
4553 if self.reference < other.reference:
4554 return -1
4555 else:
4556 return 1
4557 if self.extensions != other.extensions:
4558 if self.extensions < other.extensions:
4559 return -1
4560 else:
4561 return 1
4562 if self.options != other.options:
4563 if self.options < other.options:
4564 return -1
4565 else:
4566 return 1
4567 if self.peers != other.peers:
4568 if self.peers < other.peers:
4569 return -1
4570 else:
4571 return 1
4572 if self.collect != other.collect:
4573 if self.collect < other.collect:
4574 return -1
4575 else:
4576 return 1
4577 if self.stage != other.stage:
4578 if self.stage < other.stage:
4579 return -1
4580 else:
4581 return 1
4582 if self.store != other.store:
4583 if self.store < other.store:
4584 return -1
4585 else:
4586 return 1
4587 if self.purge != other.purge:
4588 if self.purge < other.purge:
4589 return -1
4590 else:
4591 return 1
4592 return 0
4593
4594 #############
4595 # Properties
4596 #############
4597
4598 def _setReference(self, value):
4599 """
4600 Property target used to set the reference configuration value.
4601 If not ``None``, the value must be a ``ReferenceConfig`` object.
4602 Raises:
4603 ValueError: If the value is not a ``ReferenceConfig``
4604 """
4605 if value is None:
4606 self._reference = None
4607 else:
4608 if not isinstance(value, ReferenceConfig):
4609 raise ValueError("Value must be a ``ReferenceConfig`` object.")
4610 self._reference = value
4611
4612 def _getReference(self):
4613 """
4614 Property target used to get the reference configuration value.
4615 """
4616 return self._reference
4617
4618 def _setExtensions(self, value):
4619 """
4620 Property target used to set the extensions configuration value.
4621 If not ``None``, the value must be a ``ExtensionsConfig`` object.
4622 Raises:
4623 ValueError: If the value is not a ``ExtensionsConfig``
4624 """
4625 if value is None:
4626 self._extensions = None
4627 else:
4628 if not isinstance(value, ExtensionsConfig):
4629 raise ValueError("Value must be a ``ExtensionsConfig`` object.")
4630 self._extensions = value
4631
4632 def _getExtensions(self):
4633 """
4634 Property target used to get the extensions configuration value.
4635 """
4636 return self._extensions
4637
4638 def _setOptions(self, value):
4639 """
4640 Property target used to set the options configuration value.
4641 If not ``None``, the value must be an ``OptionsConfig`` object.
4642 Raises:
4643 ValueError: If the value is not a ``OptionsConfig``
4644 """
4645 if value is None:
4646 self._options = None
4647 else:
4648 if not isinstance(value, OptionsConfig):
4649 raise ValueError("Value must be a ``OptionsConfig`` object.")
4650 self._options = value
4651
4652 def _getOptions(self):
4653 """
4654 Property target used to get the options configuration value.
4655 """
4656 return self._options
4657
4658 def _setPeers(self, value):
4659 """
4660 Property target used to set the peers configuration value.
4661 If not ``None``, the value must be an ``PeersConfig`` object.
4662 Raises:
4663 ValueError: If the value is not a ``PeersConfig``
4664 """
4665 if value is None:
4666 self._peers = None
4667 else:
4668 if not isinstance(value, PeersConfig):
4669 raise ValueError("Value must be a ``PeersConfig`` object.")
4670 self._peers = value
4671
4672 def _getPeers(self):
4673 """
4674 Property target used to get the peers configuration value.
4675 """
4676 return self._peers
4677
4678 def _setCollect(self, value):
4679 """
4680 Property target used to set the collect configuration value.
4681 If not ``None``, the value must be a ``CollectConfig`` object.
4682 Raises:
4683 ValueError: If the value is not a ``CollectConfig``
4684 """
4685 if value is None:
4686 self._collect = None
4687 else:
4688 if not isinstance(value, CollectConfig):
4689 raise ValueError("Value must be a ``CollectConfig`` object.")
4690 self._collect = value
4691
4692 def _getCollect(self):
4693 """
4694 Property target used to get the collect configuration value.
4695 """
4696 return self._collect
4697
4698 def _setStage(self, value):
4699 """
4700 Property target used to set the stage configuration value.
4701 If not ``None``, the value must be a ``StageConfig`` object.
4702 Raises:
4703 ValueError: If the value is not a ``StageConfig``
4704 """
4705 if value is None:
4706 self._stage = None
4707 else:
4708 if not isinstance(value, StageConfig):
4709 raise ValueError("Value must be a ``StageConfig`` object.")
4710 self._stage = value
4711
4712 def _getStage(self):
4713 """
4714 Property target used to get the stage configuration value.
4715 """
4716 return self._stage
4717
4718 def _setStore(self, value):
4719 """
4720 Property target used to set the store configuration value.
4721 If not ``None``, the value must be a ``StoreConfig`` object.
4722 Raises:
4723 ValueError: If the value is not a ``StoreConfig``
4724 """
4725 if value is None:
4726 self._store = None
4727 else:
4728 if not isinstance(value, StoreConfig):
4729 raise ValueError("Value must be a ``StoreConfig`` object.")
4730 self._store = value
4731
4732 def _getStore(self):
4733 """
4734 Property target used to get the store configuration value.
4735 """
4736 return self._store
4737
4738 def _setPurge(self, value):
4739 """
4740 Property target used to set the purge configuration value.
4741 If not ``None``, the value must be a ``PurgeConfig`` object.
4742 Raises:
4743 ValueError: If the value is not a ``PurgeConfig``
4744 """
4745 if value is None:
4746 self._purge = None
4747 else:
4748 if not isinstance(value, PurgeConfig):
4749 raise ValueError("Value must be a ``PurgeConfig`` object.")
4750 self._purge = value
4751
4752 def _getPurge(self):
4753 """
4754 Property target used to get the purge configuration value.
4755 """
4756 return self._purge
4757
4758 reference = property(_getReference, _setReference, None, "Reference configuration in terms of a ``ReferenceConfig`` object.")
4759 extensions = property(
4760 _getExtensions, _setExtensions, None, "Extensions configuration in terms of a ``ExtensionsConfig`` object."
4761 )
4762 options = property(_getOptions, _setOptions, None, "Options configuration in terms of a ``OptionsConfig`` object.")
4763 peers = property(_getPeers, _setPeers, None, "Peers configuration in terms of a ``PeersConfig`` object.")
4764 collect = property(_getCollect, _setCollect, None, "Collect configuration in terms of a ``CollectConfig`` object.")
4765 stage = property(_getStage, _setStage, None, "Stage configuration in terms of a ``StageConfig`` object.")
4766 store = property(_getStore, _setStore, None, "Store configuration in terms of a ``StoreConfig`` object.")
4767 purge = property(_getPurge, _setPurge, None, "Purge configuration in terms of a ``PurgeConfig`` object.")
4768
4769 #################
4770 # Public methods
4771 #################
4772
4773 def extractXml(self, xmlPath=None, validate=True):
4774 """
4775 Extracts configuration into an XML document.
4776
4777 If ``xmlPath`` is not provided, then the XML document will be returned as
4778 a string. If ``xmlPath`` is provided, then the XML document will be written
4779 to the file and ``None`` will be returned.
4780
4781 Unless the ``validate`` parameter is ``False``, the :any:`Config.validate`
4782 method will be called (with its default arguments) against the
4783 configuration before extracting the XML. If configuration is not valid,
4784 then an XML document will not be extracted.
4785
4786 *Note:* It is strongly suggested that the ``validate`` option always be set
4787 to ``True`` (the default) unless there is a specific need to write an
4788 invalid configuration file to disk.
4789
4790 Args:
4791 xmlPath (Absolute path to a file): Path to an XML file to create on disk
4792 validate (Boolean true/false): Validate the document before extracting it
4793 Returns:
4794 XML string data or ``None`` as described above
4795
4796 Raises:
4797 ValueError: If configuration within the object is not valid
4798 IOError: If there is an error writing to the file
4799 OSError: If there is an error writing to the file
4800 """
4801 if validate:
4802 self.validate()
4803 xmlData = self._extractXml()
4804 if xmlPath is not None:
4805 with open(xmlPath, "w") as f:
4806 f.write(xmlData)
4807 return None
4808 else:
4809 return xmlData
4810
4811 def validate(
4812 self,
4813 requireOneAction=True,
4814 requireReference=False,
4815 requireExtensions=False,
4816 requireOptions=True,
4817 requireCollect=False,
4818 requireStage=False,
4819 requireStore=False,
4820 requirePurge=False,
4821 requirePeers=False,
4822 ):
4823 """
4824 Validates configuration represented by the object.
4825
4826 This method encapsulates all of the validations that should apply to a
4827 fully "complete" document but are not already taken care of by earlier
4828 validations. It also provides some extra convenience functionality which
4829 might be useful to some people. The process of validation is laid out in
4830 the *Validation* section in the class notes (above).
4831
4832 Args:
4833 requireOneAction: Require at least one of the collect, stage, store or purge sections
4834 requireReference: Require the reference section
4835 requireExtensions: Require the extensions section
4836 requireOptions: Require the options section
4837 requirePeers: Require the peers section
4838 requireCollect: Require the collect section
4839 requireStage: Require the stage section
4840 requireStore: Require the store section
4841 requirePurge: Require the purge section
4842
4843 Raises:
4844 ValueError: If one of the validations fails
4845 """
4846 if requireOneAction and (self.collect, self.stage, self.store, self.purge) == (None, None, None, None):
4847 raise ValueError("At least one of the collect, stage, store and purge sections is required.")
4848 if requireReference and self.reference is None:
4849 raise ValueError("The reference is section is required.")
4850 if requireExtensions and self.extensions is None:
4851 raise ValueError("The extensions is section is required.")
4852 if requireOptions and self.options is None:
4853 raise ValueError("The options is section is required.")
4854 if requirePeers and self.peers is None:
4855 raise ValueError("The peers is section is required.")
4856 if requireCollect and self.collect is None:
4857 raise ValueError("The collect is section is required.")
4858 if requireStage and self.stage is None:
4859 raise ValueError("The stage is section is required.")
4860 if requireStore and self.store is None:
4861 raise ValueError("The store is section is required.")
4862 if requirePurge and self.purge is None:
4863 raise ValueError("The purge is section is required.")
4864 self._validateContents()
4865
4866 #####################################
4867 # High-level methods for parsing XML
4868 #####################################
4869
4870 def _parseXmlData(self, xmlData):
4871 """
4872 Internal method to parse an XML string into the object.
4873
4874 This method parses the XML document into a DOM tree (``xmlDom``) and then
4875 calls individual static methods to parse each of the individual
4876 configuration sections.
4877
4878 Most of the validation we do here has to do with whether the document can
4879 be parsed and whether any values which exist are valid. We don't do much
4880 validation as to whether required elements actually exist unless we have
4881 to to make sense of the document (instead, that's the job of the
4882 :any:`validate` method).
4883
4884 Args:
4885 xmlData (String data): XML data to be parsed
4886 Raises:
4887 ValueError: If the XML cannot be successfully parsed
4888 """
4889 (_, parentNode) = createInputDom(xmlData)
4890 self._reference = Config._parseReference(parentNode)
4891 self._extensions = Config._parseExtensions(parentNode)
4892 self._options = Config._parseOptions(parentNode)
4893 self._peers = Config._parsePeers(parentNode)
4894 self._collect = Config._parseCollect(parentNode)
4895 self._stage = Config._parseStage(parentNode)
4896 self._store = Config._parseStore(parentNode)
4897 self._purge = Config._parsePurge(parentNode)
4898
4899 @staticmethod
4900 def _parseReference(parentNode):
4901 """
4902 Parses a reference configuration section.
4903
4904 We read the following fields::
4905
4906 author //cb_config/reference/author
4907 revision //cb_config/reference/revision
4908 description //cb_config/reference/description
4909 generator //cb_config/reference/generator
4910
4911 Args:
4912 parentNode: Parent node to search beneath
4913
4914 Returns:
4915 ``ReferenceConfig`` object or ``None`` if the section does not exist
4916 Raises:
4917 ValueError: If some filled-in value is invalid
4918 """
4919 reference = None
4920 sectionNode = readFirstChild(parentNode, "reference")
4921 if sectionNode is not None:
4922 reference = ReferenceConfig()
4923 reference.author = readString(sectionNode, "author")
4924 reference.revision = readString(sectionNode, "revision")
4925 reference.description = readString(sectionNode, "description")
4926 reference.generator = readString(sectionNode, "generator")
4927 return reference
4928
4929 @staticmethod
4930 def _parseExtensions(parentNode):
4931 """
4932 Parses an extensions configuration section.
4933
4934 We read the following fields::
4935
4936 orderMode //cb_config/extensions/order_mode
4937
4938 We also read groups of the following items, one list element per item::
4939
4940 name //cb_config/extensions/action/name
4941 module //cb_config/extensions/action/module
4942 function //cb_config/extensions/action/function
4943 index //cb_config/extensions/action/index
4944 dependencies //cb_config/extensions/action/depends
4945
4946 The extended actions are parsed by :any:`_parseExtendedActions`.
4947
4948 Args:
4949 parentNode: Parent node to search beneath
4950
4951 Returns:
4952 ``ExtensionsConfig`` object or ``None`` if the section does not exist
4953 Raises:
4954 ValueError: If some filled-in value is invalid
4955 """
4956 extensions = None
4957 sectionNode = readFirstChild(parentNode, "extensions")
4958 if sectionNode is not None:
4959 extensions = ExtensionsConfig()
4960 extensions.orderMode = readString(sectionNode, "order_mode")
4961 extensions.actions = Config._parseExtendedActions(sectionNode)
4962 return extensions
4963
4964 @staticmethod
4965 def _parseOptions(parentNode):
4966 """
4967 Parses a options configuration section.
4968
4969 We read the following fields::
4970
4971 startingDay //cb_config/options/starting_day
4972 workingDir //cb_config/options/working_dir
4973 backupUser //cb_config/options/backup_user
4974 backupGroup //cb_config/options/backup_group
4975 rcpCommand //cb_config/options/rcp_command
4976 rshCommand //cb_config/options/rsh_command
4977 cbackCommand //cb_config/options/cback_command
4978 managedActions //cb_config/options/managed_actions
4979
4980 The list of managed actions is a comma-separated list of action names.
4981
4982 We also read groups of the following items, one list element per
4983 item::
4984
4985 overrides //cb_config/options/override
4986 hooks //cb_config/options/hook
4987
4988 The overrides are parsed by :any:`_parseOverrides` and the hooks are parsed
4989 by :any:`_parseHooks`.
4990
4991 Args:
4992 parentNode: Parent node to search beneath
4993
4994 Returns:
4995 ``OptionsConfig`` object or ``None`` if the section does not exist
4996 Raises:
4997 ValueError: If some filled-in value is invalid
4998 """
4999 options = None
5000 sectionNode = readFirstChild(parentNode, "options")
5001 if sectionNode is not None:
5002 options = OptionsConfig()
5003 options.startingDay = readString(sectionNode, "starting_day")
5004 options.workingDir = readString(sectionNode, "working_dir")
5005 options.backupUser = readString(sectionNode, "backup_user")
5006 options.backupGroup = readString(sectionNode, "backup_group")
5007 options.rcpCommand = readString(sectionNode, "rcp_command")
5008 options.rshCommand = readString(sectionNode, "rsh_command")
5009 options.cbackCommand = readString(sectionNode, "cback_command")
5010 options.overrides = Config._parseOverrides(sectionNode)
5011 options.hooks = Config._parseHooks(sectionNode)
5012 managedActions = readString(sectionNode, "managed_actions")
5013 options.managedActions = parseCommaSeparatedString(managedActions)
5014 return options
5015
5016 @staticmethod
5017 def _parsePeers(parentNode):
5018 """
5019 Parses a peers configuration section.
5020
5021 We read groups of the following items, one list element per
5022 item::
5023
5024 localPeers //cb_config/stage/peer
5025 remotePeers //cb_config/stage/peer
5026
5027 The individual peer entries are parsed by :any:`_parsePeerList`.
5028
5029 Args:
5030 parentNode: Parent node to search beneath
5031
5032 Returns:
5033 ``StageConfig`` object or ``None`` if the section does not exist
5034 Raises:
5035 ValueError: If some filled-in value is invalid
5036 """
5037 peers = None
5038 sectionNode = readFirstChild(parentNode, "peers")
5039 if sectionNode is not None:
5040 peers = PeersConfig()
5041 (peers.localPeers, peers.remotePeers) = Config._parsePeerList(sectionNode)
5042 return peers
5043
5044 @staticmethod
5045 def _parseCollect(parentNode):
5046 """
5047 Parses a collect configuration section.
5048
5049 We read the following individual fields::
5050
5051 targetDir //cb_config/collect/collect_dir
5052 collectMode //cb_config/collect/collect_mode
5053 archiveMode //cb_config/collect/archive_mode
5054 ignoreFile //cb_config/collect/ignore_file
5055
5056 We also read groups of the following items, one list element per
5057 item::
5058
5059 absoluteExcludePaths //cb_config/collect/exclude/abs_path
5060 excludePatterns //cb_config/collect/exclude/pattern
5061 collectFiles //cb_config/collect/file
5062 collectDirs //cb_config/collect/dir
5063
5064 The exclusions are parsed by :any:`_parseExclusions`, the collect files are
5065 parsed by :any:`_parseCollectFiles`, and the directories are parsed by
5066 :any:`_parseCollectDirs`.
5067
5068 Args:
5069 parentNode: Parent node to search beneath
5070
5071 Returns:
5072 ``CollectConfig`` object or ``None`` if the section does not exist
5073 Raises:
5074 ValueError: If some filled-in value is invalid
5075 """
5076 collect = None
5077 sectionNode = readFirstChild(parentNode, "collect")
5078 if sectionNode is not None:
5079 collect = CollectConfig()
5080 collect.targetDir = readString(sectionNode, "collect_dir")
5081 collect.collectMode = readString(sectionNode, "collect_mode")
5082 collect.archiveMode = readString(sectionNode, "archive_mode")
5083 collect.ignoreFile = readString(sectionNode, "ignore_file")
5084 (collect.absoluteExcludePaths, _, collect.excludePatterns) = Config._parseExclusions(sectionNode)
5085 collect.collectFiles = Config._parseCollectFiles(sectionNode)
5086 collect.collectDirs = Config._parseCollectDirs(sectionNode)
5087 return collect
5088
5089 @staticmethod
5090 def _parseStage(parentNode):
5091 """
5092 Parses a stage configuration section.
5093
5094 We read the following individual fields::
5095
5096 targetDir //cb_config/stage/staging_dir
5097
5098 We also read groups of the following items, one list element per
5099 item::
5100
5101 localPeers //cb_config/stage/peer
5102 remotePeers //cb_config/stage/peer
5103
5104 The individual peer entries are parsed by :any:`_parsePeerList`.
5105
5106 Args:
5107 parentNode: Parent node to search beneath
5108
5109 Returns:
5110 ``StageConfig`` object or ``None`` if the section does not exist
5111 Raises:
5112 ValueError: If some filled-in value is invalid
5113 """
5114 stage = None
5115 sectionNode = readFirstChild(parentNode, "stage")
5116 if sectionNode is not None:
5117 stage = StageConfig()
5118 stage.targetDir = readString(sectionNode, "staging_dir")
5119 (stage.localPeers, stage.remotePeers) = Config._parsePeerList(sectionNode)
5120 return stage
5121
5122 @staticmethod
5123 def _parseStore(parentNode):
5124 """
5125 Parses a store configuration section.
5126
5127 We read the following fields::
5128
5129 sourceDir //cb_config/store/source_dir
5130 mediaType //cb_config/store/media_type
5131 deviceType //cb_config/store/device_type
5132 devicePath //cb_config/store/target_device
5133 deviceScsiId //cb_config/store/target_scsi_id
5134 driveSpeed //cb_config/store/drive_speed
5135 checkData //cb_config/store/check_data
5136 checkMedia //cb_config/store/check_media
5137 warnMidnite //cb_config/store/warn_midnite
5138 noEject //cb_config/store/no_eject
5139
5140 Blanking behavior configuration is parsed by the ``_parseBlankBehavior``
5141 method.
5142
5143 Args:
5144 parentNode: Parent node to search beneath
5145
5146 Returns:
5147 ``StoreConfig`` object or ``None`` if the section does not exist
5148 Raises:
5149 ValueError: If some filled-in value is invalid
5150 """
5151 store = None
5152 sectionNode = readFirstChild(parentNode, "store")
5153 if sectionNode is not None:
5154 store = StoreConfig()
5155 store.sourceDir = readString(sectionNode, "source_dir")
5156 store.mediaType = readString(sectionNode, "media_type")
5157 store.deviceType = readString(sectionNode, "device_type")
5158 store.devicePath = readString(sectionNode, "target_device")
5159 store.deviceScsiId = readString(sectionNode, "target_scsi_id")
5160 store.driveSpeed = readInteger(sectionNode, "drive_speed")
5161 store.checkData = readBoolean(sectionNode, "check_data")
5162 store.checkMedia = readBoolean(sectionNode, "check_media")
5163 store.warnMidnite = readBoolean(sectionNode, "warn_midnite")
5164 store.noEject = readBoolean(sectionNode, "no_eject")
5165 store.blankBehavior = Config._parseBlankBehavior(sectionNode)
5166 store.refreshMediaDelay = readInteger(sectionNode, "refresh_media_delay")
5167 store.ejectDelay = readInteger(sectionNode, "eject_delay")
5168 return store
5169
5170 @staticmethod
5171 def _parsePurge(parentNode):
5172 """
5173 Parses a purge configuration section.
5174
5175 We read groups of the following items, one list element per
5176 item::
5177
5178 purgeDirs //cb_config/purge/dir
5179
5180 The individual directory entries are parsed by :any:`_parsePurgeDirs`.
5181
5182 Args:
5183 parentNode: Parent node to search beneath
5184
5185 Returns:
5186 ``PurgeConfig`` object or ``None`` if the section does not exist
5187 Raises:
5188 ValueError: If some filled-in value is invalid
5189 """
5190 purge = None
5191 sectionNode = readFirstChild(parentNode, "purge")
5192 if sectionNode is not None:
5193 purge = PurgeConfig()
5194 purge.purgeDirs = Config._parsePurgeDirs(sectionNode)
5195 return purge
5196
5197 @staticmethod
5198 def _parseExtendedActions(parentNode):
5199 """
5200 Reads extended actions data from immediately beneath the parent.
5201
5202 We read the following individual fields from each extended action::
5203
5204 name name
5205 module module
5206 function function
5207 index index
5208 dependencies depends
5209
5210 Dependency information is parsed by the ``_parseDependencies`` method.
5211
5212 Args:
5213 parentNode: Parent node to search beneath
5214
5215 Returns:
5216 List of extended actions
5217 Raises:
5218 ValueError: If the data at the location can't be read
5219 """
5220 lst = []
5221 for entry in readChildren(parentNode, "action"):
5222 if isElement(entry):
5223 action = ExtendedAction()
5224 action.name = readString(entry, "name")
5225 action.module = readString(entry, "module")
5226 action.function = readString(entry, "function")
5227 action.index = readInteger(entry, "index")
5228 action.dependencies = Config._parseDependencies(entry)
5229 lst.append(action)
5230 if not lst:
5231 lst = None
5232 return lst
5233
5234 @staticmethod
5235 def _parseExclusions(parentNode):
5236 """
5237 Reads exclusions data from immediately beneath the parent.
5238
5239 We read groups of the following items, one list element per item::
5240
5241 absolute exclude/abs_path
5242 relative exclude/rel_path
5243 patterns exclude/pattern
5244
5245 If there are none of some pattern (i.e. no relative path items) then
5246 ``None`` will be returned for that item in the tuple.
5247
5248 This method can be used to parse exclusions on both the collect
5249 configuration level and on the collect directory level within collect
5250 configuration.
5251
5252 Args:
5253 parentNode: Parent node to search beneath
5254
5255 Returns:
5256 Tuple of (absolute, relative, patterns) exclusions
5257 """
5258 sectionNode = readFirstChild(parentNode, "exclude")
5259 if sectionNode is None:
5260 return (None, None, None)
5261 else:
5262 absolute = readStringList(sectionNode, "abs_path")
5263 relative = readStringList(sectionNode, "rel_path")
5264 patterns = readStringList(sectionNode, "pattern")
5265 return (absolute, relative, patterns)
5266
5267 @staticmethod
5268 def _parseOverrides(parentNode):
5269 """
5270 Reads a list of ``CommandOverride`` objects from immediately beneath the parent.
5271
5272 We read the following individual fields::
5273
5274 command command
5275 absolutePath abs_path
5276
5277 Args:
5278 parentNode: Parent node to search beneath
5279
5280 Returns:
5281 List of ``CommandOverride`` objects or ``None`` if none are found
5282 Raises:
5283 ValueError: If some filled-in value is invalid
5284 """
5285 lst = []
5286 for entry in readChildren(parentNode, "override"):
5287 if isElement(entry):
5288 override = CommandOverride()
5289 override.command = readString(entry, "command")
5290 override.absolutePath = readString(entry, "abs_path")
5291 lst.append(override)
5292 if not lst:
5293 lst = None
5294 return lst
5295
5296 @staticmethod
5297 def _parseHooks(parentNode):
5298 """
5299 Reads a list of ``ActionHook`` objects from immediately beneath the parent.
5300
5301 We read the following individual fields::
5302
5303 action action
5304 command command
5305
5306 Args:
5307 parentNode: Parent node to search beneath
5308
5309 Returns:
5310 List of ``ActionHook`` objects or ``None`` if none are found
5311 Raises:
5312 ValueError: If some filled-in value is invalid
5313 """
5314 lst = []
5315 for entry in readChildren(parentNode, "pre_action_hook"):
5316 if isElement(entry):
5317 hook = PreActionHook()
5318 hook.action = readString(entry, "action")
5319 hook.command = readString(entry, "command")
5320 lst.append(hook)
5321 for entry in readChildren(parentNode, "post_action_hook"):
5322 if isElement(entry):
5323 hook = PostActionHook()
5324 hook.action = readString(entry, "action")
5325 hook.command = readString(entry, "command")
5326 lst.append(hook)
5327 if not lst:
5328 lst = None
5329 return lst
5330
5331 @staticmethod
5332 def _parseCollectFiles(parentNode):
5333 """
5334 Reads a list of ``CollectFile`` objects from immediately beneath the parent.
5335
5336 We read the following individual fields::
5337
5338 absolutePath abs_path
5339 collectMode mode *or* collect_mode
5340 archiveMode archive_mode
5341
5342 The collect mode is a special case. Just a ``mode`` tag is accepted, but
5343 we prefer ``collect_mode`` for consistency with the rest of the config
5344 file and to avoid confusion with the archive mode. If both are provided,
5345 only ``mode`` will be used.
5346
5347 Args:
5348 parentNode: Parent node to search beneath
5349
5350 Returns:
5351 List of ``CollectFile`` objects or ``None`` if none are found
5352 Raises:
5353 ValueError: If some filled-in value is invalid
5354 """
5355 lst = []
5356 for entry in readChildren(parentNode, "file"):
5357 if isElement(entry):
5358 cfile = CollectFile()
5359 cfile.absolutePath = readString(entry, "abs_path")
5360 cfile.collectMode = readString(entry, "mode")
5361 if cfile.collectMode is None:
5362 cfile.collectMode = readString(entry, "collect_mode")
5363 cfile.archiveMode = readString(entry, "archive_mode")
5364 lst.append(cfile)
5365 if not lst:
5366 lst = None
5367 return lst
5368
5369 @staticmethod
5370 def _parseCollectDirs(parentNode):
5371 """
5372 Reads a list of ``CollectDir`` objects from immediately beneath the parent.
5373
5374 We read the following individual fields::
5375
5376 absolutePath abs_path
5377 collectMode mode *or* collect_mode
5378 archiveMode archive_mode
5379 ignoreFile ignore_file
5380 linkDepth link_depth
5381 dereference dereference
5382 recursionLevel recursion_level
5383
5384 The collect mode is a special case. Just a ``mode`` tag is accepted for
5385 backwards compatibility, but we prefer ``collect_mode`` for consistency
5386 with the rest of the config file and to avoid confusion with the archive
5387 mode. If both are provided, only ``mode`` will be used.
5388
5389 We also read groups of the following items, one list element per
5390 item::
5391
5392 absoluteExcludePaths exclude/abs_path
5393 relativeExcludePaths exclude/rel_path
5394 excludePatterns exclude/pattern
5395
5396 The exclusions are parsed by :any:`_parseExclusions`.
5397
5398 Args:
5399 parentNode: Parent node to search beneath
5400
5401 Returns:
5402 List of ``CollectDir`` objects or ``None`` if none are found
5403 Raises:
5404 ValueError: If some filled-in value is invalid
5405 """
5406 lst = []
5407 for entry in readChildren(parentNode, "dir"):
5408 if isElement(entry):
5409 cdir = CollectDir()
5410 cdir.absolutePath = readString(entry, "abs_path")
5411 cdir.collectMode = readString(entry, "mode")
5412 if cdir.collectMode is None:
5413 cdir.collectMode = readString(entry, "collect_mode")
5414 cdir.archiveMode = readString(entry, "archive_mode")
5415 cdir.ignoreFile = readString(entry, "ignore_file")
5416 cdir.linkDepth = readInteger(entry, "link_depth")
5417 cdir.dereference = readBoolean(entry, "dereference")
5418 cdir.recursionLevel = readInteger(entry, "recursion_level")
5419 (cdir.absoluteExcludePaths, cdir.relativeExcludePaths, cdir.excludePatterns) = Config._parseExclusions(entry)
5420 lst.append(cdir)
5421 if not lst:
5422 lst = None
5423 return lst
5424
5425 @staticmethod
5426 def _parsePurgeDirs(parentNode):
5427 """
5428 Reads a list of ``PurgeDir`` objects from immediately beneath the parent.
5429
5430 We read the following individual fields::
5431
5432 absolutePath <baseExpr>/abs_path
5433 retainDays <baseExpr>/retain_days
5434
5435 Args:
5436 parentNode: Parent node to search beneath
5437
5438 Returns:
5439 List of ``PurgeDir`` objects or ``None`` if none are found
5440 Raises:
5441 ValueError: If the data at the location can't be read
5442 """
5443 lst = []
5444 for entry in readChildren(parentNode, "dir"):
5445 if isElement(entry):
5446 cdir = PurgeDir()
5447 cdir.absolutePath = readString(entry, "abs_path")
5448 cdir.retainDays = readInteger(entry, "retain_days")
5449 lst.append(cdir)
5450 if not lst:
5451 lst = None
5452 return lst
5453
5454 @staticmethod
5455 def _parsePeerList(parentNode):
5456 """
5457 Reads remote and local peer data from immediately beneath the parent.
5458
5459 We read the following individual fields for both remote
5460 and local peers::
5461
5462 name name
5463 collectDir collect_dir
5464
5465 We also read the following individual fields for remote peers
5466 only::
5467
5468 remoteUser backup_user
5469 rcpCommand rcp_command
5470 rshCommand rsh_command
5471 cbackCommand cback_command
5472 managed managed
5473 managedActions managed_actions
5474
5475 Additionally, the value in the ``type`` field is used to determine whether
5476 this entry is a remote peer. If the type is ``"remote"``, it's a remote
5477 peer, and if the type is ``"local"``, it's a remote peer.
5478
5479 If there are none of one type of peer (i.e. no local peers) then ``None``
5480 will be returned for that item in the tuple.
5481
5482 Args:
5483 parentNode: Parent node to search beneath
5484
5485 Returns:
5486 Tuple of (local, remote) peer lists
5487 Raises:
5488 ValueError: If the data at the location can't be read
5489 """
5490 localPeers = []
5491 remotePeers = []
5492 for entry in readChildren(parentNode, "peer"):
5493 if isElement(entry):
5494 peerType = readString(entry, "type")
5495 if peerType == "local":
5496 localPeer = LocalPeer()
5497 localPeer.name = readString(entry, "name")
5498 localPeer.collectDir = readString(entry, "collect_dir")
5499 localPeer.ignoreFailureMode = readString(entry, "ignore_failures")
5500 localPeers.append(localPeer)
5501 elif peerType == "remote":
5502 remotePeer = RemotePeer()
5503 remotePeer.name = readString(entry, "name")
5504 remotePeer.collectDir = readString(entry, "collect_dir")
5505 remotePeer.remoteUser = readString(entry, "backup_user")
5506 remotePeer.rcpCommand = readString(entry, "rcp_command")
5507 remotePeer.rshCommand = readString(entry, "rsh_command")
5508 remotePeer.cbackCommand = readString(entry, "cback_command")
5509 remotePeer.ignoreFailureMode = readString(entry, "ignore_failures")
5510 remotePeer.managed = readBoolean(entry, "managed")
5511 managedActions = readString(entry, "managed_actions")
5512 remotePeer.managedActions = parseCommaSeparatedString(managedActions)
5513 remotePeers.append(remotePeer)
5514 if not localPeers:
5515 localPeers = None
5516 if not remotePeers:
5517 remotePeers = None
5518 return (localPeers, remotePeers)
5519
5520 @staticmethod
5521 def _parseDependencies(parentNode):
5522 """
5523 Reads extended action dependency information from a parent node.
5524
5525 We read the following individual fields::
5526
5527 runBefore depends/run_before
5528 runAfter depends/run_after
5529
5530 Each of these fields is a comma-separated list of action names.
5531
5532 The result is placed into an ``ActionDependencies`` object.
5533
5534 If the dependencies parent node does not exist, ``None`` will be returned.
5535 Otherwise, an ``ActionDependencies`` object will always be created, even
5536 if it does not contain any actual dependencies in it.
5537
5538 Args:
5539 parentNode: Parent node to search beneath
5540
5541 Returns:
5542 ``ActionDependencies`` object or ``None``
5543 Raises:
5544 ValueError: If the data at the location can't be read
5545 """
5546 sectionNode = readFirstChild(parentNode, "depends")
5547 if sectionNode is None:
5548 return None
5549 else:
5550 runBefore = readString(sectionNode, "run_before")
5551 runAfter = readString(sectionNode, "run_after")
5552 beforeList = parseCommaSeparatedString(runBefore)
5553 afterList = parseCommaSeparatedString(runAfter)
5554 return ActionDependencies(beforeList, afterList)
5555
5556 @staticmethod
5557 def _parseBlankBehavior(parentNode):
5558 """
5559 Reads a single ``BlankBehavior`` object from immediately beneath the parent.
5560
5561 We read the following individual fields::
5562
5563 blankMode blank_behavior/mode
5564 blankFactor blank_behavior/factor
5565
5566 Args:
5567 parentNode: Parent node to search beneath
5568
5569 Returns:
5570 ``BlankBehavior`` object or ``None`` if none if the section is not found
5571 Raises:
5572 ValueError: If some filled-in value is invalid
5573 """
5574 blankBehavior = None
5575 sectionNode = readFirstChild(parentNode, "blank_behavior")
5576 if sectionNode is not None:
5577 blankBehavior = BlankBehavior()
5578 blankBehavior.blankMode = readString(sectionNode, "mode")
5579 blankBehavior.blankFactor = readString(sectionNode, "factor")
5580 return blankBehavior
5581
5582 ########################################
5583 # High-level methods for generating XML
5584 ########################################
5585
5586 def _extractXml(self):
5587 """
5588 Internal method to extract configuration into an XML string.
5589
5590 This method assumes that the internal :any:`validate` method has been called
5591 prior to extracting the XML, if the caller cares. No validation will be
5592 done internally.
5593
5594 As a general rule, fields that are set to ``None`` will be extracted into
5595 the document as empty tags. The same goes for container tags that are
5596 filled based on lists - if the list is empty or ``None``, the container
5597 tag will be empty.
5598 """
5599 (xmlDom, parentNode) = createOutputDom()
5600 Config._addReference(xmlDom, parentNode, self.reference)
5601 Config._addExtensions(xmlDom, parentNode, self.extensions)
5602 Config._addOptions(xmlDom, parentNode, self.options)
5603 Config._addPeers(xmlDom, parentNode, self.peers)
5604 Config._addCollect(xmlDom, parentNode, self.collect)
5605 Config._addStage(xmlDom, parentNode, self.stage)
5606 Config._addStore(xmlDom, parentNode, self.store)
5607 Config._addPurge(xmlDom, parentNode, self.purge)
5608 xmlData = serializeDom(xmlDom)
5609 xmlDom.unlink()
5610 return xmlData
5611
5612 @staticmethod
5613 def _addReference(xmlDom, parentNode, referenceConfig):
5614 """
5615 Adds a <reference> configuration section as the next child of a parent.
5616
5617 We add the following fields to the document::
5618
5619 author //cb_config/reference/author
5620 revision //cb_config/reference/revision
5621 description //cb_config/reference/description
5622 generator //cb_config/reference/generator
5623
5624 If ``referenceConfig`` is ``None``, then no container will be added.
5625
5626 Args:
5627 xmlDom: DOM tree as from :any:`createOutputDom`
5628 parentNode: Parent that the section should be appended to
5629 referenceConfig: Reference configuration section to be added to the document
5630 """
5631 if referenceConfig is not None:
5632 sectionNode = addContainerNode(xmlDom, parentNode, "reference")
5633 addStringNode(xmlDom, sectionNode, "author", referenceConfig.author)
5634 addStringNode(xmlDom, sectionNode, "revision", referenceConfig.revision)
5635 addStringNode(xmlDom, sectionNode, "description", referenceConfig.description)
5636 addStringNode(xmlDom, sectionNode, "generator", referenceConfig.generator)
5637
5638 @staticmethod
5639 def _addExtensions(xmlDom, parentNode, extensionsConfig):
5640 """
5641 Adds an <extensions> configuration section as the next child of a parent.
5642
5643 We add the following fields to the document::
5644
5645 order_mode //cb_config/extensions/order_mode
5646
5647 We also add groups of the following items, one list element per item::
5648
5649 actions //cb_config/extensions/action
5650
5651 The extended action entries are added by :any:`_addExtendedAction`.
5652
5653 If ``extensionsConfig`` is ``None``, then no container will be added.
5654
5655 Args:
5656 xmlDom: DOM tree as from :any:`createOutputDom`
5657 parentNode: Parent that the section should be appended to
5658 extensionsConfig: Extensions configuration section to be added to the document
5659 """
5660 if extensionsConfig is not None:
5661 sectionNode = addContainerNode(xmlDom, parentNode, "extensions")
5662 addStringNode(xmlDom, sectionNode, "order_mode", extensionsConfig.orderMode)
5663 if extensionsConfig.actions is not None:
5664 for action in extensionsConfig.actions:
5665 Config._addExtendedAction(xmlDom, sectionNode, action)
5666
5667 @staticmethod
5668 def _addOptions(xmlDom, parentNode, optionsConfig):
5669 """
5670 Adds a <options> configuration section as the next child of a parent.
5671
5672 We add the following fields to the document::
5673
5674 startingDay //cb_config/options/starting_day
5675 workingDir //cb_config/options/working_dir
5676 backupUser //cb_config/options/backup_user
5677 backupGroup //cb_config/options/backup_group
5678 rcpCommand //cb_config/options/rcp_command
5679 rshCommand //cb_config/options/rsh_command
5680 cbackCommand //cb_config/options/cback_command
5681 managedActions //cb_config/options/managed_actions
5682
5683 We also add groups of the following items, one list element per
5684 item::
5685
5686 overrides //cb_config/options/override
5687 hooks //cb_config/options/pre_action_hook
5688 hooks //cb_config/options/post_action_hook
5689
5690 The individual override items are added by :any:`_addOverride`. The
5691 individual hook items are added by :any:`_addHook`.
5692
5693 If ``optionsConfig`` is ``None``, then no container will be added.
5694
5695 Args:
5696 xmlDom: DOM tree as from :any:`createOutputDom`
5697 parentNode: Parent that the section should be appended to
5698 optionsConfig: Options configuration section to be added to the document
5699 """
5700 if optionsConfig is not None:
5701 sectionNode = addContainerNode(xmlDom, parentNode, "options")
5702 addStringNode(xmlDom, sectionNode, "starting_day", optionsConfig.startingDay)
5703 addStringNode(xmlDom, sectionNode, "working_dir", optionsConfig.workingDir)
5704 addStringNode(xmlDom, sectionNode, "backup_user", optionsConfig.backupUser)
5705 addStringNode(xmlDom, sectionNode, "backup_group", optionsConfig.backupGroup)
5706 addStringNode(xmlDom, sectionNode, "rcp_command", optionsConfig.rcpCommand)
5707 addStringNode(xmlDom, sectionNode, "rsh_command", optionsConfig.rshCommand)
5708 addStringNode(xmlDom, sectionNode, "cback_command", optionsConfig.cbackCommand)
5709 managedActions = Config._buildCommaSeparatedString(optionsConfig.managedActions)
5710 addStringNode(xmlDom, sectionNode, "managed_actions", managedActions)
5711 if optionsConfig.overrides is not None:
5712 for override in optionsConfig.overrides:
5713 Config._addOverride(xmlDom, sectionNode, override)
5714 if optionsConfig.hooks is not None:
5715 for hook in optionsConfig.hooks:
5716 Config._addHook(xmlDom, sectionNode, hook)
5717
5718 @staticmethod
5719 def _addPeers(xmlDom, parentNode, peersConfig):
5720 """
5721 Adds a <peers> configuration section as the next child of a parent.
5722
5723 We add groups of the following items, one list element per
5724 item::
5725
5726 localPeers //cb_config/peers/peer
5727 remotePeers //cb_config/peers/peer
5728
5729 The individual local and remote peer entries are added by
5730 :any:`_addLocalPeer` and :any:`_addRemotePeer`, respectively.
5731
5732 If ``peersConfig`` is ``None``, then no container will be added.
5733
5734 Args:
5735 xmlDom: DOM tree as from :any:`createOutputDom`
5736 parentNode: Parent that the section should be appended to
5737 peersConfig: Peers configuration section to be added to the document
5738 """
5739 if peersConfig is not None:
5740 sectionNode = addContainerNode(xmlDom, parentNode, "peers")
5741 if peersConfig.localPeers is not None:
5742 for localPeer in peersConfig.localPeers:
5743 Config._addLocalPeer(xmlDom, sectionNode, localPeer)
5744 if peersConfig.remotePeers is not None:
5745 for remotePeer in peersConfig.remotePeers:
5746 Config._addRemotePeer(xmlDom, sectionNode, remotePeer)
5747
5748 @staticmethod
5749 def _addCollect(xmlDom, parentNode, collectConfig):
5750 """
5751 Adds a <collect> configuration section as the next child of a parent.
5752
5753 We add the following fields to the document::
5754
5755 targetDir //cb_config/collect/collect_dir
5756 collectMode //cb_config/collect/collect_mode
5757 archiveMode //cb_config/collect/archive_mode
5758 ignoreFile //cb_config/collect/ignore_file
5759
5760 We also add groups of the following items, one list element per
5761 item::
5762
5763 absoluteExcludePaths //cb_config/collect/exclude/abs_path
5764 excludePatterns //cb_config/collect/exclude/pattern
5765 collectFiles //cb_config/collect/file
5766 collectDirs //cb_config/collect/dir
5767
5768 The individual collect files are added by :any:`_addCollectFile` and
5769 individual collect directories are added by :any:`_addCollectDir`.
5770
5771 If ``collectConfig`` is ``None``, then no container will be added.
5772
5773 Args:
5774 xmlDom: DOM tree as from :any:`createOutputDom`
5775 parentNode: Parent that the section should be appended to
5776 collectConfig: Collect configuration section to be added to the document
5777 """
5778 if collectConfig is not None:
5779 sectionNode = addContainerNode(xmlDom, parentNode, "collect")
5780 addStringNode(xmlDom, sectionNode, "collect_dir", collectConfig.targetDir)
5781 addStringNode(xmlDom, sectionNode, "collect_mode", collectConfig.collectMode)
5782 addStringNode(xmlDom, sectionNode, "archive_mode", collectConfig.archiveMode)
5783 addStringNode(xmlDom, sectionNode, "ignore_file", collectConfig.ignoreFile)
5784 if (collectConfig.absoluteExcludePaths is not None and collectConfig.absoluteExcludePaths != []) or (
5785 collectConfig.excludePatterns is not None and collectConfig.excludePatterns != []
5786 ):
5787 excludeNode = addContainerNode(xmlDom, sectionNode, "exclude")
5788 if collectConfig.absoluteExcludePaths is not None:
5789 for absolutePath in collectConfig.absoluteExcludePaths:
5790 addStringNode(xmlDom, excludeNode, "abs_path", absolutePath)
5791 if collectConfig.excludePatterns is not None:
5792 for pattern in collectConfig.excludePatterns:
5793 addStringNode(xmlDom, excludeNode, "pattern", pattern)
5794 if collectConfig.collectFiles is not None:
5795 for collectFile in collectConfig.collectFiles:
5796 Config._addCollectFile(xmlDom, sectionNode, collectFile)
5797 if collectConfig.collectDirs is not None:
5798 for collectDir in collectConfig.collectDirs:
5799 Config._addCollectDir(xmlDom, sectionNode, collectDir)
5800
5801 @staticmethod
5802 def _addStage(xmlDom, parentNode, stageConfig):
5803 """
5804 Adds a <stage> configuration section as the next child of a parent.
5805
5806 We add the following fields to the document::
5807
5808 targetDir //cb_config/stage/staging_dir
5809
5810 We also add groups of the following items, one list element per
5811 item::
5812
5813 localPeers //cb_config/stage/peer
5814 remotePeers //cb_config/stage/peer
5815
5816 The individual local and remote peer entries are added by
5817 :any:`_addLocalPeer` and :any:`_addRemotePeer`, respectively.
5818
5819 If ``stageConfig`` is ``None``, then no container will be added.
5820
5821 Args:
5822 xmlDom: DOM tree as from :any:`createOutputDom`
5823 parentNode: Parent that the section should be appended to
5824 stageConfig: Stage configuration section to be added to the document
5825 """
5826 if stageConfig is not None:
5827 sectionNode = addContainerNode(xmlDom, parentNode, "stage")
5828 addStringNode(xmlDom, sectionNode, "staging_dir", stageConfig.targetDir)
5829 if stageConfig.localPeers is not None:
5830 for localPeer in stageConfig.localPeers:
5831 Config._addLocalPeer(xmlDom, sectionNode, localPeer)
5832 if stageConfig.remotePeers is not None:
5833 for remotePeer in stageConfig.remotePeers:
5834 Config._addRemotePeer(xmlDom, sectionNode, remotePeer)
5835
5836 @staticmethod
5837 def _addStore(xmlDom, parentNode, storeConfig):
5838 """
5839 Adds a <store> configuration section as the next child of a parent.
5840
5841 We add the following fields to the document::
5842
5843 sourceDir //cb_config/store/source_dir
5844 mediaType //cb_config/store/media_type
5845 deviceType //cb_config/store/device_type
5846 devicePath //cb_config/store/target_device
5847 deviceScsiId //cb_config/store/target_scsi_id
5848 driveSpeed //cb_config/store/drive_speed
5849 checkData //cb_config/store/check_data
5850 checkMedia //cb_config/store/check_media
5851 warnMidnite //cb_config/store/warn_midnite
5852 noEject //cb_config/store/no_eject
5853 refreshMediaDelay //cb_config/store/refresh_media_delay
5854 ejectDelay //cb_config/store/eject_delay
5855
5856 Blanking behavior configuration is added by the :any:`_addBlankBehavior`
5857 method.
5858
5859 If ``storeConfig`` is ``None``, then no container will be added.
5860
5861 Args:
5862 xmlDom: DOM tree as from :any:`createOutputDom`
5863 parentNode: Parent that the section should be appended to
5864 storeConfig: Store configuration section to be added to the document
5865 """
5866 if storeConfig is not None:
5867 sectionNode = addContainerNode(xmlDom, parentNode, "store")
5868 addStringNode(xmlDom, sectionNode, "source_dir", storeConfig.sourceDir)
5869 addStringNode(xmlDom, sectionNode, "media_type", storeConfig.mediaType)
5870 addStringNode(xmlDom, sectionNode, "device_type", storeConfig.deviceType)
5871 addStringNode(xmlDom, sectionNode, "target_device", storeConfig.devicePath)
5872 addStringNode(xmlDom, sectionNode, "target_scsi_id", storeConfig.deviceScsiId)
5873 addIntegerNode(xmlDom, sectionNode, "drive_speed", storeConfig.driveSpeed)
5874 addBooleanNode(xmlDom, sectionNode, "check_data", storeConfig.checkData)
5875 addBooleanNode(xmlDom, sectionNode, "check_media", storeConfig.checkMedia)
5876 addBooleanNode(xmlDom, sectionNode, "warn_midnite", storeConfig.warnMidnite)
5877 addBooleanNode(xmlDom, sectionNode, "no_eject", storeConfig.noEject)
5878 addIntegerNode(xmlDom, sectionNode, "refresh_media_delay", storeConfig.refreshMediaDelay)
5879 addIntegerNode(xmlDom, sectionNode, "eject_delay", storeConfig.ejectDelay)
5880 Config._addBlankBehavior(xmlDom, sectionNode, storeConfig.blankBehavior)
5881
5882 @staticmethod
5883 def _addPurge(xmlDom, parentNode, purgeConfig):
5884 """
5885 Adds a <purge> configuration section as the next child of a parent.
5886
5887 We add the following fields to the document::
5888
5889 purgeDirs //cb_config/purge/dir
5890
5891 The individual directory entries are added by :any:`_addPurgeDir`.
5892
5893 If ``purgeConfig`` is ``None``, then no container will be added.
5894
5895 Args:
5896 xmlDom: DOM tree as from :any:`createOutputDom`
5897 parentNode: Parent that the section should be appended to
5898 purgeConfig: Purge configuration section to be added to the document
5899 """
5900 if purgeConfig is not None:
5901 sectionNode = addContainerNode(xmlDom, parentNode, "purge")
5902 if purgeConfig.purgeDirs is not None:
5903 for purgeDir in purgeConfig.purgeDirs:
5904 Config._addPurgeDir(xmlDom, sectionNode, purgeDir)
5905
5906 @staticmethod
5907 def _addExtendedAction(xmlDom, parentNode, action):
5908 """
5909 Adds an extended action container as the next child of a parent.
5910
5911 We add the following fields to the document::
5912
5913 name action/name
5914 module action/module
5915 function action/function
5916 index action/index
5917 dependencies action/depends
5918
5919 Dependencies are added by the :any:`_addDependencies` method.
5920
5921 The <action> node itself is created as the next child of the parent node.
5922 This method only adds one action node. The parent must loop for each action
5923 in the ``ExtensionsConfig`` object.
5924
5925 If ``action`` is ``None``, this method call will be a no-op.
5926
5927 Args:
5928 xmlDom: DOM tree as from :any:`createOutputDom`
5929 parentNode: Parent that the section should be appended to
5930 action: Purge directory to be added to the document
5931 """
5932 if action is not None:
5933 sectionNode = addContainerNode(xmlDom, parentNode, "action")
5934 addStringNode(xmlDom, sectionNode, "name", action.name)
5935 addStringNode(xmlDom, sectionNode, "module", action.module)
5936 addStringNode(xmlDom, sectionNode, "function", action.function)
5937 addIntegerNode(xmlDom, sectionNode, "index", action.index)
5938 Config._addDependencies(xmlDom, sectionNode, action.dependencies)
5939
5940 @staticmethod
5941 def _addOverride(xmlDom, parentNode, override):
5942 """
5943 Adds a command override container as the next child of a parent.
5944
5945 We add the following fields to the document::
5946
5947 command override/command
5948 absolutePath override/abs_path
5949
5950 The <override> node itself is created as the next child of the parent
5951 node. This method only adds one override node. The parent must loop for
5952 each override in the ``OptionsConfig`` object.
5953
5954 If ``override`` is ``None``, this method call will be a no-op.
5955
5956 Args:
5957 xmlDom: DOM tree as from :any:`createOutputDom`
5958 parentNode: Parent that the section should be appended to
5959 override: Command override to be added to the document
5960 """
5961 if override is not None:
5962 sectionNode = addContainerNode(xmlDom, parentNode, "override")
5963 addStringNode(xmlDom, sectionNode, "command", override.command)
5964 addStringNode(xmlDom, sectionNode, "abs_path", override.absolutePath)
5965
5966 @staticmethod
5967 def _addHook(xmlDom, parentNode, hook):
5968 """
5969 Adds an action hook container as the next child of a parent.
5970
5971 The behavior varies depending on the value of the ``before`` and ``after``
5972 flags on the hook. If the ``before`` flag is set, it's a pre-action hook,
5973 and we'll add the following fields::
5974
5975 action pre_action_hook/action
5976 command pre_action_hook/command
5977
5978 If the ``after`` flag is set, it's a post-action hook, and we'll add the
5979 following fields::
5980
5981 action post_action_hook/action
5982 command post_action_hook/command
5983
5984 The <pre_action_hook> or <post_action_hook> node itself is created as the
5985 next child of the parent node. This method only adds one hook node. The
5986 parent must loop for each hook in the ``OptionsConfig`` object.
5987
5988 If ``hook`` is ``None``, this method call will be a no-op.
5989
5990 Args:
5991 xmlDom: DOM tree as from :any:`createOutputDom`
5992 parentNode: Parent that the section should be appended to
5993 hook: Command hook to be added to the document
5994 """
5995 if hook is not None:
5996 if hook.before:
5997 sectionNode = addContainerNode(xmlDom, parentNode, "pre_action_hook")
5998 else:
5999 sectionNode = addContainerNode(xmlDom, parentNode, "post_action_hook")
6000 addStringNode(xmlDom, sectionNode, "action", hook.action)
6001 addStringNode(xmlDom, sectionNode, "command", hook.command)
6002
6003 @staticmethod
6004 def _addCollectFile(xmlDom, parentNode, collectFile):
6005 """
6006 Adds a collect file container as the next child of a parent.
6007
6008 We add the following fields to the document::
6009
6010 absolutePath dir/abs_path
6011 collectMode dir/collect_mode
6012 archiveMode dir/archive_mode
6013
6014 Note that for consistency with collect directory handling we'll only emit
6015 the preferred ``collect_mode`` tag.
6016
6017 The <file> node itself is created as the next child of the parent node.
6018 This method only adds one collect file node. The parent must loop
6019 for each collect file in the ``CollectConfig`` object.
6020
6021 If ``collectFile`` is ``None``, this method call will be a no-op.
6022
6023 Args:
6024 xmlDom: DOM tree as from :any:`createOutputDom`
6025 parentNode: Parent that the section should be appended to
6026 collectFile: Collect file to be added to the document
6027 """
6028 if collectFile is not None:
6029 sectionNode = addContainerNode(xmlDom, parentNode, "file")
6030 addStringNode(xmlDom, sectionNode, "abs_path", collectFile.absolutePath)
6031 addStringNode(xmlDom, sectionNode, "collect_mode", collectFile.collectMode)
6032 addStringNode(xmlDom, sectionNode, "archive_mode", collectFile.archiveMode)
6033
6034 @staticmethod
6035 def _addCollectDir(xmlDom, parentNode, collectDir):
6036 """
6037 Adds a collect directory container as the next child of a parent.
6038
6039 We add the following fields to the document::
6040
6041 absolutePath dir/abs_path
6042 collectMode dir/collect_mode
6043 archiveMode dir/archive_mode
6044 ignoreFile dir/ignore_file
6045 linkDepth dir/link_depth
6046 dereference dir/dereference
6047 recursionLevel dir/recursion_level
6048
6049 Note that an original XML document might have listed the collect mode
6050 using the ``mode`` tag, since we accept both ``collect_mode`` and ``mode``.
6051 However, here we'll only emit the preferred ``collect_mode`` tag.
6052
6053 We also add groups of the following items, one list element per item::
6054
6055 absoluteExcludePaths dir/exclude/abs_path
6056 relativeExcludePaths dir/exclude/rel_path
6057 excludePatterns dir/exclude/pattern
6058
6059 The <dir> node itself is created as the next child of the parent node.
6060 This method only adds one collect directory node. The parent must loop
6061 for each collect directory in the ``CollectConfig`` object.
6062
6063 If ``collectDir`` is ``None``, this method call will be a no-op.
6064
6065 Args:
6066 xmlDom: DOM tree as from :any:`createOutputDom`
6067 parentNode: Parent that the section should be appended to
6068 collectDir: Collect directory to be added to the document
6069 """
6070 if collectDir is not None:
6071 sectionNode = addContainerNode(xmlDom, parentNode, "dir")
6072 addStringNode(xmlDom, sectionNode, "abs_path", collectDir.absolutePath)
6073 addStringNode(xmlDom, sectionNode, "collect_mode", collectDir.collectMode)
6074 addStringNode(xmlDom, sectionNode, "archive_mode", collectDir.archiveMode)
6075 addStringNode(xmlDom, sectionNode, "ignore_file", collectDir.ignoreFile)
6076 addIntegerNode(xmlDom, sectionNode, "link_depth", collectDir.linkDepth)
6077 addBooleanNode(xmlDom, sectionNode, "dereference", collectDir.dereference)
6078 addIntegerNode(xmlDom, sectionNode, "recursion_level", collectDir.recursionLevel)
6079 if (
6080 (collectDir.absoluteExcludePaths is not None and collectDir.absoluteExcludePaths != [])
6081 or (collectDir.relativeExcludePaths is not None and collectDir.relativeExcludePaths != [])
6082 or (collectDir.excludePatterns is not None and collectDir.excludePatterns != [])
6083 ):
6084 excludeNode = addContainerNode(xmlDom, sectionNode, "exclude")
6085 if collectDir.absoluteExcludePaths is not None:
6086 for absolutePath in collectDir.absoluteExcludePaths:
6087 addStringNode(xmlDom, excludeNode, "abs_path", absolutePath)
6088 if collectDir.relativeExcludePaths is not None:
6089 for relativePath in collectDir.relativeExcludePaths:
6090 addStringNode(xmlDom, excludeNode, "rel_path", relativePath)
6091 if collectDir.excludePatterns is not None:
6092 for pattern in collectDir.excludePatterns:
6093 addStringNode(xmlDom, excludeNode, "pattern", pattern)
6094
6095 @staticmethod
6096 def _addLocalPeer(xmlDom, parentNode, localPeer):
6097 """
6098 Adds a local peer container as the next child of a parent.
6099
6100 We add the following fields to the document::
6101
6102 name peer/name
6103 collectDir peer/collect_dir
6104 ignoreFailureMode peer/ignore_failures
6105
6106 Additionally, ``peer/type`` is filled in with ``"local"``, since this is a
6107 local peer.
6108
6109 The <peer> node itself is created as the next child of the parent node.
6110 This method only adds one peer node. The parent must loop for each peer
6111 in the ``StageConfig`` object.
6112
6113 If ``localPeer`` is ``None``, this method call will be a no-op.
6114
6115 Args:
6116 xmlDom: DOM tree as from :any:`createOutputDom`
6117 parentNode: Parent that the section should be appended to
6118 localPeer: Purge directory to be added to the document
6119 """
6120 if localPeer is not None:
6121 sectionNode = addContainerNode(xmlDom, parentNode, "peer")
6122 addStringNode(xmlDom, sectionNode, "name", localPeer.name)
6123 addStringNode(xmlDom, sectionNode, "type", "local")
6124 addStringNode(xmlDom, sectionNode, "collect_dir", localPeer.collectDir)
6125 addStringNode(xmlDom, sectionNode, "ignore_failures", localPeer.ignoreFailureMode)
6126
6127 @staticmethod
6128 def _addRemotePeer(xmlDom, parentNode, remotePeer):
6129 """
6130 Adds a remote peer container as the next child of a parent.
6131
6132 We add the following fields to the document::
6133
6134 name peer/name
6135 collectDir peer/collect_dir
6136 remoteUser peer/backup_user
6137 rcpCommand peer/rcp_command
6138 rcpCommand peer/rcp_command
6139 rshCommand peer/rsh_command
6140 cbackCommand peer/cback_command
6141 ignoreFailureMode peer/ignore_failures
6142 managed peer/managed
6143 managedActions peer/managed_actions
6144
6145 Additionally, ``peer/type`` is filled in with ``"remote"``, since this is a
6146 remote peer.
6147
6148 The <peer> node itself is created as the next child of the parent node.
6149 This method only adds one peer node. The parent must loop for each peer
6150 in the ``StageConfig`` object.
6151
6152 If ``remotePeer`` is ``None``, this method call will be a no-op.
6153
6154 Args:
6155 xmlDom: DOM tree as from :any:`createOutputDom`
6156 parentNode: Parent that the section should be appended to
6157 remotePeer: Purge directory to be added to the document
6158 """
6159 if remotePeer is not None:
6160 sectionNode = addContainerNode(xmlDom, parentNode, "peer")
6161 addStringNode(xmlDom, sectionNode, "name", remotePeer.name)
6162 addStringNode(xmlDom, sectionNode, "type", "remote")
6163 addStringNode(xmlDom, sectionNode, "collect_dir", remotePeer.collectDir)
6164 addStringNode(xmlDom, sectionNode, "backup_user", remotePeer.remoteUser)
6165 addStringNode(xmlDom, sectionNode, "rcp_command", remotePeer.rcpCommand)
6166 addStringNode(xmlDom, sectionNode, "rsh_command", remotePeer.rshCommand)
6167 addStringNode(xmlDom, sectionNode, "cback_command", remotePeer.cbackCommand)
6168 addStringNode(xmlDom, sectionNode, "ignore_failures", remotePeer.ignoreFailureMode)
6169 addBooleanNode(xmlDom, sectionNode, "managed", remotePeer.managed)
6170 managedActions = Config._buildCommaSeparatedString(remotePeer.managedActions)
6171 addStringNode(xmlDom, sectionNode, "managed_actions", managedActions)
6172
6173 @staticmethod
6174 def _addPurgeDir(xmlDom, parentNode, purgeDir):
6175 """
6176 Adds a purge directory container as the next child of a parent.
6177
6178 We add the following fields to the document::
6179
6180 absolutePath dir/abs_path
6181 retainDays dir/retain_days
6182
6183 The <dir> node itself is created as the next child of the parent node.
6184 This method only adds one purge directory node. The parent must loop for
6185 each purge directory in the ``PurgeConfig`` object.
6186
6187 If ``purgeDir`` is ``None``, this method call will be a no-op.
6188
6189 Args:
6190 xmlDom: DOM tree as from :any:`createOutputDom`
6191 parentNode: Parent that the section should be appended to
6192 purgeDir: Purge directory to be added to the document
6193 """
6194 if purgeDir is not None:
6195 sectionNode = addContainerNode(xmlDom, parentNode, "dir")
6196 addStringNode(xmlDom, sectionNode, "abs_path", purgeDir.absolutePath)
6197 addIntegerNode(xmlDom, sectionNode, "retain_days", purgeDir.retainDays)
6198
6199 @staticmethod
6200 def _addDependencies(xmlDom, parentNode, dependencies):
6201 """
6202 Adds a extended action dependencies to parent node.
6203
6204 We add the following fields to the document::
6205
6206 runBefore depends/run_before
6207 runAfter depends/run_after
6208
6209 If ``dependencies`` is ``None``, this method call will be a no-op.
6210
6211 Args:
6212 xmlDom: DOM tree as from :any:`createOutputDom`
6213 parentNode: Parent that the section should be appended to
6214 dependencies: ``ActionDependencies`` object to be added to the document
6215 """
6216 if dependencies is not None:
6217 sectionNode = addContainerNode(xmlDom, parentNode, "depends")
6218 runBefore = Config._buildCommaSeparatedString(dependencies.beforeList)
6219 runAfter = Config._buildCommaSeparatedString(dependencies.afterList)
6220 addStringNode(xmlDom, sectionNode, "run_before", runBefore)
6221 addStringNode(xmlDom, sectionNode, "run_after", runAfter)
6222
6223 @staticmethod
6224 def _buildCommaSeparatedString(valueList):
6225 """
6226 Creates a comma-separated string from a list of values.
6227
6228 As a special case, if ``valueList`` is ``None``, then ``None`` will be
6229 returned.
6230
6231 Args:
6232 valueList: List of values to be placed into a string
6233
6234 Returns:
6235 Values from valueList as a comma-separated string
6236 """
6237 if valueList is None:
6238 return None
6239 return ",".join(valueList)
6240
6241 @staticmethod
6242 def _addBlankBehavior(xmlDom, parentNode, blankBehavior):
6243 """
6244 Adds a blanking behavior container as the next child of a parent.
6245
6246 We add the following fields to the document::
6247
6248 blankMode blank_behavior/mode
6249 blankFactor blank_behavior/factor
6250
6251 The <blank_behavior> node itself is created as the next child of the
6252 parent node.
6253
6254 If ``blankBehavior`` is ``None``, this method call will be a no-op.
6255
6256 Args:
6257 xmlDom: DOM tree as from :any:`createOutputDom`
6258 parentNode: Parent that the section should be appended to
6259 blankBehavior: Blanking behavior to be added to the document
6260 """
6261 if blankBehavior is not None:
6262 sectionNode = addContainerNode(xmlDom, parentNode, "blank_behavior")
6263 addStringNode(xmlDom, sectionNode, "mode", blankBehavior.blankMode)
6264 addStringNode(xmlDom, sectionNode, "factor", blankBehavior.blankFactor)
6265
6266 #################################################
6267 # High-level methods used for validating content
6268 #################################################
6269
6270 def _validateContents(self):
6271 """
6272 Validates configuration contents per rules discussed in module
6273 documentation.
6274
6275 This is the second pass at validation. It ensures that any filled-in
6276 section contains valid data. Any sections which is not set to ``None`` is
6277 validated per the rules for that section, laid out in the module
6278 documentation (above).
6279
6280 Raises:
6281 ValueError: If configuration is invalid
6282 """
6283 self._validateReference()
6284 self._validateExtensions()
6285 self._validateOptions()
6286 self._validatePeers()
6287 self._validateCollect()
6288 self._validateStage()
6289 self._validateStore()
6290 self._validatePurge()
6291
6292 def _validateReference(self):
6293 """
6294 Validates reference configuration.
6295 There are currently no reference-related validations.
6296 Raises:
6297 ValueError: If reference configuration is invalid
6298 """
6299
6300 def _validateExtensions(self):
6301 """
6302 Validates extensions configuration.
6303
6304 The list of actions may be either ``None`` or an empty list ``[]`` if
6305 desired. Each extended action must include a name, a module, and a
6306 function.
6307
6308 Then, if the order mode is None or "index", an index is required; and if
6309 the order mode is "dependency", dependency information is required.
6310
6311 Raises:
6312 ValueError: If reference configuration is invalid
6313 """
6314 if self.extensions is not None:
6315 if self.extensions.actions is not None:
6316 names = []
6317 for action in self.extensions.actions:
6318 if action.name is None:
6319 raise ValueError("Each extended action must set a name.")
6320 names.append(action.name)
6321 if action.module is None:
6322 raise ValueError("Each extended action must set a module.")
6323 if action.function is None:
6324 raise ValueError("Each extended action must set a function.")
6325 if self.extensions.orderMode is None or self.extensions.orderMode == "index":
6326 if action.index is None:
6327 raise ValueError("Each extended action must set an index, based on order mode.")
6328 elif self.extensions.orderMode == "dependency":
6329 if action.dependencies is None:
6330 raise ValueError("Each extended action must set dependency information, based on order mode.")
6331 checkUnique("Duplicate extension names exist:", names)
6332
6333 def _validateOptions(self):
6334 """
6335 Validates options configuration.
6336
6337 All fields must be filled in except the rsh command. The rcp and rsh
6338 commands are used as default values for all remote peers. Remote peers
6339 can also rely on the backup user as the default remote user name if they
6340 choose.
6341
6342 Raises:
6343 ValueError: If reference configuration is invalid
6344 """
6345 if self.options is not None:
6346 if self.options.startingDay is None:
6347 raise ValueError("Options section starting day must be filled in.")
6348 if self.options.workingDir is None:
6349 raise ValueError("Options section working directory must be filled in.")
6350 if self.options.backupUser is None:
6351 raise ValueError("Options section backup user must be filled in.")
6352 if self.options.backupGroup is None:
6353 raise ValueError("Options section backup group must be filled in.")
6354 if self.options.rcpCommand is None:
6355 raise ValueError("Options section remote copy command must be filled in.")
6356
6357 def _validatePeers(self):
6358 """
6359 Validates peers configuration per rules in :any:`_validatePeerList`.
6360 Raises:
6361 ValueError: If peers configuration is invalid
6362 """
6363 if self.peers is not None:
6364 self._validatePeerList(self.peers.localPeers, self.peers.remotePeers)
6365
6366 def _validateCollect(self):
6367 """
6368 Validates collect configuration.
6369
6370 The target directory must be filled in. The collect mode, archive mode,
6371 ignore file, and recursion level are all optional. The list of absolute
6372 paths to exclude and patterns to exclude may be either ``None`` or an
6373 empty list ``[]`` if desired.
6374
6375 Each collect directory entry must contain an absolute path to collect,
6376 and then must either be able to take collect mode, archive mode and
6377 ignore file configuration from the parent ``CollectConfig`` object, or
6378 must set each value on its own. The list of absolute paths to exclude,
6379 relative paths to exclude and patterns to exclude may be either ``None``
6380 or an empty list ``[]`` if desired. Any list of absolute paths to exclude
6381 or patterns to exclude will be combined with the same list in the
6382 ``CollectConfig`` object to make the complete list for a given directory.
6383
6384 Raises:
6385 ValueError: If collect configuration is invalid
6386 """
6387 if self.collect is not None:
6388 if self.collect.targetDir is None:
6389 raise ValueError("Collect section target directory must be filled in.")
6390 if self.collect.collectFiles is not None:
6391 for collectFile in self.collect.collectFiles:
6392 if collectFile.absolutePath is None:
6393 raise ValueError("Each collect file must set an absolute path.")
6394 if self.collect.collectMode is None and collectFile.collectMode is None:
6395 raise ValueError("Collect mode must either be set in parent collect section or individual collect file.")
6396 if self.collect.archiveMode is None and collectFile.archiveMode is None:
6397 raise ValueError("Archive mode must either be set in parent collect section or individual collect file.")
6398 if self.collect.collectDirs is not None:
6399 for collectDir in self.collect.collectDirs:
6400 if collectDir.absolutePath is None:
6401 raise ValueError("Each collect directory must set an absolute path.")
6402 if self.collect.collectMode is None and collectDir.collectMode is None:
6403 raise ValueError(
6404 "Collect mode must either be set in parent collect section or individual collect directory."
6405 )
6406 if self.collect.archiveMode is None and collectDir.archiveMode is None:
6407 raise ValueError(
6408 "Archive mode must either be set in parent collect section or individual collect directory."
6409 )
6410 if self.collect.ignoreFile is None and collectDir.ignoreFile is None:
6411 raise ValueError(
6412 "Ignore file must either be set in parent collect section or individual collect directory."
6413 )
6414 if (collectDir.linkDepth is None or collectDir.linkDepth < 1) and collectDir.dereference:
6415 raise ValueError("Dereference flag is only valid when a non-zero link depth is in use.")
6416
6417 def _validateStage(self):
6418 """
6419 Validates stage configuration.
6420
6421 The target directory must be filled in, and the peers are
6422 also validated.
6423
6424 Peers are only required in this section if the peers configuration
6425 section is not filled in. However, if any peers are filled in
6426 here, they override the peers configuration and must meet the
6427 validation criteria in :any:`_validatePeerList`.
6428
6429 Raises:
6430 ValueError: If stage configuration is invalid
6431 """
6432 if self.stage is not None:
6433 if self.stage.targetDir is None:
6434 raise ValueError("Stage section target directory must be filled in.")
6435 if self.peers is None:
6436 # In this case, stage configuration is our only configuration and must be valid.
6437 self._validatePeerList(self.stage.localPeers, self.stage.remotePeers)
6438 else:
6439 # In this case, peers configuration is the default and stage configuration overrides.
6440 # Validation is only needed if it's stage configuration is actually filled in.
6441 if self.stage.hasPeers():
6442 self._validatePeerList(self.stage.localPeers, self.stage.remotePeers)
6443
6444 def _validateStore(self):
6445 """
6446 Validates store configuration.
6447
6448 The device type, drive speed, and blanking behavior are optional. All
6449 other values are required. Missing booleans will be set to defaults.
6450
6451 If blanking behavior is provided, then both a blanking mode and a
6452 blanking factor are required.
6453
6454 The image writer functionality in the ``writer`` module is supposed to be
6455 able to handle a device speed of ``None``.
6456
6457 Any caller which needs a "real" (non-``None``) value for the device type
6458 can use ``DEFAULT_DEVICE_TYPE``, which is guaranteed to be sensible.
6459
6460 This is also where we make sure that the media type -- which is already a
6461 valid type -- matches up properly with the device type.
6462
6463 Raises:
6464 ValueError: If store configuration is invalid
6465 """
6466 if self.store is not None:
6467 if self.store.sourceDir is None:
6468 raise ValueError("Store section source directory must be filled in.")
6469 if self.store.mediaType is None:
6470 raise ValueError("Store section media type must be filled in.")
6471 if self.store.devicePath is None:
6472 raise ValueError("Store section device path must be filled in.")
6473 if self.store.deviceType is None or self.store.deviceType == "cdwriter":
6474 if self.store.mediaType not in VALID_CD_MEDIA_TYPES:
6475 raise ValueError("Media type must match device type.")
6476 elif self.store.deviceType == "dvdwriter":
6477 if self.store.mediaType not in VALID_DVD_MEDIA_TYPES:
6478 raise ValueError("Media type must match device type.")
6479 if self.store.blankBehavior is not None:
6480 if self.store.blankBehavior.blankMode is None and self.store.blankBehavior.blankFactor is None:
6481 raise ValueError("If blanking behavior is provided, all values must be filled in.")
6482
6483 def _validatePurge(self):
6484 """
6485 Validates purge configuration.
6486
6487 The list of purge directories may be either ``None`` or an empty list
6488 ``[]`` if desired. All purge directories must contain a path and a retain
6489 days value.
6490
6491 Raises:
6492 ValueError: If purge configuration is invalid
6493 """
6494 if self.purge is not None:
6495 if self.purge.purgeDirs is not None:
6496 for purgeDir in self.purge.purgeDirs:
6497 if purgeDir.absolutePath is None:
6498 raise ValueError("Each purge directory must set an absolute path.")
6499 if purgeDir.retainDays is None:
6500 raise ValueError("Each purge directory must set a retain days value.")
6501
6502 def _validatePeerList(self, localPeers, remotePeers):
6503 """
6504 Validates the set of local and remote peers.
6505
6506 Local peers must be completely filled in, including both name and collect
6507 directory. Remote peers must also fill in the name and collect
6508 directory, but can leave the remote user and rcp command unset. In this
6509 case, the remote user is assumed to match the backup user from the
6510 options section and rcp command is taken directly from the options
6511 section.
6512
6513 Args:
6514 localPeers: List of local peers
6515 remotePeers: List of remote peers
6516
6517 Raises:
6518 ValueError: If stage configuration is invalid
6519 """
6520 if localPeers is None and remotePeers is None:
6521 raise ValueError("Peer list must contain at least one backup peer.")
6522 if localPeers is None and remotePeers is not None:
6523 if len(remotePeers) < 1:
6524 raise ValueError("Peer list must contain at least one backup peer.")
6525 elif localPeers is not None and remotePeers is None:
6526 if len(localPeers) < 1:
6527 raise ValueError("Peer list must contain at least one backup peer.")
6528 elif localPeers is not None and remotePeers is not None:
6529 if len(localPeers) + len(remotePeers) < 1:
6530 raise ValueError("Peer list must contain at least one backup peer.")
6531 names = []
6532 if localPeers is not None:
6533 for localPeer in localPeers:
6534 if localPeer.name is None:
6535 raise ValueError("Local peers must set a name.")
6536 names.append(localPeer.name)
6537 if localPeer.collectDir is None:
6538 raise ValueError("Local peers must set a collect directory.")
6539 if remotePeers is not None:
6540 for remotePeer in remotePeers:
6541 if remotePeer.name is None:
6542 raise ValueError("Remote peers must set a name.")
6543 names.append(remotePeer.name)
6544 if remotePeer.collectDir is None:
6545 raise ValueError("Remote peers must set a collect directory.")
6546 if (self.options is None or self.options.backupUser is None) and remotePeer.remoteUser is None:
6547 raise ValueError("Remote user must either be set in options section or individual remote peer.")
6548 if (self.options is None or self.options.rcpCommand is None) and remotePeer.rcpCommand is None:
6549 raise ValueError("Remote copy command must either be set in options section or individual remote peer.")
6550 if remotePeer.managed:
6551 if (self.options is None or self.options.rshCommand is None) and remotePeer.rshCommand is None:
6552 raise ValueError("Remote shell command must either be set in options section or individual remote peer.")
6553 if (self.options is None or self.options.cbackCommand is None) and remotePeer.cbackCommand is None:
6554 raise ValueError("Remote cback command must either be set in options section or individual remote peer.")
6555 if (self.options is None or self.options.managedActions is None or len(self.options.managedActions) < 1) and (
6556 remotePeer.managedActions is None or len(remotePeer.managedActions) < 1
6557 ):
6558 raise ValueError("Managed actions list must be set in options section or individual remote peer.")
6559 checkUnique("Duplicate peer names exist:", names)
6560
6561
6562 ########################################################################
6563 # General utility functions
6564 ########################################################################
6565
6566
6567 def readByteQuantity(parent, name):
6568 """
6569 Read a byte size value from an XML document.
6570
6571 A byte size value is an interpreted string value. If the string value
6572 ends with "MB" or "GB", then the string before that is interpreted as
6573 megabytes or gigabytes. Otherwise, it is intepreted as bytes.
6574
6575 Args:
6576 parent: Parent node to search beneath
6577 name: Name of node to search for
6578
6579 Returns:
6580 ByteQuantity parsed from XML document
6581 """
6582 data = readString(parent, name)
6583 if data is None:
6584 return None
6585 data = data.strip()
6586 if data.endswith("KB"):
6587 quantity = data[0 : data.rfind("KB")].strip()
6588 units = UNIT_KBYTES
6589 elif data.endswith("MB"):
6590 quantity = data[0 : data.rfind("MB")].strip()
6591 units = UNIT_MBYTES
6592 elif data.endswith("GB"):
6593 quantity = data[0 : data.rfind("GB")].strip()
6594 units = UNIT_GBYTES
6595 else:
6596 quantity = data.strip()
6597 units = UNIT_BYTES
6598 return ByteQuantity(quantity, units)
6599
6600
6601 def addByteQuantityNode(xmlDom, parentNode, nodeName, byteQuantity):
6602 """
6603 Adds a text node as the next child of a parent, to contain a byte size.
6604
6605 If the ``byteQuantity`` is None, then the node will be created, but will
6606 be empty (i.e. will contain no text node child).
6607
6608 The size in bytes will be normalized. If it is larger than 1.0 GB, it will
6609 be shown in GB ("1.0 GB"). If it is larger than 1.0 MB ("1.0 MB"), it will
6610 be shown in MB. Otherwise, it will be shown in bytes ("423413").
6611
6612 Args:
6613 xmlDom: DOM tree as from ``impl.createDocument()``
6614 parentNode: Parent node to create child for
6615 nodeName: Name of the new container node
6616 byteQuantity: ByteQuantity object to put into the XML document
6617
6618 Returns:
6619 Reference to the newly-created node
6620 """
6621 if byteQuantity is None:
6622 byteString = None
6623 elif byteQuantity.units == UNIT_KBYTES:
6624 byteString = "%s KB" % byteQuantity.quantity
6625 elif byteQuantity.units == UNIT_MBYTES:
6626 byteString = "%s MB" % byteQuantity.quantity
6627 elif byteQuantity.units == UNIT_GBYTES:
6628 byteString = "%s GB" % byteQuantity.quantity
6629 else:
6630 byteString = byteQuantity.quantity
6631 return addStringNode(xmlDom, parentNode, nodeName, byteString)