mongodb.py 11 KB

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