shared.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from datetime import datetime
  2. import os
  3. import re
  4. import platform
  5. import subprocess
  6. from atticmatic.config import Section_format, option
  7. from atticmatic.verbosity import VERBOSITY_SOME, VERBOSITY_LOTS
  8. # Common backend functionality shared by Attic and Borg. As the two backup
  9. # commands diverge, these shared functions will likely need to be replaced
  10. # with non-shared functions within atticmatic.backends.attic and
  11. # atticmatic.backends.borg.
  12. CONFIG_FORMAT = (
  13. Section_format(
  14. 'location',
  15. (
  16. option('source_directories'),
  17. option('repository'),
  18. ),
  19. ),
  20. Section_format(
  21. 'storage',
  22. (
  23. option('encryption_passphrase', required=False),
  24. ),
  25. ),
  26. Section_format(
  27. 'retention',
  28. (
  29. option('keep_within', required=False),
  30. option('keep_hourly', int, required=False),
  31. option('keep_daily', int, required=False),
  32. option('keep_weekly', int, required=False),
  33. option('keep_monthly', int, required=False),
  34. option('keep_yearly', int, required=False),
  35. option('prefix', required=False),
  36. ),
  37. ),
  38. Section_format(
  39. 'consistency',
  40. (
  41. option('checks', required=False),
  42. ),
  43. )
  44. )
  45. def initialize(storage_config, command):
  46. passphrase = storage_config.get('encryption_passphrase')
  47. if passphrase:
  48. os.environ['{}_PASSPHRASE'.format(command.upper())] = passphrase
  49. def create_archive(
  50. excludes_filename, verbosity, storage_config, source_directories, repository, command,
  51. one_file_system=None,
  52. ):
  53. '''
  54. Given an excludes filename (or None), a vebosity flag, a storage config dict, a space-separated
  55. list of source directories, a local or remote repository path, and a command to run, create an
  56. attic archive.
  57. '''
  58. sources = tuple(re.split('\s+', source_directories))
  59. exclude_flags = ('--exclude-from', excludes_filename) if excludes_filename else ()
  60. compression = storage_config.get('compression', None)
  61. compression_flags = ('--compression', compression) if compression else ()
  62. one_file_system_flags = ('--one-file-system',) if one_file_system else ()
  63. verbosity_flags = {
  64. VERBOSITY_SOME: ('--stats',),
  65. VERBOSITY_LOTS: ('--verbose', '--stats'),
  66. }.get(verbosity, ())
  67. full_command = (
  68. command, 'create',
  69. '{repo}::{hostname}-{timestamp}'.format(
  70. repo=repository,
  71. hostname=platform.node(),
  72. timestamp=datetime.now().isoformat(),
  73. ),
  74. ) + sources + exclude_flags + compression_flags + one_file_system_flags + \
  75. verbosity_flags
  76. subprocess.check_call(full_command)
  77. def _make_prune_flags(retention_config):
  78. '''
  79. Given a retention config dict mapping from option name to value, tranform it into an iterable of
  80. command-line name-value flag pairs.
  81. For example, given a retention config of:
  82. {'keep_weekly': 4, 'keep_monthly': 6}
  83. This will be returned as an iterable of:
  84. (
  85. ('--keep-weekly', '4'),
  86. ('--keep-monthly', '6'),
  87. )
  88. '''
  89. return (
  90. ('--' + option_name.replace('_', '-'), str(retention_config[option_name]))
  91. for option_name, value in retention_config.items()
  92. )
  93. def prune_archives(verbosity, repository, retention_config, command):
  94. '''
  95. Given a verbosity flag, a local or remote repository path, a retention config dict, and a
  96. command to run, prune attic archives according the the retention policy specified in that
  97. configuration.
  98. '''
  99. verbosity_flags = {
  100. VERBOSITY_SOME: ('--stats',),
  101. VERBOSITY_LOTS: ('--verbose', '--stats'),
  102. }.get(verbosity, ())
  103. full_command = (
  104. command, 'prune',
  105. repository,
  106. ) + tuple(
  107. element
  108. for pair in _make_prune_flags(retention_config)
  109. for element in pair
  110. ) + verbosity_flags
  111. subprocess.check_call(full_command)
  112. DEFAULT_CHECKS = ('repository', 'archives')
  113. def _parse_checks(consistency_config):
  114. '''
  115. Given a consistency config with a space-separated "checks" option, transform it to a tuple of
  116. named checks to run.
  117. For example, given a retention config of:
  118. {'checks': 'repository archives'}
  119. This will be returned as:
  120. ('repository', 'archives')
  121. If no "checks" option is present, return the DEFAULT_CHECKS. If the checks value is the string
  122. "disabled", return an empty tuple, meaning that no checks should be run.
  123. '''
  124. checks = consistency_config.get('checks', '').strip()
  125. if not checks:
  126. return DEFAULT_CHECKS
  127. return tuple(
  128. check for check in consistency_config['checks'].split(' ')
  129. if check.lower() not in ('disabled', '')
  130. )
  131. def _make_check_flags(checks, check_last=None):
  132. '''
  133. Given a parsed sequence of checks, transform it into tuple of command-line flags.
  134. For example, given parsed checks of:
  135. ('repository',)
  136. This will be returned as:
  137. ('--repository-only',)
  138. Additionally, if a check_last value is given, a "--last" flag will be added. Note that only
  139. Borg supports this flag.
  140. '''
  141. last_flag = ('--last', check_last) if check_last else ()
  142. if checks == DEFAULT_CHECKS:
  143. return last_flag
  144. return tuple(
  145. '--{}-only'.format(check) for check in checks
  146. ) + last_flag
  147. def check_archives(verbosity, repository, consistency_config, command):
  148. '''
  149. Given a verbosity flag, a local or remote repository path, a consistency config dict, and a
  150. command to run, check the contained attic archives for consistency.
  151. If there are no consistency checks to run, skip running them.
  152. '''
  153. checks = _parse_checks(consistency_config)
  154. check_last = consistency_config.get('check_last', None)
  155. if not checks:
  156. return
  157. verbosity_flags = {
  158. VERBOSITY_SOME: ('--verbose',),
  159. VERBOSITY_LOTS: ('--verbose',),
  160. }.get(verbosity, ())
  161. full_command = (
  162. command, 'check',
  163. repository,
  164. ) + _make_check_flags(checks, check_last) + verbosity_flags
  165. # The check command spews to stdout even without the verbose flag. Suppress it.
  166. stdout = None if verbosity_flags else open(os.devnull, 'w')
  167. subprocess.check_call(full_command, stdout=stdout)