2
0

archiver.py 32 KB

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