btrfs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import collections
  2. import glob
  3. import json
  4. import logging
  5. import os
  6. import shutil
  7. import subprocess
  8. import borgmatic.borg.pattern
  9. import borgmatic.config.paths
  10. import borgmatic.execute
  11. import borgmatic.hooks.command
  12. import borgmatic.hooks.data_source.snapshot
  13. logger = logging.getLogger(__name__)
  14. def use_streaming(hook_config, config): # pragma: no cover
  15. '''
  16. Return whether dump streaming is used for this hook. (Spoiler: It isn't.)
  17. '''
  18. return False
  19. def get_subvolume_mount_points(findmnt_command):
  20. '''
  21. Given a findmnt command to run, get all sorted Btrfs subvolume mount points.
  22. '''
  23. findmnt_output = borgmatic.execute.execute_command_and_capture_output(
  24. tuple(findmnt_command.split(' '))
  25. + (
  26. '-t', # Filesystem type.
  27. 'btrfs',
  28. '--json',
  29. '--list', # Request a flat list instead of a nested subvolume hierarchy.
  30. )
  31. )
  32. try:
  33. return tuple(
  34. sorted(filesystem['target'] for filesystem in json.loads(findmnt_output)['filesystems'])
  35. )
  36. except json.JSONDecodeError as error:
  37. raise ValueError(f'Invalid {findmnt_command} JSON output: {error}')
  38. except KeyError as error:
  39. raise ValueError(f'Invalid {findmnt_command} output: Missing key "{error}"')
  40. Subvolume = collections.namedtuple('Subvolume', ('path', 'contained_patterns'), defaults=((),))
  41. def get_subvolumes(btrfs_command, findmnt_command, patterns=None):
  42. '''
  43. Given a Btrfs command to run and a sequence of configured patterns, find the intersection
  44. between the current Btrfs filesystem and subvolume mount points and the paths of any patterns.
  45. The idea is that these pattern paths represent the requested subvolumes to snapshot.
  46. Only include subvolumes that contain at least one root pattern sourced from borgmatic
  47. configuration (as opposed to generated elsewhere in borgmatic). But if patterns is None, then
  48. return all subvolumes instead, sorted by path.
  49. Return the result as a sequence of matching subvolume mount points.
  50. '''
  51. candidate_patterns = set(patterns or ())
  52. subvolumes = []
  53. # For each subvolume mount point, match it against the given patterns to find the subvolumes to
  54. # backup. Sort the subvolumes from longest to shortest mount points, so longer mount points get
  55. # a whack at the candidate pattern piñata before their parents do. (Patterns are consumed during
  56. # this process, so no two subvolumes end up with the same contained patterns.)
  57. for mount_point in reversed(get_subvolume_mount_points(findmnt_command)):
  58. subvolumes.extend(
  59. Subvolume(mount_point, contained_patterns)
  60. for contained_patterns in (
  61. borgmatic.hooks.data_source.snapshot.get_contained_patterns(
  62. mount_point, candidate_patterns
  63. ),
  64. )
  65. if patterns is None
  66. or any(
  67. pattern.type == borgmatic.borg.pattern.Pattern_type.ROOT
  68. and pattern.source == borgmatic.borg.pattern.Pattern_source.CONFIG
  69. for pattern in contained_patterns
  70. )
  71. )
  72. return tuple(sorted(subvolumes, key=lambda subvolume: subvolume.path))
  73. BORGMATIC_SNAPSHOT_PREFIX = '.borgmatic-snapshot-'
  74. def make_snapshot_path(subvolume_path):
  75. '''
  76. Given the path to a subvolume, make a corresponding snapshot path for it.
  77. '''
  78. return os.path.join(
  79. subvolume_path,
  80. f'{BORGMATIC_SNAPSHOT_PREFIX}{os.getpid()}',
  81. # Included so that the snapshot ends up in the Borg archive at the "original" subvolume path.
  82. ) + subvolume_path.rstrip(os.path.sep)
  83. def make_snapshot_exclude_pattern(subvolume_path): # pragma: no cover
  84. '''
  85. Given the path to a subvolume, make a corresponding exclude pattern for its embedded snapshot
  86. path. This is to work around a quirk of Btrfs: If you make a snapshot path as a child directory
  87. of a subvolume, then the snapshot's own initial directory component shows up as an empty
  88. directory within the snapshot itself. For instance, if you have a Btrfs subvolume at /mnt and
  89. make a snapshot of it at:
  90. /mnt/.borgmatic-snapshot-1234/mnt
  91. ... then the snapshot itself will have an empty directory at:
  92. /mnt/.borgmatic-snapshot-1234/mnt/.borgmatic-snapshot-1234
  93. So to prevent that from ending up in the Borg archive, this function produces an exclude pattern
  94. to exclude that path.
  95. '''
  96. snapshot_directory = f'{BORGMATIC_SNAPSHOT_PREFIX}{os.getpid()}'
  97. return borgmatic.borg.pattern.Pattern(
  98. os.path.join(
  99. subvolume_path,
  100. snapshot_directory,
  101. subvolume_path.lstrip(os.path.sep),
  102. snapshot_directory,
  103. ),
  104. borgmatic.borg.pattern.Pattern_type.NO_RECURSE,
  105. borgmatic.borg.pattern.Pattern_style.FNMATCH,
  106. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  107. )
  108. def make_borg_snapshot_pattern(subvolume_path, pattern):
  109. '''
  110. Given the path to a subvolume and a pattern as a borgmatic.borg.pattern.Pattern instance whose
  111. path is inside the subvolume, return a new Pattern with its path rewritten to be in a snapshot
  112. path intended for giving to Borg.
  113. Move any initial caret in a regular expression pattern path to the beginning, so as not to break
  114. the regular expression.
  115. '''
  116. initial_caret = (
  117. '^'
  118. if pattern.style == borgmatic.borg.pattern.Pattern_style.REGULAR_EXPRESSION
  119. and pattern.path.startswith('^')
  120. else ''
  121. )
  122. rewritten_path = initial_caret + os.path.join(
  123. subvolume_path,
  124. f'{BORGMATIC_SNAPSHOT_PREFIX}{os.getpid()}',
  125. '.', # Borg 1.4+ "slashdot" hack.
  126. # Included so that the source directory ends up in the Borg archive at its "original" path.
  127. pattern.path.lstrip('^').lstrip(os.path.sep),
  128. )
  129. return borgmatic.borg.pattern.Pattern(
  130. rewritten_path,
  131. pattern.type,
  132. pattern.style,
  133. pattern.device,
  134. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  135. )
  136. def snapshot_subvolume(btrfs_command, subvolume_path, snapshot_path): # pragma: no cover
  137. '''
  138. Given a Btrfs command to run, the path to a subvolume, and the path for a snapshot, create a new
  139. Btrfs snapshot of the subvolume.
  140. '''
  141. os.makedirs(os.path.dirname(snapshot_path), mode=0o700, exist_ok=True)
  142. borgmatic.execute.execute_command(
  143. tuple(btrfs_command.split(' '))
  144. + (
  145. 'subvolume',
  146. 'snapshot',
  147. '-r', # Read-only.
  148. subvolume_path,
  149. snapshot_path,
  150. ),
  151. output_log_level=logging.DEBUG,
  152. )
  153. def dump_data_sources(
  154. hook_config,
  155. config,
  156. config_paths,
  157. borgmatic_runtime_directory,
  158. patterns,
  159. dry_run,
  160. ):
  161. '''
  162. Given a Btrfs configuration dict, a configuration dict, the borgmatic configuration file paths,
  163. the borgmatic runtime directory, the configured patterns, and whether this is a dry run,
  164. auto-detect and snapshot any Btrfs subvolume mount points listed in the given patterns. Also
  165. update those patterns, replacing subvolume mount points with corresponding snapshot directories
  166. so they get stored in the Borg archive instead.
  167. Return an empty sequence, since there are no ongoing dump processes from this hook.
  168. If this is a dry run, then don't actually snapshot anything.
  169. '''
  170. with borgmatic.hooks.command.Before_after_hooks(
  171. command_hooks=config.get('commands'),
  172. before_after='dump_data_sources',
  173. umask=config.get('umask'),
  174. dry_run=dry_run,
  175. hook_name='btrfs',
  176. ):
  177. dry_run_label = ' (dry run; not actually snapshotting anything)' if dry_run else ''
  178. logger.info(f'Snapshotting Btrfs subvolumes{dry_run_label}')
  179. # Based on the configured patterns, determine Btrfs subvolumes to backup. Only consider those
  180. # patterns that came from actual user configuration (as opposed to, say, other hooks).
  181. btrfs_command = hook_config.get('btrfs_command', 'btrfs')
  182. findmnt_command = hook_config.get('findmnt_command', 'findmnt')
  183. subvolumes = get_subvolumes(btrfs_command, findmnt_command, patterns)
  184. if not subvolumes:
  185. logger.warning(f'No Btrfs subvolumes found to snapshot{dry_run_label}')
  186. # Snapshot each subvolume, rewriting patterns to use their snapshot paths.
  187. for subvolume in subvolumes:
  188. logger.debug(f'Creating Btrfs snapshot for {subvolume.path} subvolume')
  189. snapshot_path = make_snapshot_path(subvolume.path)
  190. if dry_run:
  191. continue
  192. snapshot_subvolume(btrfs_command, subvolume.path, snapshot_path)
  193. for pattern in subvolume.contained_patterns:
  194. snapshot_pattern = make_borg_snapshot_pattern(subvolume.path, pattern)
  195. # Attempt to update the pattern in place, since pattern order matters to Borg.
  196. try:
  197. patterns[patterns.index(pattern)] = snapshot_pattern
  198. except ValueError:
  199. patterns.append(snapshot_pattern)
  200. patterns.append(make_snapshot_exclude_pattern(subvolume.path))
  201. return []
  202. def delete_snapshot(btrfs_command, snapshot_path): # pragma: no cover
  203. '''
  204. Given a Btrfs command to run and the name of a snapshot path, delete it.
  205. '''
  206. borgmatic.execute.execute_command(
  207. tuple(btrfs_command.split(' '))
  208. + (
  209. 'subvolume',
  210. 'delete',
  211. snapshot_path,
  212. ),
  213. output_log_level=logging.DEBUG,
  214. )
  215. def remove_data_source_dumps(hook_config, config, borgmatic_runtime_directory, dry_run):
  216. '''
  217. Given a Btrfs configuration dict, a configuration dict, the borgmatic runtime directory, and
  218. whether this is a dry run, delete any Btrfs snapshots created by borgmatic. If this is a dry run
  219. or Btrfs isn't configured in borgmatic's configuration, then don't actually remove anything.
  220. '''
  221. if hook_config is None:
  222. return
  223. dry_run_label = ' (dry run; not actually removing anything)' if dry_run else ''
  224. btrfs_command = hook_config.get('btrfs_command', 'btrfs')
  225. findmnt_command = hook_config.get('findmnt_command', 'findmnt')
  226. try:
  227. all_subvolumes = get_subvolumes(btrfs_command, findmnt_command)
  228. except FileNotFoundError as error:
  229. logger.debug(f'Could not find "{error.filename}" command')
  230. return
  231. except subprocess.CalledProcessError as error:
  232. logger.debug(error)
  233. return
  234. # Reversing the sorted subvolumes ensures that we remove longer mount point paths of child
  235. # subvolumes before the shorter mount point paths of parent subvolumes.
  236. for subvolume in reversed(all_subvolumes):
  237. subvolume_snapshots_glob = borgmatic.config.paths.replace_temporary_subdirectory_with_glob(
  238. os.path.normpath(make_snapshot_path(subvolume.path)),
  239. temporary_directory_prefix=BORGMATIC_SNAPSHOT_PREFIX,
  240. )
  241. logger.debug(
  242. f'Looking for snapshots to remove in {subvolume_snapshots_glob}{dry_run_label}'
  243. )
  244. for snapshot_path in glob.glob(subvolume_snapshots_glob):
  245. if not os.path.isdir(snapshot_path):
  246. continue
  247. logger.debug(f'Deleting Btrfs snapshot {snapshot_path}{dry_run_label}')
  248. if dry_run:
  249. continue
  250. try:
  251. delete_snapshot(btrfs_command, snapshot_path)
  252. except FileNotFoundError:
  253. logger.debug(f'Could not find "{btrfs_command}" command')
  254. return
  255. except subprocess.CalledProcessError as error:
  256. logger.debug(error)
  257. return
  258. # Remove the snapshot parent directory if it still exists. (It might not exist if the
  259. # snapshot was for "/".)
  260. snapshot_parent_dir = snapshot_path.rsplit(subvolume.path, 1)[0]
  261. if os.path.isdir(snapshot_parent_dir):
  262. shutil.rmtree(snapshot_parent_dir)
  263. def make_data_source_dump_patterns(
  264. hook_config, config, borgmatic_runtime_directory, name=None
  265. ): # pragma: no cover
  266. '''
  267. Restores aren't implemented, because stored files can be extracted directly with "extract".
  268. '''
  269. return ()
  270. def restore_data_source_dump(
  271. hook_config,
  272. config,
  273. data_source,
  274. dry_run,
  275. extract_process,
  276. connection_params,
  277. borgmatic_runtime_directory,
  278. ): # pragma: no cover
  279. '''
  280. Restores aren't implemented, because stored files can be extracted directly with "extract".
  281. '''
  282. raise NotImplementedError()