mongodb.py 8.4 KB

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