postgresql.py 10.0 KB

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