test_borgmatic.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. import logging
  2. import subprocess
  3. import time
  4. from flexmock import flexmock
  5. import borgmatic.hooks.command
  6. from borgmatic.commands import borgmatic as module
  7. def test_run_configuration_runs_actions_for_each_repository():
  8. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  9. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  10. expected_results = [flexmock(), flexmock()]
  11. flexmock(module).should_receive('run_actions').and_return(expected_results[:1]).and_return(
  12. expected_results[1:]
  13. )
  14. config = {'location': {'repositories': ['foo', 'bar']}}
  15. arguments = {'global': flexmock(monitoring_verbosity=1)}
  16. results = list(module.run_configuration('test.yaml', config, arguments))
  17. assert results == expected_results
  18. def test_run_configuration_with_invalid_borg_version_errors():
  19. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  20. flexmock(module.borg_version).should_receive('local_borg_version').and_raise(ValueError)
  21. flexmock(module.command).should_receive('execute_hook').never()
  22. flexmock(module.dispatch).should_receive('call_hooks').never()
  23. flexmock(module).should_receive('run_actions').never()
  24. config = {'location': {'repositories': ['foo']}}
  25. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'prune': flexmock()}
  26. list(module.run_configuration('test.yaml', config, arguments))
  27. def test_run_configuration_logs_monitor_start_error():
  28. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  29. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  30. flexmock(module.dispatch).should_receive('call_hooks').and_raise(OSError).and_return(
  31. None
  32. ).and_return(None)
  33. expected_results = [flexmock()]
  34. flexmock(module).should_receive('log_error_records').and_return(expected_results)
  35. flexmock(module).should_receive('run_actions').never()
  36. config = {'location': {'repositories': ['foo']}}
  37. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  38. results = list(module.run_configuration('test.yaml', config, arguments))
  39. assert results == expected_results
  40. def test_run_configuration_bails_for_monitor_start_soft_failure():
  41. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  42. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  43. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  44. flexmock(module.dispatch).should_receive('call_hooks').and_raise(error)
  45. flexmock(module).should_receive('log_error_records').never()
  46. flexmock(module).should_receive('run_actions').never()
  47. config = {'location': {'repositories': ['foo']}}
  48. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  49. results = list(module.run_configuration('test.yaml', config, arguments))
  50. assert results == []
  51. def test_run_configuration_logs_actions_error():
  52. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  53. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  54. flexmock(module.command).should_receive('execute_hook')
  55. flexmock(module.dispatch).should_receive('call_hooks')
  56. expected_results = [flexmock()]
  57. flexmock(module).should_receive('log_error_records').and_return(expected_results)
  58. flexmock(module).should_receive('run_actions').and_raise(OSError)
  59. config = {'location': {'repositories': ['foo']}}
  60. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  61. results = list(module.run_configuration('test.yaml', config, arguments))
  62. assert results == expected_results
  63. def test_run_configuration_bails_for_actions_soft_failure():
  64. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  65. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  66. flexmock(module.dispatch).should_receive('call_hooks')
  67. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  68. flexmock(module).should_receive('run_actions').and_raise(error)
  69. flexmock(module).should_receive('log_error_records').never()
  70. flexmock(module.command).should_receive('considered_soft_failure').and_return(True)
  71. config = {'location': {'repositories': ['foo']}}
  72. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  73. results = list(module.run_configuration('test.yaml', config, arguments))
  74. assert results == []
  75. def test_run_configuration_logs_monitor_finish_error():
  76. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  77. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  78. flexmock(module.dispatch).should_receive('call_hooks').and_return(None).and_return(
  79. None
  80. ).and_raise(OSError)
  81. expected_results = [flexmock()]
  82. flexmock(module).should_receive('log_error_records').and_return(expected_results)
  83. flexmock(module).should_receive('run_actions').and_return([])
  84. config = {'location': {'repositories': ['foo']}}
  85. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  86. results = list(module.run_configuration('test.yaml', config, arguments))
  87. assert results == expected_results
  88. def test_run_configuration_bails_for_monitor_finish_soft_failure():
  89. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  90. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  91. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  92. flexmock(module.dispatch).should_receive('call_hooks').and_return(None).and_return(
  93. None
  94. ).and_raise(error)
  95. flexmock(module).should_receive('log_error_records').never()
  96. flexmock(module).should_receive('run_actions').and_return([])
  97. flexmock(module.command).should_receive('considered_soft_failure').and_return(True)
  98. config = {'location': {'repositories': ['foo']}}
  99. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  100. results = list(module.run_configuration('test.yaml', config, arguments))
  101. assert results == []
  102. def test_run_configuration_logs_on_error_hook_error():
  103. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  104. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  105. flexmock(module.command).should_receive('execute_hook').and_raise(OSError)
  106. expected_results = [flexmock(), flexmock()]
  107. flexmock(module).should_receive('log_error_records').and_return(
  108. expected_results[:1]
  109. ).and_return(expected_results[1:])
  110. flexmock(module).should_receive('run_actions').and_raise(OSError)
  111. config = {'location': {'repositories': ['foo']}}
  112. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  113. results = list(module.run_configuration('test.yaml', config, arguments))
  114. assert results == expected_results
  115. def test_run_configuration_bails_for_on_error_hook_soft_failure():
  116. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  117. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  118. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  119. flexmock(module.command).should_receive('execute_hook').and_raise(error)
  120. expected_results = [flexmock()]
  121. flexmock(module).should_receive('log_error_records').and_return(expected_results)
  122. flexmock(module).should_receive('run_actions').and_raise(OSError)
  123. config = {'location': {'repositories': ['foo']}}
  124. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  125. results = list(module.run_configuration('test.yaml', config, arguments))
  126. assert results == expected_results
  127. def test_run_configuration_retries_soft_error():
  128. # Run action first fails, second passes
  129. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  130. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  131. flexmock(module.command).should_receive('execute_hook')
  132. flexmock(module).should_receive('run_actions').and_raise(OSError).and_return([])
  133. flexmock(module).should_receive('log_error_records').and_return([flexmock()]).once()
  134. config = {'location': {'repositories': ['foo']}, 'storage': {'retries': 1}}
  135. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  136. results = list(module.run_configuration('test.yaml', config, arguments))
  137. assert results == []
  138. def test_run_configuration_retries_hard_error():
  139. # Run action fails twice
  140. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  141. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  142. flexmock(module.command).should_receive('execute_hook')
  143. flexmock(module).should_receive('run_actions').and_raise(OSError).times(2)
  144. flexmock(module).should_receive('log_error_records').with_args(
  145. 'foo: Error running actions for repository',
  146. OSError,
  147. levelno=logging.WARNING,
  148. log_command_error_output=True,
  149. ).and_return([flexmock()])
  150. error_logs = [flexmock()]
  151. flexmock(module).should_receive('log_error_records').with_args(
  152. 'foo: Error running actions for repository', OSError,
  153. ).and_return(error_logs)
  154. config = {'location': {'repositories': ['foo']}, 'storage': {'retries': 1}}
  155. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  156. results = list(module.run_configuration('test.yaml', config, arguments))
  157. assert results == error_logs
  158. def test_run_configuration_repos_ordered():
  159. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  160. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  161. flexmock(module.command).should_receive('execute_hook')
  162. flexmock(module).should_receive('run_actions').and_raise(OSError).times(2)
  163. expected_results = [flexmock(), flexmock()]
  164. flexmock(module).should_receive('log_error_records').with_args(
  165. 'foo: Error running actions for repository', OSError
  166. ).and_return(expected_results[:1]).ordered()
  167. flexmock(module).should_receive('log_error_records').with_args(
  168. 'bar: Error running actions for repository', OSError
  169. ).and_return(expected_results[1:]).ordered()
  170. config = {'location': {'repositories': ['foo', 'bar']}}
  171. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  172. results = list(module.run_configuration('test.yaml', config, arguments))
  173. assert results == expected_results
  174. def test_run_configuration_retries_round_robbin():
  175. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  176. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  177. flexmock(module.command).should_receive('execute_hook')
  178. flexmock(module).should_receive('run_actions').and_raise(OSError).times(4)
  179. flexmock(module).should_receive('log_error_records').with_args(
  180. 'foo: Error running actions for repository',
  181. OSError,
  182. levelno=logging.WARNING,
  183. log_command_error_output=True,
  184. ).and_return([flexmock()]).ordered()
  185. flexmock(module).should_receive('log_error_records').with_args(
  186. 'bar: Error running actions for repository',
  187. OSError,
  188. levelno=logging.WARNING,
  189. log_command_error_output=True,
  190. ).and_return([flexmock()]).ordered()
  191. foo_error_logs = [flexmock()]
  192. flexmock(module).should_receive('log_error_records').with_args(
  193. 'foo: Error running actions for repository', OSError
  194. ).and_return(foo_error_logs).ordered()
  195. bar_error_logs = [flexmock()]
  196. flexmock(module).should_receive('log_error_records').with_args(
  197. 'bar: Error running actions for repository', OSError
  198. ).and_return(bar_error_logs).ordered()
  199. config = {'location': {'repositories': ['foo', 'bar']}, 'storage': {'retries': 1}}
  200. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  201. results = list(module.run_configuration('test.yaml', config, arguments))
  202. assert results == foo_error_logs + bar_error_logs
  203. def test_run_configuration_retries_one_passes():
  204. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  205. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  206. flexmock(module.command).should_receive('execute_hook')
  207. flexmock(module).should_receive('run_actions').and_raise(OSError).and_raise(OSError).and_return(
  208. []
  209. ).and_raise(OSError).times(4)
  210. flexmock(module).should_receive('log_error_records').with_args(
  211. 'foo: Error running actions for repository',
  212. OSError,
  213. levelno=logging.WARNING,
  214. log_command_error_output=True,
  215. ).and_return([flexmock()]).ordered()
  216. flexmock(module).should_receive('log_error_records').with_args(
  217. 'bar: Error running actions for repository',
  218. OSError,
  219. levelno=logging.WARNING,
  220. log_command_error_output=True,
  221. ).and_return(flexmock()).ordered()
  222. error_logs = [flexmock()]
  223. flexmock(module).should_receive('log_error_records').with_args(
  224. 'bar: Error running actions for repository', OSError
  225. ).and_return(error_logs).ordered()
  226. config = {'location': {'repositories': ['foo', 'bar']}, 'storage': {'retries': 1}}
  227. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  228. results = list(module.run_configuration('test.yaml', config, arguments))
  229. assert results == error_logs
  230. def test_run_configuration_retry_wait():
  231. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  232. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  233. flexmock(module.command).should_receive('execute_hook')
  234. flexmock(module).should_receive('run_actions').and_raise(OSError).times(4)
  235. flexmock(module).should_receive('log_error_records').with_args(
  236. 'foo: Error running actions for repository',
  237. OSError,
  238. levelno=logging.WARNING,
  239. log_command_error_output=True,
  240. ).and_return([flexmock()]).ordered()
  241. flexmock(time).should_receive('sleep').with_args(10).and_return().ordered()
  242. flexmock(module).should_receive('log_error_records').with_args(
  243. 'foo: Error running actions for repository',
  244. OSError,
  245. levelno=logging.WARNING,
  246. log_command_error_output=True,
  247. ).and_return([flexmock()]).ordered()
  248. flexmock(time).should_receive('sleep').with_args(20).and_return().ordered()
  249. flexmock(module).should_receive('log_error_records').with_args(
  250. 'foo: Error running actions for repository',
  251. OSError,
  252. levelno=logging.WARNING,
  253. log_command_error_output=True,
  254. ).and_return([flexmock()]).ordered()
  255. flexmock(time).should_receive('sleep').with_args(30).and_return().ordered()
  256. error_logs = [flexmock()]
  257. flexmock(module).should_receive('log_error_records').with_args(
  258. 'foo: Error running actions for repository', OSError
  259. ).and_return(error_logs).ordered()
  260. config = {'location': {'repositories': ['foo']}, 'storage': {'retries': 3, 'retry_wait': 10}}
  261. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  262. results = list(module.run_configuration('test.yaml', config, arguments))
  263. assert results == error_logs
  264. def test_run_configuration_retries_timeout_multiple_repos():
  265. flexmock(module).should_receive('verbosity_to_log_level').and_return(logging.INFO)
  266. flexmock(module.borg_version).should_receive('local_borg_version').and_return(flexmock())
  267. flexmock(module.command).should_receive('execute_hook')
  268. flexmock(module).should_receive('run_actions').and_raise(OSError).and_raise(OSError).and_return(
  269. []
  270. ).and_raise(OSError).times(4)
  271. flexmock(module).should_receive('log_error_records').with_args(
  272. 'foo: Error running actions for repository',
  273. OSError,
  274. levelno=logging.WARNING,
  275. log_command_error_output=True,
  276. ).and_return([flexmock()]).ordered()
  277. flexmock(module).should_receive('log_error_records').with_args(
  278. 'bar: Error running actions for repository',
  279. OSError,
  280. levelno=logging.WARNING,
  281. log_command_error_output=True,
  282. ).and_return([flexmock()]).ordered()
  283. # Sleep before retrying foo (and passing)
  284. flexmock(time).should_receive('sleep').with_args(10).and_return().ordered()
  285. # Sleep before retrying bar (and failing)
  286. flexmock(time).should_receive('sleep').with_args(10).and_return().ordered()
  287. error_logs = [flexmock()]
  288. flexmock(module).should_receive('log_error_records').with_args(
  289. 'bar: Error running actions for repository', OSError
  290. ).and_return(error_logs).ordered()
  291. config = {
  292. 'location': {'repositories': ['foo', 'bar']},
  293. 'storage': {'retries': 1, 'retry_wait': 10},
  294. }
  295. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  296. results = list(module.run_configuration('test.yaml', config, arguments))
  297. assert results == error_logs
  298. def test_run_actions_does_not_raise_for_rcreate_action():
  299. flexmock(module).should_receive('add_custom_log_levels')
  300. flexmock(module.logger).answer = lambda message: None
  301. flexmock(module.borg_rcreate).should_receive('create_repository')
  302. arguments = {
  303. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  304. 'rcreate': flexmock(
  305. encryption_mode=flexmock(),
  306. source_repository=flexmock(),
  307. copy_crypt_key=flexmock(),
  308. append_only=flexmock(),
  309. storage_quota=flexmock(),
  310. make_parent_dirs=flexmock(),
  311. ),
  312. }
  313. list(
  314. module.run_actions(
  315. arguments=arguments,
  316. config_filename='test.yaml',
  317. location={'repositories': ['repo']},
  318. storage={},
  319. retention={},
  320. consistency={},
  321. hooks={},
  322. local_path=None,
  323. remote_path=None,
  324. local_borg_version=None,
  325. repository_path='repo',
  326. )
  327. )
  328. def test_run_actions_does_not_raise_for_transfer_action():
  329. flexmock(module).should_receive('add_custom_log_levels')
  330. flexmock(module.logger).answer = lambda message: None
  331. flexmock(module.borg_transfer).should_receive('transfer_archives')
  332. arguments = {
  333. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  334. 'transfer': flexmock(),
  335. }
  336. list(
  337. module.run_actions(
  338. arguments=arguments,
  339. config_filename='test.yaml',
  340. location={'repositories': ['repo']},
  341. storage={},
  342. retention={},
  343. consistency={},
  344. hooks={},
  345. local_path=None,
  346. remote_path=None,
  347. local_borg_version=None,
  348. repository_path='repo',
  349. )
  350. )
  351. def test_run_actions_calls_hooks_for_prune_action():
  352. flexmock(module).should_receive('add_custom_log_levels')
  353. flexmock(module.logger).answer = lambda message: None
  354. flexmock(module.borg_prune).should_receive('prune_archives')
  355. flexmock(module.command).should_receive('execute_hook').times(
  356. 4
  357. ) # Before/after extract and before/after actions.
  358. arguments = {
  359. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  360. 'prune': flexmock(stats=flexmock(), list_archives=flexmock()),
  361. }
  362. list(
  363. module.run_actions(
  364. arguments=arguments,
  365. config_filename='test.yaml',
  366. location={'repositories': ['repo']},
  367. storage={},
  368. retention={},
  369. consistency={},
  370. hooks={},
  371. local_path=None,
  372. remote_path=None,
  373. local_borg_version=None,
  374. repository_path='repo',
  375. )
  376. )
  377. def test_run_actions_calls_hooks_for_compact_action():
  378. flexmock(module).should_receive('add_custom_log_levels')
  379. flexmock(module.logger).answer = lambda message: None
  380. flexmock(module.borg_feature).should_receive('available').and_return(True)
  381. flexmock(module.borg_compact).should_receive('compact_segments')
  382. flexmock(module.command).should_receive('execute_hook').times(
  383. 4
  384. ) # Before/after extract and before/after actions.
  385. arguments = {
  386. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  387. 'compact': flexmock(progress=flexmock(), cleanup_commits=flexmock(), threshold=flexmock()),
  388. }
  389. list(
  390. module.run_actions(
  391. arguments=arguments,
  392. config_filename='test.yaml',
  393. location={'repositories': ['repo']},
  394. storage={},
  395. retention={},
  396. consistency={},
  397. hooks={},
  398. local_path=None,
  399. remote_path=None,
  400. local_borg_version=None,
  401. repository_path='repo',
  402. )
  403. )
  404. def test_run_actions_executes_and_calls_hooks_for_create_action():
  405. flexmock(module).should_receive('add_custom_log_levels')
  406. flexmock(module.logger).answer = lambda message: None
  407. flexmock(module.borg_create).should_receive('create_archive')
  408. flexmock(module.command).should_receive('execute_hook').times(
  409. 4
  410. ) # Before/after extract and before/after actions.
  411. flexmock(module.dispatch).should_receive('call_hooks').and_return({})
  412. flexmock(module.dispatch).should_receive('call_hooks_even_if_unconfigured').and_return({})
  413. arguments = {
  414. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  415. 'create': flexmock(
  416. progress=flexmock(), stats=flexmock(), json=flexmock(), list_files=flexmock()
  417. ),
  418. }
  419. list(
  420. module.run_actions(
  421. arguments=arguments,
  422. config_filename='test.yaml',
  423. location={'repositories': ['repo']},
  424. storage={},
  425. retention={},
  426. consistency={},
  427. hooks={},
  428. local_path=None,
  429. remote_path=None,
  430. local_borg_version=None,
  431. repository_path='repo',
  432. )
  433. )
  434. def test_run_actions_calls_hooks_for_check_action():
  435. flexmock(module).should_receive('add_custom_log_levels')
  436. flexmock(module.logger).answer = lambda message: None
  437. flexmock(module.checks).should_receive('repository_enabled_for_checks').and_return(True)
  438. flexmock(module.borg_check).should_receive('check_archives')
  439. flexmock(module.command).should_receive('execute_hook').times(
  440. 4
  441. ) # Before/after extract and before/after actions.
  442. arguments = {
  443. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  444. 'check': flexmock(
  445. progress=flexmock(), repair=flexmock(), only=flexmock(), force=flexmock()
  446. ),
  447. }
  448. list(
  449. module.run_actions(
  450. arguments=arguments,
  451. config_filename='test.yaml',
  452. location={'repositories': ['repo']},
  453. storage={},
  454. retention={},
  455. consistency={},
  456. hooks={},
  457. local_path=None,
  458. remote_path=None,
  459. local_borg_version=None,
  460. repository_path='repo',
  461. )
  462. )
  463. def test_run_actions_calls_hooks_for_extract_action():
  464. flexmock(module).should_receive('add_custom_log_levels')
  465. flexmock(module.logger).answer = lambda message: None
  466. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  467. flexmock(module.borg_extract).should_receive('extract_archive')
  468. flexmock(module.command).should_receive('execute_hook').times(
  469. 4
  470. ) # Before/after extract and before/after actions.
  471. arguments = {
  472. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  473. 'extract': flexmock(
  474. paths=flexmock(),
  475. progress=flexmock(),
  476. destination=flexmock(),
  477. strip_components=flexmock(),
  478. archive=flexmock(),
  479. repository='repo',
  480. ),
  481. }
  482. list(
  483. module.run_actions(
  484. arguments=arguments,
  485. config_filename='test.yaml',
  486. location={'repositories': ['repo']},
  487. storage={},
  488. retention={},
  489. consistency={},
  490. hooks={},
  491. local_path=None,
  492. remote_path=None,
  493. local_borg_version=None,
  494. repository_path='repo',
  495. )
  496. )
  497. def test_run_actions_does_not_raise_for_export_tar_action():
  498. flexmock(module).should_receive('add_custom_log_levels')
  499. flexmock(module.logger).answer = lambda message: None
  500. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  501. flexmock(module.borg_export_tar).should_receive('export_tar_archive')
  502. arguments = {
  503. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  504. 'export-tar': flexmock(
  505. repository=flexmock(),
  506. archive=flexmock(),
  507. paths=flexmock(),
  508. destination=flexmock(),
  509. tar_filter=flexmock(),
  510. list_files=flexmock(),
  511. strip_components=flexmock(),
  512. ),
  513. }
  514. list(
  515. module.run_actions(
  516. arguments=arguments,
  517. config_filename='test.yaml',
  518. location={'repositories': ['repo']},
  519. storage={},
  520. retention={},
  521. consistency={},
  522. hooks={},
  523. local_path=None,
  524. remote_path=None,
  525. local_borg_version=None,
  526. repository_path='repo',
  527. )
  528. )
  529. def test_run_actions_does_not_raise_for_mount_action():
  530. flexmock(module).should_receive('add_custom_log_levels')
  531. flexmock(module.logger).answer = lambda message: None
  532. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  533. flexmock(module.borg_mount).should_receive('mount_archive')
  534. arguments = {
  535. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  536. 'mount': flexmock(
  537. repository=flexmock(),
  538. archive=flexmock(),
  539. mount_point=flexmock(),
  540. paths=flexmock(),
  541. foreground=flexmock(),
  542. options=flexmock(),
  543. ),
  544. }
  545. list(
  546. module.run_actions(
  547. arguments=arguments,
  548. config_filename='test.yaml',
  549. location={'repositories': ['repo']},
  550. storage={},
  551. retention={},
  552. consistency={},
  553. hooks={},
  554. local_path=None,
  555. remote_path=None,
  556. local_borg_version=None,
  557. repository_path='repo',
  558. )
  559. )
  560. def test_run_actions_does_not_raise_for_rlist_action():
  561. flexmock(module).should_receive('add_custom_log_levels')
  562. flexmock(module.logger).answer = lambda message: None
  563. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  564. flexmock(module.borg_rlist).should_receive('list_repository')
  565. arguments = {
  566. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  567. 'rlist': flexmock(repository=flexmock(), json=flexmock()),
  568. }
  569. list(
  570. module.run_actions(
  571. arguments=arguments,
  572. config_filename='test.yaml',
  573. location={'repositories': ['repo']},
  574. storage={},
  575. retention={},
  576. consistency={},
  577. hooks={},
  578. local_path=None,
  579. remote_path=None,
  580. local_borg_version=None,
  581. repository_path='repo',
  582. )
  583. )
  584. def test_run_actions_does_not_raise_for_list_action():
  585. flexmock(module).should_receive('add_custom_log_levels')
  586. flexmock(module.logger).answer = lambda message: None
  587. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  588. flexmock(module.borg_rlist).should_receive('resolve_archive_name').and_return(flexmock())
  589. flexmock(module.borg_list).should_receive('list_archive')
  590. arguments = {
  591. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  592. 'list': flexmock(repository=flexmock(), archive=flexmock(), json=flexmock()),
  593. }
  594. list(
  595. module.run_actions(
  596. arguments=arguments,
  597. config_filename='test.yaml',
  598. location={'repositories': ['repo']},
  599. storage={},
  600. retention={},
  601. consistency={},
  602. hooks={},
  603. local_path=None,
  604. remote_path=None,
  605. local_borg_version=None,
  606. repository_path='repo',
  607. )
  608. )
  609. def test_run_actions_does_not_raise_for_rinfo_action():
  610. flexmock(module).should_receive('add_custom_log_levels')
  611. flexmock(module.logger).answer = lambda message: None
  612. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  613. flexmock(module.borg_rinfo).should_receive('display_repository_info')
  614. arguments = {
  615. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  616. 'rinfo': flexmock(repository=flexmock(), json=flexmock()),
  617. }
  618. list(
  619. module.run_actions(
  620. arguments=arguments,
  621. config_filename='test.yaml',
  622. location={'repositories': ['repo']},
  623. storage={},
  624. retention={},
  625. consistency={},
  626. hooks={},
  627. local_path=None,
  628. remote_path=None,
  629. local_borg_version=None,
  630. repository_path='repo',
  631. )
  632. )
  633. def test_run_actions_does_not_raise_for_info_action():
  634. flexmock(module).should_receive('add_custom_log_levels')
  635. flexmock(module.logger).answer = lambda message: None
  636. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  637. flexmock(module.borg_rlist).should_receive('resolve_archive_name').and_return(flexmock())
  638. flexmock(module.borg_info).should_receive('display_archives_info')
  639. arguments = {
  640. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  641. 'info': flexmock(repository=flexmock(), archive=flexmock(), json=flexmock()),
  642. }
  643. list(
  644. module.run_actions(
  645. arguments=arguments,
  646. config_filename='test.yaml',
  647. location={'repositories': ['repo']},
  648. storage={},
  649. retention={},
  650. consistency={},
  651. hooks={},
  652. local_path=None,
  653. remote_path=None,
  654. local_borg_version=None,
  655. repository_path='repo',
  656. )
  657. )
  658. def test_run_actions_does_not_raise_for_break_lock_action():
  659. flexmock(module).should_receive('add_custom_log_levels')
  660. flexmock(module.logger).answer = lambda message: None
  661. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  662. flexmock(module.borg_break_lock).should_receive('break_lock')
  663. arguments = {
  664. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  665. 'break-lock': flexmock(repository=flexmock()),
  666. }
  667. list(
  668. module.run_actions(
  669. arguments=arguments,
  670. config_filename='test.yaml',
  671. location={'repositories': ['repo']},
  672. storage={},
  673. retention={},
  674. consistency={},
  675. hooks={},
  676. local_path=None,
  677. remote_path=None,
  678. local_borg_version=None,
  679. repository_path='repo',
  680. )
  681. )
  682. def test_run_actions_does_not_raise_for_borg_action():
  683. flexmock(module).should_receive('add_custom_log_levels')
  684. flexmock(module.logger).answer = lambda message: None
  685. flexmock(module.validate).should_receive('repositories_match').and_return(True)
  686. flexmock(module.borg_rlist).should_receive('resolve_archive_name').and_return(flexmock())
  687. flexmock(module.borg_borg).should_receive('run_arbitrary_borg')
  688. arguments = {
  689. 'global': flexmock(monitoring_verbosity=1, dry_run=False),
  690. 'borg': flexmock(repository=flexmock(), archive=flexmock(), options=flexmock()),
  691. }
  692. list(
  693. module.run_actions(
  694. arguments=arguments,
  695. config_filename='test.yaml',
  696. location={'repositories': ['repo']},
  697. storage={},
  698. retention={},
  699. consistency={},
  700. hooks={},
  701. local_path=None,
  702. remote_path=None,
  703. local_borg_version=None,
  704. repository_path='repo',
  705. )
  706. )
  707. def test_load_configurations_collects_parsed_configurations_and_logs():
  708. configuration = flexmock()
  709. other_configuration = flexmock()
  710. test_expected_logs = [flexmock(), flexmock()]
  711. other_expected_logs = [flexmock(), flexmock()]
  712. flexmock(module.validate).should_receive('parse_configuration').and_return(
  713. configuration, test_expected_logs
  714. ).and_return(other_configuration, other_expected_logs)
  715. configs, logs = tuple(module.load_configurations(('test.yaml', 'other.yaml')))
  716. assert configs == {'test.yaml': configuration, 'other.yaml': other_configuration}
  717. assert logs == test_expected_logs + other_expected_logs
  718. def test_load_configurations_logs_warning_for_permission_error():
  719. flexmock(module.validate).should_receive('parse_configuration').and_raise(PermissionError)
  720. configs, logs = tuple(module.load_configurations(('test.yaml',)))
  721. assert configs == {}
  722. assert {log.levelno for log in logs} == {logging.WARNING}
  723. def test_load_configurations_logs_critical_for_parse_error():
  724. flexmock(module.validate).should_receive('parse_configuration').and_raise(ValueError)
  725. configs, logs = tuple(module.load_configurations(('test.yaml',)))
  726. assert configs == {}
  727. assert {log.levelno for log in logs} == {logging.CRITICAL}
  728. def test_log_record_does_not_raise():
  729. module.log_record(levelno=1, foo='bar', baz='quux')
  730. def test_log_record_with_suppress_does_not_raise():
  731. module.log_record(levelno=1, foo='bar', baz='quux', suppress_log=True)
  732. def test_log_error_records_generates_output_logs_for_message_only():
  733. flexmock(module).should_receive('log_record').replace_with(dict)
  734. logs = tuple(module.log_error_records('Error'))
  735. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  736. def test_log_error_records_generates_output_logs_for_called_process_error():
  737. flexmock(module).should_receive('log_record').replace_with(dict)
  738. flexmock(module.logger).should_receive('getEffectiveLevel').and_return(logging.WARNING)
  739. logs = tuple(
  740. module.log_error_records('Error', subprocess.CalledProcessError(1, 'ls', 'error output'))
  741. )
  742. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  743. assert any(log for log in logs if 'error output' in str(log))
  744. def test_log_error_records_generates_logs_for_value_error():
  745. flexmock(module).should_receive('log_record').replace_with(dict)
  746. logs = tuple(module.log_error_records('Error', ValueError()))
  747. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  748. def test_log_error_records_generates_logs_for_os_error():
  749. flexmock(module).should_receive('log_record').replace_with(dict)
  750. logs = tuple(module.log_error_records('Error', OSError()))
  751. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  752. def test_log_error_records_generates_nothing_for_other_error():
  753. flexmock(module).should_receive('log_record').replace_with(dict)
  754. logs = tuple(module.log_error_records('Error', KeyError()))
  755. assert logs == ()
  756. def test_get_local_path_uses_configuration_value():
  757. assert module.get_local_path({'test.yaml': {'location': {'local_path': 'borg1'}}}) == 'borg1'
  758. def test_get_local_path_without_location_defaults_to_borg():
  759. assert module.get_local_path({'test.yaml': {}}) == 'borg'
  760. def test_get_local_path_without_local_path_defaults_to_borg():
  761. assert module.get_local_path({'test.yaml': {'location': {}}}) == 'borg'
  762. def test_collect_configuration_run_summary_logs_info_for_success():
  763. flexmock(module.command).should_receive('execute_hook').never()
  764. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  765. flexmock(module).should_receive('run_configuration').and_return([])
  766. arguments = {}
  767. logs = tuple(
  768. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  769. )
  770. assert {log.levelno for log in logs} == {logging.INFO}
  771. def test_collect_configuration_run_summary_executes_hooks_for_create():
  772. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  773. flexmock(module).should_receive('run_configuration').and_return([])
  774. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  775. logs = tuple(
  776. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  777. )
  778. assert {log.levelno for log in logs} == {logging.INFO}
  779. def test_collect_configuration_run_summary_logs_info_for_success_with_extract():
  780. flexmock(module.validate).should_receive('guard_single_repository_selected')
  781. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  782. flexmock(module).should_receive('run_configuration').and_return([])
  783. arguments = {'extract': flexmock(repository='repo')}
  784. logs = tuple(
  785. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  786. )
  787. assert {log.levelno for log in logs} == {logging.INFO}
  788. def test_collect_configuration_run_summary_logs_extract_with_repository_error():
  789. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  790. ValueError
  791. )
  792. expected_logs = (flexmock(),)
  793. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  794. arguments = {'extract': flexmock(repository='repo')}
  795. logs = tuple(
  796. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  797. )
  798. assert logs == expected_logs
  799. def test_collect_configuration_run_summary_logs_info_for_success_with_mount():
  800. flexmock(module.validate).should_receive('guard_single_repository_selected')
  801. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  802. flexmock(module).should_receive('run_configuration').and_return([])
  803. arguments = {'mount': flexmock(repository='repo')}
  804. logs = tuple(
  805. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  806. )
  807. assert {log.levelno for log in logs} == {logging.INFO}
  808. def test_collect_configuration_run_summary_logs_mount_with_repository_error():
  809. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  810. ValueError
  811. )
  812. expected_logs = (flexmock(),)
  813. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  814. arguments = {'mount': flexmock(repository='repo')}
  815. logs = tuple(
  816. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  817. )
  818. assert logs == expected_logs
  819. def test_collect_configuration_run_summary_logs_missing_configs_error():
  820. arguments = {'global': flexmock(config_paths=[])}
  821. expected_logs = (flexmock(),)
  822. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  823. logs = tuple(module.collect_configuration_run_summary_logs({}, arguments=arguments))
  824. assert logs == expected_logs
  825. def test_collect_configuration_run_summary_logs_pre_hook_error():
  826. flexmock(module.command).should_receive('execute_hook').and_raise(ValueError)
  827. expected_logs = (flexmock(),)
  828. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  829. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  830. logs = tuple(
  831. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  832. )
  833. assert logs == expected_logs
  834. def test_collect_configuration_run_summary_logs_post_hook_error():
  835. flexmock(module.command).should_receive('execute_hook').and_return(None).and_raise(ValueError)
  836. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  837. flexmock(module).should_receive('run_configuration').and_return([])
  838. expected_logs = (flexmock(),)
  839. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  840. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  841. logs = tuple(
  842. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  843. )
  844. assert expected_logs[0] in logs
  845. def test_collect_configuration_run_summary_logs_for_list_with_archive_and_repository_error():
  846. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  847. ValueError
  848. )
  849. expected_logs = (flexmock(),)
  850. flexmock(module).should_receive('log_error_records').and_return(expected_logs)
  851. arguments = {'list': flexmock(repository='repo', archive='test')}
  852. logs = tuple(
  853. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  854. )
  855. assert logs == expected_logs
  856. def test_collect_configuration_run_summary_logs_info_for_success_with_list():
  857. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  858. flexmock(module).should_receive('run_configuration').and_return([])
  859. arguments = {'list': flexmock(repository='repo', archive=None)}
  860. logs = tuple(
  861. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  862. )
  863. assert {log.levelno for log in logs} == {logging.INFO}
  864. def test_collect_configuration_run_summary_logs_run_configuration_error():
  865. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  866. flexmock(module).should_receive('run_configuration').and_return(
  867. [logging.makeLogRecord(dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg='Error'))]
  868. )
  869. flexmock(module).should_receive('log_error_records').and_return([])
  870. arguments = {}
  871. logs = tuple(
  872. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  873. )
  874. assert {log.levelno for log in logs} == {logging.CRITICAL}
  875. def test_collect_configuration_run_summary_logs_run_umount_error():
  876. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  877. flexmock(module).should_receive('run_configuration').and_return([])
  878. flexmock(module.borg_umount).should_receive('unmount_archive').and_raise(OSError)
  879. flexmock(module).should_receive('log_error_records').and_return(
  880. [logging.makeLogRecord(dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg='Error'))]
  881. )
  882. arguments = {'umount': flexmock(mount_point='/mnt')}
  883. logs = tuple(
  884. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  885. )
  886. assert {log.levelno for log in logs} == {logging.INFO, logging.CRITICAL}
  887. def test_collect_configuration_run_summary_logs_outputs_merged_json_results():
  888. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  889. flexmock(module).should_receive('run_configuration').and_return(['foo', 'bar']).and_return(
  890. ['baz']
  891. )
  892. stdout = flexmock()
  893. stdout.should_receive('write').with_args('["foo", "bar", "baz"]').once()
  894. flexmock(module.sys).stdout = stdout
  895. arguments = {}
  896. tuple(
  897. module.collect_configuration_run_summary_logs(
  898. {'test.yaml': {}, 'test2.yaml': {}}, arguments=arguments
  899. )
  900. )