cache.py 9.0 KB

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