postgresql.py 15 KB

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