cache.py 7.9 KB

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