cache.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.create(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(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 item in self.files.items():
  96. # Discard cached files with the newest mtime to avoid
  97. # issues with filesystem snapshots and mtime precision
  98. if item[1][0] < 10 and item[1][3] < self._newest_mtime:
  99. msgpack.pack(item, fd)
  100. self.config.set('cache', 'manifest', hexlify(self.manifest.id).decode('ascii'))
  101. self.config.set('cache', 'timestamp', self.manifest.timestamp)
  102. with open(os.path.join(self.path, 'config'), 'w') as fd:
  103. self.config.write(fd)
  104. self.chunks.flush()
  105. os.rename(os.path.join(self.path, 'txn.active'),
  106. os.path.join(self.path, 'txn.tmp'))
  107. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  108. self.txn_active = False
  109. def rollback(self):
  110. """Roll back partial and aborted transactions
  111. """
  112. # Remove partial transaction
  113. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  114. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  115. # Roll back active transaction
  116. txn_dir = os.path.join(self.path, 'txn.active')
  117. if os.path.exists(txn_dir):
  118. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  119. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  120. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  121. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  122. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  123. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  124. self.txn_active = False
  125. def sync(self):
  126. """Initializes cache by fetching and reading all archive indicies
  127. """
  128. def add(id, size, csize):
  129. try:
  130. count, size, csize = self.chunks[id]
  131. self.chunks[id] = count + 1, size, csize
  132. except KeyError:
  133. self.chunks[id] = 1, size, csize
  134. self.begin_txn()
  135. print('Initializing cache...')
  136. self.chunks.clear()
  137. unpacker = msgpack.Unpacker()
  138. repository = cache_if_remote(self.repository)
  139. for name, info in self.manifest.archives.items():
  140. archive_id = info[b'id']
  141. cdata = repository.get(archive_id)
  142. data = self.key.decrypt(archive_id, cdata)
  143. add(archive_id, len(data), len(cdata))
  144. archive = msgpack.unpackb(data)
  145. if archive[b'version'] != 1:
  146. raise Exception('Unknown archive metadata version')
  147. decode_dict(archive, (b'name',))
  148. print('Analyzing archive:', archive[b'name'])
  149. for key, chunk in zip(archive[b'items'], repository.get_many(archive[b'items'])):
  150. data = self.key.decrypt(key, chunk)
  151. add(key, len(data), len(chunk))
  152. unpacker.feed(data)
  153. for item in unpacker:
  154. if b'chunks' in item:
  155. for chunk_id, size, csize in item[b'chunks']:
  156. add(chunk_id, size, csize)
  157. def add_chunk(self, id, data, stats):
  158. if not self.txn_active:
  159. self.begin_txn()
  160. if self.seen_chunk(id):
  161. return self.chunk_incref(id, stats)
  162. size = len(data)
  163. data = self.key.encrypt(data)
  164. csize = len(data)
  165. self.repository.put(id, data, wait=False)
  166. self.chunks[id] = (1, size, csize)
  167. stats.update(size, csize, True)
  168. return id, size, csize
  169. def seen_chunk(self, id):
  170. return self.chunks.get(id, (0, 0, 0))[0]
  171. def chunk_incref(self, id, stats):
  172. if not self.txn_active:
  173. self.begin_txn()
  174. count, size, csize = self.chunks[id]
  175. self.chunks[id] = (count + 1, size, csize)
  176. stats.update(size, csize, False)
  177. return id, size, csize
  178. def chunk_decref(self, id, stats):
  179. if not self.txn_active:
  180. self.begin_txn()
  181. count, size, csize = self.chunks[id]
  182. if count == 1:
  183. del self.chunks[id]
  184. self.repository.delete(id, wait=False)
  185. stats.update(-size, -csize, True)
  186. else:
  187. self.chunks[id] = (count - 1, size, csize)
  188. stats.update(-size, -csize, False)
  189. def file_known_and_unchanged(self, path_hash, st):
  190. if self.files is None:
  191. self._read_files()
  192. entry = self.files.get(path_hash)
  193. if not entry:
  194. return None
  195. entry = msgpack.unpackb(entry)
  196. if entry[2] == st.st_size and bigint_to_int(entry[3]) == st_mtime_ns(st) and entry[1] == st.st_ino:
  197. # reset entry age
  198. entry[0] = 0
  199. self.files[path_hash] = msgpack.packb(entry)
  200. return entry[4]
  201. else:
  202. return None
  203. def memorize_file(self, path_hash, st, ids):
  204. # Entry: Age, inode, size, mtime, chunk ids
  205. mtime_ns = st_mtime_ns(st)
  206. self.files[path_hash] = msgpack.packb((0, st.st_ino, st.st_size, int_to_bigint(mtime_ns), ids))
  207. self._newest_mtime = max(self._newest_mtime, mtime_ns)