mysql.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import copy
  2. import logging
  3. import os
  4. import shlex
  5. import borgmatic.borg.pattern
  6. import borgmatic.config.paths
  7. import borgmatic.hooks.command
  8. import borgmatic.hooks.credential.parse
  9. import borgmatic.hooks.data_source.mariadb
  10. from borgmatic.execute import (
  11. execute_command,
  12. execute_command_and_capture_output,
  13. execute_command_with_processes,
  14. )
  15. from borgmatic.hooks.data_source import dump
  16. logger = logging.getLogger(__name__)
  17. def make_dump_path(base_directory): # pragma: no cover
  18. '''
  19. Given a base directory, make the corresponding dump path.
  20. '''
  21. return dump.make_data_source_dump_path(base_directory, 'mysql_databases')
  22. SYSTEM_DATABASE_NAMES = ('information_schema', 'mysql', 'performance_schema', 'sys')
  23. def database_names_to_dump(database, config, username, password, environment, dry_run):
  24. '''
  25. Given a requested database config, a configuration dict, a database username and password, an
  26. environment dict, and whether this is a dry run, return the corresponding sequence of database
  27. names to dump. In the case of "all", query for the names of databases on the configured host and
  28. return them, excluding any system databases that will cause problems during restore.
  29. '''
  30. if database['name'] != 'all':
  31. return (database['name'],)
  32. if dry_run:
  33. return ()
  34. mysql_show_command = tuple(
  35. shlex.quote(part) for part in shlex.split(database.get('mysql_command') or 'mysql')
  36. )
  37. extra_options, defaults_extra_filename = (
  38. borgmatic.hooks.data_source.mariadb.parse_extra_options(database.get('list_options'))
  39. )
  40. show_command = (
  41. mysql_show_command
  42. + borgmatic.hooks.data_source.mariadb.make_defaults_file_options(
  43. username, password, defaults_extra_filename
  44. )
  45. + extra_options
  46. + (('--host', database['hostname']) if 'hostname' in database else ())
  47. + (('--port', str(database['port'])) if 'port' in database else ())
  48. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  49. + (('--ssl',) if database.get('tls') is True else ())
  50. + (('--skip-ssl',) if database.get('tls') is False else ())
  51. + ('--skip-column-names', '--batch')
  52. + ('--execute', 'show schemas')
  53. )
  54. logger.debug('Querying for "all" MySQL databases to dump')
  55. show_output = execute_command_and_capture_output(show_command, environment=environment)
  56. return tuple(
  57. show_name
  58. for show_name in show_output.strip().splitlines()
  59. if show_name not in SYSTEM_DATABASE_NAMES
  60. )
  61. def execute_dump_command(
  62. database,
  63. config,
  64. username,
  65. password,
  66. dump_path,
  67. database_names,
  68. environment,
  69. dry_run,
  70. dry_run_label,
  71. ):
  72. '''
  73. Kick off a dump for the given MySQL/MariaDB database (provided as a configuration dict) to a
  74. named pipe constructed from the given dump path and database name.
  75. Return a subprocess.Popen instance for the dump process ready to spew to a named pipe. But if
  76. this is a dry run, then don't actually dump anything and return None.
  77. '''
  78. database_name = database['name']
  79. dump_filename = dump.make_data_source_dump_filename(
  80. dump_path,
  81. database['name'],
  82. database.get('hostname'),
  83. database.get('port'),
  84. )
  85. if os.path.exists(dump_filename):
  86. logger.warning(
  87. f'Skipping duplicate dump of MySQL database "{database_name}" to {dump_filename}'
  88. )
  89. return None
  90. mysql_dump_command = tuple(
  91. shlex.quote(part) for part in shlex.split(database.get('mysql_dump_command') or 'mysqldump')
  92. )
  93. extra_options, defaults_extra_filename = (
  94. borgmatic.hooks.data_source.mariadb.parse_extra_options(database.get('options'))
  95. )
  96. dump_command = (
  97. mysql_dump_command
  98. + borgmatic.hooks.data_source.mariadb.make_defaults_file_options(
  99. username, password, defaults_extra_filename
  100. )
  101. + extra_options
  102. + (('--add-drop-database',) if database.get('add_drop_database', True) else ())
  103. + (('--host', database['hostname']) if 'hostname' in database else ())
  104. + (('--port', str(database['port'])) if 'port' in database else ())
  105. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  106. + (('--ssl',) if database.get('tls') is True else ())
  107. + (('--skip-ssl',) if database.get('tls') is False else ())
  108. + ('--databases',)
  109. + database_names
  110. + ('--result-file', dump_filename)
  111. )
  112. logger.debug(f'Dumping MySQL database "{database_name}" to {dump_filename}{dry_run_label}')
  113. if dry_run:
  114. return None
  115. dump.create_named_pipe_for_dump(dump_filename)
  116. return execute_command(
  117. dump_command,
  118. environment=environment,
  119. run_to_completion=False,
  120. )
  121. def get_default_port(databases, config): # pragma: no cover
  122. return 3306
  123. def use_streaming(databases, config):
  124. '''
  125. Given a sequence of MySQL database configuration dicts, a configuration dict (ignored), return
  126. whether streaming will be using during dumps.
  127. '''
  128. return any(databases)
  129. def dump_data_sources(
  130. databases,
  131. config,
  132. config_paths,
  133. borgmatic_runtime_directory,
  134. patterns,
  135. dry_run,
  136. ):
  137. '''
  138. Dump the given MySQL/MariaDB databases to a named pipe. The databases are supplied as a sequence
  139. of dicts, one dict describing each database as per the configuration schema. Use the given
  140. borgmatic runtime directory to construct the destination path.
  141. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  142. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  143. Also append the the parent directory of the database dumps to the given patterns list, so the
  144. dumps actually get backed up.
  145. '''
  146. with borgmatic.hooks.command.Before_after_hooks(
  147. command_hooks=config.get('commands'),
  148. before_after='dump_data_sources',
  149. hook_name='mysql',
  150. umask=config.get('umask'),
  151. dry_run=dry_run,
  152. ):
  153. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  154. processes = []
  155. logger.info(f'Dumping MySQL databases{dry_run_label}')
  156. for database in databases:
  157. dump_path = make_dump_path(borgmatic_runtime_directory)
  158. username = borgmatic.hooks.credential.parse.resolve_credential(
  159. database.get('username'), config
  160. )
  161. password = borgmatic.hooks.credential.parse.resolve_credential(
  162. database.get('password'), config
  163. )
  164. environment = dict(os.environ)
  165. dump_database_names = database_names_to_dump(
  166. database, config, username, password, environment, dry_run
  167. )
  168. if not dump_database_names:
  169. if dry_run:
  170. continue
  171. raise ValueError('Cannot find any MySQL databases to dump.')
  172. if database['name'] == 'all' and database.get('format'):
  173. for dump_name in dump_database_names:
  174. renamed_database = copy.copy(database)
  175. renamed_database['name'] = dump_name
  176. processes.append(
  177. execute_dump_command(
  178. renamed_database,
  179. config,
  180. username,
  181. password,
  182. dump_path,
  183. (dump_name,),
  184. environment,
  185. dry_run,
  186. dry_run_label,
  187. )
  188. )
  189. else:
  190. processes.append(
  191. execute_dump_command(
  192. database,
  193. config,
  194. username,
  195. password,
  196. dump_path,
  197. dump_database_names,
  198. environment,
  199. dry_run,
  200. dry_run_label,
  201. )
  202. )
  203. if not dry_run:
  204. patterns.append(
  205. borgmatic.borg.pattern.Pattern(
  206. os.path.join(borgmatic_runtime_directory, 'mysql_databases'),
  207. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  208. )
  209. )
  210. return [process for process in processes if process]
  211. def remove_data_source_dumps(
  212. databases, config, borgmatic_runtime_directory, dry_run
  213. ): # pragma: no cover
  214. '''
  215. Remove all database dump files for this hook regardless of the given databases. Use the
  216. borgmatic runtime directory to construct the destination path. If this is a dry run, then don't
  217. actually remove anything.
  218. '''
  219. dump.remove_data_source_dumps(make_dump_path(borgmatic_runtime_directory), 'MySQL', dry_run)
  220. def make_data_source_dump_patterns(
  221. databases, config, borgmatic_runtime_directory, name=None
  222. ): # pragma: no cover
  223. '''
  224. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  225. and a database name to match, return the corresponding glob patterns to match the database dump
  226. in an archive.
  227. '''
  228. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  229. return (
  230. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  231. dump.make_data_source_dump_filename(
  232. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  233. ),
  234. dump.make_data_source_dump_filename(
  235. make_dump_path(borgmatic_source_directory), name, hostname='*'
  236. ),
  237. )
  238. def restore_data_source_dump(
  239. hook_config,
  240. config,
  241. data_source,
  242. dry_run,
  243. extract_process,
  244. connection_params,
  245. borgmatic_runtime_directory,
  246. ):
  247. '''
  248. Restore a database from the given extract stream. The database is supplied as a data source
  249. configuration dict, but the given hook configuration is ignored. If this is a dry run, then
  250. don't actually restore anything. Trigger the given active extract process (an instance of
  251. subprocess.Popen) to produce output to consume.
  252. '''
  253. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  254. hostname = connection_params['hostname'] or data_source.get(
  255. 'restore_hostname', data_source.get('hostname')
  256. )
  257. port = str(
  258. connection_params['port'] or data_source.get('restore_port', data_source.get('port', ''))
  259. )
  260. tls = data_source.get('restore_tls', data_source.get('tls'))
  261. username = borgmatic.hooks.credential.parse.resolve_credential(
  262. (
  263. connection_params['username']
  264. or data_source.get('restore_username', data_source.get('username'))
  265. ),
  266. config,
  267. )
  268. password = borgmatic.hooks.credential.parse.resolve_credential(
  269. (
  270. connection_params['password']
  271. or data_source.get('restore_password', data_source.get('password'))
  272. ),
  273. config,
  274. )
  275. mysql_restore_command = tuple(
  276. shlex.quote(part) for part in shlex.split(data_source.get('mysql_command') or 'mysql')
  277. )
  278. extra_options, defaults_extra_filename = (
  279. borgmatic.hooks.data_source.mariadb.parse_extra_options(data_source.get('restore_options'))
  280. )
  281. restore_command = (
  282. mysql_restore_command
  283. + borgmatic.hooks.data_source.mariadb.make_defaults_file_options(
  284. username, password, defaults_extra_filename
  285. )
  286. + extra_options
  287. + ('--batch',)
  288. + (('--host', hostname) if hostname else ())
  289. + (('--port', str(port)) if port else ())
  290. + (('--protocol', 'tcp') if hostname or port else ())
  291. + (('--ssl',) if tls is True else ())
  292. + (('--skip-ssl',) if tls is False else ())
  293. )
  294. environment = dict(os.environ)
  295. logger.debug(f"Restoring MySQL database {data_source['name']}{dry_run_label}")
  296. if dry_run:
  297. return
  298. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  299. # if the restore paths don't exist in the archive.
  300. execute_command_with_processes(
  301. restore_command,
  302. [extract_process],
  303. output_log_level=logging.DEBUG,
  304. input_file=extract_process.stdout,
  305. environment=environment,
  306. )