archiver.py 113 KB

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