shared.py 6.1 KB

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