mariadb.py 9.4 KB

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