archive.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. from __future__ import with_statement
  2. from datetime import datetime, timedelta
  3. from getpass import getuser
  4. import msgpack
  5. import os
  6. import socket
  7. import stat
  8. import sys
  9. from cStringIO import StringIO
  10. from xattr import xattr, XATTR_NOFOLLOW
  11. from . import NS_ARCHIVE_METADATA, NS_CHUNK
  12. from ._speedups import chunkify
  13. from .helpers import uid2user, user2uid, gid2group, group2gid, IntegrityError, \
  14. Counter, encode_filename, Statistics
  15. ITEMS_BUFFER = 1024 * 1024
  16. CHUNK_SIZE = 64 * 1024
  17. WINDOW_SIZE = 4096
  18. have_lchmod = hasattr(os, 'lchmod')
  19. linux = sys.platform == 'linux2'
  20. class Archive(object):
  21. class DoesNotExist(Exception):
  22. pass
  23. def __init__(self, store, key, name=None, cache=None):
  24. self.key = key
  25. self.store = store
  26. self.cache = cache
  27. self.items = StringIO()
  28. self.items_ids = []
  29. self.hard_links = {}
  30. self.stats = Statistics()
  31. if name:
  32. self.load(self.key.archive_hash(name))
  33. def load(self, id):
  34. self.id = id
  35. try:
  36. data, self.hash = self.key.decrypt(self.store.get(NS_ARCHIVE_METADATA, self.id))
  37. except self.store.DoesNotExist:
  38. raise self.DoesNotExist
  39. self.metadata = msgpack.unpackb(data)
  40. if self.metadata['version'] != 1:
  41. raise Exception('Unknown archive metadata version')
  42. self.name = self.metadata['name']
  43. @property
  44. def ts(self):
  45. """Timestamp of archive creation in UTC"""
  46. t, f = self.metadata['time'].split('.', 1)
  47. return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S') + timedelta(seconds=float('.' + f))
  48. def iter_items(self, callback):
  49. unpacker = msgpack.Unpacker()
  50. counter = Counter(0)
  51. def cb(chunk, error, id):
  52. if error:
  53. raise error
  54. assert not error
  55. counter.dec()
  56. data, items_hash = self.key.decrypt(chunk)
  57. assert self.key.id_hash(data) == id
  58. unpacker.feed(data)
  59. for item in unpacker:
  60. callback(item)
  61. for id, size, csize in self.metadata['items']:
  62. # Limit the number of concurrent items requests to 10
  63. self.store.flush_rpc(counter, 10)
  64. counter.inc()
  65. self.store.get(NS_CHUNK, id, callback=cb, callback_data=id)
  66. def add_item(self, item):
  67. self.items.write(msgpack.packb(item))
  68. if self.items.tell() > ITEMS_BUFFER:
  69. self.flush_items()
  70. def flush_items(self, flush=False):
  71. if self.items.tell() == 0:
  72. return
  73. self.items.seek(0)
  74. chunks = list(str(s) for s in chunkify(self.items, CHUNK_SIZE, WINDOW_SIZE, self.key.chunk_seed))
  75. self.items.seek(0)
  76. self.items.truncate()
  77. for chunk in chunks[:-1]:
  78. self.items_ids.append(self.cache.add_chunk(self.key.id_hash(chunk),
  79. chunk, self.stats))
  80. if flush or len(chunks) == 1:
  81. self.items_ids.append(self.cache.add_chunk(self.key.id_hash(chunks[-1]),
  82. chunks[-1], self.stats))
  83. else:
  84. self.items.write(chunks[-1])
  85. def save(self, name, cache):
  86. self.id = self.key.archive_hash(name)
  87. self.flush_items(flush=True)
  88. metadata = {
  89. 'version': 1,
  90. 'name': name,
  91. 'items': self.items_ids,
  92. 'cmdline': sys.argv,
  93. 'hostname': socket.gethostname(),
  94. 'username': getuser(),
  95. 'time': datetime.utcnow().isoformat(),
  96. }
  97. data, self.hash = self.key.encrypt(msgpack.packb(metadata))
  98. self.store.put(NS_ARCHIVE_METADATA, self.id, data)
  99. self.store.commit()
  100. cache.commit()
  101. def calc_stats(self, cache):
  102. # This function is a bit evil since it abuses the cache to calculate
  103. # the stats. The cache transaction must be rolled back afterwards
  104. def cb(chunk, error, id):
  105. assert not error
  106. data, items_hash = self.key.decrypt(chunk)
  107. assert self.key.id_hash(data) == id
  108. unpacker.feed(data)
  109. for item in unpacker:
  110. try:
  111. for id, size, csize in item['chunks']:
  112. count, _, _ = self.cache.chunks[id]
  113. stats.update(size, csize, count==1)
  114. stats.nfiles += 1
  115. self.cache.chunks[id] = count - 1, size, csize
  116. except KeyError:
  117. pass
  118. unpacker = msgpack.Unpacker()
  119. cache.begin_txn()
  120. stats = Statistics()
  121. for id, size, csize in self.metadata['items']:
  122. stats.update(size, csize, self.cache.seen_chunk(id) == 1)
  123. self.store.get(NS_CHUNK, id, callback=cb, callback_data=id)
  124. self.cache.chunk_decref(id)
  125. self.store.flush_rpc()
  126. cache.rollback()
  127. return stats
  128. def extract_item(self, item, dest=None, start_cb=None, restore_attrs=True):
  129. dest = dest or os.getcwdu()
  130. dir_stat_queue = []
  131. assert item['path'][0] not in ('/', '\\', ':')
  132. path = os.path.join(dest, encode_filename(item['path']))
  133. mode = item['mode']
  134. if stat.S_ISDIR(mode):
  135. if not os.path.exists(path):
  136. os.makedirs(path)
  137. if restore_attrs:
  138. self.restore_attrs(path, item)
  139. elif stat.S_ISFIFO(mode):
  140. if not os.path.exists(os.path.dirname(path)):
  141. os.makedirs(os.path.dirname(path))
  142. os.mkfifo(path)
  143. self.restore_attrs(path, item)
  144. elif stat.S_ISLNK(mode):
  145. if not os.path.exists(os.path.dirname(path)):
  146. os.makedirs(os.path.dirname(path))
  147. source = item['source']
  148. if os.path.exists(path):
  149. os.unlink(path)
  150. os.symlink(source, path)
  151. self.restore_attrs(path, item, symlink=True)
  152. elif stat.S_ISREG(mode):
  153. if not os.path.exists(os.path.dirname(path)):
  154. os.makedirs(os.path.dirname(path))
  155. # Hard link?
  156. if 'source' in item:
  157. source = os.path.join(dest, item['source'])
  158. if os.path.exists(path):
  159. os.unlink(path)
  160. os.link(source, path)
  161. else:
  162. def extract_cb(chunk, error, (id, i)):
  163. if i == 0:
  164. state['fd'] = open(path, 'wb')
  165. start_cb(item)
  166. assert not error
  167. data, hash = self.key.decrypt(chunk)
  168. if self.key.id_hash(data) != id:
  169. raise IntegrityError('chunk hash did not match')
  170. state['fd'].write(data)
  171. if i == n - 1:
  172. state['fd'].close()
  173. self.restore_attrs(path, item)
  174. state = {}
  175. n = len(item['chunks'])
  176. ## 0 chunks indicates an empty (0 bytes) file
  177. if n == 0:
  178. open(path, 'wb').close()
  179. start_cb(item)
  180. self.restore_attrs(path, item)
  181. else:
  182. for i, (id, size, csize) in enumerate(item['chunks']):
  183. self.store.get(NS_CHUNK, id, callback=extract_cb, callback_data=(id, i))
  184. else:
  185. raise Exception('Unknown archive item type %r' % item['mode'])
  186. def restore_attrs(self, path, item, symlink=False):
  187. xattrs = item.get('xattrs')
  188. if xattrs:
  189. xa = xattr(path, XATTR_NOFOLLOW)
  190. for k, v in xattrs.items():
  191. try:
  192. xa.set(k, v)
  193. except (IOError, KeyError):
  194. pass
  195. if have_lchmod:
  196. os.lchmod(path, item['mode'])
  197. elif not symlink:
  198. os.chmod(path, item['mode'])
  199. uid = user2uid(item['user']) or item['uid']
  200. gid = group2gid(item['group']) or item['gid']
  201. try:
  202. os.lchown(path, uid, gid)
  203. except OSError:
  204. pass
  205. if not symlink:
  206. # FIXME: We should really call futimes here (c extension required)
  207. os.utime(path, (item['mtime'], item['mtime']))
  208. def verify_file(self, item, start, result):
  209. def verify_chunk(chunk, error, (id, i)):
  210. if error:
  211. raise error
  212. if i == 0:
  213. start(item)
  214. data, hash = self.key.decrypt(chunk)
  215. if self.key.id_hash(data) != id:
  216. result(item, False)
  217. elif i == n - 1:
  218. result(item, True)
  219. n = len(item['chunks'])
  220. if n == 0:
  221. start(item)
  222. result(item, True)
  223. else:
  224. for i, (id, size, csize) in enumerate(item['chunks']):
  225. self.store.get(NS_CHUNK, id, callback=verify_chunk, callback_data=(id, i))
  226. def delete(self, cache):
  227. def callback(chunk, error, id):
  228. assert not error
  229. data, items_hash = self.key.decrypt(chunk)
  230. if self.key.id_hash(data) != id:
  231. raise IntegrityError('Chunk checksum mismatch')
  232. unpacker.feed(data)
  233. for item in unpacker:
  234. try:
  235. for chunk_id, size, csize in item['chunks']:
  236. self.cache.chunk_decref(chunk_id)
  237. except KeyError:
  238. pass
  239. self.cache.chunk_decref(id)
  240. unpacker = msgpack.Unpacker()
  241. for id, size, csize in self.metadata['items']:
  242. self.store.get(NS_CHUNK, id, callback=callback, callback_data=id)
  243. self.store.flush_rpc()
  244. self.store.delete(NS_ARCHIVE_METADATA, self.id)
  245. self.store.commit()
  246. cache.commit()
  247. def stat_attrs(self, st, path):
  248. item = {
  249. 'mode': st.st_mode,
  250. 'uid': st.st_uid, 'user': uid2user(st.st_uid),
  251. 'gid': st.st_gid, 'group': gid2group(st.st_gid),
  252. 'mtime': st.st_mtime,
  253. }
  254. try:
  255. xa = xattr(path, XATTR_NOFOLLOW)
  256. xattrs = {}
  257. for key in xa:
  258. # Only store the user namespace on Linux
  259. if linux and not key.startswith('user'):
  260. continue
  261. xattrs[key] = xa[key]
  262. if xattrs:
  263. item['xattrs'] = xattrs
  264. except IOError:
  265. pass
  266. return item
  267. def process_dir(self, path, st):
  268. item = {'path': path.lstrip('/\\:')}
  269. item.update(self.stat_attrs(st, path))
  270. self.add_item(item)
  271. def process_fifo(self, path, st):
  272. item = {'path': path.lstrip('/\\:')}
  273. item.update(self.stat_attrs(st, path))
  274. self.add_item(item)
  275. def process_symlink(self, path, st):
  276. source = os.readlink(path)
  277. item = {'path': path.lstrip('/\\:'), 'source': source}
  278. item.update(self.stat_attrs(st, path))
  279. self.add_item(item)
  280. def process_file(self, path, st, cache):
  281. safe_path = path.lstrip('/\\:')
  282. # Is it a hard link?
  283. if st.st_nlink > 1:
  284. source = self.hard_links.get((st.st_ino, st.st_dev))
  285. if (st.st_ino, st.st_dev) in self.hard_links:
  286. item = self.stat_attrs(st, path)
  287. item.update({'path': safe_path, 'source': source})
  288. self.add_item(item)
  289. return
  290. else:
  291. self.hard_links[st.st_ino, st.st_dev] = safe_path
  292. path_hash = self.key.id_hash(path)
  293. ids = cache.file_known_and_unchanged(path_hash, st)
  294. chunks = None
  295. if ids is not None:
  296. # Make sure all ids are available
  297. for id in ids:
  298. if not cache.seen_chunk(id):
  299. break
  300. else:
  301. chunks = [cache.chunk_incref(id, self.stats) for id in ids]
  302. # Only chunkify the file if needed
  303. if chunks is None:
  304. with open(path, 'rb') as fd:
  305. chunks = []
  306. for chunk in chunkify(fd, CHUNK_SIZE, WINDOW_SIZE,
  307. self.key.chunk_seed):
  308. chunks.append(cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats))
  309. ids = [id for id, _, _ in chunks]
  310. cache.memorize_file(path_hash, st, ids)
  311. item = {'path': safe_path, 'chunks': chunks}
  312. item.update(self.stat_attrs(st, path))
  313. self.stats.nfiles += 1
  314. self.add_item(item)
  315. @staticmethod
  316. def list_archives(store, key, cache=None):
  317. for id in list(store.list(NS_ARCHIVE_METADATA)):
  318. archive = Archive(store, key, cache=cache)
  319. archive.load(id)
  320. yield archive