cache.py 7.8 KB

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