mariadb.py 18 KB

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