Debian Codegraph @

src/CedarBackup3/filesystem.py

raw
1 # vim: set ft=python ts=4 sw=4 expandtab:
2 # ruff: file-ignore[redefined-loop-name] # the code appars to work and changing it is risky
3 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4 #
5 # C E D A R
6 # S O L U T I O N S "Software done right."
7 # S O F T W A R E
8 #
9 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
10 #
11 # Copyright (c) 2004-2008,2010,2015 Kenneth J. Pronovici.
12 # All rights reserved.
13 #
14 # This program is free software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License,
16 # Version 2, as published by the Free Software Foundation.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
21 #
22 # Copies of the GNU General Public License are available from
23 # the Free Software Foundation website, http://www.gnu.org/.
24 #
25 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
26 #
27 # Author : Kenneth J. Pronovici <[email protected]>
28 # Language : Python 3
29 # Project : Cedar Backup, release 3
30 # Purpose : Provides filesystem-related objects.
31 #
32 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
33
34 ########################################################################
35 # Module documentation
36 ########################################################################
37
38 """
39 Provides filesystem-related objects.
40 :author: Kenneth J. Pronovici <[email protected]>
41 """
42
43
44 ########################################################################
45 # Imported modules
46 ########################################################################
47
48 import hashlib
49 import logging
50 import math
51 import os
52 import re
53 import tarfile
54
55 from CedarBackup3.knapsack import alternateFit, bestFit, firstFit, worstFit
56 from CedarBackup3.util import (
57 AbsolutePathList,
58 RegexList,
59 UnorderedList,
60 calculateFileAge,
61 dereferenceLink,
62 displayBytes,
63 encodePath,
64 pathJoin,
65 removeKeys,
66 )
67
68 ########################################################################
69 # Module-wide variables
70 ########################################################################
71
72 logger = logging.getLogger("CedarBackup3.log.filesystem")
73
74
75 ########################################################################
76 # FilesystemList class definition
77 ########################################################################
78
79
80 class FilesystemList(list):
81 ######################
82 # Class documentation
83 ######################
84
85 """
86 Represents a list of filesystem items.
87
88 This is a generic class that represents a list of filesystem items. Callers
89 can add individual files or directories to the list, or can recursively add
90 the contents of a directory. The class also allows for up-front exclusions
91 in several forms (all files, all directories, all items matching a pattern,
92 all items whose basename matches a pattern, or all directories containing a
93 specific "ignore file"). Symbolic links are typically backed up
94 non-recursively, i.e. the link to a directory is backed up, but not the
95 contents of that link (we don't want to deal with recursive loops, etc.).
96
97 The custom methods such as :any:`addFile` will only add items if they exist on
98 the filesystem and do not match any exclusions that are already in place.
99 However, since a FilesystemList is a subclass of Python's standard list
100 class, callers can also add items to the list in the usual way, using
101 methods like ``append()`` or ``insert()``. No validations apply to items
102 added to the list in this way; however, many list-manipulation methods deal
103 "gracefully" with items that don't exist in the filesystem, often by
104 ignoring them.
105
106 Once a list has been created, callers can remove individual items from the
107 list using standard methods like ``pop()`` or ``remove()`` or they can use
108 custom methods to remove specific types of entries or entries which match a
109 particular pattern.
110
111 *Note:* Regular expression patterns that apply to paths are assumed to be
112 bounded at front and back by the beginning and end of the string, i.e. they
113 are treated as if they begin with ``^`` and end with ``$``. This is true
114 whether we are matching a complete path or a basename.
115
116 """
117
118 ##############
119 # Constructor
120 ##############
121
122 def __init__(self):
123 """Initializes a list with no configured exclusions."""
124 list.__init__(self)
125 self._excludeFiles = False
126 self._excludeDirs = False
127 self._excludeLinks = False
128 self._excludePaths = None
129 self._excludePatterns = None
130 self._excludeBasenamePatterns = None
131 self._ignoreFile = None
132 self.excludeFiles = False
133 self.excludeLinks = False
134 self.excludeDirs = False
135 self.excludePaths = []
136 self.excludePatterns = RegexList()
137 self.excludeBasenamePatterns = RegexList()
138 self.ignoreFile = None
139
140 #############
141 # Properties
142 #############
143
144 def _setExcludeFiles(self, value):
145 """
146 Property target used to set the exclude files flag.
147 No validations, but we normalize the value to ``True`` or ``False``.
148 """
149 if value:
150 self._excludeFiles = True
151 else:
152 self._excludeFiles = False
153
154 def _getExcludeFiles(self):
155 """
156 Property target used to get the exclude files flag.
157 """
158 return self._excludeFiles
159
160 def _setExcludeDirs(self, value):
161 """
162 Property target used to set the exclude directories flag.
163 No validations, but we normalize the value to ``True`` or ``False``.
164 """
165 if value:
166 self._excludeDirs = True
167 else:
168 self._excludeDirs = False
169
170 def _getExcludeDirs(self):
171 """
172 Property target used to get the exclude directories flag.
173 """
174 return self._excludeDirs
175
176 def _setExcludeLinks(self, value):
177 """
178 Property target used to set the exclude soft links flag.
179 No validations, but we normalize the value to ``True`` or ``False``.
180 """
181 if value:
182 self._excludeLinks = True
183 else:
184 self._excludeLinks = False
185
186 def _getExcludeLinks(self):
187 """
188 Property target used to get the exclude soft links flag.
189 """
190 return self._excludeLinks
191
192 def _setExcludePaths(self, value):
193 """
194 Property target used to set the exclude paths list.
195 A ``None`` value is converted to an empty list.
196 Elements do not have to exist on disk at the time of assignment.
197 Raises:
198 ValueError: If any list element is not an absolute path
199 """
200 self._excludePaths = AbsolutePathList()
201 if value is not None:
202 self._excludePaths.extend(value)
203
204 def _getExcludePaths(self):
205 """
206 Property target used to get the absolute exclude paths list.
207 """
208 return self._excludePaths
209
210 def _setExcludePatterns(self, value):
211 """
212 Property target used to set the exclude patterns list.
213 A ``None`` value is converted to an empty list.
214 """
215 self._excludePatterns = RegexList()
216 if value is not None:
217 self._excludePatterns.extend(value)
218
219 def _getExcludePatterns(self):
220 """
221 Property target used to get the exclude patterns list.
222 """
223 return self._excludePatterns
224
225 def _setExcludeBasenamePatterns(self, value):
226 """
227 Property target used to set the exclude basename patterns list.
228 A ``None`` value is converted to an empty list.
229 """
230 self._excludeBasenamePatterns = RegexList()
231 if value is not None:
232 self._excludeBasenamePatterns.extend(value)
233
234 def _getExcludeBasenamePatterns(self):
235 """
236 Property target used to get the exclude basename patterns list.
237 """
238 return self._excludeBasenamePatterns
239
240 def _setIgnoreFile(self, value):
241 """
242 Property target used to set the ignore file.
243 The value must be a non-empty string if it is not ``None``.
244 Raises:
245 ValueError: If the value is an empty string
246 """
247 if value is not None:
248 if len(value) < 1:
249 raise ValueError("The ignore file must be a non-empty string.")
250 self._ignoreFile = value
251
252 def _getIgnoreFile(self):
253 """
254 Property target used to get the ignore file.
255 """
256 return self._ignoreFile
257
258 excludeFiles = property(_getExcludeFiles, _setExcludeFiles, None, "Boolean indicating whether files should be excluded.")
259 excludeDirs = property(_getExcludeDirs, _setExcludeDirs, None, "Boolean indicating whether directories should be excluded.")
260 excludeLinks = property(_getExcludeLinks, _setExcludeLinks, None, "Boolean indicating whether soft links should be excluded.")
261 excludePaths = property(_getExcludePaths, _setExcludePaths, None, "List of absolute paths to be excluded.")
262 excludePatterns = property(
263 _getExcludePatterns,
264 _setExcludePatterns,
265 None,
266 "List of regular expression patterns (matching complete path) to be excluded.",
267 )
268 excludeBasenamePatterns = property(
269 _getExcludeBasenamePatterns,
270 _setExcludeBasenamePatterns,
271 None,
272 "List of regular expression patterns (matching basename) to be excluded.",
273 )
274 ignoreFile = property(_getIgnoreFile, _setIgnoreFile, None, "Name of file which will cause directory contents to be ignored.")
275
276 ##############
277 # Add methods
278 ##############
279
280 def addFile(self, path):
281 """
282 Adds a file to the list.
283
284 The path must exist and must be a file or a link to an existing file. It
285 will be added to the list subject to any exclusions that are in place.
286
287 Args:
288 path (String representing a path on disk): File path to be added to the list
289 Returns:
290 Number of items added to the list
291
292 Raises:
293 ValueError: If path is not a file or does not exist
294 ValueError: If the path could not be encoded properly
295 """
296 path = encodePath(path)
297 path = normalizeFile(path)
298 if not os.path.exists(path) or not os.path.isfile(path):
299 logger.debug("Path [%s] is not a file or does not exist on disk.", path)
300 raise ValueError("Path is not a file or does not exist on disk.")
301 if self.excludeLinks and os.path.islink(path):
302 logger.debug("Path [%s] is excluded based on excludeLinks.", path)
303 return 0
304 if self.excludeFiles:
305 logger.debug("Path [%s] is excluded based on excludeFiles.", path)
306 return 0
307 if path in self.excludePaths:
308 logger.debug("Path [%s] is excluded based on excludePaths.", path)
309 return 0
310 for pattern in self.excludePatterns:
311 pattern = encodePath(pattern) # use same encoding as filenames
312 if re.compile(r"^%s$" % pattern).match(path): # safe to assume all are valid due to RegexList
313 logger.debug("Path [%s] is excluded based on pattern [%s].", path, pattern)
314 return 0
315 for pattern in self.excludeBasenamePatterns: # safe to assume all are valid due to RegexList
316 pattern = encodePath(pattern) # use same encoding as filenames
317 if re.compile(r"^%s$" % pattern).match(os.path.basename(path)):
318 logger.debug("Path [%s] is excluded based on basename pattern [%s].", path, pattern)
319 return 0
320 self.append(path)
321 logger.debug("Added file to list: [%s]", path)
322 return 1
323
324 def addDir(self, path):
325 """
326 Adds a directory to the list.
327
328 The path must exist and must be a directory or a link to an existing
329 directory. It will be added to the list subject to any exclusions that
330 are in place. The :any:`ignoreFile` does not apply to this method, only to
331 :any:`addDirContents`.
332
333 Args:
334 path (String representing a path on disk): Directory path to be added to the list
335 Returns:
336 Number of items added to the list
337
338 Raises:
339 ValueError: If path is not a directory or does not exist
340 ValueError: If the path could not be encoded properly
341 """
342 path = encodePath(path)
343 path = normalizeDir(path)
344 if not os.path.exists(path) or not os.path.isdir(path):
345 logger.debug("Path [%s] is not a directory or does not exist on disk.", path)
346 raise ValueError("Path is not a directory or does not exist on disk.")
347 if self.excludeLinks and os.path.islink(path):
348 logger.debug("Path [%s] is excluded based on excludeLinks.", path)
349 return 0
350 if self.excludeDirs:
351 logger.debug("Path [%s] is excluded based on excludeDirs.", path)
352 return 0
353 if path in self.excludePaths:
354 logger.debug("Path [%s] is excluded based on excludePaths.", path)
355 return 0
356 for pattern in self.excludePatterns: # safe to assume all are valid due to RegexList
357 pattern = encodePath(pattern) # use same encoding as filenames
358 if re.compile(r"^%s$" % pattern).match(path):
359 logger.debug("Path [%s] is excluded based on pattern [%s].", path, pattern)
360 return 0
361 for pattern in self.excludeBasenamePatterns: # safe to assume all are valid due to RegexList
362 pattern = encodePath(pattern) # use same encoding as filenames
363 if re.compile(r"^%s$" % pattern).match(os.path.basename(path)):
364 logger.debug("Path [%s] is excluded based on basename pattern [%s].", path, pattern)
365 return 0
366 self.append(path)
367 logger.debug("Added directory to list: [%s]", path)
368 return 1
369
370 def addDirContents(self, path, recursive=True, addSelf=True, linkDepth=0, dereference=False):
371 """
372 Adds the contents of a directory to the list.
373
374 The path must exist and must be a directory or a link to a directory.
375 The contents of the directory (as well as the directory path itself) will
376 be recursively added to the list, subject to any exclusions that are in
377 place. If you only want the directory and its immediate contents to be
378 added, then pass in ``recursive=False``.
379
380 *Note:* If a directory's absolute path matches an exclude pattern or path,
381 or if the directory contains the configured ignore file, then the
382 directory and all of its contents will be recursively excluded from the
383 list.
384
385 *Note:* If the passed-in directory happens to be a soft link, it will be
386 recursed. However, the linkDepth parameter controls whether any soft
387 links *within* the directory will be recursed. The link depth is
388 maximum depth of the tree at which soft links should be followed. So, a
389 depth of 0 does not follow any soft links, a depth of 1 follows only
390 links within the passed-in directory, a depth of 2 follows the links at
391 the next level down, etc.
392
393 *Note:* Any invalid soft links (i.e. soft links that point to
394 non-existent items) will be silently ignored.
395
396 *Note:* The :any:`excludeDirs` flag only controls whether any given directory
397 path itself is added to the list once it has been discovered. It does
398 *not* modify any behavior related to directory recursion.
399
400 *Note:* If you call this method *on a link to a directory* that link will
401 never be dereferenced (it may, however, be followed).
402
403 Args:
404 path (String representing a path on disk): Directory path whose contents should be added to the list
405 recursive (Boolean value): Indicates whether directory contents should be added recursively
406 addSelf (Boolean value): Indicates whether the directory itself should be added to the list
407 linkDepth (Integer value): Maximum depth of the tree at which soft links should be followed, zero means not to folow
408 dereference (Boolean value): Indicates whether soft links, if followed, should be dereferenced
409 Returns:
410 Number of items recursively added to the list
411
412 Raises:
413 ValueError: If path is not a directory or does not exist
414 ValueError: If the path could not be encoded properly
415 """
416 path = encodePath(path)
417 path = normalizeDir(path)
418 return self._addDirContentsInternal(path, addSelf, recursive, linkDepth, dereference)
419
420 def _addDirContentsInternal(self, path, includePath=True, recursive=True, linkDepth=0, dereference=False):
421 """
422 Internal implementation of ``addDirContents``.
423
424 This internal implementation exists due to some refactoring. Basically,
425 some subclasses have a need to add the contents of a directory, but not
426 the directory itself. This is different than the standard ``FilesystemList``
427 behavior and actually ends up making a special case out of the first
428 call in the recursive chain. Since I don't want to expose the modified
429 interface, ``addDirContents`` ends up being wholly implemented in terms
430 of this method.
431
432 The linkDepth parameter controls whether soft links are followed when we
433 are adding the contents recursively. Any recursive calls reduce the
434 value by one. If the value zero or less, then soft links will just be
435 added as directories, but will not be followed. This means that links
436 are followed to a *constant depth* starting from the top-most directory.
437
438 There is one difference between soft links and directories: soft links
439 that are added recursively are not placed into the list explicitly. This
440 is because if we do add the links recursively, the resulting tar file
441 gets a little confused (it has a link and a directory with the same
442 name).
443
444 *Note:* If you call this method *on a link to a directory* that link will
445 never be dereferenced (it may, however, be followed).
446
447 Args:
448 path: Directory path whose contents should be added to the list
449 includePath: Indicates whether to include the path as well as contents
450 recursive: Indicates whether directory contents should be added recursively
451 linkDepth: Depth of soft links that should be followed
452 dereference: Indicates whether soft links, if followed, should be dereferenced
453
454 Returns:
455 Number of items recursively added to the list
456
457 Raises:
458 ValueError: If path is not a directory or does not exist
459 """
460 added = 0
461 if not os.path.exists(path) or not os.path.isdir(path):
462 logger.debug("Path [%s] is not a directory or does not exist on disk.", path)
463 raise ValueError("Path is not a directory or does not exist on disk.")
464 if path in self.excludePaths:
465 logger.debug("Path [%s] is excluded based on excludePaths.", path)
466 return added
467 for pattern in self.excludePatterns: # safe to assume all are valid due to RegexList
468 pattern = encodePath(pattern) # use same encoding as filenames
469 if re.compile(r"^%s$" % pattern).match(path):
470 logger.debug("Path [%s] is excluded based on pattern [%s].", path, pattern)
471 return added
472 for pattern in self.excludeBasenamePatterns: # safe to assume all are valid due to RegexList
473 pattern = encodePath(pattern) # use same encoding as filenames
474 if re.compile(r"^%s$" % pattern).match(os.path.basename(path)):
475 logger.debug("Path [%s] is excluded based on basename pattern [%s].", path, pattern)
476 return added
477 if self.ignoreFile is not None and os.path.exists(pathJoin(path, self.ignoreFile)):
478 logger.debug("Path [%s] is excluded based on ignore file.", path)
479 return added
480 if includePath:
481 added += self.addDir(path) # could actually be excluded by addDir, yet
482 for entry in os.listdir(path):
483 entrypath = pathJoin(path, entry)
484 if os.path.isfile(entrypath):
485 if linkDepth > 0 and dereference:
486 derefpath = dereferenceLink(entrypath)
487 if derefpath != entrypath:
488 added += self.addFile(derefpath)
489 added += self.addFile(entrypath)
490 elif os.path.isdir(entrypath):
491 if os.path.islink(entrypath):
492 if recursive:
493 if linkDepth > 0:
494 newDepth = linkDepth - 1
495 if dereference:
496 derefpath = dereferenceLink(entrypath)
497 if derefpath != entrypath:
498 added += self._addDirContentsInternal(derefpath, True, recursive, newDepth, dereference)
499 added += self.addDir(entrypath)
500 else:
501 added += self._addDirContentsInternal(entrypath, False, recursive, newDepth, dereference)
502 else:
503 added += self.addDir(entrypath)
504 else:
505 added += self.addDir(entrypath)
506 else:
507 if recursive:
508 newDepth = linkDepth - 1
509 added += self._addDirContentsInternal(entrypath, True, recursive, newDepth, dereference)
510 else:
511 added += self.addDir(entrypath)
512 return added
513
514 #################
515 # Remove methods
516 #################
517
518 def removeFiles(self, pattern=None):
519 """
520 Removes file entries from the list.
521
522 If ``pattern`` is not passed in or is ``None``, then all file entries will
523 be removed from the list. Otherwise, only those file entries matching
524 the pattern will be removed. Any entry which does not exist on disk
525 will be ignored (use :any:`removeInvalid` to purge those entries).
526
527 This method might be fairly slow for large lists, since it must check the
528 type of each item in the list. If you know ahead of time that you want
529 to exclude all files, then you will be better off setting :any:`excludeFiles`
530 to ``True`` before adding items to the list.
531
532 Args:
533 pattern: Regular expression pattern representing entries to remove
534
535 Returns:
536 Number of entries removed
537 Raises:
538 ValueError: If the passed-in pattern is not a valid regular expression
539 """
540 removed = 0
541 if pattern is None:
542 for entry in self[:]:
543 if os.path.exists(entry) and os.path.isfile(entry):
544 self.remove(entry)
545 logger.debug("Removed path [%s] from list.", entry)
546 removed += 1
547 else:
548 try:
549 pattern = encodePath(pattern) # use same encoding as filenames
550 compiled = re.compile(pattern)
551 except re.error:
552 raise ValueError("Pattern is not a valid regular expression.")
553 for entry in self[:]:
554 if os.path.exists(entry) and os.path.isfile(entry):
555 if compiled.match(entry):
556 self.remove(entry)
557 logger.debug("Removed path [%s] from list.", entry)
558 removed += 1
559 logger.debug("Removed a total of %d entries.", removed)
560 return removed
561
562 def removeDirs(self, pattern=None):
563 """
564 Removes directory entries from the list.
565
566 If ``pattern`` is not passed in or is ``None``, then all directory entries
567 will be removed from the list. Otherwise, only those directory entries
568 matching the pattern will be removed. Any entry which does not exist on
569 disk will be ignored (use :any:`removeInvalid` to purge those entries).
570
571 This method might be fairly slow for large lists, since it must check the
572 type of each item in the list. If you know ahead of time that you want
573 to exclude all directories, then you will be better off setting
574 :any:`excludeDirs` to ``True`` before adding items to the list (note that this
575 will not prevent you from recursively adding the *contents* of
576 directories).
577
578 Args:
579 pattern: Regular expression pattern representing entries to remove
580
581 Returns:
582 Number of entries removed
583 Raises:
584 ValueError: If the passed-in pattern is not a valid regular expression
585 """
586 removed = 0
587 if pattern is None:
588 for entry in self[:]:
589 if os.path.exists(entry) and os.path.isdir(entry):
590 self.remove(entry)
591 logger.debug("Removed path [%s] from list.", entry)
592 removed += 1
593 else:
594 try:
595 pattern = encodePath(pattern) # use same encoding as filenames
596 compiled = re.compile(pattern)
597 except re.error:
598 raise ValueError("Pattern is not a valid regular expression.")
599 for entry in self[:]:
600 if os.path.exists(entry) and os.path.isdir(entry):
601 if compiled.match(entry):
602 self.remove(entry)
603 logger.debug("Removed path [%s] from list based on pattern [%s].", entry, pattern)
604 removed += 1
605 logger.debug("Removed a total of %d entries.", removed)
606 return removed
607
608 def removeLinks(self, pattern=None):
609 """
610 Removes soft link entries from the list.
611
612 If ``pattern`` is not passed in or is ``None``, then all soft link entries
613 will be removed from the list. Otherwise, only those soft link entries
614 matching the pattern will be removed. Any entry which does not exist on
615 disk will be ignored (use :any:`removeInvalid` to purge those entries).
616
617 This method might be fairly slow for large lists, since it must check the
618 type of each item in the list. If you know ahead of time that you want
619 to exclude all soft links, then you will be better off setting
620 :any:`excludeLinks` to ``True`` before adding items to the list.
621
622 Args:
623 pattern: Regular expression pattern representing entries to remove
624
625 Returns:
626 Number of entries removed
627 Raises:
628 ValueError: If the passed-in pattern is not a valid regular expression
629 """
630 removed = 0
631 if pattern is None:
632 for entry in self[:]:
633 if os.path.exists(entry) and os.path.islink(entry):
634 self.remove(entry)
635 logger.debug("Removed path [%s] from list.", entry)
636 removed += 1
637 else:
638 try:
639 pattern = encodePath(pattern) # use same encoding as filenames
640 compiled = re.compile(pattern)
641 except re.error:
642 raise ValueError("Pattern is not a valid regular expression.")
643 for entry in self[:]:
644 if os.path.exists(entry) and os.path.islink(entry):
645 if compiled.match(entry):
646 self.remove(entry)
647 logger.debug("Removed path [%s] from list based on pattern [%s].", entry, pattern)
648 removed += 1
649 logger.debug("Removed a total of %d entries.", removed)
650 return removed
651
652 def removeMatch(self, pattern):
653 """
654 Removes from the list all entries matching a pattern.
655
656 This method removes from the list all entries which match the passed in
657 ``pattern``. Since there is no need to check the type of each entry, it
658 is faster to call this method than to call the :any:`removeFiles`,
659 :any:`removeDirs` or :any:`removeLinks` methods individually. If you know which
660 patterns you will want to remove ahead of time, you may be better off
661 setting :any:`excludePatterns` or :any:`excludeBasenamePatterns` before adding
662 items to the list.
663
664 *Note:* Unlike when using the exclude lists, the pattern here is *not*
665 bounded at the front and the back of the string. You can use any pattern
666 you want.
667
668 Args:
669 pattern: Regular expression pattern representing entries to remove
670
671 Returns:
672 Number of entries removed
673 Raises:
674 ValueError: If the passed-in pattern is not a valid regular expression
675 """
676 try:
677 pattern = encodePath(pattern) # use same encoding as filenames
678 compiled = re.compile(pattern)
679 except re.error:
680 raise ValueError("Pattern is not a valid regular expression.")
681 removed = 0
682 for entry in self[:]:
683 if compiled.match(entry):
684 self.remove(entry)
685 logger.debug("Removed path [%s] from list based on pattern [%s].", entry, pattern)
686 removed += 1
687 logger.debug("Removed a total of %d entries.", removed)
688 return removed
689
690 def removeInvalid(self):
691 """
692 Removes from the list all entries that do not exist on disk.
693
694 This method removes from the list all entries which do not currently
695 exist on disk in some form. No attention is paid to whether the entries
696 are files or directories.
697
698 Returns:
699 Number of entries removed
700 """
701 removed = 0
702 for entry in self[:]:
703 if not os.path.exists(entry):
704 self.remove(entry)
705 logger.debug("Removed path [%s] from list.", entry)
706 removed += 1
707 logger.debug("Removed a total of %d entries.", removed)
708 return removed
709
710 ##################
711 # Utility methods
712 ##################
713
714 def normalize(self):
715 """Normalizes the list, ensuring that each entry is unique."""
716 orig = len(self)
717 self.sort()
718 dups = list(filter(lambda x, self=self: self[x] == self[x + 1], list(range(len(self) - 1))))
719 items = list(map(lambda x, self=self: self[x], dups))
720 list(map(self.remove, items))
721 new = len(self)
722 logger.debug("Completed normalizing list; removed %d items (%d originally, %d now).", new - orig, orig, new)
723
724 def verify(self):
725 """
726 Verifies that all entries in the list exist on disk.
727 Returns:
728 ``True`` if all entries exist, ``False`` otherwise
729 """
730 for entry in self:
731 if not os.path.exists(entry):
732 logger.debug("Path [%s] is invalid; list is not valid.", entry)
733 return False
734 logger.debug("All entries in list are valid.")
735 return True
736
737
738 ########################################################################
739 # SpanItem class definition
740 ########################################################################
741
742
743 class SpanItem:
744 """
745 Item returned by :any:`BackupFileList.generateSpan`.
746 """
747
748 def __init__(self, fileList, size, capacity, utilization):
749 """
750 Create object.
751 Args:
752 fileList: List of files
753 size: Size (in bytes) of files
754 utilization: Utilization, as a percentage (0-100)
755 """
756 self.fileList = fileList
757 self.size = size
758 self.capacity = capacity
759 self.utilization = utilization
760
761
762 ########################################################################
763 # BackupFileList class definition
764 ########################################################################
765
766
767 class BackupFileList(FilesystemList):
768 ######################
769 # Class documentation
770 ######################
771
772 """
773 List of files to be backed up.
774
775 A BackupFileList is a :any:`FilesystemList` containing a list of files to be
776 backed up. It only contains files, not directories (soft links are treated
777 like files). On top of the generic functionality provided by
778 :any:`FilesystemList`, this class adds functionality to keep a hash (checksum)
779 for each file in the list, and it also provides a method to calculate the
780 total size of the files in the list and a way to export the list into tar
781 form.
782
783 """
784
785 ##############
786 # Constructor
787 ##############
788
789 def __init__(self):
790 """Initializes a list with no configured exclusions."""
791 FilesystemList.__init__(self)
792
793 ################################
794 # Overridden superclass methods
795 ################################
796
797 def addDir(self, path):
798 """
799 Adds a directory to the list.
800
801 Note that this class does not allow directories to be added by themselves
802 (a backup list contains only files). However, since links to directories
803 are technically files, we allow them to be added.
804
805 This method is implemented in terms of the superclass method, with one
806 additional validation: the superclass method is only called if the
807 passed-in path is both a directory and a link. All of the superclass's
808 existing validations and restrictions apply.
809
810 Args:
811 path (String representing a path on disk): Directory path to be added to the list
812 Returns:
813 Number of items added to the list
814
815 Raises:
816 ValueError: If path is not a directory or does not exist
817 ValueError: If the path could not be encoded properly
818 """
819 path = encodePath(path)
820 path = normalizeDir(path)
821 if os.path.isdir(path) and not os.path.islink(path):
822 return 0
823 else:
824 return FilesystemList.addDir(self, path)
825
826 ##################
827 # Utility methods
828 ##################
829
830 def totalSize(self):
831 """
832 Returns the total size among all files in the list.
833 Only files are counted.
834 Soft links that point at files are ignored.
835 Entries which do not exist on disk are ignored.
836 Returns:
837 Total size, in bytes
838 """
839 total = 0.0
840 for entry in self:
841 if os.path.isfile(entry) and not os.path.islink(entry):
842 total += float(os.stat(entry).st_size)
843 return total
844
845 def generateSizeMap(self):
846 """
847 Generates a mapping from file to file size in bytes.
848 The mapping does include soft links, which are listed with size zero.
849 Entries which do not exist on disk are ignored.
850 Returns:
851 Dictionary mapping file to file size
852 """
853 table = {}
854 for entry in self:
855 if os.path.islink(entry):
856 table[entry] = 0.0
857 elif os.path.isfile(entry):
858 table[entry] = float(os.stat(entry).st_size)
859 return table
860
861 def generateDigestMap(self, stripPrefix=None):
862 """
863 Generates a mapping from file to file digest.
864
865 Currently, the digest is an SHA hash, which should be pretty secure. In
866 the future, this might be a different kind of hash, but we guarantee that
867 the type of the hash will not change unless the library major version
868 number is bumped.
869
870 Entries which do not exist on disk are ignored.
871
872 Soft links are ignored. We would end up generating a digest for the file
873 that the soft link points at, which doesn't make any sense.
874
875 If ``stripPrefix`` is passed in, then that prefix will be stripped from
876 each key when the map is generated. This can be useful in generating two
877 "relative" digest maps to be compared to one another.
878
879 Args:
880 stripPrefix (String with any contents): Common prefix to be stripped from paths
881 Returns:
882 Dictionary mapping file to digest value
883 @see: :any:`removeUnchanged`
884 """
885 table = {}
886 if stripPrefix is not None:
887 for entry in self:
888 if os.path.isfile(entry) and not os.path.islink(entry):
889 table[entry.replace(stripPrefix, "", 1)] = BackupFileList._generateDigest(entry)
890 else:
891 for entry in self:
892 if os.path.isfile(entry) and not os.path.islink(entry):
893 table[entry] = BackupFileList._generateDigest(entry)
894 return table
895
896 @staticmethod
897 def _generateDigest(path):
898 """
899 Generates an SHA digest for a given file on disk.
900
901 The original code for this function used this simplistic implementation,
902 which requires reading the entire file into memory at once in order to
903 generate a digest value::
904
905 sha.new(open(path).read()).hexdigest()
906
907 Not surprisingly, this isn't an optimal solution. The U{Simple file
908 hashing <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259109>}
909 Python Cookbook recipe describes how to incrementally generate a hash
910 value by reading in chunks of data rather than reading the file all at
911 once. The recipe relies on the the ``update()`` method of the various
912 Python hashing algorithms.
913
914 In my tests using a 110 MB file on CD, the original implementation
915 requires 111 seconds. This implementation requires only 40-45 seconds,
916 which is a pretty substantial speed-up.
917
918 Experience shows that reading in around 4kB (4096 bytes) at a time yields
919 the best performance. Smaller reads are quite a bit slower, and larger
920 reads don't make much of a difference. The 4kB number makes me a little
921 suspicious, and I think it might be related to the size of a filesystem
922 read at the hardware level. However, I've decided to just hardcode 4096
923 until I have evidence that shows it's worthwhile making the read size
924 configurable.
925
926 Args:
927 path: Path to generate digest for
928
929 Returns:
930 ASCII-safe SHA digest for the file
931 Raises:
932 OSError: If the file cannot be opened
933 """
934 s = hashlib.sha1() # ruff: ignore[hashlib-insecure-hash-function] # we're not using SHA-1 for cryptographic purposes, only to identify file changes
935 with open(path, mode="rb") as f:
936 readBytes = 4096 # see notes above
937 while readBytes > 0:
938 readString = f.read(readBytes)
939 s.update(readString)
940 readBytes = len(readString)
941 digest = s.hexdigest()
942 logger.debug("Generated digest [%s] for file [%s].", digest, path)
943 return digest
944
945 def generateFitted(self, capacity, algorithm="worst_fit"):
946 """
947 Generates a list of items that fit in the indicated capacity.
948
949 Sometimes, callers would like to include every item in a list, but are
950 unable to because not all of the items fit in the space available. This
951 method returns a copy of the list, containing only the items that fit in
952 a given capacity. A copy is returned so that we don't lose any
953 information if for some reason the fitted list is unsatisfactory.
954
955 The fitting is done using the functions in the knapsack module. By
956 default, the first fit algorithm is used, but you can also choose
957 from best fit, worst fit and alternate fit.
958
959 Args:
960 capacity (Integer, in bytes): Maximum capacity among the files in the new list
961 algorithm (One of "first_fit", "best_fit", "worst_fit", "alternate_fit"): Knapsack (fit) algorithm to use
962 Returns:
963 Copy of list with total size no larger than indicated capacity
964 Raises:
965 ValueError: If the algorithm is invalid
966 """
967 table = self._getKnapsackTable()
968 function = BackupFileList._getKnapsackFunction(algorithm)
969 return function(table, capacity)[0]
970
971 def generateSpan(self, capacity, algorithm="worst_fit"):
972 """
973 Splits the list of items into sub-lists that fit in a given capacity.
974
975 Sometimes, callers need split to a backup file list into a set of smaller
976 lists. For instance, you could use this to "span" the files across a set
977 of discs.
978
979 The fitting is done using the functions in the knapsack module. By
980 default, the first fit algorithm is used, but you can also choose
981 from best fit, worst fit and alternate fit.
982
983 *Note:* If any of your items are larger than the capacity, then it won't
984 be possible to find a solution. In this case, a value error will be
985 raised.
986
987 Args:
988 capacity (Integer, in bytes): Maximum capacity among the files in the new list
989 algorithm (One of "first_fit", "best_fit", "worst_fit", "alternate_fit"): Knapsack (fit) algorithm to use
990 Returns:
991 List of :any:`SpanItem` objects
992
993 Raises:
994 ValueError: If the algorithm is invalid
995 ValueError: If it's not possible to fit some items
996 """
997 spanItems = []
998 function = BackupFileList._getKnapsackFunction(algorithm)
999 table = self._getKnapsackTable(capacity)
1000 iteration = 0
1001 while len(table) > 0:
1002 iteration += 1
1003 fit = function(table, capacity)
1004 if len(fit[0]) == 0:
1005 # Should never happen due to validations in _convertToKnapsackForm(), but let's be safe
1006 raise ValueError("After iteration %d, unable to add any new items." % iteration)
1007 removeKeys(table, fit[0])
1008 utilization = (float(fit[1]) / float(capacity)) * 100.0
1009 item = SpanItem(fit[0], fit[1], capacity, utilization)
1010 spanItems.append(item)
1011 return spanItems
1012
1013 def _getKnapsackTable(self, capacity=None):
1014 """
1015 Converts the list into the form needed by the knapsack algorithms.
1016 Returns:
1017 Dictionary mapping file name to tuple of (file path, file size)
1018 """
1019 table = {}
1020 for entry in self:
1021 if os.path.islink(entry):
1022 table[entry] = (entry, 0.0)
1023 elif os.path.isfile(entry):
1024 size = float(os.stat(entry).st_size)
1025 if capacity is not None:
1026 if size > capacity:
1027 raise ValueError("File [%s] cannot fit in capacity %s." % (entry, displayBytes(capacity)))
1028 table[entry] = (entry, size)
1029 return table
1030
1031 @staticmethod
1032 def _getKnapsackFunction(algorithm):
1033 """
1034 Returns a reference to the function associated with an algorithm name.
1035 Algorithm name must be one of "first_fit", "best_fit", "worst_fit", "alternate_fit"
1036 Args:
1037 algorithm: Name of the algorithm
1038 Returns:
1039 Reference to knapsack function
1040 Raises:
1041 ValueError: If the algorithm name is unknown
1042 """
1043 if algorithm == "first_fit":
1044 return firstFit
1045 elif algorithm == "best_fit":
1046 return bestFit
1047 elif algorithm == "worst_fit":
1048 return worstFit
1049 elif algorithm == "alternate_fit":
1050 return alternateFit
1051 else:
1052 raise ValueError("Algorithm [%s] is invalid." % algorithm)
1053
1054 def generateTarfile(self, path, mode="tar", ignore=False, flat=False):
1055 """
1056 Creates a tar file containing the files in the list.
1057
1058 By default, this method will create uncompressed tar files. If you pass
1059 in mode ``'targz'``, then it will create gzipped tar files, and if you
1060 pass in mode ``'tarbz2'``, then it will create bzipped tar files.
1061
1062 The tar file will be created as a GNU tar archive, which enables extended
1063 file name lengths, etc. Since GNU tar is so prevalent, I've decided that
1064 the extra functionality out-weighs the disadvantage of not being
1065 "standard".
1066
1067 If you pass in ``flat=True``, then a "flat" archive will be created, and
1068 all of the files will be added to the root of the archive. So, the file
1069 ``/tmp/something/whatever.txt`` would be added as just ``whatever.txt``.
1070
1071 By default, the whole method call fails if there are problems adding any
1072 of the files to the archive, resulting in an exception. Under these
1073 circumstances, callers are advised that they might want to call
1074 :any:`removeInvalid` and then attempt to extract the tar file a second
1075 time, since the most common cause of failures is a missing file (a file
1076 that existed when the list was built, but is gone again by the time the
1077 tar file is built).
1078
1079 If you want to, you can pass in ``ignore=True``, and the method will
1080 ignore errors encountered when adding individual files to the archive
1081 (but not errors opening and closing the archive itself).
1082
1083 We'll always attempt to remove the tarfile from disk if an exception will
1084 be thrown.
1085
1086 *Note:* No validation is done as to whether the entries in the list are
1087 files, since only files or soft links should be in an object like this.
1088 However, to be safe, everything is explicitly added to the tar archive
1089 non-recursively so it's safe to include soft links to directories.
1090
1091 *Note:* The Python ``tarfile`` module, which is used internally here, is
1092 supposed to deal properly with long filenames and links. In my testing,
1093 I have found that it appears to be able to add long really long filenames
1094 to archives, but doesn't do a good job reading them back out, even out of
1095 an archive it created. Fortunately, all Cedar Backup does is add files
1096 to archives.
1097
1098 Args:
1099 path (String representing a path on disk): Path of tar file to create on disk
1100 mode (One of either ``'tar'``, ``'targz'`` or ``'tarbz2'``): Tar creation mode
1101 ignore (Boolean): Indicates whether to ignore certain errors
1102 flat (Boolean): Creates "flat" archive by putting all items in root
1103 Raises:
1104 ValueError: If mode is not valid
1105 ValueError: If list is empty
1106 ValueError: If the path could not be encoded properly
1107 TarError: If there is a problem creating the tar file
1108 """
1109 path = encodePath(path)
1110 if len(self) == 0:
1111 raise ValueError("Empty list cannot be used to generate tarfile.")
1112 if mode == "tar":
1113 tarmode = "w:"
1114 elif mode == "targz":
1115 tarmode = "w:gz"
1116 elif mode == "tarbz2":
1117 tarmode = "w:bz2"
1118 else:
1119 raise ValueError("Mode [%s] is not valid." % mode)
1120 try:
1121 tar = tarfile.open(path, tarmode)
1122 try:
1123 tar.format = tarfile.GNU_FORMAT
1124 except AttributeError:
1125 tar.posix = False
1126 for entry in self:
1127 try:
1128 if flat:
1129 tar.add(entry, arcname=os.path.basename(entry), recursive=False)
1130 else:
1131 tar.add(entry, recursive=False)
1132 except tarfile.TarError as e:
1133 if not ignore:
1134 raise e
1135 logger.info("Unable to add file [%s]; going on anyway.", entry)
1136 except OSError as e:
1137 if not ignore:
1138 raise tarfile.TarError(e)
1139 logger.info("Unable to add file [%s]; going on anyway.", entry)
1140 tar.close()
1141 except tarfile.ReadError:
1142 try:
1143 tar.close()
1144 except:
1145 pass
1146 if os.path.exists(path):
1147 try:
1148 os.remove(path)
1149 except:
1150 pass
1151 raise tarfile.ReadError("Unable to open [%s]; maybe directory doesn't exist?" % path)
1152 except tarfile.TarError as e:
1153 try:
1154 tar.close()
1155 except:
1156 pass
1157 if os.path.exists(path):
1158 try:
1159 os.remove(path)
1160 except:
1161 pass
1162 raise e
1163
1164 def removeUnchanged(self, digestMap, captureDigest=False):
1165 """
1166 Removes unchanged entries from the list.
1167
1168 This method relies on a digest map as returned from :any:`generateDigestMap`.
1169 For each entry in ``digestMap``, if the entry also exists in the current
1170 list *and* the entry in the current list has the same digest value as in
1171 the map, the entry in the current list will be removed.
1172
1173 This method offers a convenient way for callers to filter unneeded
1174 entries from a list. The idea is that a caller will capture a digest map
1175 from ``generateDigestMap`` at some point in time (perhaps the beginning of
1176 the week), and will save off that map using ``pickle`` or some other
1177 method. Then, the caller could use this method sometime in the future to
1178 filter out any unchanged files based on the saved-off map.
1179
1180 If ``captureDigest`` is passed-in as ``True``, then digest information will
1181 be captured for the entire list before the removal step occurs using the
1182 same rules as in :any:`generateDigestMap`. The check will involve a lookup
1183 into the complete digest map.
1184
1185 If ``captureDigest`` is passed in as ``False``, we will only generate a
1186 digest value for files we actually need to check, and we'll ignore any
1187 entry in the list which isn't a file that currently exists on disk.
1188
1189 The return value varies depending on ``captureDigest``, as well. To
1190 preserve backwards compatibility, if ``captureDigest`` is ``False``, then
1191 we'll just return a single value representing the number of entries
1192 removed. Otherwise, we'll return a tuple of C{(entries removed, digest
1193 map)}. The returned digest map will be in exactly the form returned by
1194 :any:`generateDigestMap`.
1195
1196 *Note:* For performance reasons, this method actually ends up rebuilding
1197 the list from scratch. First, we build a temporary dictionary containing
1198 all of the items from the original list. Then, we remove items as needed
1199 from the dictionary (which is faster than the equivalent operation on a
1200 list). Finally, we replace the contents of the current list based on the
1201 keys left in the dictionary. This should be transparent to the caller.
1202
1203 Args:
1204 digestMap (Map as returned from :any:`generateDigestMap`): Dictionary mapping file name to digest value
1205 captureDigest (Boolean): Indicates that digest information should be captured
1206 Returns:
1207 Results as discussed above (format varies based on arguments)
1208 """
1209 if captureDigest:
1210 removed = 0
1211 table = {}
1212 captured = {}
1213 for entry in self:
1214 if os.path.isfile(entry) and not os.path.islink(entry):
1215 table[entry] = BackupFileList._generateDigest(entry)
1216 captured[entry] = table[entry]
1217 else:
1218 table[entry] = None
1219 for entry in list(digestMap.keys()):
1220 if entry in table:
1221 if table[entry] is not None: # equivalent to file/link check in other case
1222 digest = table[entry]
1223 if digest == digestMap[entry]:
1224 removed += 1
1225 del table[entry]
1226 logger.debug("Discarded unchanged file [%s].", entry)
1227 self[:] = list(table.keys())
1228 return (removed, captured)
1229 else:
1230 removed = 0
1231 table = {}
1232 for entry in self:
1233 table[entry] = None
1234 for entry in list(digestMap.keys()):
1235 if entry in table:
1236 if os.path.isfile(entry) and not os.path.islink(entry):
1237 digest = BackupFileList._generateDigest(entry)
1238 if digest == digestMap[entry]:
1239 removed += 1
1240 del table[entry]
1241 logger.debug("Discarded unchanged file [%s].", entry)
1242 self[:] = list(table.keys())
1243 return removed
1244
1245
1246 ########################################################################
1247 # PurgeItemList class definition
1248 ########################################################################
1249
1250
1251 class PurgeItemList(FilesystemList):
1252 ######################
1253 # Class documentation
1254 ######################
1255
1256 """
1257 List of files and directories to be purged.
1258
1259 A PurgeItemList is a :any:`FilesystemList` containing a list of files and
1260 directories to be purged. On top of the generic functionality provided by
1261 :any:`FilesystemList`, this class adds functionality to remove items that are
1262 too young to be purged, and to actually remove each item in the list from
1263 the filesystem.
1264
1265 The other main difference is that when you add a directory's contents to a
1266 purge item list, the directory itself is not added to the list. This way,
1267 if someone asks to purge within in ``/opt/backup/collect``, that directory
1268 doesn't get removed once all of the files within it is gone.
1269 """
1270
1271 ##############
1272 # Constructor
1273 ##############
1274
1275 def __init__(self):
1276 """Initializes a list with no configured exclusions."""
1277 FilesystemList.__init__(self)
1278
1279 ##############
1280 # Add methods
1281 ##############
1282
1283 def addDirContents(self, path, recursive=True, addSelf=True, linkDepth=0, dereference=False): # ruff: ignore[unused-method-argument]
1284 """
1285 Adds the contents of a directory to the list.
1286
1287 The path must exist and must be a directory or a link to a directory.
1288 The contents of the directory (but *not* the directory path itself) will
1289 be recursively added to the list, subject to any exclusions that are in
1290 place. If you only want the directory and its contents to be added, then
1291 pass in ``recursive=False``.
1292
1293 *Note:* If a directory's absolute path matches an exclude pattern or path,
1294 or if the directory contains the configured ignore file, then the
1295 directory and all of its contents will be recursively excluded from the
1296 list.
1297
1298 *Note:* If the passed-in directory happens to be a soft link, it will be
1299 recursed. However, the linkDepth parameter controls whether any soft
1300 links *within* the directory will be recursed. The link depth is
1301 maximum depth of the tree at which soft links should be followed. So, a
1302 depth of 0 does not follow any soft links, a depth of 1 follows only
1303 links within the passed-in directory, a depth of 2 follows the links at
1304 the next level down, etc.
1305
1306 *Note:* Any invalid soft links (i.e. soft links that point to
1307 non-existent items) will be silently ignored.
1308
1309 *Note:* The :any:`excludeDirs` flag only controls whether any given soft link
1310 path itself is added to the list once it has been discovered. It does
1311 *not* modify any behavior related to directory recursion.
1312
1313 *Note:* The :any:`excludeDirs` flag only controls whether any given directory
1314 path itself is added to the list once it has been discovered. It does
1315 *not* modify any behavior related to directory recursion.
1316
1317 *Note:* If you call this method *on a link to a directory* that link will
1318 never be dereferenced (it may, however, be followed).
1319
1320 Args:
1321 path (String representing a path on disk): Directory path whose contents should be added to the list
1322 recursive (Boolean value): Indicates whether directory contents should be added recursively
1323 addSelf: Ignored in this subclass
1324
1325 linkDepth (Integer value, where zero means not to follow any soft links): Depth of soft links that should be followed
1326 dereference (Boolean value): Indicates whether soft links, if followed, should be dereferenced
1327 Returns:
1328 Number of items recursively added to the list
1329
1330 Raises:
1331 ValueError: If path is not a directory or does not exist
1332 ValueError: If the path could not be encoded properly
1333 """
1334 path = encodePath(path)
1335 path = normalizeDir(path)
1336 return super()._addDirContentsInternal(path, False, recursive, linkDepth, dereference)
1337
1338 ##################
1339 # Utility methods
1340 ##################
1341
1342 def removeYoungFiles(self, daysOld):
1343 """
1344 Removes from the list files younger than a certain age (in days).
1345
1346 Any file whose "age" in days is less than (``<``) the value of the
1347 ``daysOld`` parameter will be removed from the list so that it will not be
1348 purged later when :any:`purgeItems` is called. Directories and soft links
1349 will be ignored.
1350
1351 The "age" of a file is the amount of time since the file was last used,
1352 per the most recent of the file's ``st_atime`` and ``st_mtime`` values.
1353
1354 *Note:* Some people find the "sense" of this method confusing or
1355 "backwards". Keep in mind that this method is used to remove items
1356 *from the list*, not from the filesystem! It removes from the list
1357 those items that you would *not* want to purge because they are too
1358 young. As an example, passing in ``daysOld`` of zero (0) would remove
1359 from the list no files, which would result in purging all of the files
1360 later. I would be happy to make a synonym of this method with an
1361 easier-to-understand "sense", if someone can suggest one.
1362
1363 Args:
1364 daysOld (Integer value >= 0): Minimum age of files that are to be kept in the list
1365 Returns:
1366 Number of entries removed
1367 """
1368 removed = 0
1369 daysOld = int(daysOld)
1370 if daysOld < 0:
1371 raise ValueError("Days old value must be an integer >= 0.")
1372 for entry in self[:]:
1373 if os.path.isfile(entry) and not os.path.islink(entry):
1374 try:
1375 ageInDays = calculateFileAge(entry)
1376 ageInWholeDays = math.floor(ageInDays)
1377 ageInWholeDays = max(ageInWholeDays, 0)
1378 if ageInWholeDays < daysOld:
1379 removed += 1
1380 self.remove(entry)
1381 except OSError:
1382 pass
1383 return removed
1384
1385 def purgeItems(self):
1386 """
1387 Purges all items in the list.
1388
1389 Every item in the list will be purged. Directories in the list will
1390 *not* be purged recursively, and hence will only be removed if they are
1391 empty. Errors will be ignored.
1392
1393 To faciliate easy removal of directories that will end up being empty,
1394 the delete process happens in two passes: files first (including soft
1395 links), then directories.
1396
1397 Returns:
1398 Tuple containing count of (files, dirs) removed
1399 """
1400 files = 0
1401 dirs = 0
1402 for entry in self:
1403 if os.path.exists(entry) and (os.path.isfile(entry) or os.path.islink(entry)):
1404 try:
1405 os.remove(entry)
1406 files += 1
1407 logger.debug("Purged file [%s].", entry)
1408 except OSError:
1409 pass
1410 for entry in self:
1411 if os.path.exists(entry) and os.path.isdir(entry) and not os.path.islink(entry):
1412 try:
1413 os.rmdir(entry)
1414 dirs += 1
1415 logger.debug("Purged empty directory [%s].", entry)
1416 except OSError:
1417 pass
1418 return (files, dirs)
1419
1420
1421 ########################################################################
1422 # Public functions
1423 ########################################################################
1424
1425 ###########################
1426 # normalizeFile() function
1427 ###########################
1428
1429
1430 def normalizeFile(path):
1431 """
1432 Normalizes a file name.
1433
1434 On Windows in particular, we often end up with mixed slashes, where
1435 parts of a path have forward slash and parts have backward slash.
1436 This makes it difficult to construct exclusions in configuration,
1437 because you never know what part of a path will have what kind of
1438 slash. I've decided to standardize on forward slashes.
1439
1440 Args:
1441 path (String representing a path on disk): Path to be normalized
1442 Returns:
1443 Normalized path, which should be equivalent to the original
1444 """
1445 return path.replace("\\", "/")
1446
1447
1448 ##########################
1449 # normalizeDir() function
1450 ##########################
1451
1452
1453 def normalizeDir(path):
1454 """
1455 Normalizes a directory name.
1456
1457 For our purposes, a directory name is normalized by removing the trailing
1458 path separator, if any. This is important because we want directories to
1459 appear within lists in a consistent way, although from the user's
1460 perspective passing in ``/path/to/dir/`` and ``/path/to/dir`` are equivalent.
1461
1462 We also convert slashes. On Windows in particular, we often end up with
1463 mixed slashes, where parts of a path have forward slash and parts have
1464 backward slash. This makes it difficult to construct exclusions in
1465 configuration, because you never know what part of a path will have
1466 what kind of slash. I've decided to standardize on forward slashes.
1467
1468 Args:
1469 path (String representing a path on disk): Path to be normalized
1470 Returns:
1471 Normalized path, which should be equivalent to the original
1472 """
1473 if path != os.sep and path[-1:] == os.sep:
1474 return path[:-1]
1475 return path.replace("\\", "/")
1476
1477
1478 #############################
1479 # compareContents() function
1480 #############################
1481
1482
1483 def compareContents(path1, path2, verbose=False):
1484 """
1485 Compares the contents of two directories to see if they are equivalent.
1486
1487 The two directories are recursively compared. First, we check whether they
1488 contain exactly the same set of files. Then, we check to see every given
1489 file has exactly the same contents in both directories.
1490
1491 This is all relatively simple to implement through the magic of
1492 :any:`BackupFileList.generateDigestMap`, which knows how to strip a path prefix
1493 off the front of each entry in the mapping it generates. This makes our
1494 comparison as simple as creating a list for each path, then generating a
1495 digest map for each path and comparing the two.
1496
1497 If no exception is thrown, the two directories are considered identical.
1498
1499 If the ``verbose`` flag is ``True``, then an alternate (but slower) method is
1500 used so that any thrown exception can indicate exactly which file caused the
1501 comparison to fail. The thrown ``ValueError`` exception distinguishes
1502 between the directories containing different files, and containing the same
1503 files with differing content.
1504
1505 *Note:* Symlinks are *not* followed for the purposes of this comparison.
1506
1507 Args:
1508 path1 (String representing a path on disk): First path to compare
1509 path2 (String representing a path on disk): First path to compare
1510 verbose (Boolean): Indicates whether a verbose response should be given
1511 Raises:
1512 ValueError: If a directory doesn't exist or can't be read
1513 ValueError: If the two directories are not equivalent
1514 IOError: If there is an unusual problem reading the directories
1515 """
1516 try:
1517 path1List = BackupFileList()
1518 path1List.addDirContents(path1)
1519 path1Digest = path1List.generateDigestMap(stripPrefix=normalizeDir(path1))
1520 path2List = BackupFileList()
1521 path2List.addDirContents(path2)
1522 path2Digest = path2List.generateDigestMap(stripPrefix=normalizeDir(path2))
1523 compareDigestMaps(path1Digest, path2Digest, verbose)
1524 except OSError as e:
1525 logger.error("I/O error encountered during consistency check.")
1526 raise e
1527
1528
1529 def compareDigestMaps(digest1, digest2, verbose=False):
1530 """
1531 Compares two digest maps and throws an exception if they differ.
1532
1533 Args:
1534 digest1 (Digest as returned from BackupFileList.generateDigestMap()): First digest to compare
1535 digest2 (Digest as returned from BackupFileList.generateDigestMap()): Second digest to compare
1536 verbose (Boolean): Indicates whether a verbose response should be given
1537 Raises:
1538 ValueError: If the two directories are not equivalent
1539 """
1540 if not verbose:
1541 if digest1 != digest2:
1542 raise ValueError("Consistency check failed.")
1543 else:
1544 list1 = UnorderedList(list(digest1.keys()))
1545 list2 = UnorderedList(list(digest2.keys()))
1546 if list1 != list2:
1547 raise ValueError("Directories contain a different set of files.")
1548 for key in list1:
1549 if digest1[key] != digest2[key]:
1550 raise ValueError("File contents for [%s] vary between directories." % key)