cache.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from __future__ import with_statement
  2. from ConfigParser import RawConfigParser
  3. import fcntl
  4. import msgpack
  5. import os
  6. import shutil
  7. from . import NS_ARCHIVE_CHUNKS, NS_CHUNK, PACKET_ARCHIVE_CHUNKS, PACKET_CHUNK
  8. from .hashindex import NSIndex
  9. class Cache(object):
  10. """Client Side cache
  11. """
  12. def __init__(self, store, keychain):
  13. self.txn_active = False
  14. self.store = store
  15. self.keychain = keychain
  16. self.path = os.path.join(Cache.cache_dir_path(), self.store.id.encode('hex'))
  17. if not os.path.exists(self.path):
  18. self.create()
  19. self.open()
  20. assert self.id == store.id
  21. if self.tid != store.tid:
  22. self.sync()
  23. @staticmethod
  24. def cache_dir_path():
  25. """Return path to directory used for storing users cache files"""
  26. return os.path.join(os.path.expanduser('~'), '.darc', 'cache')
  27. def create(self):
  28. """Create a new empty store at `path`
  29. """
  30. os.makedirs(self.path)
  31. with open(os.path.join(self.path, 'README'), 'wb') 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', 'store_id', self.store.id.encode('hex'))
  37. config.set('cache', 'tid', '0')
  38. with open(os.path.join(self.path, 'config'), 'wb') as fd:
  39. config.write(fd)
  40. NSIndex.create(os.path.join(self.path, 'chunks'))
  41. with open(os.path.join(self.path, 'files'), 'wb') 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', 'store_id').decode('hex')
  54. self.tid = self.config.getint('cache', 'tid')
  55. self.chunks = NSIndex(os.path.join(self.path, 'chunks'))
  56. self.files = None
  57. def _read_files(self):
  58. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  59. u = msgpack.Unpacker()
  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. if item[0] < 8:
  67. self.files[hash] = (item[0] + 1,) + item[1:]
  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.iteritems():
  86. msgpack.pack(item, fd)
  87. for id, (count, size) in self.chunks.iteritems():
  88. if count > 1000000:
  89. self.chunks[id] = count - 1000000, size
  90. self.config.set('cache', 'tid', self.store.tid)
  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. # Remove partial transaction
  102. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  103. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  104. # Roll back active transaction
  105. txn_dir = os.path.join(self.path, 'txn.active')
  106. if os.path.exists(txn_dir):
  107. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  108. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  109. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  110. shutil.rmtree(txn_dir)
  111. self.txn_active = False
  112. def sync(self):
  113. """Initializes cache by fetching and reading all archive indicies
  114. """
  115. self.begin_txn()
  116. print 'Initializing cache...'
  117. self.chunks.clear()
  118. for id in self.store.list(NS_ARCHIVE_CHUNKS):
  119. magic, data, hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_CHUNKS, id))
  120. assert magic == PACKET_ARCHIVE_CHUNKS
  121. chunks = msgpack.unpackb(data)
  122. for id, size in chunks:
  123. try:
  124. count, size = self.chunks[id]
  125. self.chunks[id] = count + 1, size
  126. except KeyError:
  127. self.chunks[id] = 1, size
  128. def add_chunk(self, id, data):
  129. if not self.txn_active:
  130. self.begin_txn()
  131. if self.seen_chunk(id):
  132. return self.chunk_incref(id)
  133. data, hash = self.keychain.encrypt(PACKET_CHUNK, data)
  134. csize = len(data)
  135. self.store.put(NS_CHUNK, id, data)
  136. self.chunks[id] = (1000001, csize)
  137. return id
  138. def seen_chunk(self, id):
  139. return self.chunks.get(id, (0, 0))[0]
  140. def chunk_incref(self, id):
  141. if not self.txn_active:
  142. self.begin_txn()
  143. count, size = self.chunks[id]
  144. if count < 1000000:
  145. self.chunks[id] = (count + 1000001, size)
  146. return id
  147. def chunk_decref(self, id):
  148. if not self.txn_active:
  149. self.begin_txn()
  150. count, size = self.chunks[id]
  151. if count == 1:
  152. del self.chunks[id]
  153. self.store.delete(NS_CHUNK, id)
  154. else:
  155. self.chunks[id] = (count - 1, size)
  156. def file_known_and_unchanged(self, path_hash, st):
  157. if self.files is None:
  158. self._read_files()
  159. entry = self.files.get(path_hash)
  160. if (entry and entry[3] == st.st_mtime
  161. and entry[2] == st.st_size and entry[1] == st.st_ino):
  162. # reset entry age
  163. self.files[path_hash] = (0,) + entry[1:]
  164. return entry[4], entry[2]
  165. else:
  166. return None, 0
  167. def memorize_file(self, path_hash, st, ids):
  168. # Entry: Age, inode, size, mtime, chunk ids
  169. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids