archiver.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. from .support import argparse # see support/__init__.py docstring
  2. # DEPRECATED - remove after requiring py 3.4
  3. from binascii import hexlify
  4. from datetime import datetime
  5. from operator import attrgetter
  6. import functools
  7. import inspect
  8. import io
  9. import os
  10. import signal
  11. import stat
  12. import sys
  13. import textwrap
  14. import traceback
  15. from . import __version__
  16. from .helpers import Error, location_validator, format_time, format_file_size, \
  17. format_file_mode, ExcludePattern, IncludePattern, exclude_path, adjust_patterns, to_localtime, timestamp, \
  18. get_cache_dir, get_keys_dir, prune_within, prune_split, \
  19. Manifest, remove_surrogates, update_excludes, format_archive, check_extension_modules, Statistics, \
  20. is_cachedir, bigint_to_int, ChunkerParams, CompressionSpec, have_cython, is_slow_msgpack, yes, \
  21. EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR
  22. from .logger import create_logger, setup_logging
  23. logger = create_logger()
  24. if have_cython():
  25. from .compress import Compressor, COMPR_BUFFER
  26. from .upgrader import AtticRepositoryUpgrader
  27. from .repository import Repository
  28. from .cache import Cache
  29. from .key import key_creator
  30. from .archive import Archive, ArchiveChecker, CHUNKER_PARAMS
  31. from .remote import RepositoryServer, RemoteRepository
  32. has_lchflags = hasattr(os, 'lchflags')
  33. class Archiver:
  34. def __init__(self, verbose=False):
  35. self.exit_code = EXIT_SUCCESS
  36. self.verbose = verbose
  37. def open_repository(self, location, create=False, exclusive=False):
  38. if location.proto == 'ssh':
  39. repository = RemoteRepository(location, create=create)
  40. else:
  41. repository = Repository(location.path, create=create, exclusive=exclusive)
  42. repository._location = location
  43. return repository
  44. def print_error(self, msg, *args):
  45. msg = args and msg % args or msg
  46. self.exit_code = EXIT_ERROR
  47. logger.error(msg)
  48. def print_warning(self, msg, *args):
  49. msg = args and msg % args or msg
  50. self.exit_code = EXIT_WARNING # we do not terminate here, so it is a warning
  51. logger.warning(msg)
  52. def print_info(self, msg, *args):
  53. if self.verbose:
  54. msg = args and msg % args or msg
  55. logger.info(msg)
  56. def print_status(self, status, path):
  57. self.print_info("%1s %s", status, remove_surrogates(path))
  58. def do_serve(self, args):
  59. """Start in server mode. This command is usually not used manually.
  60. """
  61. return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()
  62. def do_init(self, args):
  63. """Initialize an empty repository"""
  64. logger.info('Initializing repository at "%s"' % args.repository.orig)
  65. repository = self.open_repository(args.repository, create=True, exclusive=True)
  66. key = key_creator(repository, args)
  67. manifest = Manifest(key, repository)
  68. manifest.key = key
  69. manifest.write()
  70. repository.commit()
  71. Cache(repository, key, manifest, warn_if_unencrypted=False)
  72. return self.exit_code
  73. def do_check(self, args):
  74. """Check repository consistency"""
  75. repository = self.open_repository(args.repository, exclusive=args.repair)
  76. if args.repair:
  77. msg = ("'check --repair' is an experimental feature that might result in data loss." +
  78. "\n" +
  79. "Type 'YES' if you understand this and want to continue: ")
  80. if not yes(msg, false_msg="Aborting.", default_notty=False,
  81. env_var_override='BORG_CHECK_I_KNOW_WHAT_I_AM_DOING', truish=('YES', )):
  82. return EXIT_ERROR
  83. if not args.archives_only:
  84. logger.info('Starting repository check...')
  85. if repository.check(repair=args.repair):
  86. logger.info('Repository check complete, no problems found.')
  87. else:
  88. return EXIT_WARNING
  89. if not args.repo_only and not ArchiveChecker().check(
  90. repository, repair=args.repair, archive=args.repository.archive, last=args.last):
  91. return EXIT_WARNING
  92. return EXIT_SUCCESS
  93. def do_change_passphrase(self, args):
  94. """Change repository key file passphrase"""
  95. repository = self.open_repository(args.repository)
  96. manifest, key = Manifest.load(repository)
  97. key.change_passphrase()
  98. return EXIT_SUCCESS
  99. def do_create(self, args):
  100. """Create new archive"""
  101. dry_run = args.dry_run
  102. t0 = datetime.now()
  103. if not dry_run:
  104. repository = self.open_repository(args.archive, exclusive=True)
  105. manifest, key = Manifest.load(repository)
  106. compr_args = dict(buffer=COMPR_BUFFER)
  107. compr_args.update(args.compression)
  108. key.compressor = Compressor(**compr_args)
  109. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  110. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,
  111. create=True, checkpoint_interval=args.checkpoint_interval,
  112. numeric_owner=args.numeric_owner, progress=args.progress,
  113. chunker_params=args.chunker_params, start=t0)
  114. else:
  115. archive = cache = None
  116. # Add cache dir to inode_skip list
  117. skip_inodes = set()
  118. try:
  119. st = os.stat(get_cache_dir())
  120. skip_inodes.add((st.st_ino, st.st_dev))
  121. except IOError:
  122. pass
  123. # Add local repository dir to inode_skip list
  124. if not args.archive.host:
  125. try:
  126. st = os.stat(args.archive.path)
  127. skip_inodes.add((st.st_ino, st.st_dev))
  128. except IOError:
  129. pass
  130. for path in args.paths:
  131. if path == '-': # stdin
  132. path = 'stdin'
  133. if not dry_run:
  134. try:
  135. status = archive.process_stdin(path, cache)
  136. except IOError as e:
  137. status = 'E'
  138. self.print_warning('%s: %s', path, e)
  139. else:
  140. status = '-'
  141. self.print_status(status, path)
  142. continue
  143. path = os.path.normpath(path)
  144. if args.one_file_system:
  145. try:
  146. restrict_dev = os.lstat(path).st_dev
  147. except OSError as e:
  148. self.print_warning('%s: %s', path, e)
  149. continue
  150. else:
  151. restrict_dev = None
  152. self._process(archive, cache, args.excludes, args.exclude_caches, skip_inodes, path, restrict_dev,
  153. read_special=args.read_special, dry_run=dry_run)
  154. if not dry_run:
  155. archive.save(timestamp=args.timestamp)
  156. if args.progress:
  157. archive.stats.show_progress(final=True)
  158. if args.stats:
  159. archive.end = datetime.now()
  160. print('-' * 78)
  161. print(str(archive))
  162. print()
  163. print(str(archive.stats))
  164. print(str(cache))
  165. print('-' * 78)
  166. return self.exit_code
  167. def _process(self, archive, cache, excludes, exclude_caches, skip_inodes, path, restrict_dev,
  168. read_special=False, dry_run=False):
  169. if exclude_path(path, excludes):
  170. return
  171. try:
  172. st = os.lstat(path)
  173. except OSError as e:
  174. self.print_warning('%s: %s', path, e)
  175. return
  176. if (st.st_ino, st.st_dev) in skip_inodes:
  177. return
  178. # Entering a new filesystem?
  179. if restrict_dev and st.st_dev != restrict_dev:
  180. return
  181. status = None
  182. # Ignore if nodump flag is set
  183. if has_lchflags and (st.st_flags & stat.UF_NODUMP):
  184. return
  185. if (stat.S_ISREG(st.st_mode) or
  186. read_special and not stat.S_ISDIR(st.st_mode)):
  187. if not dry_run:
  188. try:
  189. status = archive.process_file(path, st, cache)
  190. except IOError as e:
  191. status = 'E'
  192. self.print_warning('%s: %s', path, e)
  193. elif stat.S_ISDIR(st.st_mode):
  194. if exclude_caches and is_cachedir(path):
  195. return
  196. if not dry_run:
  197. status = archive.process_dir(path, st)
  198. try:
  199. entries = os.listdir(path)
  200. except OSError as e:
  201. status = 'E'
  202. self.print_warning('%s: %s', path, e)
  203. else:
  204. for filename in sorted(entries):
  205. entry_path = os.path.normpath(os.path.join(path, filename))
  206. self._process(archive, cache, excludes, exclude_caches, skip_inodes,
  207. entry_path, restrict_dev, read_special=read_special,
  208. dry_run=dry_run)
  209. elif stat.S_ISLNK(st.st_mode):
  210. if not dry_run:
  211. status = archive.process_symlink(path, st)
  212. elif stat.S_ISFIFO(st.st_mode):
  213. if not dry_run:
  214. status = archive.process_fifo(path, st)
  215. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  216. if not dry_run:
  217. status = archive.process_dev(path, st)
  218. elif stat.S_ISSOCK(st.st_mode):
  219. # Ignore unix sockets
  220. return
  221. else:
  222. self.print_warning('Unknown file type: %s', path)
  223. return
  224. # Status output
  225. # A lowercase character means a file type other than a regular file,
  226. # borg usually just stores them. E.g. (d)irectory.
  227. # Hardlinks to already seen content are indicated by (h).
  228. # A uppercase character means a regular file that was (A)dded,
  229. # (M)odified or was (U)nchanged.
  230. # Note: A/M/U is relative to the "files" cache, not to the repo.
  231. # This would be an issue if the files cache is not used.
  232. if status is None:
  233. if not dry_run:
  234. status = '?' # need to add a status code somewhere
  235. else:
  236. status = '-' # dry run, item was not backed up
  237. # output ALL the stuff - it can be easily filtered using grep.
  238. # even stuff considered unchanged might be interesting.
  239. self.print_status(status, path)
  240. def do_extract(self, args):
  241. """Extract archive contents"""
  242. # be restrictive when restoring files, restore permissions later
  243. if sys.getfilesystemencoding() == 'ascii':
  244. logger.warning('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  245. repository = self.open_repository(args.archive)
  246. manifest, key = Manifest.load(repository)
  247. archive = Archive(repository, key, manifest, args.archive.archive,
  248. numeric_owner=args.numeric_owner)
  249. patterns = adjust_patterns(args.paths, args.excludes)
  250. dry_run = args.dry_run
  251. stdout = args.stdout
  252. sparse = args.sparse
  253. strip_components = args.strip_components
  254. dirs = []
  255. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  256. orig_path = item[b'path']
  257. if strip_components:
  258. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  259. if not item[b'path']:
  260. continue
  261. if not args.dry_run:
  262. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  263. archive.extract_item(dirs.pop(-1), stdout=stdout)
  264. self.print_info(remove_surrogates(orig_path))
  265. try:
  266. if dry_run:
  267. archive.extract_item(item, dry_run=True)
  268. else:
  269. if stat.S_ISDIR(item[b'mode']):
  270. dirs.append(item)
  271. archive.extract_item(item, restore_attrs=False)
  272. else:
  273. archive.extract_item(item, stdout=stdout, sparse=sparse)
  274. except IOError as e:
  275. self.print_warning('%s: %s', remove_surrogates(orig_path), e)
  276. if not args.dry_run:
  277. while dirs:
  278. archive.extract_item(dirs.pop(-1))
  279. for pattern in (patterns or []):
  280. if isinstance(pattern, IncludePattern) and pattern.match_count == 0:
  281. self.print_warning("Include pattern '%s' never matched.", pattern)
  282. return self.exit_code
  283. def do_rename(self, args):
  284. """Rename an existing archive"""
  285. repository = self.open_repository(args.archive, exclusive=True)
  286. manifest, key = Manifest.load(repository)
  287. cache = Cache(repository, key, manifest)
  288. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  289. archive.rename(args.name)
  290. manifest.write()
  291. repository.commit()
  292. cache.commit()
  293. return self.exit_code
  294. def do_delete(self, args):
  295. """Delete an existing repository or archive"""
  296. repository = self.open_repository(args.target, exclusive=True)
  297. manifest, key = Manifest.load(repository)
  298. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  299. if args.target.archive:
  300. archive = Archive(repository, key, manifest, args.target.archive, cache=cache)
  301. stats = Statistics()
  302. archive.delete(stats)
  303. manifest.write()
  304. repository.commit()
  305. cache.commit()
  306. if args.stats:
  307. logger.info(stats.summary.format(label='Deleted data:', stats=stats))
  308. logger.info(str(cache))
  309. else:
  310. if not args.cache_only:
  311. msg = []
  312. msg.append("You requested to completely DELETE the repository *including* all archives it contains:")
  313. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  314. msg.append(format_archive(archive_info))
  315. msg.append("Type 'YES' if you understand this and want to continue: ")
  316. msg = '\n'.join(msg)
  317. if not yes(msg, false_msg="Aborting.", default_notty=False,
  318. env_var_override='BORG_CHECK_I_KNOW_WHAT_I_AM_DOING', truish=('YES', )):
  319. self.exit_code = EXIT_ERROR
  320. return self.exit_code
  321. repository.destroy()
  322. logger.info("Repository deleted.")
  323. cache.destroy()
  324. logger.info("Cache deleted.")
  325. return self.exit_code
  326. def do_mount(self, args):
  327. """Mount archive or an entire repository as a FUSE fileystem"""
  328. try:
  329. from .fuse import FuseOperations
  330. except ImportError as e:
  331. self.print_error('Loading fuse support failed [ImportError: %s]' % str(e))
  332. return self.exit_code
  333. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  334. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  335. return self.exit_code
  336. repository = self.open_repository(args.src)
  337. try:
  338. manifest, key = Manifest.load(repository)
  339. if args.src.archive:
  340. archive = Archive(repository, key, manifest, args.src.archive)
  341. else:
  342. archive = None
  343. operations = FuseOperations(key, repository, manifest, archive)
  344. self.print_info("Mounting filesystem")
  345. try:
  346. operations.mount(args.mountpoint, args.options, args.foreground)
  347. except RuntimeError:
  348. # Relevant error message already printed to stderr by fuse
  349. self.exit_code = EXIT_ERROR
  350. finally:
  351. repository.close()
  352. return self.exit_code
  353. def do_list(self, args):
  354. """List archive or repository contents"""
  355. repository = self.open_repository(args.src)
  356. manifest, key = Manifest.load(repository)
  357. if args.src.archive:
  358. archive = Archive(repository, key, manifest, args.src.archive)
  359. if args.short:
  360. for item in archive.iter_items():
  361. print(remove_surrogates(item[b'path']))
  362. else:
  363. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  364. for item in archive.iter_items():
  365. type = tmap.get(item[b'mode'] // 4096, '?')
  366. mode = format_file_mode(item[b'mode'])
  367. size = 0
  368. if type == '-':
  369. try:
  370. size = sum(size for _, size, _ in item[b'chunks'])
  371. except KeyError:
  372. pass
  373. try:
  374. mtime = datetime.fromtimestamp(bigint_to_int(item[b'mtime']) / 1e9)
  375. except ValueError:
  376. # likely a broken mtime and datetime did not want to go beyond year 9999
  377. mtime = datetime(9999, 12, 31, 23, 59, 59)
  378. if b'source' in item:
  379. if type == 'l':
  380. extra = ' -> %s' % item[b'source']
  381. else:
  382. type = 'h'
  383. extra = ' link to %s' % item[b'source']
  384. else:
  385. extra = ''
  386. print('%s%s %-6s %-6s %8d %s %s%s' % (
  387. type, mode, item[b'user'] or item[b'uid'],
  388. item[b'group'] or item[b'gid'], size, format_time(mtime),
  389. remove_surrogates(item[b'path']), extra))
  390. else:
  391. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  392. print(format_archive(archive_info))
  393. return self.exit_code
  394. def do_info(self, args):
  395. """Show archive details such as disk space used"""
  396. repository = self.open_repository(args.archive)
  397. manifest, key = Manifest.load(repository)
  398. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  399. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  400. stats = archive.calc_stats(cache)
  401. print('Name:', archive.name)
  402. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  403. print('Hostname:', archive.metadata[b'hostname'])
  404. print('Username:', archive.metadata[b'username'])
  405. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  406. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  407. print('Number of files: %d' % stats.nfiles)
  408. print()
  409. print(str(stats))
  410. print(str(cache))
  411. return self.exit_code
  412. def do_prune(self, args):
  413. """Prune repository archives according to specified rules"""
  414. repository = self.open_repository(args.repository, exclusive=True)
  415. manifest, key = Manifest.load(repository)
  416. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  417. archives = manifest.list_archive_infos(sort_by='ts', reverse=True) # just a ArchiveInfo list
  418. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  419. self.print_error('At least one of the "within", "keep-hourly", "keep-daily", "keep-weekly", '
  420. '"keep-monthly" or "keep-yearly" settings must be specified')
  421. return self.exit_code
  422. if args.prefix:
  423. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  424. keep = []
  425. if args.within:
  426. keep += prune_within(archives, args.within)
  427. if args.hourly:
  428. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  429. if args.daily:
  430. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  431. if args.weekly:
  432. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  433. if args.monthly:
  434. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  435. if args.yearly:
  436. keep += prune_split(archives, '%Y', args.yearly, keep)
  437. keep.sort(key=attrgetter('ts'), reverse=True)
  438. to_delete = [a for a in archives if a not in keep]
  439. stats = Statistics()
  440. for archive in keep:
  441. self.print_info('Keeping archive: %s' % format_archive(archive))
  442. for archive in to_delete:
  443. if args.dry_run:
  444. self.print_info('Would prune: %s' % format_archive(archive))
  445. else:
  446. self.print_info('Pruning archive: %s' % format_archive(archive))
  447. Archive(repository, key, manifest, archive.name, cache).delete(stats)
  448. if to_delete and not args.dry_run:
  449. manifest.write()
  450. repository.commit()
  451. cache.commit()
  452. if args.stats:
  453. logger.info(stats.summary.format(label='Deleted data:', stats=stats))
  454. logger.info(str(cache))
  455. return self.exit_code
  456. def do_upgrade(self, args):
  457. """upgrade a repository from a previous version"""
  458. # XXX: currently only upgrades from Attic repositories, but may
  459. # eventually be extended to deal with major upgrades for borg
  460. # itself.
  461. #
  462. # in this case, it should auto-detect the current repository
  463. # format and fire up necessary upgrade mechanism. this remains
  464. # to be implemented.
  465. # XXX: should auto-detect if it is an attic repository here
  466. repo = AtticRepositoryUpgrader(args.repository.path, create=False)
  467. try:
  468. repo.upgrade(args.dry_run, inplace=args.inplace)
  469. except NotImplementedError as e:
  470. print("warning: %s" % e)
  471. return self.exit_code
  472. helptext = {}
  473. helptext['patterns'] = '''
  474. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  475. number of characters, '?' matching any single character, '[...]' matching any
  476. single character specified, including ranges, and '[!...]' matching any
  477. character not specified. For the purpose of these patterns, the path
  478. separator ('\\' for Windows and '/' on other systems) is not treated
  479. specially. For a path to match a pattern, it must completely match from
  480. start to end, or must match from the start to just before a path separator.
  481. Except for the root path, paths will never end in the path separator when
  482. matching is attempted. Thus, if a given pattern ends in a path separator, a
  483. '*' is appended before matching is attempted. Patterns with wildcards should
  484. be quoted to protect them from shell expansion.
  485. Examples:
  486. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  487. $ borg create -e '*.o' backup /
  488. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  489. # not '/home/user/importantjunk' or '/etc/junk':
  490. $ borg create -e '/home/*/junk' backup /
  491. # Exclude the contents of '/home/user/cache' but not the directory itself:
  492. $ borg create -e /home/user/cache/ backup /
  493. # The file '/home/user/cache/important' is *not* backed up:
  494. $ borg create -e /home/user/cache/ backup / /home/user/cache/important
  495. '''
  496. def do_help(self, parser, commands, args):
  497. if not args.topic:
  498. parser.print_help()
  499. elif args.topic in self.helptext:
  500. print(self.helptext[args.topic])
  501. elif args.topic in commands:
  502. if args.epilog_only:
  503. print(commands[args.topic].epilog)
  504. elif args.usage_only:
  505. commands[args.topic].epilog = None
  506. commands[args.topic].print_help()
  507. else:
  508. commands[args.topic].print_help()
  509. else:
  510. parser.error('No help available on %s' % (args.topic,))
  511. return self.exit_code
  512. def preprocess_args(self, args):
  513. deprecations = [
  514. ('--hourly', '--keep-hourly', 'Warning: "--hourly" has been deprecated. Use "--keep-hourly" instead.'),
  515. ('--daily', '--keep-daily', 'Warning: "--daily" has been deprecated. Use "--keep-daily" instead.'),
  516. ('--weekly', '--keep-weekly', 'Warning: "--weekly" has been deprecated. Use "--keep-weekly" instead.'),
  517. ('--monthly', '--keep-monthly', 'Warning: "--monthly" has been deprecated. Use "--keep-monthly" instead.'),
  518. ('--yearly', '--keep-yearly', 'Warning: "--yearly" has been deprecated. Use "--keep-yearly" instead.'),
  519. ('--do-not-cross-mountpoints', '--one-file-system',
  520. 'Warning: "--do-no-cross-mountpoints" has been deprecated. Use "--one-file-system" instead.'),
  521. ]
  522. if args and args[0] == 'verify':
  523. print('Warning: "borg verify" has been deprecated. Use "borg extract --dry-run" instead.')
  524. args = ['extract', '--dry-run'] + args[1:]
  525. for i, arg in enumerate(args[:]):
  526. for old_name, new_name, warning in deprecations:
  527. if arg.startswith(old_name):
  528. args[i] = arg.replace(old_name, new_name)
  529. print(warning)
  530. return args
  531. def build_parser(self, args=None, prog=None):
  532. common_parser = argparse.ArgumentParser(add_help=False, prog=prog)
  533. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False,
  534. help='verbose output')
  535. common_parser.add_argument('--show-rc', dest='show_rc', action='store_true', default=False,
  536. help='show/log the return code (rc)')
  537. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false',
  538. help='do not load/update the file metadata cache used to detect unchanged files')
  539. common_parser.add_argument('--umask', dest='umask', type=lambda s: int(s, 8), default=RemoteRepository.umask, metavar='M',
  540. help='set umask to M (local and remote, default: %(default)s)')
  541. common_parser.add_argument('--remote-path', dest='remote_path', default=RemoteRepository.remote_path, metavar='PATH',
  542. help='set remote path to executable (default: "%(default)s")')
  543. parser = argparse.ArgumentParser(prog=prog, description='Borg - Deduplicated Backups')
  544. parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__,
  545. help='show version number and exit')
  546. subparsers = parser.add_subparsers(title='Available commands')
  547. serve_epilog = textwrap.dedent("""
  548. This command starts a repository server process. This command is usually not used manually.
  549. """)
  550. subparser = subparsers.add_parser('serve', parents=[common_parser],
  551. description=self.do_serve.__doc__, epilog=serve_epilog,
  552. formatter_class=argparse.RawDescriptionHelpFormatter)
  553. subparser.set_defaults(func=self.do_serve)
  554. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  555. metavar='PATH', help='restrict repository access to PATH')
  556. init_epilog = textwrap.dedent("""
  557. This command initializes an empty repository. A repository is a filesystem
  558. directory containing the deduplicated data from zero or more archives.
  559. Encryption can be enabled at repository init time.
  560. Please note that the 'passphrase' encryption mode is DEPRECATED (instead of it,
  561. consider using 'repokey').
  562. """)
  563. subparser = subparsers.add_parser('init', parents=[common_parser],
  564. description=self.do_init.__doc__, epilog=init_epilog,
  565. formatter_class=argparse.RawDescriptionHelpFormatter)
  566. subparser.set_defaults(func=self.do_init)
  567. subparser.add_argument('repository', metavar='REPOSITORY', nargs='?', default='',
  568. type=location_validator(archive=False),
  569. help='repository to create')
  570. subparser.add_argument('-e', '--encryption', dest='encryption',
  571. choices=('none', 'keyfile', 'repokey', 'passphrase'), default='none',
  572. help='select encryption key mode')
  573. check_epilog = textwrap.dedent("""
  574. The check command verifies the consistency of a repository and the corresponding archives.
  575. First, the underlying repository data files are checked:
  576. - For all segments the segment magic (header) is checked
  577. - For all objects stored in the segments, all metadata (e.g. crc and size) and
  578. all data is read. The read data is checked by size and CRC. Bit rot and other
  579. types of accidental damage can be detected this way.
  580. - If we are in repair mode and a integrity error is detected for a segment,
  581. we try to recover as many objects from the segment as possible.
  582. - In repair mode, it makes sure that the index is consistent with the data
  583. stored in the segments.
  584. - If you use a remote repo server via ssh:, the repo check is executed on the
  585. repo server without causing significant network traffic.
  586. - The repository check can be skipped using the --archives-only option.
  587. Second, the consistency and correctness of the archive metadata is verified:
  588. - Is the repo manifest present? If not, it is rebuilt from archive metadata
  589. chunks (this requires reading and decrypting of all metadata and data).
  590. - Check if archive metadata chunk is present. if not, remove archive from
  591. manifest.
  592. - For all files (items) in the archive, for all chunks referenced by these
  593. files, check if chunk is present (if not and we are in repair mode, replace
  594. it with a same-size chunk of zeros). This requires reading of archive and
  595. file metadata, but not data.
  596. - If we are in repair mode and we checked all the archives: delete orphaned
  597. chunks from the repo.
  598. - if you use a remote repo server via ssh:, the archive check is executed on
  599. the client machine (because if encryption is enabled, the checks will require
  600. decryption and this is always done client-side, because key access will be
  601. required).
  602. - The archive checks can be time consuming, they can be skipped using the
  603. --repository-only option.
  604. """)
  605. subparser = subparsers.add_parser('check', parents=[common_parser],
  606. description=self.do_check.__doc__,
  607. epilog=check_epilog,
  608. formatter_class=argparse.RawDescriptionHelpFormatter)
  609. subparser.set_defaults(func=self.do_check)
  610. subparser.add_argument('repository', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  611. type=location_validator(),
  612. help='repository or archive to check consistency of')
  613. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  614. default=False,
  615. help='only perform repository checks')
  616. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  617. default=False,
  618. help='only perform archives checks')
  619. subparser.add_argument('--repair', dest='repair', action='store_true',
  620. default=False,
  621. help='attempt to repair any inconsistencies found')
  622. subparser.add_argument('--last', dest='last',
  623. type=int, default=None, metavar='N',
  624. help='only check last N archives (Default: all)')
  625. change_passphrase_epilog = textwrap.dedent("""
  626. The key files used for repository encryption are optionally passphrase
  627. protected. This command can be used to change this passphrase.
  628. """)
  629. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  630. description=self.do_change_passphrase.__doc__,
  631. epilog=change_passphrase_epilog,
  632. formatter_class=argparse.RawDescriptionHelpFormatter)
  633. subparser.set_defaults(func=self.do_change_passphrase)
  634. subparser.add_argument('repository', metavar='REPOSITORY', nargs='?', default='',
  635. type=location_validator(archive=False))
  636. create_epilog = textwrap.dedent("""
  637. This command creates a backup archive containing all files found while recursively
  638. traversing all paths specified. The archive will consume almost no disk space for
  639. files or parts of files that have already been stored in other archives.
  640. See the output of the "borg help patterns" command for more help on exclude patterns.
  641. """)
  642. subparser = subparsers.add_parser('create', parents=[common_parser],
  643. description=self.do_create.__doc__,
  644. epilog=create_epilog,
  645. formatter_class=argparse.RawDescriptionHelpFormatter)
  646. subparser.set_defaults(func=self.do_create)
  647. subparser.add_argument('-s', '--stats', dest='stats',
  648. action='store_true', default=False,
  649. help='print statistics for the created archive')
  650. subparser.add_argument('-p', '--progress', dest='progress', const=not sys.stderr.isatty(),
  651. action='store_const', default=sys.stdin.isatty(),
  652. help="""toggle progress display while creating the archive, showing Original,
  653. Compressed and Deduplicated sizes, followed by the Number of files seen
  654. and the path being processed, default: %(default)s""")
  655. subparser.add_argument('-e', '--exclude', dest='excludes',
  656. type=ExcludePattern, action='append',
  657. metavar="PATTERN", help='exclude paths matching PATTERN')
  658. subparser.add_argument('--exclude-from', dest='exclude_files',
  659. type=argparse.FileType('r'), action='append',
  660. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  661. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  662. action='store_true', default=False,
  663. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  664. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  665. type=int, default=300, metavar='SECONDS',
  666. help='write checkpoint every SECONDS seconds (Default: 300)')
  667. subparser.add_argument('-x', '--one-file-system', dest='one_file_system',
  668. action='store_true', default=False,
  669. help='stay in same file system, do not cross mount points')
  670. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  671. action='store_true', default=False,
  672. help='only store numeric user and group identifiers')
  673. subparser.add_argument('--timestamp', dest='timestamp',
  674. type=timestamp, default=None,
  675. metavar='yyyy-mm-ddThh:mm:ss',
  676. help='manually specify the archive creation date/time (UTC). '
  677. 'alternatively, give a reference file/directory.')
  678. subparser.add_argument('--chunker-params', dest='chunker_params',
  679. type=ChunkerParams, default=CHUNKER_PARAMS,
  680. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  681. help='specify the chunker parameters. default: %d,%d,%d,%d' % CHUNKER_PARAMS)
  682. subparser.add_argument('-C', '--compression', dest='compression',
  683. type=CompressionSpec, default=dict(name='none'), metavar='COMPRESSION',
  684. help='select compression algorithm (and level): '
  685. 'none == no compression (default), '
  686. 'lz4 == lz4, '
  687. 'zlib == zlib (default level 6), '
  688. 'zlib,0 .. zlib,9 == zlib (with level 0..9), '
  689. 'lzma == lzma (default level 6), '
  690. 'lzma,0 .. lzma,9 == lzma (with level 0..9).')
  691. subparser.add_argument('--read-special', dest='read_special',
  692. action='store_true', default=False,
  693. help='open and read special files as if they were regular files')
  694. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  695. action='store_true', default=False,
  696. help='do not create a backup archive')
  697. subparser.add_argument('archive', metavar='ARCHIVE',
  698. type=location_validator(archive=True),
  699. help='name of archive to create (must be also a valid directory name)')
  700. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  701. help='paths to archive')
  702. extract_epilog = textwrap.dedent("""
  703. This command extracts the contents of an archive. By default the entire
  704. archive is extracted but a subset of files and directories can be selected
  705. by passing a list of ``PATHs`` as arguments. The file selection can further
  706. be restricted by using the ``--exclude`` option.
  707. See the output of the "borg help patterns" command for more help on exclude patterns.
  708. """)
  709. subparser = subparsers.add_parser('extract', parents=[common_parser],
  710. description=self.do_extract.__doc__,
  711. epilog=extract_epilog,
  712. formatter_class=argparse.RawDescriptionHelpFormatter)
  713. subparser.set_defaults(func=self.do_extract)
  714. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  715. default=False, action='store_true',
  716. help='do not actually change any files')
  717. subparser.add_argument('-e', '--exclude', dest='excludes',
  718. type=ExcludePattern, action='append',
  719. metavar="PATTERN", help='exclude paths matching PATTERN')
  720. subparser.add_argument('--exclude-from', dest='exclude_files',
  721. type=argparse.FileType('r'), action='append',
  722. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  723. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  724. action='store_true', default=False,
  725. help='only obey numeric user and group identifiers')
  726. subparser.add_argument('--strip-components', dest='strip_components',
  727. type=int, default=0, metavar='NUMBER',
  728. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  729. subparser.add_argument('--stdout', dest='stdout',
  730. action='store_true', default=False,
  731. help='write all extracted data to stdout')
  732. subparser.add_argument('--sparse', dest='sparse',
  733. action='store_true', default=False,
  734. help='create holes in output sparse file from all-zero chunks')
  735. subparser.add_argument('archive', metavar='ARCHIVE',
  736. type=location_validator(archive=True),
  737. help='archive to extract')
  738. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  739. help='paths to extract')
  740. rename_epilog = textwrap.dedent("""
  741. This command renames an archive in the repository.
  742. """)
  743. subparser = subparsers.add_parser('rename', parents=[common_parser],
  744. description=self.do_rename.__doc__,
  745. epilog=rename_epilog,
  746. formatter_class=argparse.RawDescriptionHelpFormatter)
  747. subparser.set_defaults(func=self.do_rename)
  748. subparser.add_argument('archive', metavar='ARCHIVE',
  749. type=location_validator(archive=True),
  750. help='archive to rename')
  751. subparser.add_argument('name', metavar='NEWNAME', type=str,
  752. help='the new archive name to use')
  753. delete_epilog = textwrap.dedent("""
  754. This command deletes an archive from the repository or the complete repository.
  755. Disk space is reclaimed accordingly. If you delete the complete repository, the
  756. local cache for it (if any) is also deleted.
  757. """)
  758. subparser = subparsers.add_parser('delete', parents=[common_parser],
  759. description=self.do_delete.__doc__,
  760. epilog=delete_epilog,
  761. formatter_class=argparse.RawDescriptionHelpFormatter)
  762. subparser.set_defaults(func=self.do_delete)
  763. subparser.add_argument('-s', '--stats', dest='stats',
  764. action='store_true', default=False,
  765. help='print statistics for the deleted archive')
  766. subparser.add_argument('-c', '--cache-only', dest='cache_only',
  767. action='store_true', default=False,
  768. help='delete only the local cache for the given repository')
  769. subparser.add_argument('target', metavar='TARGET', nargs='?', default='',
  770. type=location_validator(),
  771. help='archive or repository to delete')
  772. list_epilog = textwrap.dedent("""
  773. This command lists the contents of a repository or an archive.
  774. """)
  775. subparser = subparsers.add_parser('list', parents=[common_parser],
  776. description=self.do_list.__doc__,
  777. epilog=list_epilog,
  778. formatter_class=argparse.RawDescriptionHelpFormatter)
  779. subparser.set_defaults(func=self.do_list)
  780. subparser.add_argument('--short', dest='short',
  781. action='store_true', default=False,
  782. help='only print file/directory names, nothing else')
  783. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', nargs='?', default='',
  784. type=location_validator(),
  785. help='repository/archive to list contents of')
  786. mount_epilog = textwrap.dedent("""
  787. This command mounts an archive as a FUSE filesystem. This can be useful for
  788. browsing an archive or restoring individual files. Unless the ``--foreground``
  789. option is given the command will run in the background until the filesystem
  790. is ``umounted``.
  791. """)
  792. subparser = subparsers.add_parser('mount', parents=[common_parser],
  793. description=self.do_mount.__doc__,
  794. epilog=mount_epilog,
  795. formatter_class=argparse.RawDescriptionHelpFormatter)
  796. subparser.set_defaults(func=self.do_mount)
  797. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  798. help='repository/archive to mount')
  799. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  800. help='where to mount filesystem')
  801. subparser.add_argument('-f', '--foreground', dest='foreground',
  802. action='store_true', default=False,
  803. help='stay in foreground, do not daemonize')
  804. subparser.add_argument('-o', dest='options', type=str,
  805. help='Extra mount options')
  806. info_epilog = textwrap.dedent("""
  807. This command displays some detailed information about the specified archive.
  808. """)
  809. subparser = subparsers.add_parser('info', parents=[common_parser],
  810. description=self.do_info.__doc__,
  811. epilog=info_epilog,
  812. formatter_class=argparse.RawDescriptionHelpFormatter)
  813. subparser.set_defaults(func=self.do_info)
  814. subparser.add_argument('archive', metavar='ARCHIVE',
  815. type=location_validator(archive=True),
  816. help='archive to display information about')
  817. prune_epilog = textwrap.dedent("""
  818. The prune command prunes a repository by deleting archives not matching
  819. any of the specified retention options. This command is normally used by
  820. automated backup scripts wanting to keep a certain number of historic backups.
  821. As an example, "-d 7" means to keep the latest backup on each day for 7 days.
  822. Days without backups do not count towards the total.
  823. The rules are applied from hourly to yearly, and backups selected by previous
  824. rules do not count towards those of later rules. The time that each backup
  825. completes is used for pruning purposes. Dates and times are interpreted in
  826. the local timezone, and weeks go from Monday to Sunday. Specifying a
  827. negative number of archives to keep means that there is no limit.
  828. The "--keep-within" option takes an argument of the form "<int><char>",
  829. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  830. to keep all archives that were created within the past 48 hours.
  831. "1m" is taken to mean "31d". The archives kept with this option do not
  832. count towards the totals specified by any other options.
  833. If a prefix is set with -p, then only archives that start with the prefix are
  834. considered for deletion and only those archives count towards the totals
  835. specified by the rules.
  836. Otherwise, *all* archives in the repository are candidates for deletion!
  837. """)
  838. subparser = subparsers.add_parser('prune', parents=[common_parser],
  839. description=self.do_prune.__doc__,
  840. epilog=prune_epilog,
  841. formatter_class=argparse.RawDescriptionHelpFormatter)
  842. subparser.set_defaults(func=self.do_prune)
  843. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  844. default=False, action='store_true',
  845. help='do not change repository')
  846. subparser.add_argument('-s', '--stats', dest='stats',
  847. action='store_true', default=False,
  848. help='print statistics for the deleted archive')
  849. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  850. help='keep all archives within this time interval')
  851. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  852. help='number of hourly archives to keep')
  853. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  854. help='number of daily archives to keep')
  855. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  856. help='number of weekly archives to keep')
  857. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  858. help='number of monthly archives to keep')
  859. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  860. help='number of yearly archives to keep')
  861. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  862. help='only consider archive names starting with this prefix')
  863. subparser.add_argument('repository', metavar='REPOSITORY', nargs='?', default='',
  864. type=location_validator(archive=False),
  865. help='repository to prune')
  866. upgrade_epilog = textwrap.dedent("""
  867. upgrade an existing Borg repository. this currently
  868. only support converting an Attic repository, but may
  869. eventually be extended to cover major Borg upgrades as well.
  870. it will change the magic strings in the repository's segments
  871. to match the new Borg magic strings. the keyfiles found in
  872. $ATTIC_KEYS_DIR or ~/.attic/keys/ will also be converted and
  873. copied to $BORG_KEYS_DIR or ~/.borg/keys.
  874. the cache files are converted, from $ATTIC_CACHE_DIR or
  875. ~/.cache/attic to $BORG_CACHE_DIR or ~/.cache/borg, but the
  876. cache layout between Borg and Attic changed, so it is possible
  877. the first backup after the conversion takes longer than expected
  878. due to the cache resync.
  879. upgrade should be able to resume if interrupted, although it
  880. will still iterate over all segments. if you want to start
  881. from scratch, use `borg delete` over the copied repository to
  882. make sure the cache files are also removed:
  883. borg delete borg
  884. unless ``--inplace`` is specified, the upgrade process first
  885. creates a backup copy of the repository, in
  886. REPOSITORY.upgrade-DATETIME, using hardlinks. this takes
  887. longer than in place upgrades, but is much safer and gives
  888. progress information (as opposed to ``cp -al``). once you are
  889. satisfied with the conversion, you can safely destroy the
  890. backup copy.
  891. WARNING: running the upgrade in place will make the current
  892. copy unusable with older version, with no way of going back
  893. to previous versions. this can PERMANENTLY DAMAGE YOUR
  894. REPOSITORY! Attic CAN NOT READ BORG REPOSITORIES, as the
  895. magic strings have changed. you have been warned.""")
  896. subparser = subparsers.add_parser('upgrade', parents=[common_parser],
  897. description=self.do_upgrade.__doc__,
  898. epilog=upgrade_epilog,
  899. formatter_class=argparse.RawDescriptionHelpFormatter)
  900. subparser.set_defaults(func=self.do_upgrade)
  901. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  902. default=False, action='store_true',
  903. help='do not change repository')
  904. subparser.add_argument('-i', '--inplace', dest='inplace',
  905. default=False, action='store_true',
  906. help="""rewrite repository in place, with no chance of going back to older
  907. versions of the repository.""")
  908. subparser.add_argument('repository', metavar='REPOSITORY', nargs='?', default='',
  909. type=location_validator(archive=False),
  910. help='path to the repository to be upgraded')
  911. subparser = subparsers.add_parser('help', parents=[common_parser],
  912. description='Extra help')
  913. subparser.add_argument('--epilog-only', dest='epilog_only',
  914. action='store_true', default=False)
  915. subparser.add_argument('--usage-only', dest='usage_only',
  916. action='store_true', default=False)
  917. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  918. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  919. help='additional help on TOPIC')
  920. return parser
  921. def parse_args(self, args=None):
  922. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  923. if args:
  924. args = self.preprocess_args(args)
  925. parser = self.build_parser(args)
  926. args = parser.parse_args(args or ['-h'])
  927. update_excludes(args)
  928. return args
  929. def run(self, args):
  930. os.umask(args.umask) # early, before opening files
  931. self.verbose = args.verbose
  932. RemoteRepository.remote_path = args.remote_path
  933. RemoteRepository.umask = args.umask
  934. setup_logging()
  935. check_extension_modules()
  936. keys_dir = get_keys_dir()
  937. if not os.path.exists(keys_dir):
  938. os.makedirs(keys_dir)
  939. os.chmod(keys_dir, stat.S_IRWXU)
  940. cache_dir = get_cache_dir()
  941. if not os.path.exists(cache_dir):
  942. os.makedirs(cache_dir)
  943. os.chmod(cache_dir, stat.S_IRWXU)
  944. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  945. fd.write(textwrap.dedent("""
  946. Signature: 8a477f597d28d172789f06886806bc55
  947. # This file is a cache directory tag created by Borg.
  948. # For information about cache directory tags, see:
  949. # http://www.brynosaurus.com/cachedir/
  950. """).lstrip())
  951. if is_slow_msgpack():
  952. logger.warning("Using a pure-python msgpack! This will result in lower performance.")
  953. return args.func(args)
  954. def sig_info_handler(signum, stack): # pragma: no cover
  955. """search the stack for infos about the currently processed file and print them"""
  956. for frame in inspect.getouterframes(stack):
  957. func, loc = frame[3], frame[0].f_locals
  958. if func in ('process_file', '_process', ): # create op
  959. path = loc['path']
  960. try:
  961. pos = loc['fd'].tell()
  962. total = loc['st'].st_size
  963. except Exception:
  964. pos, total = 0, 0
  965. logger.info("{0} {1}/{2}".format(path, format_file_size(pos), format_file_size(total)))
  966. break
  967. if func in ('extract_item', ): # extract op
  968. path = loc['item'][b'path']
  969. try:
  970. pos = loc['fd'].tell()
  971. except Exception:
  972. pos = 0
  973. logger.info("{0} {1}/???".format(path, format_file_size(pos)))
  974. break
  975. def setup_signal_handlers(): # pragma: no cover
  976. sigs = []
  977. if hasattr(signal, 'SIGUSR1'):
  978. sigs.append(signal.SIGUSR1) # kill -USR1 pid
  979. if hasattr(signal, 'SIGINFO'):
  980. sigs.append(signal.SIGINFO) # kill -INFO pid (or ctrl-t)
  981. for sig in sigs:
  982. signal.signal(sig, sig_info_handler)
  983. def main(): # pragma: no cover
  984. # Make sure stdout and stderr have errors='replace') to avoid unicode
  985. # issues when print()-ing unicode file names
  986. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  987. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  988. setup_signal_handlers()
  989. archiver = Archiver()
  990. msg = None
  991. args = archiver.parse_args(sys.argv[1:])
  992. try:
  993. exit_code = archiver.run(args)
  994. except Error as e:
  995. msg = e.get_message()
  996. if e.traceback:
  997. msg += "\n%s" % traceback.format_exc()
  998. exit_code = e.exit_code
  999. except RemoteRepository.RPCError as e:
  1000. msg = 'Remote Exception.\n%s' % str(e)
  1001. exit_code = EXIT_ERROR
  1002. except Exception:
  1003. msg = 'Local Exception.\n%s' % traceback.format_exc()
  1004. exit_code = EXIT_ERROR
  1005. except KeyboardInterrupt:
  1006. msg = 'Keyboard interrupt.\n%s' % traceback.format_exc()
  1007. exit_code = EXIT_ERROR
  1008. if msg:
  1009. logger.error(msg)
  1010. if args.show_rc:
  1011. exit_msg = 'terminating with %s status, rc %d'
  1012. if exit_code == EXIT_SUCCESS:
  1013. logger.info(exit_msg % ('success', exit_code))
  1014. elif exit_code == EXIT_WARNING:
  1015. logger.warning(exit_msg % ('warning', exit_code))
  1016. elif exit_code == EXIT_ERROR:
  1017. logger.error(exit_msg % ('error', exit_code))
  1018. else:
  1019. # if you see 666 in output, it usually means exit_code was None
  1020. logger.error(exit_msg % ('abnormal', exit_code or 666))
  1021. sys.exit(exit_code)
  1022. if __name__ == '__main__':
  1023. main()