postgresql.py 15 KB

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