archiver.py 20 KB

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