archiver.py 42 KB

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