archive.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. from datetime import datetime
  2. import logging
  3. import msgpack
  4. import os
  5. import stat
  6. import sys
  7. from .cache import NS_ARCHIVES, NS_CHUNKS, NS_CINDEX
  8. from .chunkifier import chunkify
  9. from .helpers import uid2user, user2uid, gid2group, group2gid, IntegrityError
  10. CHUNK_SIZE = 55001
  11. class Archive(object):
  12. def __init__(self, store, crypto, name=None):
  13. self.crypto = crypto
  14. self.store = store
  15. self.items = []
  16. self.chunks = []
  17. self.chunk_idx = {}
  18. self.hard_links = {}
  19. if name:
  20. self.load(self.crypto.id_hash(name))
  21. def load(self, id):
  22. self.id = id
  23. archive = msgpack.unpackb(self.crypto.decrypt(self.store.get(NS_ARCHIVES, self.id)))
  24. if archive['version'] != 1:
  25. raise Exception('Archive version %r not supported' % archive['version'])
  26. self.items = archive['items']
  27. self.name = archive['name']
  28. cindex = msgpack.unpackb(self.crypto.decrypt(self.store.get(NS_CINDEX, self.id)))
  29. assert cindex['version'] == 1
  30. self.chunks = cindex['chunks']
  31. for i, chunk in enumerate(self.chunks):
  32. self.chunk_idx[i] = chunk[0]
  33. def save(self, name):
  34. self.id = self.crypto.id_hash(name)
  35. archive = {
  36. 'version': 1,
  37. 'name': name,
  38. 'cmdline': sys.argv,
  39. 'ts': datetime.utcnow().isoformat(),
  40. 'items': self.items,
  41. }
  42. data = self.crypto.encrypt_read(msgpack.packb(archive))
  43. self.store.put(NS_ARCHIVES, self.id, data)
  44. cindex = {
  45. 'version': 1,
  46. 'chunks': self.chunks,
  47. }
  48. data = self.crypto.encrypt_create(msgpack.packb(cindex))
  49. self.store.put(NS_CINDEX, self.id, data)
  50. self.store.commit()
  51. def add_chunk(self, id, size):
  52. try:
  53. return self.chunk_idx[id]
  54. except KeyError:
  55. idx = len(self.chunks)
  56. self.chunks.append((id, size))
  57. self.chunk_idx[id] = idx
  58. return idx
  59. def stats(self, cache):
  60. osize = csize = usize = 0
  61. for item in self.items:
  62. if item['type'] == 'FILE':
  63. osize += item['size']
  64. for id, size in self.chunks:
  65. csize += size
  66. if cache.seen_chunk(id) == 1:
  67. usize += size
  68. return osize, csize, usize
  69. def list(self):
  70. for item in self.items:
  71. print item['path']
  72. def extract(self, dest=None):
  73. dest = dest or os.getcwdu()
  74. dir_stat_queue = []
  75. for item in self.items:
  76. assert item['path'][0] not in ('/', '\\', ':')
  77. path = os.path.join(dest, item['path'].decode('utf-8'))
  78. if item['type'] == 'DIRECTORY':
  79. logging.info(path)
  80. if not os.path.exists(path):
  81. os.makedirs(path)
  82. dir_stat_queue.append((path, item))
  83. continue
  84. elif item['type'] == 'SYMLINK':
  85. if not os.path.exists(os.path.dirname(path)):
  86. os.makedirs(os.path.dirname(path))
  87. source = item['source']
  88. logging.info('%s -> %s', path, source)
  89. if os.path.exists(path):
  90. os.unlink(path)
  91. os.symlink(source, path)
  92. self.restore_stat(path, item, call_utime=False)
  93. elif item['type'] == 'HARDLINK':
  94. if not os.path.exists(os.path.dirname(path)):
  95. os.makedirs(os.path.dirname(path))
  96. source = os.path.join(dest, item['source'])
  97. logging.info('%s => %s', path, source)
  98. if os.path.exists(path):
  99. os.unlink(path)
  100. os.link(source, path)
  101. elif item['type'] == 'FILE':
  102. logging.info(path)
  103. if not os.path.exists(os.path.dirname(path)):
  104. os.makedirs(os.path.dirname(path))
  105. with open(path, 'wb') as fd:
  106. for chunk in item['chunks']:
  107. id = self.chunk_idx[chunk]
  108. try:
  109. fd.write(self.crypto.decrypt(self.store.get(NS_CHUNKS, id)))
  110. except ValueError:
  111. raise Exception('Invalid chunk checksum')
  112. self.restore_stat(path, item)
  113. else:
  114. raise Exception('Unknown archive item type %r' % item['type'])
  115. if dir_stat_queue and not path.startswith(dir_stat_queue[-1][0]):
  116. self.restore_stat(*dir_stat_queue.pop())
  117. def restore_stat(self, path, item, call_utime=True):
  118. os.lchmod(path, item['mode'])
  119. uid = user2uid(item['user']) or item['uid']
  120. gid = group2gid(item['group']) or item['gid']
  121. try:
  122. os.lchown(path, uid, gid)
  123. except OSError:
  124. pass
  125. if call_utime:
  126. # FIXME: We should really call futimes here (c extension required)
  127. os.utime(path, (item['ctime'], item['mtime']))
  128. def verify(self):
  129. for item in self.items:
  130. if item['type'] == 'FILE':
  131. item['path'] = item['path'].decode('utf-8')
  132. for chunk in item['chunks']:
  133. id = self.chunk_idx[chunk]
  134. try:
  135. self.crypto.decrypt(self.store.get(NS_CHUNKS, id))
  136. except IntegrityError:
  137. logging.error('%s ... ERROR', item['path'])
  138. break
  139. else:
  140. logging.info('%s ... OK', item['path'])
  141. def delete(self, cache):
  142. self.store.delete(NS_ARCHIVES, self.id)
  143. self.store.delete(NS_CINDEX, self.id)
  144. for id, size in self.chunks:
  145. cache.chunk_decref(id)
  146. self.store.commit()
  147. cache.save()
  148. def _walk(self, path):
  149. st = os.lstat(path)
  150. yield path, st
  151. if stat.S_ISDIR(st.st_mode):
  152. for f in os.listdir(path):
  153. for x in self._walk(os.path.join(path, f)):
  154. yield x
  155. def create(self, name, paths, cache):
  156. try:
  157. self.store.get(NS_ARCHIVES, name)
  158. except self.store.DoesNotExist:
  159. pass
  160. else:
  161. raise NameError('Archive already exists')
  162. for path in paths:
  163. for path, st in self._walk(unicode(path)):
  164. if stat.S_ISDIR(st.st_mode):
  165. self.process_dir(path, st)
  166. elif stat.S_ISLNK(st.st_mode):
  167. self.process_symlink(path, st)
  168. elif stat.S_ISREG(st.st_mode):
  169. self.process_file(path, st, cache)
  170. else:
  171. logging.error('Unknown file type: %s', path)
  172. self.save(name)
  173. cache.save()
  174. def process_dir(self, path, st):
  175. path = path.lstrip('/\\:')
  176. logging.info(path)
  177. self.items.append({
  178. 'type': 'DIRECTORY', 'path': path,
  179. 'mode': st.st_mode,
  180. 'uid': st.st_uid, 'user': uid2user(st.st_uid),
  181. 'gid': st.st_gid, 'group': gid2group(st.st_gid),
  182. 'ctime': st.st_ctime, 'mtime': st.st_mtime,
  183. })
  184. def process_symlink(self, path, st):
  185. source = os.readlink(path)
  186. path = path.lstrip('/\\:')
  187. logging.info('%s -> %s', path, source)
  188. self.items.append({
  189. 'type': 'SYMLINK', 'path': path, 'source': source,
  190. 'mode': st.st_mode,
  191. 'uid': st.st_uid, 'user': uid2user(st.st_uid),
  192. 'gid': st.st_gid, 'group': gid2group(st.st_gid),
  193. 'ctime': st.st_ctime, 'mtime': st.st_mtime,
  194. })
  195. def process_file(self, path, st, cache):
  196. safe_path = path.lstrip('/\\:')
  197. if st.st_nlink > 1:
  198. source = self.hard_links.get((st.st_ino, st.st_dev))
  199. if (st.st_ino, st.st_dev) in self.hard_links:
  200. logging.info('%s => %s', path, source)
  201. self.items.append({ 'type': 'HARDLINK',
  202. 'path': path, 'source': source})
  203. return
  204. else:
  205. self.hard_links[st.st_ino, st.st_dev] = safe_path
  206. try:
  207. fd = open(path, 'rb')
  208. except IOError, e:
  209. logging.error(e)
  210. return
  211. with fd:
  212. logging.info(safe_path)
  213. chunks = []
  214. size = 0
  215. for chunk in chunkify(fd, CHUNK_SIZE, 30):
  216. chunks.append(self.process_chunk(chunk, cache))
  217. size += len(chunk)
  218. self.items.append({
  219. 'type': 'FILE', 'path': safe_path, 'chunks': chunks, 'size': size,
  220. 'mode': st.st_mode,
  221. 'uid': st.st_uid, 'user': uid2user(st.st_uid),
  222. 'gid': st.st_gid, 'group': gid2group(st.st_gid),
  223. 'ctime': st.st_ctime, 'mtime': st.st_mtime,
  224. })
  225. def process_chunk(self, data, cache):
  226. id = self.crypto.id_hash(data)
  227. try:
  228. return self.chunk_idx[id]
  229. except KeyError:
  230. idx = len(self.chunks)
  231. size = cache.add_chunk(id, data, self.crypto)
  232. self.chunks.append((id, size))
  233. self.chunk_idx[id] = idx
  234. return idx
  235. @staticmethod
  236. def list_archives(store, crypto):
  237. for id in store.list(NS_ARCHIVES):
  238. archive = Archive(store, crypto)
  239. archive.load(id)
  240. yield archive