archiver.py 32 KB

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