mongodb.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import logging
  2. import os
  3. import shlex
  4. import borgmatic.borg.pattern
  5. import borgmatic.config.paths
  6. from borgmatic.execute import execute_command, execute_command_with_processes
  7. from borgmatic.hooks.data_source import dump
  8. logger = logging.getLogger(__name__)
  9. def make_dump_path(base_directory): # pragma: no cover
  10. '''
  11. Given a base directory, make the corresponding dump path.
  12. '''
  13. return dump.make_data_source_dump_path(base_directory, 'mongodb_databases')
  14. def get_default_port(databases, config, log_prefix): # pragma: no cover
  15. return 27017
  16. def use_streaming(databases, config, log_prefix):
  17. '''
  18. Given a sequence of MongoDB database configuration dicts, a configuration dict (ignored), and a
  19. log prefix (ignored), return whether streaming will be using during dumps.
  20. '''
  21. return any(database.get('format') != 'directory' for database in databases)
  22. def dump_data_sources(
  23. databases,
  24. config,
  25. log_prefix,
  26. config_paths,
  27. borgmatic_runtime_directory,
  28. patterns,
  29. dry_run,
  30. ):
  31. '''
  32. Dump the given MongoDB databases to a named pipe. The databases are supplied as a sequence of
  33. dicts, one dict describing each database as per the configuration schema. Use the borgmatic
  34. runtime directory to construct the destination path (used for the directory format and the given
  35. log prefix in any log entries.
  36. Return a sequence of subprocess.Popen instances for the dump processes ready to spew to a named
  37. pipe. But if this is a dry run, then don't actually dump anything and return an empty sequence.
  38. Also append the the parent directory of the database dumps to the given patterns list, so the
  39. dumps actually get backed up.
  40. '''
  41. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  42. logger.info(f'{log_prefix}: Dumping MongoDB databases{dry_run_label}')
  43. processes = []
  44. for database in databases:
  45. name = database['name']
  46. dump_filename = dump.make_data_source_dump_filename(
  47. make_dump_path(borgmatic_runtime_directory),
  48. name,
  49. database.get('hostname'),
  50. database.get('port'),
  51. )
  52. dump_format = database.get('format', 'archive')
  53. logger.debug(
  54. f'{log_prefix}: Dumping MongoDB database {name} to {dump_filename}{dry_run_label}',
  55. )
  56. if dry_run:
  57. continue
  58. command = build_dump_command(database, dump_filename, dump_format)
  59. if dump_format == 'directory':
  60. dump.create_parent_directory_for_dump(dump_filename)
  61. execute_command(command, shell=True)
  62. else:
  63. dump.create_named_pipe_for_dump(dump_filename)
  64. processes.append(execute_command(command, shell=True, run_to_completion=False))
  65. if not dry_run:
  66. patterns.append(
  67. borgmatic.borg.pattern.Pattern(
  68. os.path.join(borgmatic_runtime_directory, 'mongodb_databases')
  69. )
  70. )
  71. return processes
  72. def build_dump_command(database, dump_filename, dump_format):
  73. '''
  74. Return the mongodump command from a single database configuration.
  75. '''
  76. all_databases = database['name'] == 'all'
  77. return (
  78. ('mongodump',)
  79. + (('--out', shlex.quote(dump_filename)) if dump_format == 'directory' else ())
  80. + (('--host', shlex.quote(database['hostname'])) if 'hostname' in database else ())
  81. + (('--port', shlex.quote(str(database['port']))) if 'port' in database else ())
  82. + (('--username', shlex.quote(database['username'])) if 'username' in database else ())
  83. + (('--password', shlex.quote(database['password'])) if 'password' in database else ())
  84. + (
  85. ('--authenticationDatabase', shlex.quote(database['authentication_database']))
  86. if 'authentication_database' in database
  87. else ()
  88. )
  89. + (('--db', shlex.quote(database['name'])) if not all_databases else ())
  90. + (
  91. tuple(shlex.quote(option) for option in database['options'].split(' '))
  92. if 'options' in database
  93. else ()
  94. )
  95. + (('--archive', '>', shlex.quote(dump_filename)) if dump_format != 'directory' else ())
  96. )
  97. def remove_data_source_dumps(
  98. databases, config, log_prefix, borgmatic_runtime_directory, dry_run
  99. ): # pragma: no cover
  100. '''
  101. Remove all database dump files for this hook regardless of the given databases. Use the
  102. borgmatic_runtime_directory to construct the destination path and the log prefix in any log
  103. entries. If this is a dry run, then don't actually remove anything.
  104. '''
  105. dump.remove_data_source_dumps(
  106. make_dump_path(borgmatic_runtime_directory), 'MongoDB', log_prefix, dry_run
  107. )
  108. def make_data_source_dump_patterns(
  109. databases, config, log_prefix, borgmatic_runtime_directory, name=None
  110. ): # pragma: no cover
  111. '''
  112. Given a sequence of configurations dicts, a configuration dict, a prefix to log with, the
  113. borgmatic runtime directory, and a database name to match, return the corresponding glob
  114. patterns to match the database dump in an archive.
  115. '''
  116. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  117. return (
  118. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  119. dump.make_data_source_dump_filename(
  120. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  121. ),
  122. dump.make_data_source_dump_filename(
  123. make_dump_path(borgmatic_source_directory), name, hostname='*'
  124. ),
  125. )
  126. def restore_data_source_dump(
  127. hook_config,
  128. config,
  129. log_prefix,
  130. data_source,
  131. dry_run,
  132. extract_process,
  133. connection_params,
  134. borgmatic_runtime_directory,
  135. ):
  136. '''
  137. Restore a database from the given extract stream. The database is supplied as a data source
  138. configuration dict, but the given hook configuration is ignored. The given configuration dict is
  139. used to construct the destination path, and the given log prefix is used for any log entries. If
  140. this is a dry run, then don't actually restore anything. Trigger the given active extract
  141. process (an instance of subprocess.Popen) to produce output to consume.
  142. If the extract process is None, then restore the dump from the filesystem rather than from an
  143. extract stream.
  144. '''
  145. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  146. dump_filename = dump.make_data_source_dump_filename(
  147. make_dump_path(borgmatic_runtime_directory),
  148. data_source['name'],
  149. data_source.get('hostname'),
  150. )
  151. restore_command = build_restore_command(
  152. extract_process, data_source, dump_filename, connection_params
  153. )
  154. logger.debug(f"{log_prefix}: Restoring MongoDB database {data_source['name']}{dry_run_label}")
  155. if dry_run:
  156. return
  157. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  158. # if the restore paths don't exist in the archive.
  159. execute_command_with_processes(
  160. restore_command,
  161. [extract_process] if extract_process else [],
  162. output_log_level=logging.DEBUG,
  163. input_file=extract_process.stdout if extract_process else None,
  164. )
  165. def build_restore_command(extract_process, database, dump_filename, connection_params):
  166. '''
  167. Return the mongorestore command from a single database configuration.
  168. '''
  169. hostname = connection_params['hostname'] or database.get(
  170. 'restore_hostname', database.get('hostname')
  171. )
  172. port = str(connection_params['port'] or database.get('restore_port', database.get('port', '')))
  173. username = connection_params['username'] or database.get(
  174. 'restore_username', database.get('username')
  175. )
  176. password = connection_params['password'] or database.get(
  177. 'restore_password', database.get('password')
  178. )
  179. command = ['mongorestore']
  180. if extract_process:
  181. command.append('--archive')
  182. else:
  183. command.extend(('--dir', dump_filename))
  184. if database['name'] != 'all':
  185. command.extend(('--drop',))
  186. if hostname:
  187. command.extend(('--host', hostname))
  188. if port:
  189. command.extend(('--port', str(port)))
  190. if username:
  191. command.extend(('--username', username))
  192. if password:
  193. command.extend(('--password', password))
  194. if 'authentication_database' in database:
  195. command.extend(('--authenticationDatabase', database['authentication_database']))
  196. if 'restore_options' in database:
  197. command.extend(database['restore_options'].split(' '))
  198. if database.get('schemas'):
  199. for schema in database['schemas']:
  200. command.extend(('--nsInclude', schema))
  201. return command