archiver.py 23 KB

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