cache.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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, crypto):
  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(crypto)
  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, crypto):
  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. data, hash = crypto.decrypt(self.store.get(NS_CINDEX, id))
  40. cindex = msgpack.unpackb(data)
  41. for id, size in cindex['chunks']:
  42. try:
  43. count, size = self.chunkmap[id]
  44. self.chunkmap[id] = count + 1, size
  45. except KeyError:
  46. self.chunkmap[id] = 1, size
  47. self.save()
  48. def save(self):
  49. assert self.store.state == self.store.OPEN
  50. cache = {'version': 1,
  51. 'store': self.store.uuid,
  52. 'chunkmap': self.chunkmap,
  53. 'tid': self.store.tid,
  54. }
  55. data = msgpack.packb(cache)
  56. cachedir = os.path.dirname(self.path)
  57. if not os.path.exists(cachedir):
  58. os.makedirs(cachedir)
  59. with open(self.path, 'wb') as fd:
  60. fd.write(data)
  61. def add_chunk(self, id, data, crypto):
  62. if self.seen_chunk(id):
  63. return self.chunk_incref(id)
  64. data, hash = crypto.encrypt_read(data)
  65. csize = len(data)
  66. self.store.put(NS_CHUNKS, id, data)
  67. self.chunkmap[id] = (1, csize)
  68. return csize
  69. def seen_chunk(self, id):
  70. count, size = self.chunkmap.get(id, (0, 0))
  71. return count
  72. def chunk_incref(self, id):
  73. count, size = self.chunkmap[id]
  74. self.chunkmap[id] = (count + 1, size)
  75. return size
  76. def chunk_decref(self, id):
  77. count, size = self.chunkmap[id]
  78. if count == 1:
  79. del self.chunkmap[id]
  80. self.store.delete(NS_CHUNKS, id)
  81. else:
  82. self.chunkmap[id] = (count - 1, size)