2
0

mariadb.py 17 KB

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