sqlite.py 5.6 KB

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