cache.py 12 KB

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