2
0

cache.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. from __future__ import with_statement
  2. from ConfigParser import RawConfigParser
  3. import fcntl
  4. import msgpack
  5. import os
  6. import shutil
  7. from . import NS_CHUNK, NS_ARCHIVE_METADATA
  8. from .helpers import error_callback
  9. from .hashindex import ChunkIndex
  10. class Cache(object):
  11. """Client Side cache
  12. """
  13. def __init__(self, store, key):
  14. self.txn_active = False
  15. self.store = store
  16. self.key = key
  17. self.path = os.path.join(Cache.cache_dir_path(), self.store.id.encode('hex'))
  18. if not os.path.exists(self.path):
  19. self.create()
  20. self.open()
  21. assert self.id == store.id
  22. if self.tid != store.tid:
  23. self.sync()
  24. self.commit()
  25. @staticmethod
  26. def cache_dir_path():
  27. """Return path to directory used for storing users cache files"""
  28. return os.path.join(os.path.expanduser('~'), '.darc', 'cache')
  29. def create(self):
  30. """Create a new empty store at `path`
  31. """
  32. os.makedirs(self.path)
  33. with open(os.path.join(self.path, 'README'), 'wb') as fd:
  34. fd.write('This is a DARC cache')
  35. config = RawConfigParser()
  36. config.add_section('cache')
  37. config.set('cache', 'version', '1')
  38. config.set('cache', 'store_id', self.store.id.encode('hex'))
  39. config.set('cache', 'tid', '0')
  40. with open(os.path.join(self.path, 'config'), 'wb') as fd:
  41. config.write(fd)
  42. ChunkIndex.create(os.path.join(self.path, 'chunks'))
  43. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  44. pass # empty file
  45. def open(self):
  46. if not os.path.isdir(self.path):
  47. raise Exception('%s Does not look like a darc cache' % self.path)
  48. self.lock_fd = open(os.path.join(self.path, 'README'), 'r+')
  49. fcntl.flock(self.lock_fd, fcntl.LOCK_EX)
  50. self.rollback()
  51. self.config = RawConfigParser()
  52. self.config.read(os.path.join(self.path, 'config'))
  53. if self.config.getint('cache', 'version') != 1:
  54. raise Exception('%s Does not look like a darc cache')
  55. self.id = self.config.get('cache', 'store_id').decode('hex')
  56. self.tid = self.config.getint('cache', 'tid')
  57. self.chunks = ChunkIndex(os.path.join(self.path, 'chunks'))
  58. self.files = None
  59. def _read_files(self):
  60. self.files = {}
  61. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  62. u = msgpack.Unpacker()
  63. while True:
  64. data = fd.read(64 * 1024)
  65. if not data:
  66. break
  67. u.feed(data)
  68. for hash, item in u:
  69. if item[0] < 8:
  70. self.files[hash] = (item[0] + 1,) + item[1:]
  71. def begin_txn(self):
  72. # Initialize transaction snapshot
  73. txn_dir = os.path.join(self.path, 'txn.tmp')
  74. os.mkdir(txn_dir)
  75. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  76. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  77. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  78. os.rename(os.path.join(self.path, 'txn.tmp'),
  79. os.path.join(self.path, 'txn.active'))
  80. self.txn_active = True
  81. def commit(self):
  82. """Commit transaction
  83. """
  84. if not self.txn_active:
  85. return
  86. if self.files is not None:
  87. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  88. for item in self.files.iteritems():
  89. msgpack.pack(item, fd)
  90. self.config.set('cache', 'tid', self.store.tid)
  91. with open(os.path.join(self.path, 'config'), 'w') as fd:
  92. self.config.write(fd)
  93. self.chunks.flush()
  94. os.rename(os.path.join(self.path, 'txn.active'),
  95. os.path.join(self.path, 'txn.tmp'))
  96. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  97. self.txn_active = False
  98. def rollback(self):
  99. """Roll back partial and aborted transactions
  100. """
  101. # Remove partial transaction
  102. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  103. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  104. # Roll back active transaction
  105. txn_dir = os.path.join(self.path, 'txn.active')
  106. if os.path.exists(txn_dir):
  107. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  108. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  109. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  110. shutil.rmtree(txn_dir)
  111. self.txn_active = False
  112. def sync(self):
  113. """Initializes cache by fetching and reading all archive indicies
  114. """
  115. def cb(chunk, error, id):
  116. assert not error
  117. data, items_hash = self.key.decrypt(chunk)
  118. assert self.key.id_hash(data) == id
  119. unpacker.feed(data)
  120. for item in unpacker:
  121. try:
  122. for id, size, csize in item['chunks']:
  123. try:
  124. count, size, csize = self.chunks[id]
  125. self.chunks[id] = count + 1, size, csize
  126. except KeyError:
  127. self.chunks[id] = 1, size, csize
  128. pass
  129. except KeyError:
  130. pass
  131. self.begin_txn()
  132. print 'Initializing cache...'
  133. self.chunks.clear()
  134. unpacker = msgpack.Unpacker()
  135. for id in self.store.list(NS_ARCHIVE_METADATA):
  136. data, hash = self.key.decrypt(self.store.get(NS_ARCHIVE_METADATA, id))
  137. archive = msgpack.unpackb(data)
  138. print 'Analyzing archive:', archive['name']
  139. for id, size, csize in archive['items']:
  140. try:
  141. count, size, csize = self.chunks[id]
  142. self.chunks[id] = count + 1, size, csize
  143. except KeyError:
  144. self.chunks[id] = 1, size, csize
  145. self.store.get(NS_CHUNK, id, callback=cb, callback_data=id)
  146. self.store.flush_rpc()
  147. def add_chunk(self, id, data):
  148. if not self.txn_active:
  149. self.begin_txn()
  150. if self.seen_chunk(id):
  151. return self.chunk_incref(id)
  152. size = len(data)
  153. data, hash = self.key.encrypt(data)
  154. csize = len(data)
  155. self.store.put(NS_CHUNK, id, data, callback=error_callback)
  156. self.chunks[id] = (1, size, csize)
  157. return id, size, csize
  158. def seen_chunk(self, id):
  159. return self.chunks.get(id, (0, 0, 0))[0]
  160. def chunk_incref(self, id):
  161. if not self.txn_active:
  162. self.begin_txn()
  163. count, size, csize = self.chunks[id]
  164. self.chunks[id] = (count + 1, size, csize)
  165. return id, size, csize
  166. def chunk_decref(self, id):
  167. if not self.txn_active:
  168. self.begin_txn()
  169. count, size, csize = self.chunks[id]
  170. if count == 1:
  171. del self.chunks[id]
  172. self.store.delete(NS_CHUNK, id, callback=error_callback)
  173. else:
  174. self.chunks[id] = (count - 1, size, csize)
  175. def file_known_and_unchanged(self, path_hash, st):
  176. if self.files is None:
  177. self._read_files()
  178. entry = self.files.get(path_hash)
  179. if (entry and entry[3] == st.st_mtime
  180. and entry[2] == st.st_size and entry[1] == st.st_ino):
  181. # reset entry age
  182. self.files[path_hash] = (0,) + entry[1:]
  183. return entry[4]
  184. else:
  185. return None
  186. def memorize_file(self, path_hash, st, ids):
  187. # Entry: Age, inode, size, mtime, chunk ids
  188. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids