archiver.py 30 KB

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