2
0

cache.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 .archive import Archive
  8. from .helpers import error_callback, get_cache_dir
  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(get_cache_dir(), store.meta['id'])
  18. if not os.path.exists(self.path):
  19. self.create()
  20. self.open()
  21. if self.manifest != store.meta['manifest']:
  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.meta['id'])
  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 = self.config.get('cache', 'manifest')
  52. self.chunks = ChunkIndex(os.path.join(self.path, 'chunks'))
  53. self.files = None
  54. def _read_files(self):
  55. self.files = {}
  56. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  57. u = msgpack.Unpacker()
  58. while True:
  59. data = fd.read(64 * 1024)
  60. if not data:
  61. break
  62. u.feed(data)
  63. for hash, item in u:
  64. if item[0] < 10:
  65. self.files[hash] = (item[0] + 1,) + item[1:]
  66. def begin_txn(self):
  67. # Initialize transaction snapshot
  68. txn_dir = os.path.join(self.path, 'txn.tmp')
  69. os.mkdir(txn_dir)
  70. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  71. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  72. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  73. os.rename(os.path.join(self.path, 'txn.tmp'),
  74. os.path.join(self.path, 'txn.active'))
  75. self.txn_active = True
  76. def commit(self):
  77. """Commit transaction
  78. """
  79. if not self.txn_active:
  80. return
  81. if self.files is not None:
  82. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  83. for item in self.files.iteritems():
  84. msgpack.pack(item, fd)
  85. self.config.set('cache', 'manifest', self.store.meta['manifest'])
  86. with open(os.path.join(self.path, 'config'), 'w') as fd:
  87. self.config.write(fd)
  88. self.chunks.flush()
  89. os.rename(os.path.join(self.path, 'txn.active'),
  90. os.path.join(self.path, 'txn.tmp'))
  91. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  92. self.txn_active = False
  93. def rollback(self):
  94. """Roll back partial and aborted transactions
  95. """
  96. # Roll back active transaction
  97. txn_dir = os.path.join(self.path, 'txn.active')
  98. if os.path.exists(txn_dir):
  99. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  100. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  101. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  102. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  103. # Remove partial transaction
  104. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  105. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  106. self.txn_active = False
  107. def sync(self):
  108. """Initializes cache by fetching and reading all archive indicies
  109. """
  110. def cb(chunk, error, id):
  111. assert not error
  112. data = self.key.decrypt(id, chunk)
  113. try:
  114. count, size, csize = self.chunks[id]
  115. self.chunks[id] = count + 1, size, csize
  116. except KeyError:
  117. self.chunks[id] = 1, len(data), len(chunk)
  118. unpacker.feed(data)
  119. for item in unpacker:
  120. try:
  121. for id, size, csize in item['chunks']:
  122. try:
  123. count, size, csize = self.chunks[id]
  124. self.chunks[id] = count + 1, size, csize
  125. except KeyError:
  126. self.chunks[id] = 1, size, csize
  127. pass
  128. except KeyError:
  129. pass
  130. self.begin_txn()
  131. print 'Initializing cache...'
  132. self.chunks.clear()
  133. # Add manifest chunk to chunk index
  134. mid = self.store.meta['manifest'].decode('hex')
  135. cdata = self.store.get(mid)
  136. mdata = self.key.decrypt(mid, cdata)
  137. self.chunks[mid] = 1, len(mdata), len(cdata)
  138. unpacker = msgpack.Unpacker()
  139. for name, info in Archive.read_manifest(self.store, self.key)['archives'].items():
  140. id = info['id']
  141. cdata = self.store.get(id)
  142. data = self.key.decrypt(id, cdata)
  143. try:
  144. count, size, csize = self.chunks[id]
  145. self.chunks[id] = count + 1, size, csize
  146. except KeyError:
  147. self.chunks[id] = 1, len(data), len(cdata)
  148. archive = msgpack.unpackb(data)
  149. print 'Analyzing archive:', archive['name']
  150. for id in archive['items']:
  151. self.store.get(id, callback=cb, callback_data=id)
  152. self.store.flush_rpc()
  153. def add_chunk(self, id, data, stats):
  154. if not self.txn_active:
  155. self.begin_txn()
  156. if self.seen_chunk(id):
  157. return self.chunk_incref(id, stats)
  158. size = len(data)
  159. data = self.key.encrypt(data)
  160. csize = len(data)
  161. self.store.put(id, data, callback=error_callback)
  162. self.chunks[id] = (1, size, csize)
  163. stats.update(size, csize, True)
  164. return id, size, csize
  165. def seen_chunk(self, id):
  166. return self.chunks.get(id, (0, 0, 0))[0]
  167. def chunk_incref(self, id, stats):
  168. if not self.txn_active:
  169. self.begin_txn()
  170. count, size, csize = self.chunks[id]
  171. self.chunks[id] = (count + 1, size, csize)
  172. stats.update(size, csize, False)
  173. return id, size, csize
  174. def chunk_decref(self, id):
  175. if not self.txn_active:
  176. self.begin_txn()
  177. count, size, csize = self.chunks[id]
  178. if count == 1:
  179. del self.chunks[id]
  180. self.store.delete(id, callback=error_callback)
  181. else:
  182. self.chunks[id] = (count - 1, size, csize)
  183. def file_known_and_unchanged(self, path_hash, st):
  184. if self.files is None:
  185. self._read_files()
  186. entry = self.files.get(path_hash)
  187. if (entry and entry[3] == st.st_mtime
  188. and entry[2] == st.st_size and entry[1] == st.st_ino):
  189. # reset entry age
  190. self.files[path_hash] = (0,) + entry[1:]
  191. return entry[4]
  192. else:
  193. return None
  194. def memorize_file(self, path_hash, st, ids):
  195. # Entry: Age, inode, size, mtime, chunk ids
  196. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids