archive.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. from datetime import datetime, timedelta, timezone
  2. from getpass import getuser
  3. from itertools import groupby
  4. import errno
  5. import shutil
  6. import tempfile
  7. from attic.key import key_factory
  8. from attic.remote import cache_if_remote
  9. import msgpack
  10. import os
  11. import socket
  12. import stat
  13. import sys
  14. import time
  15. from io import BytesIO
  16. from attic import xattr
  17. from attic.platform import acl_get, acl_set
  18. from attic.chunker import Chunker
  19. from attic.hashindex import ChunkIndex
  20. from attic.helpers import Error, uid2user, user2uid, gid2group, group2gid, \
  21. Manifest, Statistics, decode_dict, st_mtime_ns, make_path_safe, StableDict, int_to_bigint, bigint_to_int
  22. ITEMS_BUFFER = 1024 * 1024
  23. CHUNK_MIN = 1024
  24. CHUNK_MAX = 10 * 1024 * 1024
  25. WINDOW_SIZE = 0xfff
  26. CHUNK_MASK = 0xffff
  27. ZEROS = b'\0' * CHUNK_MAX
  28. utime_supports_fd = os.utime in getattr(os, 'supports_fd', {})
  29. utime_supports_follow_symlinks = os.utime in getattr(os, 'supports_follow_symlinks', {})
  30. has_mtime_ns = sys.version >= '3.3'
  31. has_lchmod = hasattr(os, 'lchmod')
  32. has_lchflags = hasattr(os, 'lchflags')
  33. # Python <= 3.2 raises OSError instead of PermissionError (See #164)
  34. try:
  35. PermissionError = PermissionError
  36. except NameError:
  37. PermissionError = OSError
  38. class DownloadPipeline:
  39. def __init__(self, repository, key):
  40. self.repository = repository
  41. self.key = key
  42. def unpack_many(self, ids, filter=None, preload=False):
  43. unpacker = msgpack.Unpacker(use_list=False)
  44. for data in self.fetch_many(ids):
  45. unpacker.feed(data)
  46. items = [decode_dict(item, (b'path', b'source', b'user', b'group')) for item in unpacker]
  47. if filter:
  48. items = [item for item in items if filter(item)]
  49. if preload:
  50. for item in items:
  51. if b'chunks' in item:
  52. self.repository.preload([c[0] for c in item[b'chunks']])
  53. for item in items:
  54. yield item
  55. def fetch_many(self, ids, is_preloaded=False):
  56. for id_, data in zip(ids, self.repository.get_many(ids, is_preloaded=is_preloaded)):
  57. yield self.key.decrypt(id_, data)
  58. class ChunkBuffer:
  59. BUFFER_SIZE = 1 * 1024 * 1024
  60. def __init__(self, key):
  61. self.buffer = BytesIO()
  62. self.packer = msgpack.Packer(unicode_errors='surrogateescape')
  63. self.chunks = []
  64. self.key = key
  65. self.chunker = Chunker(WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, CHUNK_MAX,self.key.chunk_seed)
  66. def add(self, item):
  67. self.buffer.write(self.packer.pack(StableDict(item)))
  68. if self.is_full():
  69. self.flush()
  70. def write_chunk(self, chunk):
  71. raise NotImplementedError
  72. def flush(self, flush=False):
  73. if self.buffer.tell() == 0:
  74. return
  75. self.buffer.seek(0)
  76. chunks = list(bytes(s) for s in self.chunker.chunkify(self.buffer))
  77. self.buffer.seek(0)
  78. self.buffer.truncate(0)
  79. # Leave the last partial chunk in the buffer unless flush is True
  80. end = None if flush or len(chunks) == 1 else -1
  81. for chunk in chunks[:end]:
  82. self.chunks.append(self.write_chunk(chunk))
  83. if end == -1:
  84. self.buffer.write(chunks[-1])
  85. def is_full(self):
  86. return self.buffer.tell() > self.BUFFER_SIZE
  87. class CacheChunkBuffer(ChunkBuffer):
  88. def __init__(self, cache, key, stats):
  89. super(CacheChunkBuffer, self).__init__(key)
  90. self.cache = cache
  91. self.stats = stats
  92. def write_chunk(self, chunk):
  93. id_, _, _ = self.cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats)
  94. return id_
  95. class Archive:
  96. class DoesNotExist(Error):
  97. """Archive {} does not exist"""
  98. class AlreadyExists(Error):
  99. """Archive {} already exists"""
  100. def __init__(self, repository, key, manifest, name, cache=None, create=False,
  101. checkpoint_interval=300, numeric_owner=False):
  102. self.cwd = os.getcwd()
  103. self.key = key
  104. self.repository = repository
  105. self.cache = cache
  106. self.manifest = manifest
  107. self.hard_links = {}
  108. self.stats = Statistics()
  109. self.name = name
  110. self.checkpoint_interval = checkpoint_interval
  111. self.numeric_owner = numeric_owner
  112. self.pipeline = DownloadPipeline(self.repository, self.key)
  113. if create:
  114. self.items_buffer = CacheChunkBuffer(self.cache, self.key, self.stats)
  115. self.chunker = Chunker(WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, CHUNK_MAX, self.key.chunk_seed)
  116. if name in manifest.archives:
  117. raise self.AlreadyExists(name)
  118. self.last_checkpoint = time.time()
  119. i = 0
  120. while True:
  121. self.checkpoint_name = '%s.checkpoint%s' % (name, i and ('.%d' % i) or '')
  122. if not self.checkpoint_name in manifest.archives:
  123. break
  124. i += 1
  125. else:
  126. if name not in self.manifest.archives:
  127. raise self.DoesNotExist(name)
  128. info = self.manifest.archives[name]
  129. self.load(info[b'id'])
  130. def load(self, id):
  131. self.id = id
  132. data = self.key.decrypt(self.id, self.repository.get(self.id))
  133. self.metadata = msgpack.unpackb(data)
  134. if self.metadata[b'version'] != 1:
  135. raise Exception('Unknown archive metadata version')
  136. decode_dict(self.metadata, (b'name', b'hostname', b'username', b'time'))
  137. self.metadata[b'cmdline'] = [arg.decode('utf-8', 'surrogateescape') for arg in self.metadata[b'cmdline']]
  138. self.name = self.metadata[b'name']
  139. @property
  140. def ts(self):
  141. """Timestamp of archive creation in UTC"""
  142. t, f = self.metadata[b'time'].split('.', 1)
  143. return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) + timedelta(seconds=float('.' + f))
  144. def __repr__(self):
  145. return 'Archive(%r)' % self.name
  146. def iter_items(self, filter=None, preload=False):
  147. for item in self.pipeline.unpack_many(self.metadata[b'items'], filter=filter, preload=preload):
  148. yield item
  149. def add_item(self, item):
  150. self.items_buffer.add(item)
  151. if time.time() - self.last_checkpoint > self.checkpoint_interval:
  152. self.write_checkpoint()
  153. self.last_checkpoint = time.time()
  154. def write_checkpoint(self):
  155. self.save(self.checkpoint_name)
  156. del self.manifest.archives[self.checkpoint_name]
  157. self.cache.chunk_decref(self.id, self.stats)
  158. def save(self, name=None):
  159. name = name or self.name
  160. if name in self.manifest.archives:
  161. raise self.AlreadyExists(name)
  162. self.items_buffer.flush(flush=True)
  163. metadata = StableDict({
  164. 'version': 1,
  165. 'name': name,
  166. 'items': self.items_buffer.chunks,
  167. 'cmdline': sys.argv,
  168. 'hostname': socket.gethostname(),
  169. 'username': getuser(),
  170. 'time': datetime.utcnow().isoformat(),
  171. })
  172. data = msgpack.packb(metadata, unicode_errors='surrogateescape')
  173. self.id = self.key.id_hash(data)
  174. self.cache.add_chunk(self.id, data, self.stats)
  175. self.manifest.archives[name] = {'id': self.id, 'time': metadata['time']}
  176. self.manifest.write()
  177. self.repository.commit()
  178. self.cache.commit()
  179. def calc_stats(self, cache):
  180. def add(id):
  181. count, size, csize = self.cache.chunks[id]
  182. stats.update(size, csize, count == 1)
  183. self.cache.chunks[id] = count - 1, size, csize
  184. def add_file_chunks(chunks):
  185. for id, _, _ in chunks:
  186. add(id)
  187. # This function is a bit evil since it abuses the cache to calculate
  188. # the stats. The cache transaction must be rolled back afterwards
  189. unpacker = msgpack.Unpacker(use_list=False)
  190. cache.begin_txn()
  191. stats = Statistics()
  192. add(self.id)
  193. for id, chunk in zip(self.metadata[b'items'], self.repository.get_many(self.metadata[b'items'])):
  194. add(id)
  195. unpacker.feed(self.key.decrypt(id, chunk))
  196. for item in unpacker:
  197. if b'chunks' in item:
  198. stats.nfiles += 1
  199. add_file_chunks(item[b'chunks'])
  200. cache.rollback()
  201. return stats
  202. def extract_item(self, item, restore_attrs=True, dry_run=False, sparse=False):
  203. if dry_run:
  204. if b'chunks' in item:
  205. for _ in self.pipeline.fetch_many([c[0] for c in item[b'chunks']], is_preloaded=True):
  206. pass
  207. return
  208. dest = self.cwd
  209. if item[b'path'].startswith('/') or item[b'path'].startswith('..'):
  210. raise Exception('Path should be relative and local')
  211. path = os.path.join(dest, item[b'path'])
  212. # Attempt to remove existing files, ignore errors on failure
  213. try:
  214. st = os.lstat(path)
  215. if stat.S_ISDIR(st.st_mode):
  216. os.rmdir(path)
  217. else:
  218. os.unlink(path)
  219. except OSError:
  220. pass
  221. mode = item[b'mode']
  222. if stat.S_ISDIR(mode):
  223. if not os.path.exists(path):
  224. os.makedirs(path)
  225. if restore_attrs:
  226. self.restore_attrs(path, item)
  227. elif stat.S_ISREG(mode):
  228. if not os.path.exists(os.path.dirname(path)):
  229. os.makedirs(os.path.dirname(path))
  230. # Hard link?
  231. if b'source' in item:
  232. source = os.path.join(dest, item[b'source'])
  233. if os.path.exists(path):
  234. os.unlink(path)
  235. os.link(source, path)
  236. else:
  237. with open(path, 'wb') as fd:
  238. ids = [c[0] for c in item[b'chunks']]
  239. for data in self.pipeline.fetch_many(ids, is_preloaded=True):
  240. if sparse and ZEROS.startswith(data):
  241. # all-zero chunk: create a hole in a sparse file
  242. fd.seek(len(data), 1)
  243. else:
  244. fd.write(data)
  245. pos = fd.tell()
  246. fd.truncate(pos)
  247. fd.flush()
  248. self.restore_attrs(path, item, fd=fd.fileno())
  249. elif stat.S_ISFIFO(mode):
  250. if not os.path.exists(os.path.dirname(path)):
  251. os.makedirs(os.path.dirname(path))
  252. os.mkfifo(path)
  253. self.restore_attrs(path, item)
  254. elif stat.S_ISLNK(mode):
  255. if not os.path.exists(os.path.dirname(path)):
  256. os.makedirs(os.path.dirname(path))
  257. source = item[b'source']
  258. if os.path.exists(path):
  259. os.unlink(path)
  260. os.symlink(source, path)
  261. self.restore_attrs(path, item, symlink=True)
  262. elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode):
  263. os.mknod(path, item[b'mode'], item[b'rdev'])
  264. self.restore_attrs(path, item)
  265. else:
  266. raise Exception('Unknown archive item type %r' % item[b'mode'])
  267. def restore_attrs(self, path, item, symlink=False, fd=None):
  268. xattrs = item.get(b'xattrs')
  269. if xattrs:
  270. for k, v in xattrs.items():
  271. try:
  272. xattr.setxattr(fd or path, k, v, follow_symlinks=False)
  273. except OSError as e:
  274. if e.errno != errno.ENOTSUP:
  275. raise
  276. uid = gid = None
  277. if not self.numeric_owner:
  278. uid = user2uid(item[b'user'])
  279. gid = group2gid(item[b'group'])
  280. uid = item[b'uid'] if uid is None else uid
  281. gid = item[b'gid'] if gid is None else gid
  282. # This code is a bit of a mess due to os specific differences
  283. try:
  284. if fd:
  285. os.fchown(fd, uid, gid)
  286. else:
  287. os.lchown(path, uid, gid)
  288. except OSError:
  289. pass
  290. if fd:
  291. os.fchmod(fd, item[b'mode'])
  292. elif not symlink:
  293. os.chmod(path, item[b'mode'])
  294. elif has_lchmod: # Not available on Linux
  295. os.lchmod(path, item[b'mode'])
  296. mtime = bigint_to_int(item[b'mtime'])
  297. if fd and utime_supports_fd: # Python >= 3.3
  298. os.utime(fd, None, ns=(mtime, mtime))
  299. elif utime_supports_follow_symlinks: # Python >= 3.3
  300. os.utime(path, None, ns=(mtime, mtime), follow_symlinks=False)
  301. elif not symlink:
  302. os.utime(path, (mtime / 1e9, mtime / 1e9))
  303. acl_set(path, item, self.numeric_owner)
  304. # Only available on OS X and FreeBSD
  305. if has_lchflags and b'bsdflags' in item:
  306. try:
  307. os.lchflags(path, item[b'bsdflags'])
  308. except OSError:
  309. pass
  310. def delete(self, stats):
  311. unpacker = msgpack.Unpacker(use_list=False)
  312. for items_id, data in zip(self.metadata[b'items'], self.repository.get_many(self.metadata[b'items'])):
  313. unpacker.feed(self.key.decrypt(items_id, data))
  314. self.cache.chunk_decref(items_id, stats)
  315. for item in unpacker:
  316. if b'chunks' in item:
  317. for chunk_id, size, csize in item[b'chunks']:
  318. self.cache.chunk_decref(chunk_id, stats)
  319. self.cache.chunk_decref(self.id, stats)
  320. del self.manifest.archives[self.name]
  321. def stat_attrs(self, st, path):
  322. item = {
  323. b'mode': st.st_mode,
  324. b'uid': st.st_uid, b'user': uid2user(st.st_uid),
  325. b'gid': st.st_gid, b'group': gid2group(st.st_gid),
  326. b'mtime': int_to_bigint(st_mtime_ns(st))
  327. }
  328. if self.numeric_owner:
  329. item[b'user'] = item[b'group'] = None
  330. xattrs = xattr.get_all(path, follow_symlinks=False)
  331. if xattrs:
  332. item[b'xattrs'] = StableDict(xattrs)
  333. if has_lchflags and st.st_flags:
  334. item[b'bsdflags'] = st.st_flags
  335. acl_get(path, item, st, self.numeric_owner)
  336. return item
  337. def process_item(self, path, st):
  338. item = {b'path': make_path_safe(path)}
  339. item.update(self.stat_attrs(st, path))
  340. self.add_item(item)
  341. def process_dev(self, path, st):
  342. item = {b'path': make_path_safe(path), b'rdev': st.st_rdev}
  343. item.update(self.stat_attrs(st, path))
  344. self.add_item(item)
  345. def process_symlink(self, path, st):
  346. source = os.readlink(path)
  347. item = {b'path': make_path_safe(path), b'source': source}
  348. item.update(self.stat_attrs(st, path))
  349. self.add_item(item)
  350. def process_file(self, path, st, cache):
  351. safe_path = make_path_safe(path)
  352. # Is it a hard link?
  353. if st.st_nlink > 1:
  354. source = self.hard_links.get((st.st_ino, st.st_dev))
  355. if (st.st_ino, st.st_dev) in self.hard_links:
  356. item = self.stat_attrs(st, path)
  357. item.update({b'path': safe_path, b'source': source})
  358. self.add_item(item)
  359. return
  360. else:
  361. self.hard_links[st.st_ino, st.st_dev] = safe_path
  362. path_hash = self.key.id_hash(os.path.join(self.cwd, path).encode('utf-8', 'surrogateescape'))
  363. ids = cache.file_known_and_unchanged(path_hash, st)
  364. chunks = None
  365. if ids is not None:
  366. # Make sure all ids are available
  367. for id_ in ids:
  368. if not cache.seen_chunk(id_):
  369. break
  370. else:
  371. chunks = [cache.chunk_incref(id_, self.stats) for id_ in ids]
  372. # Only chunkify the file if needed
  373. if chunks is None:
  374. with Archive._open_rb(path, st) as fd:
  375. chunks = []
  376. for chunk in self.chunker.chunkify(fd):
  377. chunks.append(cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats))
  378. cache.memorize_file(path_hash, st, [c[0] for c in chunks])
  379. item = {b'path': safe_path, b'chunks': chunks}
  380. item.update(self.stat_attrs(st, path))
  381. self.stats.nfiles += 1
  382. self.add_item(item)
  383. @staticmethod
  384. def list_archives(repository, key, manifest, cache=None):
  385. for name, info in manifest.archives.items():
  386. yield Archive(repository, key, manifest, name, cache=cache)
  387. @staticmethod
  388. def _open_rb(path, st):
  389. flags_noatime = None
  390. euid = None
  391. def open_simple(p, s):
  392. return open(p, 'rb')
  393. def open_noatime_if_owner(p, s):
  394. if s.st_uid == euid:
  395. return os.fdopen(os.open(p, flags_noatime), 'rb')
  396. else:
  397. return open(p, 'rb')
  398. def open_noatime(p, s):
  399. try:
  400. fd = os.open(p, flags_noatime)
  401. except PermissionError:
  402. # Was this EPERM due to the O_NOATIME flag?
  403. fo = open(p, 'rb')
  404. # Yes, it was -- otherwise the above line would have thrown
  405. # another exception.
  406. euid = os.geteuid()
  407. # So in future, let's check whether the file is owned by us
  408. # before attempting to use O_NOATIME.
  409. Archive._open_rb = open_noatime_if_owner
  410. return fo
  411. return os.fdopen(fd, 'rb')
  412. o_noatime = getattr(os, 'O_NOATIME', None)
  413. if o_noatime is not None:
  414. flags_noatime = os.O_RDONLY | getattr(os, 'O_BINARY', 0) | o_noatime
  415. # Always use O_NOATIME version.
  416. Archive._open_rb = open_noatime
  417. else:
  418. # Always use non-O_NOATIME version.
  419. Archive._open_rb = open_simple
  420. return Archive._open_rb(path, st)
  421. class RobustUnpacker():
  422. """A restartable/robust version of the streaming msgpack unpacker
  423. """
  424. item_keys = [msgpack.packb(name) for name in ('path', 'mode', 'source', 'chunks', 'rdev', 'xattrs', 'user', 'group', 'uid', 'gid', 'mtime')]
  425. def __init__(self, validator):
  426. super(RobustUnpacker, self).__init__()
  427. self.validator = validator
  428. self._buffered_data = []
  429. self._resync = False
  430. self._unpacker = msgpack.Unpacker(object_hook=StableDict)
  431. def resync(self):
  432. self._buffered_data = []
  433. self._resync = True
  434. def feed(self, data):
  435. if self._resync:
  436. self._buffered_data.append(data)
  437. else:
  438. self._unpacker.feed(data)
  439. def __iter__(self):
  440. return self
  441. def __next__(self):
  442. if self._resync:
  443. data = b''.join(self._buffered_data)
  444. while self._resync:
  445. if not data:
  446. raise StopIteration
  447. # Abort early if the data does not look like a serialized dict
  448. if len(data) < 2 or ((data[0] & 0xf0) != 0x80) or ((data[1] & 0xe0) != 0xa0):
  449. data = data[1:]
  450. continue
  451. # Make sure it looks like an item dict
  452. for pattern in self.item_keys:
  453. if data[1:].startswith(pattern):
  454. break
  455. else:
  456. data = data[1:]
  457. continue
  458. self._unpacker = msgpack.Unpacker(object_hook=StableDict)
  459. self._unpacker.feed(data)
  460. try:
  461. item = next(self._unpacker)
  462. if self.validator(item):
  463. self._resync = False
  464. return item
  465. # Ignore exceptions that might be raised when feeding
  466. # msgpack with invalid data
  467. except (TypeError, ValueError, StopIteration):
  468. pass
  469. data = data[1:]
  470. else:
  471. return next(self._unpacker)
  472. class ArchiveChecker:
  473. def __init__(self):
  474. self.error_found = False
  475. self.possibly_superseded = set()
  476. self.tmpdir = tempfile.mkdtemp()
  477. def __del__(self):
  478. shutil.rmtree(self.tmpdir)
  479. def check(self, repository, repair=False):
  480. self.report_progress('Starting archive consistency check...')
  481. self.repair = repair
  482. self.repository = repository
  483. self.init_chunks()
  484. self.key = self.identify_key(repository)
  485. if not Manifest.MANIFEST_ID in self.chunks:
  486. self.manifest = self.rebuild_manifest()
  487. else:
  488. self.manifest, _ = Manifest.load(repository, key=self.key)
  489. self.rebuild_refcounts()
  490. self.verify_chunks()
  491. if not self.error_found:
  492. self.report_progress('Archive consistency check complete, no problems found.')
  493. return self.repair or not self.error_found
  494. def init_chunks(self):
  495. """Fetch a list of all object keys from repository
  496. """
  497. # Explicity set the initial hash table capacity to avoid performance issues
  498. # due to hash table "resonance"
  499. capacity = int(len(self.repository) * 1.2)
  500. self.chunks = ChunkIndex(capacity)
  501. marker = None
  502. while True:
  503. result = self.repository.list(limit=10000, marker=marker)
  504. if not result:
  505. break
  506. marker = result[-1]
  507. for id_ in result:
  508. self.chunks[id_] = (0, 0, 0)
  509. def report_progress(self, msg, error=False):
  510. if error:
  511. self.error_found = True
  512. print(msg, file=sys.stderr if error else sys.stdout)
  513. def identify_key(self, repository):
  514. cdata = repository.get(next(self.chunks.iteritems())[0])
  515. return key_factory(repository, cdata)
  516. def rebuild_manifest(self):
  517. """Rebuild the manifest object if it is missing
  518. Iterates through all objects in the repository looking for archive metadata blocks.
  519. """
  520. self.report_progress('Rebuilding missing manifest, this might take some time...', error=True)
  521. manifest = Manifest(self.key, self.repository)
  522. for chunk_id, _ in self.chunks.iteritems():
  523. cdata = self.repository.get(chunk_id)
  524. data = self.key.decrypt(chunk_id, cdata)
  525. # Some basic sanity checks of the payload before feeding it into msgpack
  526. if len(data) < 2 or ((data[0] & 0xf0) != 0x80) or ((data[1] & 0xe0) != 0xa0):
  527. continue
  528. if not b'cmdline' in data or not b'\xa7version\x01' in data:
  529. continue
  530. try:
  531. archive = msgpack.unpackb(data)
  532. except:
  533. continue
  534. if isinstance(archive, dict) and b'items' in archive and b'cmdline' in archive:
  535. self.report_progress('Found archive ' + archive[b'name'].decode('utf-8'), error=True)
  536. manifest.archives[archive[b'name'].decode('utf-8')] = {b'id': chunk_id, b'time': archive[b'time']}
  537. self.report_progress('Manifest rebuild complete', error=True)
  538. return manifest
  539. def rebuild_refcounts(self):
  540. """Rebuild object reference counts by walking the metadata
  541. Missing and/or incorrect data is repaired when detected
  542. """
  543. # Exclude the manifest from chunks
  544. del self.chunks[Manifest.MANIFEST_ID]
  545. def mark_as_possibly_superseded(id_):
  546. if self.chunks.get(id_, (0,))[0] == 0:
  547. self.possibly_superseded.add(id_)
  548. def add_callback(chunk):
  549. id_ = self.key.id_hash(chunk)
  550. cdata = self.key.encrypt(chunk)
  551. add_reference(id_, len(chunk), len(cdata), cdata)
  552. return id_
  553. def add_reference(id_, size, csize, cdata=None):
  554. try:
  555. count, _, _ = self.chunks[id_]
  556. self.chunks[id_] = count + 1, size, csize
  557. except KeyError:
  558. assert cdata is not None
  559. self.chunks[id_] = 1, size, csize
  560. if self.repair:
  561. self.repository.put(id_, cdata)
  562. def verify_file_chunks(item):
  563. """Verifies that all file chunks are present
  564. Missing file chunks will be replaced with new chunks of the same
  565. length containing all zeros.
  566. """
  567. offset = 0
  568. chunk_list = []
  569. for chunk_id, size, csize in item[b'chunks']:
  570. if not chunk_id in self.chunks:
  571. # If a file chunk is missing, create an all empty replacement chunk
  572. self.report_progress('{}: Missing file chunk detected (Byte {}-{})'.format(item[b'path'].decode('utf-8', 'surrogateescape'), offset, offset + size), error=True)
  573. data = bytes(size)
  574. chunk_id = self.key.id_hash(data)
  575. cdata = self.key.encrypt(data)
  576. csize = len(cdata)
  577. add_reference(chunk_id, size, csize, cdata)
  578. else:
  579. add_reference(chunk_id, size, csize)
  580. chunk_list.append((chunk_id, size, csize))
  581. offset += size
  582. item[b'chunks'] = chunk_list
  583. def robust_iterator(archive):
  584. """Iterates through all archive items
  585. Missing item chunks will be skipped and the msgpack stream will be restarted
  586. """
  587. unpacker = RobustUnpacker(lambda item: isinstance(item, dict) and b'path' in item)
  588. _state = 0
  589. def missing_chunk_detector(chunk_id):
  590. nonlocal _state
  591. if _state % 2 != int(not chunk_id in self.chunks):
  592. _state += 1
  593. return _state
  594. for state, items in groupby(archive[b'items'], missing_chunk_detector):
  595. items = list(items)
  596. if state % 2:
  597. self.report_progress('Archive metadata damage detected', error=True)
  598. continue
  599. if state > 0:
  600. unpacker.resync()
  601. for chunk_id, cdata in zip(items, repository.get_many(items)):
  602. unpacker.feed(self.key.decrypt(chunk_id, cdata))
  603. for item in unpacker:
  604. yield item
  605. repository = cache_if_remote(self.repository)
  606. num_archives = len(self.manifest.archives)
  607. for i, (name, info) in enumerate(list(self.manifest.archives.items()), 1):
  608. self.report_progress('Analyzing archive {} ({}/{})'.format(name, i, num_archives))
  609. archive_id = info[b'id']
  610. if not archive_id in self.chunks:
  611. self.report_progress('Archive metadata block is missing', error=True)
  612. del self.manifest.archives[name]
  613. continue
  614. mark_as_possibly_superseded(archive_id)
  615. cdata = self.repository.get(archive_id)
  616. data = self.key.decrypt(archive_id, cdata)
  617. archive = StableDict(msgpack.unpackb(data))
  618. if archive[b'version'] != 1:
  619. raise Exception('Unknown archive metadata version')
  620. decode_dict(archive, (b'name', b'hostname', b'username', b'time')) # fixme: argv
  621. items_buffer = ChunkBuffer(self.key)
  622. items_buffer.write_chunk = add_callback
  623. for item in robust_iterator(archive):
  624. if b'chunks' in item:
  625. verify_file_chunks(item)
  626. items_buffer.add(item)
  627. items_buffer.flush(flush=True)
  628. for previous_item_id in archive[b'items']:
  629. mark_as_possibly_superseded(previous_item_id)
  630. archive[b'items'] = items_buffer.chunks
  631. data = msgpack.packb(archive, unicode_errors='surrogateescape')
  632. new_archive_id = self.key.id_hash(data)
  633. cdata = self.key.encrypt(data)
  634. add_reference(new_archive_id, len(data), len(cdata), cdata)
  635. info[b'id'] = new_archive_id
  636. def verify_chunks(self):
  637. unused = set()
  638. for id_, (count, size, csize) in self.chunks.iteritems():
  639. if count == 0:
  640. unused.add(id_)
  641. orphaned = unused - self.possibly_superseded
  642. if orphaned:
  643. self.report_progress('{} orphaned objects found'.format(len(orphaned)), error=True)
  644. if self.repair:
  645. for id_ in unused:
  646. self.repository.delete(id_)
  647. self.manifest.write()
  648. self.repository.commit()