archiver.py 35 KB

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