cache.py 8.7 KB

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