mariadb.py 11 KB

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