2
0

mariadb.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import copy
  2. import logging
  3. import os
  4. import shlex
  5. import borgmatic.config.paths
  6. from borgmatic.execute import (
  7. execute_command,
  8. execute_command_and_capture_output,
  9. execute_command_with_processes,
  10. )
  11. from borgmatic.hooks import dump
  12. logger = logging.getLogger(__name__)
  13. def make_dump_path(base_directory): # pragma: no cover
  14. '''
  15. Given a base directory, make the corresponding dump path.
  16. '''
  17. return dump.make_data_source_dump_path(base_directory, 'mariadb_databases')
  18. SYSTEM_DATABASE_NAMES = ('information_schema', 'mysql', 'performance_schema', 'sys')
  19. def database_names_to_dump(database, extra_environment, log_prefix, dry_run):
  20. '''
  21. Given a requested database config, return the corresponding sequence of database names to dump.
  22. In the case of "all", query for the names of databases on the configured host and return them,
  23. excluding any system databases that will cause problems during restore.
  24. '''
  25. if database['name'] != 'all':
  26. return (database['name'],)
  27. if dry_run:
  28. return ()
  29. mariadb_show_command = tuple(
  30. shlex.quote(part) for part in shlex.split(database.get('mariadb_command') or 'mariadb')
  31. )
  32. show_command = (
  33. mariadb_show_command
  34. + (tuple(database['list_options'].split(' ')) if 'list_options' in database else ())
  35. + (('--host', database['hostname']) if 'hostname' in database else ())
  36. + (('--port', str(database['port'])) if 'port' in database else ())
  37. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  38. + (('--user', database['username']) if 'username' in database else ())
  39. + ('--skip-column-names', '--batch')
  40. + ('--execute', 'show schemas')
  41. )
  42. logger.debug(f'{log_prefix}: Querying for "all" MariaDB databases to dump')
  43. show_output = execute_command_and_capture_output(
  44. show_command, extra_environment=extra_environment
  45. )
  46. return tuple(
  47. show_name
  48. for show_name in show_output.strip().splitlines()
  49. if show_name not in SYSTEM_DATABASE_NAMES
  50. )
  51. def execute_dump_command(
  52. database, log_prefix, dump_path, database_names, extra_environment, dry_run, dry_run_label
  53. ):
  54. '''
  55. Kick off a dump for the given MariaDB database (provided as a configuration dict) to a named
  56. pipe constructed from the given dump path and database name. Use the given log prefix in any
  57. log entries.
  58. Return a subprocess.Popen instance for the dump process ready to spew to a named pipe. But if
  59. this is a dry run, then don't actually dump anything and return None.
  60. '''
  61. database_name = database['name']
  62. dump_filename = dump.make_data_source_dump_filename(
  63. dump_path, database['name'], database.get('hostname')
  64. )
  65. if os.path.exists(dump_filename):
  66. logger.warning(
  67. f'{log_prefix}: Skipping duplicate dump of MariaDB database "{database_name}" to {dump_filename}'
  68. )
  69. return None
  70. mariadb_dump_command = tuple(
  71. shlex.quote(part)
  72. for part in shlex.split(database.get('mariadb_dump_command') or 'mariadb-dump')
  73. )
  74. dump_command = (
  75. mariadb_dump_command
  76. + (tuple(database['options'].split(' ')) if 'options' in database else ())
  77. + (('--add-drop-database',) if database.get('add_drop_database', True) else ())
  78. + (('--host', database['hostname']) if 'hostname' in database else ())
  79. + (('--port', str(database['port'])) if 'port' in database else ())
  80. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  81. + (('--user', database['username']) if 'username' in database else ())
  82. + ('--databases',)
  83. + database_names
  84. + ('--result-file', dump_filename)
  85. )
  86. logger.debug(
  87. f'{log_prefix}: Dumping MariaDB database "{database_name}" to {dump_filename}{dry_run_label}'
  88. )
  89. if dry_run:
  90. return None
  91. dump.create_named_pipe_for_dump(dump_filename)
  92. return execute_command(
  93. dump_command,
  94. extra_environment=extra_environment,
  95. run_to_completion=False,
  96. )
  97. def use_streaming(databases, config, log_prefix):
  98. '''
  99. Given a sequence of MariaDB database configuration dicts, a configuration dict (ignored), and a
  100. log prefix (ignored), return whether streaming will be using during dumps.
  101. '''
  102. return any(databases)
  103. def dump_data_sources(databases, config, log_prefix, borgmatic_runtime_directory, dry_run):
  104. '''
  105. Dump the given MariaDB databases to a named pipe. The databases are supplied as a sequence of
  106. dicts, one dict describing each database as per the configuration schema. Use the given
  107. borgmatic runtime directory to construct the destination path and the given log prefix in any
  108. log entries.
  109. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  110. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  111. '''
  112. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  113. processes = []
  114. logger.info(f'{log_prefix}: Dumping MariaDB databases{dry_run_label}')
  115. for database in databases:
  116. dump_path = make_dump_path(borgmatic_runtime_directory)
  117. extra_environment = {'MYSQL_PWD': database['password']} if 'password' in database else None
  118. dump_database_names = database_names_to_dump(
  119. database, extra_environment, log_prefix, dry_run
  120. )
  121. if not dump_database_names:
  122. if dry_run:
  123. continue
  124. raise ValueError('Cannot find any MariaDB databases to dump.')
  125. if database['name'] == 'all' and database.get('format'):
  126. for dump_name in dump_database_names:
  127. renamed_database = copy.copy(database)
  128. renamed_database['name'] = dump_name
  129. processes.append(
  130. execute_dump_command(
  131. renamed_database,
  132. log_prefix,
  133. dump_path,
  134. (dump_name,),
  135. extra_environment,
  136. dry_run,
  137. dry_run_label,
  138. )
  139. )
  140. else:
  141. processes.append(
  142. execute_dump_command(
  143. database,
  144. log_prefix,
  145. dump_path,
  146. dump_database_names,
  147. extra_environment,
  148. dry_run,
  149. dry_run_label,
  150. )
  151. )
  152. return [process for process in processes if process]
  153. def remove_data_source_dumps(
  154. databases, config, log_prefix, borgmatic_runtime_directory, dry_run
  155. ): # pragma: no cover
  156. '''
  157. Remove all database dump files for this hook regardless of the given databases. Use the
  158. borgmatic_runtime_directory to construct the destination path and the log prefix in any log
  159. entries. If this is a dry run, then don't actually remove anything.
  160. '''
  161. dump.remove_data_source_dumps(
  162. make_dump_path(borgmatic_runtime_directory), 'MariaDB', log_prefix, dry_run
  163. )
  164. def make_data_source_dump_patterns(
  165. databases, config, log_prefix, borgmatic_runtime_directory, name=None
  166. ): # pragma: no cover
  167. '''
  168. Given a sequence of configurations dicts, a configuration dict, a prefix to log with, the
  169. borgmatic runtime directory, and a database name to match, return the corresponding glob
  170. patterns to match the database dump in an archive.
  171. '''
  172. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  173. return (
  174. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  175. dump.make_data_source_dump_filename(
  176. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  177. ),
  178. dump.make_data_source_dump_filename(
  179. make_dump_path(borgmatic_source_directory), name, hostname='*'
  180. ),
  181. )
  182. def restore_data_source_dump(
  183. hook_config, config, log_prefix, data_source, dry_run, extract_process, connection_params
  184. ):
  185. '''
  186. Restore a database from the given extract stream. The database is supplied as a data source
  187. configuration dict, but the given hook configuration is ignored. The given configuration dict is
  188. used to construct the destination path, and the given log prefix is used for any log entries. If
  189. this is a dry run, then don't actually restore anything. Trigger the given active extract
  190. process (an instance of subprocess.Popen) to produce output to consume.
  191. '''
  192. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  193. hostname = connection_params['hostname'] or data_source.get(
  194. 'restore_hostname', data_source.get('hostname')
  195. )
  196. port = str(
  197. connection_params['port'] or data_source.get('restore_port', data_source.get('port', ''))
  198. )
  199. username = connection_params['username'] or data_source.get(
  200. 'restore_username', data_source.get('username')
  201. )
  202. password = connection_params['password'] or data_source.get(
  203. 'restore_password', data_source.get('password')
  204. )
  205. mariadb_restore_command = tuple(
  206. shlex.quote(part) for part in shlex.split(data_source.get('mariadb_command') or 'mariadb')
  207. )
  208. restore_command = (
  209. mariadb_restore_command
  210. + ('--batch',)
  211. + (
  212. tuple(data_source['restore_options'].split(' '))
  213. if 'restore_options' in data_source
  214. else ()
  215. )
  216. + (('--host', hostname) if hostname else ())
  217. + (('--port', str(port)) if port else ())
  218. + (('--protocol', 'tcp') if hostname or port else ())
  219. + (('--user', username) if username else ())
  220. )
  221. extra_environment = {'MYSQL_PWD': password} if password else None
  222. logger.debug(f"{log_prefix}: Restoring MariaDB database {data_source['name']}{dry_run_label}")
  223. if dry_run:
  224. return
  225. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  226. # if the restore paths don't exist in the archive.
  227. execute_command_with_processes(
  228. restore_command,
  229. [extract_process],
  230. output_log_level=logging.DEBUG,
  231. input_file=extract_process.stdout,
  232. extra_environment=extra_environment,
  233. )