mariadb.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import copy
  2. import logging
  3. import os
  4. import shlex
  5. import borgmatic.borg.pattern
  6. import borgmatic.config.paths
  7. from borgmatic.execute import (
  8. execute_command,
  9. execute_command_and_capture_output,
  10. execute_command_with_processes,
  11. )
  12. from borgmatic.hooks.data_source import dump
  13. logger = logging.getLogger(__name__)
  14. def make_dump_path(base_directory): # pragma: no cover
  15. '''
  16. Given a base directory, make the corresponding dump path.
  17. '''
  18. return dump.make_data_source_dump_path(base_directory, 'mariadb_databases')
  19. SYSTEM_DATABASE_NAMES = ('information_schema', 'mysql', 'performance_schema', 'sys')
  20. def database_names_to_dump(database, extra_environment, 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'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, 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.
  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,
  64. database['name'],
  65. database.get('hostname'),
  66. database.get('port'),
  67. )
  68. if os.path.exists(dump_filename):
  69. logger.warning(
  70. f'Skipping duplicate dump of MariaDB database "{database_name}" to {dump_filename}'
  71. )
  72. return None
  73. mariadb_dump_command = tuple(
  74. shlex.quote(part)
  75. for part in shlex.split(database.get('mariadb_dump_command') or 'mariadb-dump')
  76. )
  77. dump_command = (
  78. mariadb_dump_command
  79. + (tuple(database['options'].split(' ')) if 'options' in database else ())
  80. + (('--add-drop-database',) if database.get('add_drop_database', True) else ())
  81. + (('--host', database['hostname']) if 'hostname' in database else ())
  82. + (('--port', str(database['port'])) if 'port' in database else ())
  83. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  84. + (('--user', database['username']) if 'username' in database else ())
  85. + ('--databases',)
  86. + database_names
  87. + ('--result-file', dump_filename)
  88. )
  89. logger.debug(
  90. f'Dumping MariaDB database "{database_name}" to {dump_filename}{dry_run_label}'
  91. )
  92. if dry_run:
  93. return None
  94. dump.create_named_pipe_for_dump(dump_filename)
  95. return execute_command(
  96. dump_command,
  97. extra_environment=extra_environment,
  98. run_to_completion=False,
  99. )
  100. def get_default_port(databases, config): # pragma: no cover
  101. return 3306
  102. def use_streaming(databases, config):
  103. '''
  104. Given a sequence of MariaDB database configuration dicts, a configuration dict (ignored), return
  105. whether streaming will be using during dumps.
  106. '''
  107. return any(databases)
  108. def dump_data_sources(
  109. databases,
  110. config,
  111. config_paths,
  112. borgmatic_runtime_directory,
  113. patterns,
  114. dry_run,
  115. ):
  116. '''
  117. Dump the given MariaDB databases to a named pipe. The databases are supplied as a sequence of
  118. dicts, one dict describing each database as per the configuration schema. Use the given
  119. borgmatic runtime directory to construct the destination path.
  120. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  121. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  122. Also append the the parent directory of the database dumps to the given patterns list, so the
  123. dumps actually get backed up.
  124. '''
  125. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  126. processes = []
  127. logger.info(f'Dumping MariaDB databases{dry_run_label}')
  128. for database in databases:
  129. dump_path = make_dump_path(borgmatic_runtime_directory)
  130. extra_environment = {'MYSQL_PWD': database['password']} if 'password' in database else None
  131. dump_database_names = database_names_to_dump(
  132. database, extra_environment, dry_run
  133. )
  134. if not dump_database_names:
  135. if dry_run:
  136. continue
  137. raise ValueError('Cannot find any MariaDB databases to dump.')
  138. if database['name'] == 'all' and database.get('format'):
  139. for dump_name in dump_database_names:
  140. renamed_database = copy.copy(database)
  141. renamed_database['name'] = dump_name
  142. processes.append(
  143. execute_dump_command(
  144. renamed_database,
  145. dump_path,
  146. (dump_name,),
  147. extra_environment,
  148. dry_run,
  149. dry_run_label,
  150. )
  151. )
  152. else:
  153. processes.append(
  154. execute_dump_command(
  155. database,
  156. dump_path,
  157. dump_database_names,
  158. extra_environment,
  159. dry_run,
  160. dry_run_label,
  161. )
  162. )
  163. if not dry_run:
  164. patterns.append(
  165. borgmatic.borg.pattern.Pattern(
  166. os.path.join(borgmatic_runtime_directory, 'mariadb_databases')
  167. )
  168. )
  169. return [process for process in processes if process]
  170. def remove_data_source_dumps(
  171. databases, config, borgmatic_runtime_directory, dry_run
  172. ): # pragma: no cover
  173. '''
  174. Remove all database dump files for this hook regardless of the given databases. Use the
  175. borgmatic_runtime_directory to construct the destination path. If this is a dry run, then don't
  176. actually remove anything.
  177. '''
  178. dump.remove_data_source_dumps(
  179. make_dump_path(borgmatic_runtime_directory), 'MariaDB', dry_run
  180. )
  181. def make_data_source_dump_patterns(
  182. databases, config, borgmatic_runtime_directory, name=None
  183. ): # pragma: no cover
  184. '''
  185. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  186. and a database name to match, return the corresponding glob patterns to match the database dump
  187. in an archive.
  188. '''
  189. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  190. return (
  191. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  192. dump.make_data_source_dump_filename(
  193. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  194. ),
  195. dump.make_data_source_dump_filename(
  196. make_dump_path(borgmatic_source_directory), name, hostname='*'
  197. ),
  198. )
  199. def restore_data_source_dump(
  200. hook_config,
  201. config,
  202. data_source,
  203. dry_run,
  204. extract_process,
  205. connection_params,
  206. borgmatic_runtime_directory,
  207. ):
  208. '''
  209. Restore a database from the given extract stream. The database is supplied as a data source
  210. configuration dict, but the given hook configuration is ignored. If this is a dry run, then
  211. don't actually restore anything. Trigger the given active extract process (an instance of
  212. subprocess.Popen) to produce output to consume.
  213. '''
  214. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  215. hostname = connection_params['hostname'] or data_source.get(
  216. 'restore_hostname', data_source.get('hostname')
  217. )
  218. port = str(
  219. connection_params['port'] or data_source.get('restore_port', data_source.get('port', ''))
  220. )
  221. username = connection_params['username'] or data_source.get(
  222. 'restore_username', data_source.get('username')
  223. )
  224. password = connection_params['password'] or data_source.get(
  225. 'restore_password', data_source.get('password')
  226. )
  227. mariadb_restore_command = tuple(
  228. shlex.quote(part) for part in shlex.split(data_source.get('mariadb_command') or 'mariadb')
  229. )
  230. restore_command = (
  231. mariadb_restore_command
  232. + ('--batch',)
  233. + (
  234. tuple(data_source['restore_options'].split(' '))
  235. if 'restore_options' in data_source
  236. else ()
  237. )
  238. + (('--host', hostname) if hostname else ())
  239. + (('--port', str(port)) if port else ())
  240. + (('--protocol', 'tcp') if hostname or port else ())
  241. + (('--user', username) if username else ())
  242. )
  243. extra_environment = {'MYSQL_PWD': password} if password else None
  244. logger.debug(f"Restoring MariaDB database {data_source['name']}{dry_run_label}")
  245. if dry_run:
  246. return
  247. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  248. # if the restore paths don't exist in the archive.
  249. execute_command_with_processes(
  250. restore_command,
  251. [extract_process],
  252. output_log_level=logging.DEBUG,
  253. input_file=extract_process.stdout,
  254. extra_environment=extra_environment,
  255. )