archive.py 10 KB

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