archiver.py 43 KB

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