archiver.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  1. from binascii import hexlify
  2. from configparser import ConfigParser
  3. import errno
  4. import os
  5. import inspect
  6. from io import StringIO
  7. import random
  8. import stat
  9. import subprocess
  10. import sys
  11. import shutil
  12. import tempfile
  13. import time
  14. import unittest
  15. from unittest.mock import patch
  16. from hashlib import sha256
  17. import pytest
  18. from .. import xattr
  19. from ..archive import Archive, ChunkBuffer, ArchiveRecreater
  20. from ..archiver import Archiver
  21. from ..cache import Cache
  22. from ..constants import * # NOQA
  23. from ..crypto import bytes_to_long, num_aes_blocks
  24. from ..helpers import Manifest
  25. from ..key import KeyfileKeyBase
  26. from ..remote import RemoteRepository, PathNotAllowed
  27. from ..repository import Repository
  28. from . import BaseTestCase, changedir, environment_variable
  29. try:
  30. import llfuse
  31. has_llfuse = True or llfuse # avoids "unused import"
  32. except ImportError:
  33. has_llfuse = False
  34. has_lchflags = hasattr(os, 'lchflags')
  35. src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
  36. def exec_cmd(*args, archiver=None, fork=False, exe=None, **kw):
  37. if fork:
  38. try:
  39. if exe is None:
  40. borg = (sys.executable, '-m', 'borg.archiver')
  41. elif isinstance(exe, str):
  42. borg = (exe, )
  43. elif not isinstance(exe, tuple):
  44. raise ValueError('exe must be None, a tuple or a str')
  45. output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT)
  46. ret = 0
  47. except subprocess.CalledProcessError as e:
  48. output = e.output
  49. ret = e.returncode
  50. return ret, os.fsdecode(output)
  51. else:
  52. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  53. try:
  54. sys.stdin = StringIO()
  55. sys.stdout = sys.stderr = output = StringIO()
  56. if archiver is None:
  57. archiver = Archiver()
  58. archiver.exit_code = EXIT_SUCCESS
  59. args = archiver.parse_args(list(args))
  60. ret = archiver.run(args)
  61. return ret, output.getvalue()
  62. finally:
  63. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  64. # check if the binary "borg.exe" is available
  65. try:
  66. exec_cmd('help', exe='borg.exe', fork=True)
  67. BORG_EXES = ['python', 'binary', ]
  68. except FileNotFoundError:
  69. BORG_EXES = ['python', ]
  70. @pytest.fixture(params=BORG_EXES)
  71. def cmd(request):
  72. if request.param == 'python':
  73. exe = None
  74. elif request.param == 'binary':
  75. exe = 'borg.exe'
  76. else:
  77. raise ValueError("param must be 'python' or 'binary'")
  78. def exec_fn(*args, **kw):
  79. return exec_cmd(*args, exe=exe, fork=True, **kw)
  80. return exec_fn
  81. def test_return_codes(cmd, tmpdir):
  82. repo = tmpdir.mkdir('repo')
  83. input = tmpdir.mkdir('input')
  84. output = tmpdir.mkdir('output')
  85. input.join('test_file').write('content')
  86. rc, out = cmd('init', '--encryption=none', '%s' % str(repo))
  87. assert rc == EXIT_SUCCESS
  88. rc, out = cmd('create', '%s::archive' % repo, str(input))
  89. assert rc == EXIT_SUCCESS
  90. with changedir(str(output)):
  91. rc, out = cmd('extract', '%s::archive' % repo)
  92. assert rc == EXIT_SUCCESS
  93. rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match')
  94. assert rc == EXIT_WARNING # pattern did not match
  95. rc, out = cmd('create', '%s::archive' % repo, str(input))
  96. assert rc == EXIT_ERROR # duplicate archive name
  97. """
  98. test_disk_full is very slow and not recommended to be included in daily testing.
  99. for this test, an empty, writable 16MB filesystem mounted on DF_MOUNT is required.
  100. for speed and other reasons, it is recommended that the underlying block device is
  101. in RAM, not a magnetic or flash disk.
  102. assuming /tmp is a tmpfs (in memory filesystem), one can use this:
  103. dd if=/dev/zero of=/tmp/borg-disk bs=16M count=1
  104. mkfs.ext4 /tmp/borg-disk
  105. mkdir /tmp/borg-mount
  106. sudo mount /tmp/borg-disk /tmp/borg-mount
  107. if the directory does not exist, the test will be skipped.
  108. """
  109. DF_MOUNT = '/tmp/borg-mount'
  110. @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT)
  111. def test_disk_full(cmd):
  112. def make_files(dir, count, size, rnd=True):
  113. shutil.rmtree(dir, ignore_errors=True)
  114. os.mkdir(dir)
  115. if rnd:
  116. count = random.randint(1, count)
  117. if size > 1:
  118. size = random.randint(1, size)
  119. for i in range(count):
  120. fn = os.path.join(dir, "file%03d" % i)
  121. with open(fn, 'wb') as f:
  122. data = os.urandom(size)
  123. f.write(data)
  124. with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='YES'):
  125. mount = DF_MOUNT
  126. assert os.path.exists(mount)
  127. repo = os.path.join(mount, 'repo')
  128. input = os.path.join(mount, 'input')
  129. reserve = os.path.join(mount, 'reserve')
  130. for j in range(100):
  131. shutil.rmtree(repo, ignore_errors=True)
  132. shutil.rmtree(input, ignore_errors=True)
  133. # keep some space and some inodes in reserve that we can free up later:
  134. make_files(reserve, 80, 100000, rnd=False)
  135. rc, out = cmd('init', repo)
  136. if rc != EXIT_SUCCESS:
  137. print('init', rc, out)
  138. assert rc == EXIT_SUCCESS
  139. try:
  140. success, i = True, 0
  141. while success:
  142. i += 1
  143. try:
  144. make_files(input, 20, 200000)
  145. except OSError as err:
  146. if err.errno == errno.ENOSPC:
  147. # already out of space
  148. break
  149. raise
  150. try:
  151. rc, out = cmd('create', '%s::test%03d' % (repo, i), input)
  152. success = rc == EXIT_SUCCESS
  153. if not success:
  154. print('create', rc, out)
  155. finally:
  156. # make sure repo is not locked
  157. shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True)
  158. os.remove(os.path.join(repo, 'lock.roster'))
  159. finally:
  160. # now some error happened, likely we are out of disk space.
  161. # free some space so we can expect borg to be able to work normally:
  162. shutil.rmtree(reserve, ignore_errors=True)
  163. rc, out = cmd('list', repo)
  164. if rc != EXIT_SUCCESS:
  165. print('list', rc, out)
  166. rc, out = cmd('check', '--repair', repo)
  167. if rc != EXIT_SUCCESS:
  168. print('check', rc, out)
  169. assert rc == EXIT_SUCCESS
  170. class ArchiverTestCaseBase(BaseTestCase):
  171. EXE = None # python source based
  172. FORK_DEFAULT = False
  173. prefix = ''
  174. def setUp(self):
  175. os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  176. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  177. os.environ['BORG_RECREATE_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  178. os.environ['BORG_PASSPHRASE'] = 'waytooeasyonlyfortests'
  179. self.archiver = not self.FORK_DEFAULT and Archiver() or None
  180. self.tmpdir = tempfile.mkdtemp()
  181. self.repository_path = os.path.join(self.tmpdir, 'repository')
  182. self.repository_location = self.prefix + self.repository_path
  183. self.input_path = os.path.join(self.tmpdir, 'input')
  184. self.output_path = os.path.join(self.tmpdir, 'output')
  185. self.keys_path = os.path.join(self.tmpdir, 'keys')
  186. self.cache_path = os.path.join(self.tmpdir, 'cache')
  187. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  188. os.environ['BORG_KEYS_DIR'] = self.keys_path
  189. os.environ['BORG_CACHE_DIR'] = self.cache_path
  190. os.mkdir(self.input_path)
  191. os.mkdir(self.output_path)
  192. os.mkdir(self.keys_path)
  193. os.mkdir(self.cache_path)
  194. with open(self.exclude_file_path, 'wb') as fd:
  195. fd.write(b'input/file2\n# A comment line, then a blank line\n\n')
  196. self._old_wd = os.getcwd()
  197. os.chdir(self.tmpdir)
  198. def tearDown(self):
  199. os.chdir(self._old_wd)
  200. shutil.rmtree(self.tmpdir)
  201. def cmd(self, *args, **kw):
  202. exit_code = kw.pop('exit_code', 0)
  203. fork = kw.pop('fork', None)
  204. if fork is None:
  205. fork = self.FORK_DEFAULT
  206. ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw)
  207. if ret != exit_code:
  208. print(output)
  209. self.assert_equal(ret, exit_code)
  210. return output
  211. def create_src_archive(self, name):
  212. self.cmd('create', self.repository_location + '::' + name, src_dir)
  213. def create_regular_file(self, name, size=0, contents=None):
  214. filename = os.path.join(self.input_path, name)
  215. if not os.path.exists(os.path.dirname(filename)):
  216. os.makedirs(os.path.dirname(filename))
  217. with open(filename, 'wb') as fd:
  218. if contents is None:
  219. contents = b'X' * size
  220. fd.write(contents)
  221. def create_test_files(self):
  222. """Create a minimal test case including all supported file types
  223. """
  224. # File
  225. self.create_regular_file('empty', size=0)
  226. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  227. # 2600-01-01 > 2**64 ns
  228. # os.utime('input/empty', (19880895600, 19880895600))
  229. # thus, we better test with something not that far in future:
  230. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  231. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  232. self.create_regular_file('file1', size=1024 * 80)
  233. self.create_regular_file('flagfile', size=1024)
  234. # Directory
  235. self.create_regular_file('dir2/file2', size=1024 * 80)
  236. # File mode
  237. os.chmod('input/file1', 0o4755)
  238. # Hard link
  239. os.link(os.path.join(self.input_path, 'file1'),
  240. os.path.join(self.input_path, 'hardlink'))
  241. # Symlink
  242. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  243. if xattr.is_enabled(self.input_path):
  244. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  245. # XXX this always fails for me
  246. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  247. # same for newer ubuntu and centos.
  248. # if this is supported just on specific platform, platform should be checked first,
  249. # so that the test setup for all tests using it does not fail here always for others.
  250. # xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  251. # FIFO node
  252. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  253. if has_lchflags:
  254. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  255. try:
  256. # Block device
  257. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  258. # Char device
  259. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  260. # File mode
  261. os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents
  262. # File owner
  263. os.chown('input/file1', 100, 200)
  264. have_root = True # we have (fake)root
  265. except PermissionError:
  266. have_root = False
  267. return have_root
  268. class ArchiverTestCase(ArchiverTestCaseBase):
  269. def test_basic_functionality(self):
  270. have_root = self.create_test_files()
  271. self.cmd('init', self.repository_location)
  272. self.cmd('create', self.repository_location + '::test', 'input')
  273. self.cmd('create', '--stats', self.repository_location + '::test.2', 'input')
  274. with changedir('output'):
  275. self.cmd('extract', self.repository_location + '::test')
  276. list_output = self.cmd('list', '--short', self.repository_location)
  277. self.assert_in('test', list_output)
  278. self.assert_in('test.2', list_output)
  279. expected = [
  280. 'input',
  281. 'input/bdev',
  282. 'input/cdev',
  283. 'input/dir2',
  284. 'input/dir2/file2',
  285. 'input/empty',
  286. 'input/fifo1',
  287. 'input/file1',
  288. 'input/flagfile',
  289. 'input/hardlink',
  290. 'input/link1',
  291. ]
  292. if not have_root:
  293. # we could not create these device files without (fake)root
  294. expected.remove('input/bdev')
  295. expected.remove('input/cdev')
  296. if has_lchflags:
  297. # remove the file we did not backup, so input and output become equal
  298. expected.remove('input/flagfile') # this file is UF_NODUMP
  299. os.remove(os.path.join('input', 'flagfile'))
  300. list_output = self.cmd('list', '--short', self.repository_location + '::test')
  301. for name in expected:
  302. self.assert_in(name, list_output)
  303. self.assert_dirs_equal('input', 'output/input')
  304. info_output = self.cmd('info', self.repository_location + '::test')
  305. item_count = 3 if has_lchflags else 4 # one file is UF_NODUMP
  306. self.assert_in('Number of files: %d' % item_count, info_output)
  307. shutil.rmtree(self.cache_path)
  308. with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='yes'):
  309. info_output2 = self.cmd('info', self.repository_location + '::test')
  310. def filter(output):
  311. # filter for interesting "info" output, ignore cache rebuilding related stuff
  312. prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:',
  313. 'All archives:', 'Chunk index:', ]
  314. result = []
  315. for line in output.splitlines():
  316. for prefix in prefixes:
  317. if line.startswith(prefix):
  318. result.append(line)
  319. return '\n'.join(result)
  320. # the interesting parts of info_output2 and info_output should be same
  321. self.assert_equal(filter(info_output), filter(info_output2))
  322. def test_atime(self):
  323. self.create_test_files()
  324. atime, mtime = 123456780, 234567890
  325. os.utime('input/file1', (atime, mtime))
  326. self.cmd('init', self.repository_location)
  327. self.cmd('create', self.repository_location + '::test', 'input')
  328. with changedir('output'):
  329. self.cmd('extract', self.repository_location + '::test')
  330. sti = os.stat('input/file1')
  331. sto = os.stat('output/input/file1')
  332. assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9
  333. if hasattr(os, 'O_NOATIME'):
  334. assert sti.st_atime_ns == sto.st_atime_ns == atime * 1e9
  335. else:
  336. # it touched the input file's atime while backing it up
  337. assert sto.st_atime_ns == atime * 1e9
  338. def _extract_repository_id(self, path):
  339. with Repository(self.repository_path) as repository:
  340. return repository.id
  341. def _set_repository_id(self, path, id):
  342. config = ConfigParser(interpolation=None)
  343. config.read(os.path.join(path, 'config'))
  344. config.set('repository', 'id', hexlify(id).decode('ascii'))
  345. with open(os.path.join(path, 'config'), 'w') as fd:
  346. config.write(fd)
  347. with Repository(self.repository_path) as repository:
  348. return repository.id
  349. def test_sparse_file(self):
  350. # no sparse file support on Mac OS X
  351. sparse_support = sys.platform != 'darwin'
  352. filename = os.path.join(self.input_path, 'sparse')
  353. content = b'foobar'
  354. hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers
  355. with open(filename, 'wb') as fd:
  356. # create a file that has a hole at the beginning and end (if the
  357. # OS and filesystem supports sparse files)
  358. fd.seek(hole_size, 1)
  359. fd.write(content)
  360. fd.seek(hole_size, 1)
  361. pos = fd.tell()
  362. fd.truncate(pos)
  363. total_len = hole_size + len(content) + hole_size
  364. st = os.stat(filename)
  365. self.assert_equal(st.st_size, total_len)
  366. if sparse_support and hasattr(st, 'st_blocks'):
  367. self.assert_true(st.st_blocks * 512 < total_len / 9) # is input sparse?
  368. self.cmd('init', self.repository_location)
  369. self.cmd('create', self.repository_location + '::test', 'input')
  370. with changedir('output'):
  371. self.cmd('extract', '--sparse', self.repository_location + '::test')
  372. self.assert_dirs_equal('input', 'output/input')
  373. filename = os.path.join(self.output_path, 'input', 'sparse')
  374. with open(filename, 'rb') as fd:
  375. # check if file contents are as expected
  376. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  377. self.assert_equal(fd.read(len(content)), content)
  378. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  379. st = os.stat(filename)
  380. self.assert_equal(st.st_size, total_len)
  381. if sparse_support and hasattr(st, 'st_blocks'):
  382. self.assert_true(st.st_blocks * 512 < total_len / 9) # is output sparse?
  383. def test_unusual_filenames(self):
  384. filenames = ['normal', 'with some blanks', '(with_parens)', ]
  385. for filename in filenames:
  386. filename = os.path.join(self.input_path, filename)
  387. with open(filename, 'wb'):
  388. pass
  389. self.cmd('init', self.repository_location)
  390. self.cmd('create', self.repository_location + '::test', 'input')
  391. for filename in filenames:
  392. with changedir('output'):
  393. self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename))
  394. assert os.path.exists(os.path.join('output', 'input', filename))
  395. def test_repository_swap_detection(self):
  396. self.create_test_files()
  397. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  398. self.cmd('init', '--encryption=repokey', self.repository_location)
  399. repository_id = self._extract_repository_id(self.repository_path)
  400. self.cmd('create', self.repository_location + '::test', 'input')
  401. shutil.rmtree(self.repository_path)
  402. self.cmd('init', '--encryption=none', self.repository_location)
  403. self._set_repository_id(self.repository_path, repository_id)
  404. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  405. if self.FORK_DEFAULT:
  406. self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR)
  407. else:
  408. self.assert_raises(Cache.EncryptionMethodMismatch, lambda: self.cmd('create', self.repository_location + '::test.2', 'input'))
  409. def test_repository_swap_detection2(self):
  410. self.create_test_files()
  411. self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted')
  412. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  413. self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted')
  414. self.cmd('create', self.repository_location + '_encrypted::test', 'input')
  415. shutil.rmtree(self.repository_path + '_encrypted')
  416. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  417. if self.FORK_DEFAULT:
  418. self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR)
  419. else:
  420. self.assert_raises(Cache.RepositoryAccessAborted, lambda: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input'))
  421. def test_strip_components(self):
  422. self.cmd('init', self.repository_location)
  423. self.create_regular_file('dir/file')
  424. self.cmd('create', self.repository_location + '::test', 'input')
  425. with changedir('output'):
  426. self.cmd('extract', self.repository_location + '::test', '--strip-components', '3')
  427. self.assert_true(not os.path.exists('file'))
  428. with self.assert_creates_file('file'):
  429. self.cmd('extract', self.repository_location + '::test', '--strip-components', '2')
  430. with self.assert_creates_file('dir/file'):
  431. self.cmd('extract', self.repository_location + '::test', '--strip-components', '1')
  432. with self.assert_creates_file('input/dir/file'):
  433. self.cmd('extract', self.repository_location + '::test', '--strip-components', '0')
  434. def _extract_hardlinks_setup(self):
  435. os.mkdir(os.path.join(self.input_path, 'dir1'))
  436. os.mkdir(os.path.join(self.input_path, 'dir1/subdir'))
  437. self.create_regular_file('source')
  438. os.link(os.path.join(self.input_path, 'source'),
  439. os.path.join(self.input_path, 'abba'))
  440. os.link(os.path.join(self.input_path, 'source'),
  441. os.path.join(self.input_path, 'dir1/hardlink'))
  442. os.link(os.path.join(self.input_path, 'source'),
  443. os.path.join(self.input_path, 'dir1/subdir/hardlink'))
  444. self.create_regular_file('dir1/source2')
  445. os.link(os.path.join(self.input_path, 'dir1/source2'),
  446. os.path.join(self.input_path, 'dir1/aaaa'))
  447. self.cmd('init', self.repository_location)
  448. self.cmd('create', self.repository_location + '::test', 'input')
  449. def test_strip_components_links(self):
  450. self._extract_hardlinks_setup()
  451. with changedir('output'):
  452. self.cmd('extract', self.repository_location + '::test', '--strip-components', '2')
  453. assert os.stat('hardlink').st_nlink == 2
  454. assert os.stat('subdir/hardlink').st_nlink == 2
  455. assert os.stat('aaaa').st_nlink == 2
  456. assert os.stat('source2').st_nlink == 2
  457. with changedir('output'):
  458. self.cmd('extract', self.repository_location + '::test')
  459. assert os.stat('input/dir1/hardlink').st_nlink == 4
  460. def test_extract_hardlinks(self):
  461. self._extract_hardlinks_setup()
  462. with changedir('output'):
  463. self.cmd('extract', self.repository_location + '::test', 'input/dir1')
  464. assert os.stat('input/dir1/hardlink').st_nlink == 2
  465. assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2
  466. assert os.stat('input/dir1/aaaa').st_nlink == 2
  467. assert os.stat('input/dir1/source2').st_nlink == 2
  468. with changedir('output'):
  469. self.cmd('extract', self.repository_location + '::test')
  470. assert os.stat('input/dir1/hardlink').st_nlink == 4
  471. def test_extract_include_exclude(self):
  472. self.cmd('init', self.repository_location)
  473. self.create_regular_file('file1', size=1024 * 80)
  474. self.create_regular_file('file2', size=1024 * 80)
  475. self.create_regular_file('file3', size=1024 * 80)
  476. self.create_regular_file('file4', size=1024 * 80)
  477. self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  478. with changedir('output'):
  479. self.cmd('extract', self.repository_location + '::test', 'input/file1', )
  480. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  481. with changedir('output'):
  482. self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test')
  483. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  484. with changedir('output'):
  485. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  486. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  487. def test_extract_include_exclude_regex(self):
  488. self.cmd('init', self.repository_location)
  489. self.create_regular_file('file1', size=1024 * 80)
  490. self.create_regular_file('file2', size=1024 * 80)
  491. self.create_regular_file('file3', size=1024 * 80)
  492. self.create_regular_file('file4', size=1024 * 80)
  493. self.create_regular_file('file333', size=1024 * 80)
  494. # Create with regular expression exclusion for file4
  495. self.cmd('create', '--exclude=re:input/file4$', self.repository_location + '::test', 'input')
  496. with changedir('output'):
  497. self.cmd('extract', self.repository_location + '::test')
  498. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333'])
  499. shutil.rmtree('output/input')
  500. # Extract with regular expression exclusion
  501. with changedir('output'):
  502. self.cmd('extract', '--exclude=re:file3+', self.repository_location + '::test')
  503. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2'])
  504. shutil.rmtree('output/input')
  505. # Combine --exclude with fnmatch and regular expression
  506. with changedir('output'):
  507. self.cmd('extract', '--exclude=input/file2', '--exclude=re:file[01]', self.repository_location + '::test')
  508. self.assert_equal(sorted(os.listdir('output/input')), ['file3', 'file333'])
  509. shutil.rmtree('output/input')
  510. # Combine --exclude-from and regular expression exclusion
  511. with changedir('output'):
  512. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, '--exclude=re:file1',
  513. '--exclude=re:file(\\d)\\1\\1$', self.repository_location + '::test')
  514. self.assert_equal(sorted(os.listdir('output/input')), ['file3'])
  515. def test_extract_include_exclude_regex_from_file(self):
  516. self.cmd('init', self.repository_location)
  517. self.create_regular_file('file1', size=1024 * 80)
  518. self.create_regular_file('file2', size=1024 * 80)
  519. self.create_regular_file('file3', size=1024 * 80)
  520. self.create_regular_file('file4', size=1024 * 80)
  521. self.create_regular_file('file333', size=1024 * 80)
  522. self.create_regular_file('aa:something', size=1024 * 80)
  523. # Create while excluding using mixed pattern styles
  524. with open(self.exclude_file_path, 'wb') as fd:
  525. fd.write(b're:input/file4$\n')
  526. fd.write(b'fm:*aa:*thing\n')
  527. self.cmd('create', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test', 'input')
  528. with changedir('output'):
  529. self.cmd('extract', self.repository_location + '::test')
  530. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333'])
  531. shutil.rmtree('output/input')
  532. # Exclude using regular expression
  533. with open(self.exclude_file_path, 'wb') as fd:
  534. fd.write(b're:file3+\n')
  535. with changedir('output'):
  536. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  537. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2'])
  538. shutil.rmtree('output/input')
  539. # Mixed exclude pattern styles
  540. with open(self.exclude_file_path, 'wb') as fd:
  541. fd.write(b're:file(\\d)\\1\\1$\n')
  542. fd.write(b'fm:nothingwillmatchthis\n')
  543. fd.write(b'*/file1\n')
  544. fd.write(b're:file2$\n')
  545. with changedir('output'):
  546. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  547. self.assert_equal(sorted(os.listdir('output/input')), ['file3'])
  548. def test_extract_with_pattern(self):
  549. self.cmd("init", self.repository_location)
  550. self.create_regular_file("file1", size=1024 * 80)
  551. self.create_regular_file("file2", size=1024 * 80)
  552. self.create_regular_file("file3", size=1024 * 80)
  553. self.create_regular_file("file4", size=1024 * 80)
  554. self.create_regular_file("file333", size=1024 * 80)
  555. self.cmd("create", self.repository_location + "::test", "input")
  556. # Extract everything with regular expression
  557. with changedir("output"):
  558. self.cmd("extract", self.repository_location + "::test", "re:.*")
  559. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file3", "file333", "file4"])
  560. shutil.rmtree("output/input")
  561. # Extract with pattern while also excluding files
  562. with changedir("output"):
  563. self.cmd("extract", "--exclude=re:file[34]$", self.repository_location + "::test", r"re:file\d$")
  564. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2"])
  565. shutil.rmtree("output/input")
  566. # Combine --exclude with pattern for extraction
  567. with changedir("output"):
  568. self.cmd("extract", "--exclude=input/file1", self.repository_location + "::test", "re:file[12]$")
  569. self.assert_equal(sorted(os.listdir("output/input")), ["file2"])
  570. shutil.rmtree("output/input")
  571. # Multiple pattern
  572. with changedir("output"):
  573. self.cmd("extract", self.repository_location + "::test", "fm:input/file1", "fm:*file33*", "input/file2")
  574. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file333"])
  575. def _create_test_caches(self):
  576. self.cmd('init', self.repository_location)
  577. self.create_regular_file('file1', size=1024 * 80)
  578. self.create_regular_file('cache1/%s' % CACHE_TAG_NAME,
  579. contents=CACHE_TAG_CONTENTS + b' extra stuff')
  580. self.create_regular_file('cache2/%s' % CACHE_TAG_NAME,
  581. contents=b'invalid signature')
  582. os.mkdir('input/cache3')
  583. os.link('input/cache1/%s' % CACHE_TAG_NAME, 'input/cache3/%s' % CACHE_TAG_NAME)
  584. def _assert_test_caches(self):
  585. with changedir('output'):
  586. self.cmd('extract', self.repository_location + '::test')
  587. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  588. self.assert_equal(sorted(os.listdir('output/input/cache2')), [CACHE_TAG_NAME])
  589. def test_exclude_caches(self):
  590. self._create_test_caches()
  591. self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input')
  592. self._assert_test_caches()
  593. def test_recreate_exclude_caches(self):
  594. self._create_test_caches()
  595. self.cmd('create', self.repository_location + '::test', 'input')
  596. self.cmd('recreate', '--exclude-caches', self.repository_location + '::test')
  597. self._assert_test_caches()
  598. def _create_test_tagged(self):
  599. self.cmd('init', self.repository_location)
  600. self.create_regular_file('file1', size=1024 * 80)
  601. self.create_regular_file('tagged1/.NOBACKUP')
  602. self.create_regular_file('tagged2/00-NOBACKUP')
  603. self.create_regular_file('tagged3/.NOBACKUP/file2')
  604. def _assert_test_tagged(self):
  605. with changedir('output'):
  606. self.cmd('extract', self.repository_location + '::test')
  607. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'tagged3'])
  608. def test_exclude_tagged(self):
  609. self._create_test_tagged()
  610. self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input')
  611. self._assert_test_tagged()
  612. def test_recreate_exclude_tagged(self):
  613. self._create_test_tagged()
  614. self.cmd('create', self.repository_location + '::test', 'input')
  615. self.cmd('recreate', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP',
  616. self.repository_location + '::test')
  617. self._assert_test_tagged()
  618. def _create_test_keep_tagged(self):
  619. self.cmd('init', self.repository_location)
  620. self.create_regular_file('file0', size=1024)
  621. self.create_regular_file('tagged1/.NOBACKUP1')
  622. self.create_regular_file('tagged1/file1', size=1024)
  623. self.create_regular_file('tagged2/.NOBACKUP2')
  624. self.create_regular_file('tagged2/file2', size=1024)
  625. self.create_regular_file('tagged3/%s' % CACHE_TAG_NAME,
  626. contents=CACHE_TAG_CONTENTS + b' extra stuff')
  627. self.create_regular_file('tagged3/file3', size=1024)
  628. self.create_regular_file('taggedall/.NOBACKUP1')
  629. self.create_regular_file('taggedall/.NOBACKUP2')
  630. self.create_regular_file('taggedall/%s' % CACHE_TAG_NAME,
  631. contents=CACHE_TAG_CONTENTS + b' extra stuff')
  632. self.create_regular_file('taggedall/file4', size=1024)
  633. def _assert_test_keep_tagged(self):
  634. with changedir('output'):
  635. self.cmd('extract', self.repository_location + '::test')
  636. self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall'])
  637. self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1'])
  638. self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2'])
  639. self.assert_equal(os.listdir('output/input/tagged3'), [CACHE_TAG_NAME])
  640. self.assert_equal(sorted(os.listdir('output/input/taggedall')),
  641. ['.NOBACKUP1', '.NOBACKUP2', CACHE_TAG_NAME, ])
  642. def test_exclude_keep_tagged(self):
  643. self._create_test_keep_tagged()
  644. self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2',
  645. '--exclude-caches', '--keep-tag-files', self.repository_location + '::test', 'input')
  646. self._assert_test_keep_tagged()
  647. def test_recreate_exclude_keep_tagged(self):
  648. self._create_test_keep_tagged()
  649. self.cmd('create', self.repository_location + '::test', 'input')
  650. self.cmd('recreate', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2',
  651. '--exclude-caches', '--keep-tag-files', self.repository_location + '::test')
  652. self._assert_test_keep_tagged()
  653. def test_path_normalization(self):
  654. self.cmd('init', self.repository_location)
  655. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  656. with changedir('input/dir1/dir2'):
  657. self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  658. output = self.cmd('list', self.repository_location + '::test')
  659. self.assert_not_in('..', output)
  660. self.assert_in(' input/dir1/dir2/file', output)
  661. def test_exclude_normalization(self):
  662. self.cmd('init', self.repository_location)
  663. self.create_regular_file('file1', size=1024 * 80)
  664. self.create_regular_file('file2', size=1024 * 80)
  665. with changedir('input'):
  666. self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.')
  667. with changedir('output'):
  668. self.cmd('extract', self.repository_location + '::test1')
  669. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  670. with changedir('input'):
  671. self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  672. with changedir('output'):
  673. self.cmd('extract', self.repository_location + '::test2')
  674. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  675. self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  676. with changedir('output'):
  677. self.cmd('extract', self.repository_location + '::test3')
  678. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  679. def test_repeated_files(self):
  680. self.create_regular_file('file1', size=1024 * 80)
  681. self.cmd('init', self.repository_location)
  682. self.cmd('create', self.repository_location + '::test', 'input', 'input')
  683. def test_overwrite(self):
  684. self.create_regular_file('file1', size=1024 * 80)
  685. self.create_regular_file('dir2/file2', size=1024 * 80)
  686. self.cmd('init', self.repository_location)
  687. self.cmd('create', self.repository_location + '::test', 'input')
  688. # Overwriting regular files and directories should be supported
  689. os.mkdir('output/input')
  690. os.mkdir('output/input/file1')
  691. os.mkdir('output/input/dir2')
  692. with changedir('output'):
  693. self.cmd('extract', self.repository_location + '::test')
  694. self.assert_dirs_equal('input', 'output/input')
  695. # But non-empty dirs should fail
  696. os.unlink('output/input/file1')
  697. os.mkdir('output/input/file1')
  698. os.mkdir('output/input/file1/dir')
  699. with changedir('output'):
  700. self.cmd('extract', self.repository_location + '::test', exit_code=1)
  701. def test_rename(self):
  702. self.create_regular_file('file1', size=1024 * 80)
  703. self.create_regular_file('dir2/file2', size=1024 * 80)
  704. self.cmd('init', self.repository_location)
  705. self.cmd('create', self.repository_location + '::test', 'input')
  706. self.cmd('create', self.repository_location + '::test.2', 'input')
  707. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  708. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  709. self.cmd('rename', self.repository_location + '::test', 'test.3')
  710. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  711. self.cmd('rename', self.repository_location + '::test.2', 'test.4')
  712. self.cmd('extract', '--dry-run', self.repository_location + '::test.3')
  713. self.cmd('extract', '--dry-run', self.repository_location + '::test.4')
  714. # Make sure both archives have been renamed
  715. with Repository(self.repository_path) as repository:
  716. manifest, key = Manifest.load(repository)
  717. self.assert_equal(len(manifest.archives), 2)
  718. self.assert_in('test.3', manifest.archives)
  719. self.assert_in('test.4', manifest.archives)
  720. def test_comment(self):
  721. self.create_regular_file('file1', size=1024 * 80)
  722. self.cmd('init', self.repository_location)
  723. self.cmd('create', self.repository_location + '::test1', 'input')
  724. self.cmd('create', '--comment', 'this is the comment', self.repository_location + '::test2', 'input')
  725. self.cmd('create', '--comment', '"deleted" comment', self.repository_location + '::test3', 'input')
  726. self.cmd('create', '--comment', 'preserved comment', self.repository_location + '::test4', 'input')
  727. assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test1')
  728. assert 'Comment: this is the comment' in self.cmd('info', self.repository_location + '::test2')
  729. self.cmd('recreate', self.repository_location + '::test1', '--comment', 'added comment')
  730. self.cmd('recreate', self.repository_location + '::test2', '--comment', 'modified comment')
  731. self.cmd('recreate', self.repository_location + '::test3', '--comment', '')
  732. self.cmd('recreate', self.repository_location + '::test4', '12345')
  733. assert 'Comment: added comment' in self.cmd('info', self.repository_location + '::test1')
  734. assert 'Comment: modified comment' in self.cmd('info', self.repository_location + '::test2')
  735. assert 'Comment: \n' in self.cmd('info', self.repository_location + '::test3')
  736. assert 'Comment: preserved comment' in self.cmd('info', self.repository_location + '::test4')
  737. def test_delete(self):
  738. self.create_regular_file('file1', size=1024 * 80)
  739. self.create_regular_file('dir2/file2', size=1024 * 80)
  740. self.cmd('init', self.repository_location)
  741. self.cmd('create', self.repository_location + '::test', 'input')
  742. self.cmd('create', self.repository_location + '::test.2', 'input')
  743. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  744. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  745. self.cmd('delete', self.repository_location + '::test')
  746. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  747. self.cmd('delete', '--stats', self.repository_location + '::test.2')
  748. # Make sure all data except the manifest has been deleted
  749. with Repository(self.repository_path) as repository:
  750. self.assert_equal(len(repository), 1)
  751. def test_delete_repo(self):
  752. self.create_regular_file('file1', size=1024 * 80)
  753. self.create_regular_file('dir2/file2', size=1024 * 80)
  754. self.cmd('init', self.repository_location)
  755. self.cmd('create', self.repository_location + '::test', 'input')
  756. self.cmd('create', self.repository_location + '::test.2', 'input')
  757. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'no'
  758. self.cmd('delete', self.repository_location, exit_code=2)
  759. assert os.path.exists(self.repository_path)
  760. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  761. self.cmd('delete', self.repository_location)
  762. # Make sure the repo is gone
  763. self.assertFalse(os.path.exists(self.repository_path))
  764. def test_corrupted_repository(self):
  765. self.cmd('init', self.repository_location)
  766. self.create_src_archive('test')
  767. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  768. self.cmd('check', self.repository_location)
  769. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  770. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd:
  771. fd.seek(100)
  772. fd.write(b'XXXX')
  773. self.cmd('check', self.repository_location, exit_code=1)
  774. # we currently need to be able to create a lock directory inside the repo:
  775. @pytest.mark.xfail(reason="we need to be able to create the lock directory inside the repo")
  776. def test_readonly_repository(self):
  777. self.cmd('init', self.repository_location)
  778. self.create_src_archive('test')
  779. os.system('chmod -R ugo-w ' + self.repository_path)
  780. try:
  781. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  782. finally:
  783. # Restore permissions so shutil.rmtree is able to delete it
  784. os.system('chmod -R u+w ' + self.repository_path)
  785. def test_umask(self):
  786. self.create_regular_file('file1', size=1024 * 80)
  787. self.cmd('init', self.repository_location)
  788. self.cmd('create', self.repository_location + '::test', 'input')
  789. mode = os.stat(self.repository_path).st_mode
  790. self.assertEqual(stat.S_IMODE(mode), 0o700)
  791. def test_create_dry_run(self):
  792. self.cmd('init', self.repository_location)
  793. self.cmd('create', '--dry-run', self.repository_location + '::test', 'input')
  794. # Make sure no archive has been created
  795. with Repository(self.repository_path) as repository:
  796. manifest, key = Manifest.load(repository)
  797. self.assert_equal(len(manifest.archives), 0)
  798. def test_progress(self):
  799. self.create_regular_file('file1', size=1024 * 80)
  800. self.cmd('init', self.repository_location)
  801. # progress forced on
  802. output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input')
  803. self.assert_in("\r", output)
  804. # progress forced off
  805. output = self.cmd('create', self.repository_location + '::test5', 'input')
  806. self.assert_not_in("\r", output)
  807. def test_file_status(self):
  808. """test that various file status show expected results
  809. clearly incomplete: only tests for the weird "unchanged" status for now"""
  810. now = time.time()
  811. self.create_regular_file('file1', size=1024 * 80)
  812. os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
  813. self.create_regular_file('file2', size=1024 * 80)
  814. self.cmd('init', self.repository_location)
  815. output = self.cmd('create', '-v', '--list', self.repository_location + '::test', 'input')
  816. self.assert_in("A input/file1", output)
  817. self.assert_in("A input/file2", output)
  818. # should find first file as unmodified
  819. output = self.cmd('create', '-v', '--list', self.repository_location + '::test1', 'input')
  820. self.assert_in("U input/file1", output)
  821. # this is expected, although surprising, for why, see:
  822. # https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file
  823. self.assert_in("A input/file2", output)
  824. def test_file_status_excluded(self):
  825. """test that excluded paths are listed"""
  826. now = time.time()
  827. self.create_regular_file('file1', size=1024 * 80)
  828. os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
  829. self.create_regular_file('file2', size=1024 * 80)
  830. self.cmd('init', self.repository_location)
  831. output = self.cmd('create', '-v', '--list', self.repository_location + '::test', 'input')
  832. self.assert_in("A input/file1", output)
  833. self.assert_in("A input/file2", output)
  834. # should find second file as excluded
  835. output = self.cmd('create', '-v', '--list', self.repository_location + '::test1', 'input', '--exclude', '*/file2')
  836. self.assert_in("U input/file1", output)
  837. self.assert_in("x input/file2", output)
  838. def test_create_topical(self):
  839. now = time.time()
  840. self.create_regular_file('file1', size=1024 * 80)
  841. os.utime('input/file1', (now-5, now-5))
  842. self.create_regular_file('file2', size=1024 * 80)
  843. self.cmd('init', self.repository_location)
  844. # no listing by default
  845. output = self.cmd('create', self.repository_location + '::test', 'input')
  846. self.assert_not_in('file1', output)
  847. # shouldn't be listed even if unchanged
  848. output = self.cmd('create', self.repository_location + '::test0', 'input')
  849. self.assert_not_in('file1', output)
  850. # should list the file as unchanged
  851. output = self.cmd('create', '-v', '--list', '--filter=U', self.repository_location + '::test1', 'input')
  852. self.assert_in('file1', output)
  853. # should *not* list the file as changed
  854. output = self.cmd('create', '-v', '--filter=AM', self.repository_location + '::test2', 'input')
  855. self.assert_not_in('file1', output)
  856. # change the file
  857. self.create_regular_file('file1', size=1024 * 100)
  858. # should list the file as changed
  859. output = self.cmd('create', '-v', '--list', '--filter=AM', self.repository_location + '::test3', 'input')
  860. self.assert_in('file1', output)
  861. # def test_cmdline_compatibility(self):
  862. # self.create_regular_file('file1', size=1024 * 80)
  863. # self.cmd('init', self.repository_location)
  864. # self.cmd('create', self.repository_location + '::test', 'input')
  865. # output = self.cmd('foo', self.repository_location, '--old')
  866. # self.assert_in('"--old" has been deprecated. Use "--new" instead', output)
  867. def test_prune_repository(self):
  868. self.cmd('init', self.repository_location)
  869. self.cmd('create', self.repository_location + '::test1', src_dir)
  870. self.cmd('create', self.repository_location + '::test2', src_dir)
  871. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
  872. self.assert_in('Keeping archive: test2', output)
  873. self.assert_in('Would prune: test1', output)
  874. output = self.cmd('list', self.repository_location)
  875. self.assert_in('test1', output)
  876. self.assert_in('test2', output)
  877. self.cmd('prune', self.repository_location, '--keep-daily=2')
  878. output = self.cmd('list', self.repository_location)
  879. self.assert_not_in('test1', output)
  880. self.assert_in('test2', output)
  881. def test_prune_repository_save_space(self):
  882. self.cmd('init', self.repository_location)
  883. self.cmd('create', self.repository_location + '::test1', src_dir)
  884. self.cmd('create', self.repository_location + '::test2', src_dir)
  885. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
  886. self.assert_in('Keeping archive: test2', output)
  887. self.assert_in('Would prune: test1', output)
  888. output = self.cmd('list', self.repository_location)
  889. self.assert_in('test1', output)
  890. self.assert_in('test2', output)
  891. self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=2')
  892. output = self.cmd('list', self.repository_location)
  893. self.assert_not_in('test1', output)
  894. self.assert_in('test2', output)
  895. def test_prune_repository_prefix(self):
  896. self.cmd('init', self.repository_location)
  897. self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir)
  898. self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir)
  899. self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
  900. self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
  901. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  902. self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
  903. self.assert_in('Would prune: foo-2015-08-12-10:00', output)
  904. output = self.cmd('list', self.repository_location)
  905. self.assert_in('foo-2015-08-12-10:00', output)
  906. self.assert_in('foo-2015-08-12-20:00', output)
  907. self.assert_in('bar-2015-08-12-10:00', output)
  908. self.assert_in('bar-2015-08-12-20:00', output)
  909. self.cmd('prune', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  910. output = self.cmd('list', self.repository_location)
  911. self.assert_not_in('foo-2015-08-12-10:00', output)
  912. self.assert_in('foo-2015-08-12-20:00', output)
  913. self.assert_in('bar-2015-08-12-10:00', output)
  914. self.assert_in('bar-2015-08-12-20:00', output)
  915. def test_list_prefix(self):
  916. self.cmd('init', self.repository_location)
  917. self.cmd('create', self.repository_location + '::test-1', src_dir)
  918. self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir)
  919. self.cmd('create', self.repository_location + '::test-2', src_dir)
  920. output = self.cmd('list', '--prefix=test-', self.repository_location)
  921. self.assert_in('test-1', output)
  922. self.assert_in('test-2', output)
  923. self.assert_not_in('something-else', output)
  924. def test_list_format(self):
  925. self.cmd('init', self.repository_location)
  926. test_archive = self.repository_location + '::test'
  927. self.cmd('create', test_archive, src_dir)
  928. self.cmd('list', '--list-format', '-', test_archive, exit_code=1)
  929. self.archiver.exit_code = 0 # reset exit code for following tests
  930. output_1 = self.cmd('list', test_archive)
  931. output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NEWLINE}', test_archive)
  932. output_3 = self.cmd('list', '--format', '{mtime:%s} {path}{NL}', test_archive)
  933. self.assertEqual(output_1, output_2)
  934. self.assertNotEqual(output_1, output_3)
  935. def test_list_hash(self):
  936. self.create_regular_file('empty_file', size=0)
  937. self.create_regular_file('amb', contents=b'a' * 1000000)
  938. self.cmd('init', self.repository_location)
  939. test_archive = self.repository_location + '::test'
  940. self.cmd('create', test_archive, 'input')
  941. output = self.cmd('list', '--format', '{sha256} {path}{NL}', test_archive)
  942. assert "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 input/amb" in output
  943. assert "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 input/empty_file" in output
  944. def test_list_chunk_counts(self):
  945. self.create_regular_file('empty_file', size=0)
  946. self.create_regular_file('two_chunks')
  947. with open(os.path.join(self.input_path, 'two_chunks'), 'wb') as fd:
  948. fd.write(b'abba' * 2000000)
  949. fd.write(b'baab' * 2000000)
  950. self.cmd('init', self.repository_location)
  951. test_archive = self.repository_location + '::test'
  952. self.cmd('create', test_archive, 'input')
  953. output = self.cmd('list', '--format', '{num_chunks} {unique_chunks} {path}{NL}', test_archive)
  954. assert "0 0 input/empty_file" in output
  955. assert "2 2 input/two_chunks" in output
  956. def test_list_size(self):
  957. self.create_regular_file('compressible_file', size=10000)
  958. self.cmd('init', self.repository_location)
  959. test_archive = self.repository_location + '::test'
  960. self.cmd('create', '-C', 'lz4', test_archive, 'input')
  961. output = self.cmd('list', '--format', '{size} {csize} {path}{NL}', test_archive)
  962. size, csize, path = output.split("\n")[1].split(" ")
  963. assert int(csize) < int(size)
  964. def test_break_lock(self):
  965. self.cmd('init', self.repository_location)
  966. self.cmd('break-lock', self.repository_location)
  967. def test_usage(self):
  968. if self.FORK_DEFAULT:
  969. self.cmd(exit_code=0)
  970. self.cmd('-h', exit_code=0)
  971. else:
  972. self.assert_raises(SystemExit, lambda: self.cmd())
  973. self.assert_raises(SystemExit, lambda: self.cmd('-h'))
  974. def test_help(self):
  975. assert 'Borg' in self.cmd('help')
  976. assert 'patterns' in self.cmd('help', 'patterns')
  977. assert 'Initialize' in self.cmd('help', 'init')
  978. assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only')
  979. assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only')
  980. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  981. def test_fuse_mount_repository(self):
  982. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  983. os.mkdir(mountpoint)
  984. self.cmd('init', self.repository_location)
  985. self.create_test_files()
  986. self.cmd('create', self.repository_location + '::archive', 'input')
  987. self.cmd('create', self.repository_location + '::archive2', 'input')
  988. try:
  989. self.cmd('mount', self.repository_location, mountpoint, fork=True)
  990. self.wait_for_mount(mountpoint)
  991. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  992. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  993. finally:
  994. if sys.platform.startswith('linux'):
  995. os.system('fusermount -u ' + mountpoint)
  996. else:
  997. os.system('umount ' + mountpoint)
  998. os.rmdir(mountpoint)
  999. # Give the daemon some time to exit
  1000. time.sleep(.2)
  1001. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  1002. def test_fuse_mount_archive(self):
  1003. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  1004. os.mkdir(mountpoint)
  1005. self.cmd('init', self.repository_location)
  1006. self.create_test_files()
  1007. self.cmd('create', self.repository_location + '::archive', 'input')
  1008. try:
  1009. self.cmd('mount', self.repository_location + '::archive', mountpoint, fork=True)
  1010. self.wait_for_mount(mountpoint)
  1011. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  1012. finally:
  1013. if sys.platform.startswith('linux'):
  1014. os.system('fusermount -u ' + mountpoint)
  1015. else:
  1016. os.system('umount ' + mountpoint)
  1017. os.rmdir(mountpoint)
  1018. # Give the daemon some time to exit
  1019. time.sleep(.2)
  1020. def verify_aes_counter_uniqueness(self, method):
  1021. seen = set() # Chunks already seen
  1022. used = set() # counter values already used
  1023. def verify_uniqueness():
  1024. with Repository(self.repository_path) as repository:
  1025. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  1026. data = repository.get(key)
  1027. hash = sha256(data).digest()
  1028. if hash not in seen:
  1029. seen.add(hash)
  1030. num_blocks = num_aes_blocks(len(data) - 41)
  1031. nonce = bytes_to_long(data[33:41])
  1032. for counter in range(nonce, nonce + num_blocks):
  1033. self.assert_not_in(counter, used)
  1034. used.add(counter)
  1035. self.create_test_files()
  1036. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  1037. self.cmd('init', '--encryption=' + method, self.repository_location)
  1038. verify_uniqueness()
  1039. self.cmd('create', self.repository_location + '::test', 'input')
  1040. verify_uniqueness()
  1041. self.cmd('create', self.repository_location + '::test.2', 'input')
  1042. verify_uniqueness()
  1043. self.cmd('delete', self.repository_location + '::test.2')
  1044. verify_uniqueness()
  1045. self.assert_equal(used, set(range(len(used))))
  1046. def test_aes_counter_uniqueness_keyfile(self):
  1047. self.verify_aes_counter_uniqueness('keyfile')
  1048. def test_aes_counter_uniqueness_passphrase(self):
  1049. self.verify_aes_counter_uniqueness('repokey')
  1050. def test_debug_dump_archive_items(self):
  1051. self.create_test_files()
  1052. self.cmd('init', self.repository_location)
  1053. self.cmd('create', self.repository_location + '::test', 'input')
  1054. with changedir('output'):
  1055. output = self.cmd('debug-dump-archive-items', self.repository_location + '::test')
  1056. output_dir = sorted(os.listdir('output'))
  1057. assert len(output_dir) > 0 and output_dir[0].startswith('000000_')
  1058. assert 'Done.' in output
  1059. def test_debug_put_get_delete_obj(self):
  1060. self.cmd('init', self.repository_location)
  1061. data = b'some data'
  1062. hexkey = sha256(data).hexdigest()
  1063. self.create_regular_file('file', contents=data)
  1064. output = self.cmd('debug-put-obj', self.repository_location, 'input/file')
  1065. assert hexkey in output
  1066. output = self.cmd('debug-get-obj', self.repository_location, hexkey, 'output/file')
  1067. assert hexkey in output
  1068. with open('output/file', 'rb') as f:
  1069. data_read = f.read()
  1070. assert data == data_read
  1071. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  1072. assert "deleted" in output
  1073. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  1074. assert "not found" in output
  1075. output = self.cmd('debug-delete-obj', self.repository_location, 'invalid')
  1076. assert "is invalid" in output
  1077. def test_init_interrupt(self):
  1078. def raise_eof(*args):
  1079. raise EOFError
  1080. with patch.object(KeyfileKeyBase, 'create', raise_eof):
  1081. self.cmd('init', self.repository_location, exit_code=1)
  1082. assert not os.path.exists(self.repository_location)
  1083. def test_recreate_basic(self):
  1084. self.create_test_files()
  1085. self.create_regular_file('dir2/file3', size=1024 * 80)
  1086. self.cmd('init', self.repository_location)
  1087. archive = self.repository_location + '::test0'
  1088. self.cmd('create', archive, 'input')
  1089. self.cmd('recreate', archive, 'input/dir2', '-e', 'input/dir2/file3')
  1090. listing = self.cmd('list', '--short', archive)
  1091. assert 'file1' not in listing
  1092. assert 'dir2/file2' in listing
  1093. assert 'dir2/file3' not in listing
  1094. def test_recreate_subtree_hardlinks(self):
  1095. # This is essentially the same problem set as in test_extract_hardlinks
  1096. self._extract_hardlinks_setup()
  1097. self.cmd('create', self.repository_location + '::test2', 'input')
  1098. self.cmd('recreate', self.repository_location + '::test', 'input/dir1')
  1099. with changedir('output'):
  1100. self.cmd('extract', self.repository_location + '::test')
  1101. assert os.stat('input/dir1/hardlink').st_nlink == 2
  1102. assert os.stat('input/dir1/subdir/hardlink').st_nlink == 2
  1103. assert os.stat('input/dir1/aaaa').st_nlink == 2
  1104. assert os.stat('input/dir1/source2').st_nlink == 2
  1105. with changedir('output'):
  1106. self.cmd('extract', self.repository_location + '::test2')
  1107. assert os.stat('input/dir1/hardlink').st_nlink == 4
  1108. def test_recreate_rechunkify(self):
  1109. with open(os.path.join(self.input_path, 'large_file'), 'wb') as fd:
  1110. fd.write(b'a' * 280)
  1111. fd.write(b'b' * 280)
  1112. self.cmd('init', self.repository_location)
  1113. self.cmd('create', '--chunker-params', '7,9,8,128', self.repository_location + '::test1', 'input')
  1114. self.cmd('create', self.repository_location + '::test2', 'input', '--no-files-cache')
  1115. list = self.cmd('list', self.repository_location + '::test1', 'input/large_file',
  1116. '--format', '{num_chunks} {unique_chunks}')
  1117. num_chunks, unique_chunks = map(int, list.split(' '))
  1118. # test1 and test2 do not deduplicate
  1119. assert num_chunks == unique_chunks
  1120. self.cmd('recreate', self.repository_location, '--chunker-params', 'default')
  1121. # test1 and test2 do deduplicate after recreate
  1122. assert not int(self.cmd('list', self.repository_location + '::test1', 'input/large_file',
  1123. '--format', '{unique_chunks}'))
  1124. def test_recreate_recompress(self):
  1125. self.create_regular_file('compressible', size=10000)
  1126. self.cmd('init', self.repository_location)
  1127. self.cmd('create', self.repository_location + '::test', 'input', '-C', 'none')
  1128. file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible',
  1129. '--format', '{size} {csize} {sha256}')
  1130. size, csize, sha256_before = file_list.split(' ')
  1131. assert int(csize) >= int(size) # >= due to metadata overhead
  1132. self.cmd('recreate', self.repository_location, '-C', 'lz4')
  1133. file_list = self.cmd('list', self.repository_location + '::test', 'input/compressible',
  1134. '--format', '{size} {csize} {sha256}')
  1135. size, csize, sha256_after = file_list.split(' ')
  1136. assert int(csize) < int(size)
  1137. assert sha256_before == sha256_after
  1138. def test_recreate_dry_run(self):
  1139. self.create_regular_file('compressible', size=10000)
  1140. self.cmd('init', self.repository_location)
  1141. self.cmd('create', self.repository_location + '::test', 'input')
  1142. archives_before = self.cmd('list', self.repository_location + '::test')
  1143. self.cmd('recreate', self.repository_location, '-n', '-e', 'input/compressible')
  1144. archives_after = self.cmd('list', self.repository_location + '::test')
  1145. assert archives_after == archives_before
  1146. def _recreate_interrupt_patch(self, interrupt_after_n_1_files):
  1147. def interrupt(self, *args):
  1148. if interrupt_after_n_1_files:
  1149. self.interrupt = True
  1150. pi_save(self, *args)
  1151. else:
  1152. raise ArchiveRecreater.Interrupted
  1153. def process_item_patch(*args):
  1154. return pi_call.pop(0)(*args)
  1155. pi_save = ArchiveRecreater.process_item
  1156. pi_call = [pi_save] * interrupt_after_n_1_files + [interrupt]
  1157. return process_item_patch
  1158. def _test_recreate_interrupt(self, change_args, interrupt_early):
  1159. self.create_test_files()
  1160. self.create_regular_file('dir2/abcdef', size=1024 * 80)
  1161. self.cmd('init', self.repository_location)
  1162. self.cmd('create', self.repository_location + '::test', 'input')
  1163. process_files = 1
  1164. if interrupt_early:
  1165. process_files = 0
  1166. with patch.object(ArchiveRecreater, 'process_item', self._recreate_interrupt_patch(process_files)):
  1167. self.cmd('recreate', '-sv', '--list', self.repository_location, 'input/dir2')
  1168. assert 'test.recreate' in self.cmd('list', self.repository_location)
  1169. if change_args:
  1170. with patch.object(sys, 'argv', sys.argv + ['non-forking tests don\'t use sys.argv']):
  1171. output = self.cmd('recreate', '-sv', '--list', '-pC', 'lz4', self.repository_location, 'input/dir2')
  1172. else:
  1173. output = self.cmd('recreate', '-sv', '--list', self.repository_location, 'input/dir2')
  1174. assert 'Found test.recreate, will resume' in output
  1175. assert change_args == ('Command line changed' in output)
  1176. if not interrupt_early:
  1177. assert 'Fast-forwarded to input/dir2/abcdef' in output
  1178. assert 'A input/dir2/abcdef' not in output
  1179. assert 'A input/dir2/file2' in output
  1180. archives = self.cmd('list', self.repository_location)
  1181. assert 'test.recreate' not in archives
  1182. assert 'test' in archives
  1183. files = self.cmd('list', self.repository_location + '::test')
  1184. assert 'dir2/file2' in files
  1185. assert 'dir2/abcdef' in files
  1186. assert 'file1' not in files
  1187. def test_recreate_interrupt(self):
  1188. self._test_recreate_interrupt(False, True)
  1189. def test_recreate_interrupt2(self):
  1190. self._test_recreate_interrupt(True, False)
  1191. def _test_recreate_chunker_interrupt_patch(self):
  1192. real_add_chunk = Cache.add_chunk
  1193. def add_chunk(*args, **kwargs):
  1194. frame = inspect.stack()[2]
  1195. try:
  1196. caller_self = frame[0].f_locals['self']
  1197. if isinstance(caller_self, ArchiveRecreater):
  1198. caller_self.interrupt = True
  1199. finally:
  1200. del frame
  1201. return real_add_chunk(*args, **kwargs)
  1202. return add_chunk
  1203. def test_recreate_rechunkify_interrupt(self):
  1204. self.create_regular_file('file1', size=1024 * 80)
  1205. self.cmd('init', self.repository_location)
  1206. self.cmd('create', self.repository_location + '::test', 'input')
  1207. archive_before = self.cmd('list', self.repository_location + '::test', '--format', '{sha512}')
  1208. with patch.object(Cache, 'add_chunk', self._test_recreate_chunker_interrupt_patch()):
  1209. self.cmd('recreate', '-pv', '--chunker-params', '10,12,11,4095', self.repository_location)
  1210. assert 'test.recreate' in self.cmd('list', self.repository_location)
  1211. output = self.cmd('recreate', '-svp', '--debug', '--chunker-params', '10,12,11,4095', self.repository_location)
  1212. assert 'Found test.recreate, will resume' in output
  1213. assert 'Copied 1 chunks from a partially processed item' in output
  1214. archive_after = self.cmd('list', self.repository_location + '::test', '--format', '{sha512}')
  1215. assert archive_after == archive_before
  1216. def test_recreate_changed_source(self):
  1217. self.create_test_files()
  1218. self.cmd('init', self.repository_location)
  1219. self.cmd('create', self.repository_location + '::test', 'input')
  1220. with patch.object(ArchiveRecreater, 'process_item', self._recreate_interrupt_patch(1)):
  1221. self.cmd('recreate', self.repository_location, 'input/dir2')
  1222. assert 'test.recreate' in self.cmd('list', self.repository_location)
  1223. self.cmd('delete', self.repository_location + '::test')
  1224. self.cmd('create', self.repository_location + '::test', 'input')
  1225. output = self.cmd('recreate', self.repository_location, 'input/dir2')
  1226. assert 'Source archive changed, will discard test.recreate and start over' in output
  1227. def test_recreate_refuses_temporary(self):
  1228. self.cmd('init', self.repository_location)
  1229. self.cmd('recreate', self.repository_location + '::cba.recreate', exit_code=2)
  1230. def test_recreate_skips_nothing_to_do(self):
  1231. self.create_regular_file('file1', size=1024 * 80)
  1232. self.cmd('init', self.repository_location)
  1233. self.cmd('create', self.repository_location + '::test', 'input')
  1234. info_before = self.cmd('info', self.repository_location + '::test')
  1235. self.cmd('recreate', self.repository_location, '--chunker-params', 'default')
  1236. info_after = self.cmd('info', self.repository_location + '::test')
  1237. assert info_before == info_after # includes archive ID
  1238. @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available')
  1239. class ArchiverTestCaseBinary(ArchiverTestCase):
  1240. EXE = 'borg.exe'
  1241. FORK_DEFAULT = True
  1242. @unittest.skip('patches objects')
  1243. def test_init_interrupt(self):
  1244. pass
  1245. @unittest.skip('patches objects')
  1246. def test_recreate_rechunkify_interrupt(self):
  1247. pass
  1248. @unittest.skip('patches objects')
  1249. def test_recreate_interrupt(self):
  1250. pass
  1251. @unittest.skip('patches objects')
  1252. def test_recreate_changed_source(self):
  1253. pass
  1254. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  1255. def setUp(self):
  1256. super().setUp()
  1257. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  1258. self.cmd('init', self.repository_location)
  1259. self.create_src_archive('archive1')
  1260. self.create_src_archive('archive2')
  1261. def open_archive(self, name):
  1262. repository = Repository(self.repository_path)
  1263. with repository:
  1264. manifest, key = Manifest.load(repository)
  1265. archive = Archive(repository, key, manifest, name)
  1266. return archive, repository
  1267. def test_check_usage(self):
  1268. output = self.cmd('check', '-v', self.repository_location, exit_code=0)
  1269. self.assert_in('Starting repository check', output)
  1270. self.assert_in('Starting archive consistency check', output)
  1271. output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0)
  1272. self.assert_in('Starting repository check', output)
  1273. self.assert_not_in('Starting archive consistency check', output)
  1274. output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0)
  1275. self.assert_not_in('Starting repository check', output)
  1276. self.assert_in('Starting archive consistency check', output)
  1277. output = self.cmd('check', '-v', '--archives-only', '--prefix=archive2', self.repository_location, exit_code=0)
  1278. self.assert_not_in('archive1', output)
  1279. def test_missing_file_chunk(self):
  1280. archive, repository = self.open_archive('archive1')
  1281. with repository:
  1282. for item in archive.iter_items():
  1283. if item[b'path'].endswith('testsuite/archiver.py'):
  1284. repository.delete(item[b'chunks'][-1].id)
  1285. break
  1286. repository.commit()
  1287. self.cmd('check', self.repository_location, exit_code=1)
  1288. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1289. self.cmd('check', self.repository_location, exit_code=0)
  1290. def test_missing_archive_item_chunk(self):
  1291. archive, repository = self.open_archive('archive1')
  1292. with repository:
  1293. repository.delete(archive.metadata[b'items'][-5])
  1294. repository.commit()
  1295. self.cmd('check', self.repository_location, exit_code=1)
  1296. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1297. self.cmd('check', self.repository_location, exit_code=0)
  1298. def test_missing_archive_metadata(self):
  1299. archive, repository = self.open_archive('archive1')
  1300. with repository:
  1301. repository.delete(archive.id)
  1302. repository.commit()
  1303. self.cmd('check', self.repository_location, exit_code=1)
  1304. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1305. self.cmd('check', self.repository_location, exit_code=0)
  1306. def test_missing_manifest(self):
  1307. archive, repository = self.open_archive('archive1')
  1308. with repository:
  1309. repository.delete(Manifest.MANIFEST_ID)
  1310. repository.commit()
  1311. self.cmd('check', self.repository_location, exit_code=1)
  1312. output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0)
  1313. self.assert_in('archive1', output)
  1314. self.assert_in('archive2', output)
  1315. self.cmd('check', self.repository_location, exit_code=0)
  1316. def test_extra_chunks(self):
  1317. self.cmd('check', self.repository_location, exit_code=0)
  1318. with Repository(self.repository_location) as repository:
  1319. repository.put(b'01234567890123456789012345678901', b'xxxx')
  1320. repository.commit()
  1321. self.cmd('check', self.repository_location, exit_code=1)
  1322. self.cmd('check', self.repository_location, exit_code=1)
  1323. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1324. self.cmd('check', self.repository_location, exit_code=0)
  1325. self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  1326. class RemoteArchiverTestCase(ArchiverTestCase):
  1327. prefix = '__testsuite__:'
  1328. def test_remote_repo_restrict_to_path(self):
  1329. self.cmd('init', self.repository_location)
  1330. path_prefix = os.path.dirname(self.repository_path)
  1331. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  1332. self.assert_raises(PathNotAllowed, lambda: self.cmd('init', self.repository_location + '_1'))
  1333. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  1334. self.cmd('init', self.repository_location + '_2')
  1335. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  1336. self.cmd('init', self.repository_location + '_3')
  1337. # skip fuse tests here, they deadlock since this change in exec_cmd:
  1338. # -output = subprocess.check_output(borg + args, stderr=None)
  1339. # +output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT)
  1340. # this was introduced because some tests expect stderr contents to show up
  1341. # in "output" also. Also, the non-forking exec_cmd catches both, too.
  1342. @unittest.skip('deadlock issues')
  1343. def test_fuse_mount_repository(self):
  1344. pass
  1345. @unittest.skip('deadlock issues')
  1346. def test_fuse_mount_archive(self):
  1347. pass
  1348. @unittest.skip('only works locally')
  1349. def test_debug_put_get_delete_obj(self):
  1350. pass
  1351. class DiffArchiverTestCase(ArchiverTestCaseBase):
  1352. def test_basic_functionality(self):
  1353. # Initialize test folder
  1354. self.create_test_files()
  1355. self.cmd('init', self.repository_location)
  1356. # Setup files for the first snapshot
  1357. self.create_regular_file('file_unchanged', size=128)
  1358. self.create_regular_file('file_removed', size=256)
  1359. self.create_regular_file('file_removed2', size=512)
  1360. self.create_regular_file('file_replaced', size=1024)
  1361. os.mkdir('input/dir_replaced_with_file')
  1362. os.chmod('input/dir_replaced_with_file', stat.S_IFDIR | 0o755)
  1363. os.mkdir('input/dir_replaced_with_link')
  1364. os.mkdir('input/dir_removed')
  1365. os.symlink('input/dir_replaced_with_file', 'input/link_changed')
  1366. os.symlink('input/file_unchanged', 'input/link_removed')
  1367. os.symlink('input/file_removed2', 'input/link_target_removed')
  1368. os.symlink('input/empty', 'input/link_target_contents_changed')
  1369. os.symlink('input/empty', 'input/link_replaced_by_file')
  1370. os.link('input/empty', 'input/hardlink_contents_changed')
  1371. os.link('input/file_removed', 'input/hardlink_removed')
  1372. os.link('input/file_removed2', 'input/hardlink_target_removed')
  1373. os.link('input/file_replaced', 'input/hardlink_target_replaced')
  1374. # Create the first snapshot
  1375. self.cmd('create', self.repository_location + '::test0', 'input')
  1376. # Setup files for the second snapshot
  1377. self.create_regular_file('file_added', size=2048)
  1378. os.unlink('input/file_removed')
  1379. os.unlink('input/file_removed2')
  1380. os.unlink('input/file_replaced')
  1381. self.create_regular_file('file_replaced', size=4096, contents=b'0')
  1382. os.rmdir('input/dir_replaced_with_file')
  1383. self.create_regular_file('dir_replaced_with_file', size=8192)
  1384. os.chmod('input/dir_replaced_with_file', stat.S_IFREG | 0o755)
  1385. os.mkdir('input/dir_added')
  1386. os.rmdir('input/dir_removed')
  1387. os.rmdir('input/dir_replaced_with_link')
  1388. os.symlink('input/dir_added', 'input/dir_replaced_with_link')
  1389. os.unlink('input/link_changed')
  1390. os.symlink('input/dir_added', 'input/link_changed')
  1391. os.symlink('input/dir_added', 'input/link_added')
  1392. os.unlink('input/link_removed')
  1393. os.unlink('input/link_replaced_by_file')
  1394. self.create_regular_file('link_replaced_by_file', size=16384)
  1395. os.unlink('input/hardlink_removed')
  1396. os.link('input/file_added', 'input/hardlink_added')
  1397. with open('input/empty', 'ab') as fd:
  1398. fd.write(b'appended_data')
  1399. # Create the second snapshot
  1400. self.cmd('create', self.repository_location + '::test1a', 'input')
  1401. self.cmd('create', '--chunker-params', '16,18,17,4095', self.repository_location + '::test1b', 'input')
  1402. def do_asserts(output, archive):
  1403. # File contents changed (deleted and replaced with a new file)
  1404. assert 'B input/file_replaced' in output
  1405. # File unchanged
  1406. assert 'input/file_unchanged' not in output
  1407. # Directory replaced with a regular file
  1408. assert '[drwxr-xr-x -> -rwxr-xr-x] input/dir_replaced_with_file' in output
  1409. # Basic directory cases
  1410. assert 'added directory input/dir_added' in output
  1411. assert 'removed directory input/dir_removed' in output
  1412. # Basic symlink cases
  1413. assert 'changed link input/link_changed' in output
  1414. assert 'added link input/link_added' in output
  1415. assert 'removed link input/link_removed' in output
  1416. # Symlink replacing or being replaced
  1417. assert '] input/dir_replaced_with_link' in output
  1418. assert '] input/link_replaced_by_file' in output
  1419. # Symlink target removed. Should not affect the symlink at all.
  1420. assert 'input/link_target_removed' not in output
  1421. # The inode has two links and the file contents changed. Borg
  1422. # should notice the changes in both links. However, the symlink
  1423. # pointing to the file is not changed.
  1424. assert '0 B input/empty' in output
  1425. assert '0 B input/hardlink_contents_changed' in output
  1426. assert 'input/link_target_contents_changed' not in output
  1427. # Added a new file and a hard link to it. Both links to the same
  1428. # inode should appear as separate files.
  1429. assert 'added 2.05 kB input/file_added' in output
  1430. assert 'added 2.05 kB input/hardlink_added' in output
  1431. # The inode has two links and both of them are deleted. They should
  1432. # appear as two deleted files.
  1433. assert 'removed 256 B input/file_removed' in output
  1434. assert 'removed 256 B input/hardlink_removed' in output
  1435. # Another link (marked previously as the source in borg) to the
  1436. # same inode was removed. This should not change this link at all.
  1437. assert 'input/hardlink_target_removed' not in output
  1438. # Another link (marked previously as the source in borg) to the
  1439. # same inode was replaced with a new regular file. This should not
  1440. # change this link at all.
  1441. assert 'input/hardlink_target_replaced' not in output
  1442. do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1a'), '1a')
  1443. # We expect exit_code=1 due to the chunker params warning
  1444. do_asserts(self.cmd('diff', self.repository_location + '::test0', 'test1b', exit_code=1), '1b')
  1445. def test_sort_option(self):
  1446. self.cmd('init', self.repository_location)
  1447. self.create_regular_file('a_file_removed', size=8)
  1448. self.create_regular_file('f_file_removed', size=16)
  1449. self.create_regular_file('c_file_changed', size=32)
  1450. self.create_regular_file('e_file_changed', size=64)
  1451. self.cmd('create', self.repository_location + '::test0', 'input')
  1452. os.unlink('input/a_file_removed')
  1453. os.unlink('input/f_file_removed')
  1454. os.unlink('input/c_file_changed')
  1455. os.unlink('input/e_file_changed')
  1456. self.create_regular_file('c_file_changed', size=512)
  1457. self.create_regular_file('e_file_changed', size=1024)
  1458. self.create_regular_file('b_file_added', size=128)
  1459. self.create_regular_file('d_file_added', size=256)
  1460. self.cmd('create', self.repository_location + '::test1', 'input')
  1461. output = self.cmd('diff', '--sort', self.repository_location + '::test0', 'test1')
  1462. expected = [
  1463. 'a_file_removed',
  1464. 'b_file_added',
  1465. 'c_file_changed',
  1466. 'd_file_added',
  1467. 'e_file_changed',
  1468. 'f_file_removed',
  1469. ]
  1470. assert all(x in line for x, line in zip(expected, output.splitlines()))
  1471. def test_get_args():
  1472. archiver = Archiver()
  1473. # everything normal:
  1474. # first param is argv as produced by ssh forced command,
  1475. # second param is like from SSH_ORIGINAL_COMMAND env variable
  1476. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1477. 'borg serve --info --umask=0027')
  1478. assert args.func == archiver.do_serve
  1479. assert args.restrict_to_paths == ['/p1', '/p2']
  1480. assert args.umask == 0o027
  1481. assert args.log_level == 'info'
  1482. # trying to cheat - break out of path restriction
  1483. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1484. 'borg serve --restrict-to-path=/')
  1485. assert args.restrict_to_paths == ['/p1', '/p2']
  1486. # trying to cheat - try to execute different subcommand
  1487. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1488. 'borg init /')
  1489. assert args.func == archiver.do_serve
  1490. def test_compare_chunk_contents():
  1491. def ccc(a, b):
  1492. compare1 = Archiver.compare_chunk_contents(iter(a), iter(b))
  1493. compare2 = Archiver.compare_chunk_contents(iter(b), iter(a))
  1494. assert compare1 == compare2
  1495. return compare1
  1496. assert ccc([
  1497. b'1234', b'567A', b'bC'
  1498. ], [
  1499. b'1', b'23', b'4567A', b'b', b'C'
  1500. ])
  1501. # one iterator exhausted before the other
  1502. assert not ccc([
  1503. b'12345',
  1504. ], [
  1505. b'1234', b'56'
  1506. ])
  1507. # content mismatch
  1508. assert not ccc([
  1509. b'1234', b'65'
  1510. ], [
  1511. b'1234', b'56'
  1512. ])
  1513. # first is the prefix of second
  1514. assert not ccc([
  1515. b'1234', b'56'
  1516. ], [
  1517. b'1234', b'565'
  1518. ])