cache.py 2.8 KB

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