repository.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import os
  2. import shutil
  3. import sys
  4. import tempfile
  5. from unittest.mock import patch
  6. from ..hashindex import NSIndex
  7. from ..helpers import Location, IntegrityError
  8. from ..locking import Lock, LockFailed
  9. from ..remote import RemoteRepository, InvalidRPCMethod
  10. from ..repository import Repository, LoggedIO, TAG_DELETE, MAX_DATA_SIZE
  11. from . import BaseTestCase
  12. from .hashindex import H
  13. UNSPECIFIED = object() # for default values where we can't use None
  14. class RepositoryTestCaseBase(BaseTestCase):
  15. key_size = 32
  16. exclusive = True
  17. def open(self, create=False, exclusive=UNSPECIFIED):
  18. if exclusive is UNSPECIFIED:
  19. exclusive = self.exclusive
  20. return Repository(os.path.join(self.tmppath, 'repository'), exclusive=exclusive, create=create)
  21. def setUp(self):
  22. self.tmppath = tempfile.mkdtemp()
  23. self.repository = self.open(create=True)
  24. self.repository.__enter__()
  25. def tearDown(self):
  26. self.repository.close()
  27. shutil.rmtree(self.tmppath)
  28. def reopen(self, exclusive=UNSPECIFIED):
  29. if self.repository:
  30. self.repository.close()
  31. self.repository = self.open(exclusive=exclusive)
  32. class RepositoryTestCase(RepositoryTestCaseBase):
  33. def test1(self):
  34. for x in range(100):
  35. self.repository.put(H(x), b'SOMEDATA')
  36. key50 = H(50)
  37. self.assert_equal(self.repository.get(key50), b'SOMEDATA')
  38. self.repository.delete(key50)
  39. self.assert_raises(Repository.ObjectNotFound, lambda: self.repository.get(key50))
  40. self.repository.commit()
  41. self.repository.close()
  42. with self.open() as repository2:
  43. self.assert_raises(Repository.ObjectNotFound, lambda: repository2.get(key50))
  44. for x in range(100):
  45. if x == 50:
  46. continue
  47. self.assert_equal(repository2.get(H(x)), b'SOMEDATA')
  48. def test2(self):
  49. """Test multiple sequential transactions
  50. """
  51. self.repository.put(H(0), b'foo')
  52. self.repository.put(H(1), b'foo')
  53. self.repository.commit()
  54. self.repository.delete(H(0))
  55. self.repository.put(H(1), b'bar')
  56. self.repository.commit()
  57. self.assert_equal(self.repository.get(H(1)), b'bar')
  58. def test_consistency(self):
  59. """Test cache consistency
  60. """
  61. self.repository.put(H(0), b'foo')
  62. self.assert_equal(self.repository.get(H(0)), b'foo')
  63. self.repository.put(H(0), b'foo2')
  64. self.assert_equal(self.repository.get(H(0)), b'foo2')
  65. self.repository.put(H(0), b'bar')
  66. self.assert_equal(self.repository.get(H(0)), b'bar')
  67. self.repository.delete(H(0))
  68. self.assert_raises(Repository.ObjectNotFound, lambda: self.repository.get(H(0)))
  69. def test_consistency2(self):
  70. """Test cache consistency2
  71. """
  72. self.repository.put(H(0), b'foo')
  73. self.assert_equal(self.repository.get(H(0)), b'foo')
  74. self.repository.commit()
  75. self.repository.put(H(0), b'foo2')
  76. self.assert_equal(self.repository.get(H(0)), b'foo2')
  77. self.repository.rollback()
  78. self.assert_equal(self.repository.get(H(0)), b'foo')
  79. def test_overwrite_in_same_transaction(self):
  80. """Test cache consistency2
  81. """
  82. self.repository.put(H(0), b'foo')
  83. self.repository.put(H(0), b'foo2')
  84. self.repository.commit()
  85. self.assert_equal(self.repository.get(H(0)), b'foo2')
  86. def test_single_kind_transactions(self):
  87. # put
  88. self.repository.put(H(0), b'foo')
  89. self.repository.commit()
  90. self.repository.close()
  91. # replace
  92. self.repository = self.open()
  93. with self.repository:
  94. self.repository.put(H(0), b'bar')
  95. self.repository.commit()
  96. # delete
  97. self.repository = self.open()
  98. with self.repository:
  99. self.repository.delete(H(0))
  100. self.repository.commit()
  101. def test_list(self):
  102. for x in range(100):
  103. self.repository.put(H(x), b'SOMEDATA')
  104. all = self.repository.list()
  105. self.assert_equal(len(all), 100)
  106. first_half = self.repository.list(limit=50)
  107. self.assert_equal(len(first_half), 50)
  108. self.assert_equal(first_half, all[:50])
  109. second_half = self.repository.list(marker=first_half[-1])
  110. self.assert_equal(len(second_half), 50)
  111. self.assert_equal(second_half, all[50:])
  112. self.assert_equal(len(self.repository.list(limit=50)), 50)
  113. def test_max_data_size(self):
  114. max_data = b'x' * MAX_DATA_SIZE
  115. self.repository.put(H(0), max_data)
  116. self.assert_equal(self.repository.get(H(0)), max_data)
  117. self.assert_raises(IntegrityError,
  118. lambda: self.repository.put(H(1), max_data + b'x'))
  119. class RepositoryCommitTestCase(RepositoryTestCaseBase):
  120. def add_keys(self):
  121. self.repository.put(H(0), b'foo')
  122. self.repository.put(H(1), b'bar')
  123. self.repository.put(H(3), b'bar')
  124. self.repository.commit()
  125. self.repository.put(H(1), b'bar2')
  126. self.repository.put(H(2), b'boo')
  127. self.repository.delete(H(3))
  128. def test_replay_of_missing_index(self):
  129. self.add_keys()
  130. for name in os.listdir(self.repository.path):
  131. if name.startswith('index.'):
  132. os.unlink(os.path.join(self.repository.path, name))
  133. self.reopen()
  134. with self.repository:
  135. self.assert_equal(len(self.repository), 3)
  136. self.assert_equal(self.repository.check(), True)
  137. def test_crash_before_compact_segments(self):
  138. self.add_keys()
  139. self.repository.compact_segments = None
  140. try:
  141. self.repository.commit()
  142. except TypeError:
  143. pass
  144. self.reopen()
  145. with self.repository:
  146. self.assert_equal(len(self.repository), 3)
  147. self.assert_equal(self.repository.check(), True)
  148. def test_crash_before_write_index(self):
  149. self.add_keys()
  150. self.repository.write_index = None
  151. try:
  152. self.repository.commit()
  153. except TypeError:
  154. pass
  155. self.reopen()
  156. with self.repository:
  157. self.assert_equal(len(self.repository), 3)
  158. self.assert_equal(self.repository.check(), True)
  159. def test_replay_lock_upgrade_old(self):
  160. self.add_keys()
  161. for name in os.listdir(self.repository.path):
  162. if name.startswith('index.'):
  163. os.unlink(os.path.join(self.repository.path, name))
  164. with patch.object(Lock, 'upgrade', side_effect=LockFailed) as upgrade:
  165. self.reopen(exclusive=None) # simulate old client that always does lock upgrades
  166. with self.repository:
  167. # the repo is only locked by a shared read lock, but to replay segments,
  168. # we need an exclusive write lock - check if the lock gets upgraded.
  169. self.assert_raises(LockFailed, lambda: len(self.repository))
  170. upgrade.assert_called_once_with()
  171. def test_replay_lock_upgrade(self):
  172. self.add_keys()
  173. for name in os.listdir(self.repository.path):
  174. if name.startswith('index.'):
  175. os.unlink(os.path.join(self.repository.path, name))
  176. with patch.object(Lock, 'upgrade', side_effect=LockFailed) as upgrade:
  177. self.reopen(exclusive=False) # current client usually does not do lock upgrade, except for replay
  178. with self.repository:
  179. # the repo is only locked by a shared read lock, but to replay segments,
  180. # we need an exclusive write lock - check if the lock gets upgraded.
  181. self.assert_raises(LockFailed, lambda: len(self.repository))
  182. upgrade.assert_called_once_with()
  183. def test_crash_before_deleting_compacted_segments(self):
  184. self.add_keys()
  185. self.repository.io.delete_segment = None
  186. try:
  187. self.repository.commit()
  188. except TypeError:
  189. pass
  190. self.reopen()
  191. with self.repository:
  192. self.assert_equal(len(self.repository), 3)
  193. self.assert_equal(self.repository.check(), True)
  194. self.assert_equal(len(self.repository), 3)
  195. def test_ignores_commit_tag_in_data(self):
  196. self.repository.put(H(0), LoggedIO.COMMIT)
  197. self.reopen()
  198. with self.repository:
  199. io = self.repository.io
  200. assert not io.is_committed_segment(io.get_latest_segment())
  201. def test_moved_deletes_are_tracked(self):
  202. self.repository.put(H(1), b'1')
  203. self.repository.put(H(2), b'2')
  204. self.repository.commit()
  205. self.repository.delete(H(1))
  206. self.repository.commit()
  207. last_segment = self.repository.io.get_latest_segment()
  208. num_deletes = 0
  209. for tag, key, offset, data in self.repository.io.iter_objects(last_segment, include_data=True):
  210. if tag == TAG_DELETE:
  211. assert key == H(1)
  212. num_deletes += 1
  213. assert num_deletes == 1
  214. assert last_segment in self.repository.compact
  215. self.repository.put(H(3), b'3')
  216. self.repository.commit()
  217. assert last_segment not in self.repository.compact
  218. assert not self.repository.io.segment_exists(last_segment)
  219. last_segment = self.repository.io.get_latest_segment()
  220. for tag, key, offset in self.repository.io.iter_objects(last_segment):
  221. assert tag != TAG_DELETE
  222. class RepositoryAppendOnlyTestCase(RepositoryTestCaseBase):
  223. def open(self, create=False):
  224. return Repository(os.path.join(self.tmppath, 'repository'), exclusive=True, create=create, append_only=True)
  225. def test_destroy_append_only(self):
  226. # Can't destroy append only repo (via the API)
  227. with self.assert_raises(ValueError):
  228. self.repository.destroy()
  229. assert self.repository.append_only
  230. def test_append_only(self):
  231. def segments_in_repository():
  232. return len(list(self.repository.io.segment_iterator()))
  233. self.repository.put(H(0), b'foo')
  234. self.repository.commit()
  235. self.repository.append_only = False
  236. assert segments_in_repository() == 1
  237. self.repository.put(H(0), b'foo')
  238. self.repository.commit()
  239. # normal: compact squashes the data together, only one segment
  240. assert segments_in_repository() == 1
  241. self.repository.append_only = True
  242. assert segments_in_repository() == 1
  243. self.repository.put(H(0), b'foo')
  244. self.repository.commit()
  245. # append only: does not compact, only new segments written
  246. assert segments_in_repository() == 2
  247. class RepositoryCheckTestCase(RepositoryTestCaseBase):
  248. def list_indices(self):
  249. return [name for name in os.listdir(os.path.join(self.tmppath, 'repository')) if name.startswith('index.')]
  250. def check(self, repair=False, status=True):
  251. self.assert_equal(self.repository.check(repair=repair), status)
  252. # Make sure no tmp files are left behind
  253. self.assert_equal([name for name in os.listdir(os.path.join(self.tmppath, 'repository')) if 'tmp' in name], [], 'Found tmp files')
  254. def get_objects(self, *ids):
  255. for id_ in ids:
  256. self.repository.get(H(id_))
  257. def add_objects(self, segments):
  258. for ids in segments:
  259. for id_ in ids:
  260. self.repository.put(H(id_), b'data')
  261. self.repository.commit()
  262. def get_head(self):
  263. return sorted(int(n) for n in os.listdir(os.path.join(self.tmppath, 'repository', 'data', '0')) if n.isdigit())[-1]
  264. def open_index(self):
  265. return NSIndex.read(os.path.join(self.tmppath, 'repository', 'index.{}'.format(self.get_head())))
  266. def corrupt_object(self, id_):
  267. idx = self.open_index()
  268. segment, offset = idx[H(id_)]
  269. with open(os.path.join(self.tmppath, 'repository', 'data', '0', str(segment)), 'r+b') as fd:
  270. fd.seek(offset)
  271. fd.write(b'BOOM')
  272. def delete_segment(self, segment):
  273. os.unlink(os.path.join(self.tmppath, 'repository', 'data', '0', str(segment)))
  274. def delete_index(self):
  275. os.unlink(os.path.join(self.tmppath, 'repository', 'index.{}'.format(self.get_head())))
  276. def rename_index(self, new_name):
  277. os.rename(os.path.join(self.tmppath, 'repository', 'index.{}'.format(self.get_head())),
  278. os.path.join(self.tmppath, 'repository', new_name))
  279. def list_objects(self):
  280. return set(int(key) for key in self.repository.list())
  281. def test_repair_corrupted_segment(self):
  282. self.add_objects([[1, 2, 3], [4, 5], [6]])
  283. self.assert_equal(set([1, 2, 3, 4, 5, 6]), self.list_objects())
  284. self.check(status=True)
  285. self.corrupt_object(5)
  286. self.assert_raises(IntegrityError, lambda: self.get_objects(5))
  287. self.repository.rollback()
  288. # Make sure a regular check does not repair anything
  289. self.check(status=False)
  290. self.check(status=False)
  291. # Make sure a repair actually repairs the repo
  292. self.check(repair=True, status=True)
  293. self.get_objects(4)
  294. self.check(status=True)
  295. self.assert_equal(set([1, 2, 3, 4, 6]), self.list_objects())
  296. def test_repair_missing_segment(self):
  297. self.add_objects([[1, 2, 3], [4, 5, 6]])
  298. self.assert_equal(set([1, 2, 3, 4, 5, 6]), self.list_objects())
  299. self.check(status=True)
  300. self.delete_segment(1)
  301. self.repository.rollback()
  302. self.check(repair=True, status=True)
  303. self.assert_equal(set([1, 2, 3]), self.list_objects())
  304. def test_repair_missing_commit_segment(self):
  305. self.add_objects([[1, 2, 3], [4, 5, 6]])
  306. self.delete_segment(1)
  307. self.assert_raises(Repository.ObjectNotFound, lambda: self.get_objects(4))
  308. self.assert_equal(set([1, 2, 3]), self.list_objects())
  309. def test_repair_corrupted_commit_segment(self):
  310. self.add_objects([[1, 2, 3], [4, 5, 6]])
  311. with open(os.path.join(self.tmppath, 'repository', 'data', '0', '1'), 'r+b') as fd:
  312. fd.seek(-1, os.SEEK_END)
  313. fd.write(b'X')
  314. self.assert_raises(Repository.ObjectNotFound, lambda: self.get_objects(4))
  315. self.check(status=True)
  316. self.get_objects(3)
  317. self.assert_equal(set([1, 2, 3]), self.list_objects())
  318. def test_repair_no_commits(self):
  319. self.add_objects([[1, 2, 3]])
  320. with open(os.path.join(self.tmppath, 'repository', 'data', '0', '0'), 'r+b') as fd:
  321. fd.seek(-1, os.SEEK_END)
  322. fd.write(b'X')
  323. self.assert_raises(Repository.CheckNeeded, lambda: self.get_objects(4))
  324. self.check(status=False)
  325. self.check(status=False)
  326. self.assert_equal(self.list_indices(), ['index.0'])
  327. self.check(repair=True, status=True)
  328. self.assert_equal(self.list_indices(), ['index.1'])
  329. self.check(status=True)
  330. self.get_objects(3)
  331. self.assert_equal(set([1, 2, 3]), self.list_objects())
  332. def test_repair_missing_index(self):
  333. self.add_objects([[1, 2, 3], [4, 5, 6]])
  334. self.delete_index()
  335. self.check(status=True)
  336. self.get_objects(4)
  337. self.assert_equal(set([1, 2, 3, 4, 5, 6]), self.list_objects())
  338. def test_repair_index_too_new(self):
  339. self.add_objects([[1, 2, 3], [4, 5, 6]])
  340. self.assert_equal(self.list_indices(), ['index.1'])
  341. self.rename_index('index.100')
  342. self.check(status=True)
  343. self.assert_equal(self.list_indices(), ['index.1'])
  344. self.get_objects(4)
  345. self.assert_equal(set([1, 2, 3, 4, 5, 6]), self.list_objects())
  346. def test_crash_before_compact(self):
  347. self.repository.put(H(0), b'data')
  348. self.repository.put(H(0), b'data2')
  349. # Simulate a crash before compact
  350. with patch.object(Repository, 'compact_segments') as compact:
  351. self.repository.commit()
  352. compact.assert_called_once_with(save_space=False)
  353. self.reopen()
  354. with self.repository:
  355. self.check(repair=True)
  356. self.assert_equal(self.repository.get(H(0)), b'data2')
  357. class RemoteRepositoryTestCase(RepositoryTestCase):
  358. def open(self, create=False):
  359. return RemoteRepository(Location('__testsuite__:' + os.path.join(self.tmppath, 'repository')),
  360. exclusive=True, create=create)
  361. def test_invalid_rpc(self):
  362. self.assert_raises(InvalidRPCMethod, lambda: self.repository.call('__init__', None))
  363. def test_ssh_cmd(self):
  364. assert self.repository.ssh_cmd(Location('example.com:foo')) == ['ssh', 'example.com']
  365. assert self.repository.ssh_cmd(Location('ssh://example.com/foo')) == ['ssh', 'example.com']
  366. assert self.repository.ssh_cmd(Location('ssh://user@example.com/foo')) == ['ssh', 'user@example.com']
  367. assert self.repository.ssh_cmd(Location('ssh://user@example.com:1234/foo')) == ['ssh', '-p', '1234', 'user@example.com']
  368. os.environ['BORG_RSH'] = 'ssh --foo'
  369. assert self.repository.ssh_cmd(Location('example.com:foo')) == ['ssh', '--foo', 'example.com']
  370. def test_borg_cmd(self):
  371. class MockArgs:
  372. remote_path = 'borg'
  373. umask = 0o077
  374. assert self.repository.borg_cmd(None, testing=True) == [sys.executable, '-m', 'borg.archiver', 'serve']
  375. args = MockArgs()
  376. # note: test logger is on info log level, so --info gets added automagically
  377. assert self.repository.borg_cmd(args, testing=False) == ['borg', 'serve', '--umask=077', '--info']
  378. args.remote_path = 'borg-0.28.2'
  379. assert self.repository.borg_cmd(args, testing=False) == ['borg-0.28.2', 'serve', '--umask=077', '--info']
  380. class RemoteRepositoryCheckTestCase(RepositoryCheckTestCase):
  381. def open(self, create=False):
  382. return RemoteRepository(Location('__testsuite__:' + os.path.join(self.tmppath, 'repository')),
  383. exclusive=True, create=create)
  384. def test_crash_before_compact(self):
  385. # skip this test, we can't mock-patch a Repository class in another process!
  386. pass