postgresql.py 11 KB

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