cache.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. from configparser import RawConfigParser
  2. import fcntl
  3. from itertools import zip_longest
  4. import msgpack
  5. import os
  6. from binascii import hexlify
  7. import shutil
  8. from .helpers import get_cache_dir, decode_dict, st_mtime_ns, unhexlify
  9. from .hashindex import ChunkIndex
  10. class Cache(object):
  11. """Client Side cache
  12. """
  13. class RepositoryReplay(Exception):
  14. """
  15. """
  16. def __init__(self, repository, key, manifest):
  17. self.timestamp = None
  18. self.txn_active = False
  19. self.repository = repository
  20. self.key = key
  21. self.manifest = manifest
  22. self.path = 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 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_fd = open(os.path.join(self.path, 'README'), 'r+')
  54. fcntl.flock(self.lock_fd, fcntl.LOCK_EX)
  55. self.rollback()
  56. self.config = RawConfigParser()
  57. self.config.read(os.path.join(self.path, 'config'))
  58. if self.config.getint('cache', 'version') != 1:
  59. raise Exception('%s Does not look like an Attic cache')
  60. self.id = self.config.get('cache', 'repository')
  61. self.manifest_id = unhexlify(self.config.get('cache', 'manifest'))
  62. self.timestamp = self.config.get('cache', 'timestamp', fallback=None)
  63. self.chunks = ChunkIndex(os.path.join(self.path, 'chunks').encode('utf-8'))
  64. self.files = None
  65. def close(self):
  66. self.lock_fd.close()
  67. def _read_files(self):
  68. self.files = {}
  69. self._newest_mtime = 0
  70. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  71. u = msgpack.Unpacker(use_list=True)
  72. while True:
  73. data = fd.read(64 * 1024)
  74. if not data:
  75. break
  76. u.feed(data)
  77. for hash, item in u:
  78. item[0] += 1
  79. self.files[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. # Roll back active transaction
  115. txn_dir = os.path.join(self.path, 'txn.active')
  116. if os.path.exists(txn_dir):
  117. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  118. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  119. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  120. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  121. # Remove partial transaction
  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. for name, info in self.manifest.archives.items():
  139. id = info[b'id']
  140. cdata = self.repository.get(id)
  141. data = self.key.decrypt(id, cdata)
  142. add(id, len(data), len(cdata))
  143. archive = msgpack.unpackb(data)
  144. decode_dict(archive, (b'name', b'hostname', b'username', b'time')) # fixme: argv
  145. print('Analyzing archive:', archive[b'name'])
  146. for id, chunk in zip_longest(archive[b'items'], self.repository.get_many(archive[b'items'])):
  147. data = self.key.decrypt(id, chunk)
  148. add(id, len(data), len(chunk))
  149. unpacker.feed(data)
  150. for item in unpacker:
  151. try:
  152. for id, size, csize in item[b'chunks']:
  153. add(id, size, csize)
  154. except KeyError:
  155. pass
  156. def add_chunk(self, id, data, stats):
  157. if not self.txn_active:
  158. self.begin_txn()
  159. if self.seen_chunk(id):
  160. return self.chunk_incref(id, stats)
  161. size = len(data)
  162. data = self.key.encrypt(data)
  163. csize = len(data)
  164. self.repository.put(id, data, wait=False)
  165. self.chunks[id] = (1, size, csize)
  166. stats.update(size, csize, True)
  167. return id, size, csize
  168. def seen_chunk(self, id):
  169. return self.chunks.get(id, (0, 0, 0))[0]
  170. def chunk_incref(self, id, stats):
  171. if not self.txn_active:
  172. self.begin_txn()
  173. count, size, csize = self.chunks[id]
  174. self.chunks[id] = (count + 1, size, csize)
  175. stats.update(size, csize, False)
  176. return id, size, csize
  177. def chunk_decref(self, id):
  178. if not self.txn_active:
  179. self.begin_txn()
  180. count, size, csize = self.chunks[id]
  181. if count == 1:
  182. del self.chunks[id]
  183. self.repository.delete(id, wait=False)
  184. else:
  185. self.chunks[id] = (count - 1, size, csize)
  186. def file_known_and_unchanged(self, path_hash, st):
  187. if self.files is None:
  188. self._read_files()
  189. entry = self.files.get(path_hash)
  190. if (entry and entry[3] == st_mtime_ns(st)
  191. and entry[2] == st.st_size and entry[1] == st.st_ino):
  192. # reset entry age
  193. self.files[path_hash][0] = 0
  194. return entry[4]
  195. else:
  196. return None
  197. def memorize_file(self, path_hash, st, ids):
  198. # Entry: Age, inode, size, mtime, chunk ids
  199. mtime_ns = st_mtime_ns(st)
  200. self.files[path_hash] = 0, st.st_ino, st.st_size, mtime_ns, ids
  201. self._newest_mtime = max(self._newest_mtime, mtime_ns)