mariadb.py 11 KB

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