archiver.py 115 KB

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