Debian Codegraph @

src/CedarBackup3/actions/collect.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,2011,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 : Implements the standard 'collect' action.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Implements the standard 'collect' action.
39 :author: Kenneth J. Pronovici <[email protected]>
40 """
41
42
43 ########################################################################
44 # Imported modules
45 ########################################################################
46
47 import logging
48 import os
49 import pickle # ruff: ignore[suspicious-pickle-import] # we operate on trusted data, so pickle is ok
50
51 from CedarBackup3.actions.constants import COLLECT_INDICATOR, DIGEST_EXTENSION
52 from CedarBackup3.actions.util import writeIndicatorFile
53 from CedarBackup3.filesystem import BackupFileList, FilesystemList
54 from CedarBackup3.util import buildNormalizedPath, changeOwnership, displayBytes, isStartOfWeek, pathJoin
55
56 ########################################################################
57 # Module-wide constants and variables
58 ########################################################################
59
60 logger = logging.getLogger("CedarBackup3.log.actions.collect")
61
62
63 ########################################################################
64 # Public functions
65 ########################################################################
66
67 ############################
68 # executeCollect() function
69 ############################
70
71
72 def executeCollect(configPath, options, config): # ruff: ignore[unused-function-argument]
73 """
74 Executes the collect backup action.
75
76 *Note:* When the collect action is complete, we will write a collect
77 indicator to the collect directory, so it's obvious that the collect action
78 has completed. The stage process uses this indicator to decide whether a
79 peer is ready to be staged.
80
81 Args:
82 configPath (String representing a path on disk): Path to configuration file on disk
83 options (Options object): Program command-line options
84 config (Config object): Program configuration
85 Raises:
86 ValueError: Under many generic error conditions
87 TarError: If there is a problem creating a tar file
88 """
89 logger.debug("Executing the 'collect' action.")
90 if config.options is None or config.collect is None:
91 raise ValueError("Collect configuration is not properly filled in.")
92 if (config.collect.collectFiles is None or len(config.collect.collectFiles) < 1) and (
93 config.collect.collectDirs is None or len(config.collect.collectDirs) < 1
94 ):
95 raise ValueError("There must be at least one collect file or collect directory.")
96 fullBackup = options.full
97 logger.debug("Full backup flag is [%s]", fullBackup)
98 todayIsStart = isStartOfWeek(config.options.startingDay)
99 resetDigest = fullBackup or todayIsStart
100 logger.debug("Reset digest flag is [%s]", resetDigest)
101 if config.collect.collectFiles is not None:
102 for collectFile in config.collect.collectFiles:
103 logger.debug("Working with collect file [%s]", collectFile.absolutePath)
104 collectMode = _getCollectMode(config, collectFile)
105 archiveMode = _getArchiveMode(config, collectFile)
106 digestPath = _getDigestPath(config, collectFile.absolutePath)
107 tarfilePath = _getTarfilePath(config, collectFile.absolutePath, archiveMode)
108 if fullBackup or (collectMode in ["daily", "incr"]) or (collectMode == "weekly" and todayIsStart):
109 logger.debug("File meets criteria to be backed up today.")
110 _collectFile(config, collectFile.absolutePath, tarfilePath, collectMode, archiveMode, resetDigest, digestPath)
111 else:
112 logger.debug("File will not be backed up, per collect mode.")
113 logger.info("Completed collecting file [%s]", collectFile.absolutePath)
114 if config.collect.collectDirs is not None:
115 for collectDir in config.collect.collectDirs:
116 logger.debug("Working with collect directory [%s]", collectDir.absolutePath)
117 collectMode = _getCollectMode(config, collectDir)
118 archiveMode = _getArchiveMode(config, collectDir)
119 ignoreFile = _getIgnoreFile(config, collectDir)
120 linkDepth = _getLinkDepth(collectDir)
121 dereference = _getDereference(collectDir)
122 recursionLevel = _getRecursionLevel(collectDir)
123 (excludePaths, excludePatterns) = _getExclusions(config, collectDir)
124 if fullBackup or (collectMode in ["daily", "incr"]) or (collectMode == "weekly" and todayIsStart):
125 logger.debug("Directory meets criteria to be backed up today.")
126 _collectDirectory(
127 config,
128 collectDir.absolutePath,
129 collectMode,
130 archiveMode,
131 ignoreFile,
132 linkDepth,
133 dereference,
134 resetDigest,
135 excludePaths,
136 excludePatterns,
137 recursionLevel,
138 )
139 else:
140 logger.debug("Directory will not be backed up, per collect mode.")
141 logger.info("Completed collecting directory [%s]", collectDir.absolutePath)
142 writeIndicatorFile(config.collect.targetDir, COLLECT_INDICATOR, config.options.backupUser, config.options.backupGroup)
143 logger.info("Executed the 'collect' action successfully.")
144
145
146 ########################################################################
147 # Private utility functions
148 ########################################################################
149
150 ##########################
151 # _collectFile() function
152 ##########################
153
154
155 def _collectFile(config, absolutePath, tarfilePath, collectMode, archiveMode, resetDigest, digestPath):
156 """
157 Collects a configured collect file.
158
159 The indicated collect file is collected into the indicated tarfile.
160 For files that are collected incrementally, we'll use the indicated
161 digest path and pay attention to the reset digest flag (basically, the reset
162 digest flag ignores any existing digest, but a new digest is always
163 rewritten).
164
165 The caller must decide what the collect and archive modes are, since they
166 can be on both the collect configuration and the collect file itself.
167
168 Args:
169 config: Config object
170 absolutePath: Absolute path of file to collect
171 tarfilePath: Path to tarfile that should be created
172 collectMode: Collect mode to use
173 archiveMode: Archive mode to use
174 resetDigest: Reset digest flag
175 digestPath: Path to digest file on disk, if needed
176 """
177 backupList = BackupFileList()
178 backupList.addFile(absolutePath)
179 _executeBackup(config, backupList, absolutePath, tarfilePath, collectMode, archiveMode, resetDigest, digestPath)
180
181
182 ###############################
183 # _collectDirectory() function
184 ###############################
185
186
187 def _collectDirectory(
188 config,
189 absolutePath,
190 collectMode,
191 archiveMode,
192 ignoreFile,
193 linkDepth,
194 dereference,
195 resetDigest,
196 excludePaths,
197 excludePatterns,
198 recursionLevel,
199 ):
200 """
201 Collects a configured collect directory.
202
203 The indicated collect directory is collected into the indicated tarfile.
204 For directories that are collected incrementally, we'll use the indicated
205 digest path and pay attention to the reset digest flag (basically, the reset
206 digest flag ignores any existing digest, but a new digest is always
207 rewritten).
208
209 The caller must decide what the collect and archive modes are, since they
210 can be on both the collect configuration and the collect directory itself.
211
212 Args:
213 config: Config object
214 absolutePath: Absolute path of directory to collect
215 collectMode: Collect mode to use
216 archiveMode: Archive mode to use
217 ignoreFile: Ignore file to use
218 linkDepth: Link depth value to use
219 dereference: Dereference flag to use
220 resetDigest: Reset digest flag
221 excludePaths: List of absolute paths to exclude
222 excludePatterns: List of patterns to exclude
223 recursionLevel: Recursion level (zero for no recursion)
224 """
225 if recursionLevel == 0:
226 # Collect the actual directory because we're at recursion level 0
227 logger.info("Collecting directory [%s]", absolutePath)
228 tarfilePath = _getTarfilePath(config, absolutePath, archiveMode)
229 digestPath = _getDigestPath(config, absolutePath)
230
231 backupList = BackupFileList()
232 backupList.ignoreFile = ignoreFile
233 backupList.excludePaths = excludePaths
234 backupList.excludePatterns = excludePatterns
235 backupList.addDirContents(absolutePath, linkDepth=linkDepth, dereference=dereference)
236
237 _executeBackup(config, backupList, absolutePath, tarfilePath, collectMode, archiveMode, resetDigest, digestPath)
238 else:
239 # Find all of the immediate subdirectories
240 subdirs = FilesystemList()
241 subdirs.excludeFiles = True
242 subdirs.excludeLinks = True
243 subdirs.excludePaths = excludePaths
244 subdirs.excludePatterns = excludePatterns
245 subdirs.addDirContents(path=absolutePath, recursive=False, addSelf=False)
246
247 # Back up the subdirectories separately
248 for subdir in subdirs:
249 _collectDirectory(
250 config,
251 subdir,
252 collectMode,
253 archiveMode,
254 ignoreFile,
255 linkDepth,
256 dereference,
257 resetDigest,
258 excludePaths,
259 excludePatterns,
260 recursionLevel - 1,
261 )
262 excludePaths.append(subdir) # this directory is already backed up, so exclude it
263
264 # Back up everything that hasn't previously been backed up
265 _collectDirectory(
266 config,
267 absolutePath,
268 collectMode,
269 archiveMode,
270 ignoreFile,
271 linkDepth,
272 dereference,
273 resetDigest,
274 excludePaths,
275 excludePatterns,
276 0,
277 )
278
279
280 ############################
281 # _executeBackup() function
282 ############################
283
284
285 def _executeBackup(config, backupList, absolutePath, tarfilePath, collectMode, archiveMode, resetDigest, digestPath):
286 """
287 Execute the backup process for the indicated backup list.
288
289 This function exists mainly to consolidate functionality between the
290 :any:`_collectFile` and :any:`_collectDirectory` functions. Those functions build
291 the backup list; this function causes the backup to execute properly and
292 also manages usage of the digest file on disk as explained in their
293 comments.
294
295 For collect files, the digest file will always just contain the single file
296 that is being backed up. This might little wasteful in terms of the number
297 of files that we keep around, but it's consistent and easy to understand.
298
299 Args:
300 config: Config object
301 backupList: List to execute backup for
302 absolutePath: Absolute path of directory or file to collect
303 tarfilePath: Path to tarfile that should be created
304 collectMode: Collect mode to use
305 archiveMode: Archive mode to use
306 resetDigest: Reset digest flag
307 digestPath: Path to digest file on disk, if needed
308 """
309 if collectMode != "incr":
310 logger.debug("Collect mode is [%s]; no digest will be used.", collectMode)
311 if len(backupList) == 1 and backupList[0] == absolutePath: # special case for individual file
312 logger.info("Backing up file [%s] (%s).", absolutePath, displayBytes(backupList.totalSize()))
313 else:
314 logger.info("Backing up %d files in [%s] (%s).", len(backupList), absolutePath, displayBytes(backupList.totalSize()))
315 if len(backupList) > 0:
316 backupList.generateTarfile(tarfilePath, archiveMode, True)
317 changeOwnership(tarfilePath, config.options.backupUser, config.options.backupGroup)
318 else:
319 if resetDigest:
320 logger.debug("Based on resetDigest flag, digest will be cleared.")
321 oldDigest = {}
322 else:
323 logger.debug("Based on resetDigest flag, digest will loaded from disk.")
324 oldDigest = _loadDigest(digestPath)
325 (removed, newDigest) = backupList.removeUnchanged(oldDigest, captureDigest=True)
326 logger.debug("Removed %d unchanged files based on digest values.", removed)
327 if len(backupList) == 1 and backupList[0] == absolutePath: # special case for individual file
328 logger.info("Backing up file [%s] (%s).", absolutePath, displayBytes(backupList.totalSize()))
329 else:
330 logger.info("Backing up %d files in [%s] (%s).", len(backupList), absolutePath, displayBytes(backupList.totalSize()))
331 if len(backupList) > 0:
332 backupList.generateTarfile(tarfilePath, archiveMode, True)
333 changeOwnership(tarfilePath, config.options.backupUser, config.options.backupGroup)
334 _writeDigest(config, newDigest, digestPath)
335
336
337 #########################
338 # _loadDigest() function
339 #########################
340
341
342 def _loadDigest(digestPath):
343 """
344 Loads the indicated digest path from disk into a dictionary.
345
346 If we can't load the digest successfully (either because it doesn't exist or
347 for some other reason), then an empty dictionary will be returned - but the
348 condition will be logged.
349
350 Args:
351 digestPath: Path to the digest file on disk
352
353 Returns:
354 Dictionary representing contents of digest path
355 """
356 if not os.path.isfile(digestPath):
357 digest = {}
358 logger.debug("Digest [%s] does not exist on disk.", digestPath)
359 else:
360 try:
361 with open(digestPath, "rb") as f:
362 digest = pickle.load(f, fix_imports=True) # ruff: ignore[suspicious-pickle-usage] # this is trusted data, so pickle is ok
363 logger.debug("Loaded digest [%s] from disk: %d entries.", digestPath, len(digest))
364 except Exception as e:
365 digest = {}
366 logger.error("Failed loading digest [%s] from disk: %s", digestPath, e)
367 return digest
368
369
370 ##########################
371 # _writeDigest() function
372 ##########################
373
374
375 def _writeDigest(config, digest, digestPath):
376 """
377 Writes the digest dictionary to the indicated digest path on disk.
378
379 If we can't write the digest successfully for any reason, we'll log the
380 condition but won't throw an exception.
381
382 Args:
383 config: Config object
384 digest: Digest dictionary to write to disk
385 digestPath: Path to the digest file on disk
386 """
387 try:
388 with open(digestPath, "wb") as f:
389 pickle.dump(digest, f, 0, fix_imports=True) # be compatible with Python 2
390 changeOwnership(digestPath, config.options.backupUser, config.options.backupGroup)
391 logger.debug("Wrote new digest [%s] to disk: %d entries.", digestPath, len(digest))
392 except Exception as e:
393 logger.error("Failed to write digest [%s] to disk: %s", digestPath, e)
394
395
396 ########################################################################
397 # Private attribute "getter" functions
398 ########################################################################
399
400 ############################
401 # getCollectMode() function
402 ############################
403
404
405 def _getCollectMode(config, item):
406 """
407 Gets the collect mode that should be used for a collect directory or file.
408 If possible, use the one on the file or directory, otherwise take from collect section.
409 Args:
410 config: Config object
411 item: ``CollectFile`` or ``CollectDir`` object
412 Returns:
413 Collect mode to use
414 """
415 if item.collectMode is None:
416 collectMode = config.collect.collectMode
417 else:
418 collectMode = item.collectMode
419 logger.debug("Collect mode is [%s]", collectMode)
420 return collectMode
421
422
423 #############################
424 # _getArchiveMode() function
425 #############################
426
427
428 def _getArchiveMode(config, item):
429 """
430 Gets the archive mode that should be used for a collect directory or file.
431 If possible, use the one on the file or directory, otherwise take from collect section.
432 Args:
433 config: Config object
434 item: ``CollectFile`` or ``CollectDir`` object
435 Returns:
436 Archive mode to use
437 """
438 if item.archiveMode is None:
439 archiveMode = config.collect.archiveMode
440 else:
441 archiveMode = item.archiveMode
442 logger.debug("Archive mode is [%s]", archiveMode)
443 return archiveMode
444
445
446 ############################
447 # _getIgnoreFile() function
448 ############################
449
450
451 def _getIgnoreFile(config, item):
452 """
453 Gets the ignore file that should be used for a collect directory or file.
454 If possible, use the one on the file or directory, otherwise take from collect section.
455 Args:
456 config: Config object
457 item: ``CollectFile`` or ``CollectDir`` object
458 Returns:
459 Ignore file to use
460 """
461 if item.ignoreFile is None:
462 ignoreFile = config.collect.ignoreFile
463 else:
464 ignoreFile = item.ignoreFile
465 logger.debug("Ignore file is [%s]", ignoreFile)
466 return ignoreFile
467
468
469 ############################
470 # _getLinkDepth() function
471 ############################
472
473
474 def _getLinkDepth(item):
475 """
476 Gets the link depth that should be used for a collect directory.
477 If possible, use the one on the directory, otherwise set a value of 0 (zero).
478 Args:
479 item: ``CollectDir`` object
480 Returns:
481 Link depth to use
482 """
483 if item.linkDepth is None:
484 linkDepth = 0
485 else:
486 linkDepth = item.linkDepth
487 logger.debug("Link depth is [%d]", linkDepth)
488 return linkDepth
489
490
491 ############################
492 # _getDereference() function
493 ############################
494
495
496 def _getDereference(item):
497 """
498 Gets the dereference flag that should be used for a collect directory.
499 If possible, use the one on the directory, otherwise set a value of False.
500 Args:
501 item: ``CollectDir`` object
502 Returns:
503 Dereference flag to use
504 """
505 if item.dereference is None:
506 dereference = False
507 else:
508 dereference = item.dereference
509 logger.debug("Dereference flag is [%s]", dereference)
510 return dereference
511
512
513 ################################
514 # _getRecursionLevel() function
515 ################################
516
517
518 def _getRecursionLevel(item):
519 """
520 Gets the recursion level that should be used for a collect directory.
521 If possible, use the one on the directory, otherwise set a value of 0 (zero).
522 Args:
523 item: ``CollectDir`` object
524 Returns:
525 Recursion level to use
526 """
527 if item.recursionLevel is None:
528 recursionLevel = 0
529 else:
530 recursionLevel = item.recursionLevel
531 logger.debug("Recursion level is [%d]", recursionLevel)
532 return recursionLevel
533
534
535 ############################
536 # _getDigestPath() function
537 ############################
538
539
540 def _getDigestPath(config, absolutePath):
541 """
542 Gets the digest path associated with a collect directory or file.
543 Args:
544 config: Config object
545 absolutePath: Absolute path to generate digest for
546 Returns:
547 Absolute path to the digest associated with the collect directory or file
548 """
549 normalized = buildNormalizedPath(absolutePath)
550 filename = "%s.%s" % (normalized, DIGEST_EXTENSION)
551 digestPath = pathJoin(config.options.workingDir, filename)
552 logger.debug("Digest path is [%s]", digestPath)
553 return digestPath
554
555
556 #############################
557 # _getTarfilePath() function
558 #############################
559
560
561 def _getTarfilePath(config, absolutePath, archiveMode):
562 """
563 Gets the tarfile path (including correct extension) associated with a collect directory.
564 Args:
565 config: Config object
566 absolutePath: Absolute path to generate tarfile for
567 archiveMode: Archive mode to use for this tarfile
568 Returns:
569 Absolute path to the tarfile associated with the collect directory
570 """
571 if archiveMode == "tar":
572 extension = "tar"
573 elif archiveMode == "targz":
574 extension = "tar.gz"
575 elif archiveMode == "tarbz2":
576 extension = "tar.bz2"
577 normalized = buildNormalizedPath(absolutePath)
578 filename = "%s.%s" % (normalized, extension)
579 tarfilePath = pathJoin(config.collect.targetDir, filename)
580 logger.debug("Tarfile path is [%s]", tarfilePath)
581 return tarfilePath
582
583
584 ############################
585 # _getExclusions() function
586 ############################
587
588
589 def _getExclusions(config, collectDir):
590 """
591 Gets exclusions (file and patterns) associated with a collect directory.
592
593 The returned files value is a list of absolute paths to be excluded from the
594 backup for a given directory. It is derived from the collect configuration
595 absolute exclude paths and the collect directory's absolute and relative
596 exclude paths.
597
598 The returned patterns value is a list of patterns to be excluded from the
599 backup for a given directory. It is derived from the list of patterns from
600 the collect configuration and from the collect directory itself.
601
602 Args:
603 config: Config object
604 collectDir: Collect directory object
605
606 Returns:
607 Tuple (files, patterns) indicating what to exclude
608 """
609 paths = []
610 if config.collect.absoluteExcludePaths is not None:
611 paths.extend(config.collect.absoluteExcludePaths)
612 if collectDir.absoluteExcludePaths is not None:
613 paths.extend(collectDir.absoluteExcludePaths)
614 if collectDir.relativeExcludePaths is not None:
615 for relativePath in collectDir.relativeExcludePaths:
616 paths.append(pathJoin(collectDir.absolutePath, relativePath))
617 patterns = []
618 if config.collect.excludePatterns is not None:
619 patterns.extend(config.collect.excludePatterns)
620 if collectDir.excludePatterns is not None:
621 patterns.extend(collectDir.excludePatterns)
622 logger.debug("Exclude paths: %s", paths)
623 logger.debug("Exclude patterns: %s", patterns)
624 return (paths, patterns)