postgresql.py 11 KB

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