archiver.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 args.phase in ('all', 'repository') and not repository.check(repair=args.repair):
  66. return 1
  67. if args.phase in ('all', 'archive') and not ArchiveChecker().check(repository, repair=args.repair):
  68. return 1
  69. return 0
  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 0
  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. if not args.dry_run:
  176. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  177. archive.extract_item(dirs.pop(-1))
  178. self.print_verbose(remove_surrogates(item[b'path']))
  179. try:
  180. if args.dry_run:
  181. archive.extract_item(item, dry_run=True)
  182. else:
  183. if stat.S_ISDIR(item[b'mode']):
  184. dirs.append(item)
  185. archive.extract_item(item, restore_attrs=False)
  186. else:
  187. archive.extract_item(item)
  188. except IOError as e:
  189. self.print_error('%s: %s', remove_surrogates(item[b'path']), e)
  190. if not args.dry_run:
  191. while dirs:
  192. archive.extract_item(dirs.pop(-1))
  193. return self.exit_code
  194. def do_delete(self, args):
  195. """Delete archive
  196. """
  197. repository = self.open_repository(args.archive)
  198. manifest, key = Manifest.load(repository)
  199. cache = Cache(repository, key, manifest)
  200. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  201. archive.delete(cache)
  202. return self.exit_code
  203. def do_mount(self, args):
  204. """Mount archive as a FUSE fileystem
  205. """
  206. try:
  207. from attic.fuse import AtticOperations
  208. except ImportError:
  209. self.print_error('the "llfuse" module is required to use this feature')
  210. return self.exit_code
  211. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  212. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  213. return self.exit_code
  214. repository = self.open_repository(args.archive)
  215. manifest, key = Manifest.load(repository)
  216. self.print_verbose("Loading archive metadata...", newline=False)
  217. archive = Archive(repository, key, manifest, args.archive.archive)
  218. self.print_verbose('done')
  219. operations = AtticOperations(key, repository, archive)
  220. self.print_verbose("Mounting filesystem")
  221. try:
  222. operations.mount(args.mountpoint, args.options, args.foreground)
  223. except RuntimeError:
  224. # Relevant error message already printed to stderr by fuse
  225. self.exit_code = 1
  226. return self.exit_code
  227. def do_list(self, args):
  228. """List archive or repository contents
  229. """
  230. repository = self.open_repository(args.src)
  231. manifest, key = Manifest.load(repository)
  232. if args.src.archive:
  233. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  234. archive = Archive(repository, key, manifest, args.src.archive)
  235. for item in archive.iter_items():
  236. type = tmap.get(item[b'mode'] // 4096, '?')
  237. mode = format_file_mode(item[b'mode'])
  238. size = 0
  239. if type == '-':
  240. try:
  241. size = sum(size for _, size, _ in item[b'chunks'])
  242. except KeyError:
  243. pass
  244. mtime = format_time(datetime.fromtimestamp(item[b'mtime'] / 10**9))
  245. if b'source' in item:
  246. if type == 'l':
  247. extra = ' -> %s' % item[b'source']
  248. else:
  249. type = 'h'
  250. extra = ' link to %s' % item[b'source']
  251. else:
  252. extra = ''
  253. print('%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item[b'user'] or item[b'uid'],
  254. item[b'group'] or item[b'gid'], size, mtime,
  255. remove_surrogates(item[b'path']), extra))
  256. else:
  257. for archive in sorted(Archive.list_archives(repository, key, manifest), key=attrgetter('ts')):
  258. print(format_archive(archive))
  259. return self.exit_code
  260. def do_info(self, args):
  261. """Show archive details such as disk space used
  262. """
  263. repository = self.open_repository(args.archive)
  264. manifest, key = Manifest.load(repository)
  265. cache = Cache(repository, key, manifest)
  266. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  267. stats = archive.calc_stats(cache)
  268. print('Name:', archive.name)
  269. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  270. print('Hostname:', archive.metadata[b'hostname'])
  271. print('Username:', archive.metadata[b'username'])
  272. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  273. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  274. stats.print_()
  275. return self.exit_code
  276. def do_prune(self, args):
  277. """Prune repository archives according to specified rules
  278. """
  279. repository = self.open_repository(args.repository)
  280. manifest, key = Manifest.load(repository)
  281. cache = Cache(repository, key, manifest)
  282. archives = list(sorted(Archive.list_archives(repository, key, manifest, cache),
  283. key=attrgetter('ts'), reverse=True))
  284. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  285. self.print_error('At least one of the "within", "hourly", "daily", "weekly", "monthly" or "yearly" '
  286. 'settings must be specified')
  287. return 1
  288. if args.prefix:
  289. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  290. keep = []
  291. if args.within:
  292. keep += prune_within(archives, args.within)
  293. if args.hourly:
  294. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  295. if args.daily:
  296. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  297. if args.weekly:
  298. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  299. if args.monthly:
  300. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  301. if args.yearly:
  302. keep += prune_split(archives, '%Y', args.yearly, keep)
  303. keep.sort(key=attrgetter('ts'), reverse=True)
  304. to_delete = [a for a in archives if a not in keep]
  305. for archive in keep:
  306. self.print_verbose('Keeping archive: %s' % format_archive(archive))
  307. for archive in to_delete:
  308. if args.dry_run:
  309. self.print_verbose('Would prune: %s' % format_archive(archive))
  310. else:
  311. self.print_verbose('Pruning archive: %s' % format_archive(archive))
  312. archive.delete(cache)
  313. return self.exit_code
  314. helptext = {}
  315. helptext['patterns'] = '''
  316. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  317. number of characters, '?' matching any single character, '[...]' matching any
  318. single character specified, including ranges, and '[!...]' matching any
  319. character not specified. For the purpose of these patterns, the path
  320. separator ('\\' for Windows and '/' on other systems) is not treated
  321. specially. For a path to match a pattern, it must completely match from
  322. start to end, or must match from the start to just before a path separator.
  323. Except for the root path, paths will never end in the path separator when
  324. matching is attempted. Thus, if a given pattern ends in a path separator, a
  325. '*' is appended before matching is attempted. Patterns with wildcards should
  326. be quoted to protect them from shell expansion.
  327. Examples:
  328. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  329. $ attic create -e '*.o' repo.attic /
  330. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  331. # not '/home/user/importantjunk' or '/etc/junk':
  332. $ attic create -e '/home/*/junk' repo.attic /
  333. # Exclude the contents of '/home/user/cache' but not the directory itself:
  334. $ attic create -e /home/user/cache/ repo.attic /
  335. # The file '/home/user/cache/important' is *not* backed up:
  336. $ attic create -e /home/user/cache/ repo.attic / /home/user/cache/important
  337. '''
  338. def do_help(self, args):
  339. if args.topic in self.helptext:
  340. print(self.helptext[args.topic])
  341. else:
  342. # FIXME: If topic is one of the regular commands, show that help.
  343. # Otherwise, show the default global help.
  344. print('No help available on %s' % (args.topic,))
  345. return self.exit_code
  346. def preprocess_args(self, args):
  347. deprecations = [
  348. ('--hourly', '--keep-hourly', 'Warning: "--hourly" has been deprecated. Use "--keep-hourly" instead.'),
  349. ('--daily', '--keep-daily', 'Warning: "--daily" has been deprecated. Use "--keep-daily" instead.'),
  350. ('--weekly', '--keep-weekly', 'Warning: "--weekly" has been deprecated. Use "--keep-weekly" instead.'),
  351. ('--monthly', '--keep-monthly', 'Warning: "--monthly" has been deprecated. Use "--keep-monthly" instead.'),
  352. ('--yearly', '--keep-yearly', 'Warning: "--yearly" has been deprecated. Use "--keep-yearly" instead.')
  353. ]
  354. if args and args[0] == 'verify':
  355. print('Warning: "attic verify" has been deprecated. Use "attic extract --dry-run" instead.')
  356. args = ['extract', '--dry-run'] + args[1:]
  357. for i, arg in enumerate(args[:]):
  358. for old_name, new_name, warning in deprecations:
  359. if arg.startswith(old_name):
  360. args[i] = arg.replace(old_name, new_name)
  361. print(warning)
  362. return args
  363. def run(self, args=None):
  364. keys_dir = get_keys_dir()
  365. if not os.path.exists(keys_dir):
  366. os.makedirs(keys_dir)
  367. os.chmod(keys_dir, stat.S_IRWXU)
  368. cache_dir = get_cache_dir()
  369. if not os.path.exists(cache_dir):
  370. os.makedirs(cache_dir)
  371. os.chmod(cache_dir, stat.S_IRWXU)
  372. common_parser = argparse.ArgumentParser(add_help=False)
  373. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  374. default=False,
  375. help='verbose output')
  376. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  377. if args and args[0] == 'serve':
  378. return self.do_serve()
  379. if args:
  380. args = self.preprocess_args(args)
  381. parser = argparse.ArgumentParser(description='Attic %s - Deduplicated Backups' % __version__)
  382. subparsers = parser.add_subparsers(title='Available commands')
  383. subparser = subparsers.add_parser('init', parents=[common_parser],
  384. description=self.do_init.__doc__)
  385. subparser.set_defaults(func=self.do_init)
  386. subparser.add_argument('repository', metavar='REPOSITORY',
  387. type=location_validator(archive=False),
  388. help='repository to create')
  389. subparser.add_argument('-e', '--encryption', dest='encryption',
  390. choices=('none', 'passphrase', 'keyfile'), default='none',
  391. help='select encryption method')
  392. check_epilog = textwrap.dedent("""
  393. The check command verifies the consistency of a repository and corresponding
  394. archives. The check is performed in two phases. In the first phase the
  395. checksums of the underlying repository segment files are verified to detect
  396. bit rot and other types of damage. In the second phase the consistency and
  397. correctness of the archive metadata is verified.
  398. A specific check phase can be selected using the --phase=repository|archive
  399. option. This can be useful since the "archive" phase can be time consuming
  400. and requires access to the key file and/or passphrase if encryption is enabled.
  401. """)
  402. subparser = subparsers.add_parser('check', parents=[common_parser],
  403. description=self.do_check.__doc__,
  404. epilog=check_epilog,
  405. formatter_class=argparse.RawDescriptionHelpFormatter)
  406. subparser.set_defaults(func=self.do_check)
  407. subparser.add_argument('repository', metavar='REPOSITORY',
  408. type=location_validator(archive=False),
  409. help='repository to check consistency of')
  410. subparser.add_argument('--phase', dest='phase', choices=['repository', 'archive', 'all'],
  411. default='all',
  412. help='which checks to perform (default: all)')
  413. subparser.add_argument('--repair', dest='repair', action='store_true',
  414. default=False,
  415. help='attempt to repair any inconsistencies found')
  416. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  417. description=self.do_change_passphrase.__doc__)
  418. subparser.set_defaults(func=self.do_change_passphrase)
  419. subparser.add_argument('repository', metavar='REPOSITORY',
  420. type=location_validator(archive=False))
  421. create_epilog = '''See "attic help patterns" for more help on exclude patterns.'''
  422. subparser = subparsers.add_parser('create', parents=[common_parser],
  423. description=self.do_create.__doc__,
  424. epilog=create_epilog)
  425. subparser.set_defaults(func=self.do_create)
  426. subparser.add_argument('-s', '--stats', dest='stats',
  427. action='store_true', default=False,
  428. help='print statistics for the created archive')
  429. subparser.add_argument('-e', '--exclude', dest='excludes',
  430. type=ExcludePattern, action='append',
  431. metavar="PATTERN", help='exclude paths matching PATTERN')
  432. subparser.add_argument('--exclude-from', dest='exclude_files',
  433. type=argparse.FileType('r'), action='append',
  434. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  435. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  436. type=int, default=300, metavar='SECONDS',
  437. help='write checkpoint every SECONDS seconds (Default: 300)')
  438. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  439. action='store_true', default=False,
  440. help='do not cross mount points')
  441. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  442. action='store_true', default=False,
  443. help='only store numeric user and group identifiers')
  444. subparser.add_argument('archive', metavar='ARCHIVE',
  445. type=location_validator(archive=True),
  446. help='archive to create')
  447. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  448. help='paths to archive')
  449. extract_epilog = '''See "attic help patterns" for more help on exclude patterns.'''
  450. subparser = subparsers.add_parser('extract', parents=[common_parser],
  451. description=self.do_extract.__doc__,
  452. epilog=extract_epilog)
  453. subparser.set_defaults(func=self.do_extract)
  454. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  455. default=False, action='store_true',
  456. help='do not actually change any files')
  457. subparser.add_argument('-e', '--exclude', dest='excludes',
  458. type=ExcludePattern, action='append',
  459. metavar="PATTERN", help='exclude paths matching PATTERN')
  460. subparser.add_argument('--exclude-from', dest='exclude_files',
  461. type=argparse.FileType('r'), action='append',
  462. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  463. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  464. action='store_true', default=False,
  465. help='only obey numeric user and group identifiers')
  466. subparser.add_argument('archive', metavar='ARCHIVE',
  467. type=location_validator(archive=True),
  468. help='archive to extract')
  469. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  470. help='paths to extract')
  471. subparser = subparsers.add_parser('delete', parents=[common_parser],
  472. description=self.do_delete.__doc__)
  473. subparser.set_defaults(func=self.do_delete)
  474. subparser.add_argument('archive', metavar='ARCHIVE',
  475. type=location_validator(archive=True),
  476. help='archive to delete')
  477. subparser = subparsers.add_parser('list', parents=[common_parser],
  478. description=self.do_list.__doc__)
  479. subparser.set_defaults(func=self.do_list)
  480. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  481. help='repository/archive to list contents of')
  482. subparser = subparsers.add_parser('mount', parents=[common_parser],
  483. description=self.do_mount.__doc__)
  484. subparser.set_defaults(func=self.do_mount)
  485. subparser.add_argument('archive', metavar='ARCHIVE', type=location_validator(archive=True),
  486. help='archive to mount')
  487. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  488. help='where to mount filesystem')
  489. subparser.add_argument('-f', '--foreground', dest='foreground',
  490. action='store_true', default=False,
  491. help='stay in foreground, do not daemonize')
  492. subparser.add_argument('-o', dest='options', type=str,
  493. help='Extra mount options')
  494. subparser = subparsers.add_parser('info', parents=[common_parser],
  495. description=self.do_info.__doc__)
  496. subparser.set_defaults(func=self.do_info)
  497. subparser.add_argument('archive', metavar='ARCHIVE',
  498. type=location_validator(archive=True),
  499. help='archive to display information about')
  500. prune_epilog = '''The prune command prunes a repository by deleting archives
  501. not matching any of the specified retention options. This command is normally
  502. used by automated backup scripts wanting to keep a certain number of historic
  503. backups. As an example, "-d 7" means to keep the latest backup on each day
  504. for 7 days. Days without backups do not count towards the total. The rules
  505. are applied from hourly to yearly, and backups selected by previous rules do
  506. not count towards those of later rules. The time that each backup completes
  507. is used for pruning purposes. 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 "--keep-within" option takes an argument of the form "<int><char>",
  511. where char is "H", "d", "w", "m", "y". For example, "--keep-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('-n', '--dry-run', dest='dry_run',
  523. default=False, action='store_true',
  524. help='do not change repository')
  525. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  526. help='keep all archives within this time interval')
  527. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  528. help='number of hourly archives to keep')
  529. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  530. help='number of daily archives to keep')
  531. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  532. help='number of weekly archives to keep')
  533. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  534. help='number of monthly archives to keep')
  535. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  536. help='number of yearly archives to keep')
  537. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  538. help='only consider archive names starting with this prefix')
  539. subparser.add_argument('repository', metavar='REPOSITORY',
  540. type=location_validator(archive=False),
  541. help='repository to prune')
  542. subparser = subparsers.add_parser('help', parents=[common_parser],
  543. description='Extra help')
  544. subparser.set_defaults(func=self.do_help)
  545. subparser.add_argument('topic', metavar='TOPIC', type=str,
  546. help='additional help on TOPIC')
  547. args = parser.parse_args(args or ['-h'])
  548. self.verbose = args.verbose
  549. update_excludes(args)
  550. return args.func(args)
  551. def main():
  552. # Make sure stdout and stderr have errors='replace') to avoid unicode
  553. # issues when print()-ing unicode file names
  554. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=sys.stdout.line_buffering)
  555. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=sys.stderr.line_buffering)
  556. archiver = Archiver()
  557. try:
  558. exit_code = archiver.run(sys.argv[1:])
  559. except Error as e:
  560. archiver.print_error(e.get_message())
  561. exit_code = e.exit_code
  562. except KeyboardInterrupt:
  563. archiver.print_error('Error: Keyboard interrupt')
  564. exit_code = 1
  565. else:
  566. if exit_code:
  567. archiver.print_error('Exiting with failure status due to previous errors')
  568. sys.exit(exit_code)
  569. if __name__ == '__main__':
  570. main()