2
0

mysql.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import logging
  2. from borgmatic.execute import execute_command, execute_command_with_processes
  3. from borgmatic.hooks import dump
  4. logger = logging.getLogger(__name__)
  5. def make_dump_path(location_config): # pragma: no cover
  6. '''
  7. Make the dump path from the given location configuration and the name of this hook.
  8. '''
  9. return dump.make_database_dump_path(
  10. location_config.get('borgmatic_source_directory'), 'mysql_databases'
  11. )
  12. SYSTEM_DATABASE_NAMES = ('information_schema', 'mysql', 'performance_schema', 'sys')
  13. def database_names_to_dump(database, extra_environment, log_prefix, dry_run_label):
  14. '''
  15. Given a requested database name, return the corresponding sequence of database names to dump.
  16. In the case of "all", query for the names of databases on the configured host and return them,
  17. excluding any system databases that will cause problems during restore.
  18. '''
  19. requested_name = database['name']
  20. if requested_name != 'all':
  21. return (requested_name,)
  22. show_command = (
  23. ('mysql',)
  24. + (tuple(database['list_options'].split(' ')) if 'list_options' in database else ())
  25. + (('--host', database['hostname']) if 'hostname' in database else ())
  26. + (('--port', str(database['port'])) if 'port' in database else ())
  27. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  28. + (('--user', database['username']) if 'username' in database else ())
  29. + ('--skip-column-names', '--batch')
  30. + ('--execute', 'show schemas')
  31. )
  32. logger.debug(
  33. '{}: Querying for "all" MySQL databases to dump{}'.format(log_prefix, dry_run_label)
  34. )
  35. show_output = execute_command(
  36. show_command, output_log_level=None, extra_environment=extra_environment
  37. )
  38. return tuple(
  39. show_name
  40. for show_name in show_output.strip().splitlines()
  41. if show_name not in SYSTEM_DATABASE_NAMES
  42. )
  43. def dump_databases(databases, log_prefix, location_config, dry_run):
  44. '''
  45. Dump the given MySQL/MariaDB databases to a named pipe. The databases are supplied as a sequence
  46. of dicts, one dict describing each database as per the configuration schema. Use the given log
  47. prefix in any log entries. Use the given location configuration dict to construct the
  48. destination path.
  49. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  50. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  51. '''
  52. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  53. processes = []
  54. logger.info('{}: Dumping MySQL databases{}'.format(log_prefix, dry_run_label))
  55. for database in databases:
  56. requested_name = database['name']
  57. dump_filename = dump.make_database_dump_filename(
  58. make_dump_path(location_config), requested_name, database.get('hostname')
  59. )
  60. extra_environment = {'MYSQL_PWD': database['password']} if 'password' in database else None
  61. dump_database_names = database_names_to_dump(
  62. database, extra_environment, log_prefix, dry_run_label
  63. )
  64. if not dump_database_names:
  65. raise ValueError('Cannot find any MySQL databases to dump.')
  66. dump_command = (
  67. ('mysqldump',)
  68. + (tuple(database['options'].split(' ')) if 'options' in database else ())
  69. + ('--add-drop-database',)
  70. + (('--host', database['hostname']) if 'hostname' in database else ())
  71. + (('--port', str(database['port'])) if 'port' in database else ())
  72. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  73. + (('--user', database['username']) if 'username' in database else ())
  74. + ('--databases',)
  75. + dump_database_names
  76. # Use shell redirection rather than execute_command(output_file=open(...)) to prevent
  77. # the open() call on a named pipe from hanging the main borgmatic process.
  78. + ('>', dump_filename)
  79. )
  80. logger.debug(
  81. '{}: Dumping MySQL database {} to {}{}'.format(
  82. log_prefix, requested_name, dump_filename, dry_run_label
  83. )
  84. )
  85. if dry_run:
  86. continue
  87. dump.create_named_pipe_for_dump(dump_filename)
  88. processes.append(
  89. execute_command(
  90. dump_command,
  91. shell=True,
  92. extra_environment=extra_environment,
  93. run_to_completion=False,
  94. )
  95. )
  96. return processes
  97. def remove_database_dumps(databases, log_prefix, location_config, dry_run): # pragma: no cover
  98. '''
  99. Remove all database dump files for this hook regardless of the given databases. Use the log
  100. prefix in any log entries. Use the given location configuration dict to construct the
  101. destination path. If this is a dry run, then don't actually remove anything.
  102. '''
  103. dump.remove_database_dumps(make_dump_path(location_config), 'MySQL', log_prefix, dry_run)
  104. def make_database_dump_pattern(
  105. databases, log_prefix, location_config, name=None
  106. ): # pragma: no cover
  107. '''
  108. Given a sequence of configurations dicts, a prefix to log with, a location configuration dict,
  109. and a database name to match, return the corresponding glob patterns to match the database dump
  110. in an archive.
  111. '''
  112. return dump.make_database_dump_filename(make_dump_path(location_config), name, hostname='*')
  113. def restore_database_dump(database_config, log_prefix, location_config, dry_run, extract_process):
  114. '''
  115. Restore the given MySQL/MariaDB database from an extract stream. The database is supplied as a
  116. one-element sequence containing a dict describing the database, as per the configuration schema.
  117. Use the given log prefix in any log entries. If this is a dry run, then don't actually restore
  118. anything. Trigger the given active extract process (an instance of subprocess.Popen) to produce
  119. output to consume.
  120. '''
  121. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  122. if len(database_config) != 1:
  123. raise ValueError('The database configuration value is invalid')
  124. database = database_config[0]
  125. restore_command = (
  126. ('mysql', '--batch')
  127. + (('--host', database['hostname']) if 'hostname' in database else ())
  128. + (('--port', str(database['port'])) if 'port' in database else ())
  129. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  130. + (('--user', database['username']) if 'username' in database else ())
  131. )
  132. extra_environment = {'MYSQL_PWD': database['password']} if 'password' in database else None
  133. logger.debug(
  134. '{}: Restoring MySQL database {}{}'.format(log_prefix, database['name'], dry_run_label)
  135. )
  136. if dry_run:
  137. return
  138. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  139. # if the restore paths don't exist in the archive.
  140. execute_command_with_processes(
  141. restore_command,
  142. [extract_process],
  143. output_log_level=logging.DEBUG,
  144. input_file=extract_process.stdout,
  145. extra_environment=extra_environment,
  146. )