mysql.py 8.9 KB

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