cache.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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, 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(), 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. def create(self):
  26. """Create a new empty store at `path`
  27. """
  28. os.makedirs(self.path)
  29. with open(os.path.join(self.path, 'README'), 'wb') as fd:
  30. fd.write('This is a DARC cache')
  31. config = RawConfigParser()
  32. config.add_section('cache')
  33. config.set('cache', 'version', '1')
  34. config.set('cache', 'store_id', self.store.id.encode('hex'))
  35. config.set('cache', 'tid', '0')
  36. with open(os.path.join(self.path, 'config'), 'wb') as fd:
  37. config.write(fd)
  38. ChunkIndex.create(os.path.join(self.path, 'chunks'))
  39. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  40. pass # empty file
  41. def open(self):
  42. if not os.path.isdir(self.path):
  43. raise Exception('%s Does not look like a darc cache' % self.path)
  44. self.lock_fd = open(os.path.join(self.path, 'README'), 'r+')
  45. fcntl.flock(self.lock_fd, fcntl.LOCK_EX)
  46. self.rollback()
  47. self.config = RawConfigParser()
  48. self.config.read(os.path.join(self.path, 'config'))
  49. if self.config.getint('cache', 'version') != 1:
  50. raise Exception('%s Does not look like a darc cache')
  51. self.id = self.config.get('cache', 'store_id').decode('hex')
  52. self.tid = self.config.getint('cache', 'tid')
  53. self.chunks = ChunkIndex(os.path.join(self.path, 'chunks'))
  54. self.files = None
  55. def _read_files(self):
  56. self.files = {}
  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] < 8:
  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. msgpack.pack(item, fd)
  86. self.config.set('cache', 'tid', self.store.tid)
  87. with open(os.path.join(self.path, 'config'), 'w') as fd:
  88. self.config.write(fd)
  89. self.chunks.flush()
  90. os.rename(os.path.join(self.path, 'txn.active'),
  91. os.path.join(self.path, 'txn.tmp'))
  92. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  93. self.txn_active = False
  94. def rollback(self):
  95. """Roll back partial and aborted transactions
  96. """
  97. # Remove partial transaction
  98. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  99. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  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. shutil.rmtree(txn_dir)
  107. self.txn_active = False
  108. def sync(self):
  109. """Initializes cache by fetching and reading all archive indicies
  110. """
  111. def cb(chunk, error, id):
  112. assert not error
  113. data, items_hash = self.key.decrypt(chunk)
  114. assert self.key.id_hash(data) == id
  115. unpacker.feed(data)
  116. for item in unpacker:
  117. try:
  118. for id, size, csize in item['chunks']:
  119. try:
  120. count, size, csize = self.chunks[id]
  121. self.chunks[id] = count + 1, size, csize
  122. except KeyError:
  123. self.chunks[id] = 1, size, csize
  124. pass
  125. except KeyError:
  126. pass
  127. self.begin_txn()
  128. print 'Initializing cache...'
  129. self.chunks.clear()
  130. unpacker = msgpack.Unpacker()
  131. for id in self.store.list(NS_ARCHIVE_METADATA):
  132. data, hash = self.key.decrypt(self.store.get(NS_ARCHIVE_METADATA, id))
  133. archive = msgpack.unpackb(data)
  134. print 'Analyzing archive:', archive['name']
  135. for id, size, csize in archive['items']:
  136. try:
  137. count, size, csize = self.chunks[id]
  138. self.chunks[id] = count + 1, size, csize
  139. except KeyError:
  140. self.chunks[id] = 1, size, csize
  141. self.store.get(NS_CHUNK, id, callback=cb, callback_data=id)
  142. self.store.flush_rpc()
  143. def add_chunk(self, id, data, stats):
  144. if not self.txn_active:
  145. self.begin_txn()
  146. if self.seen_chunk(id):
  147. return self.chunk_incref(id, stats)
  148. size = len(data)
  149. data, hash = self.key.encrypt(data)
  150. csize = len(data)
  151. self.store.put(NS_CHUNK, id, data, callback=error_callback)
  152. self.chunks[id] = (1, size, csize)
  153. stats.update(size, csize, True)
  154. return id, size, csize
  155. def seen_chunk(self, id):
  156. return self.chunks.get(id, (0, 0, 0))[0]
  157. def chunk_incref(self, id, stats):
  158. if not self.txn_active:
  159. self.begin_txn()
  160. count, size, csize = self.chunks[id]
  161. self.chunks[id] = (count + 1, size, csize)
  162. stats.update(size, csize, False)
  163. return id, size, csize
  164. def chunk_decref(self, id):
  165. if not self.txn_active:
  166. self.begin_txn()
  167. count, size, csize = self.chunks[id]
  168. if count == 1:
  169. del self.chunks[id]
  170. self.store.delete(NS_CHUNK, id, callback=error_callback)
  171. else:
  172. self.chunks[id] = (count - 1, size, csize)
  173. def file_known_and_unchanged(self, path_hash, st):
  174. if self.files is None:
  175. self._read_files()
  176. entry = self.files.get(path_hash)
  177. if (entry and entry[3] == st.st_mtime
  178. and entry[2] == st.st_size and entry[1] == st.st_ino):
  179. # reset entry age
  180. self.files[path_hash] = (0,) + entry[1:]
  181. return entry[4]
  182. else:
  183. return None
  184. def memorize_file(self, path_hash, st, ids):
  185. # Entry: Age, inode, size, mtime, chunk ids
  186. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids