cache.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. from __future__ import with_statement
  2. from ConfigParser import RawConfigParser
  3. import fcntl
  4. from itertools import izip_longest
  5. import msgpack
  6. import os
  7. import shutil
  8. from .helpers import get_cache_dir
  9. from .hashindex import ChunkIndex
  10. class Cache(object):
  11. """Client Side cache
  12. """
  13. def __init__(self, store, key, manifest):
  14. self.txn_active = False
  15. self.store = store
  16. self.key = key
  17. self.manifest = manifest
  18. self.path = os.path.join(get_cache_dir(), store.id.encode('hex'))
  19. if not os.path.exists(self.path):
  20. self.create()
  21. self.open()
  22. if self.manifest.id != self.manifest_id:
  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', self.store.id.encode('hex'))
  35. config.set('cache', 'manifest', '')
  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')
  52. self.manifest_id = self.config.get('cache', 'manifest').decode('hex')
  53. self.chunks = ChunkIndex(os.path.join(self.path, 'chunks'))
  54. self.files = None
  55. def _read_files(self):
  56. self.files = {}
  57. self._newest_mtime = 0
  58. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  59. u = msgpack.Unpacker()
  60. while True:
  61. data = fd.read(64 * 1024)
  62. if not data:
  63. break
  64. u.feed(data)
  65. for hash, item in u:
  66. if item[0] < 10:
  67. self.files[hash] = (item[0] + 1,) + item[1:]
  68. def begin_txn(self):
  69. # Initialize transaction snapshot
  70. txn_dir = os.path.join(self.path, 'txn.tmp')
  71. os.mkdir(txn_dir)
  72. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  73. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  74. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  75. os.rename(os.path.join(self.path, 'txn.tmp'),
  76. os.path.join(self.path, 'txn.active'))
  77. self.txn_active = True
  78. def commit(self):
  79. """Commit transaction
  80. """
  81. if not self.txn_active:
  82. return
  83. if self.files is not None:
  84. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  85. for item in self.files.iteritems():
  86. # Discard cached files with the newest mtime to avoid
  87. # issues with filesystem snapshots and mtime precision
  88. if item[1][3] < self._newest_mtime:
  89. msgpack.pack(item, fd)
  90. self.config.set('cache', 'manifest', self.manifest.id.encode('hex'))
  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. # Roll back active transaction
  102. txn_dir = os.path.join(self.path, 'txn.active')
  103. if os.path.exists(txn_dir):
  104. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  105. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  106. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  107. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  108. # Remove partial transaction
  109. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  110. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  111. self.txn_active = False
  112. def sync(self):
  113. """Initializes cache by fetching and reading all archive indicies
  114. """
  115. def add(id, size, csize):
  116. try:
  117. count, size, csize = self.chunks[id]
  118. self.chunks[id] = count + 1, size, csize
  119. except KeyError:
  120. self.chunks[id] = 1, size, csize
  121. self.begin_txn()
  122. print 'Initializing cache...'
  123. self.chunks.clear()
  124. unpacker = msgpack.Unpacker()
  125. for name, info in self.manifest.archives.items():
  126. id = info['id']
  127. cdata = self.store.get(id)
  128. data = self.key.decrypt(id, cdata)
  129. add(id, len(data), len(cdata))
  130. archive = msgpack.unpackb(data)
  131. print 'Analyzing archive:', archive['name']
  132. for id, chunk in izip_longest(archive['items'], self.store.get_many(archive['items'])):
  133. data = self.key.decrypt(id, chunk)
  134. add(id, len(data), len(chunk))
  135. unpacker.feed(data)
  136. for item in unpacker:
  137. try:
  138. for id, size, csize in item['chunks']:
  139. add(id, size, csize)
  140. except KeyError:
  141. pass
  142. def add_chunk(self, id, data, stats):
  143. if not self.txn_active:
  144. self.begin_txn()
  145. if self.seen_chunk(id):
  146. return self.chunk_incref(id, stats)
  147. size = len(data)
  148. data = self.key.encrypt(data)
  149. csize = len(data)
  150. self.store.put(id, data, wait=False)
  151. self.chunks[id] = (1, size, csize)
  152. stats.update(size, csize, True)
  153. return id, size, csize
  154. def seen_chunk(self, id):
  155. return self.chunks.get(id, (0, 0, 0))[0]
  156. def chunk_incref(self, id, stats):
  157. if not self.txn_active:
  158. self.begin_txn()
  159. count, size, csize = self.chunks[id]
  160. self.chunks[id] = (count + 1, size, csize)
  161. stats.update(size, csize, False)
  162. return id, size, csize
  163. def chunk_decref(self, id):
  164. if not self.txn_active:
  165. self.begin_txn()
  166. count, size, csize = self.chunks[id]
  167. if count == 1:
  168. del self.chunks[id]
  169. self.store.delete(id, wait=False)
  170. else:
  171. self.chunks[id] = (count - 1, size, csize)
  172. def file_known_and_unchanged(self, path_hash, st):
  173. if self.files is None:
  174. self._read_files()
  175. entry = self.files.get(path_hash)
  176. if (entry and entry[3] == st.st_mtime
  177. and entry[2] == st.st_size and entry[1] == st.st_ino):
  178. # reset entry age
  179. self.files[path_hash] = (0,) + entry[1:]
  180. return entry[4]
  181. else:
  182. return None
  183. def memorize_file(self, path_hash, st, ids):
  184. # Entry: Age, inode, size, mtime, chunk ids
  185. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids
  186. self._newest_mtime = max(self._newest_mtime, st.st_mtime)