cache.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 .helpers import error_callback
  9. from .hashindex import NSIndex
  10. class Cache(object):
  11. """Client Side cache
  12. """
  13. def __init__(self, store, keychain):
  14. self.txn_active = False
  15. self.store = store
  16. self.keychain = keychain
  17. self.path = os.path.join(Cache.cache_dir_path(), self.store.id.encode('hex'))
  18. if not os.path.exists(self.path):
  19. self.create()
  20. self.open()
  21. assert self.id == store.id
  22. if self.tid != store.tid:
  23. self.sync()
  24. @staticmethod
  25. def cache_dir_path():
  26. """Return path to directory used for storing users cache files"""
  27. return os.path.join(os.path.expanduser('~'), '.darc', 'cache')
  28. def create(self):
  29. """Create a new empty store at `path`
  30. """
  31. os.makedirs(self.path)
  32. with open(os.path.join(self.path, 'README'), 'wb') as fd:
  33. fd.write('This is a DARC cache')
  34. config = RawConfigParser()
  35. config.add_section('cache')
  36. config.set('cache', 'version', '1')
  37. config.set('cache', 'store_id', self.store.id.encode('hex'))
  38. config.set('cache', 'tid', '0')
  39. with open(os.path.join(self.path, 'config'), 'wb') as fd:
  40. config.write(fd)
  41. NSIndex.create(os.path.join(self.path, 'chunks'))
  42. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  43. pass # empty file
  44. def open(self):
  45. if not os.path.isdir(self.path):
  46. raise Exception('%s Does not look like a darc cache' % self.path)
  47. self.lock_fd = open(os.path.join(self.path, 'README'), 'r+')
  48. fcntl.flock(self.lock_fd, fcntl.LOCK_EX)
  49. self.rollback()
  50. self.config = RawConfigParser()
  51. self.config.read(os.path.join(self.path, 'config'))
  52. if self.config.getint('cache', 'version') != 1:
  53. raise Exception('%s Does not look like a darc cache')
  54. self.id = self.config.get('cache', 'store_id').decode('hex')
  55. self.tid = self.config.getint('cache', 'tid')
  56. self.chunks = NSIndex(os.path.join(self.path, 'chunks'))
  57. self.files = None
  58. def _read_files(self):
  59. self.files = {}
  60. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  61. u = msgpack.Unpacker()
  62. while True:
  63. data = fd.read(64 * 1024)
  64. if not data:
  65. break
  66. u.feed(data)
  67. for hash, item in u:
  68. if item[0] < 8:
  69. self.files[hash] = (item[0] + 1,) + item[1:]
  70. def begin_txn(self):
  71. # Initialize transaction snapshot
  72. txn_dir = os.path.join(self.path, 'txn.tmp')
  73. os.mkdir(txn_dir)
  74. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  75. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  76. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  77. os.rename(os.path.join(self.path, 'txn.tmp'),
  78. os.path.join(self.path, 'txn.active'))
  79. self.txn_active = True
  80. def commit(self):
  81. """Commit transaction
  82. """
  83. if not self.txn_active:
  84. return
  85. if self.files is not None:
  86. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  87. for item in self.files.iteritems():
  88. msgpack.pack(item, fd)
  89. for id, (count, size) in self.chunks.iteritems():
  90. if count > 1000000:
  91. self.chunks[id] = count - 1000000, size
  92. self.config.set('cache', 'tid', self.store.tid)
  93. with open(os.path.join(self.path, 'config'), 'w') as fd:
  94. self.config.write(fd)
  95. self.chunks.flush()
  96. os.rename(os.path.join(self.path, 'txn.active'),
  97. os.path.join(self.path, 'txn.tmp'))
  98. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  99. self.txn_active = False
  100. def rollback(self):
  101. """Roll back partial and aborted transactions
  102. """
  103. # Remove partial transaction
  104. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  105. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  106. # Roll back active transaction
  107. txn_dir = os.path.join(self.path, 'txn.active')
  108. if os.path.exists(txn_dir):
  109. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  110. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  111. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  112. shutil.rmtree(txn_dir)
  113. self.txn_active = False
  114. def sync(self):
  115. """Initializes cache by fetching and reading all archive indicies
  116. """
  117. self.begin_txn()
  118. print 'Initializing cache...'
  119. self.chunks.clear()
  120. for id in self.store.list(NS_ARCHIVE_CHUNKS):
  121. magic, data, hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_CHUNKS, id))
  122. assert magic == PACKET_ARCHIVE_CHUNKS
  123. chunks = msgpack.unpackb(data)
  124. for id, size in chunks:
  125. try:
  126. count, size = self.chunks[id]
  127. self.chunks[id] = count + 1, size
  128. except KeyError:
  129. self.chunks[id] = 1, size
  130. def add_chunk(self, id, data):
  131. if not self.txn_active:
  132. self.begin_txn()
  133. if self.seen_chunk(id):
  134. return self.chunk_incref(id)
  135. data, hash = self.keychain.encrypt(PACKET_CHUNK, data)
  136. csize = len(data)
  137. self.store.put(NS_CHUNK, id, data, callback=error_callback)
  138. self.chunks[id] = (1000001, csize)
  139. return id
  140. def seen_chunk(self, id):
  141. return self.chunks.get(id, (0, 0))[0]
  142. def chunk_incref(self, id):
  143. if not self.txn_active:
  144. self.begin_txn()
  145. count, size = self.chunks[id]
  146. if count < 1000000:
  147. self.chunks[id] = (count + 1000001, size)
  148. return id
  149. def chunk_decref(self, id):
  150. if not self.txn_active:
  151. self.begin_txn()
  152. count, size = self.chunks[id]
  153. if count == 1:
  154. del self.chunks[id]
  155. self.store.delete(NS_CHUNK, id, callback=error_callback)
  156. else:
  157. self.chunks[id] = (count - 1, size)
  158. def file_known_and_unchanged(self, path_hash, st):
  159. if self.files is None:
  160. self._read_files()
  161. entry = self.files.get(path_hash)
  162. if (entry and entry[3] == st.st_mtime
  163. and entry[2] == st.st_size and entry[1] == st.st_ino):
  164. # reset entry age
  165. self.files[path_hash] = (0,) + entry[1:]
  166. return entry[4], entry[2]
  167. else:
  168. return None, 0
  169. def memorize_file(self, path_hash, st, ids):
  170. # Entry: Age, inode, size, mtime, chunk ids
  171. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids