archiver.py 93 KB

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