archiver.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. import argparse
  2. from binascii import hexlify
  3. from datetime import datetime
  4. from operator import attrgetter
  5. import functools
  6. import io
  7. import os
  8. import stat
  9. import sys
  10. import textwrap
  11. from attic import __version__
  12. from attic.archive import Archive, ArchiveChecker
  13. from attic.repository import Repository
  14. from attic.cache import Cache
  15. from attic.key import key_creator
  16. from attic.helpers import Error, location_validator, format_time, \
  17. format_file_mode, ExcludePattern, exclude_path, adjust_patterns, to_localtime, timestamp, \
  18. get_cache_dir, get_keys_dir, format_timedelta, prune_within, prune_split, \
  19. Manifest, remove_surrogates, update_excludes, format_archive, check_extension_modules, Statistics, \
  20. is_cachedir, bigint_to_int
  21. from attic.remote import RepositoryServer, RemoteRepository
  22. class Archiver:
  23. def __init__(self):
  24. self.exit_code = 0
  25. def open_repository(self, location, create=False, exclusive=False):
  26. if location.proto == 'ssh':
  27. repository = RemoteRepository(location, create=create)
  28. else:
  29. repository = Repository(location.path, create=create, exclusive=exclusive)
  30. repository._location = location
  31. return repository
  32. def print_error(self, msg, *args):
  33. msg = args and msg % args or msg
  34. self.exit_code = 1
  35. print('borg: ' + msg, file=sys.stderr)
  36. def print_verbose(self, msg, *args, **kw):
  37. if self.verbose:
  38. msg = args and msg % args or msg
  39. if kw.get('newline', True):
  40. print(msg)
  41. else:
  42. print(msg, end=' ')
  43. def do_serve(self, args):
  44. """Start in server mode. This command is usually not used manually.
  45. """
  46. return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()
  47. def do_init(self, args):
  48. """Initialize an empty repository"""
  49. print('Initializing repository at "%s"' % args.repository.orig)
  50. repository = self.open_repository(args.repository, create=True, exclusive=True)
  51. key = key_creator(repository, args)
  52. manifest = Manifest(key, repository)
  53. manifest.key = key
  54. manifest.write()
  55. repository.commit()
  56. Cache(repository, key, manifest, warn_if_unencrypted=False)
  57. return self.exit_code
  58. def do_check(self, args):
  59. """Check repository consistency"""
  60. repository = self.open_repository(args.repository, exclusive=args.repair)
  61. if args.repair:
  62. while not os.environ.get('BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  63. self.print_error("""Warning: 'check --repair' is an experimental feature that might result
  64. in data loss.
  65. Type "Yes I am sure" if you understand this and want to continue.\n""")
  66. if input('Do you want to continue? ') == 'Yes I am sure':
  67. break
  68. if not args.archives_only:
  69. print('Starting repository check...')
  70. if repository.check(repair=args.repair):
  71. print('Repository check complete, no problems found.')
  72. else:
  73. return 1
  74. if not args.repo_only and not ArchiveChecker().check(repository, repair=args.repair, last=args.last):
  75. return 1
  76. return 0
  77. def do_change_passphrase(self, args):
  78. """Change repository key file passphrase"""
  79. repository = self.open_repository(args.repository)
  80. manifest, key = Manifest.load(repository)
  81. key.change_passphrase()
  82. return 0
  83. def do_create(self, args):
  84. """Create new archive"""
  85. t0 = datetime.now()
  86. repository = self.open_repository(args.archive, exclusive=True)
  87. manifest, key = Manifest.load(repository)
  88. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  89. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,
  90. create=True, checkpoint_interval=args.checkpoint_interval,
  91. numeric_owner=args.numeric_owner, progress=args.progress)
  92. # Add cache dir to inode_skip list
  93. skip_inodes = set()
  94. try:
  95. st = os.stat(get_cache_dir())
  96. skip_inodes.add((st.st_ino, st.st_dev))
  97. except IOError:
  98. pass
  99. # Add local repository dir to inode_skip list
  100. if not args.archive.host:
  101. try:
  102. st = os.stat(args.archive.path)
  103. skip_inodes.add((st.st_ino, st.st_dev))
  104. except IOError:
  105. pass
  106. for path in args.paths:
  107. if path == '-': # stdin
  108. path = 'stdin'
  109. self.print_verbose(path)
  110. try:
  111. archive.process_stdin(path, cache)
  112. except IOError as e:
  113. self.print_error('%s: %s', path, e)
  114. continue
  115. path = os.path.normpath(path)
  116. if args.dontcross:
  117. try:
  118. restrict_dev = os.lstat(path).st_dev
  119. except OSError as e:
  120. self.print_error('%s: %s', path, e)
  121. continue
  122. else:
  123. restrict_dev = None
  124. self._process(archive, cache, args.excludes, args.exclude_caches, skip_inodes, path, restrict_dev)
  125. archive.save(timestamp=args.timestamp)
  126. if args.progress:
  127. archive.stats.show_progress(final=True)
  128. if args.stats:
  129. t = datetime.now()
  130. diff = t - t0
  131. print('-' * 78)
  132. print('Archive name: %s' % args.archive.archive)
  133. print('Archive fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  134. print('Start time: %s' % t0.strftime('%c'))
  135. print('End time: %s' % t.strftime('%c'))
  136. print('Duration: %s' % format_timedelta(diff))
  137. print('Number of files: %d' % archive.stats.nfiles)
  138. archive.stats.print_('This archive:', cache)
  139. print('-' * 78)
  140. return self.exit_code
  141. def _process(self, archive, cache, excludes, exclude_caches, skip_inodes, path, restrict_dev):
  142. if exclude_path(path, excludes):
  143. return
  144. try:
  145. st = os.lstat(path)
  146. except OSError as e:
  147. self.print_error('%s: %s', path, e)
  148. return
  149. if (st.st_ino, st.st_dev) in skip_inodes:
  150. return
  151. # Entering a new filesystem?
  152. if restrict_dev and st.st_dev != restrict_dev:
  153. return
  154. # Ignore unix sockets
  155. if stat.S_ISSOCK(st.st_mode):
  156. return
  157. status = None
  158. if stat.S_ISREG(st.st_mode):
  159. try:
  160. status = archive.process_file(path, st, cache)
  161. except IOError as e:
  162. self.print_error('%s: %s', path, e)
  163. elif stat.S_ISDIR(st.st_mode):
  164. if exclude_caches and is_cachedir(path):
  165. return
  166. status = archive.process_dir(path, st)
  167. try:
  168. entries = os.listdir(path)
  169. except OSError as e:
  170. self.print_error('%s: %s', path, e)
  171. else:
  172. for filename in sorted(entries):
  173. entry_path = os.path.normpath(os.path.join(path, filename))
  174. self._process(archive, cache, excludes, exclude_caches, skip_inodes,
  175. entry_path, restrict_dev)
  176. elif stat.S_ISLNK(st.st_mode):
  177. status = archive.process_symlink(path, st)
  178. elif stat.S_ISFIFO(st.st_mode):
  179. status = archive.process_fifo(path, st)
  180. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  181. status = archive.process_dev(path, st)
  182. else:
  183. self.print_error('Unknown file type: %s', path)
  184. return
  185. # Status output
  186. # A lowercase character means a file type other than a regular file,
  187. # borg usually just stores them. E.g. (d)irectory.
  188. # Hardlinks to already seen content are indicated by (h).
  189. # A uppercase character means a regular file that was (A)dded,
  190. # (M)odified or was (U)nchanged.
  191. # Note: A/M/U is relative to the "files" cache, not to the repo.
  192. # This would be an issue if the files cache is not used.
  193. if status is None:
  194. status = '?' # need to add a status code somewhere
  195. # output ALL the stuff - it can be easily filtered using grep.
  196. # even stuff considered unchanged might be interesting.
  197. self.print_verbose("%1s %s", status, remove_surrogates(path))
  198. def do_extract(self, args):
  199. """Extract archive contents"""
  200. # be restrictive when restoring files, restore permissions later
  201. if sys.getfilesystemencoding() == 'ascii':
  202. print('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  203. os.umask(0o077)
  204. repository = self.open_repository(args.archive)
  205. manifest, key = Manifest.load(repository)
  206. archive = Archive(repository, key, manifest, args.archive.archive,
  207. numeric_owner=args.numeric_owner)
  208. patterns = adjust_patterns(args.paths, args.excludes)
  209. dry_run = args.dry_run
  210. stdout = args.stdout
  211. sparse = args.sparse
  212. strip_components = args.strip_components
  213. dirs = []
  214. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  215. orig_path = item[b'path']
  216. if strip_components:
  217. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  218. if not item[b'path']:
  219. continue
  220. if not args.dry_run:
  221. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  222. archive.extract_item(dirs.pop(-1), stdout=stdout)
  223. self.print_verbose(remove_surrogates(orig_path))
  224. try:
  225. if dry_run:
  226. archive.extract_item(item, dry_run=True)
  227. else:
  228. if stat.S_ISDIR(item[b'mode']):
  229. dirs.append(item)
  230. archive.extract_item(item, restore_attrs=False)
  231. else:
  232. archive.extract_item(item, stdout=stdout, sparse=sparse)
  233. except IOError as e:
  234. self.print_error('%s: %s', remove_surrogates(orig_path), e)
  235. if not args.dry_run:
  236. while dirs:
  237. archive.extract_item(dirs.pop(-1))
  238. return self.exit_code
  239. def do_rename(self, args):
  240. """Rename an existing archive"""
  241. repository = self.open_repository(args.archive, exclusive=True)
  242. manifest, key = Manifest.load(repository)
  243. cache = Cache(repository, key, manifest)
  244. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  245. archive.rename(args.name)
  246. manifest.write()
  247. repository.commit()
  248. cache.commit()
  249. return self.exit_code
  250. def do_delete(self, args):
  251. """Delete an existing repository or archive"""
  252. repository = self.open_repository(args.target, exclusive=True)
  253. manifest, key = Manifest.load(repository)
  254. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  255. if args.target.archive:
  256. archive = Archive(repository, key, manifest, args.target.archive, cache=cache)
  257. stats = Statistics()
  258. archive.delete(stats)
  259. manifest.write()
  260. repository.commit()
  261. cache.commit()
  262. if args.stats:
  263. stats.print_('Deleted data:', cache)
  264. else:
  265. print("You requested to completely DELETE the repository *including* all archives it contains:")
  266. for archive in sorted(Archive.list_archives(repository, key, manifest), key=attrgetter('ts')):
  267. print(format_archive(archive))
  268. print("""Type "YES" if you understand this and want to continue.\n""")
  269. if input('Do you want to continue? ') == 'YES':
  270. repository.destroy()
  271. cache.destroy()
  272. print("Repository and corresponding cache were deleted.")
  273. return self.exit_code
  274. def do_mount(self, args):
  275. """Mount archive or an entire repository as a FUSE fileystem"""
  276. try:
  277. from attic.fuse import AtticOperations
  278. except ImportError as e:
  279. self.print_error('loading fuse support failed [ImportError: %s]' % str(e))
  280. return self.exit_code
  281. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  282. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  283. return self.exit_code
  284. repository = self.open_repository(args.src)
  285. manifest, key = Manifest.load(repository)
  286. if args.src.archive:
  287. archive = Archive(repository, key, manifest, args.src.archive)
  288. else:
  289. archive = None
  290. operations = AtticOperations(key, repository, manifest, archive)
  291. self.print_verbose("Mounting filesystem")
  292. try:
  293. operations.mount(args.mountpoint, args.options, args.foreground)
  294. except RuntimeError:
  295. # Relevant error message already printed to stderr by fuse
  296. self.exit_code = 1
  297. return self.exit_code
  298. def do_list(self, args):
  299. """List archive or repository contents"""
  300. repository = self.open_repository(args.src)
  301. manifest, key = Manifest.load(repository)
  302. if args.src.archive:
  303. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  304. archive = Archive(repository, key, manifest, args.src.archive)
  305. for item in archive.iter_items():
  306. type = tmap.get(item[b'mode'] // 4096, '?')
  307. mode = format_file_mode(item[b'mode'])
  308. size = 0
  309. if type == '-':
  310. try:
  311. size = sum(size for _, size, _ in item[b'chunks'])
  312. except KeyError:
  313. pass
  314. try:
  315. mtime = datetime.fromtimestamp(bigint_to_int(item[b'mtime']) / 1e9)
  316. except ValueError:
  317. # likely a broken mtime and datetime did not want to go beyond year 9999
  318. mtime = datetime(9999, 12, 31, 23, 59, 59)
  319. if b'source' in item:
  320. if type == 'l':
  321. extra = ' -> %s' % item[b'source']
  322. else:
  323. type = 'h'
  324. extra = ' link to %s' % item[b'source']
  325. else:
  326. extra = ''
  327. print('%s%s %-6s %-6s %8d %s %s%s' % (
  328. type, mode, item[b'user'] or item[b'uid'],
  329. item[b'group'] or item[b'gid'], size, format_time(mtime),
  330. remove_surrogates(item[b'path']), extra))
  331. else:
  332. for archive in sorted(Archive.list_archives(repository, key, manifest), key=attrgetter('ts')):
  333. print(format_archive(archive))
  334. return self.exit_code
  335. def do_info(self, args):
  336. """Show archive details such as disk space used"""
  337. repository = self.open_repository(args.archive)
  338. manifest, key = Manifest.load(repository)
  339. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  340. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  341. stats = archive.calc_stats(cache)
  342. print('Name:', archive.name)
  343. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  344. print('Hostname:', archive.metadata[b'hostname'])
  345. print('Username:', archive.metadata[b'username'])
  346. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  347. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  348. print('Number of files: %d' % stats.nfiles)
  349. stats.print_('This archive:', cache)
  350. return self.exit_code
  351. def do_prune(self, args):
  352. """Prune repository archives according to specified rules"""
  353. repository = self.open_repository(args.repository, exclusive=True)
  354. manifest, key = Manifest.load(repository)
  355. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  356. archives = list(sorted(Archive.list_archives(repository, key, manifest, cache),
  357. key=attrgetter('ts'), reverse=True))
  358. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  359. self.print_error('At least one of the "within", "hourly", "daily", "weekly", "monthly" or "yearly" '
  360. 'settings must be specified')
  361. return 1
  362. if args.prefix:
  363. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  364. keep = []
  365. if args.within:
  366. keep += prune_within(archives, args.within)
  367. if args.hourly:
  368. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  369. if args.daily:
  370. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  371. if args.weekly:
  372. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  373. if args.monthly:
  374. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  375. if args.yearly:
  376. keep += prune_split(archives, '%Y', args.yearly, keep)
  377. keep.sort(key=attrgetter('ts'), reverse=True)
  378. to_delete = [a for a in archives if a not in keep]
  379. stats = Statistics()
  380. for archive in keep:
  381. self.print_verbose('Keeping archive: %s' % format_archive(archive))
  382. for archive in to_delete:
  383. if args.dry_run:
  384. self.print_verbose('Would prune: %s' % format_archive(archive))
  385. else:
  386. self.print_verbose('Pruning archive: %s' % format_archive(archive))
  387. archive.delete(stats)
  388. if to_delete and not args.dry_run:
  389. manifest.write()
  390. repository.commit()
  391. cache.commit()
  392. if args.stats:
  393. stats.print_('Deleted data:', cache)
  394. return self.exit_code
  395. helptext = {}
  396. helptext['patterns'] = '''
  397. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  398. number of characters, '?' matching any single character, '[...]' matching any
  399. single character specified, including ranges, and '[!...]' matching any
  400. character not specified. For the purpose of these patterns, the path
  401. separator ('\\' for Windows and '/' on other systems) is not treated
  402. specially. For a path to match a pattern, it must completely match from
  403. start to end, or must match from the start to just before a path separator.
  404. Except for the root path, paths will never end in the path separator when
  405. matching is attempted. Thus, if a given pattern ends in a path separator, a
  406. '*' is appended before matching is attempted. Patterns with wildcards should
  407. be quoted to protect them from shell expansion.
  408. Examples:
  409. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  410. $ borg create -e '*.o' repo.borg /
  411. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  412. # not '/home/user/importantjunk' or '/etc/junk':
  413. $ borg create -e '/home/*/junk' repo.borg /
  414. # Exclude the contents of '/home/user/cache' but not the directory itself:
  415. $ borg create -e /home/user/cache/ repo.borg /
  416. # The file '/home/user/cache/important' is *not* backed up:
  417. $ borg create -e /home/user/cache/ repo.borg / /home/user/cache/important
  418. '''
  419. def do_help(self, parser, commands, args):
  420. if not args.topic:
  421. parser.print_help()
  422. elif args.topic in self.helptext:
  423. print(self.helptext[args.topic])
  424. elif args.topic in commands:
  425. if args.epilog_only:
  426. print(commands[args.topic].epilog)
  427. elif args.usage_only:
  428. commands[args.topic].epilog = None
  429. commands[args.topic].print_help()
  430. else:
  431. commands[args.topic].print_help()
  432. else:
  433. parser.error('No help available on %s' % (args.topic,))
  434. return self.exit_code
  435. def preprocess_args(self, args):
  436. deprecations = [
  437. ('--hourly', '--keep-hourly', 'Warning: "--hourly" has been deprecated. Use "--keep-hourly" instead.'),
  438. ('--daily', '--keep-daily', 'Warning: "--daily" has been deprecated. Use "--keep-daily" instead.'),
  439. ('--weekly', '--keep-weekly', 'Warning: "--weekly" has been deprecated. Use "--keep-weekly" instead.'),
  440. ('--monthly', '--keep-monthly', 'Warning: "--monthly" has been deprecated. Use "--keep-monthly" instead.'),
  441. ('--yearly', '--keep-yearly', 'Warning: "--yearly" has been deprecated. Use "--keep-yearly" instead.')
  442. ]
  443. if args and args[0] == 'verify':
  444. print('Warning: "borg verify" has been deprecated. Use "borg extract --dry-run" instead.')
  445. args = ['extract', '--dry-run'] + args[1:]
  446. for i, arg in enumerate(args[:]):
  447. for old_name, new_name, warning in deprecations:
  448. if arg.startswith(old_name):
  449. args[i] = arg.replace(old_name, new_name)
  450. print(warning)
  451. return args
  452. def run(self, args=None):
  453. check_extension_modules()
  454. keys_dir = get_keys_dir()
  455. if not os.path.exists(keys_dir):
  456. os.makedirs(keys_dir)
  457. os.chmod(keys_dir, stat.S_IRWXU)
  458. cache_dir = get_cache_dir()
  459. if not os.path.exists(cache_dir):
  460. os.makedirs(cache_dir)
  461. os.chmod(cache_dir, stat.S_IRWXU)
  462. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  463. fd.write(textwrap.dedent("""
  464. Signature: 8a477f597d28d172789f06886806bc55
  465. # This file is a cache directory tag created by Borg.
  466. # For information about cache directory tags, see:
  467. # http://www.brynosaurus.com/cachedir/
  468. """).lstrip())
  469. common_parser = argparse.ArgumentParser(add_help=False)
  470. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  471. default=False,
  472. help='verbose output')
  473. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false')
  474. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  475. if args:
  476. args = self.preprocess_args(args)
  477. parser = argparse.ArgumentParser(description='Borg %s - Deduplicated Backups' % __version__)
  478. subparsers = parser.add_subparsers(title='Available commands')
  479. subparser = subparsers.add_parser('serve', parents=[common_parser],
  480. description=self.do_serve.__doc__)
  481. subparser.set_defaults(func=self.do_serve)
  482. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  483. metavar='PATH', help='restrict repository access to PATH')
  484. init_epilog = textwrap.dedent("""
  485. This command initializes an empty repository. A repository is a filesystem
  486. directory containing the deduplicated data from zero or more archives.
  487. Encryption can be enabled at repository init time.
  488. """)
  489. subparser = subparsers.add_parser('init', parents=[common_parser],
  490. description=self.do_init.__doc__, epilog=init_epilog,
  491. formatter_class=argparse.RawDescriptionHelpFormatter)
  492. subparser.set_defaults(func=self.do_init)
  493. subparser.add_argument('repository', metavar='REPOSITORY',
  494. type=location_validator(archive=False),
  495. help='repository to create')
  496. subparser.add_argument('-e', '--encryption', dest='encryption',
  497. choices=('none', 'passphrase', 'keyfile'), default='none',
  498. help='select encryption method')
  499. check_epilog = textwrap.dedent("""
  500. The check command verifies the consistency of a repository and the corresponding
  501. archives. The underlying repository data files are first checked to detect bit rot
  502. and other types of damage. After that the consistency and correctness of the archive
  503. metadata is verified.
  504. The archive metadata checks can be time consuming and requires access to the key
  505. file and/or passphrase if encryption is enabled. These checks can be skipped using
  506. the --repository-only option.
  507. """)
  508. subparser = subparsers.add_parser('check', parents=[common_parser],
  509. description=self.do_check.__doc__,
  510. epilog=check_epilog,
  511. formatter_class=argparse.RawDescriptionHelpFormatter)
  512. subparser.set_defaults(func=self.do_check)
  513. subparser.add_argument('repository', metavar='REPOSITORY',
  514. type=location_validator(archive=False),
  515. help='repository to check consistency of')
  516. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  517. default=False,
  518. help='only perform repository checks')
  519. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  520. default=False,
  521. help='only perform archives checks')
  522. subparser.add_argument('--repair', dest='repair', action='store_true',
  523. default=False,
  524. help='attempt to repair any inconsistencies found')
  525. subparser.add_argument('--last', dest='last',
  526. type=int, default=None, metavar='N',
  527. help='only check last N archives (Default: all)')
  528. change_passphrase_epilog = textwrap.dedent("""
  529. The key files used for repository encryption are optionally passphrase
  530. protected. This command can be used to change this passphrase.
  531. """)
  532. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  533. description=self.do_change_passphrase.__doc__,
  534. epilog=change_passphrase_epilog,
  535. formatter_class=argparse.RawDescriptionHelpFormatter)
  536. subparser.set_defaults(func=self.do_change_passphrase)
  537. subparser.add_argument('repository', metavar='REPOSITORY',
  538. type=location_validator(archive=False))
  539. create_epilog = textwrap.dedent("""
  540. This command creates a backup archive containing all files found while recursively
  541. traversing all paths specified. The archive will consume almost no disk space for
  542. files or parts of files that have already been stored in other archives.
  543. See "borg help patterns" for more help on exclude patterns.
  544. """)
  545. subparser = subparsers.add_parser('create', parents=[common_parser],
  546. description=self.do_create.__doc__,
  547. epilog=create_epilog,
  548. formatter_class=argparse.RawDescriptionHelpFormatter)
  549. subparser.set_defaults(func=self.do_create)
  550. subparser.add_argument('-s', '--stats', dest='stats',
  551. action='store_true', default=False,
  552. help='print statistics for the created archive')
  553. subparser.add_argument('-p', '--progress', dest='progress',
  554. action='store_true', default=False,
  555. help='print progress while creating the archive')
  556. subparser.add_argument('-e', '--exclude', dest='excludes',
  557. type=ExcludePattern, action='append',
  558. metavar="PATTERN", help='exclude paths matching PATTERN')
  559. subparser.add_argument('--exclude-from', dest='exclude_files',
  560. type=argparse.FileType('r'), action='append',
  561. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  562. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  563. action='store_true', default=False,
  564. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  565. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  566. type=int, default=300, metavar='SECONDS',
  567. help='write checkpoint every SECONDS seconds (Default: 300)')
  568. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  569. action='store_true', default=False,
  570. help='do not cross mount points')
  571. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  572. action='store_true', default=False,
  573. help='only store numeric user and group identifiers')
  574. subparser.add_argument('--timestamp', dest='timestamp',
  575. type=timestamp, default=None,
  576. metavar='yyyy-mm-ddThh:mm:ss',
  577. help='manually specify the archive creation date/time (UTC). '
  578. 'alternatively, give a reference file/directory.')
  579. subparser.add_argument('archive', metavar='ARCHIVE',
  580. type=location_validator(archive=True),
  581. help='archive to create')
  582. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  583. help='paths to archive')
  584. extract_epilog = textwrap.dedent("""
  585. This command extracts the contents of an archive. By default the entire
  586. archive is extracted but a subset of files and directories can be selected
  587. by passing a list of ``PATHs`` as arguments. The file selection can further
  588. be restricted by using the ``--exclude`` option.
  589. See "borg help patterns" for more help on exclude patterns.
  590. """)
  591. subparser = subparsers.add_parser('extract', parents=[common_parser],
  592. description=self.do_extract.__doc__,
  593. epilog=extract_epilog,
  594. formatter_class=argparse.RawDescriptionHelpFormatter)
  595. subparser.set_defaults(func=self.do_extract)
  596. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  597. default=False, action='store_true',
  598. help='do not actually change any files')
  599. subparser.add_argument('-e', '--exclude', dest='excludes',
  600. type=ExcludePattern, action='append',
  601. metavar="PATTERN", help='exclude paths matching PATTERN')
  602. subparser.add_argument('--exclude-from', dest='exclude_files',
  603. type=argparse.FileType('r'), action='append',
  604. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  605. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  606. action='store_true', default=False,
  607. help='only obey numeric user and group identifiers')
  608. subparser.add_argument('--strip-components', dest='strip_components',
  609. type=int, default=0, metavar='NUMBER',
  610. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  611. subparser.add_argument('--stdout', dest='stdout',
  612. action='store_true', default=False,
  613. help='write all extracted data to stdout')
  614. subparser.add_argument('--sparse', dest='sparse',
  615. action='store_true', default=False,
  616. help='create holes in output sparse file from all-zero chunks')
  617. subparser.add_argument('archive', metavar='ARCHIVE',
  618. type=location_validator(archive=True),
  619. help='archive to extract')
  620. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  621. help='paths to extract')
  622. rename_epilog = textwrap.dedent("""
  623. This command renames an archive in the repository.
  624. """)
  625. subparser = subparsers.add_parser('rename', parents=[common_parser],
  626. description=self.do_rename.__doc__,
  627. epilog=rename_epilog,
  628. formatter_class=argparse.RawDescriptionHelpFormatter)
  629. subparser.set_defaults(func=self.do_rename)
  630. subparser.add_argument('archive', metavar='ARCHIVE',
  631. type=location_validator(archive=True),
  632. help='archive to rename')
  633. subparser.add_argument('name', metavar='NEWNAME', type=str,
  634. help='the new archive name to use')
  635. delete_epilog = textwrap.dedent("""
  636. This command deletes an archive from the repository or the complete repository.
  637. Disk space is reclaimed accordingly. If you delete the complete repository, the
  638. local cache for it (if any) is also deleted.
  639. """)
  640. subparser = subparsers.add_parser('delete', parents=[common_parser],
  641. description=self.do_delete.__doc__,
  642. epilog=delete_epilog,
  643. formatter_class=argparse.RawDescriptionHelpFormatter)
  644. subparser.set_defaults(func=self.do_delete)
  645. subparser.add_argument('-s', '--stats', dest='stats',
  646. action='store_true', default=False,
  647. help='print statistics for the deleted archive')
  648. subparser.add_argument('target', metavar='TARGET',
  649. type=location_validator(),
  650. help='archive or repository to delete')
  651. list_epilog = textwrap.dedent("""
  652. This command lists the contents of a repository or an archive.
  653. """)
  654. subparser = subparsers.add_parser('list', parents=[common_parser],
  655. description=self.do_list.__doc__,
  656. epilog=list_epilog,
  657. formatter_class=argparse.RawDescriptionHelpFormatter)
  658. subparser.set_defaults(func=self.do_list)
  659. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  660. help='repository/archive to list contents of')
  661. mount_epilog = textwrap.dedent("""
  662. This command mounts an archive as a FUSE filesystem. This can be useful for
  663. browsing an archive or restoring individual files. Unless the ``--foreground``
  664. option is given the command will run in the background until the filesystem
  665. is ``umounted``.
  666. """)
  667. subparser = subparsers.add_parser('mount', parents=[common_parser],
  668. description=self.do_mount.__doc__,
  669. epilog=mount_epilog,
  670. formatter_class=argparse.RawDescriptionHelpFormatter)
  671. subparser.set_defaults(func=self.do_mount)
  672. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  673. help='repository/archive to mount')
  674. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  675. help='where to mount filesystem')
  676. subparser.add_argument('-f', '--foreground', dest='foreground',
  677. action='store_true', default=False,
  678. help='stay in foreground, do not daemonize')
  679. subparser.add_argument('-o', dest='options', type=str,
  680. help='Extra mount options')
  681. info_epilog = textwrap.dedent("""
  682. This command displays some detailed information about the specified archive.
  683. """)
  684. subparser = subparsers.add_parser('info', parents=[common_parser],
  685. description=self.do_info.__doc__,
  686. epilog=info_epilog,
  687. formatter_class=argparse.RawDescriptionHelpFormatter)
  688. subparser.set_defaults(func=self.do_info)
  689. subparser.add_argument('archive', metavar='ARCHIVE',
  690. type=location_validator(archive=True),
  691. help='archive to display information about')
  692. prune_epilog = textwrap.dedent("""
  693. The prune command prunes a repository by deleting archives not matching
  694. any of the specified retention options. This command is normally used by
  695. automated backup scripts wanting to keep a certain number of historic backups.
  696. As an example, "-d 7" means to keep the latest backup on each day for 7 days.
  697. Days without backups do not count towards the total.
  698. The rules are applied from hourly to yearly, and backups selected by previous
  699. rules do not count towards those of later rules. The time that each backup
  700. completes is used for pruning purposes. Dates and times are interpreted in
  701. the local timezone, and weeks go from Monday to Sunday. Specifying a
  702. negative number of archives to keep means that there is no limit.
  703. The "--keep-within" option takes an argument of the form "<int><char>",
  704. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  705. to keep all archives that were created within the past 48 hours.
  706. "1m" is taken to mean "31d". The archives kept with this option do not
  707. count towards the totals specified by any other options.
  708. If a prefix is set with -p, then only archives that start with the prefix are
  709. considered for deletion and only those archives count towards the totals
  710. specified by the rules.
  711. """)
  712. subparser = subparsers.add_parser('prune', parents=[common_parser],
  713. description=self.do_prune.__doc__,
  714. epilog=prune_epilog,
  715. formatter_class=argparse.RawDescriptionHelpFormatter)
  716. subparser.set_defaults(func=self.do_prune)
  717. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  718. default=False, action='store_true',
  719. help='do not change repository')
  720. subparser.add_argument('-s', '--stats', dest='stats',
  721. action='store_true', default=False,
  722. help='print statistics for the deleted archive')
  723. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  724. help='keep all archives within this time interval')
  725. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  726. help='number of hourly archives to keep')
  727. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  728. help='number of daily archives to keep')
  729. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  730. help='number of weekly archives to keep')
  731. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  732. help='number of monthly archives to keep')
  733. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  734. help='number of yearly archives to keep')
  735. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  736. help='only consider archive names starting with this prefix')
  737. subparser.add_argument('repository', metavar='REPOSITORY',
  738. type=location_validator(archive=False),
  739. help='repository to prune')
  740. subparser = subparsers.add_parser('help', parents=[common_parser],
  741. description='Extra help')
  742. subparser.add_argument('--epilog-only', dest='epilog_only',
  743. action='store_true', default=False)
  744. subparser.add_argument('--usage-only', dest='usage_only',
  745. action='store_true', default=False)
  746. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  747. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  748. help='additional help on TOPIC')
  749. args = parser.parse_args(args or ['-h'])
  750. self.verbose = args.verbose
  751. update_excludes(args)
  752. return args.func(args)
  753. def main():
  754. # Make sure stdout and stderr have errors='replace') to avoid unicode
  755. # issues when print()-ing unicode file names
  756. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  757. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  758. archiver = Archiver()
  759. try:
  760. exit_code = archiver.run(sys.argv[1:])
  761. except Error as e:
  762. archiver.print_error(e.get_message())
  763. exit_code = e.exit_code
  764. except RemoteRepository.RPCError as e:
  765. print(e)
  766. exit_code = 1
  767. except KeyboardInterrupt:
  768. archiver.print_error('Error: Keyboard interrupt')
  769. exit_code = 1
  770. else:
  771. if exit_code:
  772. archiver.print_error('Exiting with failure status due to previous errors')
  773. sys.exit(exit_code)
  774. if __name__ == '__main__':
  775. main()