archive.py 11 KB

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