archiver.py 20 KB

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