mongodb.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import logging
  2. import os
  3. import shlex
  4. import borgmatic.borg.pattern
  5. import borgmatic.config.paths
  6. import borgmatic.hooks.command
  7. import borgmatic.hooks.credential.parse
  8. from borgmatic.execute import execute_command, execute_command_with_processes
  9. from borgmatic.hooks.data_source import dump
  10. logger = logging.getLogger(__name__)
  11. def make_dump_path(base_directory): # pragma: no cover
  12. '''
  13. Given a base directory, make the corresponding dump path.
  14. '''
  15. return dump.make_data_source_dump_path(base_directory, 'mongodb_databases')
  16. def get_default_port(databases, config): # pragma: no cover
  17. return 27017
  18. def use_streaming(databases, config):
  19. '''
  20. Given a sequence of MongoDB database configuration dicts, a configuration dict (ignored), return
  21. whether streaming will be using during dumps.
  22. '''
  23. return any(database.get('format') != 'directory' for database in databases)
  24. def dump_data_sources(
  25. databases,
  26. config,
  27. config_paths,
  28. borgmatic_runtime_directory,
  29. patterns,
  30. dry_run,
  31. ):
  32. '''
  33. Dump the given MongoDB databases to a named pipe. The databases are supplied as a sequence of
  34. dicts, one dict describing each database as per the configuration schema. Use the borgmatic
  35. runtime directory to construct the destination path (used for the directory format.
  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. with borgmatic.hooks.command.Before_after_hooks(
  42. command_hooks=config.get('commands'),
  43. before_after='dump_data_sources',
  44. hook_name='mongodb',
  45. umask=config.get('umask'),
  46. dry_run=dry_run,
  47. ):
  48. dry_run_label = ' (dry run; not actually dumping anything)' if dry_run else ''
  49. logger.info(f'Dumping MongoDB databases{dry_run_label}')
  50. processes = []
  51. for database in databases:
  52. name = database['name']
  53. dump_filename = dump.make_data_source_dump_filename(
  54. make_dump_path(borgmatic_runtime_directory),
  55. name,
  56. database.get('hostname'),
  57. database.get('port'),
  58. )
  59. dump_format = database.get('format', 'archive')
  60. logger.debug(
  61. f'Dumping MongoDB database {name} to {dump_filename}{dry_run_label}',
  62. )
  63. if dry_run:
  64. continue
  65. command = build_dump_command(database, config, dump_filename, dump_format)
  66. if dump_format == 'directory':
  67. dump.create_parent_directory_for_dump(dump_filename)
  68. execute_command(command, shell=True)
  69. else:
  70. dump.create_named_pipe_for_dump(dump_filename)
  71. processes.append(execute_command(command, shell=True, run_to_completion=False))
  72. if not dry_run:
  73. patterns.append(
  74. borgmatic.borg.pattern.Pattern(
  75. os.path.join(borgmatic_runtime_directory, 'mongodb_databases'),
  76. source=borgmatic.borg.pattern.Pattern_source.HOOK,
  77. )
  78. )
  79. return processes
  80. def make_password_config_file(password):
  81. '''
  82. Given a database password, write it as a MongoDB configuration file to an anonymous pipe and
  83. return its filename. The idea is that this is a more secure way to transmit a password to
  84. MongoDB than providing it directly on the command-line.
  85. Do not use the returned value for multiple different command invocations. That will not work
  86. because each pipe is "used up" once read.
  87. '''
  88. logger.debug('Writing MongoDB password to configuration file pipe')
  89. read_file_descriptor, write_file_descriptor = os.pipe()
  90. os.write(write_file_descriptor, f'password: {password}'.encode('utf-8'))
  91. os.close(write_file_descriptor)
  92. # This plus subprocess.Popen(..., close_fds=False) in execute.py is necessary for the database
  93. # client child process to inherit the file descriptor.
  94. os.set_inheritable(read_file_descriptor, True)
  95. return f'/dev/fd/{read_file_descriptor}'
  96. def build_dump_command(database, config, dump_filename, dump_format):
  97. '''
  98. Return the mongodump command from a single database configuration.
  99. '''
  100. all_databases = database['name'] == 'all'
  101. password = borgmatic.hooks.credential.parse.resolve_credential(database.get('password'), config)
  102. return (
  103. ('mongodump',)
  104. + (('--out', shlex.quote(dump_filename)) if dump_format == 'directory' else ())
  105. + (('--host', shlex.quote(database['hostname'])) if 'hostname' in database else ())
  106. + (('--port', shlex.quote(str(database['port']))) if 'port' in database else ())
  107. + (
  108. (
  109. '--username',
  110. shlex.quote(
  111. borgmatic.hooks.credential.parse.resolve_credential(
  112. database['username'], config
  113. )
  114. ),
  115. )
  116. if 'username' in database
  117. else ()
  118. )
  119. + (('--config', make_password_config_file(password)) if password else ())
  120. + (
  121. ('--authenticationDatabase', shlex.quote(database['authentication_database']))
  122. if 'authentication_database' in database
  123. else ()
  124. )
  125. + (('--db', shlex.quote(database['name'])) if not all_databases else ())
  126. + (
  127. tuple(shlex.quote(option) for option in database['options'].split(' '))
  128. if 'options' in database
  129. else ()
  130. )
  131. + (('--archive', '>', shlex.quote(dump_filename)) if dump_format != 'directory' else ())
  132. )
  133. def remove_data_source_dumps(
  134. databases, config, borgmatic_runtime_directory, dry_run
  135. ): # pragma: no cover
  136. '''
  137. Remove all database dump files for this hook regardless of the given databases. Use the
  138. borgmatic_runtime_directory to construct the destination path. If this is a dry run, then don't
  139. actually remove anything.
  140. '''
  141. dump.remove_data_source_dumps(make_dump_path(borgmatic_runtime_directory), 'MongoDB', dry_run)
  142. def make_data_source_dump_patterns(
  143. databases, config, borgmatic_runtime_directory, name=None
  144. ): # pragma: no cover
  145. '''
  146. Given a sequence of configurations dicts, a configuration dict, the borgmatic runtime directory,
  147. and a database name to match, return the corresponding glob patterns to match the database dump
  148. in an archive.
  149. '''
  150. borgmatic_source_directory = borgmatic.config.paths.get_borgmatic_source_directory(config)
  151. return (
  152. dump.make_data_source_dump_filename(make_dump_path('borgmatic'), name, hostname='*'),
  153. dump.make_data_source_dump_filename(
  154. make_dump_path(borgmatic_runtime_directory), name, hostname='*'
  155. ),
  156. dump.make_data_source_dump_filename(
  157. make_dump_path(borgmatic_source_directory), name, hostname='*'
  158. ),
  159. )
  160. def restore_data_source_dump(
  161. hook_config,
  162. config,
  163. data_source,
  164. dry_run,
  165. extract_process,
  166. connection_params,
  167. borgmatic_runtime_directory,
  168. ):
  169. '''
  170. Restore a database from the given extract stream. The database is supplied as a data source
  171. configuration dict, but the given hook configuration is ignored. The given configuration dict is
  172. used to construct the destination path. If this is a dry run, then don't actually restore
  173. anything. Trigger the given active extract process (an instance of subprocess.Popen) to produce
  174. output to consume.
  175. If the extract process is None, then restore the dump from the filesystem rather than from an
  176. extract stream.
  177. '''
  178. dry_run_label = ' (dry run; not actually restoring anything)' if dry_run else ''
  179. dump_filename = dump.make_data_source_dump_filename(
  180. make_dump_path(borgmatic_runtime_directory),
  181. data_source['name'],
  182. data_source.get('hostname'),
  183. )
  184. restore_command = build_restore_command(
  185. extract_process, data_source, config, dump_filename, connection_params
  186. )
  187. logger.debug(f"Restoring MongoDB database {data_source['name']}{dry_run_label}")
  188. if dry_run:
  189. return
  190. # Don't give Borg local path so as to error on warnings, as "borg extract" only gives a warning
  191. # if the restore paths don't exist in the archive.
  192. execute_command_with_processes(
  193. restore_command,
  194. [extract_process] if extract_process else [],
  195. output_log_level=logging.DEBUG,
  196. input_file=extract_process.stdout if extract_process else None,
  197. )
  198. def build_restore_command(extract_process, database, config, dump_filename, connection_params):
  199. '''
  200. Return the mongorestore command from a single database configuration.
  201. '''
  202. hostname = connection_params['hostname'] or database.get(
  203. 'restore_hostname', database.get('hostname')
  204. )
  205. port = str(connection_params['port'] or database.get('restore_port', database.get('port', '')))
  206. username = borgmatic.hooks.credential.parse.resolve_credential(
  207. (
  208. connection_params['username']
  209. or database.get('restore_username', database.get('username'))
  210. ),
  211. config,
  212. )
  213. password = borgmatic.hooks.credential.parse.resolve_credential(
  214. (
  215. connection_params['password']
  216. or database.get('restore_password', database.get('password'))
  217. ),
  218. config,
  219. )
  220. command = ['mongorestore']
  221. if extract_process:
  222. command.append('--archive')
  223. else:
  224. command.extend(('--dir', dump_filename))
  225. if database['name'] != 'all':
  226. command.extend(('--drop',))
  227. if hostname:
  228. command.extend(('--host', hostname))
  229. if port:
  230. command.extend(('--port', str(port)))
  231. if username:
  232. command.extend(('--username', username))
  233. if password:
  234. command.extend(('--config', make_password_config_file(password)))
  235. if 'authentication_database' in database:
  236. command.extend(('--authenticationDatabase', database['authentication_database']))
  237. if 'restore_options' in database:
  238. command.extend(database['restore_options'].split(' '))
  239. if database.get('schemas'):
  240. for schema in database['schemas']:
  241. command.extend(('--nsInclude', schema))
  242. return command