archiver.py 18 KB

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