cache.py 6.6 KB

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