archive.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. from datetime import datetime
  2. from getpass import getuser
  3. import msgpack
  4. import os
  5. import socket
  6. import stat
  7. import sys
  8. from xattr import xattr, XATTR_NOFOLLOW
  9. from . import NS_ARCHIVE_METADATA, NS_ARCHIVE_ITEMS, NS_ARCHIVE_CHUNKS, NS_CHUNK, \
  10. PACKET_ARCHIVE_METADATA, PACKET_ARCHIVE_ITEMS, PACKET_ARCHIVE_CHUNKS, PACKET_CHUNK
  11. from ._speedups import chunkify
  12. from .helpers import uid2user, user2uid, gid2group, group2gid, IntegrityError
  13. CHUNK_SIZE = 64 * 1024
  14. WINDOW_SIZE = 4096
  15. have_lchmod = hasattr(os, 'lchmod')
  16. linux = sys.platform == 'linux2'
  17. class Archive(object):
  18. class DoesNotExist(Exception):
  19. pass
  20. def __init__(self, store, keychain, name=None):
  21. self.keychain = keychain
  22. self.store = store
  23. self.items = []
  24. self.items_ids = []
  25. self.hard_links = {}
  26. if name:
  27. self.load(self.keychain.id_hash(name))
  28. def load(self, id):
  29. self.id = id
  30. try:
  31. kind, data, self.hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_METADATA, self.id))
  32. except self.store.DoesNotExist:
  33. raise self.DoesNotExist
  34. assert kind == PACKET_ARCHIVE_METADATA
  35. self.metadata = msgpack.unpackb(data)
  36. assert self.metadata['version'] == 1
  37. def get_chunks(self):
  38. for id in self.metadata['chunks_ids']:
  39. magic, data, hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_CHUNKS, id))
  40. assert magic == PACKET_ARCHIVE_CHUNKS
  41. assert hash == id
  42. chunks = msgpack.unpackb(data)
  43. for chunk in chunks:
  44. yield chunk
  45. def get_items(self):
  46. for id in self.metadata['items_ids']:
  47. magic, data, items_hash = self.keychain.decrypt(self.store.get(NS_ARCHIVE_ITEMS, id))
  48. assert magic == PACKET_ARCHIVE_ITEMS
  49. assert items_hash == id
  50. items = msgpack.unpackb(data)
  51. for item in items:
  52. yield item
  53. def add_item(self, item):
  54. self.items.append(item)
  55. if len(self.items) > 100000:
  56. self.flush_items()
  57. def flush_items(self):
  58. data, hash = self.keychain.encrypt(PACKET_ARCHIVE_ITEMS, msgpack.packb(self.items))
  59. self.store.put(NS_ARCHIVE_ITEMS, hash, data)
  60. self.items_ids.append(hash)
  61. self.items = []
  62. def save_chunks(self, cache):
  63. chunks = []
  64. ids = []
  65. def flush(chunks):
  66. data, hash = self.keychain.encrypt(PACKET_ARCHIVE_CHUNKS, msgpack.packb(chunks))
  67. self.store.put(NS_ARCHIVE_CHUNKS, hash, data)
  68. ids.append(hash)
  69. for id, (count, size) in cache.chunks.iteritems():
  70. if count > 1000000:
  71. chunks.append((id, size))
  72. if len(chunks) > 100000:
  73. flush(chunks)
  74. chunks = []
  75. flush(chunks)
  76. return ids
  77. def save(self, name, cache):
  78. self.id = self.keychain.id_hash(name)
  79. chunks_ids = self.save_chunks(cache)
  80. self.flush_items()
  81. metadata = {
  82. 'version': 1,
  83. 'name': name,
  84. 'chunks_ids': chunks_ids,
  85. 'items_ids': self.items_ids,
  86. 'cmdline': sys.argv,
  87. 'hostname': socket.gethostname(),
  88. 'username': getuser(),
  89. 'time': datetime.utcnow().isoformat(),
  90. }
  91. data, self.hash = self.keychain.encrypt(PACKET_ARCHIVE_METADATA, msgpack.packb(metadata))
  92. self.store.put(NS_ARCHIVE_METADATA, self.id, data)
  93. self.store.commit()
  94. cache.commit()
  95. def stats(self, cache):
  96. osize = csize = usize = 0
  97. for item in self.get_items():
  98. if stat.S_ISREG(item['mode']) and not 'source' in item:
  99. osize += item['size']
  100. for id, size in self.get_chunks():
  101. csize += size
  102. if cache.seen_chunk(id) == 1:
  103. usize += size
  104. return osize, csize, usize
  105. def extract_item(self, item, dest=None):
  106. dest = dest or os.getcwdu()
  107. dir_stat_queue = []
  108. assert item['path'][0] not in ('/', '\\', ':')
  109. path = os.path.join(dest, item['path'].decode('utf-8'))
  110. mode = item['mode']
  111. if stat.S_ISDIR(mode):
  112. if not os.path.exists(path):
  113. os.makedirs(path)
  114. self.restore_attrs(path, item)
  115. elif stat.S_ISFIFO(mode):
  116. if not os.path.exists(os.path.dirname(path)):
  117. os.makedirs(os.path.dirname(path))
  118. os.mkfifo(path)
  119. self.restore_attrs(path, item)
  120. elif stat.S_ISLNK(mode):
  121. if not os.path.exists(os.path.dirname(path)):
  122. os.makedirs(os.path.dirname(path))
  123. source = item['source']
  124. if os.path.exists(path):
  125. os.unlink(path)
  126. os.symlink(source, path)
  127. self.restore_attrs(path, item, symlink=True)
  128. elif stat.S_ISREG(mode):
  129. if not os.path.exists(os.path.dirname(path)):
  130. os.makedirs(os.path.dirname(path))
  131. # Hard link?
  132. if 'source' in item:
  133. source = os.path.join(dest, item['source'])
  134. if os.path.exists(path):
  135. os.unlink(path)
  136. os.link(source, path)
  137. else:
  138. with open(path, 'wb') as fd:
  139. for id in item['chunks']:
  140. try:
  141. magic, data, hash = self.keychain.decrypt(self.store.get(NS_CHUNK, id))
  142. assert magic == PACKET_CHUNK
  143. if self.keychain.id_hash(data) != id:
  144. raise IntegrityError('chunk hash did not match')
  145. fd.write(data)
  146. except ValueError:
  147. raise Exception('Invalid chunk checksum')
  148. self.restore_attrs(path, item)
  149. else:
  150. raise Exception('Unknown archive item type %r' % item['mode'])
  151. def restore_attrs(self, path, item, symlink=False):
  152. xattrs = item.get('xattrs')
  153. if xattrs:
  154. xa = xattr(path, XATTR_NOFOLLOW)
  155. for k, v in xattrs.items():
  156. try:
  157. xa.set(k, v)
  158. except KeyError:
  159. pass
  160. if have_lchmod:
  161. os.lchmod(path, item['mode'])
  162. elif not symlink:
  163. os.chmod(path, item['mode'])
  164. uid = user2uid(item['user']) or item['uid']
  165. gid = group2gid(item['group']) or item['gid']
  166. try:
  167. os.lchown(path, uid, gid)
  168. except OSError:
  169. pass
  170. if not symlink:
  171. # FIXME: We should really call futimes here (c extension required)
  172. os.utime(path, (item['atime'], item['mtime']))
  173. def verify_file(self, item):
  174. for id in item['chunks']:
  175. try:
  176. magic, data, hash = self.keychain.decrypt(self.store.get(NS_CHUNK, id))
  177. assert magic == PACKET_CHUNK
  178. if self.keychain.id_hash(data) != id:
  179. raise IntegrityError('chunk id did not match')
  180. except IntegrityError:
  181. return False
  182. return True
  183. def delete(self, cache):
  184. for id, size in self.get_chunks():
  185. cache.chunk_decref(id)
  186. self.store.delete(NS_ARCHIVE_METADATA, self.id)
  187. for id in self.metadata['chunks_ids']:
  188. self.store.delete(NS_ARCHIVE_CHUNKS, id)
  189. for id in self.metadata['items_ids']:
  190. self.store.delete(NS_ARCHIVE_ITEMS, id)
  191. self.store.commit()
  192. cache.commit()
  193. def stat_attrs(self, st, path):
  194. item = {
  195. 'mode': st.st_mode,
  196. 'uid': st.st_uid, 'user': uid2user(st.st_uid),
  197. 'gid': st.st_gid, 'group': gid2group(st.st_gid),
  198. 'atime': st.st_atime, 'mtime': st.st_mtime,
  199. }
  200. try:
  201. xa = xattr(path, XATTR_NOFOLLOW)
  202. xattrs = {}
  203. for key in xa:
  204. # Only store the user namespace on Linux
  205. if linux and not key.startswith('user'):
  206. continue
  207. xattrs[key] = xa[key]
  208. if xattrs:
  209. item['xattrs'] = xattrs
  210. except IOError:
  211. pass
  212. return item
  213. def process_dir(self, path, st):
  214. item = {'path': path.lstrip('/\\:')}
  215. item.update(self.stat_attrs(st, path))
  216. self.add_item(item)
  217. def process_fifo(self, path, st):
  218. item = {'path': path.lstrip('/\\:')}
  219. item.update(self.stat_attrs(st, path))
  220. self.add_item(item)
  221. def process_symlink(self, path, st):
  222. source = os.readlink(path)
  223. item = {'path': path.lstrip('/\\:'), 'source': source}
  224. item.update(self.stat_attrs(st, path))
  225. self.add_item(item)
  226. def process_file(self, path, st, cache):
  227. safe_path = path.lstrip('/\\:')
  228. # Is it a hard link?
  229. if st.st_nlink > 1:
  230. source = self.hard_links.get((st.st_ino, st.st_dev))
  231. if (st.st_ino, st.st_dev) in self.hard_links:
  232. self.add_item({'mode': st.st_mode,
  233. 'path': path, 'source': source})
  234. return
  235. else:
  236. self.hard_links[st.st_ino, st.st_dev] = safe_path
  237. path_hash = self.keychain.id_hash(path.encode('utf-8'))
  238. ids, size = cache.file_known_and_unchanged(path_hash, st)
  239. if ids is not None:
  240. # Make sure all ids are available
  241. for id in ids:
  242. if not cache.seen_chunk(id):
  243. ids = None
  244. break
  245. else:
  246. for id in ids:
  247. cache.chunk_incref(id)
  248. # Only chunkify the file if needed
  249. if ids is None:
  250. with open(path, 'rb') as fd:
  251. size = 0
  252. ids = []
  253. for chunk in chunkify(fd, CHUNK_SIZE, WINDOW_SIZE,
  254. self.keychain.get_chunkify_seed()):
  255. ids.append(cache.add_chunk(self.keychain.id_hash(chunk), chunk))
  256. size += len(chunk)
  257. cache.memorize_file(path_hash, st, ids)
  258. item = {'path': safe_path, 'chunks': ids, 'size': size}
  259. item.update(self.stat_attrs(st, path))
  260. self.add_item(item)
  261. @staticmethod
  262. def list_archives(store, keychain):
  263. for id in list(store.list(NS_ARCHIVE_METADATA)):
  264. archive = Archive(store, keychain)
  265. archive.load(id)
  266. yield archive