mongodb.py 8.8 KB

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