archiver.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import os
  2. from io import StringIO
  3. import stat
  4. import subprocess
  5. import sys
  6. import shutil
  7. import tempfile
  8. import time
  9. import unittest
  10. from hashlib import sha256
  11. from attic import xattr
  12. from attic.archive import Archive, ChunkBuffer
  13. from attic.archiver import Archiver
  14. from attic.crypto import bytes_to_long, num_aes_blocks
  15. from attic.helpers import Manifest
  16. from attic.remote import RemoteRepository, PathNotAllowed
  17. from attic.repository import Repository
  18. from attic.testsuite import AtticTestCase
  19. from attic.testsuite.mock import patch
  20. try:
  21. import llfuse
  22. has_llfuse = True
  23. except ImportError:
  24. has_llfuse = False
  25. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..')
  26. class changedir:
  27. def __init__(self, dir):
  28. self.dir = dir
  29. def __enter__(self):
  30. self.old = os.getcwd()
  31. os.chdir(self.dir)
  32. def __exit__(self, *args, **kw):
  33. os.chdir(self.old)
  34. class ArchiverTestCaseBase(AtticTestCase):
  35. prefix = ''
  36. def setUp(self):
  37. os.environ['ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'] = '1'
  38. self.archiver = Archiver()
  39. self.tmpdir = tempfile.mkdtemp()
  40. self.repository_path = os.path.join(self.tmpdir, 'repository')
  41. self.repository_location = self.prefix + self.repository_path
  42. self.input_path = os.path.join(self.tmpdir, 'input')
  43. self.output_path = os.path.join(self.tmpdir, 'output')
  44. self.keys_path = os.path.join(self.tmpdir, 'keys')
  45. self.cache_path = os.path.join(self.tmpdir, 'cache')
  46. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  47. os.environ['ATTIC_KEYS_DIR'] = self.keys_path
  48. os.environ['ATTIC_CACHE_DIR'] = self.cache_path
  49. os.mkdir(self.input_path)
  50. os.mkdir(self.output_path)
  51. os.mkdir(self.keys_path)
  52. os.mkdir(self.cache_path)
  53. with open(self.exclude_file_path, 'wb') as fd:
  54. fd.write(b'input/file2\n# A commment line, then a blank line\n\n')
  55. self._old_wd = os.getcwd()
  56. os.chdir(self.tmpdir)
  57. def tearDown(self):
  58. shutil.rmtree(self.tmpdir)
  59. os.chdir(self._old_wd)
  60. def attic(self, *args, **kw):
  61. exit_code = kw.get('exit_code', 0)
  62. fork = kw.get('fork', False)
  63. if fork:
  64. try:
  65. output = subprocess.check_output((sys.executable, '-m', 'attic.archiver') + args)
  66. ret = 0
  67. except subprocess.CalledProcessError as e:
  68. output = e.output
  69. ret = e.returncode
  70. output = os.fsdecode(output)
  71. if ret != exit_code:
  72. print(output)
  73. self.assert_equal(exit_code, ret)
  74. return output
  75. args = list(args)
  76. stdout, stderr = sys.stdout, sys.stderr
  77. try:
  78. output = StringIO()
  79. sys.stdout = sys.stderr = output
  80. ret = self.archiver.run(args)
  81. sys.stdout, sys.stderr = stdout, stderr
  82. if ret != exit_code:
  83. print(output.getvalue())
  84. self.assert_equal(exit_code, ret)
  85. return output.getvalue()
  86. finally:
  87. sys.stdout, sys.stderr = stdout, stderr
  88. def create_src_archive(self, name):
  89. self.attic('create', self.repository_location + '::' + name, src_dir)
  90. class ArchiverTestCase(ArchiverTestCaseBase):
  91. def create_regual_file(self, name, size=0):
  92. filename = os.path.join(self.input_path, name)
  93. if not os.path.exists(os.path.dirname(filename)):
  94. os.makedirs(os.path.dirname(filename))
  95. with open(filename, 'wb') as fd:
  96. fd.write(b'X' * size)
  97. def create_test_files(self):
  98. """Create a minimal test case including all supported file types
  99. """
  100. # File
  101. self.create_regual_file('empty', size=0)
  102. self.create_regual_file('file1', size=1024 * 80)
  103. # Directory
  104. self.create_regual_file('dir2/file2', size=1024 * 80)
  105. # File owner
  106. os.chown('input/file1', 100, 200)
  107. # File mode
  108. os.chmod('input/file1', 0o7755)
  109. os.chmod('input/dir2', 0o555)
  110. # Block device
  111. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  112. # Char device
  113. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  114. if xattr.is_enabled():
  115. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  116. # Hard link
  117. os.link(os.path.join(self.input_path, 'file1'),
  118. os.path.join(self.input_path, 'hardlink'))
  119. # Symlink
  120. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  121. # FIFO node
  122. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  123. def test_basic_functionality(self):
  124. self.create_test_files()
  125. self.attic('init', self.repository_location)
  126. self.attic('create', self.repository_location + '::test', 'input')
  127. self.attic('create', self.repository_location + '::test.2', 'input')
  128. with changedir('output'):
  129. self.attic('extract', self.repository_location + '::test')
  130. self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
  131. self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 10)
  132. self.assert_dirs_equal('input', 'output/input')
  133. info_output = self.attic('info', self.repository_location + '::test')
  134. shutil.rmtree(self.cache_path)
  135. info_output2 = self.attic('info', self.repository_location + '::test')
  136. # info_output2 starts with some "initializing cache" text but should
  137. # end the same way as info_output
  138. assert info_output2.endswith(info_output)
  139. def test_extract_include_exclude(self):
  140. self.attic('init', self.repository_location)
  141. self.create_regual_file('file1', size=1024 * 80)
  142. self.create_regual_file('file2', size=1024 * 80)
  143. self.create_regual_file('file3', size=1024 * 80)
  144. self.create_regual_file('file4', size=1024 * 80)
  145. self.attic('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  146. with changedir('output'):
  147. self.attic('extract', self.repository_location + '::test', 'input/file1', )
  148. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  149. with changedir('output'):
  150. self.attic('extract', '--exclude=input/file2', self.repository_location + '::test')
  151. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  152. with changedir('output'):
  153. self.attic('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  154. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  155. def test_path_normalization(self):
  156. self.attic('init', self.repository_location)
  157. self.create_regual_file('dir1/dir2/file', size=1024 * 80)
  158. with changedir('input/dir1/dir2'):
  159. self.attic('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  160. output = self.attic('list', self.repository_location + '::test')
  161. self.assert_not_in('..', output)
  162. self.assert_in(' input/dir1/dir2/file', output)
  163. def test_repeated_files(self):
  164. self.create_regual_file('file1', size=1024 * 80)
  165. self.attic('init', self.repository_location)
  166. self.attic('create', self.repository_location + '::test', 'input', 'input')
  167. def test_overwrite(self):
  168. self.create_regual_file('file1', size=1024 * 80)
  169. self.create_regual_file('dir2/file2', size=1024 * 80)
  170. self.attic('init', self.repository_location)
  171. self.attic('create', self.repository_location + '::test', 'input')
  172. # Overwriting regular files and directories should be supported
  173. os.mkdir('output/input')
  174. os.mkdir('output/input/file1')
  175. os.mkdir('output/input/dir2')
  176. with changedir('output'):
  177. self.attic('extract', self.repository_location + '::test')
  178. self.assert_dirs_equal('input', 'output/input')
  179. # But non-empty dirs should fail
  180. os.unlink('output/input/file1')
  181. os.mkdir('output/input/file1')
  182. os.mkdir('output/input/file1/dir')
  183. with changedir('output'):
  184. self.attic('extract', self.repository_location + '::test', exit_code=1)
  185. def test_delete(self):
  186. self.create_regual_file('file1', size=1024 * 80)
  187. self.create_regual_file('dir2/file2', size=1024 * 80)
  188. self.attic('init', self.repository_location)
  189. self.attic('create', self.repository_location + '::test', 'input')
  190. self.attic('create', self.repository_location + '::test.2', 'input')
  191. self.attic('extract', '--dry-run', self.repository_location + '::test')
  192. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  193. self.attic('delete', self.repository_location + '::test')
  194. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  195. self.attic('delete', self.repository_location + '::test.2')
  196. # Make sure all data except the manifest has been deleted
  197. repository = Repository(self.repository_path)
  198. self.assert_equal(len(repository), 1)
  199. def test_corrupted_repository(self):
  200. self.attic('init', self.repository_location)
  201. self.create_src_archive('test')
  202. self.attic('extract', '--dry-run', self.repository_location + '::test')
  203. self.attic('check', self.repository_location)
  204. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  205. fd = open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+')
  206. fd.seek(100)
  207. fd.write('XXXX')
  208. fd.close()
  209. self.attic('check', self.repository_location, exit_code=1)
  210. def test_readonly_repository(self):
  211. self.attic('init', self.repository_location)
  212. self.create_src_archive('test')
  213. os.system('chmod -R ugo-w ' + self.repository_path)
  214. try:
  215. self.attic('extract', '--dry-run', self.repository_location + '::test')
  216. finally:
  217. # Restore permissions so shutil.rmtree is able to delete it
  218. os.system('chmod -R u+w ' + self.repository_path)
  219. def test_cmdline_compatibility(self):
  220. self.create_regual_file('file1', size=1024 * 80)
  221. self.attic('init', self.repository_location)
  222. self.attic('create', self.repository_location + '::test', 'input')
  223. output = self.attic('verify', '-v', self.repository_location + '::test')
  224. self.assert_in('"attic verify" has been deprecated', output)
  225. output = self.attic('prune', self.repository_location, '--hourly=1')
  226. self.assert_in('"--hourly" has been deprecated. Use "--keep-hourly" instead', output)
  227. def test_prune_repository(self):
  228. self.attic('init', self.repository_location)
  229. self.attic('create', self.repository_location + '::test1', src_dir)
  230. self.attic('create', self.repository_location + '::test2', src_dir)
  231. output = self.attic('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  232. self.assert_in('Keeping archive: test2', output)
  233. self.assert_in('Would prune: test1', output)
  234. output = self.attic('list', self.repository_location)
  235. self.assert_in('test1', output)
  236. self.assert_in('test2', output)
  237. self.attic('prune', self.repository_location, '--keep-daily=2')
  238. output = self.attic('list', self.repository_location)
  239. self.assert_not_in('test1', output)
  240. self.assert_in('test2', output)
  241. def test_usage(self):
  242. self.assert_raises(SystemExit, lambda: self.attic())
  243. self.assert_raises(SystemExit, lambda: self.attic('-h'))
  244. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  245. def test_fuse_mount_repository(self):
  246. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  247. os.mkdir(mountpoint)
  248. self.attic('init', self.repository_location)
  249. self.create_test_files()
  250. self.attic('create', self.repository_location + '::archive', 'input')
  251. self.attic('create', self.repository_location + '::archive2', 'input')
  252. try:
  253. self.attic('mount', self.repository_location, mountpoint, fork=True)
  254. self.wait_for_mount(mountpoint)
  255. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  256. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  257. finally:
  258. if sys.platform.startswith('linux'):
  259. os.system('fusermount -u ' + mountpoint)
  260. else:
  261. os.system('umount ' + mountpoint)
  262. os.rmdir(mountpoint)
  263. # Give the daemon some time to exit
  264. time.sleep(.2)
  265. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  266. def test_fuse_mount_archive(self):
  267. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  268. os.mkdir(mountpoint)
  269. self.attic('init', self.repository_location)
  270. self.create_test_files()
  271. self.attic('create', self.repository_location + '::archive', 'input')
  272. try:
  273. self.attic('mount', self.repository_location + '::archive', mountpoint, fork=True)
  274. self.wait_for_mount(mountpoint)
  275. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  276. finally:
  277. if sys.platform.startswith('linux'):
  278. os.system('fusermount -u ' + mountpoint)
  279. else:
  280. os.system('umount ' + mountpoint)
  281. os.rmdir(mountpoint)
  282. # Give the daemon some time to exit
  283. time.sleep(.2)
  284. def verify_aes_counter_uniqueness(self, method):
  285. seen = set() # Chunks already seen
  286. used = set() # counter values already used
  287. def verify_uniqueness():
  288. repository = Repository(self.repository_path)
  289. for key, _ in repository.get_read_only_index(repository.get_transaction_id()).iteritems():
  290. data = repository.get(key)
  291. hash = sha256(data).digest()
  292. if not hash in seen:
  293. seen.add(hash)
  294. num_blocks = num_aes_blocks(len(data) - 41)
  295. nonce = bytes_to_long(data[33:41])
  296. for counter in range(nonce, nonce + num_blocks):
  297. self.assert_not_in(counter, used)
  298. used.add(counter)
  299. self.create_test_files()
  300. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  301. self.attic('init', '--encryption=' + method, self.repository_location)
  302. verify_uniqueness()
  303. self.attic('create', self.repository_location + '::test', 'input')
  304. verify_uniqueness()
  305. self.attic('create', self.repository_location + '::test.2', 'input')
  306. verify_uniqueness()
  307. self.attic('delete', self.repository_location + '::test.2')
  308. verify_uniqueness()
  309. self.assert_equal(used, set(range(len(used))))
  310. def test_aes_counter_uniqueness_keyfile(self):
  311. self.verify_aes_counter_uniqueness('keyfile')
  312. def test_aes_counter_uniqueness_passphrase(self):
  313. self.verify_aes_counter_uniqueness('passphrase')
  314. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  315. def setUp(self):
  316. super(ArchiverCheckTestCase, self).setUp()
  317. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  318. self.attic('init', self.repository_location)
  319. self.create_src_archive('archive1')
  320. self.create_src_archive('archive2')
  321. def open_archive(self, name):
  322. repository = Repository(self.repository_path)
  323. manifest, key = Manifest.load(repository)
  324. archive = Archive(repository, key, manifest, name)
  325. return archive, repository
  326. def test_check_usage(self):
  327. output = self.attic('check', self.repository_location, exit_code=0)
  328. self.assert_in('Starting repository check', output)
  329. self.assert_in('Starting archive consistency check', output)
  330. output = self.attic('check', '--repository-only', self.repository_location, exit_code=0)
  331. self.assert_in('Starting repository check', output)
  332. self.assert_not_in('Starting archive consistency check', output)
  333. output = self.attic('check', '--archives-only', self.repository_location, exit_code=0)
  334. self.assert_not_in('Starting repository check', output)
  335. self.assert_in('Starting archive consistency check', output)
  336. def test_missing_file_chunk(self):
  337. archive, repository = self.open_archive('archive1')
  338. for item in archive.iter_items():
  339. if item[b'path'].endswith('testsuite/archiver.py'):
  340. repository.delete(item[b'chunks'][-1][0])
  341. break
  342. repository.commit()
  343. self.attic('check', self.repository_location, exit_code=1)
  344. self.attic('check', '--repair', self.repository_location, exit_code=0)
  345. self.attic('check', self.repository_location, exit_code=0)
  346. def test_missing_archive_item_chunk(self):
  347. archive, repository = self.open_archive('archive1')
  348. repository.delete(archive.metadata[b'items'][-5])
  349. repository.commit()
  350. self.attic('check', self.repository_location, exit_code=1)
  351. self.attic('check', '--repair', self.repository_location, exit_code=0)
  352. self.attic('check', self.repository_location, exit_code=0)
  353. def test_missing_archive_metadata(self):
  354. archive, repository = self.open_archive('archive1')
  355. repository.delete(archive.id)
  356. repository.commit()
  357. self.attic('check', self.repository_location, exit_code=1)
  358. self.attic('check', '--repair', self.repository_location, exit_code=0)
  359. self.attic('check', self.repository_location, exit_code=0)
  360. def test_missing_manifest(self):
  361. archive, repository = self.open_archive('archive1')
  362. repository.delete(Manifest.MANIFEST_ID)
  363. repository.commit()
  364. self.attic('check', self.repository_location, exit_code=1)
  365. output = self.attic('check', '--repair', self.repository_location, exit_code=0)
  366. self.assert_in('archive1', output)
  367. self.assert_in('archive2', output)
  368. self.attic('check', self.repository_location, exit_code=0)
  369. def test_extra_chunks(self):
  370. self.attic('check', self.repository_location, exit_code=0)
  371. repository = Repository(self.repository_location)
  372. repository.put(b'01234567890123456789012345678901', b'xxxx')
  373. repository.commit()
  374. repository.close()
  375. self.attic('check', self.repository_location, exit_code=1)
  376. self.attic('check', self.repository_location, exit_code=1)
  377. self.attic('check', '--repair', self.repository_location, exit_code=0)
  378. self.attic('check', self.repository_location, exit_code=0)
  379. self.attic('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  380. class RemoteArchiverTestCase(ArchiverTestCase):
  381. prefix = '__testsuite__:'
  382. def test_remote_repo_restrict_to_path(self):
  383. self.attic('init', self.repository_location)
  384. path_prefix = os.path.dirname(self.repository_path)
  385. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  386. self.assert_raises(PathNotAllowed, lambda: self.attic('init', self.repository_location + '_1'))
  387. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  388. self.attic('init', self.repository_location + '_2')
  389. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  390. self.attic('init', self.repository_location + '_3')