archiver.py 30 KB

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