cache.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import logging
  2. import msgpack
  3. import os
  4. from . import NS_ARCHIVE_CHUNKS, NS_CHUNK
  5. class Cache(object):
  6. """Client Side cache
  7. """
  8. def __init__(self, store, crypto):
  9. self.store = store
  10. self.path = os.path.join(os.path.expanduser('~'), '.dedupestore', 'cache',
  11. '%s.cache' % self.store.uuid)
  12. self.tid = -1
  13. self.open()
  14. if self.tid != self.store.tid:
  15. self.init(crypto)
  16. def open(self):
  17. if not os.path.exists(self.path):
  18. return
  19. cache = msgpack.unpackb(open(self.path, 'rb').read())
  20. version = cache.get('version')
  21. if version != 1:
  22. logging.error('Unsupported cache version %r' % version)
  23. return
  24. if cache['store'] != self.store.uuid:
  25. raise Exception('Cache UUID mismatch')
  26. self.chunkmap = cache['chunkmap']
  27. self.tid = cache['tid']
  28. def init(self, crypto):
  29. """Initializes cache by fetching and reading all archive indicies
  30. """
  31. logging.info('Initializing cache...')
  32. self.chunkmap = {}
  33. self.tid = self.store.tid
  34. if self.store.tid == 0:
  35. return
  36. for id in list(self.store.list(NS_ARCHIVE_CHUNKS)):
  37. data, hash = crypto.decrypt(self.store.get(NS_ARCHIVE_CHUNKS, id))
  38. cindex = msgpack.unpackb(data)
  39. for id, size in cindex['chunks']:
  40. try:
  41. count, size = self.chunkmap[id]
  42. self.chunkmap[id] = count + 1, size
  43. except KeyError:
  44. self.chunkmap[id] = 1, size
  45. self.save()
  46. def save(self):
  47. assert self.store.state == self.store.OPEN
  48. cache = {'version': 1,
  49. 'store': self.store.uuid,
  50. 'chunkmap': self.chunkmap,
  51. 'tid': self.store.tid,
  52. }
  53. data = msgpack.packb(cache)
  54. cachedir = os.path.dirname(self.path)
  55. if not os.path.exists(cachedir):
  56. os.makedirs(cachedir)
  57. with open(self.path, 'wb') as fd:
  58. fd.write(data)
  59. def add_chunk(self, id, data, crypto):
  60. if self.seen_chunk(id):
  61. return self.chunk_incref(id)
  62. data, hash = crypto.encrypt_read(data)
  63. csize = len(data)
  64. self.store.put(NS_CHUNK, id, data)
  65. self.chunkmap[id] = (1, csize)
  66. return csize
  67. def seen_chunk(self, id):
  68. count, size = self.chunkmap.get(id, (0, 0))
  69. return count
  70. def chunk_incref(self, id):
  71. count, size = self.chunkmap[id]
  72. self.chunkmap[id] = (count + 1, size)
  73. return size
  74. def chunk_decref(self, id):
  75. count, size = self.chunkmap[id]
  76. if count == 1:
  77. del self.chunkmap[id]
  78. self.store.delete(NS_CHUNK, id)
  79. else:
  80. self.chunkmap[id] = (count - 1, size)