shared.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. ):
  52. '''
  53. Given an excludes filename (or None), a vebosity flag, a storage config dict, a space-separated
  54. list of source directories, a local or remote repository path, and a command to run, create an
  55. attic archive.
  56. '''
  57. sources = tuple(re.split('\s+', source_directories))
  58. exclude_flags = ('--exclude-from', excludes_filename) if excludes_filename else ()
  59. compression = storage_config.get('compression', None)
  60. compression_flags = ('--compression', compression) if compression else ()
  61. verbosity_flags = {
  62. VERBOSITY_SOME: ('--stats',),
  63. VERBOSITY_LOTS: ('--verbose', '--stats'),
  64. }.get(verbosity, ())
  65. full_command = (
  66. command, 'create',
  67. '{repo}::{hostname}-{timestamp}'.format(
  68. repo=repository,
  69. hostname=platform.node(),
  70. timestamp=datetime.now().isoformat(),
  71. ),
  72. ) + sources + exclude_flags + compression_flags + verbosity_flags
  73. subprocess.check_call(full_command)
  74. def _make_prune_flags(retention_config):
  75. '''
  76. Given a retention config dict mapping from option name to value, tranform it into an iterable of
  77. command-line name-value flag pairs.
  78. For example, given a retention config of:
  79. {'keep_weekly': 4, 'keep_monthly': 6}
  80. This will be returned as an iterable of:
  81. (
  82. ('--keep-weekly', '4'),
  83. ('--keep-monthly', '6'),
  84. )
  85. '''
  86. return (
  87. ('--' + option_name.replace('_', '-'), str(retention_config[option_name]))
  88. for option_name, value in retention_config.items()
  89. )
  90. def prune_archives(verbosity, repository, retention_config, command):
  91. '''
  92. Given a verbosity flag, a local or remote repository path, a retention config dict, and a
  93. command to run, prune attic archives according the the retention policy specified in that
  94. configuration.
  95. '''
  96. verbosity_flags = {
  97. VERBOSITY_SOME: ('--stats',),
  98. VERBOSITY_LOTS: ('--verbose', '--stats'),
  99. }.get(verbosity, ())
  100. full_command = (
  101. command, 'prune',
  102. repository,
  103. ) + tuple(
  104. element
  105. for pair in _make_prune_flags(retention_config)
  106. for element in pair
  107. ) + verbosity_flags
  108. subprocess.check_call(full_command)
  109. DEFAULT_CHECKS = ('repository', 'archives')
  110. def _parse_checks(consistency_config):
  111. '''
  112. Given a consistency config with a space-separated "checks" option, transform it to a tuple of
  113. named checks to run.
  114. For example, given a retention config of:
  115. {'checks': 'repository archives'}
  116. This will be returned as:
  117. ('repository', 'archives')
  118. If no "checks" option is present, return the DEFAULT_CHECKS. If the checks value is the string
  119. "disabled", return an empty tuple, meaning that no checks should be run.
  120. '''
  121. checks = consistency_config.get('checks', '').strip()
  122. if not checks:
  123. return DEFAULT_CHECKS
  124. return tuple(
  125. check for check in consistency_config['checks'].split(' ')
  126. if check.lower() not in ('disabled', '')
  127. )
  128. def _make_check_flags(checks, check_last=None):
  129. '''
  130. Given a parsed sequence of checks, transform it into tuple of command-line flags.
  131. For example, given parsed checks of:
  132. ('repository',)
  133. This will be returned as:
  134. ('--repository-only',)
  135. Additionally, if a check_last value is given, a "--last" flag will be added. Note that only
  136. Borg supports this flag.
  137. '''
  138. last_flag = ('--last', check_last) if check_last else ()
  139. if checks == DEFAULT_CHECKS:
  140. return last_flag
  141. return tuple(
  142. '--{}-only'.format(check) for check in checks
  143. ) + last_flag
  144. def check_archives(verbosity, repository, consistency_config, command):
  145. '''
  146. Given a verbosity flag, a local or remote repository path, a consistency config dict, and a
  147. command to run, check the contained attic archives for consistency.
  148. If there are no consistency checks to run, skip running them.
  149. '''
  150. checks = _parse_checks(consistency_config)
  151. check_last = consistency_config.get('check_last', None)
  152. if not checks:
  153. return
  154. verbosity_flags = {
  155. VERBOSITY_SOME: ('--verbose',),
  156. VERBOSITY_LOTS: ('--verbose',),
  157. }.get(verbosity, ())
  158. full_command = (
  159. command, 'check',
  160. repository,
  161. ) + _make_check_flags(checks, check_last) + verbosity_flags
  162. # The check command spews to stdout even without the verbose flag. Suppress it.
  163. stdout = None if verbosity_flags else open(os.devnull, 'w')
  164. subprocess.check_call(full_command, stdout=stdout)