archive.py 31 KB

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