cache.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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(key_size=self.repository.key_size).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. key_size=self.repository.key_size)
  65. self.files = None
  66. def close(self):
  67. if self.lock:
  68. self.lock.release()
  69. self.lock = None
  70. def _read_files(self):
  71. self.files = {}
  72. self._newest_mtime = 0
  73. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  74. u = msgpack.Unpacker(use_list=True)
  75. while True:
  76. data = fd.read(64 * 1024)
  77. if not data:
  78. break
  79. u.feed(data)
  80. for path_hash, item in u:
  81. item[0] += 1
  82. # in the end, this takes about 240 Bytes per file
  83. self.files[path_hash] = msgpack.packb(item)
  84. def begin_txn(self):
  85. # Initialize transaction snapshot
  86. txn_dir = os.path.join(self.path, 'txn.tmp')
  87. os.mkdir(txn_dir)
  88. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  89. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  90. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  91. os.rename(os.path.join(self.path, 'txn.tmp'),
  92. os.path.join(self.path, 'txn.active'))
  93. self.txn_active = True
  94. def commit(self):
  95. """Commit transaction
  96. """
  97. if not self.txn_active:
  98. return
  99. if self.files is not None:
  100. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  101. for path_hash, item in self.files.items():
  102. # Discard cached files with the newest mtime to avoid
  103. # issues with filesystem snapshots and mtime precision
  104. item = msgpack.unpackb(item)
  105. if item[0] < 10 and bigint_to_int(item[3]) < self._newest_mtime:
  106. msgpack.pack((path_hash, item), fd)
  107. self.config.set('cache', 'manifest', hexlify(self.manifest.id).decode('ascii'))
  108. self.config.set('cache', 'timestamp', self.manifest.timestamp)
  109. with open(os.path.join(self.path, 'config'), 'w') as fd:
  110. self.config.write(fd)
  111. self.chunks.write(os.path.join(self.path, 'chunks').encode('utf-8'))
  112. os.rename(os.path.join(self.path, 'txn.active'),
  113. os.path.join(self.path, 'txn.tmp'))
  114. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  115. self.txn_active = False
  116. def rollback(self):
  117. """Roll back partial and aborted transactions
  118. """
  119. # Remove partial transaction
  120. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  121. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  122. # Roll back active transaction
  123. txn_dir = os.path.join(self.path, 'txn.active')
  124. if os.path.exists(txn_dir):
  125. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  126. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  127. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  128. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  129. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  130. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  131. self.txn_active = False
  132. def sync(self):
  133. """Initializes cache by fetching and reading all archive indicies
  134. """
  135. def add(id, size, csize):
  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.begin_txn()
  142. print('Initializing cache...')
  143. self.chunks.clear()
  144. unpacker = msgpack.Unpacker()
  145. repository = cache_if_remote(self.repository)
  146. for name, info in self.manifest.archives.items():
  147. archive_id = info[b'id']
  148. cdata = repository.get(archive_id)
  149. data = self.key.decrypt(archive_id, cdata)
  150. add(archive_id, len(data), len(cdata))
  151. archive = msgpack.unpackb(data)
  152. if archive[b'version'] != 1:
  153. raise Exception('Unknown archive metadata version')
  154. decode_dict(archive, (b'name',))
  155. print('Analyzing archive:', archive[b'name'])
  156. for key, chunk in zip(archive[b'items'], repository.get_many(archive[b'items'])):
  157. data = self.key.decrypt(key, chunk)
  158. add(key, len(data), len(chunk))
  159. unpacker.feed(data)
  160. for item in unpacker:
  161. if b'chunks' in item:
  162. for chunk_id, size, csize in item[b'chunks']:
  163. add(chunk_id, size, csize)
  164. def add_chunk(self, id, data, stats):
  165. if not self.txn_active:
  166. self.begin_txn()
  167. if self.seen_chunk(id):
  168. return self.chunk_incref(id, stats)
  169. size = len(data)
  170. data = self.key.encrypt(data)
  171. csize = len(data)
  172. self.repository.put(id, data, wait=False)
  173. self.chunks[id] = (1, size, csize)
  174. stats.update(size, csize, True)
  175. return id, size, csize
  176. def seen_chunk(self, id):
  177. return self.chunks.get(id, (0, 0, 0))[0]
  178. def chunk_incref(self, id, stats):
  179. if not self.txn_active:
  180. self.begin_txn()
  181. count, size, csize = self.chunks[id]
  182. self.chunks[id] = (count + 1, size, csize)
  183. stats.update(size, csize, False)
  184. return id, size, csize
  185. def chunk_decref(self, id, stats):
  186. if not self.txn_active:
  187. self.begin_txn()
  188. count, size, csize = self.chunks[id]
  189. if count == 1:
  190. del self.chunks[id]
  191. self.repository.delete(id, wait=False)
  192. stats.update(-size, -csize, True)
  193. else:
  194. self.chunks[id] = (count - 1, size, csize)
  195. stats.update(-size, -csize, False)
  196. def file_known_and_unchanged(self, path_hash, st):
  197. if not self.do_files:
  198. return None
  199. if self.files is None:
  200. self._read_files()
  201. entry = self.files.get(path_hash)
  202. if not entry:
  203. return None
  204. entry = msgpack.unpackb(entry)
  205. if entry[2] == st.st_size and bigint_to_int(entry[3]) == st_mtime_ns(st) and entry[1] == st.st_ino:
  206. # reset entry age
  207. entry[0] = 0
  208. self.files[path_hash] = msgpack.packb(entry)
  209. return entry[4]
  210. else:
  211. return None
  212. def memorize_file(self, path_hash, st, ids):
  213. if not self.do_files:
  214. return
  215. # Entry: Age, inode, size, mtime, chunk ids
  216. mtime_ns = st_mtime_ns(st)
  217. self.files[path_hash] = msgpack.packb((0, st.st_ino, st.st_size, int_to_bigint(mtime_ns), ids))
  218. self._newest_mtime = max(self._newest_mtime, mtime_ns)