cache.py 11 KB

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