archiver.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. is_cachedir, bigint_to_int
  21. from attic.remote import RepositoryServer, RemoteRepository
  22. class Archiver:
  23. def __init__(self):
  24. self.exit_code = 0
  25. def open_repository(self, location, create=False, exclusive=False):
  26. if location.proto == 'ssh':
  27. repository = RemoteRepository(location, create=create)
  28. else:
  29. repository = Repository(location.path, create=create, exclusive=exclusive)
  30. repository._location = location
  31. return repository
  32. def print_error(self, msg, *args):
  33. msg = args and msg % args or msg
  34. self.exit_code = 1
  35. print('attic: ' + msg, file=sys.stderr)
  36. def print_verbose(self, msg, *args, **kw):
  37. if self.verbose:
  38. msg = args and msg % args or msg
  39. if kw.get('newline', True):
  40. print(msg)
  41. else:
  42. print(msg, end=' ')
  43. def do_serve(self, args):
  44. """Start Attic in server mode. This command is usually not used manually.
  45. """
  46. return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()
  47. def do_init(self, args):
  48. """Initialize an empty repository"""
  49. print('Initializing repository at "%s"' % args.repository.orig)
  50. repository = self.open_repository(args.repository, create=True, exclusive=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. repository = self.open_repository(args.repository, exclusive=args.repair)
  60. if args.repair:
  61. while not os.environ.get('ATTIC_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  62. self.print_error("""Warning: 'check --repair' is an experimental feature that might result
  63. in data loss.
  64. Type "Yes I am sure" if you understand this and want to continue.\n""")
  65. if input('Do you want to continue? ') == 'Yes I am sure':
  66. break
  67. if not args.archives_only:
  68. print('Starting repository check...')
  69. if repository.check(repair=args.repair):
  70. print('Repository check complete, no problems found.')
  71. else:
  72. return 1
  73. if not args.repo_only and not ArchiveChecker().check(repository, repair=args.repair, last=args.last):
  74. return 1
  75. return 0
  76. def do_change_passphrase(self, args):
  77. """Change repository key file passphrase"""
  78. repository = self.open_repository(args.repository)
  79. manifest, key = Manifest.load(repository)
  80. key.change_passphrase()
  81. return 0
  82. def do_create(self, args):
  83. """Create new archive"""
  84. t0 = datetime.now()
  85. repository = self.open_repository(args.archive, exclusive=True)
  86. manifest, key = Manifest.load(repository)
  87. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  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, progress=args.progress)
  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. if path == '-': # stdin
  107. path = 'stdin'
  108. self.print_verbose(path)
  109. try:
  110. archive.process_stdin(path, cache)
  111. except IOError as e:
  112. self.print_error('%s: %s', path, e)
  113. continue
  114. path = os.path.normpath(path)
  115. if args.dontcross:
  116. try:
  117. restrict_dev = os.lstat(path).st_dev
  118. except OSError as e:
  119. self.print_error('%s: %s', path, e)
  120. continue
  121. else:
  122. restrict_dev = None
  123. self._process(archive, cache, args.excludes, args.exclude_caches, skip_inodes, path, restrict_dev)
  124. archive.save()
  125. if args.progress:
  126. archive.stats.show_progress(final=True)
  127. if args.stats:
  128. t = datetime.now()
  129. diff = t - t0
  130. print('-' * 78)
  131. print('Archive name: %s' % args.archive.archive)
  132. print('Archive fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  133. print('Start time: %s' % t0.strftime('%c'))
  134. print('End time: %s' % t.strftime('%c'))
  135. print('Duration: %s' % format_timedelta(diff))
  136. print('Number of files: %d' % archive.stats.nfiles)
  137. archive.stats.print_('This archive:', cache)
  138. print('-' * 78)
  139. return self.exit_code
  140. def _process(self, archive, cache, excludes, exclude_caches, skip_inodes, path, restrict_dev):
  141. if exclude_path(path, excludes):
  142. return
  143. try:
  144. st = os.lstat(path)
  145. except OSError as e:
  146. self.print_error('%s: %s', path, e)
  147. return
  148. if (st.st_ino, st.st_dev) in skip_inodes:
  149. return
  150. # Entering a new filesystem?
  151. if restrict_dev and st.st_dev != restrict_dev:
  152. return
  153. # Ignore unix sockets
  154. if stat.S_ISSOCK(st.st_mode):
  155. return
  156. status = None
  157. if stat.S_ISREG(st.st_mode):
  158. try:
  159. status = archive.process_file(path, st, cache)
  160. except IOError as e:
  161. self.print_error('%s: %s', path, e)
  162. elif stat.S_ISDIR(st.st_mode):
  163. if exclude_caches and is_cachedir(path):
  164. return
  165. status = archive.process_dir(path, st)
  166. try:
  167. entries = os.listdir(path)
  168. except OSError as e:
  169. self.print_error('%s: %s', path, e)
  170. else:
  171. for filename in sorted(entries):
  172. entry_path = os.path.normpath(os.path.join(path, filename))
  173. self._process(archive, cache, excludes, exclude_caches, skip_inodes,
  174. entry_path, restrict_dev)
  175. elif stat.S_ISLNK(st.st_mode):
  176. status = archive.process_symlink(path, st)
  177. elif stat.S_ISFIFO(st.st_mode):
  178. status = archive.process_fifo(path, st)
  179. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  180. status = archive.process_dev(path, st)
  181. else:
  182. self.print_error('Unknown file type: %s', path)
  183. return
  184. # Status output
  185. # A lowercase character means a file type other than a regular file,
  186. # attic usually just stores them. E.g. (d)irectory.
  187. # Hardlinks to already seen content are indicated by (h).
  188. # A uppercase character means a regular file that was (A)dded,
  189. # (M)odified or was (U)nchanged.
  190. # Note: A/M/U is relative to the "files" cache, not to the repo.
  191. # This would be an issue if the files cache is not used.
  192. if status is None:
  193. status = '?' # need to add a status code somewhere
  194. # output ALL the stuff - it can be easily filtered using grep.
  195. # even stuff considered unchanged might be interesting.
  196. self.print_verbose("%1s %s", status, remove_surrogates(path))
  197. def do_extract(self, args):
  198. """Extract archive contents"""
  199. # be restrictive when restoring files, restore permissions later
  200. os.umask(0o077)
  201. repository = self.open_repository(args.archive)
  202. manifest, key = Manifest.load(repository)
  203. archive = Archive(repository, key, manifest, args.archive.archive,
  204. numeric_owner=args.numeric_owner)
  205. patterns = adjust_patterns(args.paths, args.excludes)
  206. dry_run = args.dry_run
  207. stdout = args.stdout
  208. strip_components = args.strip_components
  209. dirs = []
  210. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  211. orig_path = item[b'path']
  212. if strip_components:
  213. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  214. if not item[b'path']:
  215. continue
  216. if not args.dry_run:
  217. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  218. archive.extract_item(dirs.pop(-1), stdout=stdout)
  219. self.print_verbose(remove_surrogates(orig_path))
  220. try:
  221. if dry_run:
  222. archive.extract_item(item, dry_run=True)
  223. else:
  224. if stat.S_ISDIR(item[b'mode']):
  225. dirs.append(item)
  226. archive.extract_item(item, restore_attrs=False)
  227. else:
  228. archive.extract_item(item, stdout=stdout)
  229. except IOError as e:
  230. self.print_error('%s: %s', remove_surrogates(orig_path), e)
  231. if not args.dry_run:
  232. while dirs:
  233. archive.extract_item(dirs.pop(-1))
  234. return self.exit_code
  235. def do_rename(self, args):
  236. """Rename an existing archive"""
  237. repository = self.open_repository(args.archive, exclusive=True)
  238. manifest, key = Manifest.load(repository)
  239. cache = Cache(repository, key, manifest)
  240. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  241. archive.rename(args.name)
  242. manifest.write()
  243. repository.commit()
  244. cache.commit()
  245. return self.exit_code
  246. def do_delete(self, args):
  247. """Delete an existing archive"""
  248. repository = self.open_repository(args.archive, exclusive=True)
  249. manifest, key = Manifest.load(repository)
  250. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  251. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  252. stats = Statistics()
  253. archive.delete(stats)
  254. manifest.write()
  255. repository.commit()
  256. cache.commit()
  257. if args.stats:
  258. stats.print_('Deleted data:', cache)
  259. return self.exit_code
  260. def do_mount(self, args):
  261. """Mount archive or an entire repository as a FUSE fileystem"""
  262. try:
  263. from attic.fuse import AtticOperations
  264. except ImportError as e:
  265. self.print_error('loading fuse support failed [ImportError: %s]' % str(e))
  266. return self.exit_code
  267. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  268. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  269. return self.exit_code
  270. repository = self.open_repository(args.src)
  271. manifest, key = Manifest.load(repository)
  272. if args.src.archive:
  273. archive = Archive(repository, key, manifest, args.src.archive)
  274. else:
  275. archive = None
  276. operations = AtticOperations(key, repository, manifest, archive)
  277. self.print_verbose("Mounting filesystem")
  278. try:
  279. operations.mount(args.mountpoint, args.options, args.foreground)
  280. except RuntimeError:
  281. # Relevant error message already printed to stderr by fuse
  282. self.exit_code = 1
  283. return self.exit_code
  284. def do_list(self, args):
  285. """List archive or repository contents"""
  286. repository = self.open_repository(args.src)
  287. manifest, key = Manifest.load(repository)
  288. if args.src.archive:
  289. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  290. archive = Archive(repository, key, manifest, args.src.archive)
  291. for item in archive.iter_items():
  292. type = tmap.get(item[b'mode'] // 4096, '?')
  293. mode = format_file_mode(item[b'mode'])
  294. size = 0
  295. if type == '-':
  296. try:
  297. size = sum(size for _, size, _ in item[b'chunks'])
  298. except KeyError:
  299. pass
  300. try:
  301. mtime = datetime.fromtimestamp(bigint_to_int(item[b'mtime']) / 1e9)
  302. except ValueError:
  303. # likely a broken mtime and datetime did not want to go beyond year 9999
  304. mtime = datetime(9999, 12, 31, 23, 59, 59)
  305. if b'source' in item:
  306. if type == 'l':
  307. extra = ' -> %s' % item[b'source']
  308. else:
  309. type = 'h'
  310. extra = ' link to %s' % item[b'source']
  311. else:
  312. extra = ''
  313. print('%s%s %-6s %-6s %8d %s %s%s' % (
  314. type, mode, item[b'user'] or item[b'uid'],
  315. item[b'group'] or item[b'gid'], size, format_time(mtime),
  316. remove_surrogates(item[b'path']), extra))
  317. else:
  318. for archive in sorted(Archive.list_archives(repository, key, manifest), key=attrgetter('ts')):
  319. print(format_archive(archive))
  320. return self.exit_code
  321. def do_info(self, args):
  322. """Show archive details such as disk space used"""
  323. repository = self.open_repository(args.archive)
  324. manifest, key = Manifest.load(repository)
  325. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  326. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  327. stats = archive.calc_stats(cache)
  328. print('Name:', archive.name)
  329. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  330. print('Hostname:', archive.metadata[b'hostname'])
  331. print('Username:', archive.metadata[b'username'])
  332. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  333. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  334. print('Number of files: %d' % stats.nfiles)
  335. stats.print_('This archive:', cache)
  336. return self.exit_code
  337. def do_prune(self, args):
  338. """Prune repository archives according to specified rules"""
  339. repository = self.open_repository(args.repository, exclusive=True)
  340. manifest, key = Manifest.load(repository)
  341. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  342. archives = list(sorted(Archive.list_archives(repository, key, manifest, cache),
  343. key=attrgetter('ts'), reverse=True))
  344. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  345. self.print_error('At least one of the "within", "hourly", "daily", "weekly", "monthly" or "yearly" '
  346. 'settings must be specified')
  347. return 1
  348. if args.prefix:
  349. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  350. keep = []
  351. if args.within:
  352. keep += prune_within(archives, args.within)
  353. if args.hourly:
  354. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  355. if args.daily:
  356. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  357. if args.weekly:
  358. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  359. if args.monthly:
  360. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  361. if args.yearly:
  362. keep += prune_split(archives, '%Y', args.yearly, keep)
  363. keep.sort(key=attrgetter('ts'), reverse=True)
  364. to_delete = [a for a in archives if a not in keep]
  365. stats = Statistics()
  366. for archive in keep:
  367. self.print_verbose('Keeping archive: %s' % format_archive(archive))
  368. for archive in to_delete:
  369. if args.dry_run:
  370. self.print_verbose('Would prune: %s' % format_archive(archive))
  371. else:
  372. self.print_verbose('Pruning archive: %s' % format_archive(archive))
  373. archive.delete(stats)
  374. if to_delete and not args.dry_run:
  375. manifest.write()
  376. repository.commit()
  377. cache.commit()
  378. if args.stats:
  379. stats.print_('Deleted data:', cache)
  380. return self.exit_code
  381. helptext = {}
  382. helptext['patterns'] = '''
  383. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  384. number of characters, '?' matching any single character, '[...]' matching any
  385. single character specified, including ranges, and '[!...]' matching any
  386. character not specified. For the purpose of these patterns, the path
  387. separator ('\\' for Windows and '/' on other systems) is not treated
  388. specially. For a path to match a pattern, it must completely match from
  389. start to end, or must match from the start to just before a path separator.
  390. Except for the root path, paths will never end in the path separator when
  391. matching is attempted. Thus, if a given pattern ends in a path separator, a
  392. '*' is appended before matching is attempted. Patterns with wildcards should
  393. be quoted to protect them from shell expansion.
  394. Examples:
  395. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  396. $ attic create -e '*.o' repo.attic /
  397. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  398. # not '/home/user/importantjunk' or '/etc/junk':
  399. $ attic create -e '/home/*/junk' repo.attic /
  400. # Exclude the contents of '/home/user/cache' but not the directory itself:
  401. $ attic create -e /home/user/cache/ repo.attic /
  402. # The file '/home/user/cache/important' is *not* backed up:
  403. $ attic create -e /home/user/cache/ repo.attic / /home/user/cache/important
  404. '''
  405. def do_help(self, parser, commands, args):
  406. if not args.topic:
  407. parser.print_help()
  408. elif args.topic in self.helptext:
  409. print(self.helptext[args.topic])
  410. elif args.topic in commands:
  411. if args.epilog_only:
  412. print(commands[args.topic].epilog)
  413. elif args.usage_only:
  414. commands[args.topic].epilog = None
  415. commands[args.topic].print_help()
  416. else:
  417. commands[args.topic].print_help()
  418. else:
  419. parser.error('No help available on %s' % (args.topic,))
  420. return self.exit_code
  421. def preprocess_args(self, args):
  422. deprecations = [
  423. ('--hourly', '--keep-hourly', 'Warning: "--hourly" has been deprecated. Use "--keep-hourly" instead.'),
  424. ('--daily', '--keep-daily', 'Warning: "--daily" has been deprecated. Use "--keep-daily" instead.'),
  425. ('--weekly', '--keep-weekly', 'Warning: "--weekly" has been deprecated. Use "--keep-weekly" instead.'),
  426. ('--monthly', '--keep-monthly', 'Warning: "--monthly" has been deprecated. Use "--keep-monthly" instead.'),
  427. ('--yearly', '--keep-yearly', 'Warning: "--yearly" has been deprecated. Use "--keep-yearly" instead.')
  428. ]
  429. if args and args[0] == 'verify':
  430. print('Warning: "attic verify" has been deprecated. Use "attic extract --dry-run" instead.')
  431. args = ['extract', '--dry-run'] + args[1:]
  432. for i, arg in enumerate(args[:]):
  433. for old_name, new_name, warning in deprecations:
  434. if arg.startswith(old_name):
  435. args[i] = arg.replace(old_name, new_name)
  436. print(warning)
  437. return args
  438. def run(self, args=None):
  439. check_extension_modules()
  440. keys_dir = get_keys_dir()
  441. if not os.path.exists(keys_dir):
  442. os.makedirs(keys_dir)
  443. os.chmod(keys_dir, stat.S_IRWXU)
  444. cache_dir = get_cache_dir()
  445. if not os.path.exists(cache_dir):
  446. os.makedirs(cache_dir)
  447. os.chmod(cache_dir, stat.S_IRWXU)
  448. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  449. fd.write(textwrap.dedent("""
  450. Signature: 8a477f597d28d172789f06886806bc55
  451. # This file is a cache directory tag created by Attic.
  452. # For information about cache directory tags, see:
  453. # http://www.brynosaurus.com/cachedir/
  454. """).lstrip())
  455. common_parser = argparse.ArgumentParser(add_help=False)
  456. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  457. default=False,
  458. help='verbose output')
  459. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false')
  460. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  461. if args:
  462. args = self.preprocess_args(args)
  463. parser = argparse.ArgumentParser(description='Attic %s - Deduplicated Backups' % __version__)
  464. subparsers = parser.add_subparsers(title='Available commands')
  465. subparser = subparsers.add_parser('serve', parents=[common_parser],
  466. description=self.do_serve.__doc__)
  467. subparser.set_defaults(func=self.do_serve)
  468. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  469. metavar='PATH', help='restrict repository access to PATH')
  470. init_epilog = textwrap.dedent("""
  471. This command initializes an empty repository. A repository is a filesystem
  472. directory containing the deduplicated data from zero or more archives.
  473. Encryption can be enabled at repository init time.
  474. """)
  475. subparser = subparsers.add_parser('init', parents=[common_parser],
  476. description=self.do_init.__doc__, epilog=init_epilog,
  477. formatter_class=argparse.RawDescriptionHelpFormatter)
  478. subparser.set_defaults(func=self.do_init)
  479. subparser.add_argument('repository', metavar='REPOSITORY',
  480. type=location_validator(archive=False),
  481. help='repository to create')
  482. subparser.add_argument('-e', '--encryption', dest='encryption',
  483. choices=('none', 'passphrase', 'keyfile'), default='none',
  484. help='select encryption method')
  485. check_epilog = textwrap.dedent("""
  486. The check command verifies the consistency of a repository and the corresponding
  487. archives. The underlying repository data files are first checked to detect bit rot
  488. and other types of damage. After that the consistency and correctness of the archive
  489. metadata is verified.
  490. The archive metadata checks can be time consuming and requires access to the key
  491. file and/or passphrase if encryption is enabled. These checks can be skipped using
  492. the --repository-only option.
  493. """)
  494. subparser = subparsers.add_parser('check', parents=[common_parser],
  495. description=self.do_check.__doc__,
  496. epilog=check_epilog,
  497. formatter_class=argparse.RawDescriptionHelpFormatter)
  498. subparser.set_defaults(func=self.do_check)
  499. subparser.add_argument('repository', metavar='REPOSITORY',
  500. type=location_validator(archive=False),
  501. help='repository to check consistency of')
  502. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  503. default=False,
  504. help='only perform repository checks')
  505. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  506. default=False,
  507. help='only perform archives checks')
  508. subparser.add_argument('--repair', dest='repair', action='store_true',
  509. default=False,
  510. help='attempt to repair any inconsistencies found')
  511. subparser.add_argument('--last', dest='last',
  512. type=int, default=None, metavar='N',
  513. help='only check last N archives (Default: all)')
  514. change_passphrase_epilog = textwrap.dedent("""
  515. The key files used for repository encryption are optionally passphrase
  516. protected. This command can be used to change this passphrase.
  517. """)
  518. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  519. description=self.do_change_passphrase.__doc__,
  520. epilog=change_passphrase_epilog,
  521. formatter_class=argparse.RawDescriptionHelpFormatter)
  522. subparser.set_defaults(func=self.do_change_passphrase)
  523. subparser.add_argument('repository', metavar='REPOSITORY',
  524. type=location_validator(archive=False))
  525. create_epilog = textwrap.dedent("""
  526. This command creates a backup archive containing all files found while recursively
  527. traversing all paths specified. The archive will consume almost no disk space for
  528. files or parts of files that have already been stored in other archives.
  529. See "attic help patterns" for more help on exclude patterns.
  530. """)
  531. subparser = subparsers.add_parser('create', parents=[common_parser],
  532. description=self.do_create.__doc__,
  533. epilog=create_epilog,
  534. formatter_class=argparse.RawDescriptionHelpFormatter)
  535. subparser.set_defaults(func=self.do_create)
  536. subparser.add_argument('-s', '--stats', dest='stats',
  537. action='store_true', default=False,
  538. help='print statistics for the created archive')
  539. subparser.add_argument('-p', '--progress', dest='progress',
  540. action='store_true', default=False,
  541. help='print progress while creating the archive')
  542. subparser.add_argument('-e', '--exclude', dest='excludes',
  543. type=ExcludePattern, action='append',
  544. metavar="PATTERN", help='exclude paths matching PATTERN')
  545. subparser.add_argument('--exclude-from', dest='exclude_files',
  546. type=argparse.FileType('r'), action='append',
  547. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  548. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  549. action='store_true', default=False,
  550. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  551. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  552. type=int, default=300, metavar='SECONDS',
  553. help='write checkpoint every SECONDS seconds (Default: 300)')
  554. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  555. action='store_true', default=False,
  556. help='do not cross mount points')
  557. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  558. action='store_true', default=False,
  559. help='only store numeric user and group identifiers')
  560. subparser.add_argument('archive', metavar='ARCHIVE',
  561. type=location_validator(archive=True),
  562. help='archive to create')
  563. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  564. help='paths to archive')
  565. extract_epilog = textwrap.dedent("""
  566. This command extracts the contents of an archive. By default the entire
  567. archive is extracted but a subset of files and directories can be selected
  568. by passing a list of ``PATHs`` as arguments. The file selection can further
  569. be restricted by using the ``--exclude`` option.
  570. See "attic help patterns" for more help on exclude patterns.
  571. """)
  572. subparser = subparsers.add_parser('extract', parents=[common_parser],
  573. description=self.do_extract.__doc__,
  574. epilog=extract_epilog,
  575. formatter_class=argparse.RawDescriptionHelpFormatter)
  576. subparser.set_defaults(func=self.do_extract)
  577. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  578. default=False, action='store_true',
  579. help='do not actually change any files')
  580. subparser.add_argument('-e', '--exclude', dest='excludes',
  581. type=ExcludePattern, action='append',
  582. metavar="PATTERN", help='exclude paths matching PATTERN')
  583. subparser.add_argument('--exclude-from', dest='exclude_files',
  584. type=argparse.FileType('r'), action='append',
  585. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  586. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  587. action='store_true', default=False,
  588. help='only obey numeric user and group identifiers')
  589. subparser.add_argument('--strip-components', dest='strip_components',
  590. type=int, default=0, metavar='NUMBER',
  591. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  592. subparser.add_argument('--stdout', dest='stdout',
  593. action='store_true', default=False,
  594. help='write all extracted data to stdout')
  595. subparser.add_argument('archive', metavar='ARCHIVE',
  596. type=location_validator(archive=True),
  597. help='archive to extract')
  598. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  599. help='paths to extract')
  600. rename_epilog = textwrap.dedent("""
  601. This command renames an archive in the repository.
  602. """)
  603. subparser = subparsers.add_parser('rename', parents=[common_parser],
  604. description=self.do_rename.__doc__,
  605. epilog=rename_epilog,
  606. formatter_class=argparse.RawDescriptionHelpFormatter)
  607. subparser.set_defaults(func=self.do_rename)
  608. subparser.add_argument('archive', metavar='ARCHIVE',
  609. type=location_validator(archive=True),
  610. help='archive to rename')
  611. subparser.add_argument('name', metavar='NEWNAME', type=str,
  612. help='the new archive name to use')
  613. delete_epilog = textwrap.dedent("""
  614. This command deletes an archive from the repository. Any disk space not
  615. shared with any other existing archive is also reclaimed.
  616. """)
  617. subparser = subparsers.add_parser('delete', parents=[common_parser],
  618. description=self.do_delete.__doc__,
  619. epilog=delete_epilog,
  620. formatter_class=argparse.RawDescriptionHelpFormatter)
  621. subparser.set_defaults(func=self.do_delete)
  622. subparser.add_argument('-s', '--stats', dest='stats',
  623. action='store_true', default=False,
  624. help='print statistics for the deleted archive')
  625. subparser.add_argument('archive', metavar='ARCHIVE',
  626. type=location_validator(archive=True),
  627. help='archive to delete')
  628. list_epilog = textwrap.dedent("""
  629. This command lists the contents of a repository or an archive.
  630. """)
  631. subparser = subparsers.add_parser('list', parents=[common_parser],
  632. description=self.do_list.__doc__,
  633. epilog=list_epilog,
  634. formatter_class=argparse.RawDescriptionHelpFormatter)
  635. subparser.set_defaults(func=self.do_list)
  636. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  637. help='repository/archive to list contents of')
  638. mount_epilog = textwrap.dedent("""
  639. This command mounts an archive as a FUSE filesystem. This can be useful for
  640. browsing an archive or restoring individual files. Unless the ``--foreground``
  641. option is given the command will run in the background until the filesystem
  642. is ``umounted``.
  643. """)
  644. subparser = subparsers.add_parser('mount', parents=[common_parser],
  645. description=self.do_mount.__doc__,
  646. epilog=mount_epilog,
  647. formatter_class=argparse.RawDescriptionHelpFormatter)
  648. subparser.set_defaults(func=self.do_mount)
  649. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  650. help='repository/archive to mount')
  651. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  652. help='where to mount filesystem')
  653. subparser.add_argument('-f', '--foreground', dest='foreground',
  654. action='store_true', default=False,
  655. help='stay in foreground, do not daemonize')
  656. subparser.add_argument('-o', dest='options', type=str,
  657. help='Extra mount options')
  658. info_epilog = textwrap.dedent("""
  659. This command displays some detailed information about the specified archive.
  660. """)
  661. subparser = subparsers.add_parser('info', parents=[common_parser],
  662. description=self.do_info.__doc__,
  663. epilog=info_epilog,
  664. formatter_class=argparse.RawDescriptionHelpFormatter)
  665. subparser.set_defaults(func=self.do_info)
  666. subparser.add_argument('archive', metavar='ARCHIVE',
  667. type=location_validator(archive=True),
  668. help='archive to display information about')
  669. prune_epilog = textwrap.dedent("""
  670. The prune command prunes a repository by deleting archives not matching
  671. any of the specified retention options. This command is normally used by
  672. automated backup scripts wanting to keep a certain number of historic backups.
  673. As an example, "-d 7" means to keep the latest backup on each day for 7 days.
  674. Days without backups do not count towards the total.
  675. The rules are applied from hourly to yearly, and backups selected by previous
  676. rules do not count towards those of later rules. The time that each backup
  677. completes is used for pruning purposes. Dates and times are interpreted in
  678. the local timezone, and weeks go from Monday to Sunday. Specifying a
  679. negative number of archives to keep means that there is no limit.
  680. The "--keep-within" option takes an argument of the form "<int><char>",
  681. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  682. to keep all archives that were created within the past 48 hours.
  683. "1m" is taken to mean "31d". The archives kept with this option do not
  684. count towards the totals specified by any other options.
  685. If a prefix is set with -p, then only archives that start with the prefix are
  686. considered for deletion and only those archives count towards the totals
  687. specified by the rules.
  688. """)
  689. subparser = subparsers.add_parser('prune', parents=[common_parser],
  690. description=self.do_prune.__doc__,
  691. epilog=prune_epilog,
  692. formatter_class=argparse.RawDescriptionHelpFormatter)
  693. subparser.set_defaults(func=self.do_prune)
  694. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  695. default=False, action='store_true',
  696. help='do not change repository')
  697. subparser.add_argument('-s', '--stats', dest='stats',
  698. action='store_true', default=False,
  699. help='print statistics for the deleted archive')
  700. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  701. help='keep all archives within this time interval')
  702. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  703. help='number of hourly archives to keep')
  704. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  705. help='number of daily archives to keep')
  706. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  707. help='number of weekly archives to keep')
  708. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  709. help='number of monthly archives to keep')
  710. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  711. help='number of yearly archives to keep')
  712. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  713. help='only consider archive names starting with this prefix')
  714. subparser.add_argument('repository', metavar='REPOSITORY',
  715. type=location_validator(archive=False),
  716. help='repository to prune')
  717. subparser = subparsers.add_parser('help', parents=[common_parser],
  718. description='Extra help')
  719. subparser.add_argument('--epilog-only', dest='epilog_only',
  720. action='store_true', default=False)
  721. subparser.add_argument('--usage-only', dest='usage_only',
  722. action='store_true', default=False)
  723. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  724. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  725. help='additional help on TOPIC')
  726. args = parser.parse_args(args or ['-h'])
  727. self.verbose = args.verbose
  728. update_excludes(args)
  729. return args.func(args)
  730. def main():
  731. # Make sure stdout and stderr have errors='replace') to avoid unicode
  732. # issues when print()-ing unicode file names
  733. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  734. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  735. archiver = Archiver()
  736. try:
  737. exit_code = archiver.run(sys.argv[1:])
  738. except Error as e:
  739. archiver.print_error(e.get_message())
  740. exit_code = e.exit_code
  741. except RemoteRepository.RPCError as e:
  742. print(e)
  743. exit_code = 1
  744. except KeyboardInterrupt:
  745. archiver.print_error('Error: Keyboard interrupt')
  746. exit_code = 1
  747. else:
  748. if exit_code:
  749. archiver.print_error('Exiting with failure status due to previous errors')
  750. sys.exit(exit_code)
  751. if __name__ == '__main__':
  752. main()