mongodb.py 7.9 KB

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