cache.py 9.1 KB

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