archive.py 10 KB

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