cache.py 10 KB

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