archiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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('file1', size=1024 * 80)
  93. # Directory
  94. self.create_regual_file('dir2/file2', size=1024 * 80)
  95. # File owner
  96. os.chown('input/file1', 100, 200)
  97. # File mode
  98. os.chmod('input/file1', 0o7755)
  99. os.chmod('input/dir2', 0o555)
  100. # Block device
  101. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  102. # Char device
  103. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  104. if xattr.is_enabled():
  105. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  106. # Hard link
  107. os.link(os.path.join(self.input_path, 'file1'),
  108. os.path.join(self.input_path, 'hardlink'))
  109. # Symlink
  110. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  111. # FIFO node
  112. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  113. def test_basic_functionality(self):
  114. self.create_test_files()
  115. self.attic('init', self.repository_location)
  116. self.attic('create', self.repository_location + '::test', 'input')
  117. self.attic('create', self.repository_location + '::test.2', 'input')
  118. with changedir('output'):
  119. self.attic('extract', self.repository_location + '::test')
  120. self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
  121. self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 9)
  122. self.assert_dirs_equal('input', 'output/input')
  123. info_output = self.attic('info', self.repository_location + '::test')
  124. shutil.rmtree(self.cache_path)
  125. info_output2 = self.attic('info', self.repository_location + '::test')
  126. # info_output2 starts with some "initializing cache" text but should
  127. # end the same way as info_output
  128. assert info_output2.endswith(info_output)
  129. def test_extract_include_exclude(self):
  130. self.attic('init', self.repository_location)
  131. self.create_regual_file('file1', size=1024 * 80)
  132. self.create_regual_file('file2', size=1024 * 80)
  133. self.create_regual_file('file3', size=1024 * 80)
  134. self.create_regual_file('file4', size=1024 * 80)
  135. self.attic('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  136. with changedir('output'):
  137. self.attic('extract', self.repository_location + '::test', 'input/file1', )
  138. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  139. with changedir('output'):
  140. self.attic('extract', '--exclude=input/file2', self.repository_location + '::test')
  141. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  142. def test_path_normalization(self):
  143. self.attic('init', self.repository_location)
  144. self.create_regual_file('dir1/dir2/file', size=1024 * 80)
  145. with changedir('input/dir1/dir2'):
  146. self.attic('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  147. output = self.attic('list', self.repository_location + '::test')
  148. self.assert_not_in('..', output)
  149. self.assert_in(' input/dir1/dir2/file', output)
  150. def test_overwrite(self):
  151. self.create_regual_file('file1', size=1024 * 80)
  152. self.create_regual_file('dir2/file2', size=1024 * 80)
  153. self.attic('init', self.repository_location)
  154. self.attic('create', self.repository_location + '::test', 'input')
  155. # Overwriting regular files and directories should be supported
  156. os.mkdir('output/input')
  157. os.mkdir('output/input/file1')
  158. os.mkdir('output/input/dir2')
  159. with changedir('output'):
  160. self.attic('extract', self.repository_location + '::test')
  161. self.assert_dirs_equal('input', 'output/input')
  162. # But non-empty dirs should fail
  163. os.unlink('output/input/file1')
  164. os.mkdir('output/input/file1')
  165. os.mkdir('output/input/file1/dir')
  166. with changedir('output'):
  167. self.attic('extract', self.repository_location + '::test', exit_code=1)
  168. def test_delete(self):
  169. self.create_regual_file('file1', size=1024 * 80)
  170. self.create_regual_file('dir2/file2', size=1024 * 80)
  171. self.attic('init', self.repository_location)
  172. self.attic('create', self.repository_location + '::test', 'input')
  173. self.attic('create', self.repository_location + '::test.2', 'input')
  174. self.attic('verify', self.repository_location + '::test')
  175. self.attic('verify', self.repository_location + '::test.2')
  176. self.attic('delete', self.repository_location + '::test')
  177. self.attic('verify', self.repository_location + '::test.2')
  178. self.attic('delete', self.repository_location + '::test.2')
  179. # Make sure all data except the manifest has been deleted
  180. repository = Repository(self.repository_path)
  181. self.assert_equal(repository._len(), 1)
  182. def test_corrupted_repository(self):
  183. self.attic('init', self.repository_location)
  184. self.create_src_archive('test')
  185. self.attic('verify', self.repository_location + '::test')
  186. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  187. fd = open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+')
  188. fd.seek(100)
  189. fd.write('XXXX')
  190. fd.close()
  191. self.attic('verify', self.repository_location + '::test', exit_code=1)
  192. def test_readonly_repository(self):
  193. self.attic('init', self.repository_location)
  194. self.create_src_archive('test')
  195. os.system('chmod -R ugo-w ' + self.repository_path)
  196. try:
  197. self.attic('verify', self.repository_location + '::test')
  198. finally:
  199. # Restore permissions so shutil.rmtree is able to delete it
  200. os.system('chmod -R u+w ' + self.repository_path)
  201. def test_prune_repository(self):
  202. self.attic('init', self.repository_location)
  203. self.attic('create', self.repository_location + '::test1', src_dir)
  204. self.attic('create', self.repository_location + '::test2', src_dir)
  205. self.attic('prune', self.repository_location, '--daily=2')
  206. output = self.attic('list', self.repository_location)
  207. assert 'test1' not in output
  208. assert 'test2' in output
  209. def test_usage(self):
  210. self.assert_raises(SystemExit, lambda: self.attic())
  211. self.assert_raises(SystemExit, lambda: self.attic('-h'))
  212. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  213. def test_mount(self):
  214. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  215. os.mkdir(mountpoint)
  216. self.attic('init', self.repository_location)
  217. self.create_test_files()
  218. self.attic('create', self.repository_location + '::archive', 'input')
  219. try:
  220. self.attic('mount', self.repository_location + '::archive', mountpoint, fork=True)
  221. self.wait_for_mount(mountpoint)
  222. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  223. finally:
  224. if sys.platform.startswith('linux'):
  225. os.system('fusermount -u ' + mountpoint)
  226. else:
  227. os.system('umount ' + mountpoint)
  228. os.rmdir(mountpoint)
  229. # Give the daemon some time to exit
  230. time.sleep(.2)
  231. def verify_aes_counter_uniqueness(self, method):
  232. seen = set() # Chunks already seen
  233. used = set() # counter values already used
  234. def verify_uniqueness():
  235. repository = Repository(self.repository_path)
  236. for key, _ in repository.index.iteritems():
  237. data = repository.get(key)
  238. hash = sha256(data).digest()
  239. if not hash in seen:
  240. seen.add(hash)
  241. num_blocks = num_aes_blocks(len(data) - 41)
  242. nonce = bytes_to_long(data[33:41])
  243. for counter in range(nonce, nonce + num_blocks):
  244. self.assert_not_in(counter, used)
  245. used.add(counter)
  246. self.create_test_files()
  247. os.environ['ATTIC_PASSPHRASE'] = 'passphrase'
  248. self.attic('init', '--encryption=' + method, self.repository_location)
  249. verify_uniqueness()
  250. self.attic('create', self.repository_location + '::test', 'input')
  251. verify_uniqueness()
  252. self.attic('create', self.repository_location + '::test.2', 'input')
  253. verify_uniqueness()
  254. self.attic('delete', self.repository_location + '::test.2')
  255. verify_uniqueness()
  256. self.assert_equal(used, set(range(len(used))))
  257. def test_aes_counter_uniqueness_keyfile(self):
  258. self.verify_aes_counter_uniqueness('keyfile')
  259. def test_aes_counter_uniqueness_passphrase(self):
  260. self.verify_aes_counter_uniqueness('passphrase')
  261. class RemoteArchiverTestCase(ArchiverTestCase):
  262. prefix = '__testsuite__:'