archiver.py 36 KB

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