archiver.py 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. from binascii import unhexlify
  2. from datetime import datetime
  3. from hashlib import sha256
  4. from operator import attrgetter
  5. import argparse
  6. import faulthandler
  7. import functools
  8. import inspect
  9. import os
  10. import re
  11. import shlex
  12. import signal
  13. import stat
  14. import sys
  15. import textwrap
  16. import time
  17. import traceback
  18. import collections
  19. from . import __version__
  20. from .helpers import Error, location_validator, archivename_validator, format_line, format_time, format_file_size, \
  21. parse_pattern, PathPrefixPattern, to_localtime, timestamp, safe_timestamp, bin_to_hex, \
  22. get_cache_dir, prune_within, prune_split, \
  23. Manifest, NoManifestError, remove_surrogates, update_excludes, format_archive, check_extension_modules, Statistics, \
  24. dir_is_tagged, bigint_to_int, ChunkerParams, CompressionSpec, PrefixSpec, is_slow_msgpack, yes, sysinfo, \
  25. EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR, log_multi, PatternMatcher, ErrorIgnoringTextIOWrapper
  26. from .helpers import signal_handler, raising_signal_handler, SigHup, SigTerm
  27. from .logger import create_logger, setup_logging
  28. logger = create_logger()
  29. from .compress import Compressor
  30. from .upgrader import AtticRepositoryUpgrader, BorgRepositoryUpgrader
  31. from .repository import Repository
  32. from .cache import Cache
  33. from .key import key_creator, tam_required_file, tam_required, RepoKey, PassphraseKey
  34. from .keymanager import KeyManager
  35. from .archive import backup_io, BackupOSError, Archive, ArchiveChecker, CHUNKER_PARAMS, is_special
  36. from .remote import RepositoryServer, RemoteRepository, cache_if_remote
  37. from .platform import umount
  38. has_lchflags = hasattr(os, 'lchflags')
  39. # default umask, overriden by --umask, defaults to read/write only for owner
  40. UMASK_DEFAULT = 0o077
  41. DASHES = '-' * 78
  42. def argument(args, str_or_bool):
  43. """If bool is passed, return it. If str is passed, retrieve named attribute from args."""
  44. if isinstance(str_or_bool, str):
  45. return getattr(args, str_or_bool)
  46. if isinstance(str_or_bool, (list, tuple)):
  47. return any(getattr(args, item) for item in str_or_bool)
  48. return str_or_bool
  49. def with_repository(fake=False, invert_fake=False, create=False, lock=True, exclusive=False, manifest=True, cache=False):
  50. """
  51. Method decorator for subcommand-handling methods: do_XYZ(self, args, repository, …)
  52. If a parameter (where allowed) is a str the attribute named of args is used instead.
  53. :param fake: (str or bool) use None instead of repository, don't do anything else
  54. :param create: create repository
  55. :param lock: lock repository
  56. :param exclusive: (str or bool) lock repository exclusively (for writing)
  57. :param manifest: load manifest and key, pass them as keyword arguments
  58. :param cache: open cache, pass it as keyword argument (implies manifest)
  59. """
  60. def decorator(method):
  61. @functools.wraps(method)
  62. def wrapper(self, args, **kwargs):
  63. location = args.location # note: 'location' must be always present in args
  64. append_only = getattr(args, 'append_only', False)
  65. if argument(args, fake) ^ invert_fake:
  66. return method(self, args, repository=None, **kwargs)
  67. elif location.proto == 'ssh':
  68. repository = RemoteRepository(location, create=create, exclusive=argument(args, exclusive),
  69. lock_wait=self.lock_wait, lock=lock, append_only=append_only, args=args)
  70. else:
  71. repository = Repository(location.path, create=create, exclusive=argument(args, exclusive),
  72. lock_wait=self.lock_wait, lock=lock,
  73. append_only=append_only)
  74. with repository:
  75. if manifest or cache:
  76. kwargs['manifest'], kwargs['key'] = Manifest.load(repository)
  77. if cache:
  78. with Cache(repository, kwargs['key'], kwargs['manifest'],
  79. do_files=getattr(args, 'cache_files', False), lock_wait=self.lock_wait) as cache_:
  80. return method(self, args, repository=repository, cache=cache_, **kwargs)
  81. else:
  82. return method(self, args, repository=repository, **kwargs)
  83. return wrapper
  84. return decorator
  85. def with_archive(method):
  86. @functools.wraps(method)
  87. def wrapper(self, args, repository, key, manifest, **kwargs):
  88. archive = Archive(repository, key, manifest, args.location.archive,
  89. numeric_owner=getattr(args, 'numeric_owner', False), cache=kwargs.get('cache'))
  90. return method(self, args, repository=repository, manifest=manifest, key=key, archive=archive, **kwargs)
  91. return wrapper
  92. class Archiver:
  93. def __init__(self, lock_wait=None):
  94. self.exit_code = EXIT_SUCCESS
  95. self.lock_wait = lock_wait
  96. def print_error(self, msg, *args):
  97. msg = args and msg % args or msg
  98. self.exit_code = EXIT_ERROR
  99. logger.error(msg)
  100. def print_warning(self, msg, *args):
  101. msg = args and msg % args or msg
  102. self.exit_code = EXIT_WARNING # we do not terminate here, so it is a warning
  103. logger.warning(msg)
  104. def print_file_status(self, status, path):
  105. if self.output_list and (self.output_filter is None or status in self.output_filter):
  106. logger.info("%1s %s", status, remove_surrogates(path))
  107. def do_serve(self, args):
  108. """Start in server mode. This command is usually not used manually.
  109. """
  110. return RepositoryServer(restrict_to_paths=args.restrict_to_paths, append_only=args.append_only).serve()
  111. @with_repository(create=True, exclusive=True, manifest=False)
  112. def do_init(self, args, repository):
  113. """Initialize an empty repository"""
  114. path = args.location.canonical_path()
  115. logger.info('Initializing repository at "%s"' % path)
  116. key = key_creator(repository, args)
  117. manifest = Manifest(key, repository)
  118. manifest.key = key
  119. manifest.write()
  120. repository.commit()
  121. with Cache(repository, key, manifest, warn_if_unencrypted=False):
  122. pass
  123. if key.tam_required:
  124. tam_file = tam_required_file(repository)
  125. open(tam_file, 'w').close()
  126. logger.warning(
  127. '\n'
  128. 'By default repositories initialized with this version will produce security\n'
  129. 'errors if written to with an older version (up to and including Borg 1.0.8).\n'
  130. '\n'
  131. 'If you want to use these older versions, you can disable the check by runnning:\n'
  132. 'borg upgrade --disable-tam \'%s\'\n'
  133. '\n'
  134. 'See https://borgbackup.readthedocs.io/en/stable/changes.html#pre-1-0-9-manifest-spoofing-vulnerability '
  135. 'for details about the security implications.', path)
  136. return self.exit_code
  137. @with_repository(exclusive=True, manifest=False)
  138. def do_check(self, args, repository):
  139. """Check repository consistency"""
  140. if args.repair:
  141. msg = ("'check --repair' is an experimental feature that might result in data loss." +
  142. "\n" +
  143. "Type 'YES' if you understand this and want to continue: ")
  144. if not yes(msg, false_msg="Aborting.", invalid_msg="Invalid answer, aborting.",
  145. truish=('YES', ), retry=False,
  146. env_var_override='BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  147. return EXIT_ERROR
  148. if not args.archives_only:
  149. if not repository.check(repair=args.repair, save_space=args.save_space):
  150. return EXIT_WARNING
  151. if not args.repo_only and not ArchiveChecker().check(
  152. repository, repair=args.repair, archive=args.location.archive,
  153. last=args.last, prefix=args.prefix, save_space=args.save_space):
  154. return EXIT_WARNING
  155. return EXIT_SUCCESS
  156. @with_repository()
  157. def do_change_passphrase(self, args, repository, manifest, key):
  158. """Change repository key file passphrase"""
  159. if not hasattr(key, 'change_passphrase'):
  160. print('This repository is not encrypted, cannot change the passphrase.')
  161. return EXIT_ERROR
  162. key.change_passphrase()
  163. logger.info('Key updated')
  164. if hasattr(key, 'find_key'):
  165. # print key location to make backing it up easier
  166. logger.info('Key location: %s', key.find_key())
  167. return EXIT_SUCCESS
  168. @with_repository(lock=False, exclusive=False, manifest=False, cache=False)
  169. def do_key_export(self, args, repository):
  170. """Export the repository key for backup"""
  171. manager = KeyManager(repository)
  172. manager.load_keyblob()
  173. if args.paper:
  174. manager.export_paperkey(args.path)
  175. else:
  176. if not args.path:
  177. self.print_error("output file to export key to expected")
  178. return EXIT_ERROR
  179. manager.export(args.path)
  180. return EXIT_SUCCESS
  181. @with_repository(lock=False, exclusive=False, manifest=False, cache=False)
  182. def do_key_import(self, args, repository):
  183. """Import the repository key from backup"""
  184. manager = KeyManager(repository)
  185. if args.paper:
  186. if args.path:
  187. self.print_error("with --paper import from file is not supported")
  188. return EXIT_ERROR
  189. manager.import_paperkey(args)
  190. else:
  191. if not args.path:
  192. self.print_error("input file to import key from expected")
  193. return EXIT_ERROR
  194. if not os.path.exists(args.path):
  195. self.print_error("input file does not exist: " + args.path)
  196. return EXIT_ERROR
  197. manager.import_keyfile(args)
  198. return EXIT_SUCCESS
  199. @with_repository(manifest=False)
  200. def do_migrate_to_repokey(self, args, repository):
  201. """Migrate passphrase -> repokey"""
  202. manifest_data = repository.get(Manifest.MANIFEST_ID)
  203. key_old = PassphraseKey.detect(repository, manifest_data)
  204. key_new = RepoKey(repository)
  205. key_new.target = repository
  206. key_new.repository_id = repository.id
  207. key_new.enc_key = key_old.enc_key
  208. key_new.enc_hmac_key = key_old.enc_hmac_key
  209. key_new.id_key = key_old.id_key
  210. key_new.chunk_seed = key_old.chunk_seed
  211. key_new.change_passphrase() # option to change key protection passphrase, save
  212. logger.info('Key updated')
  213. return EXIT_SUCCESS
  214. @with_repository(fake='dry_run', exclusive=True)
  215. def do_create(self, args, repository, manifest=None, key=None):
  216. """Create new archive"""
  217. matcher = PatternMatcher(fallback=True)
  218. if args.excludes:
  219. matcher.add(args.excludes, False)
  220. def create_inner(archive, cache):
  221. # Add cache dir to inode_skip list
  222. skip_inodes = set()
  223. try:
  224. st = os.stat(get_cache_dir())
  225. skip_inodes.add((st.st_ino, st.st_dev))
  226. except OSError:
  227. pass
  228. # Add local repository dir to inode_skip list
  229. if not args.location.host:
  230. try:
  231. st = os.stat(args.location.path)
  232. skip_inodes.add((st.st_ino, st.st_dev))
  233. except OSError:
  234. pass
  235. for path in args.paths:
  236. if path == '-': # stdin
  237. path = 'stdin'
  238. if not dry_run:
  239. try:
  240. status = archive.process_stdin(path, cache)
  241. except BackupOSError as e:
  242. status = 'E'
  243. self.print_warning('%s: %s', path, e)
  244. else:
  245. status = '-'
  246. self.print_file_status(status, path)
  247. continue
  248. path = os.path.normpath(path)
  249. if args.one_file_system:
  250. try:
  251. restrict_dev = os.lstat(path).st_dev
  252. except OSError as e:
  253. self.print_warning('%s: %s', path, e)
  254. continue
  255. else:
  256. restrict_dev = None
  257. self._process(archive, cache, matcher, args.exclude_caches, args.exclude_if_present,
  258. args.keep_tag_files, skip_inodes, path, restrict_dev,
  259. read_special=args.read_special, dry_run=dry_run)
  260. if not dry_run:
  261. archive.save(timestamp=args.timestamp)
  262. if args.progress:
  263. archive.stats.show_progress(final=True)
  264. if args.stats:
  265. log_multi(DASHES,
  266. str(archive),
  267. DASHES,
  268. str(archive.stats),
  269. str(cache),
  270. DASHES)
  271. self.output_filter = args.output_filter
  272. self.output_list = args.output_list
  273. self.ignore_inode = args.ignore_inode
  274. dry_run = args.dry_run
  275. t0 = datetime.utcnow()
  276. t0_monotonic = time.monotonic()
  277. if not dry_run:
  278. key.compressor = Compressor(**args.compression)
  279. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  280. archive = Archive(repository, key, manifest, args.location.archive, cache=cache,
  281. create=True, checkpoint_interval=args.checkpoint_interval,
  282. numeric_owner=args.numeric_owner, noatime=args.noatime, noctime=args.noctime,
  283. progress=args.progress,
  284. chunker_params=args.chunker_params, start=t0, start_monotonic=t0_monotonic)
  285. create_inner(archive, cache)
  286. else:
  287. create_inner(None, None)
  288. return self.exit_code
  289. def _process(self, archive, cache, matcher, exclude_caches, exclude_if_present,
  290. keep_tag_files, skip_inodes, path, restrict_dev,
  291. read_special=False, dry_run=False):
  292. if not matcher.match(path):
  293. return
  294. try:
  295. st = os.lstat(path)
  296. except OSError as e:
  297. self.print_warning('%s: %s', path, e)
  298. return
  299. if (st.st_ino, st.st_dev) in skip_inodes:
  300. return
  301. # Entering a new filesystem?
  302. if restrict_dev is not None and st.st_dev != restrict_dev:
  303. return
  304. status = None
  305. # Ignore if nodump flag is set
  306. if has_lchflags and (st.st_flags & stat.UF_NODUMP):
  307. return
  308. if stat.S_ISREG(st.st_mode):
  309. if not dry_run:
  310. try:
  311. status = archive.process_file(path, st, cache, self.ignore_inode)
  312. except BackupOSError as e:
  313. status = 'E'
  314. self.print_warning('%s: %s', path, e)
  315. elif stat.S_ISDIR(st.st_mode):
  316. tag_paths = dir_is_tagged(path, exclude_caches, exclude_if_present)
  317. if tag_paths:
  318. if keep_tag_files and not dry_run:
  319. archive.process_dir(path, st)
  320. for tag_path in tag_paths:
  321. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  322. keep_tag_files, skip_inodes, tag_path, restrict_dev,
  323. read_special=read_special, dry_run=dry_run)
  324. return
  325. if not dry_run:
  326. status = archive.process_dir(path, st)
  327. try:
  328. entries = os.listdir(path)
  329. except OSError as e:
  330. status = 'E'
  331. self.print_warning('%s: %s', path, e)
  332. else:
  333. for filename in sorted(entries):
  334. entry_path = os.path.normpath(os.path.join(path, filename))
  335. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  336. keep_tag_files, skip_inodes, entry_path, restrict_dev,
  337. read_special=read_special, dry_run=dry_run)
  338. elif stat.S_ISLNK(st.st_mode):
  339. if not dry_run:
  340. if not read_special:
  341. status = archive.process_symlink(path, st)
  342. else:
  343. try:
  344. st_target = os.stat(path)
  345. except OSError:
  346. special = False
  347. else:
  348. special = is_special(st_target.st_mode)
  349. if special:
  350. status = archive.process_file(path, st_target, cache)
  351. else:
  352. status = archive.process_symlink(path, st)
  353. elif stat.S_ISFIFO(st.st_mode):
  354. if not dry_run:
  355. if not read_special:
  356. status = archive.process_fifo(path, st)
  357. else:
  358. status = archive.process_file(path, st, cache)
  359. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  360. if not dry_run:
  361. if not read_special:
  362. status = archive.process_dev(path, st)
  363. else:
  364. status = archive.process_file(path, st, cache)
  365. elif stat.S_ISSOCK(st.st_mode):
  366. # Ignore unix sockets
  367. return
  368. elif stat.S_ISDOOR(st.st_mode):
  369. # Ignore Solaris doors
  370. return
  371. elif stat.S_ISPORT(st.st_mode):
  372. # Ignore Solaris event ports
  373. return
  374. else:
  375. self.print_warning('Unknown file type: %s', path)
  376. return
  377. # Status output
  378. if status is None:
  379. if not dry_run:
  380. status = '?' # need to add a status code somewhere
  381. else:
  382. status = '-' # dry run, item was not backed up
  383. self.print_file_status(status, path)
  384. @staticmethod
  385. def build_filter(matcher, strip_components=0):
  386. if strip_components:
  387. def item_filter(item):
  388. return matcher.match(item[b'path']) and os.sep.join(item[b'path'].split(os.sep)[strip_components:])
  389. else:
  390. def item_filter(item):
  391. return matcher.match(item[b'path'])
  392. return item_filter
  393. @with_repository()
  394. @with_archive
  395. def do_extract(self, args, repository, manifest, key, archive):
  396. """Extract archive contents"""
  397. # be restrictive when restoring files, restore permissions later
  398. if sys.getfilesystemencoding() == 'ascii':
  399. logger.warning('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  400. if sys.platform.startswith(('linux', 'freebsd', 'netbsd', 'openbsd', 'darwin', )):
  401. logger.warning('Hint: You likely need to fix your locale setup. E.g. install locales and use: LANG=en_US.UTF-8')
  402. matcher = PatternMatcher()
  403. if args.excludes:
  404. matcher.add(args.excludes, False)
  405. include_patterns = []
  406. if args.paths:
  407. include_patterns.extend(parse_pattern(i, PathPrefixPattern) for i in args.paths)
  408. matcher.add(include_patterns, True)
  409. matcher.fallback = not include_patterns
  410. output_list = args.output_list
  411. dry_run = args.dry_run
  412. stdout = args.stdout
  413. sparse = args.sparse
  414. strip_components = args.strip_components
  415. dirs = []
  416. filter = self.build_filter(matcher, strip_components)
  417. for item in archive.iter_items(filter, preload=True):
  418. orig_path = item[b'path']
  419. if strip_components:
  420. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  421. if not args.dry_run:
  422. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  423. dir_item = dirs.pop(-1)
  424. try:
  425. archive.extract_item(dir_item, stdout=stdout)
  426. except BackupOSError as e:
  427. self.print_warning('%s: %s', remove_surrogates(dir_item[b'path']), e)
  428. if output_list:
  429. logger.info(remove_surrogates(orig_path))
  430. try:
  431. if dry_run:
  432. archive.extract_item(item, dry_run=True)
  433. else:
  434. if stat.S_ISDIR(item[b'mode']):
  435. dirs.append(item)
  436. archive.extract_item(item, restore_attrs=False)
  437. else:
  438. archive.extract_item(item, stdout=stdout, sparse=sparse)
  439. except BackupOSError as e:
  440. self.print_warning('%s: %s', remove_surrogates(orig_path), e)
  441. if not args.dry_run:
  442. while dirs:
  443. dir_item = dirs.pop(-1)
  444. try:
  445. archive.extract_item(dir_item)
  446. except BackupOSError as e:
  447. self.print_warning('%s: %s', remove_surrogates(dir_item[b'path']), e)
  448. for pattern in include_patterns:
  449. if pattern.match_count == 0:
  450. self.print_warning("Include pattern '%s' never matched.", pattern)
  451. return self.exit_code
  452. @with_repository(exclusive=True, cache=True)
  453. @with_archive
  454. def do_rename(self, args, repository, manifest, key, cache, archive):
  455. """Rename an existing archive"""
  456. archive.rename(args.name)
  457. manifest.write()
  458. repository.commit()
  459. cache.commit()
  460. return self.exit_code
  461. @with_repository(exclusive=True, manifest=False)
  462. def do_delete(self, args, repository):
  463. """Delete an existing repository or archive"""
  464. if args.location.archive:
  465. manifest, key = Manifest.load(repository)
  466. with Cache(repository, key, manifest, lock_wait=self.lock_wait) as cache:
  467. archive = Archive(repository, key, manifest, args.location.archive, cache=cache)
  468. stats = Statistics()
  469. archive.delete(stats, progress=args.progress, forced=args.forced)
  470. manifest.write()
  471. repository.commit(save_space=args.save_space)
  472. cache.commit()
  473. logger.info("Archive deleted.")
  474. if args.stats:
  475. log_multi(DASHES,
  476. stats.summary.format(label='Deleted data:', stats=stats),
  477. str(cache),
  478. DASHES)
  479. else:
  480. if not args.cache_only:
  481. msg = []
  482. try:
  483. manifest, key = Manifest.load(repository)
  484. except NoManifestError:
  485. msg.append("You requested to completely DELETE the repository *including* all archives it may contain.")
  486. msg.append("This repository seems to have no manifest, so we can't tell anything about its contents.")
  487. else:
  488. msg.append("You requested to completely DELETE the repository *including* all archives it contains:")
  489. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  490. msg.append(format_archive(archive_info))
  491. msg.append("Type 'YES' if you understand this and want to continue: ")
  492. msg = '\n'.join(msg)
  493. if not yes(msg, false_msg="Aborting.", invalid_msg='Invalid answer, aborting.', truish=('YES', ),
  494. retry=False, env_var_override='BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'):
  495. self.exit_code = EXIT_ERROR
  496. return self.exit_code
  497. repository.destroy()
  498. logger.info("Repository deleted.")
  499. Cache.destroy(repository)
  500. logger.info("Cache deleted.")
  501. return self.exit_code
  502. @with_repository()
  503. def do_mount(self, args, repository, manifest, key):
  504. """Mount archive or an entire repository as a FUSE filesystem"""
  505. try:
  506. from .fuse import FuseOperations
  507. except ImportError as e:
  508. self.print_error('Loading fuse support failed [ImportError: %s]' % str(e))
  509. return self.exit_code
  510. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  511. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  512. return self.exit_code
  513. with cache_if_remote(repository) as cached_repo:
  514. if args.location.archive:
  515. archive = Archive(repository, key, manifest, args.location.archive)
  516. else:
  517. archive = None
  518. operations = FuseOperations(key, repository, manifest, archive, cached_repo)
  519. logger.info("Mounting filesystem")
  520. try:
  521. operations.mount(args.mountpoint, args.options, args.foreground)
  522. except RuntimeError:
  523. # Relevant error message already printed to stderr by fuse
  524. self.exit_code = EXIT_ERROR
  525. return self.exit_code
  526. def do_umount(self, args):
  527. """un-mount the FUSE filesystem"""
  528. return umount(args.mountpoint)
  529. @with_repository()
  530. def do_list(self, args, repository, manifest, key):
  531. """List archive or repository contents"""
  532. if args.location.archive:
  533. archive = Archive(repository, key, manifest, args.location.archive)
  534. """use_user_format flag is used to speed up default listing.
  535. When user issues format options, listing is a bit slower, but more keys are available and
  536. precalculated.
  537. """
  538. use_user_format = args.listformat is not None
  539. if use_user_format:
  540. list_format = args.listformat
  541. elif args.short:
  542. list_format = "{path}{LF}"
  543. else:
  544. list_format = "{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{LF}"
  545. for item in archive.iter_items():
  546. mode = stat.filemode(item[b'mode'])
  547. type = mode[0]
  548. size = 0
  549. if type == '-':
  550. try:
  551. size = sum(size for _, size, _ in item[b'chunks'])
  552. except KeyError:
  553. pass
  554. mtime = safe_timestamp(item[b'mtime'])
  555. if use_user_format:
  556. atime = safe_timestamp(item.get(b'atime') or item[b'mtime'])
  557. ctime = safe_timestamp(item.get(b'ctime') or item[b'mtime'])
  558. if b'source' in item:
  559. source = item[b'source']
  560. if type == 'l':
  561. extra = ' -> %s' % item[b'source']
  562. else:
  563. mode = 'h' + mode[1:]
  564. extra = ' link to %s' % item[b'source']
  565. else:
  566. extra = ''
  567. source = ''
  568. item_data = {
  569. 'mode': mode,
  570. 'user': item[b'user'] or item[b'uid'],
  571. 'group': item[b'group'] or item[b'gid'],
  572. 'size': size,
  573. 'isomtime': format_time(mtime),
  574. 'path': remove_surrogates(item[b'path']),
  575. 'extra': extra,
  576. 'LF': '\n',
  577. }
  578. if use_user_format:
  579. item_data_advanced = {
  580. 'bmode': item[b'mode'],
  581. 'type': type,
  582. 'source': source,
  583. 'linktarget': source,
  584. 'uid': item[b'uid'],
  585. 'gid': item[b'gid'],
  586. 'mtime': mtime,
  587. 'isoctime': format_time(ctime),
  588. 'ctime': ctime,
  589. 'isoatime': format_time(atime),
  590. 'atime': atime,
  591. 'archivename': archive.name,
  592. 'SPACE': ' ',
  593. 'TAB': '\t',
  594. 'CR': '\r',
  595. 'NEWLINE': os.linesep,
  596. }
  597. item_data.update(item_data_advanced)
  598. item_data['formatkeys'] = list(item_data.keys())
  599. print(format_line(list_format, item_data), end='')
  600. else:
  601. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  602. if args.prefix and not archive_info.name.startswith(args.prefix):
  603. continue
  604. if args.short:
  605. print(archive_info.name)
  606. else:
  607. print(format_archive(archive_info))
  608. return self.exit_code
  609. @with_repository(cache=True)
  610. @with_archive
  611. def do_info(self, args, repository, manifest, key, archive, cache):
  612. """Show archive details such as disk space used"""
  613. stats = archive.calc_stats(cache)
  614. print('Name:', archive.name)
  615. print('Fingerprint: %s' % bin_to_hex(archive.id))
  616. print('Hostname:', archive.metadata[b'hostname'])
  617. print('Username:', archive.metadata[b'username'])
  618. print('Time (start): %s' % format_time(to_localtime(archive.ts)))
  619. print('Time (end): %s' % format_time(to_localtime(archive.ts_end)))
  620. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  621. print('Number of files: %d' % stats.nfiles)
  622. print()
  623. print(str(stats))
  624. print(str(cache))
  625. return self.exit_code
  626. @with_repository(exclusive=True)
  627. def do_prune(self, args, repository, manifest, key):
  628. """Prune repository archives according to specified rules"""
  629. if not any((args.hourly, args.daily,
  630. args.weekly, args.monthly, args.yearly, args.within)):
  631. self.print_error('At least one of the "keep-within", "keep-last", '
  632. '"keep-hourly", "keep-daily", '
  633. '"keep-weekly", "keep-monthly" or "keep-yearly" settings must be specified.')
  634. return self.exit_code
  635. archives = manifest.list_archive_infos(sort_by='ts', reverse=True) # just a ArchiveInfo list
  636. if args.prefix:
  637. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  638. # ignore all checkpoint archives to avoid keeping one (which is an incomplete backup)
  639. # that is newer than a successfully completed backup - and killing the successful backup.
  640. is_checkpoint = re.compile(r'\.checkpoint(\.\d+)?$').search
  641. archives = [archive for archive in archives if not is_checkpoint(archive.name)]
  642. keep = []
  643. if args.within:
  644. keep += prune_within(archives, args.within)
  645. if args.hourly:
  646. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  647. if args.daily:
  648. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  649. if args.weekly:
  650. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  651. if args.monthly:
  652. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  653. if args.yearly:
  654. keep += prune_split(archives, '%Y', args.yearly, keep)
  655. keep.sort(key=attrgetter('ts'), reverse=True)
  656. to_delete = [a for a in archives if a not in keep]
  657. stats = Statistics()
  658. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  659. for archive in keep:
  660. if args.output_list:
  661. logger.info('Keeping archive: %s' % format_archive(archive))
  662. for archive in to_delete:
  663. if args.dry_run:
  664. if args.output_list:
  665. logger.info('Would prune: %s' % format_archive(archive))
  666. else:
  667. if args.output_list:
  668. logger.info('Pruning archive: %s' % format_archive(archive))
  669. Archive(repository, key, manifest, archive.name, cache).delete(stats, forced=args.forced)
  670. if to_delete and not args.dry_run:
  671. manifest.write()
  672. repository.commit(save_space=args.save_space)
  673. cache.commit()
  674. if args.stats:
  675. log_multi(DASHES,
  676. stats.summary.format(label='Deleted data:', stats=stats),
  677. str(cache),
  678. DASHES)
  679. return self.exit_code
  680. @with_repository(fake=('tam', 'disable_tam'), invert_fake=True, manifest=False, exclusive=True)
  681. def do_upgrade(self, args, repository, manifest=None, key=None):
  682. """upgrade a repository from a previous version"""
  683. if args.tam:
  684. manifest, key = Manifest.load(repository, force_tam_not_required=args.force)
  685. if not hasattr(key, 'change_passphrase'):
  686. print('This repository is not encrypted, cannot enable TAM.')
  687. return EXIT_ERROR
  688. if not manifest.tam_verified or not manifest.config.get(b'tam_required', False):
  689. # The standard archive listing doesn't include the archive ID like in borg 1.1.x
  690. print('Manifest contents:')
  691. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  692. print(format_archive(archive_info), '[%s]' % bin_to_hex(archive_info.id))
  693. manifest.config[b'tam_required'] = True
  694. manifest.write()
  695. repository.commit()
  696. if not key.tam_required:
  697. key.tam_required = True
  698. key.change_passphrase(key._passphrase)
  699. print('Key updated')
  700. if hasattr(key, 'find_key'):
  701. print('Key location:', key.find_key())
  702. if not tam_required(repository):
  703. tam_file = tam_required_file(repository)
  704. open(tam_file, 'w').close()
  705. print('Updated security database')
  706. elif args.disable_tam:
  707. manifest, key = Manifest.load(repository, force_tam_not_required=True)
  708. if tam_required(repository):
  709. os.unlink(tam_required_file(repository))
  710. if key.tam_required:
  711. key.tam_required = False
  712. key.change_passphrase(key._passphrase)
  713. print('Key updated')
  714. if hasattr(key, 'find_key'):
  715. print('Key location:', key.find_key())
  716. manifest.config[b'tam_required'] = False
  717. manifest.write()
  718. repository.commit()
  719. else:
  720. # mainly for upgrades from Attic repositories,
  721. # but also supports borg 0.xx -> 1.0 upgrade.
  722. repo = AtticRepositoryUpgrader(args.location.path, create=False)
  723. try:
  724. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  725. except NotImplementedError as e:
  726. print("warning: %s" % e)
  727. repo = BorgRepositoryUpgrader(args.location.path, create=False)
  728. try:
  729. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  730. except NotImplementedError as e:
  731. print("warning: %s" % e)
  732. return self.exit_code
  733. def do_debug_info(self, args):
  734. """display system information for debugging / bug reports"""
  735. print(sysinfo())
  736. return EXIT_SUCCESS
  737. @with_repository()
  738. def do_debug_dump_archive_items(self, args, repository, manifest, key):
  739. """dump (decrypted, decompressed) archive items metadata (not: data)"""
  740. archive = Archive(repository, key, manifest, args.location.archive)
  741. for i, item_id in enumerate(archive.metadata[b'items']):
  742. data = key.decrypt(item_id, repository.get(item_id))
  743. filename = '%06d_%s.items' % (i, bin_to_hex(item_id))
  744. print('Dumping', filename)
  745. with open(filename, 'wb') as fd:
  746. fd.write(data)
  747. print('Done.')
  748. return EXIT_SUCCESS
  749. @with_repository()
  750. def do_debug_dump_repo_objs(self, args, repository, manifest, key):
  751. """dump (decrypted, decompressed) repo objects"""
  752. marker = None
  753. i = 0
  754. while True:
  755. result = repository.list(limit=10000, marker=marker)
  756. if not result:
  757. break
  758. marker = result[-1]
  759. for id in result:
  760. cdata = repository.get(id)
  761. give_id = id if id != Manifest.MANIFEST_ID else None
  762. data = key.decrypt(give_id, cdata)
  763. filename = '%06d_%s.obj' % (i, bin_to_hex(id))
  764. print('Dumping', filename)
  765. with open(filename, 'wb') as fd:
  766. fd.write(data)
  767. i += 1
  768. print('Done.')
  769. return EXIT_SUCCESS
  770. @with_repository(manifest=False)
  771. def do_debug_get_obj(self, args, repository):
  772. """get object contents from the repository and write it into file"""
  773. hex_id = args.id
  774. try:
  775. id = unhexlify(hex_id)
  776. except ValueError:
  777. print("object id %s is invalid." % hex_id)
  778. else:
  779. try:
  780. data = repository.get(id)
  781. except Repository.ObjectNotFound:
  782. print("object %s not found." % hex_id)
  783. else:
  784. with open(args.path, "wb") as f:
  785. f.write(data)
  786. print("object %s fetched." % hex_id)
  787. return EXIT_SUCCESS
  788. @with_repository(manifest=False, exclusive=True)
  789. def do_debug_put_obj(self, args, repository):
  790. """put file(s) contents into the repository"""
  791. for path in args.paths:
  792. with open(path, "rb") as f:
  793. data = f.read()
  794. h = sha256(data) # XXX hardcoded
  795. repository.put(h.digest(), data)
  796. print("object %s put." % h.hexdigest())
  797. repository.commit()
  798. return EXIT_SUCCESS
  799. @with_repository(manifest=False, exclusive=True)
  800. def do_debug_delete_obj(self, args, repository):
  801. """delete the objects with the given IDs from the repo"""
  802. modified = False
  803. for hex_id in args.ids:
  804. try:
  805. id = unhexlify(hex_id)
  806. except ValueError:
  807. print("object id %s is invalid." % hex_id)
  808. else:
  809. try:
  810. repository.delete(id)
  811. modified = True
  812. print("object %s deleted." % hex_id)
  813. except Repository.ObjectNotFound:
  814. print("object %s not found." % hex_id)
  815. if modified:
  816. repository.commit()
  817. print('Done.')
  818. return EXIT_SUCCESS
  819. @with_repository(manifest=False, exclusive=True, cache=True)
  820. def do_debug_refcount_obj(self, args, repository, manifest, key, cache):
  821. """display refcounts for the objects with the given IDs"""
  822. for hex_id in args.ids:
  823. try:
  824. id = unhexlify(hex_id)
  825. except ValueError:
  826. print("object id %s is invalid." % hex_id)
  827. else:
  828. try:
  829. refcount = cache.chunks[id][0]
  830. print("object %s has %d referrers [info from chunks cache]." % (hex_id, refcount))
  831. except KeyError:
  832. print("object %s not found [info from chunks cache]." % hex_id)
  833. return EXIT_SUCCESS
  834. @with_repository(lock=False, manifest=False)
  835. def do_break_lock(self, args, repository):
  836. """Break the repository lock (e.g. in case it was left by a dead borg."""
  837. repository.break_lock()
  838. Cache.break_lock(repository)
  839. return self.exit_code
  840. helptext = collections.OrderedDict()
  841. helptext['patterns'] = textwrap.dedent('''
  842. Exclusion patterns support four separate styles, fnmatch, shell, regular
  843. expressions and path prefixes. By default, fnmatch is used. If followed
  844. by a colon (':') the first two characters of a pattern are used as a
  845. style selector. Explicit style selection is necessary when a
  846. non-default style is desired or when the desired pattern starts with
  847. two alphanumeric characters followed by a colon (i.e. `aa:something/*`).
  848. `Fnmatch <https://docs.python.org/3/library/fnmatch.html>`_, selector `fm:`
  849. This is the default style. These patterns use a variant of shell
  850. pattern syntax, with '*' matching any number of characters, '?'
  851. matching any single character, '[...]' matching any single
  852. character specified, including ranges, and '[!...]' matching any
  853. character not specified. For the purpose of these patterns, the
  854. path separator ('\\' for Windows and '/' on other systems) is not
  855. treated specially. Wrap meta-characters in brackets for a literal
  856. match (i.e. `[?]` to match the literal character `?`). For a path
  857. to match a pattern, it must completely match from start to end, or
  858. must match from the start to just before a path separator. Except
  859. for the root path, paths will never end in the path separator when
  860. matching is attempted. Thus, if a given pattern ends in a path
  861. separator, a '*' is appended before matching is attempted.
  862. Shell-style patterns, selector `sh:`
  863. Like fnmatch patterns these are similar to shell patterns. The difference
  864. is that the pattern may include `**/` for matching zero or more directory
  865. levels, `*` for matching zero or more arbitrary characters with the
  866. exception of any path separator.
  867. Regular expressions, selector `re:`
  868. Regular expressions similar to those found in Perl are supported. Unlike
  869. shell patterns regular expressions are not required to match the complete
  870. path and any substring match is sufficient. It is strongly recommended to
  871. anchor patterns to the start ('^'), to the end ('$') or both. Path
  872. separators ('\\' for Windows and '/' on other systems) in paths are
  873. always normalized to a forward slash ('/') before applying a pattern. The
  874. regular expression syntax is described in the `Python documentation for
  875. the re module <https://docs.python.org/3/library/re.html>`_.
  876. Prefix path, selector `pp:`
  877. This pattern style is useful to match whole sub-directories. The pattern
  878. `pp:/data/bar` matches `/data/bar` and everything therein.
  879. Exclusions can be passed via the command line option `--exclude`. When used
  880. from within a shell the patterns should be quoted to protect them from
  881. expansion.
  882. The `--exclude-from` option permits loading exclusion patterns from a text
  883. file with one pattern per line. Lines empty or starting with the number sign
  884. ('#') after removing whitespace on both ends are ignored. The optional style
  885. selector prefix is also supported for patterns loaded from a file. Due to
  886. whitespace removal paths with whitespace at the beginning or end can only be
  887. excluded using regular expressions.
  888. Examples::
  889. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  890. $ borg create -e '*.o' backup /
  891. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  892. # not '/home/user/importantjunk' or '/etc/junk':
  893. $ borg create -e '/home/*/junk' backup /
  894. # Exclude the contents of '/home/user/cache' but not the directory itself:
  895. $ borg create -e /home/user/cache/ backup /
  896. # The file '/home/user/cache/important' is *not* backed up:
  897. $ borg create -e /home/user/cache/ backup / /home/user/cache/important
  898. # The contents of directories in '/home' are not backed up when their name
  899. # ends in '.tmp'
  900. $ borg create --exclude 're:^/home/[^/]+\.tmp/' backup /
  901. # Load exclusions from file
  902. $ cat >exclude.txt <<EOF
  903. # Comment line
  904. /home/*/junk
  905. *.tmp
  906. fm:aa:something/*
  907. re:^/home/[^/]\.tmp/
  908. sh:/home/*/.thumbnails
  909. EOF
  910. $ borg create --exclude-from exclude.txt backup /\n\n''')
  911. helptext['placeholders'] = textwrap.dedent('''
  912. Repository (or Archive) URLs, --prefix and --remote-path values support these
  913. placeholders:
  914. {hostname}
  915. The (short) hostname of the machine.
  916. {fqdn}
  917. The full name of the machine.
  918. {now}
  919. The current local date and time.
  920. {utcnow}
  921. The current UTC date and time.
  922. {user}
  923. The user name (or UID, if no name is available) of the user running borg.
  924. {pid}
  925. The current process ID.
  926. {borgversion}
  927. The version of borg, e.g.: 1.0.8rc1
  928. {borgmajor}
  929. The version of borg, only the major version, e.g.: 1
  930. {borgminor}
  931. The version of borg, only major and minor version, e.g.: 1.0
  932. {borgpatch}
  933. The version of borg, only major, minor and patch version, e.g.: 1.0.8
  934. Examples::
  935. borg create /path/to/repo::{hostname}-{user}-{utcnow} ...
  936. borg create /path/to/repo::{hostname}-{now:%Y-%m-%d_%H:%M:%S} ...
  937. borg prune --prefix '{hostname}-' ...\n\n''')
  938. def do_help(self, parser, commands, args):
  939. if not args.topic:
  940. parser.print_help()
  941. elif args.topic in self.helptext:
  942. print(self.helptext[args.topic])
  943. elif args.topic in commands:
  944. if args.epilog_only:
  945. print(commands[args.topic].epilog)
  946. elif args.usage_only:
  947. commands[args.topic].epilog = None
  948. commands[args.topic].print_help()
  949. else:
  950. commands[args.topic].print_help()
  951. else:
  952. parser.error('No help available on %s' % (args.topic,))
  953. return self.exit_code
  954. def do_subcommand_help(self, parser, args):
  955. """display infos about subcommand"""
  956. parser.print_help()
  957. return EXIT_SUCCESS
  958. def preprocess_args(self, args):
  959. deprecations = [
  960. # ('--old', '--new', 'Warning: "--old" has been deprecated. Use "--new" instead.'),
  961. ]
  962. for i, arg in enumerate(args[:]):
  963. for old_name, new_name, warning in deprecations:
  964. if arg.startswith(old_name):
  965. args[i] = arg.replace(old_name, new_name)
  966. print(warning)
  967. return args
  968. def build_parser(self, args=None, prog=None):
  969. common_parser = argparse.ArgumentParser(add_help=False, prog=prog)
  970. common_parser.add_argument('--critical', dest='log_level',
  971. action='store_const', const='critical', default='warning',
  972. help='work on log level CRITICAL')
  973. common_parser.add_argument('--error', dest='log_level',
  974. action='store_const', const='error', default='warning',
  975. help='work on log level ERROR')
  976. common_parser.add_argument('--warning', dest='log_level',
  977. action='store_const', const='warning', default='warning',
  978. help='work on log level WARNING (default)')
  979. common_parser.add_argument('--info', '-v', '--verbose', dest='log_level',
  980. action='store_const', const='info', default='warning',
  981. help='work on log level INFO')
  982. common_parser.add_argument('--debug', dest='log_level',
  983. action='store_const', const='debug', default='warning',
  984. help='work on log level DEBUG')
  985. common_parser.add_argument('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1,
  986. help='wait for the lock, but max. N seconds (default: %(default)d).')
  987. common_parser.add_argument('--show-rc', dest='show_rc', action='store_true', default=False,
  988. help='show/log the return code (rc)')
  989. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false',
  990. help='do not load/update the file metadata cache used to detect unchanged files')
  991. common_parser.add_argument('--umask', dest='umask', type=lambda s: int(s, 8), default=UMASK_DEFAULT, metavar='M',
  992. help='set umask to M (local and remote, default: %(default)04o)')
  993. common_parser.add_argument('--remote-path', dest='remote_path', metavar='PATH',
  994. help='set remote path to executable (default: "borg")')
  995. parser = argparse.ArgumentParser(prog=prog, description='Borg - Deduplicated Backups')
  996. parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__,
  997. help='show version number and exit')
  998. subparsers = parser.add_subparsers(title='required arguments', metavar='<command>')
  999. serve_epilog = textwrap.dedent("""
  1000. This command starts a repository server process. This command is usually not used manually.
  1001. """)
  1002. subparser = subparsers.add_parser('serve', parents=[common_parser],
  1003. description=self.do_serve.__doc__, epilog=serve_epilog,
  1004. formatter_class=argparse.RawDescriptionHelpFormatter,
  1005. help='start repository server process')
  1006. subparser.set_defaults(func=self.do_serve)
  1007. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  1008. metavar='PATH', help='restrict repository access to PATH. '
  1009. 'Can be specified multiple times to allow the client access to several directories. '
  1010. 'Access to all sub-directories is granted implicitly; PATH doesn\'t need to directly point to a repository.')
  1011. subparser.add_argument('--append-only', dest='append_only', action='store_true',
  1012. help='only allow appending to repository segment files')
  1013. init_epilog = textwrap.dedent("""
  1014. This command initializes an empty repository. A repository is a filesystem
  1015. directory containing the deduplicated data from zero or more archives.
  1016. Encryption can be enabled at repository init time.
  1017. """)
  1018. subparser = subparsers.add_parser('init', parents=[common_parser],
  1019. description=self.do_init.__doc__, epilog=init_epilog,
  1020. formatter_class=argparse.RawDescriptionHelpFormatter,
  1021. help='initialize empty repository')
  1022. subparser.set_defaults(func=self.do_init)
  1023. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1024. type=location_validator(archive=False),
  1025. help='repository to create')
  1026. subparser.add_argument('-e', '--encryption', dest='encryption',
  1027. choices=('none', 'keyfile', 'repokey'), default='repokey',
  1028. help='select encryption key mode (default: "%(default)s")')
  1029. subparser.add_argument('-a', '--append-only', dest='append_only', action='store_true',
  1030. help='create an append-only mode repository')
  1031. check_epilog = textwrap.dedent("""
  1032. The check command verifies the consistency of a repository and the corresponding archives.
  1033. First, the underlying repository data files are checked:
  1034. - For all segments the segment magic (header) is checked
  1035. - For all objects stored in the segments, all metadata (e.g. crc and size) and
  1036. all data is read. The read data is checked by size and CRC. Bit rot and other
  1037. types of accidental damage can be detected this way.
  1038. - If we are in repair mode and a integrity error is detected for a segment,
  1039. we try to recover as many objects from the segment as possible.
  1040. - In repair mode, it makes sure that the index is consistent with the data
  1041. stored in the segments.
  1042. - If you use a remote repo server via ssh:, the repo check is executed on the
  1043. repo server without causing significant network traffic.
  1044. - The repository check can be skipped using the --archives-only option.
  1045. Second, the consistency and correctness of the archive metadata is verified:
  1046. - Is the repo manifest present? If not, it is rebuilt from archive metadata
  1047. chunks (this requires reading and decrypting of all metadata and data).
  1048. - Check if archive metadata chunk is present. if not, remove archive from
  1049. manifest.
  1050. - For all files (items) in the archive, for all chunks referenced by these
  1051. files, check if chunk is present.
  1052. If a chunk is not present and we are in repair mode, replace it with a same-size
  1053. replacement chunk of zeros.
  1054. If a previously lost chunk reappears (e.g. via a later backup) and we are in
  1055. repair mode, the all-zero replacement chunk will be replaced by the correct chunk.
  1056. This requires reading of archive and file metadata, but not data.
  1057. - If we are in repair mode and we checked all the archives: delete orphaned
  1058. chunks from the repo.
  1059. - if you use a remote repo server via ssh:, the archive check is executed on
  1060. the client machine (because if encryption is enabled, the checks will require
  1061. decryption and this is always done client-side, because key access will be
  1062. required).
  1063. - The archive checks can be time consuming, they can be skipped using the
  1064. --repository-only option.
  1065. """)
  1066. subparser = subparsers.add_parser('check', parents=[common_parser],
  1067. description=self.do_check.__doc__,
  1068. epilog=check_epilog,
  1069. formatter_class=argparse.RawDescriptionHelpFormatter,
  1070. help='verify repository')
  1071. subparser.set_defaults(func=self.do_check)
  1072. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  1073. type=location_validator(),
  1074. help='repository or archive to check consistency of')
  1075. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  1076. default=False,
  1077. help='only perform repository checks')
  1078. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  1079. default=False,
  1080. help='only perform archives checks')
  1081. subparser.add_argument('--repair', dest='repair', action='store_true',
  1082. default=False,
  1083. help='attempt to repair any inconsistencies found')
  1084. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1085. default=False,
  1086. help='work slower, but using less space')
  1087. subparser.add_argument('--last', dest='last',
  1088. type=int, default=None, metavar='N',
  1089. help='only check last N archives (Default: all)')
  1090. subparser.add_argument('-P', '--prefix', dest='prefix', type=PrefixSpec,
  1091. help='only consider archive names starting with this prefix')
  1092. change_passphrase_epilog = textwrap.dedent("""
  1093. The key files used for repository encryption are optionally passphrase
  1094. protected. This command can be used to change this passphrase.
  1095. """)
  1096. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  1097. description=self.do_change_passphrase.__doc__,
  1098. epilog=change_passphrase_epilog,
  1099. formatter_class=argparse.RawDescriptionHelpFormatter,
  1100. help='change repository passphrase')
  1101. subparser.set_defaults(func=self.do_change_passphrase)
  1102. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1103. type=location_validator(archive=False))
  1104. subparser = subparsers.add_parser('key', parents=[common_parser],
  1105. description="Manage a keyfile or repokey of a repository",
  1106. epilog="",
  1107. formatter_class=argparse.RawDescriptionHelpFormatter,
  1108. help='manage repository key')
  1109. key_parsers = subparser.add_subparsers(title='required arguments', metavar='<command>')
  1110. subparser.set_defaults(fallback_func=functools.partial(self.do_subcommand_help, subparser))
  1111. key_export_epilog = textwrap.dedent("""
  1112. If repository encryption is used, the repository is inaccessible
  1113. without the key. This command allows to backup this essential key.
  1114. There are two backup formats. The normal backup format is suitable for
  1115. digital storage as a file. The ``--paper`` backup format is optimized
  1116. for printing and typing in while importing, with per line checks to
  1117. reduce problems with manual input.
  1118. For repositories using keyfile encryption the key is saved locally
  1119. on the system that is capable of doing backups. To guard against loss
  1120. of this key, the key needs to be backed up independently of the main
  1121. data backup.
  1122. For repositories using the repokey encryption the key is saved in the
  1123. repository in the config file. A backup is thus not strictly needed,
  1124. but guards against the repository becoming inaccessible if the file
  1125. is damaged for some reason.
  1126. """)
  1127. subparser = key_parsers.add_parser('export', parents=[common_parser],
  1128. description=self.do_key_export.__doc__,
  1129. epilog=key_export_epilog,
  1130. formatter_class=argparse.RawDescriptionHelpFormatter,
  1131. help='export repository key for backup')
  1132. subparser.set_defaults(func=self.do_key_export)
  1133. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1134. type=location_validator(archive=False))
  1135. subparser.add_argument('path', metavar='PATH', nargs='?', type=str,
  1136. help='where to store the backup')
  1137. subparser.add_argument('--paper', dest='paper', action='store_true',
  1138. default=False,
  1139. help='Create an export suitable for printing and later type-in')
  1140. key_import_epilog = textwrap.dedent("""
  1141. This command allows to restore a key previously backed up with the
  1142. export command.
  1143. If the ``--paper`` option is given, the import will be an interactive
  1144. process in which each line is checked for plausibility before
  1145. proceeding to the next line. For this format PATH must not be given.
  1146. """)
  1147. subparser = key_parsers.add_parser('import', parents=[common_parser],
  1148. description=self.do_key_import.__doc__,
  1149. epilog=key_import_epilog,
  1150. formatter_class=argparse.RawDescriptionHelpFormatter,
  1151. help='import repository key from backup')
  1152. subparser.set_defaults(func=self.do_key_import)
  1153. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1154. type=location_validator(archive=False))
  1155. subparser.add_argument('path', metavar='PATH', nargs='?', type=str,
  1156. help='path to the backup')
  1157. subparser.add_argument('--paper', dest='paper', action='store_true',
  1158. default=False,
  1159. help='interactively import from a backup done with --paper')
  1160. migrate_to_repokey_epilog = textwrap.dedent("""
  1161. This command migrates a repository from passphrase mode (not supported any
  1162. more) to repokey mode.
  1163. You will be first asked for the repository passphrase (to open it in passphrase
  1164. mode). This is the same passphrase as you used to use for this repo before 1.0.
  1165. It will then derive the different secrets from this passphrase.
  1166. Then you will be asked for a new passphrase (twice, for safety). This
  1167. passphrase will be used to protect the repokey (which contains these same
  1168. secrets in encrypted form). You may use the same passphrase as you used to
  1169. use, but you may also use a different one.
  1170. After migrating to repokey mode, you can change the passphrase at any time.
  1171. But please note: the secrets will always stay the same and they could always
  1172. be derived from your (old) passphrase-mode passphrase.
  1173. """)
  1174. subparser = subparsers.add_parser('migrate-to-repokey', parents=[common_parser],
  1175. description=self.do_migrate_to_repokey.__doc__,
  1176. epilog=migrate_to_repokey_epilog,
  1177. formatter_class=argparse.RawDescriptionHelpFormatter,
  1178. help='migrate passphrase-mode repository to repokey')
  1179. subparser.set_defaults(func=self.do_migrate_to_repokey)
  1180. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1181. type=location_validator(archive=False))
  1182. create_epilog = textwrap.dedent("""
  1183. This command creates a backup archive containing all files found while recursively
  1184. traversing all paths specified. When giving '-' as path, borg will read data
  1185. from standard input and create a file 'stdin' in the created archive from that
  1186. data.
  1187. The archive will consume almost no disk space for files or parts of files that
  1188. have already been stored in other archives.
  1189. The archive name needs to be unique. It must not end in '.checkpoint' or
  1190. '.checkpoint.N' (with N being a number), because these names are used for
  1191. checkpoints and treated in special ways.
  1192. In the archive name, you may use the following placeholders:
  1193. {now}, {utcnow}, {fqdn}, {hostname}, {user} and some others.
  1194. To speed up pulling backups over sshfs and similar network file systems which do
  1195. not provide correct inode information the --ignore-inode flag can be used. This
  1196. potentially decreases reliability of change detection, while avoiding always reading
  1197. all files on these file systems.
  1198. See the output of the "borg help patterns" command for more help on exclude patterns.
  1199. See the output of the "borg help placeholders" command for more help on placeholders.
  1200. """)
  1201. subparser = subparsers.add_parser('create', parents=[common_parser],
  1202. description=self.do_create.__doc__,
  1203. epilog=create_epilog,
  1204. formatter_class=argparse.RawDescriptionHelpFormatter,
  1205. help='create backup')
  1206. subparser.set_defaults(func=self.do_create)
  1207. subparser.add_argument('-s', '--stats', dest='stats',
  1208. action='store_true', default=False,
  1209. help='print statistics for the created archive')
  1210. subparser.add_argument('-p', '--progress', dest='progress',
  1211. action='store_true', default=False,
  1212. help="""show progress display while creating the archive, showing Original,
  1213. Compressed and Deduplicated sizes, followed by the Number of files seen
  1214. and the path being processed, default: %(default)s""")
  1215. subparser.add_argument('--list', dest='output_list',
  1216. action='store_true', default=False,
  1217. help='output verbose list of items (files, dirs, ...)')
  1218. subparser.add_argument('--filter', dest='output_filter', metavar='STATUSCHARS',
  1219. help='only display items with the given status characters')
  1220. subparser.add_argument('-e', '--exclude', dest='excludes',
  1221. type=parse_pattern, action='append',
  1222. metavar="PATTERN", help='exclude paths matching PATTERN')
  1223. subparser.add_argument('--exclude-from', dest='exclude_files',
  1224. type=argparse.FileType('r'), action='append',
  1225. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1226. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  1227. action='store_true', default=False,
  1228. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  1229. subparser.add_argument('--exclude-if-present', dest='exclude_if_present',
  1230. metavar='FILENAME', action='append', type=str,
  1231. help='exclude directories that contain the specified file')
  1232. subparser.add_argument('--keep-tag-files', dest='keep_tag_files',
  1233. action='store_true', default=False,
  1234. help='keep tag files of excluded caches/directories')
  1235. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  1236. type=int, default=300, metavar='SECONDS',
  1237. help='write checkpoint every SECONDS seconds (Default: 300)')
  1238. subparser.add_argument('-x', '--one-file-system', dest='one_file_system',
  1239. action='store_true', default=False,
  1240. help='stay in same file system, do not cross mount points')
  1241. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1242. action='store_true', default=False,
  1243. help='only store numeric user and group identifiers')
  1244. subparser.add_argument('--noatime', dest='noatime',
  1245. action='store_true', default=False,
  1246. help='do not store atime into archive')
  1247. subparser.add_argument('--noctime', dest='noctime',
  1248. action='store_true', default=False,
  1249. help='do not store ctime into archive')
  1250. subparser.add_argument('--timestamp', dest='timestamp',
  1251. type=timestamp, default=None,
  1252. metavar='yyyy-mm-ddThh:mm:ss',
  1253. help='manually specify the archive creation date/time (UTC). '
  1254. 'alternatively, give a reference file/directory.')
  1255. subparser.add_argument('--chunker-params', dest='chunker_params',
  1256. type=ChunkerParams, default=CHUNKER_PARAMS,
  1257. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  1258. help='specify the chunker parameters. default: %d,%d,%d,%d' % CHUNKER_PARAMS)
  1259. subparser.add_argument('--ignore-inode', dest='ignore_inode',
  1260. action='store_true', default=False,
  1261. help='ignore inode data in the file metadata cache used to detect unchanged files.')
  1262. subparser.add_argument('-C', '--compression', dest='compression',
  1263. type=CompressionSpec, default=dict(name='none'), metavar='COMPRESSION',
  1264. help='select compression algorithm (and level): '
  1265. 'none == no compression (default), '
  1266. 'lz4 == lz4, '
  1267. 'zlib == zlib (default level 6), '
  1268. 'zlib,0 .. zlib,9 == zlib (with level 0..9), '
  1269. 'lzma == lzma (default level 6), '
  1270. 'lzma,0 .. lzma,9 == lzma (with level 0..9).')
  1271. subparser.add_argument('--read-special', dest='read_special',
  1272. action='store_true', default=False,
  1273. help='open and read block and char device files as well as FIFOs as if they were '
  1274. 'regular files. Also follows symlinks pointing to these kinds of files.')
  1275. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1276. action='store_true', default=False,
  1277. help='do not create a backup archive')
  1278. subparser.add_argument('location', metavar='ARCHIVE',
  1279. type=location_validator(archive=True),
  1280. help='name of archive to create (must be also a valid directory name)')
  1281. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1282. help='paths to archive')
  1283. extract_epilog = textwrap.dedent("""
  1284. This command extracts the contents of an archive. By default the entire
  1285. archive is extracted but a subset of files and directories can be selected
  1286. by passing a list of ``PATHs`` as arguments. The file selection can further
  1287. be restricted by using the ``--exclude`` option.
  1288. See the output of the "borg help patterns" command for more help on exclude patterns.
  1289. """)
  1290. subparser = subparsers.add_parser('extract', parents=[common_parser],
  1291. description=self.do_extract.__doc__,
  1292. epilog=extract_epilog,
  1293. formatter_class=argparse.RawDescriptionHelpFormatter,
  1294. help='extract archive contents')
  1295. subparser.set_defaults(func=self.do_extract)
  1296. subparser.add_argument('--list', dest='output_list',
  1297. action='store_true', default=False,
  1298. help='output verbose list of items (files, dirs, ...)')
  1299. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1300. default=False, action='store_true',
  1301. help='do not actually change any files')
  1302. subparser.add_argument('-e', '--exclude', dest='excludes',
  1303. type=parse_pattern, action='append',
  1304. metavar="PATTERN", help='exclude paths matching PATTERN')
  1305. subparser.add_argument('--exclude-from', dest='exclude_files',
  1306. type=argparse.FileType('r'), action='append',
  1307. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1308. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1309. action='store_true', default=False,
  1310. help='only obey numeric user and group identifiers')
  1311. subparser.add_argument('--strip-components', dest='strip_components',
  1312. type=int, default=0, metavar='NUMBER',
  1313. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  1314. subparser.add_argument('--stdout', dest='stdout',
  1315. action='store_true', default=False,
  1316. help='write all extracted data to stdout')
  1317. subparser.add_argument('--sparse', dest='sparse',
  1318. action='store_true', default=False,
  1319. help='create holes in output sparse file from all-zero chunks')
  1320. subparser.add_argument('location', metavar='ARCHIVE',
  1321. type=location_validator(archive=True),
  1322. help='archive to extract')
  1323. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1324. help='paths to extract; patterns are supported')
  1325. rename_epilog = textwrap.dedent("""
  1326. This command renames an archive in the repository.
  1327. """)
  1328. subparser = subparsers.add_parser('rename', parents=[common_parser],
  1329. description=self.do_rename.__doc__,
  1330. epilog=rename_epilog,
  1331. formatter_class=argparse.RawDescriptionHelpFormatter,
  1332. help='rename archive')
  1333. subparser.set_defaults(func=self.do_rename)
  1334. subparser.add_argument('location', metavar='ARCHIVE',
  1335. type=location_validator(archive=True),
  1336. help='archive to rename')
  1337. subparser.add_argument('name', metavar='NEWNAME',
  1338. type=archivename_validator(),
  1339. help='the new archive name to use')
  1340. delete_epilog = textwrap.dedent("""
  1341. This command deletes an archive from the repository or the complete repository.
  1342. Disk space is reclaimed accordingly. If you delete the complete repository, the
  1343. local cache for it (if any) is also deleted.
  1344. """)
  1345. subparser = subparsers.add_parser('delete', parents=[common_parser],
  1346. description=self.do_delete.__doc__,
  1347. epilog=delete_epilog,
  1348. formatter_class=argparse.RawDescriptionHelpFormatter,
  1349. help='delete archive')
  1350. subparser.set_defaults(func=self.do_delete)
  1351. subparser.add_argument('-p', '--progress', dest='progress',
  1352. action='store_true', default=False,
  1353. help="""show progress display while deleting a single archive""")
  1354. subparser.add_argument('-s', '--stats', dest='stats',
  1355. action='store_true', default=False,
  1356. help='print statistics for the deleted archive')
  1357. subparser.add_argument('-c', '--cache-only', dest='cache_only',
  1358. action='store_true', default=False,
  1359. help='delete only the local cache for the given repository')
  1360. subparser.add_argument('--force', dest='forced',
  1361. action='store_true', default=False,
  1362. help='force deletion of corrupted archives')
  1363. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1364. default=False,
  1365. help='work slower, but using less space')
  1366. subparser.add_argument('location', metavar='TARGET', nargs='?', default='',
  1367. type=location_validator(),
  1368. help='archive or repository to delete')
  1369. list_epilog = textwrap.dedent("""
  1370. This command lists the contents of a repository or an archive.
  1371. """)
  1372. subparser = subparsers.add_parser('list', parents=[common_parser],
  1373. description=self.do_list.__doc__,
  1374. epilog=list_epilog,
  1375. formatter_class=argparse.RawDescriptionHelpFormatter,
  1376. help='list archive or repository contents')
  1377. subparser.set_defaults(func=self.do_list)
  1378. subparser.add_argument('--short', dest='short',
  1379. action='store_true', default=False,
  1380. help='only print file/directory names, nothing else')
  1381. subparser.add_argument('--list-format', dest='listformat', type=str,
  1382. help="""specify format for archive file listing
  1383. (default: "{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NEWLINE}")
  1384. Special "{formatkeys}" exists to list available keys""")
  1385. subparser.add_argument('-P', '--prefix', dest='prefix', type=PrefixSpec,
  1386. help='only consider archive names starting with this prefix')
  1387. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  1388. type=location_validator(),
  1389. help='repository/archive to list contents of')
  1390. mount_epilog = textwrap.dedent("""
  1391. This command mounts an archive as a FUSE filesystem. This can be useful for
  1392. browsing an archive or restoring individual files. Unless the ``--foreground``
  1393. option is given the command will run in the background until the filesystem
  1394. is ``umounted``.
  1395. The BORG_MOUNT_DATA_CACHE_ENTRIES environment variable is meant for advanced users
  1396. to tweak the performance. It sets the number of cached data chunks; additional
  1397. memory usage can be up to ~8 MiB times this number. The default is the number
  1398. of CPU cores.
  1399. For mount options, see the fuse(8) manual page. Additional mount options
  1400. supported by borg:
  1401. - allow_damaged_files: by default damaged files (where missing chunks were
  1402. replaced with runs of zeros by borg check --repair) are not readable and
  1403. return EIO (I/O error). Set this option to read such files.
  1404. """)
  1405. subparser = subparsers.add_parser('mount', parents=[common_parser],
  1406. description=self.do_mount.__doc__,
  1407. epilog=mount_epilog,
  1408. formatter_class=argparse.RawDescriptionHelpFormatter,
  1409. help='mount repository')
  1410. subparser.set_defaults(func=self.do_mount)
  1411. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  1412. help='repository/archive to mount')
  1413. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  1414. help='where to mount filesystem')
  1415. subparser.add_argument('-f', '--foreground', dest='foreground',
  1416. action='store_true', default=False,
  1417. help='stay in foreground, do not daemonize')
  1418. subparser.add_argument('-o', dest='options', type=str,
  1419. help='Extra mount options')
  1420. umount_epilog = textwrap.dedent("""
  1421. This command un-mounts a FUSE filesystem that was mounted with ``borg mount``.
  1422. This is a convenience wrapper that just calls the platform-specific shell
  1423. command - usually this is either umount or fusermount -u.
  1424. """)
  1425. subparser = subparsers.add_parser('umount', parents=[common_parser],
  1426. description=self.do_umount.__doc__,
  1427. epilog=umount_epilog,
  1428. formatter_class=argparse.RawDescriptionHelpFormatter,
  1429. help='umount repository')
  1430. subparser.set_defaults(func=self.do_umount)
  1431. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  1432. help='mountpoint of the filesystem to umount')
  1433. info_epilog = textwrap.dedent("""
  1434. This command displays some detailed information about the specified archive.
  1435. Please note that the deduplicated sizes of the individual archives do not add
  1436. up to the deduplicated size of the repository ("all archives"), because the two
  1437. are meaning different things:
  1438. This archive / deduplicated size = amount of data stored ONLY for this archive
  1439. = unique chunks of this archive.
  1440. All archives / deduplicated size = amount of data stored in the repo
  1441. = all chunks in the repository.
  1442. """)
  1443. subparser = subparsers.add_parser('info', parents=[common_parser],
  1444. description=self.do_info.__doc__,
  1445. epilog=info_epilog,
  1446. formatter_class=argparse.RawDescriptionHelpFormatter,
  1447. help='show archive information')
  1448. subparser.set_defaults(func=self.do_info)
  1449. subparser.add_argument('location', metavar='ARCHIVE',
  1450. type=location_validator(archive=True),
  1451. help='archive to display information about')
  1452. break_lock_epilog = textwrap.dedent("""
  1453. This command breaks the repository and cache locks.
  1454. Please use carefully and only while no borg process (on any machine) is
  1455. trying to access the Cache or the Repository.
  1456. """)
  1457. subparser = subparsers.add_parser('break-lock', parents=[common_parser],
  1458. description=self.do_break_lock.__doc__,
  1459. epilog=break_lock_epilog,
  1460. formatter_class=argparse.RawDescriptionHelpFormatter,
  1461. help='break repository and cache locks')
  1462. subparser.set_defaults(func=self.do_break_lock)
  1463. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1464. type=location_validator(archive=False),
  1465. help='repository for which to break the locks')
  1466. prune_epilog = textwrap.dedent("""
  1467. The prune command prunes a repository by deleting all archives not matching
  1468. any of the specified retention options. This command is normally used by
  1469. automated backup scripts wanting to keep a certain number of historic backups.
  1470. As an example, "-d 7" means to keep the latest backup on each day, up to 7
  1471. most recent days with backups (days without backups do not count).
  1472. The rules are applied from hourly to yearly, and backups selected by previous
  1473. rules do not count towards those of later rules. The time that each backup
  1474. starts is used for pruning purposes. Dates and times are interpreted in
  1475. the local timezone, and weeks go from Monday to Sunday. Specifying a
  1476. negative number of archives to keep means that there is no limit.
  1477. The "--keep-within" option takes an argument of the form "<int><char>",
  1478. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  1479. to keep all archives that were created within the past 48 hours.
  1480. "1m" is taken to mean "31d". The archives kept with this option do not
  1481. count towards the totals specified by any other options.
  1482. If a prefix is set with -P, then only archives that start with the prefix are
  1483. considered for deletion and only those archives count towards the totals
  1484. specified by the rules.
  1485. Otherwise, *all* archives in the repository are candidates for deletion!
  1486. There is no automatic distinction between archives representing different
  1487. contents. These need to be distinguished by specifying matching prefixes.
  1488. """)
  1489. subparser = subparsers.add_parser('prune', parents=[common_parser],
  1490. description=self.do_prune.__doc__,
  1491. epilog=prune_epilog,
  1492. formatter_class=argparse.RawDescriptionHelpFormatter,
  1493. help='prune archives')
  1494. subparser.set_defaults(func=self.do_prune)
  1495. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1496. default=False, action='store_true',
  1497. help='do not change repository')
  1498. subparser.add_argument('--force', dest='forced',
  1499. action='store_true', default=False,
  1500. help='force pruning of corrupted archives')
  1501. subparser.add_argument('-s', '--stats', dest='stats',
  1502. action='store_true', default=False,
  1503. help='print statistics for the deleted archive')
  1504. subparser.add_argument('--list', dest='output_list',
  1505. action='store_true', default=False,
  1506. help='output verbose list of archives it keeps/prunes')
  1507. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  1508. help='keep all archives within this time interval')
  1509. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  1510. help='number of hourly archives to keep')
  1511. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  1512. help='number of daily archives to keep')
  1513. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  1514. help='number of weekly archives to keep')
  1515. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  1516. help='number of monthly archives to keep')
  1517. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  1518. help='number of yearly archives to keep')
  1519. subparser.add_argument('-P', '--prefix', dest='prefix', type=PrefixSpec,
  1520. help='only consider archive names starting with this prefix')
  1521. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1522. default=False,
  1523. help='work slower, but using less space')
  1524. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1525. type=location_validator(archive=False),
  1526. help='repository to prune')
  1527. upgrade_epilog = textwrap.dedent("""
  1528. Upgrade an existing Borg repository.
  1529. Borg 1.x.y upgrades
  1530. +++++++++++++++++++
  1531. Use ``borg upgrade --tam REPO`` to require manifest authentication
  1532. introduced with Borg 1.0.9 to address security issues. This means
  1533. that modifying the repository after doing this with a version prior
  1534. to 1.0.9 will raise a validation error, so only perform this upgrade
  1535. after updating all clients using the repository to 1.0.9 or newer.
  1536. This upgrade should be done on each client for safety reasons.
  1537. If a repository is accidentally modified with a pre-1.0.9 client after
  1538. this upgrade, use ``borg upgrade --tam --force REPO`` to remedy it.
  1539. If you routinely do this you might not want to enable this upgrade
  1540. (which will leave you exposed to the security issue). You can
  1541. reverse the upgrade by issuing ``borg upgrade --disable-tam REPO``.
  1542. See
  1543. https://borgbackup.readthedocs.io/en/stable/changes.html#pre-1-0-9-manifest-spoofing-vulnerability
  1544. for details.
  1545. Attic and Borg 0.xx to Borg 1.x
  1546. +++++++++++++++++++++++++++++++
  1547. This currently supports converting an Attic repository to Borg and also
  1548. helps with converting Borg 0.xx to 1.0.
  1549. Currently, only LOCAL repositories can be upgraded (issue #465).
  1550. It will change the magic strings in the repository's segments
  1551. to match the new Borg magic strings. The keyfiles found in
  1552. $ATTIC_KEYS_DIR or ~/.attic/keys/ will also be converted and
  1553. copied to $BORG_KEYS_DIR or ~/.config/borg/keys.
  1554. The cache files are converted, from $ATTIC_CACHE_DIR or
  1555. ~/.cache/attic to $BORG_CACHE_DIR or ~/.cache/borg, but the
  1556. cache layout between Borg and Attic changed, so it is possible
  1557. the first backup after the conversion takes longer than expected
  1558. due to the cache resync.
  1559. Upgrade should be able to resume if interrupted, although it
  1560. will still iterate over all segments. If you want to start
  1561. from scratch, use `borg delete` over the copied repository to
  1562. make sure the cache files are also removed:
  1563. borg delete borg
  1564. Unless ``--inplace`` is specified, the upgrade process first
  1565. creates a backup copy of the repository, in
  1566. REPOSITORY.upgrade-DATETIME, using hardlinks. This takes
  1567. longer than in place upgrades, but is much safer and gives
  1568. progress information (as opposed to ``cp -al``). Once you are
  1569. satisfied with the conversion, you can safely destroy the
  1570. backup copy.
  1571. WARNING: Running the upgrade in place will make the current
  1572. copy unusable with older version, with no way of going back
  1573. to previous versions. This can PERMANENTLY DAMAGE YOUR
  1574. REPOSITORY! Attic CAN NOT READ BORG REPOSITORIES, as the
  1575. magic strings have changed. You have been warned.""")
  1576. subparser = subparsers.add_parser('upgrade', parents=[common_parser],
  1577. description=self.do_upgrade.__doc__,
  1578. epilog=upgrade_epilog,
  1579. formatter_class=argparse.RawDescriptionHelpFormatter,
  1580. help='upgrade repository format')
  1581. subparser.set_defaults(func=self.do_upgrade)
  1582. subparser.add_argument('-p', '--progress', dest='progress',
  1583. action='store_true', default=False,
  1584. help="""show progress display while upgrading the repository""")
  1585. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1586. default=False, action='store_true',
  1587. help='do not change repository')
  1588. subparser.add_argument('-i', '--inplace', dest='inplace',
  1589. default=False, action='store_true',
  1590. help="""rewrite repository in place, with no chance of going back to older
  1591. versions of the repository.""")
  1592. subparser.add_argument('--force', dest='force', action='store_true',
  1593. help="""Force upgrade""")
  1594. subparser.add_argument('--tam', dest='tam', action='store_true',
  1595. help="""Enable manifest authentication (in key and cache) (Borg 1.0.9 and later)""")
  1596. subparser.add_argument('--disable-tam', dest='disable_tam', action='store_true',
  1597. help="""Disable manifest authentication (in key and cache)""")
  1598. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1599. type=location_validator(archive=False),
  1600. help='path to the repository to be upgraded')
  1601. subparser = subparsers.add_parser('help', parents=[common_parser],
  1602. description='Extra help')
  1603. subparser.add_argument('--epilog-only', dest='epilog_only',
  1604. action='store_true', default=False)
  1605. subparser.add_argument('--usage-only', dest='usage_only',
  1606. action='store_true', default=False)
  1607. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  1608. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  1609. help='additional help on TOPIC')
  1610. debug_epilog = textwrap.dedent("""
  1611. These commands are not intended for normal use and potentially very
  1612. dangerous if used incorrectly.
  1613. They exist to improve debugging capabilities without direct system access, e.g.
  1614. in case you ever run into some severe malfunction. Use them only if you know
  1615. what you are doing or if a trusted developer tells you what to do.""")
  1616. subparser = subparsers.add_parser('debug', parents=[common_parser],
  1617. description='debugging command (not intended for normal use)',
  1618. epilog=debug_epilog,
  1619. formatter_class=argparse.RawDescriptionHelpFormatter,
  1620. help='debugging command (not intended for normal use)')
  1621. debug_parsers = subparser.add_subparsers(title='required arguments', metavar='<command>')
  1622. subparser.set_defaults(fallback_func=functools.partial(self.do_subcommand_help, subparser))
  1623. debug_info_epilog = textwrap.dedent("""
  1624. This command displays some system information that might be useful for bug
  1625. reports and debugging problems. If a traceback happens, this information is
  1626. already appended at the end of the traceback.
  1627. """)
  1628. subparser = subparsers.add_parser('debug-info', parents=[common_parser],
  1629. description=self.do_debug_info.__doc__,
  1630. epilog=debug_info_epilog,
  1631. formatter_class=argparse.RawDescriptionHelpFormatter,
  1632. help='show system infos for debugging / bug reports (debug)')
  1633. subparser.set_defaults(func=self.do_debug_info)
  1634. subparser = debug_parsers.add_parser('info', parents=[common_parser],
  1635. description=self.do_debug_info.__doc__,
  1636. epilog=debug_info_epilog,
  1637. formatter_class=argparse.RawDescriptionHelpFormatter,
  1638. help='show system infos for debugging / bug reports (debug)')
  1639. subparser.set_defaults(func=self.do_debug_info)
  1640. debug_dump_archive_items_epilog = textwrap.dedent("""
  1641. This command dumps raw (but decrypted and decompressed) archive items (only metadata) to files.
  1642. """)
  1643. subparser = subparsers.add_parser('debug-dump-archive-items', parents=[common_parser],
  1644. description=self.do_debug_dump_archive_items.__doc__,
  1645. epilog=debug_dump_archive_items_epilog,
  1646. formatter_class=argparse.RawDescriptionHelpFormatter,
  1647. help='dump archive items (metadata) (debug)')
  1648. subparser.set_defaults(func=self.do_debug_dump_archive_items)
  1649. subparser.add_argument('location', metavar='ARCHIVE',
  1650. type=location_validator(archive=True),
  1651. help='archive to dump')
  1652. subparser = debug_parsers.add_parser('dump-archive-items', parents=[common_parser],
  1653. description=self.do_debug_dump_archive_items.__doc__,
  1654. epilog=debug_dump_archive_items_epilog,
  1655. formatter_class=argparse.RawDescriptionHelpFormatter,
  1656. help='dump archive items (metadata) (debug)')
  1657. subparser.set_defaults(func=self.do_debug_dump_archive_items)
  1658. subparser.add_argument('location', metavar='ARCHIVE',
  1659. type=location_validator(archive=True),
  1660. help='archive to dump')
  1661. debug_dump_repo_objs_epilog = textwrap.dedent("""
  1662. This command dumps raw (but decrypted and decompressed) repo objects to files.
  1663. """)
  1664. subparser = subparsers.add_parser('debug-dump-repo-objs', parents=[common_parser],
  1665. description=self.do_debug_dump_repo_objs.__doc__,
  1666. epilog=debug_dump_repo_objs_epilog,
  1667. formatter_class=argparse.RawDescriptionHelpFormatter,
  1668. help='dump repo objects (debug)')
  1669. subparser.set_defaults(func=self.do_debug_dump_repo_objs)
  1670. subparser.add_argument('location', metavar='REPOSITORY',
  1671. type=location_validator(archive=False),
  1672. help='repo to dump')
  1673. subparser = debug_parsers.add_parser('dump-repo-objs', parents=[common_parser],
  1674. description=self.do_debug_dump_repo_objs.__doc__,
  1675. epilog=debug_dump_repo_objs_epilog,
  1676. formatter_class=argparse.RawDescriptionHelpFormatter,
  1677. help='dump repo objects (debug)')
  1678. subparser.set_defaults(func=self.do_debug_dump_repo_objs)
  1679. subparser.add_argument('location', metavar='REPOSITORY',
  1680. type=location_validator(archive=False),
  1681. help='repo to dump')
  1682. debug_get_obj_epilog = textwrap.dedent("""
  1683. This command gets an object from the repository.
  1684. """)
  1685. subparser = subparsers.add_parser('debug-get-obj', parents=[common_parser],
  1686. description=self.do_debug_get_obj.__doc__,
  1687. epilog=debug_get_obj_epilog,
  1688. formatter_class=argparse.RawDescriptionHelpFormatter,
  1689. help='get object from repository (debug)')
  1690. subparser.set_defaults(func=self.do_debug_get_obj)
  1691. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1692. type=location_validator(archive=False),
  1693. help='repository to use')
  1694. subparser.add_argument('id', metavar='ID', type=str,
  1695. help='hex object ID to get from the repo')
  1696. subparser.add_argument('path', metavar='PATH', type=str,
  1697. help='file to write object data into')
  1698. subparser = debug_parsers.add_parser('get-obj', parents=[common_parser],
  1699. description=self.do_debug_get_obj.__doc__,
  1700. epilog=debug_get_obj_epilog,
  1701. formatter_class=argparse.RawDescriptionHelpFormatter,
  1702. help='get object from repository (debug)')
  1703. subparser.set_defaults(func=self.do_debug_get_obj)
  1704. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1705. type=location_validator(archive=False),
  1706. help='repository to use')
  1707. subparser.add_argument('id', metavar='ID', type=str,
  1708. help='hex object ID to get from the repo')
  1709. subparser.add_argument('path', metavar='PATH', type=str,
  1710. help='file to write object data into')
  1711. debug_put_obj_epilog = textwrap.dedent("""
  1712. This command puts objects into the repository.
  1713. """)
  1714. subparser = subparsers.add_parser('debug-put-obj', parents=[common_parser],
  1715. description=self.do_debug_put_obj.__doc__,
  1716. epilog=debug_put_obj_epilog,
  1717. formatter_class=argparse.RawDescriptionHelpFormatter,
  1718. help='put object to repository (debug)')
  1719. subparser.set_defaults(func=self.do_debug_put_obj)
  1720. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1721. type=location_validator(archive=False),
  1722. help='repository to use')
  1723. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1724. help='file(s) to read and create object(s) from')
  1725. subparser = debug_parsers.add_parser('put-obj', parents=[common_parser],
  1726. description=self.do_debug_put_obj.__doc__,
  1727. epilog=debug_put_obj_epilog,
  1728. formatter_class=argparse.RawDescriptionHelpFormatter,
  1729. help='put object to repository (debug)')
  1730. subparser.set_defaults(func=self.do_debug_put_obj)
  1731. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1732. type=location_validator(archive=False),
  1733. help='repository to use')
  1734. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1735. help='file(s) to read and create object(s) from')
  1736. debug_delete_obj_epilog = textwrap.dedent("""
  1737. This command deletes objects from the repository.
  1738. """)
  1739. subparser = subparsers.add_parser('debug-delete-obj', parents=[common_parser],
  1740. description=self.do_debug_delete_obj.__doc__,
  1741. epilog=debug_delete_obj_epilog,
  1742. formatter_class=argparse.RawDescriptionHelpFormatter,
  1743. help='delete object from repository (debug)')
  1744. subparser.set_defaults(func=self.do_debug_delete_obj)
  1745. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1746. type=location_validator(archive=False),
  1747. help='repository to use')
  1748. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  1749. help='hex object ID(s) to delete from the repo')
  1750. subparser = debug_parsers.add_parser('delete-obj', parents=[common_parser],
  1751. description=self.do_debug_delete_obj.__doc__,
  1752. epilog=debug_delete_obj_epilog,
  1753. formatter_class=argparse.RawDescriptionHelpFormatter,
  1754. help='delete object from repository (debug)')
  1755. subparser.set_defaults(func=self.do_debug_delete_obj)
  1756. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1757. type=location_validator(archive=False),
  1758. help='repository to use')
  1759. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  1760. help='hex object ID(s) to delete from the repo')
  1761. debug_refcount_obj_epilog = textwrap.dedent("""
  1762. This command displays the reference count for objects from the repository.
  1763. """)
  1764. subparser = subparsers.add_parser('debug-refcount-obj', parents=[common_parser],
  1765. description=self.do_debug_refcount_obj.__doc__,
  1766. epilog=debug_refcount_obj_epilog,
  1767. formatter_class=argparse.RawDescriptionHelpFormatter,
  1768. help='show refcount for object from repository (debug)')
  1769. subparser.set_defaults(func=self.do_debug_refcount_obj)
  1770. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1771. type=location_validator(archive=False),
  1772. help='repository to use')
  1773. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  1774. help='hex object ID(s) to show refcounts for')
  1775. subparser = debug_parsers.add_parser('refcount-obj', parents=[common_parser],
  1776. description=self.do_debug_refcount_obj.__doc__,
  1777. epilog=debug_refcount_obj_epilog,
  1778. formatter_class=argparse.RawDescriptionHelpFormatter,
  1779. help='show refcount for object from repository (debug)')
  1780. subparser.set_defaults(func=self.do_debug_refcount_obj)
  1781. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1782. type=location_validator(archive=False),
  1783. help='repository to use')
  1784. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  1785. help='hex object ID(s) to show refcounts for')
  1786. return parser
  1787. def get_args(self, argv, cmd):
  1788. """usually, just returns argv, except if we deal with a ssh forced command for borg serve."""
  1789. result = self.parse_args(argv[1:])
  1790. if cmd is not None and result.func == self.do_serve:
  1791. forced_result = result
  1792. argv = shlex.split(cmd)
  1793. result = self.parse_args(argv[1:])
  1794. if result.func != forced_result.func:
  1795. # someone is trying to execute a different borg subcommand, don't do that!
  1796. return forced_result
  1797. # we only take specific options from the forced "borg serve" command:
  1798. result.restrict_to_paths = forced_result.restrict_to_paths
  1799. result.append_only = forced_result.append_only
  1800. return result
  1801. def parse_args(self, args=None):
  1802. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  1803. if args:
  1804. args = self.preprocess_args(args)
  1805. parser = self.build_parser(args)
  1806. args = parser.parse_args(args or ['-h'])
  1807. update_excludes(args)
  1808. return args
  1809. def run(self, args):
  1810. os.umask(args.umask) # early, before opening files
  1811. self.lock_wait = args.lock_wait
  1812. # This works around http://bugs.python.org/issue9351
  1813. func = getattr(args, 'func', None) or getattr(args, 'fallback_func')
  1814. setup_logging(level=args.log_level, is_serve=func == self.do_serve) # do not use loggers before this!
  1815. check_extension_modules()
  1816. if is_slow_msgpack():
  1817. logger.warning("Using a pure-python msgpack! This will result in lower performance.")
  1818. return func(args)
  1819. def sig_info_handler(sig_no, stack): # pragma: no cover
  1820. """search the stack for infos about the currently processed file and print them"""
  1821. with signal_handler(sig_no, signal.SIG_IGN):
  1822. for frame in inspect.getouterframes(stack):
  1823. func, loc = frame[3], frame[0].f_locals
  1824. if func in ('process_file', '_process', ): # create op
  1825. path = loc['path']
  1826. try:
  1827. pos = loc['fd'].tell()
  1828. total = loc['st'].st_size
  1829. except Exception:
  1830. pos, total = 0, 0
  1831. logger.info("{0} {1}/{2}".format(path, format_file_size(pos), format_file_size(total)))
  1832. break
  1833. if func in ('extract_item', ): # extract op
  1834. path = loc['item'][b'path']
  1835. try:
  1836. pos = loc['fd'].tell()
  1837. except Exception:
  1838. pos = 0
  1839. logger.info("{0} {1}/???".format(path, format_file_size(pos)))
  1840. break
  1841. def sig_trace_handler(sig_no, stack): # pragma: no cover
  1842. print('\nReceived SIGUSR2 at %s, dumping trace...' % datetime.now().replace(microsecond=0), file=sys.stderr)
  1843. faulthandler.dump_traceback()
  1844. def main(): # pragma: no cover
  1845. # Make sure stdout and stderr have errors='replace') to avoid unicode
  1846. # issues when print()-ing unicode file names
  1847. sys.stdout = ErrorIgnoringTextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  1848. sys.stderr = ErrorIgnoringTextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  1849. # If we receive SIGINT (ctrl-c), SIGTERM (kill) or SIGHUP (kill -HUP),
  1850. # catch them and raise a proper exception that can be handled for an
  1851. # orderly exit.
  1852. # SIGHUP is important especially for systemd systems, where logind
  1853. # sends it when a session exits, in addition to any traditional use.
  1854. # Output some info if we receive SIGUSR1 or SIGINFO (ctrl-t).
  1855. # Register fault handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL.
  1856. faulthandler.enable()
  1857. with signal_handler('SIGINT', raising_signal_handler(KeyboardInterrupt)), \
  1858. signal_handler('SIGHUP', raising_signal_handler(SigHup)), \
  1859. signal_handler('SIGTERM', raising_signal_handler(SigTerm)), \
  1860. signal_handler('SIGUSR1', sig_info_handler), \
  1861. signal_handler('SIGUSR2', sig_trace_handler), \
  1862. signal_handler('SIGINFO', sig_info_handler):
  1863. archiver = Archiver()
  1864. msg = None
  1865. try:
  1866. args = archiver.get_args(sys.argv, os.environ.get('SSH_ORIGINAL_COMMAND'))
  1867. except Error as e:
  1868. msg = e.get_message()
  1869. if e.traceback:
  1870. msg += "\n%s\n%s" % (traceback.format_exc(), sysinfo())
  1871. # we might not have logging setup yet, so get out quickly
  1872. print(msg, file=sys.stderr)
  1873. sys.exit(e.exit_code)
  1874. try:
  1875. exit_code = archiver.run(args)
  1876. except Error as e:
  1877. msg = e.get_message()
  1878. if e.traceback:
  1879. msg += "\n%s\n%s" % (traceback.format_exc(), sysinfo())
  1880. exit_code = e.exit_code
  1881. except RemoteRepository.RPCError as e:
  1882. msg = '%s\n%s' % (str(e), sysinfo())
  1883. exit_code = EXIT_ERROR
  1884. except Exception:
  1885. msg = 'Local Exception.\n%s\n%s' % (traceback.format_exc(), sysinfo())
  1886. exit_code = EXIT_ERROR
  1887. except KeyboardInterrupt:
  1888. msg = 'Keyboard interrupt.\n%s\n%s' % (traceback.format_exc(), sysinfo())
  1889. exit_code = EXIT_ERROR
  1890. except SigTerm:
  1891. msg = 'Received SIGTERM.'
  1892. exit_code = EXIT_ERROR
  1893. except SigHup:
  1894. msg = 'Received SIGHUP.'
  1895. exit_code = EXIT_ERROR
  1896. if msg:
  1897. logger.error(msg)
  1898. if args.show_rc:
  1899. exit_msg = 'terminating with %s status, rc %d'
  1900. if exit_code == EXIT_SUCCESS:
  1901. logger.info(exit_msg % ('success', exit_code))
  1902. elif exit_code == EXIT_WARNING:
  1903. logger.warning(exit_msg % ('warning', exit_code))
  1904. elif exit_code == EXIT_ERROR:
  1905. logger.error(exit_msg % ('error', exit_code))
  1906. else:
  1907. # if you see 666 in output, it usually means exit_code was None
  1908. logger.error(exit_msg % ('abnormal', exit_code or 666))
  1909. sys.exit(exit_code)
  1910. if __name__ == '__main__':
  1911. main()