2
0

postgresql.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import csv
  2. import itertools
  3. import logging
  4. import os
  5. import shlex
  6. from borgmatic.execute import (
  7. execute_command,
  8. execute_command_and_capture_output,
  9. execute_command_with_processes,
  10. )
  11. from borgmatic.hooks import dump
  12. logger = logging.getLogger(__name__)
  13. def make_dump_path(config): # pragma: no cover
  14. '''
  15. Make the dump path from the given configuration dict and the name of this hook.
  16. '''
  17. return dump.make_data_source_dump_path(
  18. config.get('borgmatic_source_directory'), 'postgresql_databases'
  19. )
  20. def make_extra_environment(database, restore_connection_params=None):
  21. '''
  22. Make the extra_environment dict from the given database configuration. If restore connection
  23. params are given, this is for a restore operation.
  24. '''
  25. extra = dict()
  26. try:
  27. if restore_connection_params:
  28. extra['PGPASSWORD'] = restore_connection_params.get('password') or database.get(
  29. 'restore_password', database['password']
  30. )
  31. else:
  32. extra['PGPASSWORD'] = database['password']
  33. except (AttributeError, KeyError):
  34. pass
  35. if 'ssl_mode' in database:
  36. extra['PGSSLMODE'] = database['ssl_mode']
  37. if 'ssl_cert' in database:
  38. extra['PGSSLCERT'] = database['ssl_cert']
  39. if 'ssl_key' in database:
  40. extra['PGSSLKEY'] = database['ssl_key']
  41. if 'ssl_root_cert' in database:
  42. extra['PGSSLROOTCERT'] = database['ssl_root_cert']
  43. if 'ssl_crl' in database:
  44. extra['PGSSLCRL'] = database['ssl_crl']
  45. return extra
  46. EXCLUDED_DATABASE_NAMES = ('template0', 'template1')
  47. def database_names_to_dump(database, extra_environment, log_prefix, dry_run):
  48. '''
  49. Given a requested database config, return the corresponding sequence of database names to dump.
  50. In the case of "all" when a database format is given, query for the names of databases on the
  51. configured host and return them. For "all" without a database format, just return a sequence
  52. containing "all".
  53. '''
  54. requested_name = database['name']
  55. if requested_name != 'all':
  56. return (requested_name,)
  57. if not database.get('format'):
  58. return ('all',)
  59. if dry_run:
  60. return ()
  61. psql_command = tuple(
  62. shlex.quote(part) for part in shlex.split(database.get('psql_command') or 'psql')
  63. )
  64. list_command = (
  65. psql_command
  66. + ('--list', '--no-password', '--no-psqlrc', '--csv', '--tuples-only')
  67. + (('--host', database['hostname']) if 'hostname' in database else ())
  68. + (('--port', str(database['port'])) if 'port' in database else ())
  69. + (('--username', database['username']) if 'username' in database else ())
  70. + (tuple(database['list_options'].split(' ')) if 'list_options' in database else ())
  71. )
  72. logger.debug(f'{log_prefix}: Querying for "all" PostgreSQL databases to dump')
  73. list_output = execute_command_and_capture_output(
  74. list_command, extra_environment=extra_environment
  75. )
  76. return tuple(
  77. row[0]
  78. for row in csv.reader(list_output.splitlines(), delimiter=',', quotechar='"')
  79. if row[0] not in EXCLUDED_DATABASE_NAMES
  80. )
  81. def dump_data_sources(databases, config, log_prefix, dry_run):
  82. '''
  83. Dump the given PostgreSQL databases to a named pipe. The databases are supplied as a sequence of
  84. dicts, one dict describing each database as per the configuration schema. Use the given
  85. configuration dict to construct the destination path and the given log prefix in any log
  86. entries.
  87. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  88. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  89. Raise ValueError if the databases to dump cannot be determined.
  90. '''
  91. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  92. processes = []
  93. logger.info(f'{log_prefix}: Dumping PostgreSQL databases{dry_run_label}')
  94. for database in databases:
  95. extra_environment = make_extra_environment(database)
  96. dump_path = make_dump_path(config)
  97. dump_database_names = database_names_to_dump(
  98. database, extra_environment, log_prefix, dry_run
  99. )
  100. if not dump_database_names:
  101. if dry_run:
  102. continue
  103. raise ValueError('Cannot find any PostgreSQL databases to dump.')
  104. for database_name in dump_database_names:
  105. dump_format = database.get('format', None if database_name == 'all' else 'custom')
  106. default_dump_command = 'pg_dumpall' if database_name == 'all' else 'pg_dump'
  107. dump_command = tuple(
  108. shlex.quote(part)
  109. for part in shlex.split(database.get('pg_dump_command') or default_dump_command)
  110. )
  111. dump_filename = dump.make_data_source_dump_filename(
  112. dump_path, database_name, database.get('hostname')
  113. )
  114. if os.path.exists(dump_filename):
  115. logger.warning(
  116. f'{log_prefix}: Skipping duplicate dump of PostgreSQL database "{database_name}" to {dump_filename}'
  117. )
  118. continue
  119. command = (
  120. dump_command
  121. + (
  122. '--no-password',
  123. '--clean',
  124. '--if-exists',
  125. )
  126. + (('--host', shlex.quote(database['hostname'])) if 'hostname' in database else ())
  127. + (('--port', shlex.quote(str(database['port']))) if 'port' in database else ())
  128. + (
  129. ('--username', shlex.quote(database['username']))
  130. if 'username' in database
  131. else ()
  132. )
  133. + (('--no-owner',) if database.get('no_owner', False) else ())
  134. + (('--format', shlex.quote(dump_format)) if dump_format else ())
  135. + (('--file', shlex.quote(dump_filename)) if dump_format == 'directory' else ())
  136. + (
  137. tuple(shlex.quote(option) for option in database['options'].split(' '))
  138. if 'options' in database
  139. else ()
  140. )
  141. + (() if database_name == 'all' else (shlex.quote(database_name),))
  142. # Use shell redirection rather than the --file flag to sidestep synchronization issues
  143. # when pg_dump/pg_dumpall tries to write to a named pipe. But for the directory dump
  144. # format in a particular, a named destination is required, and redirection doesn't work.
  145. + (('>', shlex.quote(dump_filename)) if dump_format != 'directory' else ())
  146. )
  147. logger.debug(
  148. f'{log_prefix}: Dumping PostgreSQL database "{database_name}" to {dump_filename}{dry_run_label}'
  149. )
  150. if dry_run:
  151. continue
  152. if dump_format == 'directory':
  153. dump.create_parent_directory_for_dump(dump_filename)
  154. execute_command(
  155. command,
  156. shell=True,
  157. extra_environment=extra_environment,
  158. )
  159. else:
  160. dump.create_named_pipe_for_dump(dump_filename)
  161. processes.append(
  162. execute_command(
  163. command,
  164. shell=True,
  165. extra_environment=extra_environment,
  166. run_to_completion=False,
  167. )
  168. )
  169. return processes
  170. def remove_data_source_dumps(databases, config, log_prefix, dry_run): # pragma: no cover
  171. '''
  172. Remove all database dump files for this hook regardless of the given databases. Use the given
  173. configuration dict to construct the destination path and the log prefix in any log entries. If
  174. this is a dry run, then don't actually remove anything.
  175. '''
  176. dump.remove_data_source_dumps(make_dump_path(config), 'PostgreSQL', log_prefix, dry_run)
  177. def make_data_source_dump_pattern(databases, config, log_prefix, name=None): # pragma: no cover
  178. '''
  179. Given a sequence of configurations dicts, a configuration dict, a prefix to log with, and a
  180. database name to match, return the corresponding glob patterns to match the database dump in an
  181. archive.
  182. '''
  183. return dump.make_data_source_dump_filename(make_dump_path(config), name, hostname='*')
  184. def restore_data_source_dump(
  185. hook_config, config, log_prefix, data_source, dry_run, extract_process, connection_params
  186. ):
  187. '''
  188. Restore a database from the given extract stream. The database is supplied as a data source
  189. configuration dict, but the given hook configuration is ignored. The given configuration dict is
  190. used to construct the destination path, and the given log prefix is used for any log entries. If
  191. this is a dry run, then don't actually restore anything. Trigger the given active extract
  192. process (an instance of subprocess.Popen) to produce output to consume.
  193. If the extract process is None, then restore the dump from the filesystem rather than from an
  194. extract stream.
  195. Use the given connection parameters to connect to the database. The connection parameters are
  196. hostname, port, username, and password.
  197. '''
  198. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  199. hostname = connection_params['hostname'] or data_source.get(
  200. 'restore_hostname', data_source.get('hostname')
  201. )
  202. port = str(
  203. connection_params['port'] or data_source.get('restore_port', data_source.get('port', ''))
  204. )
  205. username = connection_params['username'] or data_source.get(
  206. 'restore_username', data_source.get('username')
  207. )
  208. all_databases = bool(data_source['name'] == 'all')
  209. dump_filename = dump.make_data_source_dump_filename(
  210. make_dump_path(config), data_source['name'], data_source.get('hostname')
  211. )
  212. psql_command = tuple(
  213. shlex.quote(part) for part in shlex.split(data_source.get('psql_command') or 'psql')
  214. )
  215. analyze_command = (
  216. psql_command
  217. + ('--no-password', '--no-psqlrc', '--quiet')
  218. + (('--host', hostname) if hostname else ())
  219. + (('--port', port) if port else ())
  220. + (('--username', username) if username else ())
  221. + (('--dbname', data_source['name']) if not all_databases else ())
  222. + (
  223. tuple(data_source['analyze_options'].split(' '))
  224. if 'analyze_options' in data_source
  225. else ()
  226. )
  227. + ('--command', 'ANALYZE')
  228. )
  229. use_psql_command = all_databases or data_source.get('format') == 'plain'
  230. pg_restore_command = tuple(
  231. shlex.quote(part)
  232. for part in shlex.split(data_source.get('pg_restore_command') or 'pg_restore')
  233. )
  234. restore_command = (
  235. (psql_command if use_psql_command else pg_restore_command)
  236. + ('--no-password',)
  237. + (('--no-psqlrc',) if use_psql_command else ('--if-exists', '--exit-on-error', '--clean'))
  238. + (('--dbname', data_source['name']) if not all_databases else ())
  239. + (('--host', hostname) if hostname else ())
  240. + (('--port', port) if port else ())
  241. + (('--username', username) if username else ())
  242. + (('--no-owner',) if data_source.get('no_owner', False) else ())
  243. + (
  244. tuple(data_source['restore_options'].split(' '))
  245. if 'restore_options' in data_source
  246. else ()
  247. )
  248. + (() if extract_process else (dump_filename,))
  249. + tuple(
  250. itertools.chain.from_iterable(('--schema', schema) for schema in data_source['schemas'])
  251. if data_source.get('schemas')
  252. else ()
  253. )
  254. )
  255. extra_environment = make_extra_environment(
  256. data_source, restore_connection_params=connection_params
  257. )
  258. logger.debug(
  259. f"{log_prefix}: Restoring PostgreSQL database {data_source['name']}{dry_run_label}"
  260. )
  261. if dry_run:
  262. return
  263. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  264. # if the restore paths don't exist in the archive.
  265. execute_command_with_processes(
  266. restore_command,
  267. [extract_process] if extract_process else [],
  268. output_log_level=logging.DEBUG,
  269. input_file=extract_process.stdout if extract_process else None,
  270. extra_environment=extra_environment,
  271. )
  272. execute_command(analyze_command, extra_environment=extra_environment)