2
0

archiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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.archiver import Archiver
  13. from attic.repository import Repository
  14. from attic.testsuite import AtticTestCase
  15. from attic.crypto import bytes_to_long, num_aes_blocks
  16. try:
  17. import llfuse
  18. has_llfuse = True
  19. except ImportError:
  20. has_llfuse = False
  21. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..', '..')
  22. class changedir:
  23. def __init__(self, dir):
  24. self.dir = dir
  25. def __enter__(self):
  26. self.old = os.getcwd()
  27. os.chdir(self.dir)
  28. def __exit__(self, *args, **kw):
  29. os.chdir(self.old)
  30. class ArchiverTestCase(AtticTestCase):
  31. prefix = ''
  32. def setUp(self):
  33. self.archiver = Archiver()
  34. self.tmpdir = tempfile.mkdtemp()
  35. self.repository_path = os.path.join(self.tmpdir, 'repository')
  36. self.repository_location = self.prefix + self.repository_path
  37. self.input_path = os.path.join(self.tmpdir, 'input')
  38. self.output_path = os.path.join(self.tmpdir, 'output')
  39. self.keys_path = os.path.join(self.tmpdir, 'keys')
  40. self.cache_path = os.path.join(self.tmpdir, 'cache')
  41. os.environ['ATTIC_KEYS_DIR'] = self.keys_path
  42. os.environ['ATTIC_CACHE_DIR'] = self.cache_path
  43. os.mkdir(self.input_path)
  44. os.mkdir(self.output_path)
  45. os.mkdir(self.keys_path)
  46. os.mkdir(self.cache_path)
  47. self._old_wd = os.getcwd()
  48. os.chdir(self.tmpdir)
  49. def tearDown(self):
  50. shutil.rmtree(self.tmpdir)
  51. os.chdir(self._old_wd)
  52. def attic(self, *args, **kw):
  53. exit_code = kw.get('exit_code', 0)
  54. fork = kw.get('fork', False)
  55. if fork:
  56. try:
  57. output = subprocess.check_output((sys.executable, '-m', 'attic.archiver') + args)
  58. ret = 0
  59. except subprocess.CalledProcessError as e:
  60. output = e.output
  61. ret = e.returncode
  62. output = os.fsdecode(output)
  63. if ret != exit_code:
  64. print(output)
  65. self.assert_equal(exit_code, ret)
  66. return output
  67. args = list(args)
  68. stdout, stderr = sys.stdout, sys.stderr
  69. try:
  70. output = StringIO()
  71. sys.stdout = sys.stderr = output
  72. ret = self.archiver.run(args)
  73. sys.stdout, sys.stderr = stdout, stderr
  74. if ret != exit_code:
  75. print(output.getvalue())
  76. self.assert_equal(exit_code, ret)
  77. return output.getvalue()
  78. finally:
  79. sys.stdout, sys.stderr = stdout, stderr
  80. def create_src_archive(self, name):
  81. self.attic('create', self.repository_location + '::' + name, src_dir)
  82. def create_regual_file(self, name, size=0):
  83. filename = os.path.join(self.input_path, name)
  84. if not os.path.exists(os.path.dirname(filename)):
  85. os.makedirs(os.path.dirname(filename))
  86. with open(filename, 'wb') as fd:
  87. fd.write(b'X' * size)
  88. def create_test_files(self):
  89. """Create a minimal test case including all supported file types
  90. """
  91. # File
  92. self.create_regual_file('empty', size=0)
  93. self.create_regual_file('file1', size=1024 * 80)
  94. # Directory
  95. self.create_regual_file('dir2/file2', size=1024 * 80)
  96. # File owner
  97. os.chown('input/file1', 100, 200)
  98. # File mode
  99. os.chmod('input/file1', 0o7755)
  100. os.chmod('input/dir2', 0o555)
  101. # Block device
  102. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  103. # Char device
  104. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  105. if xattr.is_enabled():
  106. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  107. # Hard link
  108. os.link(os.path.join(self.input_path, 'file1'),
  109. os.path.join(self.input_path, 'hardlink'))
  110. # Symlink
  111. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  112. # FIFO node
  113. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  114. def test_basic_functionality(self):
  115. self.create_test_files()
  116. self.attic('init', self.repository_location)
  117. self.attic('create', self.repository_location + '::test', 'input')
  118. self.attic('create', self.repository_location + '::test.2', 'input')
  119. with changedir('output'):
  120. self.attic('extract', self.repository_location + '::test')
  121. self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
  122. self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 10)
  123. self.assert_dirs_equal('input', 'output/input')
  124. info_output = self.attic('info', self.repository_location + '::test')
  125. shutil.rmtree(self.cache_path)
  126. info_output2 = self.attic('info', self.repository_location + '::test')
  127. # info_output2 starts with some "initializing cache" text but should
  128. # end the same way as info_output
  129. assert info_output2.endswith(info_output)
  130. def test_extract_include_exclude(self):
  131. self.attic('init', self.repository_location)
  132. self.create_regual_file('file1', size=1024 * 80)
  133. self.create_regual_file('file2', size=1024 * 80)
  134. self.create_regual_file('file3', size=1024 * 80)
  135. self.create_regual_file('file4', size=1024 * 80)
  136. self.attic('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  137. with changedir('output'):
  138. self.attic('extract', self.repository_location + '::test', 'input/file1', )
  139. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  140. with changedir('output'):
  141. self.attic('extract', '--exclude=input/file2', self.repository_location + '::test')
  142. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  143. def test_path_normalization(self):
  144. self.attic('init', self.repository_location)
  145. self.create_regual_file('dir1/dir2/file', size=1024 * 80)
  146. with changedir('input/dir1/dir2'):
  147. self.attic('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  148. output = self.attic('list', self.repository_location + '::test')
  149. self.assert_not_in('..', output)
  150. self.assert_in(' input/dir1/dir2/file', output)
  151. def test_overwrite(self):
  152. self.create_regual_file('file1', size=1024 * 80)
  153. self.create_regual_file('dir2/file2', size=1024 * 80)
  154. self.attic('init', self.repository_location)
  155. self.attic('create', self.repository_location + '::test', 'input')
  156. # Overwriting regular files and directories should be supported
  157. os.mkdir('output/input')
  158. os.mkdir('output/input/file1')
  159. os.mkdir('output/input/dir2')
  160. with changedir('output'):
  161. self.attic('extract', self.repository_location + '::test')
  162. self.assert_dirs_equal('input', 'output/input')
  163. # But non-empty dirs should fail
  164. os.unlink('output/input/file1')
  165. os.mkdir('output/input/file1')
  166. os.mkdir('output/input/file1/dir')
  167. with changedir('output'):
  168. self.attic('extract', self.repository_location + '::test', exit_code=1)
  169. def test_delete(self):
  170. self.create_regual_file('file1', size=1024 * 80)
  171. self.create_regual_file('dir2/file2', size=1024 * 80)
  172. self.attic('init', self.repository_location)
  173. self.attic('create', self.repository_location + '::test', 'input')
  174. self.attic('create', self.repository_location + '::test.2', 'input')
  175. self.attic('verify', self.repository_location + '::test')
  176. self.attic('verify', self.repository_location + '::test.2')
  177. self.attic('delete', self.repository_location + '::test')
  178. self.attic('verify', self.repository_location + '::test.2')
  179. self.attic('delete', self.repository_location + '::test.2')
  180. # Make sure all data except the manifest has been deleted
  181. repository = Repository(self.repository_path)
  182. self.assert_equal(repository._len(), 1)
  183. def test_corrupted_repository(self):
  184. self.attic('init', self.repository_location)
  185. self.create_src_archive('test')
  186. self.attic('verify', self.repository_location + '::test')
  187. self.attic('check', self.repository_location)
  188. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  189. fd = open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+')
  190. fd.seek(100)
  191. fd.write('XXXX')
  192. fd.close()
  193. self.attic('verify', self.repository_location + '::test', exit_code=1)
  194. self.attic('check', self.repository_location, exit_code=1)
  195. def test_readonly_repository(self):
  196. self.attic('init', self.repository_location)
  197. self.create_src_archive('test')
  198. os.system('chmod -R ugo-w ' + self.repository_path)
  199. try:
  200. self.attic('verify', self.repository_location + '::test')
  201. finally:
  202. # Restore permissions so shutil.rmtree is able to delete it
  203. os.system('chmod -R u+w ' + self.repository_path)
  204. def test_prune_repository(self):
  205. self.attic('init', self.repository_location)
  206. self.attic('create', self.repository_location + '::test1', src_dir)
  207. self.attic('create', self.repository_location + '::test2', src_dir)
  208. self.attic('prune', self.repository_location, '--daily=2')
  209. output = self.attic('list', self.repository_location)
  210. assert 'test1' not in output
  211. assert 'test2' in output
  212. def test_usage(self):
  213. self.assert_raises(SystemExit, lambda: self.attic())
  214. self.assert_raises(SystemExit, lambda: self.attic('-h'))
  215. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  216. def test_mount(self):
  217. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  218. os.mkdir(mountpoint)
  219. self.attic('init', self.repository_location)
  220. self.create_test_files()
  221. self.attic('create', self.repository_location + '::archive', 'input')
  222. try:
  223. self.attic('mount', self.repository_location + '::archive', mountpoint, fork=True)
  224. self.wait_for_mount(mountpoint)
  225. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  226. finally:
  227. if sys.platform.startswith('linux'):
  228. os.system('fusermount -u ' + mountpoint)
  229. else:
  230. os.system('umount ' + mountpoint)
  231. os.rmdir(mountpoint)
  232. # Give the daemon some time to exit
  233. time.sleep(.2)
  234. def verify_aes_counter_uniqueness(self, method):
  235. seen = set() # Chunks already seen
  236. used = set() # counter values already used
  237. def verify_uniqueness():
  238. repository = Repository(self.repository_path)
  239. for key, _ in repository.index.iteritems():
  240. data = repository.get(key)
  241. hash = sha256(data).digest()
  242. if not hash in seen:
  243. seen.add(hash)
  244. num_blocks = num_aes_blocks(len(data) - 41)
  245. nonce = bytes_to_long(data[33:41])
  246. for counter in range(nonce, nonce + num_blocks):
  247. self.assert_not_in(counter, used)
  248. used.add(counter)
  249. self.create_test_files()
  250. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  251. self.attic('init', '--encryption=' + method, self.repository_location)
  252. verify_uniqueness()
  253. self.attic('create', self.repository_location + '::test', 'input')
  254. verify_uniqueness()
  255. self.attic('create', self.repository_location + '::test.2', 'input')
  256. verify_uniqueness()
  257. self.attic('delete', self.repository_location + '::test.2')
  258. verify_uniqueness()
  259. self.assert_equal(used, set(range(len(used))))
  260. def test_aes_counter_uniqueness_keyfile(self):
  261. self.verify_aes_counter_uniqueness('keyfile')
  262. def test_aes_counter_uniqueness_passphrase(self):
  263. self.verify_aes_counter_uniqueness('passphrase')
  264. class RemoteArchiverTestCase(ArchiverTestCase):
  265. prefix = '__testsuite__:'