mariadb.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import copy
  2. import logging
  3. import os
  4. import re
  5. import shlex
  6. import borgmatic.borg.pattern
  7. import borgmatic.config.paths
  8. import borgmatic.hooks.credential.parse
  9. from borgmatic.execute import (
  10. execute_command,
  11. execute_command_and_capture_output,
  12. execute_command_with_processes,
  13. )
  14. from borgmatic.hooks.data_source import dump
  15. logger = logging.getLogger(__name__)
  16. def make_dump_path(base_directory): # pragma: no cover
  17. '''
  18. Given a base directory, make the corresponding dump path.
  19. '''
  20. return dump.make_data_source_dump_path(base_directory, 'mariadb_databases')
  21. DEFAULTS_EXTRA_FILE_FLAG_PATTERN = re.compile('^--defaults-extra-file=(?P<filename>.*)$')
  22. def parse_extra_options(extra_options):
  23. '''
  24. Given an extra options string, split the options into a tuple and return it. Additionally, if
  25. the first option is "--defaults-extra-file=...", then remove it from the options and return the
  26. filename.
  27. So the return value is a tuple of: (parsed options, defaults extra filename).
  28. The intent is to support downstream merging of multiple "--defaults-extra-file"s, as
  29. MariaDB/MySQL only allows one at a time.
  30. '''
  31. split_extra_options = tuple(shlex.split(extra_options)) if extra_options else ()
  32. if not split_extra_options:
  33. return ((), None)
  34. match = DEFAULTS_EXTRA_FILE_FLAG_PATTERN.match(split_extra_options[0])
  35. if not match:
  36. return (split_extra_options, None)
  37. return (split_extra_options[1:], match.group('filename'))
  38. def make_defaults_file_options(username=None, password=None, defaults_extra_filename=None):
  39. '''
  40. Given a database username and/or password, write it to an anonymous pipe and return the flags
  41. for passing that file descriptor to an executed command. The idea is that this is a more secure
  42. way to transmit credentials to a database client than using an environment variable.
  43. If no username or password are given, then return the options for the given defaults extra
  44. filename (if any). But if there is a username and/or password and a defaults extra filename is
  45. given, then "!include" it from the generated file, effectively allowing multiple defaults extra
  46. files.
  47. Do not use the returned value for multiple different command invocations. That will not work
  48. because each pipe is "used up" once read.
  49. '''
  50. escaped_password = None if password is None else password.replace('\\', '\\\\')
  51. values = '\n'.join(
  52. (
  53. (f'user={username}' if username is not None else ''),
  54. (f'password="{escaped_password}"' if escaped_password is not None else ''),
  55. )
  56. ).strip()
  57. if not values:
  58. if defaults_extra_filename:
  59. return (f'--defaults-extra-file={defaults_extra_filename}',)
  60. return ()
  61. fields_message = ' and '.join(
  62. field_name
  63. for field_name in (
  64. (f'username ({username})' if username is not None else None),
  65. ('password' if password is not None else None),
  66. )
  67. if field_name is not None
  68. )
  69. include_message = f' (including {defaults_extra_filename})' if defaults_extra_filename else ''
  70. logger.debug(f'Writing database {fields_message} to defaults extra file pipe{include_message}')
  71. include = f'!include {defaults_extra_filename}\n' if defaults_extra_filename else ''
  72. read_file_descriptor, write_file_descriptor = os.pipe()
  73. os.write(write_file_descriptor, f'{include}[client]\n{values}'.encode('utf-8'))
  74. os.close(write_file_descriptor)
  75. # This plus subprocess.Popen(..., close_fds=False) in execute.py is necessary for the database
  76. # client child process to inherit the file descriptor.
  77. os.set_inheritable(read_file_descriptor, True)
  78. return (f'--defaults-extra-file=/dev/fd/{read_file_descriptor}',)
  79. def database_names_to_dump(database, config, username, password, environment, dry_run):
  80. '''
  81. Given a requested database config, a configuration dict, a database username and password, an
  82. environment dict, and whether this is a dry run, return the corresponding sequence of database
  83. names to dump. In the case of "all", query for the names of databases on the configured host and
  84. return them, excluding any system databases that will cause problems during restore.
  85. '''
  86. if database['name'] != 'all':
  87. return (database['name'],)
  88. if dry_run:
  89. return ()
  90. mariadb_show_command = tuple(
  91. shlex.quote(part) for part in shlex.split(database.get('mariadb_command') or 'mariadb')
  92. )
  93. extra_options, defaults_extra_filename = parse_extra_options(database.get('list_options'))
  94. password_transport = config.get('password_transport', 'pipe')
  95. show_command = (
  96. mariadb_show_command
  97. + (make_defaults_file_options(username, password, defaults_extra_filename) if password_transport == 'pipe' else ())
  98. + extra_options
  99. + (('--host', database['hostname']) if 'hostname' in database else ())
  100. + (('--port', str(database['port'])) if 'port' in database else ())
  101. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  102. + (('--user', username) if username and password_transport == 'environment' else ())
  103. + (('--ssl',) if database.get('tls') is True else ())
  104. + (('--skip-ssl',) if database.get('tls') is False else ())
  105. + ('--skip-column-names', '--batch')
  106. + ('--execute', 'show schemas')
  107. )
  108. logger.debug('Querying for "all" MariaDB databases to dump')
  109. show_output = execute_command_and_capture_output(show_command, environment=environment)
  110. return tuple(
  111. show_name
  112. for show_name in show_output.strip().splitlines()
  113. if show_name not in SYSTEM_DATABASE_NAMES
  114. )
  115. SYSTEM_DATABASE_NAMES = ('information_schema', 'mysql', 'performance_schema', 'sys')
  116. def execute_dump_command(
  117. database,
  118. config,
  119. username,
  120. password,
  121. dump_path,
  122. database_names,
  123. environment,
  124. dry_run,
  125. dry_run_label,
  126. ):
  127. '''
  128. Kick off a dump for the given MariaDB database (provided as a configuration dict) to a named
  129. pipe constructed from the given dump path and database name.
  130. Return a subprocess.Popen instance for the dump process ready to spew to a named pipe. But if
  131. this is a dry run, then don't actually dump anything and return None.
  132. '''
  133. database_name = database['name']
  134. dump_filename = dump.make_data_source_dump_filename(
  135. dump_path,
  136. database['name'],
  137. database.get('hostname'),
  138. database.get('port'),
  139. )
  140. if os.path.exists(dump_filename):
  141. logger.warning(
  142. f'Skipping duplicate dump of MariaDB database "{database_name}" to {dump_filename}'
  143. )
  144. return None
  145. mariadb_dump_command = tuple(
  146. shlex.quote(part)
  147. for part in shlex.split(database.get('mariadb_dump_command') or 'mariadb-dump')
  148. )
  149. extra_options, defaults_extra_filename = parse_extra_options(database.get('options'))
  150. password_transport = config.get('password_transport', 'pipe')
  151. dump_command = (
  152. mariadb_dump_command
  153. + (make_defaults_file_options(username, password, defaults_extra_filename) if password_transport == 'pipe' else ())
  154. + extra_options
  155. + (('--add-drop-database',) if database.get('add_drop_database', True) else ())
  156. + (('--host', database['hostname']) if 'hostname' in database else ())
  157. + (('--port', str(database['port'])) if 'port' in database else ())
  158. + (('--protocol', 'tcp') if 'hostname' in database or 'port' in database else ())
  159. + (('--user', username) if username and password_transport == 'environment' else ())
  160. + (('--ssl',) if database.get('tls') is True else ())
  161. + (('--skip-ssl',) if database.get('tls') is False else ())
  162. + ('--databases',)
  163. + database_names
  164. + ('--result-file', dump_filename)
  165. )
  166. logger.debug(f'Dumping MariaDB database "{database_name}" to {dump_filename}{dry_run_label}')
  167. if dry_run:
  168. return None
  169. dump.create_named_pipe_for_dump(dump_filename)
  170. return execute_command(
  171. dump_command,
  172. environment=environment,
  173. run_to_completion=False,
  174. )
  175. def get_default_port(databases, config): # pragma: no cover
  176. return 3306
  177. def use_streaming(databases, config):
  178. '''
  179. Given a sequence of MariaDB database configuration dicts, a configuration dict (ignored), return
  180. whether streaming will be using during dumps.
  181. '''
  182. return any(databases)
  183. def dump_data_sources(
  184. databases,
  185. config,
  186. config_paths,
  187. borgmatic_runtime_directory,
  188. patterns,
  189. dry_run,
  190. ):
  191. '''
  192. Dump the given MariaDB databases to a named pipe. The databases are supplied as a sequence of
  193. dicts, one dict describing each database as per the configuration schema. Use the given
  194. borgmatic runtime directory to construct the destination path.
  195. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  196. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  197. Also append the the parent directory of the database dumps to the given patterns list, so the
  198. dumps actually get backed up.
  199. '''
  200. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  201. processes = []
  202. logger.info(f'Dumping MariaDB databases{dry_run_label}')
  203. for database in databases:
  204. dump_path = make_dump_path(borgmatic_runtime_directory)
  205. username = borgmatic.hooks.credential.parse.resolve_credential(
  206. database.get('username'), config
  207. )
  208. password = borgmatic.hooks.credential.parse.resolve_credential(
  209. database.get('password'), config
  210. )
  211. environment = dict(os.environ, **({'MYSQL_PWD': password} if password and config.get('password_transport') == 'environment' else {}))
  212. dump_database_names = database_names_to_dump(
  213. database, config, username, password, environment, dry_run
  214. )
  215. if not dump_database_names:
  216. if dry_run:
  217. continue
  218. raise ValueError('Cannot find any MariaDB databases to dump.')
  219. if database['name'] == 'all' and database.get('format'):
  220. for dump_name in dump_database_names:
  221. renamed_database = copy.copy(database)
  222. renamed_database['name'] = dump_name
  223. processes.append(
  224. execute_dump_command(
  225. renamed_database,
  226. config,
  227. username,
  228. password,
  229. dump_path,
  230. (dump_name,),
  231. environment,
  232. dry_run,
  233. dry_run_label,
  234. )
  235. )
  236. else:
  237. processes.append(
  238. execute_dump_command(
  239. database,
  240. config,
  241. username,
  242. password,
  243. dump_path,
  244. dump_database_names,
  245. environment,
  246. dry_run,
  247. dry_run_label,
  248. )
  249. )
  250. if not dry_run:
  251. patterns.append(
  252. borgmatic.borg.pattern.Pattern(
  253. os.path.join(borgmatic_runtime_directory, 'mariadb_databases'),
  254. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  255. )
  256. )
  257. return [process for process in processes if process]
  258. def remove_data_source_dumps(
  259. databases, config, borgmatic_runtime_directory, dry_run
  260. ): # pragma: no cover
  261. '''
  262. Remove all database dump files for this hook regardless of the given databases. Use the
  263. borgmatic_runtime_directory to construct the destination path. If this is a dry run, then don't
  264. actually remove anything.
  265. '''
  266. dump.remove_data_source_dumps(make_dump_path(borgmatic_runtime_directory), 'MariaDB', dry_run)
  267. def make_data_source_dump_patterns(
  268. databases, config, borgmatic_runtime_directory, name=None
  269. ): # pragma: no cover
  270. '''
  271. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  272. and a database name to match, return the corresponding glob patterns to match the database dump
  273. in an archive.
  274. '''
  275. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  276. return (
  277. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  278. dump.make_data_source_dump_filename(
  279. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  280. ),
  281. dump.make_data_source_dump_filename(
  282. make_dump_path(borgmatic_source_directory), name, hostname='*'
  283. ),
  284. )
  285. def restore_data_source_dump(
  286. hook_config,
  287. config,
  288. data_source,
  289. dry_run,
  290. extract_process,
  291. connection_params,
  292. borgmatic_runtime_directory,
  293. ):
  294. '''
  295. Restore a database from the given extract stream. The database is supplied as a data source
  296. configuration dict, but the given hook configuration is ignored. If this is a dry run, then
  297. don't actually restore anything. Trigger the given active extract process (an instance of
  298. subprocess.Popen) to produce output to consume.
  299. '''
  300. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  301. hostname = connection_params['hostname'] or data_source.get(
  302. 'restore_hostname', data_source.get('hostname')
  303. )
  304. port = str(
  305. connection_params['port'] or data_source.get('restore_port', data_source.get('port', ''))
  306. )
  307. tls = data_source.get('restore_tls', data_source.get('tls'))
  308. username = borgmatic.hooks.credential.parse.resolve_credential(
  309. (
  310. connection_params['username']
  311. or data_source.get('restore_username', data_source.get('username'))
  312. ),
  313. config,
  314. )
  315. password = borgmatic.hooks.credential.parse.resolve_credential(
  316. (
  317. connection_params['password']
  318. or data_source.get('restore_password', data_source.get('password'))
  319. ),
  320. config,
  321. )
  322. mariadb_restore_command = tuple(
  323. shlex.quote(part) for part in shlex.split(data_source.get('mariadb_command') or 'mariadb')
  324. )
  325. extra_options, defaults_extra_filename = parse_extra_options(data_source.get('restore_options'))
  326. password_transport = config.get('password_transport', 'pipe')
  327. restore_command = (
  328. mariadb_restore_command
  329. + (make_defaults_file_options(username, password, defaults_extra_filename) if password_transport == 'pipe' else ())
  330. + extra_options
  331. + ('--batch',)
  332. + (('--host', hostname) if hostname else ())
  333. + (('--port', str(port)) if port else ())
  334. + (('--protocol', 'tcp') if hostname or port else ())
  335. + (('--user', username) if username and password_transport == 'environment' else ())
  336. + (('--ssl',) if tls is True else ())
  337. + (('--skip-ssl',) if tls is False else ())
  338. )
  339. environment = dict(os.environ, **({'MYSQL_PWD': password} if password and password_transport == 'environment' else {}))
  340. logger.debug(f"Restoring MariaDB database {data_source['name']}{dry_run_label}")
  341. if dry_run:
  342. return
  343. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  344. # if the restore paths don't exist in the archive.
  345. execute_command_with_processes(
  346. restore_command,
  347. [extract_process],
  348. output_log_level=logging.DEBUG,
  349. input_file=extract_process.stdout,
  350. environment=environment,
  351. )