archiver.py 25 KB

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