sqlite.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import logging
  2. import os
  3. import shlex
  4. import borgmatic.borg.pattern
  5. import borgmatic.config.paths
  6. from borgmatic.execute import execute_command, execute_command_with_processes
  7. from borgmatic.hooks.data_source import dump
  8. logger = logging.getLogger(__name__)
  9. def make_dump_path(base_directory): # pragma: no cover
  10. '''
  11. Given a base directory, make the corresponding dump path.
  12. '''
  13. return dump.make_data_source_dump_path(base_directory, 'sqlite_databases')
  14. def get_default_port(databases, config): # pragma: no cover
  15. return None # SQLite doesn't use a port.
  16. def use_streaming(databases, config):
  17. '''
  18. Given a sequence of SQLite database configuration dicts, a configuration dict (ignored), return
  19. whether streaming will be using during dumps.
  20. '''
  21. return any(databases)
  22. def dump_data_sources(
  23. databases,
  24. config,
  25. config_paths,
  26. borgmatic_runtime_directory,
  27. patterns,
  28. dry_run,
  29. ):
  30. '''
  31. Dump the given SQLite databases to a named pipe. The databases are supplied as a sequence of
  32. configuration dicts, as per the configuration schema. Use the given borgmatic runtime directory
  33. to construct the destination path.
  34. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  35. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  36. Also append the the parent directory of the database dumps to the given patterns list, so the
  37. dumps actually get backed up.
  38. '''
  39. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  40. processes = []
  41. logger.info(f'Dumping SQLite databases{dry_run_label}')
  42. for database in databases:
  43. database_path = database['path']
  44. if database['name'] == 'all':
  45. logger.warning('The "all" database name has no meaning for SQLite databases')
  46. if not os.path.exists(database_path):
  47. logger.warning(
  48. f'No SQLite database at {database_path}; an empty database will be created and dumped'
  49. )
  50. dump_path = make_dump_path(borgmatic_runtime_directory)
  51. dump_filename = dump.make_data_source_dump_filename(dump_path, database['name'])
  52. if os.path.exists(dump_filename):
  53. logger.warning(
  54. f'Skipping duplicate dump of SQLite database at {database_path} to {dump_filename}'
  55. )
  56. continue
  57. sqlite_command = tuple(
  58. shlex.quote(part) for part in shlex.split(database.get('sqlite_command') or 'sqlite3')
  59. )
  60. command = sqlite_command + (
  61. shlex.quote(database_path),
  62. '.dump',
  63. '>',
  64. shlex.quote(dump_filename),
  65. )
  66. logger.debug(
  67. f'Dumping SQLite database at {database_path} to {dump_filename}{dry_run_label}'
  68. )
  69. if dry_run:
  70. continue
  71. dump.create_named_pipe_for_dump(dump_filename)
  72. processes.append(
  73. execute_command(command, shell=True, run_to_completion=False) # noqa: S604
  74. )
  75. if not dry_run:
  76. patterns.append(
  77. borgmatic.borg.pattern.Pattern(
  78. os.path.join(borgmatic_runtime_directory, 'sqlite_databases'),
  79. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  80. )
  81. )
  82. return processes
  83. def remove_data_source_dumps(
  84. databases, config, borgmatic_runtime_directory, dry_run
  85. ): # pragma: no cover
  86. '''
  87. Remove all database dump files for this hook regardless of the given databases. Use the
  88. borgmatic runtime directory to construct the destination path. If this is a dry run, then don't
  89. actually remove anything.
  90. '''
  91. dump.remove_data_source_dumps(make_dump_path(borgmatic_runtime_directory), 'SQLite', dry_run)
  92. def make_data_source_dump_patterns(
  93. databases, config, borgmatic_runtime_directory, name=None
  94. ): # pragma: no cover
  95. '''
  96. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  97. and a database name to match, return the corresponding glob patterns to match the database dump
  98. in an archive.
  99. '''
  100. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  101. return (
  102. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  103. dump.make_data_source_dump_filename(
  104. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  105. ),
  106. dump.make_data_source_dump_filename(
  107. make_dump_path(borgmatic_source_directory), name, hostname='*'
  108. ),
  109. )
  110. def restore_data_source_dump(
  111. hook_config,
  112. config,
  113. data_source,
  114. dry_run,
  115. extract_process,
  116. connection_params,
  117. borgmatic_runtime_directory,
  118. ):
  119. '''
  120. Restore a database from the given extract stream. The database is supplied as a data source
  121. configuration dict, but the given hook configuration is ignored. If this is a dry run, then
  122. don't actually restore anything. Trigger the given active extract process (an instance of
  123. subprocess.Popen) to produce output to consume.
  124. '''
  125. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  126. database_path = connection_params['restore_path'] or data_source.get(
  127. 'restore_path', data_source.get('path')
  128. )
  129. logger.debug(f'Restoring SQLite database at {database_path}{dry_run_label}')
  130. if dry_run:
  131. return
  132. try:
  133. os.remove(database_path)
  134. logger.warning(f'Removed existing SQLite database at {database_path}')
  135. except FileNotFoundError: # pragma: no cover
  136. pass
  137. sqlite_restore_command = tuple(
  138. shlex.quote(part)
  139. for part in shlex.split(data_source.get('sqlite_restore_command') or 'sqlite3')
  140. )
  141. restore_command = sqlite_restore_command + (shlex.quote(database_path),)
  142. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  143. # if the restore paths don't exist in the archive.
  144. execute_command_with_processes(
  145. restore_command,
  146. [extract_process],
  147. output_log_level=logging.DEBUG,
  148. input_file=extract_process.stdout,
  149. )