cache.py 9.3 KB

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