archiver.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 .archive import Archive
  9. from .store import Store
  10. from .cache import Cache
  11. from .key import key_creator
  12. from .helpers import location_validator, format_time, \
  13. format_file_mode, IncludePattern, ExcludePattern, exclude_path, adjust_patterns, to_localtime, \
  14. get_cache_dir, format_timedelta, prune_split, Manifest, Location, remove_surrogates
  15. from .remote import StoreServer, RemoteStore
  16. class Archiver(object):
  17. def __init__(self):
  18. self.exit_code = 0
  19. def open_store(self, location, create=False):
  20. if location.proto == 'ssh':
  21. store = RemoteStore(location, create=create)
  22. else:
  23. store = Store(location.path, create=create)
  24. store._location = location
  25. return store
  26. def print_error(self, msg, *args):
  27. msg = args and msg % args or msg
  28. self.exit_code = 1
  29. print('darc: ' + msg, file=sys.stderr)
  30. def print_verbose(self, msg, *args, **kw):
  31. if self.verbose:
  32. msg = args and msg % args or msg
  33. if kw.get('newline', True):
  34. print(msg)
  35. else:
  36. print(msg, end=' ')
  37. def do_serve(self, args):
  38. return StoreServer().serve()
  39. def do_init(self, args):
  40. print('Initializing store "%s"' % args.store.orig)
  41. store = self.open_store(args.store, create=True)
  42. key = key_creator(store, args)
  43. manifest = Manifest()
  44. manifest.store = store
  45. manifest.key = key
  46. manifest.write()
  47. store.commit()
  48. return self.exit_code
  49. def do_change_passphrase(self, args):
  50. store = self.open_store(Location(args.store))
  51. manifest, key = Manifest.load(store)
  52. key.change_passphrase()
  53. return self.exit_code
  54. def do_create(self, args):
  55. t0 = datetime.now()
  56. store = self.open_store(args.archive)
  57. manifest, key = Manifest.load(store)
  58. cache = Cache(store, key, manifest)
  59. archive = Archive(store, key, manifest, args.archive.archive, cache=cache,
  60. create=True, checkpoint_interval=args.checkpoint_interval,
  61. numeric_owner=args.numeric_owner)
  62. # Add darc cache dir to inode_skip list
  63. skip_inodes = set()
  64. try:
  65. st = os.stat(get_cache_dir())
  66. skip_inodes.add((st.st_ino, st.st_dev))
  67. except IOError:
  68. pass
  69. # Add local store dir to inode_skip list
  70. if not args.archive.host:
  71. try:
  72. st = os.stat(args.archive.path)
  73. skip_inodes.add((st.st_ino, st.st_dev))
  74. except IOError:
  75. pass
  76. for path in args.paths:
  77. if args.dontcross:
  78. try:
  79. restrict_dev = os.lstat(path).st_dev
  80. except OSError as e:
  81. self.print_error('%s: %s', path, e)
  82. continue
  83. else:
  84. restrict_dev = None
  85. self._process(archive, cache, args.patterns, skip_inodes, path, restrict_dev)
  86. archive.save()
  87. if args.stats:
  88. t = datetime.now()
  89. diff = t - t0
  90. print('-' * 40)
  91. print('Archive name: %s' % args.archive.archive)
  92. print('Archive fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  93. print('Start time: %s' % t0.strftime('%c'))
  94. print('End time: %s' % t.strftime('%c'))
  95. print('Duration: %s' % format_timedelta(diff))
  96. archive.stats.print_()
  97. print('-' * 40)
  98. return self.exit_code
  99. def _process(self, archive, cache, patterns, skip_inodes, path, restrict_dev):
  100. if exclude_path(path, patterns):
  101. return
  102. try:
  103. st = os.lstat(path)
  104. except OSError as e:
  105. self.print_error('%s: %s', path, e)
  106. return
  107. if (st.st_ino, st.st_dev) in skip_inodes:
  108. return
  109. # Entering a new filesystem?
  110. if restrict_dev and st.st_dev != restrict_dev:
  111. return
  112. # Ignore unix sockets
  113. if stat.S_ISSOCK(st.st_mode):
  114. return
  115. self.print_verbose(remove_surrogates(path))
  116. if stat.S_ISREG(st.st_mode):
  117. try:
  118. archive.process_file(path, st, cache)
  119. except IOError as e:
  120. self.print_error('%s: %s', path, e)
  121. elif stat.S_ISDIR(st.st_mode):
  122. archive.process_item(path, st)
  123. try:
  124. entries = os.listdir(path)
  125. except OSError as e:
  126. self.print_error('%s: %s', path, e)
  127. else:
  128. for filename in sorted(entries):
  129. self._process(archive, cache, patterns, skip_inodes,
  130. os.path.join(path, filename), restrict_dev)
  131. elif stat.S_ISLNK(st.st_mode):
  132. archive.process_symlink(path, st)
  133. elif stat.S_ISFIFO(st.st_mode):
  134. archive.process_item(path, st)
  135. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  136. archive.process_dev(path, st)
  137. else:
  138. self.print_error('Unknown file type: %s', path)
  139. def do_extract(self, args):
  140. store = self.open_store(args.archive)
  141. manifest, key = Manifest.load(store)
  142. archive = Archive(store, key, manifest, args.archive.archive,
  143. numeric_owner=args.numeric_owner)
  144. dirs = []
  145. for item, peek in archive.iter_items(lambda item: not exclude_path(item[b'path'], args.patterns)):
  146. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  147. archive.extract_item(dirs.pop(-1), args.dest)
  148. self.print_verbose(remove_surrogates(item[b'path']))
  149. try:
  150. if stat.S_ISDIR(item[b'mode']):
  151. dirs.append(item)
  152. archive.extract_item(item, args.dest, restore_attrs=False)
  153. else:
  154. archive.extract_item(item, args.dest, peek=peek)
  155. except IOError as e:
  156. self.print_error('%s: %s', remove_surrogates(item[b'path']), e)
  157. while dirs:
  158. archive.extract_item(dirs.pop(-1), args.dest)
  159. return self.exit_code
  160. def do_delete(self, args):
  161. store = self.open_store(args.archive)
  162. manifest, key = Manifest.load(store)
  163. cache = Cache(store, key, manifest)
  164. archive = Archive(store, key, manifest, args.archive.archive, cache=cache)
  165. archive.delete(cache)
  166. return self.exit_code
  167. def do_list(self, args):
  168. store = self.open_store(args.src)
  169. manifest, key = Manifest.load(store)
  170. if args.src.archive:
  171. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  172. archive = Archive(store, key, manifest, args.src.archive)
  173. for item, _ in archive.iter_items():
  174. type = tmap.get(item[b'mode'] // 4096, '?')
  175. mode = format_file_mode(item[b'mode'])
  176. size = 0
  177. if type == '-':
  178. try:
  179. size = sum(size for _, size, _ in item[b'chunks'])
  180. except KeyError:
  181. pass
  182. mtime = format_time(datetime.fromtimestamp(item[b'mtime']))
  183. if b'source' in item:
  184. if type == 'l':
  185. extra = ' -> %s' % item[b'source']
  186. else:
  187. type = 'h'
  188. extra = ' link to %s' % item[b'source']
  189. else:
  190. extra = ''
  191. print('%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item[b'user'] or item[b'uid'],
  192. item[b'group'] or item[b'gid'], size, mtime,
  193. remove_surrogates(item[b'path']), extra))
  194. else:
  195. for archive in sorted(Archive.list_archives(store, key, manifest), key=attrgetter('ts')):
  196. print('%-20s %s' % (archive.metadata[b'name'], to_localtime(archive.ts).strftime('%c')))
  197. return self.exit_code
  198. def do_verify(self, args):
  199. store = self.open_store(args.archive)
  200. manifest, key = Manifest.load(store)
  201. archive = Archive(store, key, manifest, args.archive.archive)
  202. def start_cb(item):
  203. self.print_verbose('%s ...', remove_surrogates(item[b'path']), newline=False)
  204. def result_cb(item, success):
  205. if success:
  206. self.print_verbose('OK')
  207. else:
  208. self.print_verbose('ERROR')
  209. self.print_error('%s: verification failed' % remove_surrogates(item[b'path']))
  210. for item, peek in archive.iter_items(lambda item: not exclude_path(item[b'path'], args.patterns)):
  211. if stat.S_ISREG(item[b'mode']) and b'chunks' in item:
  212. archive.verify_file(item, start_cb, result_cb, peek=peek)
  213. return self.exit_code
  214. def do_info(self, args):
  215. store = self.open_store(args.archive)
  216. manifest, key = Manifest.load(store)
  217. cache = Cache(store, key, manifest)
  218. archive = Archive(store, key, manifest, args.archive.archive, cache=cache)
  219. stats = archive.calc_stats(cache)
  220. print('Name:', archive.name)
  221. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  222. print('Hostname:', archive.metadata[b'hostname'])
  223. print('Username:', archive.metadata[b'username'])
  224. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  225. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  226. stats.print_()
  227. return self.exit_code
  228. def do_prune(self, args):
  229. store = self.open_store(args.store)
  230. manifest, key = Manifest.load(store)
  231. cache = Cache(store, key, manifest)
  232. archives = list(sorted(Archive.list_archives(store, key, manifest, cache),
  233. key=attrgetter('ts'), reverse=True))
  234. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0:
  235. self.print_error('At least one of the "hourly", "daily", "weekly", "monthly" or "yearly" '
  236. 'settings must be specified')
  237. return 1
  238. if args.prefix:
  239. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  240. keep = []
  241. if args.hourly:
  242. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly)
  243. if args.daily:
  244. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  245. if args.weekly:
  246. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  247. if args.monthly:
  248. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  249. if args.yearly:
  250. keep += prune_split(archives, '%Y', args.yearly, keep)
  251. keep.sort(key=attrgetter('ts'), reverse=True)
  252. to_delete = [a for a in archives if a not in keep]
  253. for archive in keep:
  254. self.print_verbose('Keeping archive "%s"' % archive.name)
  255. for archive in to_delete:
  256. self.print_verbose('Pruning archive "%s"', archive.name)
  257. archive.delete(cache)
  258. return self.exit_code
  259. def run(self, args=None):
  260. dot_path = os.path.join(os.path.expanduser('~'), '.darc')
  261. if not os.path.exists(dot_path):
  262. os.mkdir(dot_path)
  263. os.mkdir(os.path.join(dot_path, 'keys'))
  264. os.mkdir(os.path.join(dot_path, 'cache'))
  265. common_parser = argparse.ArgumentParser(add_help=False)
  266. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  267. default=False,
  268. help='Verbose output')
  269. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  270. subparsers = parser.add_subparsers(title='Available subcommands')
  271. subparser = subparsers.add_parser('serve', parents=[common_parser])
  272. subparser.set_defaults(func=self.do_serve)
  273. subparser = subparsers.add_parser('init', parents=[common_parser])
  274. subparser.set_defaults(func=self.do_init)
  275. subparser.add_argument('store',
  276. type=location_validator(archive=False),
  277. help='Store to create')
  278. subparser.add_argument('--key-file', dest='keyfile',
  279. action='store_true', default=False,
  280. help='Encrypt data using key file')
  281. subparser.add_argument('--passphrase', dest='passphrase',
  282. action='store_true', default=False,
  283. help='Encrypt data using passphrase derived key')
  284. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser])
  285. subparser.set_defaults(func=self.do_change_passphrase)
  286. subparser.add_argument('store', type=location_validator(archive=False))
  287. subparser = subparsers.add_parser('create', parents=[common_parser])
  288. subparser.set_defaults(func=self.do_create)
  289. subparser.add_argument('-s', '--stats', dest='stats',
  290. action='store_true', default=False,
  291. help='Print statistics for the created archive')
  292. subparser.add_argument('-i', '--include', dest='patterns',
  293. type=IncludePattern, action='append',
  294. help='Include condition')
  295. subparser.add_argument('-e', '--exclude', dest='patterns',
  296. type=ExcludePattern, action='append',
  297. help='Include condition')
  298. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  299. type=int, default=300, metavar='SECONDS',
  300. help='Write checkpointe ever SECONDS seconds (Default: 300)')
  301. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  302. action='store_true', default=False,
  303. help='Do not cross mount points')
  304. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  305. action='store_true', default=False,
  306. help='Only store numeric user and group identifiers')
  307. subparser.add_argument('archive', metavar='ARCHIVE',
  308. type=location_validator(archive=True),
  309. help='Archive to create')
  310. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  311. default=['.'], help='Paths to add to archive')
  312. subparser = subparsers.add_parser('extract', parents=[common_parser])
  313. subparser.set_defaults(func=self.do_extract)
  314. subparser.add_argument('-i', '--include', dest='patterns',
  315. type=IncludePattern, action='append',
  316. help='Include condition')
  317. subparser.add_argument('-e', '--exclude', dest='patterns',
  318. type=ExcludePattern, action='append',
  319. help='Include condition')
  320. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  321. action='store_true', default=False,
  322. help='Only obey numeric user and group identifiers')
  323. subparser.add_argument('archive', metavar='ARCHIVE',
  324. type=location_validator(archive=True),
  325. help='Archive to create')
  326. subparser.add_argument('dest', metavar='DEST', type=str, nargs='?',
  327. help='Where to extract files')
  328. subparser = subparsers.add_parser('delete', parents=[common_parser])
  329. subparser.set_defaults(func=self.do_delete)
  330. subparser.add_argument('archive', metavar='ARCHIVE',
  331. type=location_validator(archive=True),
  332. help='Archive to delete')
  333. subparser = subparsers.add_parser('list', parents=[common_parser])
  334. subparser.set_defaults(func=self.do_list)
  335. subparser.add_argument('src', metavar='SRC', type=location_validator(),
  336. help='Store/Archive to list contents of')
  337. subparser = subparsers.add_parser('verify', parents=[common_parser])
  338. subparser.set_defaults(func=self.do_verify)
  339. subparser.add_argument('-i', '--include', dest='patterns',
  340. type=IncludePattern, action='append',
  341. help='Include condition')
  342. subparser.add_argument('-e', '--exclude', dest='patterns',
  343. type=ExcludePattern, action='append',
  344. help='Include condition')
  345. subparser.add_argument('archive', metavar='ARCHIVE',
  346. type=location_validator(archive=True),
  347. help='Archive to verity integrity of')
  348. subparser = subparsers.add_parser('info', parents=[common_parser])
  349. subparser.set_defaults(func=self.do_info)
  350. subparser.add_argument('archive', metavar='ARCHIVE',
  351. type=location_validator(archive=True),
  352. help='Archive to display information about')
  353. subparser = subparsers.add_parser('prune', parents=[common_parser])
  354. subparser.set_defaults(func=self.do_prune)
  355. subparser.add_argument('-H', '--hourly', dest='hourly', type=int, default=0,
  356. help='Number of hourly archives to keep')
  357. subparser.add_argument('-d', '--daily', dest='daily', type=int, default=0,
  358. help='Number of daily archives to keep')
  359. subparser.add_argument('-w', '--weekly', dest='weekly', type=int, default=0,
  360. help='Number of daily archives to keep')
  361. subparser.add_argument('-m', '--monthly', dest='monthly', type=int, default=0,
  362. help='Number of monthly archives to keep')
  363. subparser.add_argument('-y', '--yearly', dest='yearly', type=int, default=0,
  364. help='Number of yearly archives to keep')
  365. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  366. help='Only consider archive names starting with this prefix')
  367. subparser.add_argument('store', metavar='STORE',
  368. type=location_validator(archive=False),
  369. help='Store to prune')
  370. args = parser.parse_args(args)
  371. if getattr(args, 'patterns', None):
  372. adjust_patterns(args.patterns)
  373. self.verbose = args.verbose
  374. return args.func(args)
  375. def main():
  376. archiver = Archiver()
  377. try:
  378. exit_code = archiver.run()
  379. except Store.DoesNotExist:
  380. archiver.print_error('Error: Store not found')
  381. exit_code = 1
  382. except Store.AlreadyExists:
  383. archiver.print_error('Error: Store already exists')
  384. exit_code = 1
  385. except Archive.AlreadyExists as e:
  386. archiver.print_error('Error: Archive "%s" already exists', e)
  387. exit_code = 1
  388. except Archive.DoesNotExist as e:
  389. archiver.print_error('Error: Archive "%s" does not exist', e)
  390. exit_code = 1
  391. except KeyboardInterrupt:
  392. archiver.print_error('Error: Keyboard interrupt')
  393. exit_code = 1
  394. else:
  395. if exit_code:
  396. archiver.print_error('Exiting with failure status due to previous errors')
  397. sys.exit(exit_code)
  398. if __name__ == '__main__':
  399. main()