mariadb.py 15 KB

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