archiver.py 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. from binascii import hexlify, unhexlify
  2. from datetime import datetime
  3. from itertools import zip_longest
  4. from operator import attrgetter
  5. import argparse
  6. import collections
  7. import functools
  8. import hashlib
  9. import inspect
  10. import io
  11. import os
  12. import shlex
  13. import signal
  14. import stat
  15. import sys
  16. import textwrap
  17. import traceback
  18. from . import __version__
  19. from .helpers import Error, location_validator, archivename_validator, format_time, format_file_size, \
  20. parse_pattern, PathPrefixPattern, to_localtime, timestamp, \
  21. get_cache_dir, prune_within, prune_split, \
  22. Manifest, remove_surrogates, update_excludes, format_archive, check_extension_modules, Statistics, \
  23. dir_is_tagged, ChunkerParams, CompressionSpec, is_slow_msgpack, yes, sysinfo, \
  24. EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR, log_multi, PatternMatcher, ItemFormatter
  25. from .logger import create_logger, setup_logging
  26. logger = create_logger()
  27. from .compress import Compressor, COMPR_BUFFER
  28. from .upgrader import AtticRepositoryUpgrader, BorgRepositoryUpgrader
  29. from .repository import Repository
  30. from .cache import Cache
  31. from .key import key_creator, RepoKey, PassphraseKey
  32. from .archive import Archive, ArchiveChecker, CHUNKER_PARAMS
  33. from .remote import RepositoryServer, RemoteRepository, cache_if_remote
  34. has_lchflags = hasattr(os, 'lchflags')
  35. # default umask, overriden by --umask, defaults to read/write only for owner
  36. UMASK_DEFAULT = 0o077
  37. DASHES = '-' * 78
  38. def argument(args, str_or_bool):
  39. """If bool is passed, return it. If str is passed, retrieve named attribute from args."""
  40. if isinstance(str_or_bool, str):
  41. return getattr(args, str_or_bool)
  42. return str_or_bool
  43. def with_repository(fake=False, create=False, lock=True, exclusive=False, manifest=True, cache=False):
  44. """
  45. Method decorator for subcommand-handling methods: do_XYZ(self, args, repository, …)
  46. If a parameter (where allowed) is a str the attribute named of args is used instead.
  47. :param fake: (str or bool) use None instead of repository, don't do anything else
  48. :param create: create repository
  49. :param lock: lock repository
  50. :param exclusive: (str or bool) lock repository exclusively (for writing)
  51. :param manifest: load manifest and key, pass them as keyword arguments
  52. :param cache: open cache, pass it as keyword argument (implies manifest)
  53. """
  54. def decorator(method):
  55. @functools.wraps(method)
  56. def wrapper(self, args, **kwargs):
  57. location = args.location # note: 'location' must be always present in args
  58. if argument(args, fake):
  59. return method(self, args, repository=None, **kwargs)
  60. elif location.proto == 'ssh':
  61. repository = RemoteRepository(location, create=create, lock_wait=self.lock_wait, lock=lock, args=args)
  62. else:
  63. repository = Repository(location.path, create=create, exclusive=argument(args, exclusive),
  64. lock_wait=self.lock_wait, lock=lock)
  65. with repository:
  66. if manifest or cache:
  67. kwargs['manifest'], kwargs['key'] = Manifest.load(repository)
  68. if cache:
  69. with Cache(repository, kwargs['key'], kwargs['manifest'],
  70. do_files=getattr(args, 'cache_files', False), lock_wait=self.lock_wait) as cache_:
  71. return method(self, args, repository=repository, cache=cache_, **kwargs)
  72. else:
  73. return method(self, args, repository=repository, **kwargs)
  74. return wrapper
  75. return decorator
  76. def with_archive(method):
  77. @functools.wraps(method)
  78. def wrapper(self, args, repository, key, manifest, **kwargs):
  79. archive = Archive(repository, key, manifest, args.location.archive,
  80. numeric_owner=getattr(args, 'numeric_owner', False), cache=kwargs.get('cache'))
  81. return method(self, args, repository=repository, manifest=manifest, key=key, archive=archive, **kwargs)
  82. return wrapper
  83. class Archiver:
  84. def __init__(self, lock_wait=None):
  85. self.exit_code = EXIT_SUCCESS
  86. self.lock_wait = lock_wait
  87. def print_error(self, msg, *args):
  88. msg = args and msg % args or msg
  89. self.exit_code = EXIT_ERROR
  90. logger.error(msg)
  91. def print_warning(self, msg, *args):
  92. msg = args and msg % args or msg
  93. self.exit_code = EXIT_WARNING # we do not terminate here, so it is a warning
  94. logger.warning(msg)
  95. def print_file_status(self, status, path):
  96. if self.output_list and (self.output_filter is None or status in self.output_filter):
  97. logger.info("%1s %s", status, remove_surrogates(path))
  98. @staticmethod
  99. def compare_chunk_contents(chunks1, chunks2):
  100. """Compare two chunk iterators (like returned by :meth:`.DownloadPipeline.fetch_many`)"""
  101. end = object()
  102. alen = ai = 0
  103. blen = bi = 0
  104. while True:
  105. if not alen - ai:
  106. a = next(chunks1, end)
  107. if a is end:
  108. return not blen - bi and next(chunks2, end) is end
  109. a = memoryview(a)
  110. alen = len(a)
  111. ai = 0
  112. if not blen - bi:
  113. b = next(chunks2, end)
  114. if b is end:
  115. return not alen - ai and next(chunks1, end) is end
  116. b = memoryview(b)
  117. blen = len(b)
  118. bi = 0
  119. slicelen = min(alen - ai, blen - bi)
  120. if a[ai:ai + slicelen] != b[bi:bi + slicelen]:
  121. return False
  122. ai += slicelen
  123. bi += slicelen
  124. @staticmethod
  125. def build_matcher(excludes, paths):
  126. matcher = PatternMatcher()
  127. if excludes:
  128. matcher.add(excludes, False)
  129. include_patterns = []
  130. if paths:
  131. include_patterns.extend(parse_pattern(i, PathPrefixPattern) for i in paths)
  132. matcher.add(include_patterns, True)
  133. matcher.fallback = not include_patterns
  134. return matcher, include_patterns
  135. def do_serve(self, args):
  136. """Start in server mode. This command is usually not used manually.
  137. """
  138. return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()
  139. @with_repository(create=True, exclusive=True, manifest=False)
  140. def do_init(self, args, repository):
  141. """Initialize an empty repository"""
  142. logger.info('Initializing repository at "%s"' % args.location.canonical_path())
  143. try:
  144. key = key_creator(repository, args)
  145. except (EOFError, KeyboardInterrupt):
  146. repository.destroy()
  147. return EXIT_WARNING
  148. manifest = Manifest(key, repository)
  149. manifest.key = key
  150. manifest.write()
  151. repository.commit()
  152. with Cache(repository, key, manifest, warn_if_unencrypted=False):
  153. pass
  154. return self.exit_code
  155. @with_repository(exclusive='repair', manifest=False)
  156. def do_check(self, args, repository):
  157. """Check repository consistency"""
  158. if args.repair:
  159. msg = ("'check --repair' is an experimental feature that might result in data loss." +
  160. "\n" +
  161. "Type 'YES' if you understand this and want to continue: ")
  162. if not yes(msg, false_msg="Aborting.", truish=('YES', ),
  163. env_var_override='BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  164. return EXIT_ERROR
  165. if not args.archives_only:
  166. if not repository.check(repair=args.repair, save_space=args.save_space):
  167. return EXIT_WARNING
  168. if not args.repo_only and not ArchiveChecker().check(
  169. repository, repair=args.repair, archive=args.location.archive,
  170. last=args.last, prefix=args.prefix, save_space=args.save_space):
  171. return EXIT_WARNING
  172. return EXIT_SUCCESS
  173. @with_repository()
  174. def do_change_passphrase(self, args, repository, manifest, key):
  175. """Change repository key file passphrase"""
  176. key.change_passphrase()
  177. return EXIT_SUCCESS
  178. @with_repository(manifest=False)
  179. def do_migrate_to_repokey(self, args, repository):
  180. """Migrate passphrase -> repokey"""
  181. manifest_data = repository.get(Manifest.MANIFEST_ID)
  182. key_old = PassphraseKey.detect(repository, manifest_data)
  183. key_new = RepoKey(repository)
  184. key_new.target = repository
  185. key_new.repository_id = repository.id
  186. key_new.enc_key = key_old.enc_key
  187. key_new.enc_hmac_key = key_old.enc_hmac_key
  188. key_new.id_key = key_old.id_key
  189. key_new.chunk_seed = key_old.chunk_seed
  190. key_new.change_passphrase() # option to change key protection passphrase, save
  191. return EXIT_SUCCESS
  192. @with_repository(fake='dry_run')
  193. def do_create(self, args, repository, manifest=None, key=None):
  194. """Create new archive"""
  195. matcher = PatternMatcher(fallback=True)
  196. if args.excludes:
  197. matcher.add(args.excludes, False)
  198. def create_inner(archive, cache):
  199. # Add cache dir to inode_skip list
  200. skip_inodes = set()
  201. try:
  202. st = os.stat(get_cache_dir())
  203. skip_inodes.add((st.st_ino, st.st_dev))
  204. except OSError:
  205. pass
  206. # Add local repository dir to inode_skip list
  207. if not args.location.host:
  208. try:
  209. st = os.stat(args.location.path)
  210. skip_inodes.add((st.st_ino, st.st_dev))
  211. except OSError:
  212. pass
  213. for path in args.paths:
  214. if path == '-': # stdin
  215. path = 'stdin'
  216. if not dry_run:
  217. try:
  218. status = archive.process_stdin(path, cache)
  219. except OSError as e:
  220. status = 'E'
  221. self.print_warning('%s: %s', path, e)
  222. else:
  223. status = '-'
  224. self.print_file_status(status, path)
  225. continue
  226. path = os.path.normpath(path)
  227. if args.one_file_system:
  228. try:
  229. restrict_dev = os.lstat(path).st_dev
  230. except OSError as e:
  231. self.print_warning('%s: %s', path, e)
  232. continue
  233. else:
  234. restrict_dev = None
  235. self._process(archive, cache, matcher, args.exclude_caches, args.exclude_if_present,
  236. args.keep_tag_files, skip_inodes, path, restrict_dev,
  237. read_special=args.read_special, dry_run=dry_run)
  238. if not dry_run:
  239. archive.save(comment=args.comment, timestamp=args.timestamp)
  240. if args.progress:
  241. archive.stats.show_progress(final=True)
  242. if args.stats:
  243. archive.end = datetime.utcnow()
  244. log_multi(DASHES,
  245. str(archive),
  246. DASHES,
  247. str(archive.stats),
  248. str(cache),
  249. DASHES)
  250. self.output_filter = args.output_filter
  251. self.output_list = args.output_list
  252. self.ignore_inode = args.ignore_inode
  253. dry_run = args.dry_run
  254. t0 = datetime.utcnow()
  255. if not dry_run:
  256. compr_args = dict(buffer=COMPR_BUFFER)
  257. compr_args.update(args.compression)
  258. key.compressor = Compressor(**compr_args)
  259. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  260. archive = Archive(repository, key, manifest, args.location.archive, cache=cache,
  261. create=True, checkpoint_interval=args.checkpoint_interval,
  262. numeric_owner=args.numeric_owner, progress=args.progress,
  263. chunker_params=args.chunker_params, start=t0)
  264. create_inner(archive, cache)
  265. else:
  266. create_inner(None, None)
  267. return self.exit_code
  268. def _process(self, archive, cache, matcher, exclude_caches, exclude_if_present,
  269. keep_tag_files, skip_inodes, path, restrict_dev,
  270. read_special=False, dry_run=False):
  271. if not matcher.match(path):
  272. self.print_file_status('x', path)
  273. return
  274. try:
  275. st = os.lstat(path)
  276. except OSError as e:
  277. self.print_warning('%s: %s', path, e)
  278. return
  279. if (st.st_ino, st.st_dev) in skip_inodes:
  280. return
  281. # Entering a new filesystem?
  282. if restrict_dev and st.st_dev != restrict_dev:
  283. return
  284. status = None
  285. # Ignore if nodump flag is set
  286. if has_lchflags and (st.st_flags & stat.UF_NODUMP):
  287. return
  288. if stat.S_ISREG(st.st_mode) or read_special and not stat.S_ISDIR(st.st_mode):
  289. if not dry_run:
  290. try:
  291. status = archive.process_file(path, st, cache, self.ignore_inode)
  292. except OSError as e:
  293. status = 'E'
  294. self.print_warning('%s: %s', path, e)
  295. elif stat.S_ISDIR(st.st_mode):
  296. tag_paths = dir_is_tagged(path, exclude_caches, exclude_if_present)
  297. if tag_paths:
  298. if keep_tag_files and not dry_run:
  299. archive.process_dir(path, st)
  300. for tag_path in tag_paths:
  301. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  302. keep_tag_files, skip_inodes, tag_path, restrict_dev,
  303. read_special=read_special, dry_run=dry_run)
  304. return
  305. if not dry_run:
  306. status = archive.process_dir(path, st)
  307. try:
  308. entries = os.listdir(path)
  309. except OSError as e:
  310. status = 'E'
  311. self.print_warning('%s: %s', path, e)
  312. else:
  313. for filename in sorted(entries):
  314. entry_path = os.path.normpath(os.path.join(path, filename))
  315. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  316. keep_tag_files, skip_inodes, entry_path, restrict_dev,
  317. read_special=read_special, dry_run=dry_run)
  318. elif stat.S_ISLNK(st.st_mode):
  319. if not dry_run:
  320. status = archive.process_symlink(path, st)
  321. elif stat.S_ISFIFO(st.st_mode):
  322. if not dry_run:
  323. status = archive.process_fifo(path, st)
  324. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  325. if not dry_run:
  326. status = archive.process_dev(path, st)
  327. elif stat.S_ISSOCK(st.st_mode):
  328. # Ignore unix sockets
  329. return
  330. elif stat.S_ISDOOR(st.st_mode):
  331. # Ignore Solaris doors
  332. return
  333. elif stat.S_ISPORT(st.st_mode):
  334. # Ignore Solaris event ports
  335. return
  336. else:
  337. self.print_warning('Unknown file type: %s', path)
  338. return
  339. # Status output
  340. if status is None:
  341. if not dry_run:
  342. status = '?' # need to add a status code somewhere
  343. else:
  344. status = '-' # dry run, item was not backed up
  345. self.print_file_status(status, path)
  346. @with_repository()
  347. @with_archive
  348. def do_extract(self, args, repository, manifest, key, archive):
  349. """Extract archive contents"""
  350. # be restrictive when restoring files, restore permissions later
  351. if sys.getfilesystemencoding() == 'ascii':
  352. logger.warning('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  353. if sys.platform.startswith(('linux', 'freebsd', 'netbsd', 'openbsd', 'darwin', )):
  354. logger.warning('Hint: You likely need to fix your locale setup. E.g. install locales and use: LANG=en_US.UTF-8')
  355. matcher, include_patterns = self.build_matcher(args.excludes, args.paths)
  356. output_list = args.output_list
  357. dry_run = args.dry_run
  358. stdout = args.stdout
  359. sparse = args.sparse
  360. strip_components = args.strip_components
  361. dirs = []
  362. partial_extract = not matcher.empty() or strip_components
  363. hardlink_masters = {} if partial_extract else None
  364. def item_is_hardlink_master(item):
  365. return (partial_extract and stat.S_ISREG(item[b'mode']) and
  366. item.get(b'hardlink_master', True) and b'source' not in item)
  367. for item in archive.iter_items(preload=True,
  368. filter=lambda item: item_is_hardlink_master(item) or matcher.match(item[b'path'])):
  369. orig_path = item[b'path']
  370. if item_is_hardlink_master(item):
  371. hardlink_masters[orig_path] = (item.get(b'chunks'), item.get(b'source'))
  372. if not matcher.match(item[b'path']):
  373. continue
  374. if strip_components:
  375. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  376. if not item[b'path']:
  377. continue
  378. if not args.dry_run:
  379. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  380. archive.extract_item(dirs.pop(-1), stdout=stdout)
  381. if output_list:
  382. logger.info(remove_surrogates(orig_path))
  383. try:
  384. if dry_run:
  385. archive.extract_item(item, dry_run=True)
  386. else:
  387. if stat.S_ISDIR(item[b'mode']):
  388. dirs.append(item)
  389. archive.extract_item(item, restore_attrs=False)
  390. else:
  391. archive.extract_item(item, stdout=stdout, sparse=sparse, hardlink_masters=hardlink_masters,
  392. original_path=orig_path)
  393. except OSError as e:
  394. self.print_warning('%s: %s', remove_surrogates(orig_path), e)
  395. if not args.dry_run:
  396. while dirs:
  397. archive.extract_item(dirs.pop(-1))
  398. for pattern in include_patterns:
  399. if pattern.match_count == 0:
  400. self.print_warning("Include pattern '%s' never matched.", pattern)
  401. return self.exit_code
  402. @with_repository()
  403. @with_archive
  404. def do_diff(self, args, repository, manifest, key, archive):
  405. """Diff contents of two archives"""
  406. def fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2):
  407. chunks1 = archive1.pipeline.fetch_many(chunk_ids1)
  408. chunks2 = archive2.pipeline.fetch_many(chunk_ids2)
  409. return self.compare_chunk_contents(chunks1, chunks2)
  410. def sum_chunk_size(item):
  411. if item.get(b'deleted'):
  412. return None
  413. else:
  414. return sum(c[1] for c in item[b'chunks'])
  415. def get_owner(item):
  416. if args.numeric_owner:
  417. return item[b'uid'], item[b'gid']
  418. else:
  419. return item[b'user'], item[b'group']
  420. def get_mode(item):
  421. if b'mode' in item:
  422. return stat.filemode(item[b'mode'])
  423. else:
  424. return [None]
  425. def has_hardlink_master(item, hardlink_masters):
  426. return item.get(b'source') in hardlink_masters and get_mode(item)[0] != 'l'
  427. def compare_link(item1, item2):
  428. # These are the simple link cases. For special cases, e.g. if a
  429. # regular file is replaced with a link or vice versa, it is
  430. # indicated in compare_mode instead.
  431. if item1.get(b'deleted'):
  432. return 'added link'
  433. elif item2.get(b'deleted'):
  434. return 'removed link'
  435. elif item1[b'source'] != item2[b'source']:
  436. return 'changed link'
  437. def contents_changed(item1, item2):
  438. if can_compare_chunk_ids:
  439. return item1[b'chunks'] != item2[b'chunks']
  440. else:
  441. if sum_chunk_size(item1) != sum_chunk_size(item2):
  442. return True
  443. else:
  444. chunk_ids1 = [c[0] for c in item1[b'chunks']]
  445. chunk_ids2 = [c[0] for c in item2[b'chunks']]
  446. return not fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2)
  447. def compare_content(path, item1, item2):
  448. if contents_changed(item1, item2):
  449. if item1.get(b'deleted'):
  450. return ('added {:>13}'.format(format_file_size(sum_chunk_size(item2))))
  451. elif item2.get(b'deleted'):
  452. return ('removed {:>11}'.format(format_file_size(sum_chunk_size(item1))))
  453. else:
  454. chunk_id_set1 = {c[0] for c in item1[b'chunks']}
  455. chunk_id_set2 = {c[0] for c in item2[b'chunks']}
  456. added = sum(c[1] for c in (chunk_id_set2 - chunk_id_set1))
  457. removed = -sum(c[1] for c in (chunk_id_set1 - chunk_id_set2))
  458. return ('{:>9} {:>9}'.format(format_file_size(added, precision=1, sign=True),
  459. format_file_size(removed, precision=1, sign=True)))
  460. def compare_directory(item1, item2):
  461. if item2.get(b'deleted') and not item1.get(b'deleted'):
  462. return 'removed directory'
  463. elif item1.get(b'deleted') and not item2.get(b'deleted'):
  464. return 'added directory'
  465. def compare_owner(item1, item2):
  466. user1, group1 = get_owner(item1)
  467. user2, group2 = get_owner(item2)
  468. if user1 != user2 or group1 != group2:
  469. return '[{}:{} -> {}:{}]'.format(user1, group1, user2, group2)
  470. def compare_mode(item1, item2):
  471. if item1[b'mode'] != item2[b'mode']:
  472. return '[{} -> {}]'.format(get_mode(item1), get_mode(item2))
  473. def compare_items(output, path, item1, item2, hardlink_masters, deleted=False):
  474. """
  475. Compare two items with identical paths.
  476. :param deleted: Whether one of the items has been deleted
  477. """
  478. changes = []
  479. if item1.get(b'hardlink_master') or item2.get(b'hardlink_master'):
  480. hardlink_masters[path] = (item1, item2)
  481. if has_hardlink_master(item1, hardlink_masters):
  482. item1 = hardlink_masters[item1[b'source']][0]
  483. if has_hardlink_master(item2, hardlink_masters):
  484. item2 = hardlink_masters[item2[b'source']][1]
  485. if get_mode(item1)[0] == 'l' or get_mode(item2)[0] == 'l':
  486. changes.append(compare_link(item1, item2))
  487. if b'chunks' in item1 and b'chunks' in item2:
  488. changes.append(compare_content(path, item1, item2))
  489. if get_mode(item1)[0] == 'd' or get_mode(item2)[0] == 'd':
  490. changes.append(compare_directory(item1, item2))
  491. if not deleted:
  492. changes.append(compare_owner(item1, item2))
  493. changes.append(compare_mode(item1, item2))
  494. changes = [x for x in changes if x]
  495. if changes:
  496. output_line = (remove_surrogates(path), ' '.join(changes))
  497. if args.sort:
  498. output.append(output_line)
  499. else:
  500. print_output(output_line)
  501. def print_output(line):
  502. print("{:<19} {}".format(line[1], line[0]))
  503. def compare_archives(archive1, archive2, matcher):
  504. orphans_archive1 = collections.OrderedDict()
  505. orphans_archive2 = collections.OrderedDict()
  506. hardlink_masters = {}
  507. output = []
  508. for item1, item2 in zip_longest(
  509. archive1.iter_items(lambda item: matcher.match(item[b'path'])),
  510. archive2.iter_items(lambda item: matcher.match(item[b'path'])),
  511. ):
  512. if item1 and item2 and item1[b'path'] == item2[b'path']:
  513. compare_items(output, item1[b'path'], item1, item2, hardlink_masters)
  514. continue
  515. if item1:
  516. matching_orphan = orphans_archive2.pop(item1[b'path'], None)
  517. if matching_orphan:
  518. compare_items(output, item1[b'path'], item1, matching_orphan, hardlink_masters)
  519. else:
  520. orphans_archive1[item1[b'path']] = item1
  521. if item2:
  522. matching_orphan = orphans_archive1.pop(item2[b'path'], None)
  523. if matching_orphan:
  524. compare_items(output, item2[b'path'], matching_orphan, item2, hardlink_masters)
  525. else:
  526. orphans_archive2[item2[b'path']] = item2
  527. # At this point orphans_* contain items that had no matching partner in the other archive
  528. for added in orphans_archive2.values():
  529. compare_items(output, added[b'path'], {
  530. b'deleted': True,
  531. b'chunks': [],
  532. }, added, hardlink_masters, deleted=True)
  533. for deleted in orphans_archive1.values():
  534. compare_items(output, deleted[b'path'], deleted, {
  535. b'deleted': True,
  536. b'chunks': [],
  537. }, hardlink_masters, deleted=True)
  538. for line in sorted(output):
  539. print_output(line)
  540. archive1 = archive
  541. archive2 = Archive(repository, key, manifest, args.archive2)
  542. can_compare_chunk_ids = archive1.metadata.get(b'chunker_params', False) == archive2.metadata.get(
  543. b'chunker_params', True) or args.same_chunker_params
  544. if not can_compare_chunk_ids:
  545. self.print_warning('--chunker-params might be different between archives, diff will be slow.\n'
  546. 'If you know for certain that they are the same, pass --same-chunker-params '
  547. 'to override this check.')
  548. matcher, include_patterns = self.build_matcher(args.excludes, args.paths)
  549. compare_archives(archive1, archive2, matcher)
  550. for pattern in include_patterns:
  551. if pattern.match_count == 0:
  552. self.print_warning("Include pattern '%s' never matched.", pattern)
  553. return self.exit_code
  554. @with_repository(exclusive=True, cache=True)
  555. @with_archive
  556. def do_rename(self, args, repository, manifest, key, cache, archive):
  557. """Rename an existing archive"""
  558. archive.rename(args.name)
  559. manifest.write()
  560. repository.commit()
  561. cache.commit()
  562. return self.exit_code
  563. @with_repository(exclusive=True, cache=True)
  564. @with_archive
  565. def do_comment(self, args, repository, manifest, key, cache, archive):
  566. """Set the archive comment"""
  567. archive.set_meta(b'comment', args.comment)
  568. manifest.write()
  569. repository.commit()
  570. cache.commit()
  571. return self.exit_code
  572. @with_repository(exclusive=True, cache=True)
  573. def do_delete(self, args, repository, manifest, key, cache):
  574. """Delete an existing repository or archive"""
  575. if args.location.archive:
  576. archive = Archive(repository, key, manifest, args.location.archive, cache=cache)
  577. stats = Statistics()
  578. archive.delete(stats, progress=args.progress)
  579. manifest.write()
  580. repository.commit(save_space=args.save_space)
  581. cache.commit()
  582. logger.info("Archive deleted.")
  583. if args.stats:
  584. log_multi(DASHES,
  585. stats.summary.format(label='Deleted data:', stats=stats),
  586. str(cache),
  587. DASHES)
  588. else:
  589. if not args.cache_only:
  590. msg = []
  591. msg.append("You requested to completely DELETE the repository *including* all archives it contains:")
  592. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  593. msg.append(format_archive(archive_info))
  594. msg.append("Type 'YES' if you understand this and want to continue: ")
  595. msg = '\n'.join(msg)
  596. if not yes(msg, false_msg="Aborting.", truish=('YES', ),
  597. env_var_override='BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'):
  598. self.exit_code = EXIT_ERROR
  599. return self.exit_code
  600. repository.destroy()
  601. logger.info("Repository deleted.")
  602. cache.destroy()
  603. logger.info("Cache deleted.")
  604. return self.exit_code
  605. @with_repository()
  606. def do_mount(self, args, repository, manifest, key):
  607. """Mount archive or an entire repository as a FUSE fileystem"""
  608. try:
  609. from .fuse import FuseOperations
  610. except ImportError as e:
  611. self.print_error('Loading fuse support failed [ImportError: %s]' % str(e))
  612. return self.exit_code
  613. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  614. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  615. return self.exit_code
  616. with cache_if_remote(repository) as cached_repo:
  617. if args.location.archive:
  618. archive = Archive(repository, key, manifest, args.location.archive)
  619. else:
  620. archive = None
  621. operations = FuseOperations(key, repository, manifest, archive, cached_repo)
  622. logger.info("Mounting filesystem")
  623. try:
  624. operations.mount(args.mountpoint, args.options, args.foreground)
  625. except RuntimeError:
  626. # Relevant error message already printed to stderr by fuse
  627. self.exit_code = EXIT_ERROR
  628. return self.exit_code
  629. @with_repository()
  630. def do_list(self, args, repository, manifest, key):
  631. """List archive or repository contents"""
  632. if args.location.archive:
  633. matcher, _ = self.build_matcher(args.excludes, args.paths)
  634. with Cache(repository, key, manifest, lock_wait=self.lock_wait) as cache:
  635. archive = Archive(repository, key, manifest, args.location.archive, cache=cache)
  636. if args.format:
  637. format = args.format
  638. elif args.short:
  639. format = "{path}{NL}"
  640. else:
  641. format = "{mode} {user:6} {group:6} {size:8} {isomtime} {path}{extra}{NL}"
  642. formatter = ItemFormatter(archive, format)
  643. if not hasattr(sys.stdout, 'buffer'):
  644. # This is a shim for supporting unit tests replacing sys.stdout with e.g. StringIO,
  645. # which doesn't have an underlying buffer (= lower file object).
  646. def write(bytestring):
  647. sys.stdout.write(bytestring.decode('utf-8', errors='replace'))
  648. else:
  649. write = sys.stdout.buffer.write
  650. for item in archive.iter_items(lambda item: matcher.match(item[b'path'])):
  651. write(formatter.format_item(item).encode('utf-8', errors='surrogateescape'))
  652. else:
  653. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  654. if args.prefix and not archive_info.name.startswith(args.prefix):
  655. continue
  656. if args.short:
  657. print(archive_info.name)
  658. else:
  659. print(format_archive(archive_info))
  660. return self.exit_code
  661. @with_repository(cache=True)
  662. @with_archive
  663. def do_info(self, args, repository, manifest, key, archive, cache):
  664. """Show archive details such as disk space used"""
  665. def format_cmdline(cmdline):
  666. return remove_surrogates(' '.join(shlex.quote(x) for x in cmdline))
  667. stats = archive.calc_stats(cache)
  668. print('Name:', archive.name)
  669. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  670. print('Comment:', archive.metadata.get(b'comment', ''))
  671. print('Hostname:', archive.metadata[b'hostname'])
  672. print('Username:', archive.metadata[b'username'])
  673. print('Time (start): %s' % format_time(to_localtime(archive.ts)))
  674. print('Time (end): %s' % format_time(to_localtime(archive.ts_end)))
  675. print('Command line:', format_cmdline(archive.metadata[b'cmdline']))
  676. print('Number of files: %d' % stats.nfiles)
  677. print()
  678. print(str(stats))
  679. print(str(cache))
  680. return self.exit_code
  681. @with_repository()
  682. def do_prune(self, args, repository, manifest, key):
  683. """Prune repository archives according to specified rules"""
  684. archives = manifest.list_archive_infos(sort_by='ts', reverse=True) # just a ArchiveInfo list
  685. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  686. self.print_error('At least one of the "keep-within", "keep-hourly", "keep-daily", "keep-weekly", '
  687. '"keep-monthly" or "keep-yearly" settings must be specified')
  688. return self.exit_code
  689. if args.prefix:
  690. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  691. keep = []
  692. if args.within:
  693. keep += prune_within(archives, args.within)
  694. if args.hourly:
  695. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  696. if args.daily:
  697. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  698. if args.weekly:
  699. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  700. if args.monthly:
  701. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  702. if args.yearly:
  703. keep += prune_split(archives, '%Y', args.yearly, keep)
  704. keep.sort(key=attrgetter('ts'), reverse=True)
  705. to_delete = [a for a in archives if a not in keep]
  706. stats = Statistics()
  707. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  708. for archive in keep:
  709. if args.output_list:
  710. logger.info('Keeping archive: %s' % format_archive(archive))
  711. for archive in to_delete:
  712. if args.dry_run:
  713. if args.output_list:
  714. logger.info('Would prune: %s' % format_archive(archive))
  715. else:
  716. if args.output_list:
  717. logger.info('Pruning archive: %s' % format_archive(archive))
  718. Archive(repository, key, manifest, archive.name, cache).delete(stats)
  719. if to_delete and not args.dry_run:
  720. manifest.write()
  721. repository.commit(save_space=args.save_space)
  722. cache.commit()
  723. if args.stats:
  724. log_multi(DASHES,
  725. stats.summary.format(label='Deleted data:', stats=stats),
  726. str(cache),
  727. DASHES)
  728. return self.exit_code
  729. def do_upgrade(self, args):
  730. """upgrade a repository from a previous version"""
  731. # mainly for upgrades from Attic repositories,
  732. # but also supports borg 0.xx -> 1.0 upgrade.
  733. repo = AtticRepositoryUpgrader(args.location.path, create=False)
  734. try:
  735. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  736. except NotImplementedError as e:
  737. print("warning: %s" % e)
  738. repo = BorgRepositoryUpgrader(args.location.path, create=False)
  739. try:
  740. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  741. except NotImplementedError as e:
  742. print("warning: %s" % e)
  743. return self.exit_code
  744. @with_repository()
  745. def do_debug_dump_archive_items(self, args, repository, manifest, key):
  746. """dump (decrypted, decompressed) archive items metadata (not: data)"""
  747. archive = Archive(repository, key, manifest, args.location.archive)
  748. for i, item_id in enumerate(archive.metadata[b'items']):
  749. data = key.decrypt(item_id, repository.get(item_id))
  750. filename = '%06d_%s.items' % (i, hexlify(item_id).decode('ascii'))
  751. print('Dumping', filename)
  752. with open(filename, 'wb') as fd:
  753. fd.write(data)
  754. print('Done.')
  755. return EXIT_SUCCESS
  756. @with_repository(manifest=False)
  757. def do_debug_get_obj(self, args, repository):
  758. """get object contents from the repository and write it into file"""
  759. hex_id = args.id
  760. try:
  761. id = unhexlify(hex_id)
  762. except ValueError:
  763. print("object id %s is invalid." % hex_id)
  764. else:
  765. try:
  766. data = repository.get(id)
  767. except repository.ObjectNotFound:
  768. print("object %s not found." % hex_id)
  769. else:
  770. with open(args.path, "wb") as f:
  771. f.write(data)
  772. print("object %s fetched." % hex_id)
  773. return EXIT_SUCCESS
  774. @with_repository(manifest=False)
  775. def do_debug_put_obj(self, args, repository):
  776. """put file(s) contents into the repository"""
  777. for path in args.paths:
  778. with open(path, "rb") as f:
  779. data = f.read()
  780. h = hashlib.sha256(data) # XXX hardcoded
  781. repository.put(h.digest(), data)
  782. print("object %s put." % h.hexdigest())
  783. repository.commit()
  784. return EXIT_SUCCESS
  785. @with_repository(manifest=False)
  786. def do_debug_delete_obj(self, args, repository):
  787. """delete the objects with the given IDs from the repo"""
  788. modified = False
  789. for hex_id in args.ids:
  790. try:
  791. id = unhexlify(hex_id)
  792. except ValueError:
  793. print("object id %s is invalid." % hex_id)
  794. else:
  795. try:
  796. repository.delete(id)
  797. modified = True
  798. print("object %s deleted." % hex_id)
  799. except repository.ObjectNotFound:
  800. print("object %s not found." % hex_id)
  801. if modified:
  802. repository.commit()
  803. print('Done.')
  804. return EXIT_SUCCESS
  805. @with_repository(lock=False, manifest=False)
  806. def do_break_lock(self, args, repository):
  807. """Break the repository lock (e.g. in case it was left by a dead borg."""
  808. repository.break_lock()
  809. Cache.break_lock(repository)
  810. return self.exit_code
  811. helptext = {}
  812. helptext['patterns'] = textwrap.dedent('''
  813. Exclusion patterns support four separate styles, fnmatch, shell, regular
  814. expressions and path prefixes. If followed by a colon (':') the first two
  815. characters of a pattern are used as a style selector. Explicit style
  816. selection is necessary when a non-default style is desired or when the
  817. desired pattern starts with two alphanumeric characters followed by a colon
  818. (i.e. `aa:something/*`).
  819. `Fnmatch <https://docs.python.org/3/library/fnmatch.html>`_, selector `fm:`
  820. These patterns use a variant of shell pattern syntax, with '*' matching
  821. any number of characters, '?' matching any single character, '[...]'
  822. matching any single character specified, including ranges, and '[!...]'
  823. matching any character not specified. For the purpose of these patterns,
  824. the path separator ('\\' for Windows and '/' on other systems) is not
  825. treated specially. Wrap meta-characters in brackets for a literal match
  826. (i.e. `[?]` to match the literal character `?`). For a path to match
  827. a pattern, it must completely match from start to end, or must match from
  828. the start to just before a path separator. Except for the root path,
  829. paths will never end in the path separator when matching is attempted.
  830. Thus, if a given pattern ends in a path separator, a '*' is appended
  831. before matching is attempted.
  832. Shell-style patterns, selector `sh:`
  833. Like fnmatch patterns these are similar to shell patterns. The difference
  834. is that the pattern may include `**/` for matching zero or more directory
  835. levels, `*` for matching zero or more arbitrary characters with the
  836. exception of any path separator.
  837. Regular expressions, selector `re:`
  838. Regular expressions similar to those found in Perl are supported. Unlike
  839. shell patterns regular expressions are not required to match the complete
  840. path and any substring match is sufficient. It is strongly recommended to
  841. anchor patterns to the start ('^'), to the end ('$') or both. Path
  842. separators ('\\' for Windows and '/' on other systems) in paths are
  843. always normalized to a forward slash ('/') before applying a pattern. The
  844. regular expression syntax is described in the `Python documentation for
  845. the re module <https://docs.python.org/3/library/re.html>`_.
  846. Prefix path, selector `pp:`
  847. This pattern style is useful to match whole sub-directories. The pattern
  848. `pp:/data/bar` matches `/data/bar` and everything therein.
  849. Exclusions can be passed via the command line option `--exclude`. When used
  850. from within a shell the patterns should be quoted to protect them from
  851. expansion.
  852. The `--exclude-from` option permits loading exclusion patterns from a text
  853. file with one pattern per line. Lines empty or starting with the number sign
  854. ('#') after removing whitespace on both ends are ignored. The optional style
  855. selector prefix is also supported for patterns loaded from a file. Due to
  856. whitespace removal paths with whitespace at the beginning or end can only be
  857. excluded using regular expressions.
  858. Examples:
  859. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  860. $ borg create -e '*.o' backup /
  861. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  862. # not '/home/user/importantjunk' or '/etc/junk':
  863. $ borg create -e '/home/*/junk' backup /
  864. # Exclude the contents of '/home/user/cache' but not the directory itself:
  865. $ borg create -e /home/user/cache/ backup /
  866. # The file '/home/user/cache/important' is *not* backed up:
  867. $ borg create -e /home/user/cache/ backup / /home/user/cache/important
  868. # The contents of directories in '/home' are not backed up when their name
  869. # ends in '.tmp'
  870. $ borg create --exclude 're:^/home/[^/]+\.tmp/' backup /
  871. # Load exclusions from file
  872. $ cat >exclude.txt <<EOF
  873. # Comment line
  874. /home/*/junk
  875. *.tmp
  876. fm:aa:something/*
  877. re:^/home/[^/]\.tmp/
  878. sh:/home/*/.thumbnails
  879. EOF
  880. $ borg create --exclude-from exclude.txt backup /
  881. ''')
  882. def do_help(self, parser, commands, args):
  883. if not args.topic:
  884. parser.print_help()
  885. elif args.topic in self.helptext:
  886. print(self.helptext[args.topic])
  887. elif args.topic in commands:
  888. if args.epilog_only:
  889. print(commands[args.topic].epilog)
  890. elif args.usage_only:
  891. commands[args.topic].epilog = None
  892. commands[args.topic].print_help()
  893. else:
  894. commands[args.topic].print_help()
  895. else:
  896. parser.error('No help available on %s' % (args.topic,))
  897. return self.exit_code
  898. def preprocess_args(self, args):
  899. deprecations = [
  900. # ('--old', '--new', 'Warning: "--old" has been deprecated. Use "--new" instead.'),
  901. ('--list-format', '--format', 'Warning: "--list-format" has been deprecated. Use "--format" instead.'),
  902. ]
  903. for i, arg in enumerate(args[:]):
  904. for old_name, new_name, warning in deprecations:
  905. if arg.startswith(old_name):
  906. args[i] = arg.replace(old_name, new_name)
  907. self.print_warning(warning)
  908. return args
  909. def build_parser(self, args=None, prog=None):
  910. common_parser = argparse.ArgumentParser(add_help=False, prog=prog)
  911. common_parser.add_argument('-v', '--verbose', '--info', dest='log_level',
  912. action='store_const', const='info', default='warning',
  913. help='enable informative (verbose) output, work on log level INFO')
  914. common_parser.add_argument('--debug', dest='log_level',
  915. action='store_const', const='debug', default='warning',
  916. help='enable debug output, work on log level DEBUG')
  917. common_parser.add_argument('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1,
  918. help='wait for the lock, but max. N seconds (default: %(default)d).')
  919. common_parser.add_argument('--show-version', dest='show_version', action='store_true', default=False,
  920. help='show/log the borg version')
  921. common_parser.add_argument('--show-rc', dest='show_rc', action='store_true', default=False,
  922. help='show/log the return code (rc)')
  923. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false',
  924. help='do not load/update the file metadata cache used to detect unchanged files')
  925. common_parser.add_argument('--umask', dest='umask', type=lambda s: int(s, 8), default=UMASK_DEFAULT, metavar='M',
  926. help='set umask to M (local and remote, default: %(default)04o)')
  927. common_parser.add_argument('--remote-path', dest='remote_path', default='borg', metavar='PATH',
  928. help='set remote path to executable (default: "%(default)s")')
  929. parser = argparse.ArgumentParser(prog=prog, description='Borg - Deduplicated Backups')
  930. parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__,
  931. help='show version number and exit')
  932. subparsers = parser.add_subparsers(title='required arguments', metavar='<command>')
  933. serve_epilog = textwrap.dedent("""
  934. This command starts a repository server process. This command is usually not used manually.
  935. """)
  936. subparser = subparsers.add_parser('serve', parents=[common_parser],
  937. description=self.do_serve.__doc__, epilog=serve_epilog,
  938. formatter_class=argparse.RawDescriptionHelpFormatter,
  939. help='start repository server process')
  940. subparser.set_defaults(func=self.do_serve)
  941. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  942. metavar='PATH', help='restrict repository access to PATH')
  943. init_epilog = textwrap.dedent("""
  944. This command initializes an empty repository. A repository is a filesystem
  945. directory containing the deduplicated data from zero or more archives.
  946. Encryption can be enabled at repository init time.
  947. """)
  948. subparser = subparsers.add_parser('init', parents=[common_parser],
  949. description=self.do_init.__doc__, epilog=init_epilog,
  950. formatter_class=argparse.RawDescriptionHelpFormatter,
  951. help='initialize empty repository')
  952. subparser.set_defaults(func=self.do_init)
  953. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  954. type=location_validator(archive=False),
  955. help='repository to create')
  956. subparser.add_argument('-e', '--encryption', dest='encryption',
  957. choices=('none', 'keyfile', 'repokey'), default='repokey',
  958. help='select encryption key mode (default: "%(default)s")')
  959. check_epilog = textwrap.dedent("""
  960. The check command verifies the consistency of a repository and the corresponding archives.
  961. First, the underlying repository data files are checked:
  962. - For all segments the segment magic (header) is checked
  963. - For all objects stored in the segments, all metadata (e.g. crc and size) and
  964. all data is read. The read data is checked by size and CRC. Bit rot and other
  965. types of accidental damage can be detected this way.
  966. - If we are in repair mode and a integrity error is detected for a segment,
  967. we try to recover as many objects from the segment as possible.
  968. - In repair mode, it makes sure that the index is consistent with the data
  969. stored in the segments.
  970. - If you use a remote repo server via ssh:, the repo check is executed on the
  971. repo server without causing significant network traffic.
  972. - The repository check can be skipped using the --archives-only option.
  973. Second, the consistency and correctness of the archive metadata is verified:
  974. - Is the repo manifest present? If not, it is rebuilt from archive metadata
  975. chunks (this requires reading and decrypting of all metadata and data).
  976. - Check if archive metadata chunk is present. if not, remove archive from
  977. manifest.
  978. - For all files (items) in the archive, for all chunks referenced by these
  979. files, check if chunk is present (if not and we are in repair mode, replace
  980. it with a same-size chunk of zeros). This requires reading of archive and
  981. file metadata, but not data.
  982. - If we are in repair mode and we checked all the archives: delete orphaned
  983. chunks from the repo.
  984. - if you use a remote repo server via ssh:, the archive check is executed on
  985. the client machine (because if encryption is enabled, the checks will require
  986. decryption and this is always done client-side, because key access will be
  987. required).
  988. - The archive checks can be time consuming, they can be skipped using the
  989. --repository-only option.
  990. """)
  991. subparser = subparsers.add_parser('check', parents=[common_parser],
  992. description=self.do_check.__doc__,
  993. epilog=check_epilog,
  994. formatter_class=argparse.RawDescriptionHelpFormatter,
  995. help='verify repository')
  996. subparser.set_defaults(func=self.do_check)
  997. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  998. type=location_validator(),
  999. help='repository or archive to check consistency of')
  1000. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  1001. default=False,
  1002. help='only perform repository checks')
  1003. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  1004. default=False,
  1005. help='only perform archives checks')
  1006. subparser.add_argument('--repair', dest='repair', action='store_true',
  1007. default=False,
  1008. help='attempt to repair any inconsistencies found')
  1009. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1010. default=False,
  1011. help='work slower, but using less space')
  1012. subparser.add_argument('--last', dest='last',
  1013. type=int, default=None, metavar='N',
  1014. help='only check last N archives (Default: all)')
  1015. subparser.add_argument('-P', '--prefix', dest='prefix', type=str,
  1016. help='only consider archive names starting with this prefix')
  1017. change_passphrase_epilog = textwrap.dedent("""
  1018. The key files used for repository encryption are optionally passphrase
  1019. protected. This command can be used to change this passphrase.
  1020. """)
  1021. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  1022. description=self.do_change_passphrase.__doc__,
  1023. epilog=change_passphrase_epilog,
  1024. formatter_class=argparse.RawDescriptionHelpFormatter,
  1025. help='change repository passphrase')
  1026. subparser.set_defaults(func=self.do_change_passphrase)
  1027. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1028. type=location_validator(archive=False))
  1029. migrate_to_repokey_epilog = textwrap.dedent("""
  1030. This command migrates a repository from passphrase mode (not supported any
  1031. more) to repokey mode.
  1032. You will be first asked for the repository passphrase (to open it in passphrase
  1033. mode). This is the same passphrase as you used to use for this repo before 1.0.
  1034. It will then derive the different secrets from this passphrase.
  1035. Then you will be asked for a new passphrase (twice, for safety). This
  1036. passphrase will be used to protect the repokey (which contains these same
  1037. secrets in encrypted form). You may use the same passphrase as you used to
  1038. use, but you may also use a different one.
  1039. After migrating to repokey mode, you can change the passphrase at any time.
  1040. But please note: the secrets will always stay the same and they could always
  1041. be derived from your (old) passphrase-mode passphrase.
  1042. """)
  1043. subparser = subparsers.add_parser('migrate-to-repokey', parents=[common_parser],
  1044. description=self.do_migrate_to_repokey.__doc__,
  1045. epilog=migrate_to_repokey_epilog,
  1046. formatter_class=argparse.RawDescriptionHelpFormatter,
  1047. help='migrate passphrase-mode repository to repokey')
  1048. subparser.set_defaults(func=self.do_migrate_to_repokey)
  1049. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1050. type=location_validator(archive=False))
  1051. create_epilog = textwrap.dedent("""
  1052. This command creates a backup archive containing all files found while recursively
  1053. traversing all paths specified. The archive will consume almost no disk space for
  1054. files or parts of files that have already been stored in other archives.
  1055. To speed up pulling backups over sshfs and similar network file systems which do
  1056. not provide correct inode information the --ignore-inode flag can be used. This
  1057. potentially decreases reliability of change detection, while avoiding always reading
  1058. all files on these file systems.
  1059. See the output of the "borg help patterns" command for more help on exclude patterns.
  1060. """)
  1061. subparser = subparsers.add_parser('create', parents=[common_parser],
  1062. description=self.do_create.__doc__,
  1063. epilog=create_epilog,
  1064. formatter_class=argparse.RawDescriptionHelpFormatter,
  1065. help='create backup')
  1066. subparser.set_defaults(func=self.do_create)
  1067. subparser.add_argument('--comment', dest='comment', metavar='COMMENT', default='',
  1068. help='add a comment text to the archive')
  1069. subparser.add_argument('-s', '--stats', dest='stats',
  1070. action='store_true', default=False,
  1071. help='print statistics for the created archive')
  1072. subparser.add_argument('-p', '--progress', dest='progress',
  1073. action='store_true', default=False,
  1074. help="""show progress display while creating the archive, showing Original,
  1075. Compressed and Deduplicated sizes, followed by the Number of files seen
  1076. and the path being processed, default: %(default)s""")
  1077. subparser.add_argument('--list', dest='output_list',
  1078. action='store_true', default=False,
  1079. help='output verbose list of items (files, dirs, ...)')
  1080. subparser.add_argument('--filter', dest='output_filter', metavar='STATUSCHARS',
  1081. help='only display items with the given status characters')
  1082. subparser.add_argument('-e', '--exclude', dest='excludes',
  1083. type=parse_pattern, action='append',
  1084. metavar="PATTERN", help='exclude paths matching PATTERN')
  1085. subparser.add_argument('--exclude-from', dest='exclude_files',
  1086. type=argparse.FileType('r'), action='append',
  1087. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1088. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  1089. action='store_true', default=False,
  1090. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  1091. subparser.add_argument('--exclude-if-present', dest='exclude_if_present',
  1092. metavar='FILENAME', action='append', type=str,
  1093. help='exclude directories that contain the specified file')
  1094. subparser.add_argument('--keep-tag-files', dest='keep_tag_files',
  1095. action='store_true', default=False,
  1096. help='keep tag files of excluded caches/directories')
  1097. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  1098. type=int, default=300, metavar='SECONDS',
  1099. help='write checkpoint every SECONDS seconds (Default: 300)')
  1100. subparser.add_argument('-x', '--one-file-system', dest='one_file_system',
  1101. action='store_true', default=False,
  1102. help='stay in same file system, do not cross mount points')
  1103. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1104. action='store_true', default=False,
  1105. help='only store numeric user and group identifiers')
  1106. subparser.add_argument('--timestamp', dest='timestamp',
  1107. type=timestamp, default=None,
  1108. metavar='yyyy-mm-ddThh:mm:ss',
  1109. help='manually specify the archive creation date/time (UTC). '
  1110. 'alternatively, give a reference file/directory.')
  1111. subparser.add_argument('--chunker-params', dest='chunker_params',
  1112. type=ChunkerParams, default=CHUNKER_PARAMS,
  1113. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  1114. help='specify the chunker parameters. default: %d,%d,%d,%d' % CHUNKER_PARAMS)
  1115. subparser.add_argument('--ignore-inode', dest='ignore_inode',
  1116. action='store_true', default=False,
  1117. help='ignore inode data in the file metadata cache used to detect unchanged files.')
  1118. subparser.add_argument('-C', '--compression', dest='compression',
  1119. type=CompressionSpec, default=dict(name='none'), metavar='COMPRESSION',
  1120. help='select compression algorithm (and level): '
  1121. 'none == no compression (default), '
  1122. 'lz4 == lz4, '
  1123. 'zlib == zlib (default level 6), '
  1124. 'zlib,0 .. zlib,9 == zlib (with level 0..9), '
  1125. 'lzma == lzma (default level 6), '
  1126. 'lzma,0 .. lzma,9 == lzma (with level 0..9).')
  1127. subparser.add_argument('--read-special', dest='read_special',
  1128. action='store_true', default=False,
  1129. help='open and read special files as if they were regular files')
  1130. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1131. action='store_true', default=False,
  1132. help='do not create a backup archive')
  1133. subparser.add_argument('location', metavar='ARCHIVE',
  1134. type=location_validator(archive=True),
  1135. help='name of archive to create (must be also a valid directory name)')
  1136. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1137. help='paths to archive')
  1138. extract_epilog = textwrap.dedent("""
  1139. This command extracts the contents of an archive. By default the entire
  1140. archive is extracted but a subset of files and directories can be selected
  1141. by passing a list of ``PATHs`` as arguments. The file selection can further
  1142. be restricted by using the ``--exclude`` option.
  1143. See the output of the "borg help patterns" command for more help on exclude patterns.
  1144. """)
  1145. subparser = subparsers.add_parser('extract', parents=[common_parser],
  1146. description=self.do_extract.__doc__,
  1147. epilog=extract_epilog,
  1148. formatter_class=argparse.RawDescriptionHelpFormatter,
  1149. help='extract archive contents')
  1150. subparser.set_defaults(func=self.do_extract)
  1151. subparser.add_argument('--list', dest='output_list',
  1152. action='store_true', default=False,
  1153. help='output verbose list of items (files, dirs, ...)')
  1154. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1155. default=False, action='store_true',
  1156. help='do not actually change any files')
  1157. subparser.add_argument('-e', '--exclude', dest='excludes',
  1158. type=parse_pattern, action='append',
  1159. metavar="PATTERN", help='exclude paths matching PATTERN')
  1160. subparser.add_argument('--exclude-from', dest='exclude_files',
  1161. type=argparse.FileType('r'), action='append',
  1162. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1163. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1164. action='store_true', default=False,
  1165. help='only obey numeric user and group identifiers')
  1166. subparser.add_argument('--strip-components', dest='strip_components',
  1167. type=int, default=0, metavar='NUMBER',
  1168. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  1169. subparser.add_argument('--stdout', dest='stdout',
  1170. action='store_true', default=False,
  1171. help='write all extracted data to stdout')
  1172. subparser.add_argument('--sparse', dest='sparse',
  1173. action='store_true', default=False,
  1174. help='create holes in output sparse file from all-zero chunks')
  1175. subparser.add_argument('location', metavar='ARCHIVE',
  1176. type=location_validator(archive=True),
  1177. help='archive to extract')
  1178. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1179. help='paths to extract; patterns are supported')
  1180. diff_epilog = textwrap.dedent("""
  1181. This command finds differences in files (contents, user, group, mode) between archives.
  1182. Both archives need to be in the same repository, and a repository location may only
  1183. be specified for ARCHIVE1.
  1184. For archives created with Borg 1.1 or newer diff automatically detects whether
  1185. the archives are created with the same chunker params. If so, only chunk IDs
  1186. are compared, which is very fast.
  1187. For archives prior to Borg 1.1 chunk contents are compared by default.
  1188. If you did not create the archives with different chunker params,
  1189. pass --same-chunker-params.
  1190. Note that the chunker params changed from Borg 0.xx to 1.0.
  1191. See the output of the "borg help patterns" command for more help on exclude patterns.
  1192. """)
  1193. subparser = subparsers.add_parser('diff', parents=[common_parser],
  1194. description=self.do_diff.__doc__,
  1195. epilog=diff_epilog,
  1196. formatter_class=argparse.RawDescriptionHelpFormatter,
  1197. help='find differences in archive contents')
  1198. subparser.set_defaults(func=self.do_diff)
  1199. subparser.add_argument('-e', '--exclude', dest='excludes',
  1200. type=parse_pattern, action='append',
  1201. metavar="PATTERN", help='exclude paths matching PATTERN')
  1202. subparser.add_argument('--exclude-from', dest='exclude_files',
  1203. type=argparse.FileType('r'), action='append',
  1204. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1205. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1206. action='store_true', default=False,
  1207. help='only consider numeric user and group identifiers')
  1208. subparser.add_argument('--same-chunker-params', dest='same_chunker_params',
  1209. action='store_true', default=False,
  1210. help='Override check of chunker parameters.')
  1211. subparser.add_argument('--sort', dest='sort',
  1212. action='store_true', default=False,
  1213. help='Sort the output lines by file path.')
  1214. subparser.add_argument('location', metavar='ARCHIVE1',
  1215. type=location_validator(archive=True),
  1216. help='archive')
  1217. subparser.add_argument('archive2', metavar='ARCHIVE2',
  1218. type=archivename_validator(),
  1219. help='archive to compare with ARCHIVE1 (no repository location)')
  1220. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1221. help='paths to compare; patterns are supported')
  1222. rename_epilog = textwrap.dedent("""
  1223. This command renames an archive in the repository.
  1224. """)
  1225. subparser = subparsers.add_parser('rename', parents=[common_parser],
  1226. description=self.do_rename.__doc__,
  1227. epilog=rename_epilog,
  1228. formatter_class=argparse.RawDescriptionHelpFormatter,
  1229. help='rename archive')
  1230. subparser.set_defaults(func=self.do_rename)
  1231. subparser.add_argument('location', metavar='ARCHIVE',
  1232. type=location_validator(archive=True),
  1233. help='archive to rename')
  1234. subparser.add_argument('name', metavar='NEWNAME',
  1235. type=archivename_validator(),
  1236. help='the new archive name to use')
  1237. comment_epilog = textwrap.dedent("""
  1238. This command sets the archive comment.
  1239. """)
  1240. subparser = subparsers.add_parser('comment', parents=[common_parser],
  1241. description=self.do_comment.__doc__,
  1242. epilog=comment_epilog,
  1243. formatter_class=argparse.RawDescriptionHelpFormatter,
  1244. help='set the archive comment')
  1245. subparser.set_defaults(func=self.do_comment)
  1246. subparser.add_argument('location', metavar='ARCHIVE',
  1247. type=location_validator(archive=True),
  1248. help='archive to modify')
  1249. subparser.add_argument('comment', metavar='COMMENT',
  1250. help='the new archive comment')
  1251. delete_epilog = textwrap.dedent("""
  1252. This command deletes an archive from the repository or the complete repository.
  1253. Disk space is reclaimed accordingly. If you delete the complete repository, the
  1254. local cache for it (if any) is also deleted.
  1255. """)
  1256. subparser = subparsers.add_parser('delete', parents=[common_parser],
  1257. description=self.do_delete.__doc__,
  1258. epilog=delete_epilog,
  1259. formatter_class=argparse.RawDescriptionHelpFormatter,
  1260. help='delete archive')
  1261. subparser.set_defaults(func=self.do_delete)
  1262. subparser.add_argument('-p', '--progress', dest='progress',
  1263. action='store_true', default=False,
  1264. help="""show progress display while deleting a single archive""")
  1265. subparser.add_argument('-s', '--stats', dest='stats',
  1266. action='store_true', default=False,
  1267. help='print statistics for the deleted archive')
  1268. subparser.add_argument('-c', '--cache-only', dest='cache_only',
  1269. action='store_true', default=False,
  1270. help='delete only the local cache for the given repository')
  1271. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1272. default=False,
  1273. help='work slower, but using less space')
  1274. subparser.add_argument('location', metavar='TARGET', nargs='?', default='',
  1275. type=location_validator(),
  1276. help='archive or repository to delete')
  1277. list_epilog = textwrap.dedent("""
  1278. This command lists the contents of a repository or an archive.
  1279. See the "borg help patterns" command for more help on exclude patterns.
  1280. The following keys are available for --format when listing files:
  1281. """) + ItemFormatter.keys_help()
  1282. subparser = subparsers.add_parser('list', parents=[common_parser],
  1283. description=self.do_list.__doc__,
  1284. epilog=list_epilog,
  1285. formatter_class=argparse.RawDescriptionHelpFormatter,
  1286. help='list archive or repository contents')
  1287. subparser.set_defaults(func=self.do_list)
  1288. subparser.add_argument('--short', dest='short',
  1289. action='store_true', default=False,
  1290. help='only print file/directory names, nothing else')
  1291. subparser.add_argument('--format', '--list-format', dest='format', type=str,
  1292. help="""specify format for file listing
  1293. (default: "{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NL}")""")
  1294. subparser.add_argument('-P', '--prefix', dest='prefix', type=str,
  1295. help='only consider archive names starting with this prefix')
  1296. subparser.add_argument('-e', '--exclude', dest='excludes',
  1297. type=parse_pattern, action='append',
  1298. metavar="PATTERN", help='exclude paths matching PATTERN')
  1299. subparser.add_argument('--exclude-from', dest='exclude_files',
  1300. type=argparse.FileType('r'), action='append',
  1301. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1302. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  1303. type=location_validator(),
  1304. help='repository/archive to list contents of')
  1305. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1306. help='paths to list; patterns are supported')
  1307. mount_epilog = textwrap.dedent("""
  1308. This command mounts an archive as a FUSE filesystem. This can be useful for
  1309. browsing an archive or restoring individual files. Unless the ``--foreground``
  1310. option is given the command will run in the background until the filesystem
  1311. is ``umounted``.
  1312. The command ``borgfs`` provides a wrapper for ``borg mount``. This can also be
  1313. used in fstab entries:
  1314. ``/path/to/repo /mnt/point fuse.borgfs defaults,noauto 0 0``
  1315. To allow a regular user to use fstab entries, add the ``user`` option:
  1316. ``/path/to/repo /mnt/point fuse.borgfs defaults,noauto,user 0 0``
  1317. """)
  1318. subparser = subparsers.add_parser('mount', parents=[common_parser],
  1319. description=self.do_mount.__doc__,
  1320. epilog=mount_epilog,
  1321. formatter_class=argparse.RawDescriptionHelpFormatter,
  1322. help='mount repository')
  1323. subparser.set_defaults(func=self.do_mount)
  1324. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  1325. help='repository/archive to mount')
  1326. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  1327. help='where to mount filesystem')
  1328. subparser.add_argument('-f', '--foreground', dest='foreground',
  1329. action='store_true', default=False,
  1330. help='stay in foreground, do not daemonize')
  1331. subparser.add_argument('-o', dest='options', type=str,
  1332. help='Extra mount options')
  1333. info_epilog = textwrap.dedent("""
  1334. This command displays some detailed information about the specified archive.
  1335. """)
  1336. subparser = subparsers.add_parser('info', parents=[common_parser],
  1337. description=self.do_info.__doc__,
  1338. epilog=info_epilog,
  1339. formatter_class=argparse.RawDescriptionHelpFormatter,
  1340. help='show archive information')
  1341. subparser.set_defaults(func=self.do_info)
  1342. subparser.add_argument('location', metavar='ARCHIVE',
  1343. type=location_validator(archive=True),
  1344. help='archive to display information about')
  1345. break_lock_epilog = textwrap.dedent("""
  1346. This command breaks the repository and cache locks.
  1347. Please use carefully and only while no borg process (on any machine) is
  1348. trying to access the Cache or the Repository.
  1349. """)
  1350. subparser = subparsers.add_parser('break-lock', parents=[common_parser],
  1351. description=self.do_break_lock.__doc__,
  1352. epilog=break_lock_epilog,
  1353. formatter_class=argparse.RawDescriptionHelpFormatter,
  1354. help='break repository and cache locks')
  1355. subparser.set_defaults(func=self.do_break_lock)
  1356. subparser.add_argument('location', metavar='REPOSITORY',
  1357. type=location_validator(archive=False),
  1358. help='repository for which to break the locks')
  1359. prune_epilog = textwrap.dedent("""
  1360. The prune command prunes a repository by deleting archives not matching
  1361. any of the specified retention options. This command is normally used by
  1362. automated backup scripts wanting to keep a certain number of historic backups.
  1363. As an example, "-d 7" means to keep the latest backup on each day, up to 7
  1364. most recent days with backups (days without backups do not count).
  1365. The rules are applied from hourly to yearly, and backups selected by previous
  1366. rules do not count towards those of later rules. The time that each backup
  1367. completes is used for pruning purposes. Dates and times are interpreted in
  1368. the local timezone, and weeks go from Monday to Sunday. Specifying a
  1369. negative number of archives to keep means that there is no limit.
  1370. The "--keep-within" option takes an argument of the form "<int><char>",
  1371. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  1372. to keep all archives that were created within the past 48 hours.
  1373. "1m" is taken to mean "31d". The archives kept with this option do not
  1374. count towards the totals specified by any other options.
  1375. If a prefix is set with -P, then only archives that start with the prefix are
  1376. considered for deletion and only those archives count towards the totals
  1377. specified by the rules.
  1378. Otherwise, *all* archives in the repository are candidates for deletion!
  1379. """)
  1380. subparser = subparsers.add_parser('prune', parents=[common_parser],
  1381. description=self.do_prune.__doc__,
  1382. epilog=prune_epilog,
  1383. formatter_class=argparse.RawDescriptionHelpFormatter,
  1384. help='prune archives')
  1385. subparser.set_defaults(func=self.do_prune)
  1386. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1387. default=False, action='store_true',
  1388. help='do not change repository')
  1389. subparser.add_argument('-s', '--stats', dest='stats',
  1390. action='store_true', default=False,
  1391. help='print statistics for the deleted archive')
  1392. subparser.add_argument('--list', dest='output_list',
  1393. action='store_true', default=False,
  1394. help='output verbose list of archives it keeps/prunes')
  1395. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  1396. help='keep all archives within this time interval')
  1397. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  1398. help='number of hourly archives to keep')
  1399. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  1400. help='number of daily archives to keep')
  1401. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  1402. help='number of weekly archives to keep')
  1403. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  1404. help='number of monthly archives to keep')
  1405. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  1406. help='number of yearly archives to keep')
  1407. subparser.add_argument('-P', '--prefix', dest='prefix', type=str,
  1408. help='only consider archive names starting with this prefix')
  1409. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1410. default=False,
  1411. help='work slower, but using less space')
  1412. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1413. type=location_validator(archive=False),
  1414. help='repository to prune')
  1415. upgrade_epilog = textwrap.dedent("""
  1416. Upgrade an existing Borg repository.
  1417. This currently supports converting an Attic repository to Borg and also
  1418. helps with converting Borg 0.xx to 1.0.
  1419. Currently, only LOCAL repositories can be upgraded (issue #465).
  1420. It will change the magic strings in the repository's segments
  1421. to match the new Borg magic strings. The keyfiles found in
  1422. $ATTIC_KEYS_DIR or ~/.attic/keys/ will also be converted and
  1423. copied to $BORG_KEYS_DIR or ~/.config/borg/keys.
  1424. The cache files are converted, from $ATTIC_CACHE_DIR or
  1425. ~/.cache/attic to $BORG_CACHE_DIR or ~/.cache/borg, but the
  1426. cache layout between Borg and Attic changed, so it is possible
  1427. the first backup after the conversion takes longer than expected
  1428. due to the cache resync.
  1429. Upgrade should be able to resume if interrupted, although it
  1430. will still iterate over all segments. If you want to start
  1431. from scratch, use `borg delete` over the copied repository to
  1432. make sure the cache files are also removed:
  1433. borg delete borg
  1434. Unless ``--inplace`` is specified, the upgrade process first
  1435. creates a backup copy of the repository, in
  1436. REPOSITORY.upgrade-DATETIME, using hardlinks. This takes
  1437. longer than in place upgrades, but is much safer and gives
  1438. progress information (as opposed to ``cp -al``). Once you are
  1439. satisfied with the conversion, you can safely destroy the
  1440. backup copy.
  1441. WARNING: Running the upgrade in place will make the current
  1442. copy unusable with older version, with no way of going back
  1443. to previous versions. This can PERMANENTLY DAMAGE YOUR
  1444. REPOSITORY! Attic CAN NOT READ BORG REPOSITORIES, as the
  1445. magic strings have changed. You have been warned.""")
  1446. subparser = subparsers.add_parser('upgrade', parents=[common_parser],
  1447. description=self.do_upgrade.__doc__,
  1448. epilog=upgrade_epilog,
  1449. formatter_class=argparse.RawDescriptionHelpFormatter,
  1450. help='upgrade repository format')
  1451. subparser.set_defaults(func=self.do_upgrade)
  1452. subparser.add_argument('-p', '--progress', dest='progress',
  1453. action='store_true', default=False,
  1454. help="""show progress display while upgrading the repository""")
  1455. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1456. default=False, action='store_true',
  1457. help='do not change repository')
  1458. subparser.add_argument('-i', '--inplace', dest='inplace',
  1459. default=False, action='store_true',
  1460. help="""rewrite repository in place, with no chance of going back to older
  1461. versions of the repository.""")
  1462. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1463. type=location_validator(archive=False),
  1464. help='path to the repository to be upgraded')
  1465. subparser = subparsers.add_parser('help', parents=[common_parser],
  1466. description='Extra help')
  1467. subparser.add_argument('--epilog-only', dest='epilog_only',
  1468. action='store_true', default=False)
  1469. subparser.add_argument('--usage-only', dest='usage_only',
  1470. action='store_true', default=False)
  1471. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  1472. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  1473. help='additional help on TOPIC')
  1474. debug_dump_archive_items_epilog = textwrap.dedent("""
  1475. This command dumps raw (but decrypted and decompressed) archive items (only metadata) to files.
  1476. """)
  1477. subparser = subparsers.add_parser('debug-dump-archive-items', parents=[common_parser],
  1478. description=self.do_debug_dump_archive_items.__doc__,
  1479. epilog=debug_dump_archive_items_epilog,
  1480. formatter_class=argparse.RawDescriptionHelpFormatter,
  1481. help='dump archive items (metadata) (debug)')
  1482. subparser.set_defaults(func=self.do_debug_dump_archive_items)
  1483. subparser.add_argument('location', metavar='ARCHIVE',
  1484. type=location_validator(archive=True),
  1485. help='archive to dump')
  1486. debug_get_obj_epilog = textwrap.dedent("""
  1487. This command gets an object from the repository.
  1488. """)
  1489. subparser = subparsers.add_parser('debug-get-obj', parents=[common_parser],
  1490. description=self.do_debug_get_obj.__doc__,
  1491. epilog=debug_get_obj_epilog,
  1492. formatter_class=argparse.RawDescriptionHelpFormatter,
  1493. help='get object from repository (debug)')
  1494. subparser.set_defaults(func=self.do_debug_get_obj)
  1495. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1496. type=location_validator(archive=False),
  1497. help='repository to use')
  1498. subparser.add_argument('id', metavar='ID', type=str,
  1499. help='hex object ID to get from the repo')
  1500. subparser.add_argument('path', metavar='PATH', type=str,
  1501. help='file to write object data into')
  1502. debug_put_obj_epilog = textwrap.dedent("""
  1503. This command puts objects into the repository.
  1504. """)
  1505. subparser = subparsers.add_parser('debug-put-obj', parents=[common_parser],
  1506. description=self.do_debug_put_obj.__doc__,
  1507. epilog=debug_put_obj_epilog,
  1508. formatter_class=argparse.RawDescriptionHelpFormatter,
  1509. help='put object to repository (debug)')
  1510. subparser.set_defaults(func=self.do_debug_put_obj)
  1511. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1512. type=location_validator(archive=False),
  1513. help='repository to use')
  1514. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1515. help='file(s) to read and create object(s) from')
  1516. debug_delete_obj_epilog = textwrap.dedent("""
  1517. This command deletes objects from the repository.
  1518. """)
  1519. subparser = subparsers.add_parser('debug-delete-obj', parents=[common_parser],
  1520. description=self.do_debug_delete_obj.__doc__,
  1521. epilog=debug_delete_obj_epilog,
  1522. formatter_class=argparse.RawDescriptionHelpFormatter,
  1523. help='delete object from repository (debug)')
  1524. subparser.set_defaults(func=self.do_debug_delete_obj)
  1525. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1526. type=location_validator(archive=False),
  1527. help='repository to use')
  1528. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  1529. help='hex object ID(s) to delete from the repo')
  1530. return parser
  1531. def get_args(self, argv, cmd):
  1532. """usually, just returns argv, except if we deal with a ssh forced command for borg serve."""
  1533. result = self.parse_args(argv[1:])
  1534. if cmd is not None and result.func == self.do_serve:
  1535. forced_result = result
  1536. argv = shlex.split(cmd)
  1537. result = self.parse_args(argv[1:])
  1538. if result.func != forced_result.func:
  1539. # someone is trying to execute a different borg subcommand, don't do that!
  1540. return forced_result
  1541. # the only thing we take from the forced "borg serve" ssh command is --restrict-to-path
  1542. result.restrict_to_paths = forced_result.restrict_to_paths
  1543. return result
  1544. def parse_args(self, args=None):
  1545. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  1546. if args:
  1547. args = self.preprocess_args(args)
  1548. parser = self.build_parser(args)
  1549. args = parser.parse_args(args or ['-h'])
  1550. update_excludes(args)
  1551. return args
  1552. def run(self, args):
  1553. os.umask(args.umask) # early, before opening files
  1554. self.lock_wait = args.lock_wait
  1555. setup_logging(level=args.log_level, is_serve=args.func == self.do_serve) # do not use loggers before this!
  1556. if args.show_version:
  1557. logger.info('borgbackup version %s' % __version__)
  1558. check_extension_modules()
  1559. if is_slow_msgpack():
  1560. logger.warning("Using a pure-python msgpack! This will result in lower performance.")
  1561. return args.func(args)
  1562. def sig_info_handler(signum, stack): # pragma: no cover
  1563. """search the stack for infos about the currently processed file and print them"""
  1564. for frame in inspect.getouterframes(stack):
  1565. func, loc = frame[3], frame[0].f_locals
  1566. if func in ('process_file', '_process', ): # create op
  1567. path = loc['path']
  1568. try:
  1569. pos = loc['fd'].tell()
  1570. total = loc['st'].st_size
  1571. except Exception:
  1572. pos, total = 0, 0
  1573. logger.info("{0} {1}/{2}".format(path, format_file_size(pos), format_file_size(total)))
  1574. break
  1575. if func in ('extract_item', ): # extract op
  1576. path = loc['item'][b'path']
  1577. try:
  1578. pos = loc['fd'].tell()
  1579. except Exception:
  1580. pos = 0
  1581. logger.info("{0} {1}/???".format(path, format_file_size(pos)))
  1582. break
  1583. def setup_signal_handlers(): # pragma: no cover
  1584. sigs = []
  1585. if hasattr(signal, 'SIGUSR1'):
  1586. sigs.append(signal.SIGUSR1) # kill -USR1 pid
  1587. if hasattr(signal, 'SIGINFO'):
  1588. sigs.append(signal.SIGINFO) # kill -INFO pid (or ctrl-t)
  1589. for sig in sigs:
  1590. signal.signal(sig, sig_info_handler)
  1591. def main(): # pragma: no cover
  1592. # provide 'borg mount' behaviour when the main script/executable is named borgfs
  1593. if os.path.basename(sys.argv[0]) == "borgfs":
  1594. sys.argv.insert(1, "mount")
  1595. # Make sure stdout and stderr have errors='replace') to avoid unicode
  1596. # issues when print()-ing unicode file names
  1597. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  1598. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  1599. setup_signal_handlers()
  1600. archiver = Archiver()
  1601. msg = None
  1602. args = archiver.get_args(sys.argv, os.environ.get('SSH_ORIGINAL_COMMAND'))
  1603. try:
  1604. exit_code = archiver.run(args)
  1605. except Error as e:
  1606. msg = e.get_message()
  1607. if e.traceback:
  1608. msg += "\n%s\n%s" % (traceback.format_exc(), sysinfo())
  1609. exit_code = e.exit_code
  1610. except RemoteRepository.RPCError as e:
  1611. msg = '%s\n%s' % (str(e), sysinfo())
  1612. exit_code = EXIT_ERROR
  1613. except Exception:
  1614. msg = 'Local Exception.\n%s\n%s' % (traceback.format_exc(), sysinfo())
  1615. exit_code = EXIT_ERROR
  1616. except KeyboardInterrupt:
  1617. msg = 'Keyboard interrupt.\n%s\n%s' % (traceback.format_exc(), sysinfo())
  1618. exit_code = EXIT_ERROR
  1619. if msg:
  1620. logger.error(msg)
  1621. if args.show_rc:
  1622. exit_msg = 'terminating with %s status, rc %d'
  1623. if exit_code == EXIT_SUCCESS:
  1624. logger.info(exit_msg % ('success', exit_code))
  1625. elif exit_code == EXIT_WARNING:
  1626. logger.warning(exit_msg % ('warning', exit_code))
  1627. elif exit_code == EXIT_ERROR:
  1628. logger.error(exit_msg % ('error', exit_code))
  1629. else:
  1630. # if you see 666 in output, it usually means exit_code was None
  1631. logger.error(exit_msg % ('abnormal', exit_code or 666))
  1632. sys.exit(exit_code)
  1633. if __name__ == '__main__':
  1634. main()