archiver.py 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778
  1. import argparse
  2. import collections
  3. import functools
  4. import hashlib
  5. import inspect
  6. import logging
  7. import os
  8. import re
  9. import shlex
  10. import signal
  11. import stat
  12. import subprocess
  13. import sys
  14. import textwrap
  15. import traceback
  16. from binascii import unhexlify
  17. from datetime import datetime
  18. from itertools import zip_longest
  19. from operator import attrgetter
  20. from .logger import create_logger, setup_logging
  21. logger = create_logger()
  22. from . import __version__
  23. from . import helpers
  24. from .archive import Archive, ArchiveChecker, ArchiveRecreater, Statistics, is_special
  25. from .archive import BackupOSError, CHUNKER_PARAMS
  26. from .cache import Cache
  27. from .constants import * # NOQA
  28. from .helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR
  29. from .helpers import Error, NoManifestError
  30. from .helpers import location_validator, archivename_validator, ChunkerParams, CompressionSpec
  31. from .helpers import PrefixSpec, SortBySpec, HUMAN_SORT_KEYS
  32. from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter, format_time, format_file_size, format_archive
  33. from .helpers import safe_encode, remove_surrogates, bin_to_hex
  34. from .helpers import prune_within, prune_split
  35. from .helpers import to_localtime, timestamp
  36. from .helpers import get_cache_dir
  37. from .helpers import Manifest
  38. from .helpers import update_excludes, check_extension_modules
  39. from .helpers import dir_is_tagged, is_slow_msgpack, yes, sysinfo
  40. from .helpers import log_multi
  41. from .helpers import parse_pattern, PatternMatcher, PathPrefixPattern
  42. from .helpers import signal_handler, raising_signal_handler, SigHup, SigTerm
  43. from .helpers import ErrorIgnoringTextIOWrapper
  44. from .helpers import ProgressIndicatorPercent
  45. from .item import Item
  46. from .key import key_creator, RepoKey, PassphraseKey
  47. from .keymanager import KeyManager
  48. from .platform import get_flags
  49. from .remote import RepositoryServer, RemoteRepository, cache_if_remote
  50. from .repository import Repository
  51. from .selftest import selftest
  52. from .upgrader import AtticRepositoryUpgrader, BorgRepositoryUpgrader
  53. STATS_HEADER = " Original size Compressed size Deduplicated size"
  54. def argument(args, str_or_bool):
  55. """If bool is passed, return it. If str is passed, retrieve named attribute from args."""
  56. if isinstance(str_or_bool, str):
  57. return getattr(args, str_or_bool)
  58. return str_or_bool
  59. def with_repository(fake=False, create=False, lock=True, exclusive=False, manifest=True, cache=False):
  60. """
  61. Method decorator for subcommand-handling methods: do_XYZ(self, args, repository, …)
  62. If a parameter (where allowed) is a str the attribute named of args is used instead.
  63. :param fake: (str or bool) use None instead of repository, don't do anything else
  64. :param create: create repository
  65. :param lock: lock repository
  66. :param exclusive: (str or bool) lock repository exclusively (for writing)
  67. :param manifest: load manifest and key, pass them as keyword arguments
  68. :param cache: open cache, pass it as keyword argument (implies manifest)
  69. """
  70. def decorator(method):
  71. @functools.wraps(method)
  72. def wrapper(self, args, **kwargs):
  73. location = args.location # note: 'location' must be always present in args
  74. append_only = getattr(args, 'append_only', False)
  75. if argument(args, fake):
  76. return method(self, args, repository=None, **kwargs)
  77. elif location.proto == 'ssh':
  78. repository = RemoteRepository(location, create=create, exclusive=argument(args, exclusive),
  79. lock_wait=self.lock_wait, lock=lock, append_only=append_only, args=args)
  80. else:
  81. repository = Repository(location.path, create=create, exclusive=argument(args, exclusive),
  82. lock_wait=self.lock_wait, lock=lock,
  83. append_only=append_only)
  84. with repository:
  85. if manifest or cache:
  86. kwargs['manifest'], kwargs['key'] = Manifest.load(repository)
  87. if cache:
  88. with Cache(repository, kwargs['key'], kwargs['manifest'],
  89. do_files=getattr(args, 'cache_files', False), lock_wait=self.lock_wait) as cache_:
  90. return method(self, args, repository=repository, cache=cache_, **kwargs)
  91. else:
  92. return method(self, args, repository=repository, **kwargs)
  93. return wrapper
  94. return decorator
  95. def with_archive(method):
  96. @functools.wraps(method)
  97. def wrapper(self, args, repository, key, manifest, **kwargs):
  98. archive = Archive(repository, key, manifest, args.location.archive,
  99. numeric_owner=getattr(args, 'numeric_owner', False), cache=kwargs.get('cache'),
  100. consider_part_files=args.consider_part_files)
  101. return method(self, args, repository=repository, manifest=manifest, key=key, archive=archive, **kwargs)
  102. return wrapper
  103. class Archiver:
  104. def __init__(self, lock_wait=None, prog=None):
  105. self.exit_code = EXIT_SUCCESS
  106. self.lock_wait = lock_wait
  107. self.parser = self.build_parser(prog)
  108. def print_error(self, msg, *args):
  109. msg = args and msg % args or msg
  110. self.exit_code = EXIT_ERROR
  111. logger.error(msg)
  112. def print_warning(self, msg, *args):
  113. msg = args and msg % args or msg
  114. self.exit_code = EXIT_WARNING # we do not terminate here, so it is a warning
  115. logger.warning(msg)
  116. def print_file_status(self, status, path):
  117. if self.output_list and (self.output_filter is None or status in self.output_filter):
  118. logging.getLogger('borg.output.list').info("%1s %s", status, remove_surrogates(path))
  119. @staticmethod
  120. def compare_chunk_contents(chunks1, chunks2):
  121. """Compare two chunk iterators (like returned by :meth:`.DownloadPipeline.fetch_many`)"""
  122. end = object()
  123. alen = ai = 0
  124. blen = bi = 0
  125. while True:
  126. if not alen - ai:
  127. a = next(chunks1, end)
  128. if a is end:
  129. return not blen - bi and next(chunks2, end) is end
  130. a = memoryview(a.data)
  131. alen = len(a)
  132. ai = 0
  133. if not blen - bi:
  134. b = next(chunks2, end)
  135. if b is end:
  136. return not alen - ai and next(chunks1, end) is end
  137. b = memoryview(b.data)
  138. blen = len(b)
  139. bi = 0
  140. slicelen = min(alen - ai, blen - bi)
  141. if a[ai:ai + slicelen] != b[bi:bi + slicelen]:
  142. return False
  143. ai += slicelen
  144. bi += slicelen
  145. @staticmethod
  146. def build_matcher(excludes, paths):
  147. matcher = PatternMatcher()
  148. if excludes:
  149. matcher.add(excludes, False)
  150. include_patterns = []
  151. if paths:
  152. include_patterns.extend(parse_pattern(i, PathPrefixPattern) for i in paths)
  153. matcher.add(include_patterns, True)
  154. matcher.fallback = not include_patterns
  155. return matcher, include_patterns
  156. def do_serve(self, args):
  157. """Start in server mode. This command is usually not used manually.
  158. """
  159. return RepositoryServer(restrict_to_paths=args.restrict_to_paths, append_only=args.append_only).serve()
  160. @with_repository(create=True, exclusive=True, manifest=False)
  161. def do_init(self, args, repository):
  162. """Initialize an empty repository"""
  163. logger.info('Initializing repository at "%s"' % args.location.canonical_path())
  164. try:
  165. key = key_creator(repository, args)
  166. except (EOFError, KeyboardInterrupt):
  167. repository.destroy()
  168. return EXIT_WARNING
  169. manifest = Manifest(key, repository)
  170. manifest.key = key
  171. manifest.write()
  172. repository.commit()
  173. with Cache(repository, key, manifest, warn_if_unencrypted=False):
  174. pass
  175. return self.exit_code
  176. @with_repository(exclusive=True, manifest=False)
  177. def do_check(self, args, repository):
  178. """Check repository consistency"""
  179. if args.repair:
  180. msg = ("'check --repair' is an experimental feature that might result in data loss." +
  181. "\n" +
  182. "Type 'YES' if you understand this and want to continue: ")
  183. if not yes(msg, false_msg="Aborting.", invalid_msg="Invalid answer, aborting.",
  184. truish=('YES', ), retry=False,
  185. env_var_override='BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  186. return EXIT_ERROR
  187. if args.repo_only and any((args.verify_data, args.first, args.last, args.prefix)):
  188. self.print_error("--repository-only contradicts --first, --last, --prefix and --verify-data arguments.")
  189. return EXIT_ERROR
  190. if not args.archives_only:
  191. if not repository.check(repair=args.repair, save_space=args.save_space):
  192. return EXIT_WARNING
  193. if not args.repo_only and not ArchiveChecker().check(
  194. repository, repair=args.repair, archive=args.location.archive,
  195. first=args.first, last=args.last, sort_by=args.sort_by or 'ts', prefix=args.prefix,
  196. verify_data=args.verify_data, save_space=args.save_space):
  197. return EXIT_WARNING
  198. return EXIT_SUCCESS
  199. @with_repository()
  200. def do_change_passphrase(self, args, repository, manifest, key):
  201. """Change repository key file passphrase"""
  202. key.change_passphrase()
  203. return EXIT_SUCCESS
  204. @with_repository(lock=False, exclusive=False, manifest=False, cache=False)
  205. def do_key_export(self, args, repository):
  206. """Export the repository key for backup"""
  207. manager = KeyManager(repository)
  208. manager.load_keyblob()
  209. if args.paper:
  210. manager.export_paperkey(args.path)
  211. else:
  212. if not args.path:
  213. self.print_error("output file to export key to expected")
  214. return EXIT_ERROR
  215. manager.export(args.path)
  216. return EXIT_SUCCESS
  217. @with_repository(lock=False, exclusive=False, manifest=False, cache=False)
  218. def do_key_import(self, args, repository):
  219. """Import the repository key from backup"""
  220. manager = KeyManager(repository)
  221. if args.paper:
  222. if args.path:
  223. self.print_error("with --paper import from file is not supported")
  224. return EXIT_ERROR
  225. manager.import_paperkey(args)
  226. else:
  227. if not args.path:
  228. self.print_error("input file to import key from expected")
  229. return EXIT_ERROR
  230. if not os.path.exists(args.path):
  231. self.print_error("input file does not exist: " + args.path)
  232. return EXIT_ERROR
  233. manager.import_keyfile(args)
  234. return EXIT_SUCCESS
  235. @with_repository(manifest=False)
  236. def do_migrate_to_repokey(self, args, repository):
  237. """Migrate passphrase -> repokey"""
  238. manifest_data = repository.get(Manifest.MANIFEST_ID)
  239. key_old = PassphraseKey.detect(repository, manifest_data)
  240. key_new = RepoKey(repository)
  241. key_new.target = repository
  242. key_new.repository_id = repository.id
  243. key_new.enc_key = key_old.enc_key
  244. key_new.enc_hmac_key = key_old.enc_hmac_key
  245. key_new.id_key = key_old.id_key
  246. key_new.chunk_seed = key_old.chunk_seed
  247. key_new.change_passphrase() # option to change key protection passphrase, save
  248. return EXIT_SUCCESS
  249. @with_repository(fake='dry_run', exclusive=True)
  250. def do_create(self, args, repository, manifest=None, key=None):
  251. """Create new archive"""
  252. matcher = PatternMatcher(fallback=True)
  253. if args.excludes:
  254. matcher.add(args.excludes, False)
  255. def create_inner(archive, cache):
  256. # Add cache dir to inode_skip list
  257. skip_inodes = set()
  258. try:
  259. st = os.stat(get_cache_dir())
  260. skip_inodes.add((st.st_ino, st.st_dev))
  261. except OSError:
  262. pass
  263. # Add local repository dir to inode_skip list
  264. if not args.location.host:
  265. try:
  266. st = os.stat(args.location.path)
  267. skip_inodes.add((st.st_ino, st.st_dev))
  268. except OSError:
  269. pass
  270. for path in args.paths:
  271. if path == '-': # stdin
  272. path = 'stdin'
  273. if not dry_run:
  274. try:
  275. status = archive.process_stdin(path, cache)
  276. except BackupOSError as e:
  277. status = 'E'
  278. self.print_warning('%s: %s', path, e)
  279. else:
  280. status = '-'
  281. self.print_file_status(status, path)
  282. continue
  283. path = os.path.normpath(path)
  284. try:
  285. st = os.lstat(path)
  286. except OSError as e:
  287. self.print_warning('%s: %s', path, e)
  288. continue
  289. if args.one_file_system:
  290. restrict_dev = st.st_dev
  291. else:
  292. restrict_dev = None
  293. self._process(archive, cache, matcher, args.exclude_caches, args.exclude_if_present,
  294. args.keep_tag_files, skip_inodes, path, restrict_dev,
  295. read_special=args.read_special, dry_run=dry_run, st=st)
  296. if not dry_run:
  297. archive.save(comment=args.comment, timestamp=args.timestamp)
  298. if args.progress:
  299. archive.stats.show_progress(final=True)
  300. if args.stats:
  301. archive.end = datetime.utcnow()
  302. log_multi(DASHES,
  303. str(archive),
  304. DASHES,
  305. STATS_HEADER,
  306. str(archive.stats),
  307. str(cache),
  308. DASHES, logger=logging.getLogger('borg.output.stats'))
  309. self.output_filter = args.output_filter
  310. self.output_list = args.output_list
  311. self.ignore_inode = args.ignore_inode
  312. dry_run = args.dry_run
  313. t0 = datetime.utcnow()
  314. if not dry_run:
  315. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  316. archive = Archive(repository, key, manifest, args.location.archive, cache=cache,
  317. create=True, checkpoint_interval=args.checkpoint_interval,
  318. numeric_owner=args.numeric_owner, progress=args.progress,
  319. chunker_params=args.chunker_params, start=t0,
  320. compression=args.compression, compression_files=args.compression_files)
  321. create_inner(archive, cache)
  322. else:
  323. create_inner(None, None)
  324. return self.exit_code
  325. def _process(self, archive, cache, matcher, exclude_caches, exclude_if_present,
  326. keep_tag_files, skip_inodes, path, restrict_dev,
  327. read_special=False, dry_run=False, st=None):
  328. if not matcher.match(path):
  329. self.print_file_status('x', path)
  330. return
  331. if st is None:
  332. try:
  333. st = os.lstat(path)
  334. except OSError as e:
  335. self.print_warning('%s: %s', path, e)
  336. return
  337. if (st.st_ino, st.st_dev) in skip_inodes:
  338. return
  339. # if restrict_dev is given, we do not want to recurse into a new filesystem,
  340. # but we WILL save the mountpoint directory (or more precise: the root
  341. # directory of the mounted filesystem that shadows the mountpoint dir).
  342. recurse = restrict_dev is None or st.st_dev == restrict_dev
  343. status = None
  344. # Ignore if nodump flag is set
  345. try:
  346. if get_flags(path, st) & stat.UF_NODUMP:
  347. self.print_file_status('x', path)
  348. return
  349. except OSError as e:
  350. self.print_warning('%s: %s', path, e)
  351. return
  352. if stat.S_ISREG(st.st_mode):
  353. if not dry_run:
  354. try:
  355. status = archive.process_file(path, st, cache, self.ignore_inode)
  356. except BackupOSError as e:
  357. status = 'E'
  358. self.print_warning('%s: %s', path, e)
  359. elif stat.S_ISDIR(st.st_mode):
  360. if recurse:
  361. tag_paths = dir_is_tagged(path, exclude_caches, exclude_if_present)
  362. if tag_paths:
  363. if keep_tag_files and not dry_run:
  364. archive.process_dir(path, st)
  365. for tag_path in tag_paths:
  366. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  367. keep_tag_files, skip_inodes, tag_path, restrict_dev,
  368. read_special=read_special, dry_run=dry_run)
  369. return
  370. if not dry_run:
  371. status = archive.process_dir(path, st)
  372. if recurse:
  373. try:
  374. entries = helpers.scandir_inorder(path)
  375. except OSError as e:
  376. status = 'E'
  377. self.print_warning('%s: %s', path, e)
  378. else:
  379. for dirent in entries:
  380. normpath = os.path.normpath(dirent.path)
  381. self._process(archive, cache, matcher, exclude_caches, exclude_if_present,
  382. keep_tag_files, skip_inodes, normpath, restrict_dev,
  383. read_special=read_special, dry_run=dry_run)
  384. elif stat.S_ISLNK(st.st_mode):
  385. if not dry_run:
  386. if not read_special:
  387. status = archive.process_symlink(path, st)
  388. else:
  389. try:
  390. st_target = os.stat(path)
  391. except OSError:
  392. special = False
  393. else:
  394. special = is_special(st_target.st_mode)
  395. if special:
  396. status = archive.process_file(path, st_target, cache)
  397. else:
  398. status = archive.process_symlink(path, st)
  399. elif stat.S_ISFIFO(st.st_mode):
  400. if not dry_run:
  401. if not read_special:
  402. status = archive.process_fifo(path, st)
  403. else:
  404. status = archive.process_file(path, st, cache)
  405. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  406. if not dry_run:
  407. if not read_special:
  408. status = archive.process_dev(path, st)
  409. else:
  410. status = archive.process_file(path, st, cache)
  411. elif stat.S_ISSOCK(st.st_mode):
  412. # Ignore unix sockets
  413. return
  414. elif stat.S_ISDOOR(st.st_mode):
  415. # Ignore Solaris doors
  416. return
  417. elif stat.S_ISPORT(st.st_mode):
  418. # Ignore Solaris event ports
  419. return
  420. else:
  421. self.print_warning('Unknown file type: %s', path)
  422. return
  423. # Status output
  424. if status is None:
  425. if not dry_run:
  426. status = '?' # need to add a status code somewhere
  427. else:
  428. status = '-' # dry run, item was not backed up
  429. self.print_file_status(status, path)
  430. @staticmethod
  431. def build_filter(matcher, peek_and_store_hardlink_masters, strip_components):
  432. if strip_components:
  433. def item_filter(item):
  434. matched = matcher.match(item.path) and os.sep.join(item.path.split(os.sep)[strip_components:])
  435. peek_and_store_hardlink_masters(item, matched)
  436. return matched
  437. else:
  438. def item_filter(item):
  439. matched = matcher.match(item.path)
  440. peek_and_store_hardlink_masters(item, matched)
  441. return matched
  442. return item_filter
  443. @with_repository()
  444. @with_archive
  445. def do_extract(self, args, repository, manifest, key, archive):
  446. """Extract archive contents"""
  447. # be restrictive when restoring files, restore permissions later
  448. if sys.getfilesystemencoding() == 'ascii':
  449. logger.warning('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  450. if sys.platform.startswith(('linux', 'freebsd', 'netbsd', 'openbsd', 'darwin', )):
  451. logger.warning('Hint: You likely need to fix your locale setup. E.g. install locales and use: LANG=en_US.UTF-8')
  452. matcher, include_patterns = self.build_matcher(args.excludes, args.paths)
  453. progress = args.progress
  454. output_list = args.output_list
  455. dry_run = args.dry_run
  456. stdout = args.stdout
  457. sparse = args.sparse
  458. strip_components = args.strip_components
  459. dirs = []
  460. partial_extract = not matcher.empty() or strip_components
  461. hardlink_masters = {} if partial_extract else None
  462. def peek_and_store_hardlink_masters(item, matched):
  463. if (partial_extract and not matched and stat.S_ISREG(item.mode) and
  464. item.get('hardlink_master', True) and 'source' not in item):
  465. hardlink_masters[item.get('path')] = (item.get('chunks'), None)
  466. filter = self.build_filter(matcher, peek_and_store_hardlink_masters, strip_components)
  467. if progress:
  468. pi = ProgressIndicatorPercent(msg='Extracting files %5.1f%%', step=0.1)
  469. pi.output('Calculating size')
  470. extracted_size = sum(item.file_size(hardlink_masters) for item in archive.iter_items(filter))
  471. pi.total = extracted_size
  472. else:
  473. pi = None
  474. for item in archive.iter_items(filter, preload=True):
  475. orig_path = item.path
  476. if strip_components:
  477. item.path = os.sep.join(orig_path.split(os.sep)[strip_components:])
  478. if not args.dry_run:
  479. while dirs and not item.path.startswith(dirs[-1].path):
  480. dir_item = dirs.pop(-1)
  481. try:
  482. archive.extract_item(dir_item, stdout=stdout)
  483. except BackupOSError as e:
  484. self.print_warning('%s: %s', remove_surrogates(dir_item.path), e)
  485. if output_list:
  486. logging.getLogger('borg.output.list').info(remove_surrogates(orig_path))
  487. try:
  488. if dry_run:
  489. archive.extract_item(item, dry_run=True, pi=pi)
  490. else:
  491. if stat.S_ISDIR(item.mode):
  492. dirs.append(item)
  493. archive.extract_item(item, restore_attrs=False)
  494. else:
  495. archive.extract_item(item, stdout=stdout, sparse=sparse, hardlink_masters=hardlink_masters,
  496. stripped_components=strip_components, original_path=orig_path, pi=pi)
  497. except BackupOSError as e:
  498. self.print_warning('%s: %s', remove_surrogates(orig_path), e)
  499. if not args.dry_run:
  500. pi = ProgressIndicatorPercent(total=len(dirs), msg='Setting directory permissions %3.0f%%')
  501. while dirs:
  502. pi.show()
  503. dir_item = dirs.pop(-1)
  504. try:
  505. archive.extract_item(dir_item)
  506. except BackupOSError as e:
  507. self.print_warning('%s: %s', remove_surrogates(dir_item.path), e)
  508. for pattern in include_patterns:
  509. if pattern.match_count == 0:
  510. self.print_warning("Include pattern '%s' never matched.", pattern)
  511. return self.exit_code
  512. @with_repository()
  513. @with_archive
  514. def do_diff(self, args, repository, manifest, key, archive):
  515. """Diff contents of two archives"""
  516. def fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2):
  517. chunks1 = archive1.pipeline.fetch_many(chunk_ids1)
  518. chunks2 = archive2.pipeline.fetch_many(chunk_ids2)
  519. return self.compare_chunk_contents(chunks1, chunks2)
  520. def sum_chunk_size(item, consider_ids=None):
  521. if item.get('deleted'):
  522. return None
  523. else:
  524. return sum(c.size for c in item.chunks
  525. if consider_ids is None or c.id in consider_ids)
  526. def get_owner(item):
  527. if args.numeric_owner:
  528. return item.uid, item.gid
  529. else:
  530. return item.user, item.group
  531. def get_mode(item):
  532. if 'mode' in item:
  533. return stat.filemode(item.mode)
  534. else:
  535. return [None]
  536. def has_hardlink_master(item, hardlink_masters):
  537. return stat.S_ISREG(item.mode) and item.get('source') in hardlink_masters
  538. def compare_link(item1, item2):
  539. # These are the simple link cases. For special cases, e.g. if a
  540. # regular file is replaced with a link or vice versa, it is
  541. # indicated in compare_mode instead.
  542. if item1.get('deleted'):
  543. return 'added link'
  544. elif item2.get('deleted'):
  545. return 'removed link'
  546. elif 'source' in item1 and 'source' in item2 and item1.source != item2.source:
  547. return 'changed link'
  548. def contents_changed(item1, item2):
  549. if can_compare_chunk_ids:
  550. return item1.chunks != item2.chunks
  551. else:
  552. if sum_chunk_size(item1) != sum_chunk_size(item2):
  553. return True
  554. else:
  555. chunk_ids1 = [c.id for c in item1.chunks]
  556. chunk_ids2 = [c.id for c in item2.chunks]
  557. return not fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2)
  558. def compare_content(path, item1, item2):
  559. if contents_changed(item1, item2):
  560. if item1.get('deleted'):
  561. return ('added {:>13}'.format(format_file_size(sum_chunk_size(item2))))
  562. elif item2.get('deleted'):
  563. return ('removed {:>11}'.format(format_file_size(sum_chunk_size(item1))))
  564. else:
  565. chunk_ids1 = {c.id for c in item1.chunks}
  566. chunk_ids2 = {c.id for c in item2.chunks}
  567. added_ids = chunk_ids2 - chunk_ids1
  568. removed_ids = chunk_ids1 - chunk_ids2
  569. added = sum_chunk_size(item2, added_ids)
  570. removed = sum_chunk_size(item1, removed_ids)
  571. return ('{:>9} {:>9}'.format(format_file_size(added, precision=1, sign=True),
  572. format_file_size(-removed, precision=1, sign=True)))
  573. def compare_directory(item1, item2):
  574. if item2.get('deleted') and not item1.get('deleted'):
  575. return 'removed directory'
  576. elif item1.get('deleted') and not item2.get('deleted'):
  577. return 'added directory'
  578. def compare_owner(item1, item2):
  579. user1, group1 = get_owner(item1)
  580. user2, group2 = get_owner(item2)
  581. if user1 != user2 or group1 != group2:
  582. return '[{}:{} -> {}:{}]'.format(user1, group1, user2, group2)
  583. def compare_mode(item1, item2):
  584. if item1.mode != item2.mode:
  585. return '[{} -> {}]'.format(get_mode(item1), get_mode(item2))
  586. def compare_items(output, path, item1, item2, hardlink_masters, deleted=False):
  587. """
  588. Compare two items with identical paths.
  589. :param deleted: Whether one of the items has been deleted
  590. """
  591. changes = []
  592. if has_hardlink_master(item1, hardlink_masters):
  593. item1 = hardlink_masters[item1.source][0]
  594. if has_hardlink_master(item2, hardlink_masters):
  595. item2 = hardlink_masters[item2.source][1]
  596. if get_mode(item1)[0] == 'l' or get_mode(item2)[0] == 'l':
  597. changes.append(compare_link(item1, item2))
  598. if 'chunks' in item1 and 'chunks' in item2:
  599. changes.append(compare_content(path, item1, item2))
  600. if get_mode(item1)[0] == 'd' or get_mode(item2)[0] == 'd':
  601. changes.append(compare_directory(item1, item2))
  602. if not deleted:
  603. changes.append(compare_owner(item1, item2))
  604. changes.append(compare_mode(item1, item2))
  605. changes = [x for x in changes if x]
  606. if changes:
  607. output_line = (remove_surrogates(path), ' '.join(changes))
  608. if args.sort:
  609. output.append(output_line)
  610. else:
  611. print_output(output_line)
  612. def print_output(line):
  613. print("{:<19} {}".format(line[1], line[0]))
  614. def compare_archives(archive1, archive2, matcher):
  615. def hardlink_master_seen(item):
  616. return 'source' not in item or not stat.S_ISREG(item.mode) or item.source in hardlink_masters
  617. def is_hardlink_master(item):
  618. return item.get('hardlink_master', True) and 'source' not in item
  619. def update_hardlink_masters(item1, item2):
  620. if is_hardlink_master(item1) or is_hardlink_master(item2):
  621. hardlink_masters[item1.path] = (item1, item2)
  622. def compare_or_defer(item1, item2):
  623. update_hardlink_masters(item1, item2)
  624. if not hardlink_master_seen(item1) or not hardlink_master_seen(item2):
  625. deferred.append((item1, item2))
  626. else:
  627. compare_items(output, item1.path, item1, item2, hardlink_masters)
  628. orphans_archive1 = collections.OrderedDict()
  629. orphans_archive2 = collections.OrderedDict()
  630. deferred = []
  631. hardlink_masters = {}
  632. output = []
  633. for item1, item2 in zip_longest(
  634. archive1.iter_items(lambda item: matcher.match(item.path)),
  635. archive2.iter_items(lambda item: matcher.match(item.path)),
  636. ):
  637. if item1 and item2 and item1.path == item2.path:
  638. compare_or_defer(item1, item2)
  639. continue
  640. if item1:
  641. matching_orphan = orphans_archive2.pop(item1.path, None)
  642. if matching_orphan:
  643. compare_or_defer(item1, matching_orphan)
  644. else:
  645. orphans_archive1[item1.path] = item1
  646. if item2:
  647. matching_orphan = orphans_archive1.pop(item2.path, None)
  648. if matching_orphan:
  649. compare_or_defer(matching_orphan, item2)
  650. else:
  651. orphans_archive2[item2.path] = item2
  652. # At this point orphans_* contain items that had no matching partner in the other archive
  653. deleted_item = Item(
  654. deleted=True,
  655. chunks=[],
  656. mode=0,
  657. )
  658. for added in orphans_archive2.values():
  659. path = added.path
  660. deleted_item.path = path
  661. update_hardlink_masters(deleted_item, added)
  662. compare_items(output, path, deleted_item, added, hardlink_masters, deleted=True)
  663. for deleted in orphans_archive1.values():
  664. path = deleted.path
  665. deleted_item.path = path
  666. update_hardlink_masters(deleted, deleted_item)
  667. compare_items(output, path, deleted, deleted_item, hardlink_masters, deleted=True)
  668. for item1, item2 in deferred:
  669. assert hardlink_master_seen(item1)
  670. assert hardlink_master_seen(item2)
  671. compare_items(output, item1.path, item1, item2, hardlink_masters)
  672. for line in sorted(output):
  673. print_output(line)
  674. archive1 = archive
  675. archive2 = Archive(repository, key, manifest, args.archive2,
  676. consider_part_files=args.consider_part_files)
  677. can_compare_chunk_ids = archive1.metadata.get('chunker_params', False) == archive2.metadata.get(
  678. 'chunker_params', True) or args.same_chunker_params
  679. if not can_compare_chunk_ids:
  680. self.print_warning('--chunker-params might be different between archives, diff will be slow.\n'
  681. 'If you know for certain that they are the same, pass --same-chunker-params '
  682. 'to override this check.')
  683. matcher, include_patterns = self.build_matcher(args.excludes, args.paths)
  684. compare_archives(archive1, archive2, matcher)
  685. for pattern in include_patterns:
  686. if pattern.match_count == 0:
  687. self.print_warning("Include pattern '%s' never matched.", pattern)
  688. return self.exit_code
  689. @with_repository(exclusive=True, cache=True)
  690. @with_archive
  691. def do_rename(self, args, repository, manifest, key, cache, archive):
  692. """Rename an existing archive"""
  693. archive.rename(args.name)
  694. manifest.write()
  695. repository.commit()
  696. cache.commit()
  697. return self.exit_code
  698. @with_repository(exclusive=True, manifest=False)
  699. def do_delete(self, args, repository):
  700. """Delete an existing repository or archives"""
  701. if any((args.location.archive, args.first, args.last, args.prefix)):
  702. return self._delete_archives(args, repository)
  703. else:
  704. return self._delete_repository(args, repository)
  705. def _delete_archives(self, args, repository):
  706. """Delete archives"""
  707. manifest, key = Manifest.load(repository)
  708. if args.location.archive:
  709. archive_names = (args.location.archive,)
  710. else:
  711. archive_names = tuple(x.name for x in manifest.archives.list_considering(args))
  712. if not archive_names:
  713. return self.exit_code
  714. stats_logger = logging.getLogger('borg.output.stats')
  715. if args.stats:
  716. log_multi(DASHES, STATS_HEADER, logger=stats_logger)
  717. with Cache(repository, key, manifest, lock_wait=self.lock_wait) as cache:
  718. for i, archive_name in enumerate(archive_names, 1):
  719. logger.info('Deleting {} ({}/{}):'.format(archive_name, i, len(archive_names)))
  720. archive = Archive(repository, key, manifest, archive_name, cache=cache)
  721. stats = Statistics()
  722. archive.delete(stats, progress=args.progress, forced=args.forced)
  723. manifest.write()
  724. repository.commit(save_space=args.save_space)
  725. cache.commit()
  726. logger.info("Archive deleted.")
  727. if args.stats:
  728. log_multi(stats.summary.format(label='Deleted data:', stats=stats),
  729. DASHES, logger=stats_logger)
  730. if not args.forced and self.exit_code:
  731. break
  732. if args.stats:
  733. stats_logger.info(str(cache))
  734. return self.exit_code
  735. def _delete_repository(self, args, repository):
  736. """Delete a repository"""
  737. if not args.cache_only:
  738. msg = []
  739. try:
  740. manifest, key = Manifest.load(repository)
  741. except NoManifestError:
  742. msg.append("You requested to completely DELETE the repository *including* all archives it may "
  743. "contain.")
  744. msg.append("This repository seems to have no manifest, so we can't tell anything about its "
  745. "contents.")
  746. else:
  747. msg.append("You requested to completely DELETE the repository *including* all archives it "
  748. "contains:")
  749. for archive_info in manifest.archives.list(sort_by=['ts']):
  750. msg.append(format_archive(archive_info))
  751. msg.append("Type 'YES' if you understand this and want to continue: ")
  752. msg = '\n'.join(msg)
  753. if not yes(msg, false_msg="Aborting.", invalid_msg='Invalid answer, aborting.', truish=('YES',),
  754. retry=False, env_var_override='BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'):
  755. self.exit_code = EXIT_ERROR
  756. return self.exit_code
  757. repository.destroy()
  758. logger.info("Repository deleted.")
  759. Cache.destroy(repository)
  760. logger.info("Cache deleted.")
  761. return self.exit_code
  762. @with_repository()
  763. def do_mount(self, args, repository, manifest, key):
  764. """Mount archive or an entire repository as a FUSE filesystem"""
  765. try:
  766. from .fuse import FuseOperations
  767. except ImportError as e:
  768. self.print_error('Loading fuse support failed [ImportError: %s]' % str(e))
  769. return self.exit_code
  770. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  771. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  772. return self.exit_code
  773. with cache_if_remote(repository) as cached_repo:
  774. operations = FuseOperations(key, repository, manifest, args, cached_repo)
  775. logger.info("Mounting filesystem")
  776. try:
  777. operations.mount(args.mountpoint, args.options, args.foreground)
  778. except RuntimeError:
  779. # Relevant error message already printed to stderr by fuse
  780. self.exit_code = EXIT_ERROR
  781. return self.exit_code
  782. @with_repository()
  783. def do_list(self, args, repository, manifest, key):
  784. """List archive or repository contents"""
  785. if not hasattr(sys.stdout, 'buffer'):
  786. # This is a shim for supporting unit tests replacing sys.stdout with e.g. StringIO,
  787. # which doesn't have an underlying buffer (= lower file object).
  788. def write(bytestring):
  789. sys.stdout.write(bytestring.decode('utf-8', errors='replace'))
  790. else:
  791. write = sys.stdout.buffer.write
  792. if args.location.archive:
  793. return self._list_archive(args, repository, manifest, key, write)
  794. else:
  795. return self._list_repository(args, manifest, write)
  796. def _list_archive(self, args, repository, manifest, key, write):
  797. matcher, _ = self.build_matcher(args.excludes, args.paths)
  798. with Cache(repository, key, manifest, lock_wait=self.lock_wait) as cache:
  799. archive = Archive(repository, key, manifest, args.location.archive, cache=cache,
  800. consider_part_files=args.consider_part_files)
  801. if args.format is not None:
  802. format = args.format
  803. elif args.short:
  804. format = "{path}{NL}"
  805. else:
  806. format = "{mode} {user:6} {group:6} {size:8} {isomtime} {path}{extra}{NL}"
  807. formatter = ItemFormatter(archive, format)
  808. for item in archive.iter_items(lambda item: matcher.match(item.path)):
  809. write(safe_encode(formatter.format_item(item)))
  810. return self.exit_code
  811. def _list_repository(self, args, manifest, write):
  812. if args.format is not None:
  813. format = args.format
  814. elif args.short:
  815. format = "{archive}{NL}"
  816. else:
  817. format = "{archive:<36} {time} [{id}]{NL}"
  818. formatter = ArchiveFormatter(format)
  819. for archive_info in manifest.archives.list_considering(args):
  820. write(safe_encode(formatter.format_item(archive_info)))
  821. return self.exit_code
  822. @with_repository(cache=True)
  823. def do_info(self, args, repository, manifest, key, cache):
  824. """Show archive details such as disk space used"""
  825. if any((args.location.archive, args.first, args.last, args.prefix)):
  826. return self._info_archives(args, repository, manifest, key, cache)
  827. else:
  828. return self._info_repository(repository, key, cache)
  829. def _info_archives(self, args, repository, manifest, key, cache):
  830. def format_cmdline(cmdline):
  831. return remove_surrogates(' '.join(shlex.quote(x) for x in cmdline))
  832. if args.location.archive:
  833. archive_names = (args.location.archive,)
  834. else:
  835. archive_names = tuple(x.name for x in manifest.archives.list_considering(args))
  836. if not archive_names:
  837. return self.exit_code
  838. for i, archive_name in enumerate(archive_names, 1):
  839. archive = Archive(repository, key, manifest, archive_name, cache=cache,
  840. consider_part_files=args.consider_part_files)
  841. stats = archive.calc_stats(cache)
  842. print('Archive name: %s' % archive.name)
  843. print('Archive fingerprint: %s' % archive.fpr)
  844. print('Comment: %s' % archive.metadata.get('comment', ''))
  845. print('Hostname: %s' % archive.metadata.hostname)
  846. print('Username: %s' % archive.metadata.username)
  847. print('Time (start): %s' % format_time(to_localtime(archive.ts)))
  848. print('Time (end): %s' % format_time(to_localtime(archive.ts_end)))
  849. print('Duration: %s' % archive.duration_from_meta)
  850. print('Number of files: %d' % stats.nfiles)
  851. print('Command line: %s' % format_cmdline(archive.metadata.cmdline))
  852. print(DASHES)
  853. print(STATS_HEADER)
  854. print(str(stats))
  855. print(str(cache))
  856. if self.exit_code:
  857. break
  858. if len(archive_names) - i:
  859. print()
  860. return self.exit_code
  861. def _info_repository(self, repository, key, cache):
  862. print('Repository ID: %s' % bin_to_hex(repository.id))
  863. if key.NAME == 'plaintext':
  864. encrypted = 'No'
  865. else:
  866. encrypted = 'Yes (%s)' % key.NAME
  867. print('Encrypted: %s' % encrypted)
  868. if key.NAME == 'key file':
  869. print('Key file: %s' % key.find_key())
  870. print('Cache: %s' % cache.path)
  871. print(DASHES)
  872. print(STATS_HEADER)
  873. print(str(cache))
  874. return self.exit_code
  875. @with_repository(exclusive=True)
  876. def do_prune(self, args, repository, manifest, key):
  877. """Prune repository archives according to specified rules"""
  878. if not any((args.secondly, args.minutely, args.hourly, args.daily,
  879. args.weekly, args.monthly, args.yearly, args.within)):
  880. self.print_error('At least one of the "keep-within", "keep-last", '
  881. '"keep-secondly", "keep-minutely", "keep-hourly", "keep-daily", '
  882. '"keep-weekly", "keep-monthly" or "keep-yearly" settings must be specified.')
  883. return self.exit_code
  884. archives_checkpoints = manifest.archives.list(sort_by=['ts'], reverse=True) # just a ArchiveInfo list
  885. if args.prefix:
  886. archives_checkpoints = [arch for arch in archives_checkpoints if arch.name.startswith(args.prefix)]
  887. is_checkpoint = re.compile(r'\.checkpoint(\.\d+)?$').search
  888. checkpoints = [arch for arch in archives_checkpoints if is_checkpoint(arch.name)]
  889. # keep the latest checkpoint, if there is no later non-checkpoint archive
  890. if archives_checkpoints and checkpoints and archives_checkpoints[0] is checkpoints[0]:
  891. keep_checkpoints = checkpoints[:1]
  892. else:
  893. keep_checkpoints = []
  894. checkpoints = set(checkpoints)
  895. # ignore all checkpoint archives to avoid keeping one (which is an incomplete backup)
  896. # that is newer than a successfully completed backup - and killing the successful backup.
  897. archives = [arch for arch in archives_checkpoints if arch not in checkpoints]
  898. keep = []
  899. if args.within:
  900. keep += prune_within(archives, args.within)
  901. if args.secondly:
  902. keep += prune_split(archives, '%Y-%m-%d %H:%M:%S', args.secondly, keep)
  903. if args.minutely:
  904. keep += prune_split(archives, '%Y-%m-%d %H:%M', args.minutely, keep)
  905. if args.hourly:
  906. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  907. if args.daily:
  908. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  909. if args.weekly:
  910. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  911. if args.monthly:
  912. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  913. if args.yearly:
  914. keep += prune_split(archives, '%Y', args.yearly, keep)
  915. to_delete = (set(archives) | checkpoints) - (set(keep) | set(keep_checkpoints))
  916. stats = Statistics()
  917. with Cache(repository, key, manifest, do_files=args.cache_files, lock_wait=self.lock_wait) as cache:
  918. list_logger = logging.getLogger('borg.output.list')
  919. for archive in archives_checkpoints:
  920. if archive in to_delete:
  921. if args.dry_run:
  922. if args.output_list:
  923. list_logger.info('Would prune: %s' % format_archive(archive))
  924. else:
  925. if args.output_list:
  926. list_logger.info('Pruning archive: %s' % format_archive(archive))
  927. Archive(repository, key, manifest, archive.name, cache).delete(stats, forced=args.forced)
  928. else:
  929. if args.output_list:
  930. list_logger.info('Keeping archive: %s' % format_archive(archive))
  931. if to_delete and not args.dry_run:
  932. manifest.write()
  933. repository.commit(save_space=args.save_space)
  934. cache.commit()
  935. if args.stats:
  936. log_multi(DASHES,
  937. STATS_HEADER,
  938. stats.summary.format(label='Deleted data:', stats=stats),
  939. str(cache),
  940. DASHES, logger=logging.getLogger('borg.output.stats'))
  941. return self.exit_code
  942. def do_upgrade(self, args):
  943. """upgrade a repository from a previous version"""
  944. # mainly for upgrades from Attic repositories,
  945. # but also supports borg 0.xx -> 1.0 upgrade.
  946. repo = AtticRepositoryUpgrader(args.location.path, create=False)
  947. try:
  948. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  949. except NotImplementedError as e:
  950. print("warning: %s" % e)
  951. repo = BorgRepositoryUpgrader(args.location.path, create=False)
  952. try:
  953. repo.upgrade(args.dry_run, inplace=args.inplace, progress=args.progress)
  954. except NotImplementedError as e:
  955. print("warning: %s" % e)
  956. return self.exit_code
  957. @with_repository(cache=True, exclusive=True)
  958. def do_recreate(self, args, repository, manifest, key, cache):
  959. """Re-create archives"""
  960. def interrupt(signal_num, stack_frame):
  961. if recreater.interrupt:
  962. print("\nReceived signal, again. I'm not deaf.", file=sys.stderr)
  963. else:
  964. print("\nReceived signal, will exit cleanly.", file=sys.stderr)
  965. recreater.interrupt = True
  966. msg = ("recreate is an experimental feature.\n"
  967. "Type 'YES' if you understand this and want to continue: ")
  968. if not yes(msg, false_msg="Aborting.", truish=('YES',),
  969. env_var_override='BORG_RECREATE_I_KNOW_WHAT_I_AM_DOING'):
  970. return EXIT_ERROR
  971. matcher, include_patterns = self.build_matcher(args.excludes, args.paths)
  972. self.output_list = args.output_list
  973. self.output_filter = args.output_filter
  974. recreater = ArchiveRecreater(repository, manifest, key, cache, matcher,
  975. exclude_caches=args.exclude_caches, exclude_if_present=args.exclude_if_present,
  976. keep_tag_files=args.keep_tag_files, chunker_params=args.chunker_params,
  977. compression=args.compression, compression_files=args.compression_files,
  978. always_recompress=args.always_recompress,
  979. progress=args.progress, stats=args.stats,
  980. file_status_printer=self.print_file_status,
  981. dry_run=args.dry_run)
  982. with signal_handler(signal.SIGTERM, interrupt), \
  983. signal_handler(signal.SIGINT, interrupt), \
  984. signal_handler(signal.SIGHUP, interrupt):
  985. if args.location.archive:
  986. name = args.location.archive
  987. if recreater.is_temporary_archive(name):
  988. self.print_error('Refusing to work on temporary archive of prior recreate: %s', name)
  989. return self.exit_code
  990. recreater.recreate(name, args.comment, args.target)
  991. else:
  992. if args.target is not None:
  993. self.print_error('--target: Need to specify single archive')
  994. return self.exit_code
  995. for archive in manifest.archives.list(sort_by=['ts']):
  996. name = archive.name
  997. if recreater.is_temporary_archive(name):
  998. continue
  999. print('Processing', name)
  1000. if not recreater.recreate(name, args.comment):
  1001. break
  1002. manifest.write()
  1003. repository.commit()
  1004. cache.commit()
  1005. return self.exit_code
  1006. @with_repository(manifest=False, exclusive=True)
  1007. def do_with_lock(self, args, repository):
  1008. """run a user specified command with the repository lock held"""
  1009. # for a new server, this will immediately take an exclusive lock.
  1010. # to support old servers, that do not have "exclusive" arg in open()
  1011. # RPC API, we also do it the old way:
  1012. # re-write manifest to start a repository transaction - this causes a
  1013. # lock upgrade to exclusive for remote (and also for local) repositories.
  1014. # by using manifest=False in the decorator, we avoid having to require
  1015. # the encryption key (and can operate just with encrypted data).
  1016. data = repository.get(Manifest.MANIFEST_ID)
  1017. repository.put(Manifest.MANIFEST_ID, data)
  1018. try:
  1019. # we exit with the return code we get from the subprocess
  1020. return subprocess.call([args.command] + args.args)
  1021. finally:
  1022. repository.rollback()
  1023. def do_debug_info(self, args):
  1024. """display system information for debugging / bug reports"""
  1025. print(sysinfo())
  1026. return EXIT_SUCCESS
  1027. @with_repository()
  1028. def do_debug_dump_archive_items(self, args, repository, manifest, key):
  1029. """dump (decrypted, decompressed) archive items metadata (not: data)"""
  1030. archive = Archive(repository, key, manifest, args.location.archive,
  1031. consider_part_files=args.consider_part_files)
  1032. for i, item_id in enumerate(archive.metadata.items):
  1033. _, data = key.decrypt(item_id, repository.get(item_id))
  1034. filename = '%06d_%s.items' % (i, bin_to_hex(item_id))
  1035. print('Dumping', filename)
  1036. with open(filename, 'wb') as fd:
  1037. fd.write(data)
  1038. print('Done.')
  1039. return EXIT_SUCCESS
  1040. @with_repository()
  1041. def do_debug_dump_repo_objs(self, args, repository, manifest, key):
  1042. """dump (decrypted, decompressed) repo objects"""
  1043. marker = None
  1044. i = 0
  1045. while True:
  1046. result = repository.list(limit=10000, marker=marker)
  1047. if not result:
  1048. break
  1049. marker = result[-1]
  1050. for id in result:
  1051. cdata = repository.get(id)
  1052. give_id = id if id != Manifest.MANIFEST_ID else None
  1053. _, data = key.decrypt(give_id, cdata)
  1054. filename = '%06d_%s.obj' % (i, bin_to_hex(id))
  1055. print('Dumping', filename)
  1056. with open(filename, 'wb') as fd:
  1057. fd.write(data)
  1058. i += 1
  1059. print('Done.')
  1060. return EXIT_SUCCESS
  1061. @with_repository(manifest=False)
  1062. def do_debug_get_obj(self, args, repository):
  1063. """get object contents from the repository and write it into file"""
  1064. hex_id = args.id
  1065. try:
  1066. id = unhexlify(hex_id)
  1067. except ValueError:
  1068. print("object id %s is invalid." % hex_id)
  1069. else:
  1070. try:
  1071. data = repository.get(id)
  1072. except Repository.ObjectNotFound:
  1073. print("object %s not found." % hex_id)
  1074. else:
  1075. with open(args.path, "wb") as f:
  1076. f.write(data)
  1077. print("object %s fetched." % hex_id)
  1078. return EXIT_SUCCESS
  1079. @with_repository(manifest=False, exclusive=True)
  1080. def do_debug_put_obj(self, args, repository):
  1081. """put file(s) contents into the repository"""
  1082. for path in args.paths:
  1083. with open(path, "rb") as f:
  1084. data = f.read()
  1085. h = hashlib.sha256(data) # XXX hardcoded
  1086. repository.put(h.digest(), data)
  1087. print("object %s put." % h.hexdigest())
  1088. repository.commit()
  1089. return EXIT_SUCCESS
  1090. @with_repository(manifest=False, exclusive=True)
  1091. def do_debug_delete_obj(self, args, repository):
  1092. """delete the objects with the given IDs from the repo"""
  1093. modified = False
  1094. for hex_id in args.ids:
  1095. try:
  1096. id = unhexlify(hex_id)
  1097. except ValueError:
  1098. print("object id %s is invalid." % hex_id)
  1099. else:
  1100. try:
  1101. repository.delete(id)
  1102. modified = True
  1103. print("object %s deleted." % hex_id)
  1104. except Repository.ObjectNotFound:
  1105. print("object %s not found." % hex_id)
  1106. if modified:
  1107. repository.commit()
  1108. print('Done.')
  1109. return EXIT_SUCCESS
  1110. @with_repository(manifest=False, exclusive=True, cache=True)
  1111. def do_debug_refcount_obj(self, args, repository, manifest, key, cache):
  1112. """display refcounts for the objects with the given IDs"""
  1113. for hex_id in args.ids:
  1114. try:
  1115. id = unhexlify(hex_id)
  1116. except ValueError:
  1117. print("object id %s is invalid." % hex_id)
  1118. else:
  1119. try:
  1120. refcount = cache.chunks[id][0]
  1121. print("object %s has %d referrers [info from chunks cache]." % (hex_id, refcount))
  1122. except KeyError:
  1123. print("object %s not found [info from chunks cache]." % hex_id)
  1124. return EXIT_SUCCESS
  1125. @with_repository(lock=False, manifest=False)
  1126. def do_break_lock(self, args, repository):
  1127. """Break the repository lock (e.g. in case it was left by a dead borg."""
  1128. repository.break_lock()
  1129. Cache.break_lock(repository)
  1130. return self.exit_code
  1131. helptext = collections.OrderedDict()
  1132. helptext['patterns'] = textwrap.dedent('''
  1133. Exclusion patterns support four separate styles, fnmatch, shell, regular
  1134. expressions and path prefixes. By default, fnmatch is used. If followed
  1135. by a colon (':') the first two characters of a pattern are used as a
  1136. style selector. Explicit style selection is necessary when a
  1137. non-default style is desired or when the desired pattern starts with
  1138. two alphanumeric characters followed by a colon (i.e. `aa:something/*`).
  1139. `Fnmatch <https://docs.python.org/3/library/fnmatch.html>`_, selector `fm:`
  1140. This is the default style. These patterns use a variant of shell
  1141. pattern syntax, with '*' matching any number of characters, '?'
  1142. matching any single character, '[...]' matching any single
  1143. character specified, including ranges, and '[!...]' matching any
  1144. character not specified. For the purpose of these patterns, the
  1145. path separator ('\\' for Windows and '/' on other systems) is not
  1146. treated specially. Wrap meta-characters in brackets for a literal
  1147. match (i.e. `[?]` to match the literal character `?`). For a path
  1148. to match a pattern, it must completely match from start to end, or
  1149. must match from the start to just before a path separator. Except
  1150. for the root path, paths will never end in the path separator when
  1151. matching is attempted. Thus, if a given pattern ends in a path
  1152. separator, a '*' is appended before matching is attempted.
  1153. Shell-style patterns, selector `sh:`
  1154. Like fnmatch patterns these are similar to shell patterns. The difference
  1155. is that the pattern may include `**/` for matching zero or more directory
  1156. levels, `*` for matching zero or more arbitrary characters with the
  1157. exception of any path separator.
  1158. Regular expressions, selector `re:`
  1159. Regular expressions similar to those found in Perl are supported. Unlike
  1160. shell patterns regular expressions are not required to match the complete
  1161. path and any substring match is sufficient. It is strongly recommended to
  1162. anchor patterns to the start ('^'), to the end ('$') or both. Path
  1163. separators ('\\' for Windows and '/' on other systems) in paths are
  1164. always normalized to a forward slash ('/') before applying a pattern. The
  1165. regular expression syntax is described in the `Python documentation for
  1166. the re module <https://docs.python.org/3/library/re.html>`_.
  1167. Prefix path, selector `pp:`
  1168. This pattern style is useful to match whole sub-directories. The pattern
  1169. `pp:/data/bar` matches `/data/bar` and everything therein.
  1170. Exclusions can be passed via the command line option `--exclude`. When used
  1171. from within a shell the patterns should be quoted to protect them from
  1172. expansion.
  1173. The `--exclude-from` option permits loading exclusion patterns from a text
  1174. file with one pattern per line. Lines empty or starting with the number sign
  1175. ('#') after removing whitespace on both ends are ignored. The optional style
  1176. selector prefix is also supported for patterns loaded from a file. Due to
  1177. whitespace removal paths with whitespace at the beginning or end can only be
  1178. excluded using regular expressions.
  1179. Examples::
  1180. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  1181. $ borg create -e '*.o' backup /
  1182. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  1183. # not '/home/user/importantjunk' or '/etc/junk':
  1184. $ borg create -e '/home/*/junk' backup /
  1185. # Exclude the contents of '/home/user/cache' but not the directory itself:
  1186. $ borg create -e /home/user/cache/ backup /
  1187. # The file '/home/user/cache/important' is *not* backed up:
  1188. $ borg create -e /home/user/cache/ backup / /home/user/cache/important
  1189. # The contents of directories in '/home' are not backed up when their name
  1190. # ends in '.tmp'
  1191. $ borg create --exclude 're:^/home/[^/]+\.tmp/' backup /
  1192. # Load exclusions from file
  1193. $ cat >exclude.txt <<EOF
  1194. # Comment line
  1195. /home/*/junk
  1196. *.tmp
  1197. fm:aa:something/*
  1198. re:^/home/[^/]\.tmp/
  1199. sh:/home/*/.thumbnails
  1200. EOF
  1201. $ borg create --exclude-from exclude.txt backup /\n\n''')
  1202. helptext['placeholders'] = textwrap.dedent('''
  1203. Repository (or Archive) URLs, --prefix and --remote-path values support these
  1204. placeholders:
  1205. {hostname}
  1206. The (short) hostname of the machine.
  1207. {fqdn}
  1208. The full name of the machine.
  1209. {now}
  1210. The current local date and time, by default in ISO-8601 format.
  1211. You can also supply your own `format string <https://docs.python.org/3.4/library/datetime.html#strftime-and-strptime-behavior>`_, e.g. {now:%Y-%m-%d_%H:%M:%S}
  1212. {utcnow}
  1213. The current UTC date and time, by default in ISO-8601 format.
  1214. You can also supply your own `format string <https://docs.python.org/3.4/library/datetime.html#strftime-and-strptime-behavior>`_, e.g. {utcnow:%Y-%m-%d_%H:%M:%S}
  1215. {user}
  1216. The user name (or UID, if no name is available) of the user running borg.
  1217. {pid}
  1218. The current process ID.
  1219. {borgversion}
  1220. The version of borg, e.g.: 1.0.8rc1
  1221. {borgmajor}
  1222. The version of borg, only the major version, e.g.: 1
  1223. {borgminor}
  1224. The version of borg, only major and minor version, e.g.: 1.0
  1225. {borgpatch}
  1226. The version of borg, only major, minor and patch version, e.g.: 1.0.8
  1227. Examples::
  1228. borg create /path/to/repo::{hostname}-{user}-{utcnow} ...
  1229. borg create /path/to/repo::{hostname}-{now:%Y-%m-%d_%H:%M:%S} ...
  1230. borg prune --prefix '{hostname}-' ...\n\n''')
  1231. helptext['compression'] = textwrap.dedent('''
  1232. Compression is off by default, if you want some, you have to specify what you want.
  1233. Valid compression specifiers are:
  1234. none
  1235. Do not compress. (default)
  1236. lz4
  1237. Use lz4 compression. High speed, low compression.
  1238. zlib[,L]
  1239. Use zlib ("gz") compression. Medium speed, medium compression.
  1240. If you do not explicitely give the compression level L (ranging from 0
  1241. to 9), it will use level 6.
  1242. Giving level 0 (means "no compression", but still has zlib protocol
  1243. overhead) is usually pointless, you better use "none" compression.
  1244. lzma[,L]
  1245. Use lzma ("xz") compression. Low speed, high compression.
  1246. If you do not explicitely give the compression level L (ranging from 0
  1247. to 9), it will use level 6.
  1248. Giving levels above 6 is pointless and counterproductive because it does
  1249. not compress better due to the buffer size used by borg - but it wastes
  1250. lots of CPU cycles and RAM.
  1251. auto,C[,L]
  1252. Use a built-in heuristic to decide per chunk whether to compress or not.
  1253. The heuristic tries with lz4 whether the data is compressible.
  1254. For incompressible data, it will not use compression (uses "none").
  1255. For compressible data, it uses the given C[,L] compression - with C[,L]
  1256. being any valid compression specifier.
  1257. The decision about which compression to use is done by borg like this:
  1258. 1. find a compression specifier (per file):
  1259. match the path/filename against all patterns in all --compression-from
  1260. files (if any). If a pattern matches, use the compression spec given for
  1261. that pattern. If no pattern matches (and also if you do not give any
  1262. --compression-from option), default to the compression spec given by
  1263. --compression. See docs/misc/compression.conf for an example config.
  1264. 2. if the found compression spec is not "auto", the decision is taken:
  1265. use the found compression spec.
  1266. 3. if the found compression spec is "auto", test compressibility of each
  1267. chunk using lz4.
  1268. If it is compressible, use the C,[L] compression spec given within the
  1269. "auto" specifier. If it is not compressible, use no compression.
  1270. Examples::
  1271. borg create --compression lz4 REPO::ARCHIVE data
  1272. borg create --compression zlib REPO::ARCHIVE data
  1273. borg create --compression zlib,1 REPO::ARCHIVE data
  1274. borg create --compression auto,lzma,6 REPO::ARCHIVE data
  1275. borg create --compression-from compression.conf --compression auto,lzma ...
  1276. compression.conf has entries like::
  1277. # example config file for --compression-from option
  1278. #
  1279. # Format of non-comment / non-empty lines:
  1280. # <compression-spec>:<path/filename pattern>
  1281. # compression-spec is same format as for --compression option
  1282. # path/filename pattern is same format as for --exclude option
  1283. none:*.gz
  1284. none:*.zip
  1285. none:*.mp3
  1286. none:*.ogg
  1287. General remarks:
  1288. It is no problem to mix different compression methods in one repo,
  1289. deduplication is done on the source data chunks (not on the compressed
  1290. or encrypted data).
  1291. If some specific chunk was once compressed and stored into the repo, creating
  1292. another backup that also uses this chunk will not change the stored chunk.
  1293. So if you use different compression specs for the backups, whichever stores a
  1294. chunk first determines its compression. See also borg recreate.\n\n''')
  1295. def do_help(self, parser, commands, args):
  1296. if not args.topic:
  1297. parser.print_help()
  1298. elif args.topic in self.helptext:
  1299. print(self.helptext[args.topic])
  1300. elif args.topic in commands:
  1301. if args.epilog_only:
  1302. print(commands[args.topic].epilog)
  1303. elif args.usage_only:
  1304. commands[args.topic].epilog = None
  1305. commands[args.topic].print_help()
  1306. else:
  1307. commands[args.topic].print_help()
  1308. else:
  1309. parser.error('No help available on %s' % (args.topic,))
  1310. return self.exit_code
  1311. def preprocess_args(self, args):
  1312. deprecations = [
  1313. # ('--old', '--new', 'Warning: "--old" has been deprecated. Use "--new" instead.'),
  1314. ('--list-format', '--format', 'Warning: "--list-format" has been deprecated. Use "--format" instead.'),
  1315. ]
  1316. for i, arg in enumerate(args[:]):
  1317. for old_name, new_name, warning in deprecations:
  1318. if arg.startswith(old_name):
  1319. args[i] = arg.replace(old_name, new_name)
  1320. print(warning, file=sys.stderr)
  1321. return args
  1322. def build_parser(self, prog=None):
  1323. common_parser = argparse.ArgumentParser(add_help=False, prog=prog)
  1324. common_group = common_parser.add_argument_group('Common options')
  1325. common_group.add_argument('-h', '--help', action='help', help='show this help message and exit')
  1326. common_group.add_argument('--critical', dest='log_level',
  1327. action='store_const', const='critical', default='warning',
  1328. help='work on log level CRITICAL')
  1329. common_group.add_argument('--error', dest='log_level',
  1330. action='store_const', const='error', default='warning',
  1331. help='work on log level ERROR')
  1332. common_group.add_argument('--warning', dest='log_level',
  1333. action='store_const', const='warning', default='warning',
  1334. help='work on log level WARNING (default)')
  1335. common_group.add_argument('--info', '-v', '--verbose', dest='log_level',
  1336. action='store_const', const='info', default='warning',
  1337. help='work on log level INFO')
  1338. common_group.add_argument('--debug', dest='log_level',
  1339. action='store_const', const='debug', default='warning',
  1340. help='enable debug output, work on log level DEBUG')
  1341. common_group.add_argument('--debug-topic', dest='debug_topics',
  1342. action='append', metavar='TOPIC', default=[],
  1343. help='enable TOPIC debugging (can be specified multiple times). '
  1344. 'The logger path is borg.debug.<TOPIC> if TOPIC is not fully qualified.')
  1345. common_group.add_argument('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1,
  1346. help='wait for the lock, but max. N seconds (default: %(default)d).')
  1347. common_group.add_argument('--show-version', dest='show_version', action='store_true', default=False,
  1348. help='show/log the borg version')
  1349. common_group.add_argument('--show-rc', dest='show_rc', action='store_true', default=False,
  1350. help='show/log the return code (rc)')
  1351. common_group.add_argument('--no-files-cache', dest='cache_files', action='store_false',
  1352. help='do not load/update the file metadata cache used to detect unchanged files')
  1353. common_group.add_argument('--umask', dest='umask', type=lambda s: int(s, 8), default=UMASK_DEFAULT, metavar='M',
  1354. help='set umask to M (local and remote, default: %(default)04o)')
  1355. common_group.add_argument('--remote-path', dest='remote_path', metavar='PATH',
  1356. help='set remote path to executable (default: "borg")')
  1357. common_group.add_argument('--remote-ratelimit', dest='remote_ratelimit', type=int, metavar='rate',
  1358. help='set remote network upload rate limit in kiByte/s (default: 0=unlimited)')
  1359. common_group.add_argument('--consider-part-files', dest='consider_part_files',
  1360. action='store_true', default=False,
  1361. help='treat part files like normal files (e.g. to list/extract them)')
  1362. parser = argparse.ArgumentParser(prog=prog, description='Borg - Deduplicated Backups')
  1363. parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__,
  1364. help='show version number and exit')
  1365. subparsers = parser.add_subparsers(title='required arguments', metavar='<command>')
  1366. serve_epilog = textwrap.dedent("""
  1367. This command starts a repository server process. This command is usually not used manually.
  1368. """)
  1369. subparser = subparsers.add_parser('serve', parents=[common_parser], add_help=False,
  1370. description=self.do_serve.__doc__, epilog=serve_epilog,
  1371. formatter_class=argparse.RawDescriptionHelpFormatter,
  1372. help='start repository server process')
  1373. subparser.set_defaults(func=self.do_serve)
  1374. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  1375. metavar='PATH', help='restrict repository access to PATH. '
  1376. 'Can be specified multiple times to allow the client access to several directories. '
  1377. 'Access to all sub-directories is granted implicitly; PATH doesn\'t need to directly point to a repository.')
  1378. subparser.add_argument('--append-only', dest='append_only', action='store_true',
  1379. help='only allow appending to repository segment files')
  1380. init_epilog = textwrap.dedent("""
  1381. This command initializes an empty repository. A repository is a filesystem
  1382. directory containing the deduplicated data from zero or more archives.
  1383. Encryption can be enabled at repository init time (the default).
  1384. It is not recommended to disable encryption. Repository encryption protects you
  1385. e.g. against the case that an attacker has access to your backup repository.
  1386. But be careful with the key / the passphrase:
  1387. If you want "passphrase-only" security, use the repokey mode. The key will
  1388. be stored inside the repository (in its "config" file). In above mentioned
  1389. attack scenario, the attacker will have the key (but not the passphrase).
  1390. If you want "passphrase and having-the-key" security, use the keyfile mode.
  1391. The key will be stored in your home directory (in .config/borg/keys). In
  1392. the attack scenario, the attacker who has just access to your repo won't have
  1393. the key (and also not the passphrase).
  1394. Make a backup copy of the key file (keyfile mode) or repo config file
  1395. (repokey mode) and keep it at a safe place, so you still have the key in
  1396. case it gets corrupted or lost. Also keep the passphrase at a safe place.
  1397. The backup that is encrypted with that key won't help you with that, of course.
  1398. Make sure you use a good passphrase. Not too short, not too simple. The real
  1399. encryption / decryption key is encrypted with / locked by your passphrase.
  1400. If an attacker gets your key, he can't unlock and use it without knowing the
  1401. passphrase.
  1402. Be careful with special or non-ascii characters in your passphrase:
  1403. - Borg processes the passphrase as unicode (and encodes it as utf-8),
  1404. so it does not have problems dealing with even the strangest characters.
  1405. - BUT: that does not necessarily apply to your OS / VM / keyboard configuration.
  1406. So better use a long passphrase made from simple ascii chars than one that
  1407. includes non-ascii stuff or characters that are hard/impossible to enter on
  1408. a different keyboard layout.
  1409. You can change your passphrase for existing repos at any time, it won't affect
  1410. the encryption/decryption key or other secrets.
  1411. When encrypting, AES-CTR-256 is used for encryption, and HMAC-SHA256 for
  1412. authentication. Hardware acceleration will be used automatically.
  1413. """)
  1414. subparser = subparsers.add_parser('init', parents=[common_parser], add_help=False,
  1415. description=self.do_init.__doc__, epilog=init_epilog,
  1416. formatter_class=argparse.RawDescriptionHelpFormatter,
  1417. help='initialize empty repository')
  1418. subparser.set_defaults(func=self.do_init)
  1419. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1420. type=location_validator(archive=False),
  1421. help='repository to create')
  1422. subparser.add_argument('-e', '--encryption', dest='encryption',
  1423. choices=('none', 'keyfile', 'repokey'), default='repokey',
  1424. help='select encryption key mode (default: "%(default)s")')
  1425. subparser.add_argument('-a', '--append-only', dest='append_only', action='store_true',
  1426. help='create an append-only mode repository')
  1427. check_epilog = textwrap.dedent("""
  1428. The check command verifies the consistency of a repository and the corresponding archives.
  1429. First, the underlying repository data files are checked:
  1430. - For all segments the segment magic (header) is checked
  1431. - For all objects stored in the segments, all metadata (e.g. crc and size) and
  1432. all data is read. The read data is checked by size and CRC. Bit rot and other
  1433. types of accidental damage can be detected this way.
  1434. - If we are in repair mode and a integrity error is detected for a segment,
  1435. we try to recover as many objects from the segment as possible.
  1436. - In repair mode, it makes sure that the index is consistent with the data
  1437. stored in the segments.
  1438. - If you use a remote repo server via ssh:, the repo check is executed on the
  1439. repo server without causing significant network traffic.
  1440. - The repository check can be skipped using the --archives-only option.
  1441. Second, the consistency and correctness of the archive metadata is verified:
  1442. - Is the repo manifest present? If not, it is rebuilt from archive metadata
  1443. chunks (this requires reading and decrypting of all metadata and data).
  1444. - Check if archive metadata chunk is present. if not, remove archive from
  1445. manifest.
  1446. - For all files (items) in the archive, for all chunks referenced by these
  1447. files, check if chunk is present.
  1448. If a chunk is not present and we are in repair mode, replace it with a same-size
  1449. replacement chunk of zeros.
  1450. If a previously lost chunk reappears (e.g. via a later backup) and we are in
  1451. repair mode, the all-zero replacement chunk will be replaced by the correct chunk.
  1452. This requires reading of archive and file metadata, but not data.
  1453. - If we are in repair mode and we checked all the archives: delete orphaned
  1454. chunks from the repo.
  1455. - if you use a remote repo server via ssh:, the archive check is executed on
  1456. the client machine (because if encryption is enabled, the checks will require
  1457. decryption and this is always done client-side, because key access will be
  1458. required).
  1459. - The archive checks can be time consuming, they can be skipped using the
  1460. --repository-only option.
  1461. The --verify-data option will perform a full integrity verification (as opposed to
  1462. checking the CRC32 of the segment) of data, which means reading the data from the
  1463. repository, decrypting and decompressing it. This is a cryptographic verification,
  1464. which will detect (accidental) corruption. For encrypted repositories it is
  1465. tamper-resistant as well, unless the attacker has access to the keys.
  1466. It is also very slow.
  1467. """)
  1468. subparser = subparsers.add_parser('check', parents=[common_parser], add_help=False,
  1469. description=self.do_check.__doc__,
  1470. epilog=check_epilog,
  1471. formatter_class=argparse.RawDescriptionHelpFormatter,
  1472. help='verify repository')
  1473. subparser.set_defaults(func=self.do_check)
  1474. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  1475. type=location_validator(),
  1476. help='repository or archive to check consistency of')
  1477. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  1478. default=False,
  1479. help='only perform repository checks')
  1480. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  1481. default=False,
  1482. help='only perform archives checks')
  1483. subparser.add_argument('--verify-data', dest='verify_data', action='store_true',
  1484. default=False,
  1485. help='perform cryptographic archive data integrity verification '
  1486. '(conflicts with --repository-only)')
  1487. subparser.add_argument('--repair', dest='repair', action='store_true',
  1488. default=False,
  1489. help='attempt to repair any inconsistencies found')
  1490. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1491. default=False,
  1492. help='work slower, but using less space')
  1493. subparser.add_argument('-p', '--progress', dest='progress',
  1494. action='store_true', default=False,
  1495. help="""show progress display while checking""")
  1496. self.add_archives_filters_args(subparser)
  1497. change_passphrase_epilog = textwrap.dedent("""
  1498. The key files used for repository encryption are optionally passphrase
  1499. protected. This command can be used to change this passphrase.
  1500. """)
  1501. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser], add_help=False,
  1502. description=self.do_change_passphrase.__doc__,
  1503. epilog=change_passphrase_epilog,
  1504. formatter_class=argparse.RawDescriptionHelpFormatter,
  1505. help='change repository passphrase')
  1506. subparser.set_defaults(func=self.do_change_passphrase)
  1507. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1508. type=location_validator(archive=False))
  1509. subparser = subparsers.add_parser('key', add_help=False,
  1510. description="Manage a keyfile or repokey of a repository",
  1511. epilog="",
  1512. formatter_class=argparse.RawDescriptionHelpFormatter,
  1513. help='manage repository key')
  1514. key_parsers = subparser.add_subparsers(title='required arguments', metavar='<command>')
  1515. key_export_epilog = textwrap.dedent("""
  1516. If repository encryption is used, the repository is inaccessible
  1517. without the key. This command allows to backup this essential key.
  1518. There are two backup formats. The normal backup format is suitable for
  1519. digital storage as a file. The ``--paper`` backup format is optimized
  1520. for printing and typing in while importing, with per line checks to
  1521. reduce problems with manual input.
  1522. For repositories using keyfile encryption the key is saved locally
  1523. on the system that is capable of doing backups. To guard against loss
  1524. of this key, the key needs to be backed up independently of the main
  1525. data backup.
  1526. For repositories using the repokey encryption the key is saved in the
  1527. repository in the config file. A backup is thus not strictly needed,
  1528. but guards against the repository becoming inaccessible if the file
  1529. is damaged for some reason.
  1530. """)
  1531. subparser = key_parsers.add_parser('export', parents=[common_parser], add_help=False,
  1532. description=self.do_key_export.__doc__,
  1533. epilog=key_export_epilog,
  1534. formatter_class=argparse.RawDescriptionHelpFormatter,
  1535. help='export repository key for backup')
  1536. subparser.set_defaults(func=self.do_key_export)
  1537. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1538. type=location_validator(archive=False))
  1539. subparser.add_argument('path', metavar='PATH', nargs='?', type=str,
  1540. help='where to store the backup')
  1541. subparser.add_argument('--paper', dest='paper', action='store_true',
  1542. default=False,
  1543. help='Create an export suitable for printing and later type-in')
  1544. key_import_epilog = textwrap.dedent("""
  1545. This command allows to restore a key previously backed up with the
  1546. export command.
  1547. If the ``--paper`` option is given, the import will be an interactive
  1548. process in which each line is checked for plausibility before
  1549. proceeding to the next line. For this format PATH must not be given.
  1550. """)
  1551. subparser = key_parsers.add_parser('import', parents=[common_parser], add_help=False,
  1552. description=self.do_key_import.__doc__,
  1553. epilog=key_import_epilog,
  1554. formatter_class=argparse.RawDescriptionHelpFormatter,
  1555. help='import repository key from backup')
  1556. subparser.set_defaults(func=self.do_key_import)
  1557. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1558. type=location_validator(archive=False))
  1559. subparser.add_argument('path', metavar='PATH', nargs='?', type=str,
  1560. help='path to the backup')
  1561. subparser.add_argument('--paper', dest='paper', action='store_true',
  1562. default=False,
  1563. help='interactively import from a backup done with --paper')
  1564. migrate_to_repokey_epilog = textwrap.dedent("""
  1565. This command migrates a repository from passphrase mode (not supported any
  1566. more) to repokey mode.
  1567. You will be first asked for the repository passphrase (to open it in passphrase
  1568. mode). This is the same passphrase as you used to use for this repo before 1.0.
  1569. It will then derive the different secrets from this passphrase.
  1570. Then you will be asked for a new passphrase (twice, for safety). This
  1571. passphrase will be used to protect the repokey (which contains these same
  1572. secrets in encrypted form). You may use the same passphrase as you used to
  1573. use, but you may also use a different one.
  1574. After migrating to repokey mode, you can change the passphrase at any time.
  1575. But please note: the secrets will always stay the same and they could always
  1576. be derived from your (old) passphrase-mode passphrase.
  1577. """)
  1578. subparser = subparsers.add_parser('migrate-to-repokey', parents=[common_parser], add_help=False,
  1579. description=self.do_migrate_to_repokey.__doc__,
  1580. epilog=migrate_to_repokey_epilog,
  1581. formatter_class=argparse.RawDescriptionHelpFormatter,
  1582. help='migrate passphrase-mode repository to repokey')
  1583. subparser.set_defaults(func=self.do_migrate_to_repokey)
  1584. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1585. type=location_validator(archive=False))
  1586. create_epilog = textwrap.dedent("""
  1587. This command creates a backup archive containing all files found while recursively
  1588. traversing all paths specified. The archive will consume almost no disk space for
  1589. files or parts of files that have already been stored in other archives.
  1590. The archive name needs to be unique. It must not end in '.checkpoint' or
  1591. '.checkpoint.N' (with N being a number), because these names are used for
  1592. checkpoints and treated in special ways.
  1593. In the archive name, you may use the following placeholders:
  1594. {now}, {utcnow}, {fqdn}, {hostname}, {user} and some others.
  1595. To speed up pulling backups over sshfs and similar network file systems which do
  1596. not provide correct inode information the --ignore-inode flag can be used. This
  1597. potentially decreases reliability of change detection, while avoiding always reading
  1598. all files on these file systems.
  1599. See the output of the "borg help patterns" command for more help on exclude patterns.
  1600. See the output of the "borg help placeholders" command for more help on placeholders.
  1601. """)
  1602. subparser = subparsers.add_parser('create', parents=[common_parser], add_help=False,
  1603. description=self.do_create.__doc__,
  1604. epilog=create_epilog,
  1605. formatter_class=argparse.RawDescriptionHelpFormatter,
  1606. help='create backup')
  1607. subparser.set_defaults(func=self.do_create)
  1608. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1609. action='store_true', default=False,
  1610. help='do not create a backup archive')
  1611. subparser.add_argument('-s', '--stats', dest='stats',
  1612. action='store_true', default=False,
  1613. help='print statistics for the created archive')
  1614. subparser.add_argument('-p', '--progress', dest='progress',
  1615. action='store_true', default=False,
  1616. help='show progress display while creating the archive, showing Original, '
  1617. 'Compressed and Deduplicated sizes, followed by the Number of files seen '
  1618. 'and the path being processed, default: %(default)s')
  1619. subparser.add_argument('--list', dest='output_list',
  1620. action='store_true', default=False,
  1621. help='output verbose list of items (files, dirs, ...)')
  1622. subparser.add_argument('--filter', dest='output_filter', metavar='STATUSCHARS',
  1623. help='only display items with the given status characters')
  1624. exclude_group = subparser.add_argument_group('Exclusion options')
  1625. exclude_group.add_argument('-e', '--exclude', dest='excludes',
  1626. type=parse_pattern, action='append',
  1627. metavar="PATTERN", help='exclude paths matching PATTERN')
  1628. exclude_group.add_argument('--exclude-from', dest='exclude_files',
  1629. type=argparse.FileType('r'), action='append',
  1630. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1631. exclude_group.add_argument('--exclude-caches', dest='exclude_caches',
  1632. action='store_true', default=False,
  1633. help='exclude directories that contain a CACHEDIR.TAG file ('
  1634. 'http://www.brynosaurus.com/cachedir/spec.html)')
  1635. exclude_group.add_argument('--exclude-if-present', dest='exclude_if_present',
  1636. metavar='FILENAME', action='append', type=str,
  1637. help='exclude directories that contain the specified file')
  1638. exclude_group.add_argument('--keep-tag-files', dest='keep_tag_files',
  1639. action='store_true', default=False,
  1640. help='keep tag files of excluded caches/directories')
  1641. fs_group = subparser.add_argument_group('Filesystem options')
  1642. fs_group.add_argument('-x', '--one-file-system', dest='one_file_system',
  1643. action='store_true', default=False,
  1644. help='stay in same file system, do not cross mount points')
  1645. fs_group.add_argument('--numeric-owner', dest='numeric_owner',
  1646. action='store_true', default=False,
  1647. help='only store numeric user and group identifiers')
  1648. fs_group.add_argument('--ignore-inode', dest='ignore_inode',
  1649. action='store_true', default=False,
  1650. help='ignore inode data in the file metadata cache used to detect unchanged files.')
  1651. fs_group.add_argument('--read-special', dest='read_special',
  1652. action='store_true', default=False,
  1653. help='open and read block and char device files as well as FIFOs as if they were '
  1654. 'regular files. Also follows symlinks pointing to these kinds of files.')
  1655. archive_group = subparser.add_argument_group('Archive options')
  1656. archive_group.add_argument('--comment', dest='comment', metavar='COMMENT', default='',
  1657. help='add a comment text to the archive')
  1658. archive_group.add_argument('--timestamp', dest='timestamp',
  1659. type=timestamp, default=None,
  1660. metavar='yyyy-mm-ddThh:mm:ss',
  1661. help='manually specify the archive creation date/time (UTC). '
  1662. 'alternatively, give a reference file/directory.')
  1663. archive_group.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  1664. type=int, default=1800, metavar='SECONDS',
  1665. help='write checkpoint every SECONDS seconds (Default: 1800)')
  1666. archive_group.add_argument('--chunker-params', dest='chunker_params',
  1667. type=ChunkerParams, default=CHUNKER_PARAMS,
  1668. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  1669. help='specify the chunker parameters. default: %d,%d,%d,%d' % CHUNKER_PARAMS)
  1670. archive_group.add_argument('-C', '--compression', dest='compression',
  1671. type=CompressionSpec, default=dict(name='none'), metavar='COMPRESSION',
  1672. help='select compression algorithm, see the output of the '
  1673. '"borg help compression" command for details.')
  1674. archive_group.add_argument('--compression-from', dest='compression_files',
  1675. type=argparse.FileType('r'), action='append',
  1676. metavar='COMPRESSIONCONFIG',
  1677. help='read compression patterns from COMPRESSIONCONFIG, see the output of the '
  1678. '"borg help compression" command for details.')
  1679. subparser.add_argument('location', metavar='ARCHIVE',
  1680. type=location_validator(archive=True),
  1681. help='name of archive to create (must be also a valid directory name)')
  1682. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  1683. help='paths to archive')
  1684. extract_epilog = textwrap.dedent("""
  1685. This command extracts the contents of an archive. By default the entire
  1686. archive is extracted but a subset of files and directories can be selected
  1687. by passing a list of ``PATHs`` as arguments. The file selection can further
  1688. be restricted by using the ``--exclude`` option.
  1689. See the output of the "borg help patterns" command for more help on exclude patterns.
  1690. By using ``--dry-run``, you can do all extraction steps except actually writing the
  1691. output data: reading metadata and data chunks from the repo, checking the hash/hmac,
  1692. decrypting, decompressing.
  1693. """)
  1694. subparser = subparsers.add_parser('extract', parents=[common_parser], add_help=False,
  1695. description=self.do_extract.__doc__,
  1696. epilog=extract_epilog,
  1697. formatter_class=argparse.RawDescriptionHelpFormatter,
  1698. help='extract archive contents')
  1699. subparser.set_defaults(func=self.do_extract)
  1700. subparser.add_argument('-p', '--progress', dest='progress',
  1701. action='store_true', default=False,
  1702. help='show progress while extracting (may be slower)')
  1703. subparser.add_argument('--list', dest='output_list',
  1704. action='store_true', default=False,
  1705. help='output verbose list of items (files, dirs, ...)')
  1706. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1707. default=False, action='store_true',
  1708. help='do not actually change any files')
  1709. subparser.add_argument('-e', '--exclude', dest='excludes',
  1710. type=parse_pattern, action='append',
  1711. metavar="PATTERN", help='exclude paths matching PATTERN')
  1712. subparser.add_argument('--exclude-from', dest='exclude_files',
  1713. type=argparse.FileType('r'), action='append',
  1714. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1715. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1716. action='store_true', default=False,
  1717. help='only obey numeric user and group identifiers')
  1718. subparser.add_argument('--strip-components', dest='strip_components',
  1719. type=int, default=0, metavar='NUMBER',
  1720. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  1721. subparser.add_argument('--stdout', dest='stdout',
  1722. action='store_true', default=False,
  1723. help='write all extracted data to stdout')
  1724. subparser.add_argument('--sparse', dest='sparse',
  1725. action='store_true', default=False,
  1726. help='create holes in output sparse file from all-zero chunks')
  1727. subparser.add_argument('location', metavar='ARCHIVE',
  1728. type=location_validator(archive=True),
  1729. help='archive to extract')
  1730. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1731. help='paths to extract; patterns are supported')
  1732. diff_epilog = textwrap.dedent("""
  1733. This command finds differences (file contents, user/group/mode) between archives.
  1734. A repository location and an archive name must be specified for REPO_ARCHIVE1.
  1735. ARCHIVE2 is just another archive name in same repository (no repository location
  1736. allowed).
  1737. For archives created with Borg 1.1 or newer diff automatically detects whether
  1738. the archives are created with the same chunker params. If so, only chunk IDs
  1739. are compared, which is very fast.
  1740. For archives prior to Borg 1.1 chunk contents are compared by default.
  1741. If you did not create the archives with different chunker params,
  1742. pass --same-chunker-params.
  1743. Note that the chunker params changed from Borg 0.xx to 1.0.
  1744. See the output of the "borg help patterns" command for more help on exclude patterns.
  1745. """)
  1746. subparser = subparsers.add_parser('diff', parents=[common_parser], add_help=False,
  1747. description=self.do_diff.__doc__,
  1748. epilog=diff_epilog,
  1749. formatter_class=argparse.RawDescriptionHelpFormatter,
  1750. help='find differences in archive contents')
  1751. subparser.set_defaults(func=self.do_diff)
  1752. subparser.add_argument('-e', '--exclude', dest='excludes',
  1753. type=parse_pattern, action='append',
  1754. metavar="PATTERN", help='exclude paths matching PATTERN')
  1755. subparser.add_argument('--exclude-from', dest='exclude_files',
  1756. type=argparse.FileType('r'), action='append',
  1757. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1758. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  1759. action='store_true', default=False,
  1760. help='only consider numeric user and group identifiers')
  1761. subparser.add_argument('--same-chunker-params', dest='same_chunker_params',
  1762. action='store_true', default=False,
  1763. help='Override check of chunker parameters.')
  1764. subparser.add_argument('--sort', dest='sort',
  1765. action='store_true', default=False,
  1766. help='Sort the output lines by file path.')
  1767. subparser.add_argument('location', metavar='REPO_ARCHIVE1',
  1768. type=location_validator(archive=True),
  1769. help='repository location and ARCHIVE1 name')
  1770. subparser.add_argument('archive2', metavar='ARCHIVE2',
  1771. type=archivename_validator(),
  1772. help='ARCHIVE2 name (no repository location allowed)')
  1773. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1774. help='paths of items inside the archives to compare; patterns are supported')
  1775. rename_epilog = textwrap.dedent("""
  1776. This command renames an archive in the repository.
  1777. This results in a different archive ID.
  1778. """)
  1779. subparser = subparsers.add_parser('rename', parents=[common_parser], add_help=False,
  1780. description=self.do_rename.__doc__,
  1781. epilog=rename_epilog,
  1782. formatter_class=argparse.RawDescriptionHelpFormatter,
  1783. help='rename archive')
  1784. subparser.set_defaults(func=self.do_rename)
  1785. subparser.add_argument('location', metavar='ARCHIVE',
  1786. type=location_validator(archive=True),
  1787. help='archive to rename')
  1788. subparser.add_argument('name', metavar='NEWNAME',
  1789. type=archivename_validator(),
  1790. help='the new archive name to use')
  1791. delete_epilog = textwrap.dedent("""
  1792. This command deletes an archive from the repository or the complete repository.
  1793. Disk space is reclaimed accordingly. If you delete the complete repository, the
  1794. local cache for it (if any) is also deleted.
  1795. """)
  1796. subparser = subparsers.add_parser('delete', parents=[common_parser], add_help=False,
  1797. description=self.do_delete.__doc__,
  1798. epilog=delete_epilog,
  1799. formatter_class=argparse.RawDescriptionHelpFormatter,
  1800. help='delete archive')
  1801. subparser.set_defaults(func=self.do_delete)
  1802. subparser.add_argument('-p', '--progress', dest='progress',
  1803. action='store_true', default=False,
  1804. help="""show progress display while deleting a single archive""")
  1805. subparser.add_argument('-s', '--stats', dest='stats',
  1806. action='store_true', default=False,
  1807. help='print statistics for the deleted archive')
  1808. subparser.add_argument('-c', '--cache-only', dest='cache_only',
  1809. action='store_true', default=False,
  1810. help='delete only the local cache for the given repository')
  1811. subparser.add_argument('--force', dest='forced',
  1812. action='store_true', default=False,
  1813. help='force deletion of corrupted archives')
  1814. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1815. default=False,
  1816. help='work slower, but using less space')
  1817. subparser.add_argument('location', metavar='TARGET', nargs='?', default='',
  1818. type=location_validator(),
  1819. help='archive or repository to delete')
  1820. self.add_archives_filters_args(subparser)
  1821. list_epilog = textwrap.dedent("""
  1822. This command lists the contents of a repository or an archive.
  1823. See the "borg help patterns" command for more help on exclude patterns.
  1824. The following keys are available for --format:
  1825. """) + BaseFormatter.keys_help() + textwrap.dedent("""
  1826. -- Keys for listing repository archives:
  1827. """) + ArchiveFormatter.keys_help() + textwrap.dedent("""
  1828. -- Keys for listing archive files:
  1829. """) + ItemFormatter.keys_help()
  1830. subparser = subparsers.add_parser('list', parents=[common_parser], add_help=False,
  1831. description=self.do_list.__doc__,
  1832. epilog=list_epilog,
  1833. formatter_class=argparse.RawDescriptionHelpFormatter,
  1834. help='list archive or repository contents')
  1835. subparser.set_defaults(func=self.do_list)
  1836. subparser.add_argument('--short', dest='short',
  1837. action='store_true', default=False,
  1838. help='only print file/directory names, nothing else')
  1839. subparser.add_argument('--format', '--list-format', dest='format', type=str,
  1840. help="""specify format for file listing
  1841. (default: "{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NL}")""")
  1842. subparser.add_argument('-e', '--exclude', dest='excludes',
  1843. type=parse_pattern, action='append',
  1844. metavar="PATTERN", help='exclude paths matching PATTERN')
  1845. subparser.add_argument('--exclude-from', dest='exclude_files',
  1846. type=argparse.FileType('r'), action='append',
  1847. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  1848. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  1849. type=location_validator(),
  1850. help='repository/archive to list contents of')
  1851. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  1852. help='paths to list; patterns are supported')
  1853. self.add_archives_filters_args(subparser)
  1854. mount_epilog = textwrap.dedent("""
  1855. This command mounts an archive as a FUSE filesystem. This can be useful for
  1856. browsing an archive or restoring individual files. Unless the ``--foreground``
  1857. option is given the command will run in the background until the filesystem
  1858. is ``umounted``.
  1859. The command ``borgfs`` provides a wrapper for ``borg mount``. This can also be
  1860. used in fstab entries:
  1861. ``/path/to/repo /mnt/point fuse.borgfs defaults,noauto 0 0``
  1862. To allow a regular user to use fstab entries, add the ``user`` option:
  1863. ``/path/to/repo /mnt/point fuse.borgfs defaults,noauto,user 0 0``
  1864. For mount options, see the fuse(8) manual page. Additional mount options
  1865. supported by borg:
  1866. - versions: when used with a repository mount, this gives a merged, versioned
  1867. view of the files in the archives. EXPERIMENTAL, layout may change in future.
  1868. - allow_damaged_files: by default damaged files (where missing chunks were
  1869. replaced with runs of zeros by borg check --repair) are not readable and
  1870. return EIO (I/O error). Set this option to read such files.
  1871. The BORG_MOUNT_DATA_CACHE_ENTRIES environment variable is meant for advanced users
  1872. to tweak the performance. It sets the number of cached data chunks; additional
  1873. memory usage can be up to ~8 MiB times this number. The default is the number
  1874. of CPU cores.
  1875. """)
  1876. subparser = subparsers.add_parser('mount', parents=[common_parser], add_help=False,
  1877. description=self.do_mount.__doc__,
  1878. epilog=mount_epilog,
  1879. formatter_class=argparse.RawDescriptionHelpFormatter,
  1880. help='mount repository')
  1881. subparser.set_defaults(func=self.do_mount)
  1882. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  1883. help='repository/archive to mount')
  1884. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  1885. help='where to mount filesystem')
  1886. subparser.add_argument('-f', '--foreground', dest='foreground',
  1887. action='store_true', default=False,
  1888. help='stay in foreground, do not daemonize')
  1889. subparser.add_argument('-o', dest='options', type=str,
  1890. help='Extra mount options')
  1891. self.add_archives_filters_args(subparser)
  1892. info_epilog = textwrap.dedent("""
  1893. This command displays detailed information about the specified archive or repository.
  1894. Please note that the deduplicated sizes of the individual archives do not add
  1895. up to the deduplicated size of the repository ("all archives"), because the two
  1896. are meaning different things:
  1897. This archive / deduplicated size = amount of data stored ONLY for this archive
  1898. = unique chunks of this archive.
  1899. All archives / deduplicated size = amount of data stored in the repo
  1900. = all chunks in the repository.
  1901. """)
  1902. subparser = subparsers.add_parser('info', parents=[common_parser], add_help=False,
  1903. description=self.do_info.__doc__,
  1904. epilog=info_epilog,
  1905. formatter_class=argparse.RawDescriptionHelpFormatter,
  1906. help='show repository or archive information')
  1907. subparser.set_defaults(func=self.do_info)
  1908. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE',
  1909. type=location_validator(),
  1910. help='archive or repository to display information about')
  1911. self.add_archives_filters_args(subparser)
  1912. break_lock_epilog = textwrap.dedent("""
  1913. This command breaks the repository and cache locks.
  1914. Please use carefully and only while no borg process (on any machine) is
  1915. trying to access the Cache or the Repository.
  1916. """)
  1917. subparser = subparsers.add_parser('break-lock', parents=[common_parser], add_help=False,
  1918. description=self.do_break_lock.__doc__,
  1919. epilog=break_lock_epilog,
  1920. formatter_class=argparse.RawDescriptionHelpFormatter,
  1921. help='break repository and cache locks')
  1922. subparser.set_defaults(func=self.do_break_lock)
  1923. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1924. type=location_validator(archive=False),
  1925. help='repository for which to break the locks')
  1926. prune_epilog = textwrap.dedent("""
  1927. The prune command prunes a repository by deleting all archives not matching
  1928. any of the specified retention options. This command is normally used by
  1929. automated backup scripts wanting to keep a certain number of historic backups.
  1930. Also, prune automatically removes checkpoint archives (incomplete archives left
  1931. behind by interrupted backup runs) except if the checkpoint is the latest
  1932. archive (and thus still needed). Checkpoint archives are not considered when
  1933. comparing archive counts against the retention limits (--keep-*).
  1934. If a prefix is set with -P, then only archives that start with the prefix are
  1935. considered for deletion and only those archives count towards the totals
  1936. specified by the rules.
  1937. Otherwise, *all* archives in the repository are candidates for deletion!
  1938. If you have multiple sequences of archives with different data sets (e.g.
  1939. from different machines) in one shared repository, use one prune call per
  1940. data set that matches only the respective archives using the -P option.
  1941. The "--keep-within" option takes an argument of the form "<int><char>",
  1942. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  1943. to keep all archives that were created within the past 48 hours.
  1944. "1m" is taken to mean "31d". The archives kept with this option do not
  1945. count towards the totals specified by any other options.
  1946. A good procedure is to thin out more and more the older your backups get.
  1947. As an example, "--keep-daily 7" means to keep the latest backup on each day,
  1948. up to 7 most recent days with backups (days without backups do not count).
  1949. The rules are applied from secondly to yearly, and backups selected by previous
  1950. rules do not count towards those of later rules. The time that each backup
  1951. starts is used for pruning purposes. Dates and times are interpreted in
  1952. the local timezone, and weeks go from Monday to Sunday. Specifying a
  1953. negative number of archives to keep means that there is no limit.
  1954. The "--keep-last N" option is doing the same as "--keep-secondly N" (and it will
  1955. keep the last N archives under the assumption that you do not create more than one
  1956. backup archive in the same second).
  1957. """)
  1958. subparser = subparsers.add_parser('prune', parents=[common_parser], add_help=False,
  1959. description=self.do_prune.__doc__,
  1960. epilog=prune_epilog,
  1961. formatter_class=argparse.RawDescriptionHelpFormatter,
  1962. help='prune archives')
  1963. subparser.set_defaults(func=self.do_prune)
  1964. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  1965. default=False, action='store_true',
  1966. help='do not change repository')
  1967. subparser.add_argument('--force', dest='forced',
  1968. action='store_true', default=False,
  1969. help='force pruning of corrupted archives')
  1970. subparser.add_argument('-s', '--stats', dest='stats',
  1971. action='store_true', default=False,
  1972. help='print statistics for the deleted archive')
  1973. subparser.add_argument('--list', dest='output_list',
  1974. action='store_true', default=False,
  1975. help='output verbose list of archives it keeps/prunes')
  1976. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  1977. help='keep all archives within this time interval')
  1978. subparser.add_argument('--keep-last', '--keep-secondly', dest='secondly', type=int, default=0,
  1979. help='number of secondly archives to keep')
  1980. subparser.add_argument('--keep-minutely', dest='minutely', type=int, default=0,
  1981. help='number of minutely archives to keep')
  1982. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  1983. help='number of hourly archives to keep')
  1984. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  1985. help='number of daily archives to keep')
  1986. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  1987. help='number of weekly archives to keep')
  1988. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  1989. help='number of monthly archives to keep')
  1990. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  1991. help='number of yearly archives to keep')
  1992. subparser.add_argument('-P', '--prefix', dest='prefix', type=PrefixSpec,
  1993. help='only consider archive names starting with this prefix')
  1994. subparser.add_argument('--save-space', dest='save_space', action='store_true',
  1995. default=False,
  1996. help='work slower, but using less space')
  1997. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  1998. type=location_validator(archive=False),
  1999. help='repository to prune')
  2000. upgrade_epilog = textwrap.dedent("""
  2001. Upgrade an existing Borg repository.
  2002. This currently supports converting an Attic repository to Borg and also
  2003. helps with converting Borg 0.xx to 1.0.
  2004. Currently, only LOCAL repositories can be upgraded (issue #465).
  2005. It will change the magic strings in the repository's segments
  2006. to match the new Borg magic strings. The keyfiles found in
  2007. $ATTIC_KEYS_DIR or ~/.attic/keys/ will also be converted and
  2008. copied to $BORG_KEYS_DIR or ~/.config/borg/keys.
  2009. The cache files are converted, from $ATTIC_CACHE_DIR or
  2010. ~/.cache/attic to $BORG_CACHE_DIR or ~/.cache/borg, but the
  2011. cache layout between Borg and Attic changed, so it is possible
  2012. the first backup after the conversion takes longer than expected
  2013. due to the cache resync.
  2014. Upgrade should be able to resume if interrupted, although it
  2015. will still iterate over all segments. If you want to start
  2016. from scratch, use `borg delete` over the copied repository to
  2017. make sure the cache files are also removed:
  2018. borg delete borg
  2019. Unless ``--inplace`` is specified, the upgrade process first
  2020. creates a backup copy of the repository, in
  2021. REPOSITORY.upgrade-DATETIME, using hardlinks. This takes
  2022. longer than in place upgrades, but is much safer and gives
  2023. progress information (as opposed to ``cp -al``). Once you are
  2024. satisfied with the conversion, you can safely destroy the
  2025. backup copy.
  2026. WARNING: Running the upgrade in place will make the current
  2027. copy unusable with older version, with no way of going back
  2028. to previous versions. This can PERMANENTLY DAMAGE YOUR
  2029. REPOSITORY! Attic CAN NOT READ BORG REPOSITORIES, as the
  2030. magic strings have changed. You have been warned.""")
  2031. subparser = subparsers.add_parser('upgrade', parents=[common_parser], add_help=False,
  2032. description=self.do_upgrade.__doc__,
  2033. epilog=upgrade_epilog,
  2034. formatter_class=argparse.RawDescriptionHelpFormatter,
  2035. help='upgrade repository format')
  2036. subparser.set_defaults(func=self.do_upgrade)
  2037. subparser.add_argument('-p', '--progress', dest='progress',
  2038. action='store_true', default=False,
  2039. help="""show progress display while upgrading the repository""")
  2040. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  2041. default=False, action='store_true',
  2042. help='do not change repository')
  2043. subparser.add_argument('-i', '--inplace', dest='inplace',
  2044. default=False, action='store_true',
  2045. help="""rewrite repository in place, with no chance of going back to older
  2046. versions of the repository.""")
  2047. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  2048. type=location_validator(archive=False),
  2049. help='path to the repository to be upgraded')
  2050. recreate_epilog = textwrap.dedent("""
  2051. Recreate the contents of existing archives.
  2052. --exclude, --exclude-from and PATH have the exact same semantics
  2053. as in "borg create". If PATHs are specified the resulting archive
  2054. will only contain files from these PATHs.
  2055. Note that all paths in an archive are relative, therefore absolute patterns/paths
  2056. will *not* match (--exclude, --exclude-from, --compression-from, PATHs).
  2057. --compression: all chunks seen will be stored using the given method.
  2058. Due to how Borg stores compressed size information this might display
  2059. incorrect information for archives that were not recreated at the same time.
  2060. There is no risk of data loss by this.
  2061. --chunker-params will re-chunk all files in the archive, this can be
  2062. used to have upgraded Borg 0.xx or Attic archives deduplicate with
  2063. Borg 1.x archives.
  2064. borg recreate is signal safe. Send either SIGINT (Ctrl-C on most terminals) or
  2065. SIGTERM to request termination.
  2066. Use the *exact same* command line to resume the operation later - changing excludes
  2067. or paths will lead to inconsistencies (changed excludes will only apply to newly
  2068. processed files/dirs). Changing compression leads to incorrect size information
  2069. (which does not cause any data loss, but can be misleading).
  2070. Changing chunker params between invocations might lead to data loss.
  2071. USE WITH CAUTION.
  2072. Depending on the PATHs and patterns given, recreate can be used to permanently
  2073. delete files from archives.
  2074. When in doubt, use "--dry-run --verbose --list" to see how patterns/PATHS are
  2075. interpreted.
  2076. The archive being recreated is only removed after the operation completes. The
  2077. archive that is built during the operation exists at the same time at
  2078. "<ARCHIVE>.recreate". The new archive will have a different archive ID.
  2079. With --target the original archive is not replaced, instead a new archive is created.
  2080. When rechunking space usage can be substantial, expect at least the entire
  2081. deduplicated size of the archives using the previous chunker params.
  2082. When recompressing approximately 1 % of the repository size or 512 MB
  2083. (whichever is greater) of additional space is used.
  2084. """)
  2085. subparser = subparsers.add_parser('recreate', parents=[common_parser], add_help=False,
  2086. description=self.do_recreate.__doc__,
  2087. epilog=recreate_epilog,
  2088. formatter_class=argparse.RawDescriptionHelpFormatter,
  2089. help=self.do_recreate.__doc__)
  2090. subparser.set_defaults(func=self.do_recreate)
  2091. subparser.add_argument('--list', dest='output_list',
  2092. action='store_true', default=False,
  2093. help='output verbose list of items (files, dirs, ...)')
  2094. subparser.add_argument('--filter', dest='output_filter', metavar='STATUSCHARS',
  2095. help='only display items with the given status characters')
  2096. subparser.add_argument('-p', '--progress', dest='progress',
  2097. action='store_true', default=False,
  2098. help='show progress display while recreating archives')
  2099. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  2100. action='store_true', default=False,
  2101. help='do not change anything')
  2102. subparser.add_argument('-s', '--stats', dest='stats',
  2103. action='store_true', default=False,
  2104. help='print statistics at end')
  2105. exclude_group = subparser.add_argument_group('Exclusion options')
  2106. exclude_group.add_argument('-e', '--exclude', dest='excludes',
  2107. type=parse_pattern, action='append',
  2108. metavar="PATTERN", help='exclude paths matching PATTERN')
  2109. exclude_group.add_argument('--exclude-from', dest='exclude_files',
  2110. type=argparse.FileType('r'), action='append',
  2111. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  2112. exclude_group.add_argument('--exclude-caches', dest='exclude_caches',
  2113. action='store_true', default=False,
  2114. help='exclude directories that contain a CACHEDIR.TAG file ('
  2115. 'http://www.brynosaurus.com/cachedir/spec.html)')
  2116. exclude_group.add_argument('--exclude-if-present', dest='exclude_if_present',
  2117. metavar='FILENAME', action='append', type=str,
  2118. help='exclude directories that contain the specified file')
  2119. exclude_group.add_argument('--keep-tag-files', dest='keep_tag_files',
  2120. action='store_true', default=False,
  2121. help='keep tag files of excluded caches/directories')
  2122. archive_group = subparser.add_argument_group('Archive options')
  2123. archive_group.add_argument('--target', dest='target', metavar='TARGET', default=None,
  2124. type=archivename_validator(),
  2125. help='create a new archive with the name ARCHIVE, do not replace existing archive '
  2126. '(only applies for a single archive)')
  2127. archive_group.add_argument('--comment', dest='comment', metavar='COMMENT', default=None,
  2128. help='add a comment text to the archive')
  2129. archive_group.add_argument('--timestamp', dest='timestamp',
  2130. type=timestamp, default=None,
  2131. metavar='yyyy-mm-ddThh:mm:ss',
  2132. help='manually specify the archive creation date/time (UTC). '
  2133. 'alternatively, give a reference file/directory.')
  2134. archive_group.add_argument('-C', '--compression', dest='compression',
  2135. type=CompressionSpec, default=None, metavar='COMPRESSION',
  2136. help='select compression algorithm, see the output of the '
  2137. '"borg help compression" command for details.')
  2138. archive_group.add_argument('--always-recompress', dest='always_recompress', action='store_true',
  2139. help='always recompress chunks, don\'t skip chunks already compressed with the same'
  2140. 'algorithm.')
  2141. archive_group.add_argument('--compression-from', dest='compression_files',
  2142. type=argparse.FileType('r'), action='append',
  2143. metavar='COMPRESSIONCONFIG',
  2144. help='read compression patterns from COMPRESSIONCONFIG, see the output of the '
  2145. '"borg help compression" command for details.')
  2146. archive_group.add_argument('--chunker-params', dest='chunker_params',
  2147. type=ChunkerParams, default=None,
  2148. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  2149. help='specify the chunker parameters (or "default").')
  2150. subparser.add_argument('location', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  2151. type=location_validator(),
  2152. help='repository/archive to recreate')
  2153. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  2154. help='paths to recreate; patterns are supported')
  2155. with_lock_epilog = textwrap.dedent("""
  2156. This command runs a user-specified command while the repository lock is held.
  2157. It will first try to acquire the lock (make sure that no other operation is
  2158. running in the repo), then execute the given command as a subprocess and wait
  2159. for its termination, release the lock and return the user command's return
  2160. code as borg's return code.
  2161. Note: if you copy a repository with the lock held, the lock will be present in
  2162. the copy, obviously. Thus, before using borg on the copy, you need to
  2163. use "borg break-lock" on it.
  2164. """)
  2165. subparser = subparsers.add_parser('with-lock', parents=[common_parser], add_help=False,
  2166. description=self.do_with_lock.__doc__,
  2167. epilog=with_lock_epilog,
  2168. formatter_class=argparse.RawDescriptionHelpFormatter,
  2169. help='run user command with lock held')
  2170. subparser.set_defaults(func=self.do_with_lock)
  2171. subparser.add_argument('location', metavar='REPOSITORY',
  2172. type=location_validator(archive=False),
  2173. help='repository to lock')
  2174. subparser.add_argument('command', metavar='COMMAND',
  2175. help='command to run')
  2176. subparser.add_argument('args', metavar='ARGS', nargs=argparse.REMAINDER,
  2177. help='command arguments')
  2178. subparser = subparsers.add_parser('help', parents=[common_parser], add_help=False,
  2179. description='Extra help')
  2180. subparser.add_argument('--epilog-only', dest='epilog_only',
  2181. action='store_true', default=False)
  2182. subparser.add_argument('--usage-only', dest='usage_only',
  2183. action='store_true', default=False)
  2184. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  2185. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  2186. help='additional help on TOPIC')
  2187. debug_epilog = textwrap.dedent("""
  2188. These commands are not intended for normal use and potentially very
  2189. dangerous if used incorrectly.
  2190. They exist to improve debugging capabilities without direct system access, e.g.
  2191. in case you ever run into some severe malfunction. Use them only if you know
  2192. what you are doing or if a trusted developer tells you what to do.""")
  2193. subparser = subparsers.add_parser('debug', add_help=False,
  2194. description='debugging command (not intended for normal use)',
  2195. epilog=debug_epilog,
  2196. formatter_class=argparse.RawDescriptionHelpFormatter,
  2197. help='debugging command (not intended for normal use)')
  2198. debug_parsers = subparser.add_subparsers(title='required arguments', metavar='<command>')
  2199. debug_info_epilog = textwrap.dedent("""
  2200. This command displays some system information that might be useful for bug
  2201. reports and debugging problems. If a traceback happens, this information is
  2202. already appended at the end of the traceback.
  2203. """)
  2204. subparser = debug_parsers.add_parser('info', parents=[common_parser], add_help=False,
  2205. description=self.do_debug_info.__doc__,
  2206. epilog=debug_info_epilog,
  2207. formatter_class=argparse.RawDescriptionHelpFormatter,
  2208. help='show system infos for debugging / bug reports (debug)')
  2209. subparser.set_defaults(func=self.do_debug_info)
  2210. debug_dump_archive_items_epilog = textwrap.dedent("""
  2211. This command dumps raw (but decrypted and decompressed) archive items (only metadata) to files.
  2212. """)
  2213. subparser = debug_parsers.add_parser('dump-archive-items', parents=[common_parser], add_help=False,
  2214. description=self.do_debug_dump_archive_items.__doc__,
  2215. epilog=debug_dump_archive_items_epilog,
  2216. formatter_class=argparse.RawDescriptionHelpFormatter,
  2217. help='dump archive items (metadata) (debug)')
  2218. subparser.set_defaults(func=self.do_debug_dump_archive_items)
  2219. subparser.add_argument('location', metavar='ARCHIVE',
  2220. type=location_validator(archive=True),
  2221. help='archive to dump')
  2222. debug_dump_repo_objs_epilog = textwrap.dedent("""
  2223. This command dumps raw (but decrypted and decompressed) repo objects to files.
  2224. """)
  2225. subparser = debug_parsers.add_parser('dump-repo-objs', parents=[common_parser], add_help=False,
  2226. description=self.do_debug_dump_repo_objs.__doc__,
  2227. epilog=debug_dump_repo_objs_epilog,
  2228. formatter_class=argparse.RawDescriptionHelpFormatter,
  2229. help='dump repo objects (debug)')
  2230. subparser.set_defaults(func=self.do_debug_dump_repo_objs)
  2231. subparser.add_argument('location', metavar='REPOSITORY',
  2232. type=location_validator(archive=False),
  2233. help='repo to dump')
  2234. debug_get_obj_epilog = textwrap.dedent("""
  2235. This command gets an object from the repository.
  2236. """)
  2237. subparser = debug_parsers.add_parser('get-obj', parents=[common_parser], add_help=False,
  2238. description=self.do_debug_get_obj.__doc__,
  2239. epilog=debug_get_obj_epilog,
  2240. formatter_class=argparse.RawDescriptionHelpFormatter,
  2241. help='get object from repository (debug)')
  2242. subparser.set_defaults(func=self.do_debug_get_obj)
  2243. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  2244. type=location_validator(archive=False),
  2245. help='repository to use')
  2246. subparser.add_argument('id', metavar='ID', type=str,
  2247. help='hex object ID to get from the repo')
  2248. subparser.add_argument('path', metavar='PATH', type=str,
  2249. help='file to write object data into')
  2250. debug_put_obj_epilog = textwrap.dedent("""
  2251. This command puts objects into the repository.
  2252. """)
  2253. subparser = debug_parsers.add_parser('put-obj', parents=[common_parser], add_help=False,
  2254. description=self.do_debug_put_obj.__doc__,
  2255. epilog=debug_put_obj_epilog,
  2256. formatter_class=argparse.RawDescriptionHelpFormatter,
  2257. help='put object to repository (debug)')
  2258. subparser.set_defaults(func=self.do_debug_put_obj)
  2259. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  2260. type=location_validator(archive=False),
  2261. help='repository to use')
  2262. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  2263. help='file(s) to read and create object(s) from')
  2264. debug_delete_obj_epilog = textwrap.dedent("""
  2265. This command deletes objects from the repository.
  2266. """)
  2267. subparser = debug_parsers.add_parser('delete-obj', parents=[common_parser], add_help=False,
  2268. description=self.do_debug_delete_obj.__doc__,
  2269. epilog=debug_delete_obj_epilog,
  2270. formatter_class=argparse.RawDescriptionHelpFormatter,
  2271. help='delete object from repository (debug)')
  2272. subparser.set_defaults(func=self.do_debug_delete_obj)
  2273. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  2274. type=location_validator(archive=False),
  2275. help='repository to use')
  2276. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  2277. help='hex object ID(s) to delete from the repo')
  2278. debug_refcount_obj_epilog = textwrap.dedent("""
  2279. This command displays the reference count for objects from the repository.
  2280. """)
  2281. subparser = debug_parsers.add_parser('refcount-obj', parents=[common_parser], add_help=False,
  2282. description=self.do_debug_refcount_obj.__doc__,
  2283. epilog=debug_refcount_obj_epilog,
  2284. formatter_class=argparse.RawDescriptionHelpFormatter,
  2285. help='show refcount for object from repository (debug)')
  2286. subparser.set_defaults(func=self.do_debug_refcount_obj)
  2287. subparser.add_argument('location', metavar='REPOSITORY', nargs='?', default='',
  2288. type=location_validator(archive=False),
  2289. help='repository to use')
  2290. subparser.add_argument('ids', metavar='IDs', nargs='+', type=str,
  2291. help='hex object ID(s) to show refcounts for')
  2292. return parser
  2293. @staticmethod
  2294. def add_archives_filters_args(subparser):
  2295. filters_group = subparser.add_argument_group('filters', 'Archive filters can be applied to repository targets.')
  2296. filters_group.add_argument('-P', '--prefix', dest='prefix', type=PrefixSpec, default='',
  2297. help='only consider archive names starting with this prefix')
  2298. sort_by_default = 'timestamp'
  2299. filters_group.add_argument('--sort-by', dest='sort_by', type=SortBySpec, default=sort_by_default,
  2300. help='Comma-separated list of sorting keys; valid keys are: {}; default is: {}'
  2301. .format(', '.join(HUMAN_SORT_KEYS), sort_by_default))
  2302. group = filters_group.add_mutually_exclusive_group()
  2303. group.add_argument('--first', dest='first', metavar='N', default=0, type=int,
  2304. help='consider first N archives after other filters were applied')
  2305. group.add_argument('--last', dest='last', metavar='N', default=0, type=int,
  2306. help='consider last N archives after other filters were applied')
  2307. def get_args(self, argv, cmd):
  2308. """usually, just returns argv, except if we deal with a ssh forced command for borg serve."""
  2309. result = self.parse_args(argv[1:])
  2310. if cmd is not None and result.func == self.do_serve:
  2311. forced_result = result
  2312. argv = shlex.split(cmd)
  2313. result = self.parse_args(argv[1:])
  2314. if result.func != forced_result.func:
  2315. # someone is trying to execute a different borg subcommand, don't do that!
  2316. return forced_result
  2317. # we only take specific options from the forced "borg serve" command:
  2318. result.restrict_to_paths = forced_result.restrict_to_paths
  2319. result.append_only = forced_result.append_only
  2320. return result
  2321. def parse_args(self, args=None):
  2322. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  2323. if args:
  2324. args = self.preprocess_args(args)
  2325. args = self.parser.parse_args(args or ['-h'])
  2326. update_excludes(args)
  2327. return args
  2328. def prerun_checks(self, logger):
  2329. check_extension_modules()
  2330. selftest(logger)
  2331. def _setup_implied_logging(self, args):
  2332. """ turn on INFO level logging for args that imply that they will produce output """
  2333. # map of option name to name of logger for that option
  2334. option_logger = {
  2335. 'output_list': 'borg.output.list',
  2336. 'show_version': 'borg.output.show-version',
  2337. 'show_rc': 'borg.output.show-rc',
  2338. 'stats': 'borg.output.stats',
  2339. 'progress': 'borg.output.progress',
  2340. }
  2341. for option, logger_name in option_logger.items():
  2342. if args.get(option, False):
  2343. logging.getLogger(logger_name).setLevel('INFO')
  2344. def _setup_topic_debugging(self, args):
  2345. """Turn on DEBUG level logging for specified --debug-topics."""
  2346. for topic in args.debug_topics:
  2347. if '.' not in topic:
  2348. topic = 'borg.debug.' + topic
  2349. logger.debug('Enabling debug topic %s', topic)
  2350. logging.getLogger(topic).setLevel('DEBUG')
  2351. def run(self, args):
  2352. os.umask(args.umask) # early, before opening files
  2353. self.lock_wait = args.lock_wait
  2354. setup_logging(level=args.log_level, is_serve=args.func == self.do_serve) # do not use loggers before this!
  2355. self._setup_implied_logging(vars(args))
  2356. self._setup_topic_debugging(args)
  2357. if args.show_version:
  2358. logging.getLogger('borg.output.show-version').info('borgbackup version %s' % __version__)
  2359. self.prerun_checks(logger)
  2360. if is_slow_msgpack():
  2361. logger.warning("Using a pure-python msgpack! This will result in lower performance.")
  2362. return args.func(args)
  2363. def sig_info_handler(sig_no, stack): # pragma: no cover
  2364. """search the stack for infos about the currently processed file and print them"""
  2365. with signal_handler(sig_no, signal.SIG_IGN):
  2366. for frame in inspect.getouterframes(stack):
  2367. func, loc = frame[3], frame[0].f_locals
  2368. if func in ('process_file', '_process', ): # create op
  2369. path = loc['path']
  2370. try:
  2371. pos = loc['fd'].tell()
  2372. total = loc['st'].st_size
  2373. except Exception:
  2374. pos, total = 0, 0
  2375. logger.info("{0} {1}/{2}".format(path, format_file_size(pos), format_file_size(total)))
  2376. break
  2377. if func in ('extract_item', ): # extract op
  2378. path = loc['item'].path
  2379. try:
  2380. pos = loc['fd'].tell()
  2381. except Exception:
  2382. pos = 0
  2383. logger.info("{0} {1}/???".format(path, format_file_size(pos)))
  2384. break
  2385. def main(): # pragma: no cover
  2386. # provide 'borg mount' behaviour when the main script/executable is named borgfs
  2387. if os.path.basename(sys.argv[0]) == "borgfs":
  2388. sys.argv.insert(1, "mount")
  2389. # Make sure stdout and stderr have errors='replace' to avoid unicode
  2390. # issues when print()-ing unicode file names
  2391. sys.stdout = ErrorIgnoringTextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  2392. sys.stderr = ErrorIgnoringTextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  2393. # If we receive SIGINT (ctrl-c), SIGTERM (kill) or SIGHUP (kill -HUP),
  2394. # catch them and raise a proper exception that can be handled for an
  2395. # orderly exit.
  2396. # SIGHUP is important especially for systemd systems, where logind
  2397. # sends it when a session exits, in addition to any traditional use.
  2398. # Output some info if we receive SIGUSR1 or SIGINFO (ctrl-t).
  2399. with signal_handler('SIGINT', raising_signal_handler(KeyboardInterrupt)), \
  2400. signal_handler('SIGHUP', raising_signal_handler(SigHup)), \
  2401. signal_handler('SIGTERM', raising_signal_handler(SigTerm)), \
  2402. signal_handler('SIGUSR1', sig_info_handler), \
  2403. signal_handler('SIGINFO', sig_info_handler):
  2404. archiver = Archiver()
  2405. msg = tb = None
  2406. tb_log_level = logging.ERROR
  2407. try:
  2408. args = archiver.get_args(sys.argv, os.environ.get('SSH_ORIGINAL_COMMAND'))
  2409. except Error as e:
  2410. msg = e.get_message()
  2411. tb_log_level = logging.ERROR if e.traceback else logging.DEBUG
  2412. tb = '%s\n%s' % (traceback.format_exc(), sysinfo())
  2413. # we might not have logging setup yet, so get out quickly
  2414. print(msg, file=sys.stderr)
  2415. if tb_log_level == logging.ERROR:
  2416. print(tb, file=sys.stderr)
  2417. sys.exit(e.exit_code)
  2418. try:
  2419. exit_code = archiver.run(args)
  2420. except Error as e:
  2421. msg = e.get_message()
  2422. tb_log_level = logging.ERROR if e.traceback else logging.DEBUG
  2423. tb = "%s\n%s" % (traceback.format_exc(), sysinfo())
  2424. exit_code = e.exit_code
  2425. except RemoteRepository.RPCError as e:
  2426. msg = "%s %s" % (e.remote_type, e.name)
  2427. important = e.remote_type not in ('LockTimeout', )
  2428. tb_log_level = logging.ERROR if important else logging.DEBUG
  2429. tb = sysinfo()
  2430. exit_code = EXIT_ERROR
  2431. except Exception:
  2432. msg = 'Local Exception'
  2433. tb_log_level = logging.ERROR
  2434. tb = '%s\n%s' % (traceback.format_exc(), sysinfo())
  2435. exit_code = EXIT_ERROR
  2436. except KeyboardInterrupt:
  2437. msg = 'Keyboard interrupt'
  2438. tb_log_level = logging.DEBUG
  2439. tb = '%s\n%s' % (traceback.format_exc(), sysinfo())
  2440. exit_code = EXIT_ERROR
  2441. except SigTerm:
  2442. msg = 'Received SIGTERM'
  2443. tb_log_level = logging.DEBUG
  2444. tb = '%s\n%s' % (traceback.format_exc(), sysinfo())
  2445. exit_code = EXIT_ERROR
  2446. except SigHup:
  2447. msg = 'Received SIGHUP.'
  2448. exit_code = EXIT_ERROR
  2449. if msg:
  2450. logger.error(msg)
  2451. if tb:
  2452. logger.log(tb_log_level, tb)
  2453. if args.show_rc:
  2454. rc_logger = logging.getLogger('borg.output.show-rc')
  2455. exit_msg = 'terminating with %s status, rc %d'
  2456. if exit_code == EXIT_SUCCESS:
  2457. rc_logger.info(exit_msg % ('success', exit_code))
  2458. elif exit_code == EXIT_WARNING:
  2459. rc_logger.warning(exit_msg % ('warning', exit_code))
  2460. elif exit_code == EXIT_ERROR:
  2461. rc_logger.error(exit_msg % ('error', exit_code))
  2462. else:
  2463. rc_logger.error(exit_msg % ('abnormal', exit_code or 666))
  2464. sys.exit(exit_code)
  2465. if __name__ == '__main__':
  2466. main()