cache.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 error_callback, 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. 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.manifest.id.encode('hex'))
  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. unpacker = msgpack.Unpacker()
  134. for name, info in self.manifest.archives.items():
  135. id = info['id']
  136. cdata = self.store.get(id)
  137. data = self.key.decrypt(id, cdata)
  138. try:
  139. count, size, csize = self.chunks[id]
  140. self.chunks[id] = count + 1, size, csize
  141. except KeyError:
  142. self.chunks[id] = 1, len(data), len(cdata)
  143. archive = msgpack.unpackb(data)
  144. print 'Analyzing archive:', archive['name']
  145. for id in archive['items']:
  146. self.store.get(id, callback=cb, callback_data=id)
  147. self.store.flush_rpc()
  148. def add_chunk(self, id, data, stats):
  149. if not self.txn_active:
  150. self.begin_txn()
  151. if self.seen_chunk(id):
  152. return self.chunk_incref(id, stats)
  153. size = len(data)
  154. data = self.key.encrypt(data)
  155. csize = len(data)
  156. self.store.put(id, data, callback=error_callback)
  157. self.chunks[id] = (1, size, csize)
  158. stats.update(size, csize, True)
  159. return id, size, csize
  160. def seen_chunk(self, id):
  161. return self.chunks.get(id, (0, 0, 0))[0]
  162. def chunk_incref(self, id, stats):
  163. if not self.txn_active:
  164. self.begin_txn()
  165. count, size, csize = self.chunks[id]
  166. self.chunks[id] = (count + 1, size, csize)
  167. stats.update(size, csize, False)
  168. return id, size, csize
  169. def chunk_decref(self, id):
  170. if not self.txn_active:
  171. self.begin_txn()
  172. count, size, csize = self.chunks[id]
  173. if count == 1:
  174. del self.chunks[id]
  175. self.store.delete(id, callback=error_callback)
  176. else:
  177. self.chunks[id] = (count - 1, size, csize)
  178. def file_known_and_unchanged(self, path_hash, st):
  179. if self.files is None:
  180. self._read_files()
  181. entry = self.files.get(path_hash)
  182. if (entry and entry[3] == st.st_mtime
  183. and entry[2] == st.st_size and entry[1] == st.st_ino):
  184. # reset entry age
  185. self.files[path_hash] = (0,) + entry[1:]
  186. return entry[4]
  187. else:
  188. return None
  189. def memorize_file(self, path_hash, st, ids):
  190. # Entry: Age, inode, size, mtime, chunk ids
  191. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids