cache.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 = {}
  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. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  84. for item in self.files.iteritems():
  85. msgpack.pack(item, fd)
  86. for id, (count, size) in self.chunks.iteritems():
  87. if count > 1000000:
  88. self.chunks[id] = count - 1000000, size
  89. self.config.set('cache', 'tid', self.store.tid)
  90. with open(os.path.join(self.path, 'config'), 'w') as fd:
  91. self.config.write(fd)
  92. self.chunks.flush()
  93. os.rename(os.path.join(self.path, 'txn.active'),
  94. os.path.join(self.path, 'txn.tmp'))
  95. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  96. self.txn_active = False
  97. def rollback(self):
  98. """Roll back partial and aborted transactions
  99. """
  100. # Remove partial transaction
  101. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  102. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  103. # Roll back active transaction
  104. txn_dir = os.path.join(self.path, 'txn.active')
  105. if os.path.exists(txn_dir):
  106. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  107. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  108. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  109. shutil.rmtree(txn_dir)
  110. self.txn_active = False
  111. def sync(self):
  112. """Initializes cache by fetching and reading all archive indicies
  113. """
  114. self.begin_txn()
  115. print 'Initializing cache...'
  116. self.chunks.clear()
  117. for id in self.store.list(NS_ARCHIVE_CHUNKS):
  118. magic, data, hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_CHUNKS, id))
  119. assert magic == PACKET_ARCHIVE_CHUNKS
  120. chunks = msgpack.unpackb(data)
  121. for id, size in chunks:
  122. try:
  123. count, size = self.chunks[id]
  124. self.chunks[id] = count + 1, size
  125. except KeyError:
  126. self.chunks[id] = 1, size
  127. def add_chunk(self, id, data):
  128. if not self.txn_active:
  129. self.begin_txn()
  130. if self.seen_chunk(id):
  131. return self.chunk_incref(id)
  132. data, hash = self.keychain.encrypt(PACKET_CHUNK, data)
  133. csize = len(data)
  134. self.store.put(NS_CHUNK, id, data)
  135. self.chunks[id] = (1000001, csize)
  136. return id
  137. def seen_chunk(self, id):
  138. return self.chunks.get(id, (0, 0))[0]
  139. def chunk_incref(self, id):
  140. if not self.txn_active:
  141. self.begin_txn()
  142. count, size = self.chunks[id]
  143. if count < 1000000:
  144. self.chunks[id] = (count + 1000001, size)
  145. return id
  146. def chunk_decref(self, id):
  147. if not self.txn_active:
  148. self.begin_txn()
  149. count, size = self.chunks[id]
  150. if count == 1:
  151. del self.chunks[id]
  152. self.store.delete(NS_CHUNK, id)
  153. else:
  154. self.chunks[id] = (count - 1, size)
  155. def file_known_and_unchanged(self, path_hash, st):
  156. if not self.files:
  157. self._read_files()
  158. entry = self.files.get(path_hash)
  159. if (entry and entry[3] == st.st_mtime
  160. and entry[2] == st.st_size and entry[1] == st.st_ino):
  161. # reset entry age
  162. self.files[path_hash] = (0,) + entry[1:]
  163. return entry[4], entry[2]
  164. else:
  165. return None, 0
  166. def memorize_file(self, path_hash, st, ids):
  167. # Entry: Age, inode, size, mtime, chunk ids
  168. self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids