test_database.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import json
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. import pymongo
  8. import pytest
  9. import ruamel.yaml
  10. def write_configuration(
  11. source_directory,
  12. config_path,
  13. repository_path,
  14. user_runtime_directory,
  15. postgresql_dump_format='custom',
  16. postgresql_all_dump_format=None,
  17. mariadb_mysql_all_dump_format=None,
  18. mongodb_dump_format='archive',
  19. ):
  20. '''
  21. Write out borgmatic configuration into a file at the config path. Set the options so as to work
  22. for testing. This includes injecting the given repository path, borgmatic source directory for
  23. storing database dumps, dump format (for PostgreSQL), and encryption passphrase.
  24. '''
  25. postgresql_all_format_option = (
  26. f'format: {postgresql_all_dump_format}' if postgresql_all_dump_format else ''
  27. )
  28. mariadb_mysql_dump_format_option = (
  29. f'format: {mariadb_mysql_all_dump_format}' if mariadb_mysql_all_dump_format else ''
  30. )
  31. config_yaml = f'''
  32. source_directories:
  33. - {source_directory}
  34. repositories:
  35. - path: {repository_path}
  36. user_runtime_directory: {user_runtime_directory}
  37. encryption_passphrase: "test"
  38. postgresql_databases:
  39. - name: test
  40. hostname: postgresql
  41. username: postgres
  42. password: test
  43. format: {postgresql_dump_format}
  44. - name: all
  45. {postgresql_all_format_option}
  46. hostname: postgresql
  47. username: postgres
  48. password: test
  49. mariadb_databases:
  50. - name: test
  51. hostname: mariadb
  52. username: root
  53. password: test
  54. - name: all
  55. {mariadb_mysql_dump_format_option}
  56. hostname: mariadb
  57. username: root
  58. password: test
  59. mysql_databases:
  60. - name: test
  61. hostname: not-actually-mysql
  62. username: root
  63. password: test
  64. - name: all
  65. {mariadb_mysql_dump_format_option}
  66. hostname: not-actually-mysql
  67. username: root
  68. password: test
  69. mongodb_databases:
  70. - name: test
  71. hostname: mongodb
  72. username: root
  73. password: test
  74. authentication_database: admin
  75. format: {mongodb_dump_format}
  76. - name: all
  77. hostname: mongodb
  78. username: root
  79. password: test
  80. sqlite_databases:
  81. - name: sqlite_test
  82. path: /tmp/sqlite_test.db
  83. '''
  84. with open(config_path, 'w') as config_file:
  85. config_file.write(config_yaml)
  86. return ruamel.yaml.YAML(typ='safe').load(config_yaml)
  87. @pytest.mark.parametrize(
  88. 'postgresql_all_dump_format,mariadb_mysql_all_dump_format',
  89. (
  90. (None, None),
  91. ('custom', 'sql'),
  92. ),
  93. )
  94. def write_custom_restore_configuration(
  95. source_directory,
  96. config_path,
  97. repository_path,
  98. user_runtime_directory,
  99. postgresql_dump_format='custom',
  100. postgresql_all_dump_format=None,
  101. mariadb_mysql_all_dump_format=None,
  102. mongodb_dump_format='archive',
  103. ):
  104. '''
  105. Write out borgmatic configuration into a file at the config path. Set the options so as to work
  106. for testing with custom restore options. This includes a custom restore_hostname, restore_port,
  107. restore_username, restore_password and restore_path.
  108. '''
  109. config_yaml = f'''
  110. source_directories:
  111. - {source_directory}
  112. repositories:
  113. - path: {repository_path}
  114. user_runtime_directory: {user_runtime_directory}
  115. encryption_passphrase: "test"
  116. postgresql_databases:
  117. - name: test
  118. hostname: postgresql
  119. username: postgres
  120. password: test
  121. format: {postgresql_dump_format}
  122. restore_hostname: postgresql2
  123. restore_port: 5433
  124. restore_password: test2
  125. mariadb_databases:
  126. - name: test
  127. hostname: mariadb
  128. username: root
  129. password: test
  130. restore_hostname: mariadb2
  131. restore_port: 3307
  132. restore_username: root
  133. restore_password: test2
  134. mysql_databases:
  135. - name: test
  136. hostname: not-actually-mysql
  137. username: root
  138. password: test
  139. restore_hostname: not-actually-mysql2
  140. restore_port: 3307
  141. restore_username: root
  142. restore_password: test2
  143. mongodb_databases:
  144. - name: test
  145. hostname: mongodb
  146. username: root
  147. password: test
  148. authentication_database: admin
  149. format: {mongodb_dump_format}
  150. restore_hostname: mongodb2
  151. restore_port: 27018
  152. restore_username: root2
  153. restore_password: test2
  154. sqlite_databases:
  155. - name: sqlite_test
  156. path: /tmp/sqlite_test.db
  157. restore_path: /tmp/sqlite_test2.db
  158. '''
  159. with open(config_path, 'w') as config_file:
  160. config_file.write(config_yaml)
  161. return ruamel.yaml.YAML(typ='safe').load(config_yaml)
  162. def write_simple_custom_restore_configuration(
  163. source_directory,
  164. config_path,
  165. repository_path,
  166. user_runtime_directory,
  167. postgresql_dump_format='custom',
  168. ):
  169. '''
  170. Write out borgmatic configuration into a file at the config path. Set the options so as to work
  171. for testing with custom restore options, but this time using CLI arguments. This includes a
  172. custom restore_hostname, restore_port, restore_username and restore_password as we only test
  173. these options for PostgreSQL.
  174. '''
  175. config_yaml = f'''
  176. source_directories:
  177. - {source_directory}
  178. repositories:
  179. - path: {repository_path}
  180. user_runtime_directory: {user_runtime_directory}
  181. encryption_passphrase: "test"
  182. postgresql_databases:
  183. - name: test
  184. hostname: postgresql
  185. username: postgres
  186. password: test
  187. format: {postgresql_dump_format}
  188. '''
  189. with open(config_path, 'w') as config_file:
  190. config_file.write(config_yaml)
  191. return ruamel.yaml.YAML(typ='safe').load(config_yaml)
  192. def get_connection_params(database, use_restore_options=False):
  193. hostname = (database.get('restore_hostname') if use_restore_options else None) or database.get(
  194. 'hostname'
  195. )
  196. port = (database.get('restore_port') if use_restore_options else None) or database.get('port')
  197. username = (database.get('restore_username') if use_restore_options else None) or database.get(
  198. 'username'
  199. )
  200. password = (database.get('restore_password') if use_restore_options else None) or database.get(
  201. 'password'
  202. )
  203. return (hostname, port, username, password)
  204. def run_postgresql_command(command, config, use_restore_options=False):
  205. (hostname, port, username, password) = get_connection_params(
  206. config['postgresql_databases'][0], use_restore_options
  207. )
  208. subprocess.check_call(
  209. [
  210. '/usr/bin/psql',
  211. f'--host={hostname}',
  212. f'--port={port or 5432}',
  213. f"--username={username or 'root'}",
  214. f'--command={command}',
  215. 'test',
  216. ],
  217. env={'PGPASSWORD': password},
  218. )
  219. def run_mariadb_command(command, config, use_restore_options=False, binary_name='mariadb'):
  220. (hostname, port, username, password) = get_connection_params(
  221. config[f'{binary_name}_databases'][0], use_restore_options
  222. )
  223. subprocess.check_call(
  224. [
  225. f'/usr/bin/{binary_name}',
  226. f'--host={hostname}',
  227. f'--port={port or 3306}',
  228. f'--user={username}',
  229. f'--execute={command}',
  230. 'test',
  231. ],
  232. env={'MYSQL_PWD': password},
  233. )
  234. def get_mongodb_database_client(config, use_restore_options=False):
  235. (hostname, port, username, password) = get_connection_params(
  236. config['mongodb_databases'][0], use_restore_options
  237. )
  238. return pymongo.MongoClient(f'mongodb://{username}:{password}@{hostname}:{port or 27017}').test
  239. def run_sqlite_command(command, config, use_restore_options=False):
  240. database = config['sqlite_databases'][0]
  241. path = (database.get('restore_path') if use_restore_options else None) or database.get('path')
  242. subprocess.check_call(
  243. [
  244. '/usr/bin/sqlite3',
  245. path,
  246. command,
  247. '.exit',
  248. ],
  249. )
  250. DEFAULT_HOOK_NAMES = {'postgresql', 'mariadb', 'mysql', 'mongodb', 'sqlite'}
  251. def create_test_tables(config, use_restore_options=False):
  252. '''
  253. Create test tables for borgmatic to dump and backup.
  254. '''
  255. command = 'create table test{id} (thing int); insert into test{id} values (1);'
  256. if 'postgresql_databases' in config:
  257. run_postgresql_command(command.format(id=1), config, use_restore_options)
  258. if 'mariadb_databases' in config:
  259. run_mariadb_command(command.format(id=2), config, use_restore_options)
  260. if 'mysql_databases' in config:
  261. run_mariadb_command(command.format(id=3), config, use_restore_options, binary_name='mysql')
  262. if 'mongodb_databases' in config:
  263. get_mongodb_database_client(config, use_restore_options)['test4'].insert_one({'thing': 1})
  264. if 'sqlite_databases' in config:
  265. run_sqlite_command(command.format(id=5), config, use_restore_options)
  266. def drop_test_tables(config, use_restore_options=False):
  267. '''
  268. Drop the test tables in preparation for borgmatic restoring them.
  269. '''
  270. command = 'drop table if exists test{id};'
  271. if 'postgresql_databases' in config:
  272. run_postgresql_command(command.format(id=1), config, use_restore_options)
  273. if 'mariadb_databases' in config:
  274. run_mariadb_command(command.format(id=2), config, use_restore_options)
  275. if 'mysql_databases' in config:
  276. run_mariadb_command(command.format(id=3), config, use_restore_options, binary_name='mysql')
  277. if 'mongodb_databases' in config:
  278. get_mongodb_database_client(config, use_restore_options)['test4'].drop()
  279. if 'sqlite_databases' in config:
  280. run_sqlite_command(command.format(id=5), config, use_restore_options)
  281. def select_test_tables(config, use_restore_options=False):
  282. '''
  283. Select the test tables to make sure they exist.
  284. Raise if the expected tables cannot be selected, for instance if a restore hasn't worked as
  285. expected.
  286. '''
  287. command = 'select count(*) from test{id};'
  288. if 'postgresql_databases' in config:
  289. run_postgresql_command(command.format(id=1), config, use_restore_options)
  290. if 'mariadb_databases' in config:
  291. run_mariadb_command(command.format(id=2), config, use_restore_options)
  292. if 'mysql_databases' in config:
  293. run_mariadb_command(command.format(id=3), config, use_restore_options, binary_name='mysql')
  294. if 'mongodb_databases' in config:
  295. assert (
  296. get_mongodb_database_client(config, use_restore_options)['test4'].count_documents(
  297. filter={}
  298. )
  299. > 0
  300. )
  301. if 'sqlite_databases' in config:
  302. run_sqlite_command(command.format(id=5), config, use_restore_options)
  303. def test_database_dump_and_restore():
  304. # Create a Borg repository.
  305. temporary_directory = tempfile.mkdtemp()
  306. repository_path = os.path.join(temporary_directory, 'test.borg')
  307. # Write out a special file to ensure that it gets properly excluded and Borg doesn't hang on it.
  308. os.mkfifo(os.path.join(temporary_directory, 'special_file'))
  309. original_working_directory = os.getcwd()
  310. try:
  311. config_path = os.path.join(temporary_directory, 'test.yaml')
  312. config = write_configuration(
  313. temporary_directory, config_path, repository_path, temporary_directory
  314. )
  315. create_test_tables(config)
  316. select_test_tables(config)
  317. subprocess.check_call(
  318. [
  319. 'borgmatic',
  320. '-v',
  321. '2',
  322. '--config',
  323. config_path,
  324. 'repo-create',
  325. '--encryption',
  326. 'repokey',
  327. ]
  328. )
  329. # Run borgmatic to generate a backup archive including database dumps.
  330. subprocess.check_call(['borgmatic', 'create', '--config', config_path, '-v', '2'])
  331. # Get the created archive name.
  332. output = subprocess.check_output(
  333. ['borgmatic', '--config', config_path, 'list', '--json']
  334. ).decode(sys.stdout.encoding)
  335. parsed_output = json.loads(output)
  336. assert len(parsed_output) == 1
  337. assert len(parsed_output[0]['archives']) == 1
  338. archive_name = parsed_output[0]['archives'][0]['archive']
  339. # Restore the databases from the archive.
  340. drop_test_tables(config)
  341. subprocess.check_call(
  342. ['borgmatic', '-v', '2', '--config', config_path, 'restore', '--archive', archive_name]
  343. )
  344. # Ensure the test tables have actually been restored.
  345. select_test_tables(config)
  346. finally:
  347. os.chdir(original_working_directory)
  348. shutil.rmtree(temporary_directory)
  349. drop_test_tables(config)
  350. def test_database_dump_and_restore_with_restore_cli_flags():
  351. # Create a Borg repository.
  352. temporary_directory = tempfile.mkdtemp()
  353. repository_path = os.path.join(temporary_directory, 'test.borg')
  354. original_working_directory = os.getcwd()
  355. try:
  356. config_path = os.path.join(temporary_directory, 'test.yaml')
  357. config = write_simple_custom_restore_configuration(
  358. temporary_directory, config_path, repository_path, temporary_directory
  359. )
  360. create_test_tables(config)
  361. select_test_tables(config)
  362. subprocess.check_call(
  363. [
  364. 'borgmatic',
  365. '-v',
  366. '2',
  367. '--config',
  368. config_path,
  369. 'repo-create',
  370. '--encryption',
  371. 'repokey',
  372. ]
  373. )
  374. # Run borgmatic to generate a backup archive including a database dump.
  375. subprocess.check_call(['borgmatic', 'create', '--config', config_path, '-v', '2'])
  376. # Get the created archive name.
  377. output = subprocess.check_output(
  378. ['borgmatic', '--config', config_path, 'list', '--json']
  379. ).decode(sys.stdout.encoding)
  380. parsed_output = json.loads(output)
  381. assert len(parsed_output) == 1
  382. assert len(parsed_output[0]['archives']) == 1
  383. archive_name = parsed_output[0]['archives'][0]['archive']
  384. # Restore the database from the archive.
  385. drop_test_tables(config)
  386. subprocess.check_call(
  387. [
  388. 'borgmatic',
  389. '-v',
  390. '2',
  391. '--config',
  392. config_path,
  393. 'restore',
  394. '--archive',
  395. archive_name,
  396. '--hostname',
  397. 'postgresql2',
  398. '--port',
  399. '5433',
  400. '--password',
  401. 'test2',
  402. ]
  403. )
  404. # Ensure the test tables have actually been restored. But first modify the config to contain
  405. # the altered restore values from the borgmatic command above. This ensures that the test
  406. # tables are selected from the correct database.
  407. database = config['postgresql_databases'][0]
  408. database['restore_hostname'] = 'postgresql2'
  409. database['restore_port'] = '5433'
  410. database['restore_password'] = 'test2'
  411. select_test_tables(config, use_restore_options=True)
  412. finally:
  413. os.chdir(original_working_directory)
  414. shutil.rmtree(temporary_directory)
  415. drop_test_tables(config)
  416. drop_test_tables(config, use_restore_options=True)
  417. def test_database_dump_and_restore_with_restore_configuration_options():
  418. # Create a Borg repository.
  419. temporary_directory = tempfile.mkdtemp()
  420. repository_path = os.path.join(temporary_directory, 'test.borg')
  421. original_working_directory = os.getcwd()
  422. try:
  423. config_path = os.path.join(temporary_directory, 'test.yaml')
  424. config = write_custom_restore_configuration(
  425. temporary_directory, config_path, repository_path, temporary_directory
  426. )
  427. create_test_tables(config)
  428. select_test_tables(config)
  429. subprocess.check_call(
  430. [
  431. 'borgmatic',
  432. '-v',
  433. '2',
  434. '--config',
  435. config_path,
  436. 'repo-create',
  437. '--encryption',
  438. 'repokey',
  439. ]
  440. )
  441. # Run borgmatic to generate a backup archive including a database dump.
  442. subprocess.check_call(['borgmatic', 'create', '--config', config_path, '-v', '2'])
  443. # Get the created archive name.
  444. output = subprocess.check_output(
  445. ['borgmatic', '--config', config_path, 'list', '--json']
  446. ).decode(sys.stdout.encoding)
  447. parsed_output = json.loads(output)
  448. assert len(parsed_output) == 1
  449. assert len(parsed_output[0]['archives']) == 1
  450. archive_name = parsed_output[0]['archives'][0]['archive']
  451. # Restore the database from the archive.
  452. drop_test_tables(config)
  453. subprocess.check_call(
  454. ['borgmatic', '-v', '2', '--config', config_path, 'restore', '--archive', archive_name]
  455. )
  456. # Ensure the test tables have actually been restored.
  457. select_test_tables(config, use_restore_options=True)
  458. finally:
  459. os.chdir(original_working_directory)
  460. shutil.rmtree(temporary_directory)
  461. drop_test_tables(config)
  462. drop_test_tables(config, use_restore_options=True)
  463. def test_database_dump_and_restore_with_directory_format():
  464. # Create a Borg repository.
  465. temporary_directory = tempfile.mkdtemp()
  466. repository_path = os.path.join(temporary_directory, 'test.borg')
  467. original_working_directory = os.getcwd()
  468. try:
  469. config_path = os.path.join(temporary_directory, 'test.yaml')
  470. config = write_configuration(
  471. temporary_directory,
  472. config_path,
  473. repository_path,
  474. temporary_directory,
  475. postgresql_dump_format='directory',
  476. mongodb_dump_format='directory',
  477. )
  478. create_test_tables(config)
  479. select_test_tables(config)
  480. subprocess.check_call(
  481. [
  482. 'borgmatic',
  483. '-v',
  484. '2',
  485. '--config',
  486. config_path,
  487. 'repo-create',
  488. '--encryption',
  489. 'repokey',
  490. ]
  491. )
  492. # Run borgmatic to generate a backup archive including a database dump.
  493. subprocess.check_call(['borgmatic', 'create', '--config', config_path, '-v', '2'])
  494. # Restore the database from the archive.
  495. drop_test_tables(config)
  496. subprocess.check_call(
  497. ['borgmatic', '--config', config_path, 'restore', '--archive', 'latest']
  498. )
  499. # Ensure the test tables have actually been restored.
  500. select_test_tables(config)
  501. finally:
  502. os.chdir(original_working_directory)
  503. shutil.rmtree(temporary_directory)
  504. drop_test_tables(config)
  505. def test_database_dump_with_error_causes_borgmatic_to_exit():
  506. # Create a Borg repository.
  507. temporary_directory = tempfile.mkdtemp()
  508. repository_path = os.path.join(temporary_directory, 'test.borg')
  509. original_working_directory = os.getcwd()
  510. try:
  511. config_path = os.path.join(temporary_directory, 'test.yaml')
  512. write_configuration(temporary_directory, config_path, repository_path, temporary_directory)
  513. subprocess.check_call(
  514. [
  515. 'borgmatic',
  516. '-v',
  517. '2',
  518. '--config',
  519. config_path,
  520. 'repo-create',
  521. '--encryption',
  522. 'repokey',
  523. ]
  524. )
  525. # Run borgmatic with a config override such that the database dump fails.
  526. with pytest.raises(subprocess.CalledProcessError):
  527. subprocess.check_call(
  528. [
  529. 'borgmatic',
  530. 'create',
  531. '--config',
  532. config_path,
  533. '-v',
  534. '2',
  535. '--override',
  536. "hooks.postgresql_databases=[{'name': 'nope'}]", # noqa: FS003
  537. ]
  538. )
  539. finally:
  540. os.chdir(original_working_directory)
  541. shutil.rmtree(temporary_directory)