archive.py 11 KB

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