postgresql.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import csv
  2. import itertools
  3. import logging
  4. import os
  5. import pathlib
  6. import shlex
  7. import borgmatic.borg.pattern
  8. import borgmatic.config.paths
  9. import borgmatic.hooks.credential.parse
  10. import borgmatic.hooks.data_source.config
  11. from borgmatic.execute import (
  12. execute_command,
  13. execute_command_and_capture_output,
  14. execute_command_with_processes,
  15. )
  16. from borgmatic.hooks.data_source import config as database_config
  17. from borgmatic.hooks.data_source import dump
  18. logger = logging.getLogger(__name__)
  19. def make_dump_path(base_directory): # pragma: no cover
  20. '''
  21. Given a base directory, make the corresponding dump path.
  22. '''
  23. return dump.make_data_source_dump_path(base_directory, 'postgresql_databases')
  24. def make_environment(database, config, restore_connection_params=None):
  25. '''
  26. Make an environment dict from the current environment variables and the given database
  27. configuration. If restore connection params are given, this is for a restore operation.
  28. '''
  29. environment = dict(os.environ)
  30. password = database_config.resolve_database_option(
  31. 'password', database, restore_connection_params, restore=restore_connection_params
  32. )
  33. if password:
  34. environment['PGPASSWORD'] = borgmatic.hooks.credential.parse.resolve_credential(
  35. password,
  36. config,
  37. )
  38. if 'ssl_mode' in database:
  39. environment['PGSSLMODE'] = database['ssl_mode']
  40. if 'ssl_cert' in database:
  41. environment['PGSSLCERT'] = database['ssl_cert']
  42. if 'ssl_key' in database:
  43. environment['PGSSLKEY'] = database['ssl_key']
  44. if 'ssl_root_cert' in database:
  45. environment['PGSSLROOTCERT'] = database['ssl_root_cert']
  46. if 'ssl_crl' in database:
  47. environment['PGSSLCRL'] = database['ssl_crl']
  48. return environment
  49. EXCLUDED_DATABASE_NAMES = ('template0', 'template1')
  50. def database_names_to_dump(database, config, environment, dry_run):
  51. '''
  52. Given a requested database config and a configuration dict, return the corresponding sequence of
  53. database names to dump. In the case of "all" when a database format is given, query for the
  54. names of databases on the configured host and return them. For "all" without a database format,
  55. just return a sequence containing "all".
  56. '''
  57. requested_name = database['name']
  58. if requested_name != 'all':
  59. return (requested_name,)
  60. if not database.get('format'):
  61. return ('all',)
  62. if dry_run:
  63. return ()
  64. psql_command = tuple(
  65. shlex.quote(part) for part in shlex.split(database.get('psql_command') or 'psql')
  66. )
  67. hostname = database_config.resolve_database_option('hostname', database)
  68. list_command = (
  69. psql_command
  70. + ('--list', '--no-password', '--no-psqlrc', '--csv', '--tuples-only')
  71. + (('--host', hostname) if hostname else ())
  72. + (('--port', str(database['port'])) if 'port' in database else ())
  73. + (
  74. (
  75. '--username',
  76. borgmatic.hooks.credential.parse.resolve_credential(database['username'], config),
  77. )
  78. if 'username' in database
  79. else ()
  80. )
  81. + (tuple(database['list_options'].split(' ')) if 'list_options' in database else ())
  82. )
  83. logger.debug('Querying for "all" PostgreSQL databases to dump')
  84. list_output = execute_command_and_capture_output(
  85. list_command,
  86. environment=environment,
  87. working_directory=borgmatic.config.paths.get_working_directory(config),
  88. )
  89. return tuple(
  90. row[0]
  91. for row in csv.reader(list_output.splitlines(), delimiter=',', quotechar='"')
  92. if row[0] not in EXCLUDED_DATABASE_NAMES
  93. )
  94. def get_default_port(databases, config): # pragma: no cover
  95. return 5432
  96. def use_streaming(databases, config):
  97. '''
  98. Given a sequence of PostgreSQL database configuration dicts, a configuration dict (ignored),
  99. return whether streaming will be using during dumps.
  100. '''
  101. return any(database.get('format') != 'directory' for database in databases)
  102. def dump_data_sources(
  103. databases,
  104. config,
  105. config_paths,
  106. borgmatic_runtime_directory,
  107. patterns,
  108. dry_run,
  109. ):
  110. '''
  111. Dump the given PostgreSQL databases to a named pipe. The databases are supplied as a sequence of
  112. dicts, one dict describing each database as per the configuration schema. Use the given
  113. borgmatic runtime directory to construct the destination path.
  114. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  115. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  116. Also append the the parent directory of the database dumps to the given patterns list, so the
  117. dumps actually get backed up.
  118. Raise ValueError if the databases to dump cannot be determined.
  119. '''
  120. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  121. processes = []
  122. dumps_metadata = []
  123. logger.info(f'Dumping PostgreSQL databases{dry_run_label}')
  124. dump_path = make_dump_path(borgmatic_runtime_directory)
  125. for database in databases:
  126. environment = make_environment(database, config)
  127. dump_database_names = database_names_to_dump(database, config, environment, dry_run)
  128. if not dump_database_names:
  129. if dry_run:
  130. continue
  131. raise ValueError('Cannot find any PostgreSQL databases to dump.')
  132. for database_name in dump_database_names:
  133. dumps_metadata.append(
  134. borgmatic.actions.restore.Dump(
  135. 'postgresql_databases',
  136. database_name,
  137. database.get('hostname'),
  138. database.get('port'),
  139. database.get('label'),
  140. database.get('container'),
  141. )
  142. )
  143. dump_format = database.get('format', None if database_name == 'all' else 'custom')
  144. compression = database.get('compression')
  145. default_dump_command = 'pg_dumpall' if database_name == 'all' else 'pg_dump'
  146. dump_command = tuple(
  147. shlex.quote(part)
  148. for part in shlex.split(database.get('pg_dump_command') or default_dump_command)
  149. )
  150. dump_filename = dump.make_data_source_dump_filename(
  151. dump_path,
  152. database_name,
  153. hostname=database.get('hostname'),
  154. port=database.get('port'),
  155. container=database.get('container'),
  156. label=database.get('label'),
  157. )
  158. if os.path.exists(dump_filename):
  159. logger.warning(
  160. f'Skipping duplicate dump of PostgreSQL database "{database_name}" to {dump_filename}',
  161. )
  162. continue
  163. hostname = database_config.resolve_database_option('hostname', database)
  164. command = (
  165. dump_command
  166. + (
  167. '--no-password',
  168. '--clean',
  169. '--if-exists',
  170. )
  171. + (('--host', shlex.quote(hostname)) if hostname else ())
  172. + (('--port', shlex.quote(str(database['port']))) if 'port' in database else ())
  173. + (
  174. (
  175. '--username',
  176. shlex.quote(
  177. borgmatic.hooks.credential.parse.resolve_credential(
  178. database['username'],
  179. config,
  180. ),
  181. ),
  182. )
  183. if 'username' in database
  184. else ()
  185. )
  186. + (('--no-owner',) if database.get('no_owner', False) else ())
  187. + (('--format', shlex.quote(dump_format)) if dump_format else ())
  188. + (('--compress', shlex.quote(str(compression))) if compression is not None else ())
  189. + (('--file', shlex.quote(dump_filename)) if dump_format == 'directory' else ())
  190. + (
  191. tuple(shlex.quote(option) for option in database['options'].split(' '))
  192. if 'options' in database
  193. else ()
  194. )
  195. + (() if database_name == 'all' else (shlex.quote(database_name),))
  196. # Use shell redirection rather than the --file flag to sidestep synchronization issues
  197. # when pg_dump/pg_dumpall tries to write to a named pipe. But for the directory dump
  198. # format in a particular, a named destination is required, and redirection doesn't work.
  199. + (('>', shlex.quote(dump_filename)) if dump_format != 'directory' else ())
  200. )
  201. logger.debug(
  202. f'Dumping PostgreSQL database "{database_name}" to {dump_filename}{dry_run_label}',
  203. )
  204. if dry_run:
  205. continue
  206. if dump_format == 'directory':
  207. dump.create_parent_directory_for_dump(dump_filename)
  208. execute_command( # noqa: S604
  209. command,
  210. shell=True,
  211. environment=environment,
  212. working_directory=borgmatic.config.paths.get_working_directory(config),
  213. )
  214. else:
  215. dump.create_named_pipe_for_dump(dump_filename)
  216. processes.append(
  217. execute_command( # noqa: S604
  218. command,
  219. shell=True,
  220. environment=environment,
  221. run_to_completion=False,
  222. working_directory=borgmatic.config.paths.get_working_directory(config),
  223. ),
  224. )
  225. if not dry_run:
  226. dump.write_data_source_dumps_metadata(
  227. borgmatic_runtime_directory, 'postgresql_databases', dumps_metadata
  228. )
  229. borgmatic.hooks.data_source.config.inject_pattern(
  230. patterns,
  231. borgmatic.borg.pattern.Pattern(
  232. os.path.join(borgmatic_runtime_directory, 'postgresql_databases'),
  233. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  234. ),
  235. )
  236. return processes
  237. def remove_data_source_dumps(
  238. databases,
  239. config,
  240. borgmatic_runtime_directory,
  241. patterns,
  242. dry_run,
  243. ): # pragma: no cover
  244. '''
  245. Remove all database dump files for this hook regardless of the given databases. Use the
  246. borgmatic runtime directory to construct the destination path. If this is a dry run, then don't
  247. actually remove anything.
  248. '''
  249. dump.remove_data_source_dumps(
  250. make_dump_path(borgmatic_runtime_directory),
  251. 'PostgreSQL',
  252. dry_run,
  253. )
  254. def make_data_source_dump_patterns(
  255. databases,
  256. config,
  257. borgmatic_runtime_directory,
  258. name=None,
  259. hostname=None,
  260. port=None,
  261. container=None,
  262. label=None,
  263. ): # pragma: no cover
  264. '''
  265. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  266. and a database name to match, return the corresponding glob patterns to match the database dump
  267. in an archive.
  268. '''
  269. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  270. return (
  271. dump.make_data_source_dump_filename(
  272. make_dump_path('borgmatic'), name, hostname, port, container, label
  273. ),
  274. dump.make_data_source_dump_filename(
  275. make_dump_path(borgmatic_runtime_directory),
  276. name,
  277. hostname,
  278. port,
  279. container,
  280. label,
  281. ),
  282. dump.make_data_source_dump_filename(
  283. make_dump_path(borgmatic_source_directory),
  284. name,
  285. hostname,
  286. port,
  287. container,
  288. label,
  289. ),
  290. )
  291. def restore_data_source_dump(
  292. hook_config,
  293. config,
  294. data_source,
  295. dry_run,
  296. extract_process,
  297. connection_params,
  298. borgmatic_runtime_directory,
  299. ):
  300. '''
  301. Restore a database from the given extract stream. The database is supplied as a data source
  302. configuration dict, but the given hook configuration is ignored. The given borgmatic runtime
  303. directory is used to construct the destination path (used for the directory format). If this is
  304. a dry run, then don't actually restore anything. Trigger the given active extract process (an
  305. instance of subprocess.Popen) to produce output to consume.
  306. If the extract process is None, then restore the dump from the filesystem rather than from an
  307. extract stream.
  308. Use the given connection parameters to connect to the database. The connection parameters are
  309. hostname, port, username, and password.
  310. '''
  311. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  312. hostname = database_config.resolve_database_option(
  313. 'hostname', data_source, connection_params, restore=True
  314. )
  315. port = database_config.resolve_database_option(
  316. 'port', data_source, connection_params, restore=True
  317. )
  318. username = borgmatic.hooks.credential.parse.resolve_credential(
  319. database_config.resolve_database_option(
  320. 'username', data_source, connection_params, restore=True
  321. ),
  322. config,
  323. )
  324. all_databases = bool(data_source['name'] == 'all')
  325. dump_filename = dump.make_data_source_dump_filename(
  326. make_dump_path(borgmatic_runtime_directory),
  327. data_source['name'],
  328. hostname=hostname,
  329. port=port,
  330. container=data_source.get('container'),
  331. label=data_source.get('label'),
  332. )
  333. psql_command = tuple(
  334. shlex.quote(part) for part in shlex.split(data_source.get('psql_command') or 'psql')
  335. )
  336. analyze_command = (
  337. psql_command
  338. + ('--no-password', '--no-psqlrc', '--quiet')
  339. + (('--host', hostname) if hostname else ())
  340. + (('--port', str(port)) if port else ())
  341. + (('--username', username) if username else ())
  342. + (('--dbname', data_source['name']) if not all_databases else ())
  343. + (
  344. tuple(data_source['analyze_options'].split(' '))
  345. if 'analyze_options' in data_source
  346. else ()
  347. )
  348. + ('--command', 'ANALYZE')
  349. )
  350. use_psql_command = all_databases or data_source.get('format') == 'plain'
  351. pg_restore_command = tuple(
  352. shlex.quote(part)
  353. for part in shlex.split(data_source.get('pg_restore_command') or 'pg_restore')
  354. )
  355. restore_command = (
  356. (psql_command if use_psql_command else pg_restore_command)
  357. + ('--no-password',)
  358. + (('--no-psqlrc',) if use_psql_command else ('--if-exists', '--exit-on-error', '--clean'))
  359. + (('--dbname', data_source['name']) if not all_databases else ())
  360. + (('--host', hostname) if hostname else ())
  361. + (('--port', str(port)) if port else ())
  362. + (('--username', username) if username else ())
  363. + (('--no-owner',) if data_source.get('no_owner', False) else ())
  364. + (
  365. tuple(data_source['restore_options'].split(' '))
  366. if 'restore_options' in data_source
  367. else ()
  368. )
  369. + (() if extract_process else (str(pathlib.Path(dump_filename)),))
  370. + tuple(
  371. itertools.chain.from_iterable(('--schema', schema) for schema in data_source['schemas'])
  372. if data_source.get('schemas')
  373. else (),
  374. )
  375. )
  376. environment = make_environment(data_source, config, restore_connection_params=connection_params)
  377. logger.debug(f"Restoring PostgreSQL database {data_source['name']}{dry_run_label}")
  378. if dry_run:
  379. return
  380. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  381. # if the restore paths don't exist in the archive.
  382. execute_command_with_processes(
  383. restore_command,
  384. [extract_process] if extract_process else [],
  385. output_log_level=logging.DEBUG,
  386. input_file=extract_process.stdout if extract_process else None,
  387. environment=environment,
  388. working_directory=borgmatic.config.paths.get_working_directory(config),
  389. )
  390. execute_command(
  391. analyze_command,
  392. environment=environment,
  393. working_directory=borgmatic.config.paths.get_working_directory(config),
  394. )