mysql.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. + (('--host', database['hostname']) if 'hostname' in database else ())
  25. + (('--port', str(database['port'])) if 'port' in database else ())
  26. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  27. + (('--user', database['username']) if 'username' in database else ())
  28. + ('--skip-column-names', '--batch')
  29. + ('--execute', 'show schemas')
  30. )
  31. logger.debug(
  32. '{}: Querying for "all" MySQL databases to dump{}'.format(log_prefix, dry_run_label)
  33. )
  34. show_output = execute_command(
  35. show_command, output_log_level=None, extra_environment=extra_environment
  36. )
  37. return tuple(
  38. show_name
  39. for show_name in show_output.strip().splitlines()
  40. if show_name not in SYSTEM_DATABASE_NAMES
  41. )
  42. def dump_databases(databases, log_prefix, location_config, dry_run):
  43. '''
  44. Dump the given MySQL/MariaDB databases to a named pipe. The databases are supplied as a sequence
  45. of dicts, one dict describing each database as per the configuration schema. Use the given log
  46. prefix in any log entries. Use the given location configuration dict to construct the
  47. destination path.
  48. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  49. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  50. '''
  51. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  52. processes = []
  53. logger.info('{}: Dumping MySQL databases{}'.format(log_prefix, dry_run_label))
  54. for database in databases:
  55. requested_name = database['name']
  56. dump_filename = dump.make_database_dump_filename(
  57. make_dump_path(location_config), requested_name, database.get('hostname')
  58. )
  59. extra_environment = {'MYSQL_PWD': database['password']} if 'password' in database else None
  60. dump_command_names = database_names_to_dump(
  61. database, extra_environment, log_prefix, dry_run_label
  62. )
  63. dump_command = (
  64. ('mysqldump',)
  65. + ('--add-drop-database',)
  66. + (('--host', database['hostname']) if 'hostname' in database else ())
  67. + (('--port', str(database['port'])) if 'port' in database else ())
  68. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  69. + (('--user', database['username']) if 'username' in database else ())
  70. + (tuple(database['options'].split(' ')) if 'options' in database else ())
  71. + ('--databases',)
  72. + dump_command_names
  73. # Use shell redirection rather than execute_command(output_file=open(...)) to prevent
  74. # the open() call on a named pipe from hanging the main borgmatic process.
  75. + ('>', dump_filename)
  76. )
  77. logger.debug(
  78. '{}: Dumping MySQL database {} to {}{}'.format(
  79. log_prefix, requested_name, dump_filename, dry_run_label
  80. )
  81. )
  82. if dry_run:
  83. continue
  84. dump.create_named_pipe_for_dump(dump_filename)
  85. processes.append(
  86. execute_command(
  87. dump_command,
  88. shell=True,
  89. extra_environment=extra_environment,
  90. run_to_completion=False,
  91. )
  92. )
  93. return processes
  94. def remove_database_dumps(databases, log_prefix, location_config, dry_run): # pragma: no cover
  95. '''
  96. Remove the database dumps for the given databases. The databases are supplied as a sequence of
  97. dicts, one dict describing each database as per the configuration schema. Use the log prefix in
  98. any log entries. Use the given location configuration dict to construct the destination path. If
  99. this is a dry run, then don't actually remove anything.
  100. '''
  101. dump.remove_database_dumps(
  102. make_dump_path(location_config), databases, 'MySQL', log_prefix, dry_run
  103. )
  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', '--verbose')
  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. execute_command_with_processes(
  139. restore_command,
  140. [extract_process],
  141. output_log_level=logging.DEBUG,
  142. input_file=extract_process.stdout,
  143. extra_environment=extra_environment,
  144. borg_local_path=location_config.get('local_path', 'borg'),
  145. )