archive.py 13 KB

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