archiver.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. from binascii import hexlify
  2. from configparser import RawConfigParser
  3. import os
  4. from io import StringIO
  5. import stat
  6. import subprocess
  7. import sys
  8. import shutil
  9. import tempfile
  10. import time
  11. import unittest
  12. from hashlib import sha256
  13. from mock import patch
  14. import pytest
  15. from .. import xattr
  16. from ..archive import Archive, ChunkBuffer, CHUNK_MAX_EXP
  17. from ..archiver import Archiver
  18. from ..cache import Cache
  19. from ..crypto import bytes_to_long, num_aes_blocks
  20. from ..helpers import Manifest
  21. from ..remote import RemoteRepository, PathNotAllowed
  22. from ..repository import Repository
  23. from . import BaseTestCase
  24. try:
  25. import llfuse
  26. has_llfuse = True or llfuse # avoids "unused import"
  27. except ImportError:
  28. has_llfuse = False
  29. has_lchflags = hasattr(os, 'lchflags')
  30. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..')
  31. # Python <= 3.2 raises OSError instead of PermissionError (See #164)
  32. try:
  33. PermissionError = PermissionError
  34. except NameError:
  35. PermissionError = OSError
  36. class changedir:
  37. def __init__(self, dir):
  38. self.dir = dir
  39. def __enter__(self):
  40. self.old = os.getcwd()
  41. os.chdir(self.dir)
  42. def __exit__(self, *args, **kw):
  43. os.chdir(self.old)
  44. class environment_variable:
  45. def __init__(self, **values):
  46. self.values = values
  47. self.old_values = {}
  48. def __enter__(self):
  49. for k, v in self.values.items():
  50. self.old_values[k] = os.environ.get(k)
  51. os.environ[k] = v
  52. def __exit__(self, *args, **kw):
  53. for k, v in self.old_values.items():
  54. if v is None:
  55. del os.environ[k]
  56. else:
  57. os.environ[k] = v
  58. class ArchiverTestCaseBase(BaseTestCase):
  59. prefix = ''
  60. def setUp(self):
  61. os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = '1'
  62. self.archiver = Archiver()
  63. self.tmpdir = tempfile.mkdtemp()
  64. self.repository_path = os.path.join(self.tmpdir, 'repository')
  65. self.repository_location = self.prefix + self.repository_path
  66. self.input_path = os.path.join(self.tmpdir, 'input')
  67. self.output_path = os.path.join(self.tmpdir, 'output')
  68. self.keys_path = os.path.join(self.tmpdir, 'keys')
  69. self.cache_path = os.path.join(self.tmpdir, 'cache')
  70. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  71. os.environ['BORG_KEYS_DIR'] = self.keys_path
  72. os.environ['BORG_CACHE_DIR'] = self.cache_path
  73. os.mkdir(self.input_path)
  74. os.mkdir(self.output_path)
  75. os.mkdir(self.keys_path)
  76. os.mkdir(self.cache_path)
  77. with open(self.exclude_file_path, 'wb') as fd:
  78. fd.write(b'input/file2\n# A comment line, then a blank line\n\n')
  79. self._old_wd = os.getcwd()
  80. os.chdir(self.tmpdir)
  81. def tearDown(self):
  82. os.chdir(self._old_wd)
  83. shutil.rmtree(self.tmpdir)
  84. def cmd(self, *args, **kw):
  85. exit_code = kw.get('exit_code', 0)
  86. fork = kw.get('fork', False)
  87. if fork:
  88. try:
  89. output = subprocess.check_output((sys.executable, '-m', 'borg.archiver') + args)
  90. ret = 0
  91. except subprocess.CalledProcessError as e:
  92. output = e.output
  93. ret = e.returncode
  94. output = os.fsdecode(output)
  95. if ret != exit_code:
  96. print(output)
  97. self.assert_equal(exit_code, ret)
  98. return output
  99. args = list(args)
  100. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  101. try:
  102. sys.stdin = StringIO()
  103. output = StringIO()
  104. sys.stdout = sys.stderr = output
  105. ret = self.archiver.run(args)
  106. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  107. if ret != exit_code:
  108. print(output.getvalue())
  109. self.assert_equal(exit_code, ret)
  110. return output.getvalue()
  111. finally:
  112. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  113. def create_src_archive(self, name):
  114. self.cmd('create', self.repository_location + '::' + name, src_dir)
  115. class ArchiverTestCase(ArchiverTestCaseBase):
  116. def create_regular_file(self, name, size=0, contents=None):
  117. filename = os.path.join(self.input_path, name)
  118. if not os.path.exists(os.path.dirname(filename)):
  119. os.makedirs(os.path.dirname(filename))
  120. with open(filename, 'wb') as fd:
  121. if contents is None:
  122. contents = b'X' * size
  123. fd.write(contents)
  124. def create_test_files(self):
  125. """Create a minimal test case including all supported file types
  126. """
  127. # File
  128. self.create_regular_file('empty', size=0)
  129. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  130. # 2600-01-01 > 2**64 ns
  131. # os.utime('input/empty', (19880895600, 19880895600))
  132. # thus, we better test with something not that far in future:
  133. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  134. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  135. self.create_regular_file('file1', size=1024 * 80)
  136. self.create_regular_file('flagfile', size=1024)
  137. # Directory
  138. self.create_regular_file('dir2/file2', size=1024 * 80)
  139. # File mode
  140. os.chmod('input/file1', 0o4755)
  141. # Hard link
  142. os.link(os.path.join(self.input_path, 'file1'),
  143. os.path.join(self.input_path, 'hardlink'))
  144. # Symlink
  145. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  146. if xattr.is_enabled(self.input_path):
  147. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  148. # XXX this always fails for me
  149. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  150. # same for newer ubuntu and centos.
  151. # if this is supported just on specific platform, platform should be checked first,
  152. # so that the test setup for all tests using it does not fail here always for others.
  153. # xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  154. # FIFO node
  155. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  156. if has_lchflags:
  157. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  158. try:
  159. # Block device
  160. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  161. # Char device
  162. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  163. # File mode
  164. os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents
  165. # File owner
  166. os.chown('input/file1', 100, 200)
  167. have_root = True # we have (fake)root
  168. except PermissionError:
  169. have_root = False
  170. return have_root
  171. def test_basic_functionality(self):
  172. have_root = self.create_test_files()
  173. self.cmd('init', self.repository_location)
  174. self.cmd('create', self.repository_location + '::test', 'input')
  175. self.cmd('create', '--stats', self.repository_location + '::test.2', 'input')
  176. with changedir('output'):
  177. self.cmd('extract', self.repository_location + '::test')
  178. self.assert_equal(len(self.cmd('list', self.repository_location).splitlines()), 2)
  179. expected = set([
  180. 'input',
  181. 'input/bdev',
  182. 'input/cdev',
  183. 'input/dir2',
  184. 'input/dir2/file2',
  185. 'input/empty',
  186. 'input/fifo1',
  187. 'input/file1',
  188. 'input/flagfile',
  189. 'input/hardlink',
  190. 'input/link1',
  191. ])
  192. if not have_root:
  193. # we could not create these device files without (fake)root
  194. expected.remove('input/bdev')
  195. expected.remove('input/cdev')
  196. if has_lchflags:
  197. # remove the file we did not backup, so input and output become equal
  198. expected.remove('input/flagfile') # this file is UF_NODUMP
  199. os.remove(os.path.join('input', 'flagfile'))
  200. self.assert_equal(set(self.cmd('list', '--short', self.repository_location + '::test').splitlines()), expected)
  201. self.assert_dirs_equal('input', 'output/input')
  202. info_output = self.cmd('info', self.repository_location + '::test')
  203. item_count = 3 if has_lchflags else 4 # one file is UF_NODUMP
  204. self.assert_in('Number of files: %d' % item_count, info_output)
  205. shutil.rmtree(self.cache_path)
  206. with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='1'):
  207. info_output2 = self.cmd('info', self.repository_location + '::test')
  208. # info_output2 starts with some "initializing cache" text but should
  209. # end the same way as info_output
  210. assert info_output2.endswith(info_output)
  211. def _extract_repository_id(self, path):
  212. return Repository(self.repository_path).id
  213. def _set_repository_id(self, path, id):
  214. config = RawConfigParser()
  215. config.read(os.path.join(path, 'config'))
  216. config.set('repository', 'id', hexlify(id).decode('ascii'))
  217. with open(os.path.join(path, 'config'), 'w') as fd:
  218. config.write(fd)
  219. return Repository(self.repository_path).id
  220. def test_sparse_file(self):
  221. # no sparse file support on Mac OS X
  222. sparse_support = sys.platform != 'darwin'
  223. filename = os.path.join(self.input_path, 'sparse')
  224. content = b'foobar'
  225. hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers
  226. with open(filename, 'wb') as fd:
  227. # create a file that has a hole at the beginning and end (if the
  228. # OS and filesystem supports sparse files)
  229. fd.seek(hole_size, 1)
  230. fd.write(content)
  231. fd.seek(hole_size, 1)
  232. pos = fd.tell()
  233. fd.truncate(pos)
  234. total_len = hole_size + len(content) + hole_size
  235. st = os.stat(filename)
  236. self.assert_equal(st.st_size, total_len)
  237. if sparse_support and hasattr(st, 'st_blocks'):
  238. self.assert_true(st.st_blocks * 512 < total_len / 9) # is input sparse?
  239. self.cmd('init', self.repository_location)
  240. self.cmd('create', self.repository_location + '::test', 'input')
  241. with changedir('output'):
  242. self.cmd('extract', '--sparse', self.repository_location + '::test')
  243. self.assert_dirs_equal('input', 'output/input')
  244. filename = os.path.join(self.output_path, 'input', 'sparse')
  245. with open(filename, 'rb') as fd:
  246. # check if file contents are as expected
  247. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  248. self.assert_equal(fd.read(len(content)), content)
  249. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  250. st = os.stat(filename)
  251. self.assert_equal(st.st_size, total_len)
  252. if sparse_support and hasattr(st, 'st_blocks'):
  253. self.assert_true(st.st_blocks * 512 < total_len / 9) # is output sparse?
  254. def test_unusual_filenames(self):
  255. filenames = ['normal', 'with some blanks', '(with_parens)', ]
  256. for filename in filenames:
  257. filename = os.path.join(self.input_path, filename)
  258. with open(filename, 'wb') as fd:
  259. pass
  260. self.cmd('init', self.repository_location)
  261. self.cmd('create', self.repository_location + '::test', 'input')
  262. for filename in filenames:
  263. with changedir('output'):
  264. self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename))
  265. assert os.path.exists(os.path.join('output', 'input', filename))
  266. def test_repository_swap_detection(self):
  267. self.create_test_files()
  268. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  269. self.cmd('init', '--encryption=passphrase', self.repository_location)
  270. repository_id = self._extract_repository_id(self.repository_path)
  271. self.cmd('create', self.repository_location + '::test', 'input')
  272. shutil.rmtree(self.repository_path)
  273. self.cmd('init', '--encryption=none', self.repository_location)
  274. self._set_repository_id(self.repository_path, repository_id)
  275. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  276. self.assert_raises(Cache.EncryptionMethodMismatch, lambda: self.cmd('create', self.repository_location + '::test.2', 'input'))
  277. def test_repository_swap_detection2(self):
  278. self.create_test_files()
  279. self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted')
  280. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  281. self.cmd('init', '--encryption=passphrase', self.repository_location + '_encrypted')
  282. self.cmd('create', self.repository_location + '_encrypted::test', 'input')
  283. shutil.rmtree(self.repository_path + '_encrypted')
  284. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  285. self.assert_raises(Cache.RepositoryAccessAborted, lambda: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input'))
  286. def test_strip_components(self):
  287. self.cmd('init', self.repository_location)
  288. self.create_regular_file('dir/file')
  289. self.cmd('create', self.repository_location + '::test', 'input')
  290. with changedir('output'):
  291. self.cmd('extract', self.repository_location + '::test', '--strip-components', '3')
  292. self.assert_true(not os.path.exists('file'))
  293. with self.assert_creates_file('file'):
  294. self.cmd('extract', self.repository_location + '::test', '--strip-components', '2')
  295. with self.assert_creates_file('dir/file'):
  296. self.cmd('extract', self.repository_location + '::test', '--strip-components', '1')
  297. with self.assert_creates_file('input/dir/file'):
  298. self.cmd('extract', self.repository_location + '::test', '--strip-components', '0')
  299. def test_extract_include_exclude(self):
  300. self.cmd('init', self.repository_location)
  301. self.create_regular_file('file1', size=1024 * 80)
  302. self.create_regular_file('file2', size=1024 * 80)
  303. self.create_regular_file('file3', size=1024 * 80)
  304. self.create_regular_file('file4', size=1024 * 80)
  305. self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  306. with changedir('output'):
  307. self.cmd('extract', self.repository_location + '::test', 'input/file1', )
  308. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  309. with changedir('output'):
  310. self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test')
  311. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  312. with changedir('output'):
  313. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  314. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  315. def test_exclude_caches(self):
  316. self.cmd('init', self.repository_location)
  317. self.create_regular_file('file1', size=1024 * 80)
  318. self.create_regular_file('cache1/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  319. self.create_regular_file('cache2/CACHEDIR.TAG', contents=b'invalid signature')
  320. self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input')
  321. with changedir('output'):
  322. self.cmd('extract', self.repository_location + '::test')
  323. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  324. self.assert_equal(sorted(os.listdir('output/input/cache2')), ['CACHEDIR.TAG'])
  325. def test_path_normalization(self):
  326. self.cmd('init', self.repository_location)
  327. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  328. with changedir('input/dir1/dir2'):
  329. self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  330. output = self.cmd('list', self.repository_location + '::test')
  331. self.assert_not_in('..', output)
  332. self.assert_in(' input/dir1/dir2/file', output)
  333. def test_exclude_normalization(self):
  334. self.cmd('init', self.repository_location)
  335. self.create_regular_file('file1', size=1024 * 80)
  336. self.create_regular_file('file2', size=1024 * 80)
  337. with changedir('input'):
  338. self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.')
  339. with changedir('output'):
  340. self.cmd('extract', self.repository_location + '::test1')
  341. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  342. with changedir('input'):
  343. self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  344. with changedir('output'):
  345. self.cmd('extract', self.repository_location + '::test2')
  346. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  347. self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  348. with changedir('output'):
  349. self.cmd('extract', self.repository_location + '::test3')
  350. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  351. def test_repeated_files(self):
  352. self.create_regular_file('file1', size=1024 * 80)
  353. self.cmd('init', self.repository_location)
  354. self.cmd('create', self.repository_location + '::test', 'input', 'input')
  355. def test_overwrite(self):
  356. self.create_regular_file('file1', size=1024 * 80)
  357. self.create_regular_file('dir2/file2', size=1024 * 80)
  358. self.cmd('init', self.repository_location)
  359. self.cmd('create', self.repository_location + '::test', 'input')
  360. # Overwriting regular files and directories should be supported
  361. os.mkdir('output/input')
  362. os.mkdir('output/input/file1')
  363. os.mkdir('output/input/dir2')
  364. with changedir('output'):
  365. self.cmd('extract', self.repository_location + '::test')
  366. self.assert_dirs_equal('input', 'output/input')
  367. # But non-empty dirs should fail
  368. os.unlink('output/input/file1')
  369. os.mkdir('output/input/file1')
  370. os.mkdir('output/input/file1/dir')
  371. with changedir('output'):
  372. self.cmd('extract', self.repository_location + '::test', exit_code=1)
  373. def test_rename(self):
  374. self.create_regular_file('file1', size=1024 * 80)
  375. self.create_regular_file('dir2/file2', size=1024 * 80)
  376. self.cmd('init', self.repository_location)
  377. self.cmd('create', self.repository_location + '::test', 'input')
  378. self.cmd('create', self.repository_location + '::test.2', 'input')
  379. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  380. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  381. self.cmd('rename', self.repository_location + '::test', 'test.3')
  382. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  383. self.cmd('rename', self.repository_location + '::test.2', 'test.4')
  384. self.cmd('extract', '--dry-run', self.repository_location + '::test.3')
  385. self.cmd('extract', '--dry-run', self.repository_location + '::test.4')
  386. # Make sure both archives have been renamed
  387. repository = Repository(self.repository_path)
  388. manifest, key = Manifest.load(repository)
  389. self.assert_equal(len(manifest.archives), 2)
  390. self.assert_in('test.3', manifest.archives)
  391. self.assert_in('test.4', manifest.archives)
  392. def test_delete(self):
  393. self.create_regular_file('file1', size=1024 * 80)
  394. self.create_regular_file('dir2/file2', size=1024 * 80)
  395. self.cmd('init', self.repository_location)
  396. self.cmd('create', self.repository_location + '::test', 'input')
  397. self.cmd('create', self.repository_location + '::test.2', 'input')
  398. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  399. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  400. self.cmd('delete', self.repository_location + '::test')
  401. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  402. self.cmd('delete', '--stats', self.repository_location + '::test.2')
  403. # Make sure all data except the manifest has been deleted
  404. repository = Repository(self.repository_path)
  405. self.assert_equal(len(repository), 1)
  406. def test_delete_repo(self):
  407. self.create_regular_file('file1', size=1024 * 80)
  408. self.create_regular_file('dir2/file2', size=1024 * 80)
  409. self.cmd('init', self.repository_location)
  410. self.cmd('create', self.repository_location + '::test', 'input')
  411. self.cmd('create', self.repository_location + '::test.2', 'input')
  412. self.cmd('delete', self.repository_location)
  413. # Make sure the repo is gone
  414. self.assertFalse(os.path.exists(self.repository_path))
  415. def test_corrupted_repository(self):
  416. self.cmd('init', self.repository_location)
  417. self.create_src_archive('test')
  418. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  419. self.cmd('check', self.repository_location)
  420. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  421. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd:
  422. fd.seek(100)
  423. fd.write(b'XXXX')
  424. self.cmd('check', self.repository_location, exit_code=1)
  425. # we currently need to be able to create a lock directory inside the repo:
  426. @pytest.mark.xfail(reason="we need to be able to create the lock directory inside the repo")
  427. def test_readonly_repository(self):
  428. self.cmd('init', self.repository_location)
  429. self.create_src_archive('test')
  430. os.system('chmod -R ugo-w ' + self.repository_path)
  431. try:
  432. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  433. finally:
  434. # Restore permissions so shutil.rmtree is able to delete it
  435. os.system('chmod -R u+w ' + self.repository_path)
  436. def test_umask(self):
  437. self.create_regular_file('file1', size=1024 * 80)
  438. self.cmd('init', self.repository_location)
  439. self.cmd('create', self.repository_location + '::test', 'input')
  440. mode = os.stat(self.repository_path).st_mode
  441. self.assertEqual(stat.S_IMODE(mode), 0o700)
  442. def test_create_dry_run(self):
  443. self.cmd('init', self.repository_location)
  444. self.cmd('create', '--dry-run', self.repository_location + '::test', 'input')
  445. # Make sure no archive has been created
  446. repository = Repository(self.repository_path)
  447. manifest, key = Manifest.load(repository)
  448. self.assert_equal(len(manifest.archives), 0)
  449. def test_cmdline_compatibility(self):
  450. self.create_regular_file('file1', size=1024 * 80)
  451. self.cmd('init', self.repository_location)
  452. self.cmd('create', self.repository_location + '::test', 'input')
  453. output = self.cmd('verify', '-v', self.repository_location + '::test')
  454. self.assert_in('"borg verify" has been deprecated', output)
  455. output = self.cmd('prune', self.repository_location, '--hourly=1')
  456. self.assert_in('"--hourly" has been deprecated. Use "--keep-hourly" instead', output)
  457. def test_prune_repository(self):
  458. self.cmd('init', self.repository_location)
  459. self.cmd('create', self.repository_location + '::test1', src_dir)
  460. self.cmd('create', self.repository_location + '::test2', src_dir)
  461. output = self.cmd('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  462. self.assert_in('Keeping archive: test2', output)
  463. self.assert_in('Would prune: test1', output)
  464. output = self.cmd('list', self.repository_location)
  465. self.assert_in('test1', output)
  466. self.assert_in('test2', output)
  467. self.cmd('prune', self.repository_location, '--keep-daily=2')
  468. output = self.cmd('list', self.repository_location)
  469. self.assert_not_in('test1', output)
  470. self.assert_in('test2', output)
  471. def test_prune_repository_prefix(self):
  472. self.cmd('init', self.repository_location)
  473. self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir)
  474. self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir)
  475. self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
  476. self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
  477. output = self.cmd('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  478. self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
  479. self.assert_in('Would prune: foo-2015-08-12-10:00', output)
  480. output = self.cmd('list', self.repository_location)
  481. self.assert_in('foo-2015-08-12-10:00', output)
  482. self.assert_in('foo-2015-08-12-20:00', output)
  483. self.assert_in('bar-2015-08-12-10:00', output)
  484. self.assert_in('bar-2015-08-12-20:00', output)
  485. self.cmd('prune', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  486. output = self.cmd('list', self.repository_location)
  487. self.assert_not_in('foo-2015-08-12-10:00', output)
  488. self.assert_in('foo-2015-08-12-20:00', output)
  489. self.assert_in('bar-2015-08-12-10:00', output)
  490. self.assert_in('bar-2015-08-12-20:00', output)
  491. def test_usage(self):
  492. self.assert_raises(SystemExit, lambda: self.cmd())
  493. self.assert_raises(SystemExit, lambda: self.cmd('-h'))
  494. def test_help(self):
  495. assert 'Borg' in self.cmd('help')
  496. assert 'patterns' in self.cmd('help', 'patterns')
  497. assert 'Initialize' in self.cmd('help', 'init')
  498. assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only')
  499. assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only')
  500. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  501. def test_fuse_mount_repository(self):
  502. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  503. os.mkdir(mountpoint)
  504. self.cmd('init', self.repository_location)
  505. self.create_test_files()
  506. self.cmd('create', self.repository_location + '::archive', 'input')
  507. self.cmd('create', self.repository_location + '::archive2', 'input')
  508. try:
  509. self.cmd('mount', self.repository_location, mountpoint, fork=True)
  510. self.wait_for_mount(mountpoint)
  511. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  512. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  513. finally:
  514. if sys.platform.startswith('linux'):
  515. os.system('fusermount -u ' + mountpoint)
  516. else:
  517. os.system('umount ' + mountpoint)
  518. os.rmdir(mountpoint)
  519. # Give the daemon some time to exit
  520. time.sleep(.2)
  521. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  522. def test_fuse_mount_archive(self):
  523. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  524. os.mkdir(mountpoint)
  525. self.cmd('init', self.repository_location)
  526. self.create_test_files()
  527. self.cmd('create', self.repository_location + '::archive', 'input')
  528. try:
  529. self.cmd('mount', self.repository_location + '::archive', mountpoint, fork=True)
  530. self.wait_for_mount(mountpoint)
  531. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  532. finally:
  533. if sys.platform.startswith('linux'):
  534. os.system('fusermount -u ' + mountpoint)
  535. else:
  536. os.system('umount ' + mountpoint)
  537. os.rmdir(mountpoint)
  538. # Give the daemon some time to exit
  539. time.sleep(.2)
  540. def verify_aes_counter_uniqueness(self, method):
  541. seen = set() # Chunks already seen
  542. used = set() # counter values already used
  543. def verify_uniqueness():
  544. repository = Repository(self.repository_path)
  545. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  546. data = repository.get(key)
  547. hash = sha256(data).digest()
  548. if hash not in seen:
  549. seen.add(hash)
  550. num_blocks = num_aes_blocks(len(data) - 41)
  551. nonce = bytes_to_long(data[33:41])
  552. for counter in range(nonce, nonce + num_blocks):
  553. self.assert_not_in(counter, used)
  554. used.add(counter)
  555. self.create_test_files()
  556. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  557. self.cmd('init', '--encryption=' + method, self.repository_location)
  558. verify_uniqueness()
  559. self.cmd('create', self.repository_location + '::test', 'input')
  560. verify_uniqueness()
  561. self.cmd('create', self.repository_location + '::test.2', 'input')
  562. verify_uniqueness()
  563. self.cmd('delete', self.repository_location + '::test.2')
  564. verify_uniqueness()
  565. self.assert_equal(used, set(range(len(used))))
  566. def test_aes_counter_uniqueness_keyfile(self):
  567. self.verify_aes_counter_uniqueness('keyfile')
  568. def test_aes_counter_uniqueness_passphrase(self):
  569. self.verify_aes_counter_uniqueness('passphrase')
  570. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  571. def setUp(self):
  572. super().setUp()
  573. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  574. self.cmd('init', self.repository_location)
  575. self.create_src_archive('archive1')
  576. self.create_src_archive('archive2')
  577. def open_archive(self, name):
  578. repository = Repository(self.repository_path)
  579. manifest, key = Manifest.load(repository)
  580. archive = Archive(repository, key, manifest, name)
  581. return archive, repository
  582. def test_check_usage(self):
  583. output = self.cmd('check', self.repository_location, exit_code=0)
  584. self.assert_in('Starting repository check', output)
  585. self.assert_in('Starting archive consistency check', output)
  586. output = self.cmd('check', '--repository-only', self.repository_location, exit_code=0)
  587. self.assert_in('Starting repository check', output)
  588. self.assert_not_in('Starting archive consistency check', output)
  589. output = self.cmd('check', '--archives-only', self.repository_location, exit_code=0)
  590. self.assert_not_in('Starting repository check', output)
  591. self.assert_in('Starting archive consistency check', output)
  592. def test_missing_file_chunk(self):
  593. archive, repository = self.open_archive('archive1')
  594. for item in archive.iter_items():
  595. if item[b'path'].endswith('testsuite/archiver.py'):
  596. repository.delete(item[b'chunks'][-1][0])
  597. break
  598. repository.commit()
  599. self.cmd('check', self.repository_location, exit_code=1)
  600. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  601. self.cmd('check', self.repository_location, exit_code=0)
  602. def test_missing_archive_item_chunk(self):
  603. archive, repository = self.open_archive('archive1')
  604. repository.delete(archive.metadata[b'items'][-5])
  605. repository.commit()
  606. self.cmd('check', self.repository_location, exit_code=1)
  607. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  608. self.cmd('check', self.repository_location, exit_code=0)
  609. def test_missing_archive_metadata(self):
  610. archive, repository = self.open_archive('archive1')
  611. repository.delete(archive.id)
  612. repository.commit()
  613. self.cmd('check', self.repository_location, exit_code=1)
  614. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  615. self.cmd('check', self.repository_location, exit_code=0)
  616. def test_missing_manifest(self):
  617. archive, repository = self.open_archive('archive1')
  618. repository.delete(Manifest.MANIFEST_ID)
  619. repository.commit()
  620. self.cmd('check', self.repository_location, exit_code=1)
  621. output = self.cmd('check', '--repair', self.repository_location, exit_code=0)
  622. self.assert_in('archive1', output)
  623. self.assert_in('archive2', output)
  624. self.cmd('check', self.repository_location, exit_code=0)
  625. def test_extra_chunks(self):
  626. self.cmd('check', self.repository_location, exit_code=0)
  627. repository = Repository(self.repository_location)
  628. repository.put(b'01234567890123456789012345678901', b'xxxx')
  629. repository.commit()
  630. repository.close()
  631. self.cmd('check', self.repository_location, exit_code=1)
  632. self.cmd('check', self.repository_location, exit_code=1)
  633. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  634. self.cmd('check', self.repository_location, exit_code=0)
  635. self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  636. if 0:
  637. class RemoteArchiverTestCase(ArchiverTestCase):
  638. prefix = '__testsuite__:'
  639. def test_remote_repo_restrict_to_path(self):
  640. self.cmd('init', self.repository_location)
  641. path_prefix = os.path.dirname(self.repository_path)
  642. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  643. self.assert_raises(PathNotAllowed, lambda: self.cmd('init', self.repository_location + '_1'))
  644. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  645. self.cmd('init', self.repository_location + '_2')
  646. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  647. self.cmd('init', self.repository_location + '_3')