cache.py 6.7 KB

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