archiver.py 19 KB

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