archiver.py 22 KB

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