cache.py 6.5 KB

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