archive.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. from binascii import hexlify
  2. from datetime import datetime, timedelta, timezone
  3. from getpass import getuser
  4. from itertools import groupby
  5. import shutil
  6. import tempfile
  7. from attic.key import key_factory
  8. import msgpack
  9. import os
  10. import socket
  11. import stat
  12. import sys
  13. import time
  14. from io import BytesIO
  15. from attic import xattr
  16. from attic.chunker import chunkify
  17. from attic.hashindex import ChunkIndex
  18. from attic.helpers import Error, uid2user, user2uid, gid2group, group2gid, \
  19. Manifest, Statistics, decode_dict, st_mtime_ns, make_path_safe
  20. ITEMS_BUFFER = 1024 * 1024
  21. CHUNK_MIN = 1024
  22. WINDOW_SIZE = 0xfff
  23. CHUNK_MASK = 0xffff
  24. utime_supports_fd = os.utime in getattr(os, 'supports_fd', {})
  25. has_mtime_ns = sys.version >= '3.3'
  26. has_lchmod = hasattr(os, 'lchmod')
  27. class DownloadPipeline:
  28. def __init__(self, repository, key):
  29. self.repository = repository
  30. self.key = key
  31. def unpack_many(self, ids, filter=None, preload=False):
  32. unpacker = msgpack.Unpacker(use_list=False)
  33. for data in self.fetch_many(ids):
  34. unpacker.feed(data)
  35. items = [decode_dict(item, (b'path', b'source', b'user', b'group')) for item in unpacker]
  36. if filter:
  37. items = [item for item in items if filter(item)]
  38. if preload:
  39. for item in items:
  40. if b'chunks' in item:
  41. self.repository.preload([c[0] for c in item[b'chunks']])
  42. for item in items:
  43. yield item
  44. def fetch_many(self, ids, is_preloaded=False):
  45. for id_, data in zip(ids, self.repository.get_many(ids, is_preloaded=is_preloaded)):
  46. yield self.key.decrypt(id_, data)
  47. class ChunkBuffer:
  48. BUFFER_SIZE = 1 * 1024 * 1024
  49. def __init__(self, key):
  50. self.buffer = BytesIO()
  51. self.packer = msgpack.Packer(unicode_errors='surrogateescape')
  52. self.chunks = []
  53. self.key = key
  54. def add(self, item):
  55. self.buffer.write(self.packer.pack(item))
  56. if self.is_full():
  57. self.flush()
  58. def write_chunk(self, chunk):
  59. raise NotImplementedError
  60. def flush(self, flush=False):
  61. if self.buffer.tell() == 0:
  62. return
  63. self.buffer.seek(0)
  64. chunks = list(bytes(s) for s in chunkify(self.buffer, WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, self.key.chunk_seed))
  65. self.buffer.seek(0)
  66. self.buffer.truncate(0)
  67. # Leave the last parital chunk in the buffer unless flush is True
  68. end = None if flush or len(chunks) == 1 else -1
  69. for chunk in chunks[:end]:
  70. self.chunks.append(self.write_chunk(chunk))
  71. if end == -1:
  72. self.buffer.write(chunks[-1])
  73. def is_full(self):
  74. return self.buffer.tell() > self.BUFFER_SIZE
  75. class CacheChunkBuffer(ChunkBuffer):
  76. def __init__(self, cache, key, stats):
  77. super(CacheChunkBuffer, self).__init__(key)
  78. self.cache = cache
  79. self.stats = stats
  80. def write_chunk(self, chunk):
  81. id_, _, _ = self.cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats)
  82. return id_
  83. class Archive:
  84. class DoesNotExist(Error):
  85. """Archive {} does not exist"""
  86. class AlreadyExists(Error):
  87. """Archive {} already exists"""
  88. def __init__(self, repository, key, manifest, name, cache=None, create=False,
  89. checkpoint_interval=300, numeric_owner=False):
  90. self.cwd = os.getcwd()
  91. self.key = key
  92. self.repository = repository
  93. self.cache = cache
  94. self.manifest = manifest
  95. self.hard_links = {}
  96. self.stats = Statistics()
  97. self.name = name
  98. self.checkpoint_interval = checkpoint_interval
  99. self.numeric_owner = numeric_owner
  100. self.items_buffer = CacheChunkBuffer(self.cache, self.key, self.stats)
  101. self.pipeline = DownloadPipeline(self.repository, self.key)
  102. if create:
  103. if name in manifest.archives:
  104. raise self.AlreadyExists(name)
  105. self.last_checkpoint = time.time()
  106. i = 0
  107. while True:
  108. self.checkpoint_name = '%s.checkpoint%s' % (name, i and ('.%d' % i) or '')
  109. if not self.checkpoint_name in manifest.archives:
  110. break
  111. i += 1
  112. else:
  113. if name not in self.manifest.archives:
  114. raise self.DoesNotExist(name)
  115. info = self.manifest.archives[name]
  116. self.load(info[b'id'])
  117. def load(self, id):
  118. self.id = id
  119. data = self.key.decrypt(self.id, self.repository.get(self.id))
  120. self.metadata = msgpack.unpackb(data)
  121. if self.metadata[b'version'] != 1:
  122. raise Exception('Unknown archive metadata version')
  123. decode_dict(self.metadata, (b'name', b'hostname', b'username', b'time'))
  124. self.metadata[b'cmdline'] = [arg.decode('utf-8', 'surrogateescape') for arg in self.metadata[b'cmdline']]
  125. self.name = self.metadata[b'name']
  126. @property
  127. def ts(self):
  128. """Timestamp of archive creation in UTC"""
  129. t, f = self.metadata[b'time'].split('.', 1)
  130. return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) + timedelta(seconds=float('.' + f))
  131. def __repr__(self):
  132. return 'Archive(%r)' % self.name
  133. def iter_items(self, filter=None, preload=False):
  134. for item in self.pipeline.unpack_many(self.metadata[b'items'], filter=filter, preload=preload):
  135. yield item
  136. def add_item(self, item):
  137. self.items_buffer.add(item)
  138. now = time.time()
  139. if now - self.last_checkpoint > self.checkpoint_interval:
  140. self.last_checkpoint = now
  141. self.write_checkpoint()
  142. def write_checkpoint(self):
  143. self.save(self.checkpoint_name)
  144. del self.manifest.archives[self.checkpoint_name]
  145. self.cache.chunk_decref(self.id)
  146. def save(self, name=None):
  147. name = name or self.name
  148. if name in self.manifest.archives:
  149. raise self.AlreadyExists(name)
  150. self.items_buffer.flush(flush=True)
  151. metadata = {
  152. 'version': 1,
  153. 'name': name,
  154. 'items': self.items_buffer.chunks,
  155. 'cmdline': sys.argv,
  156. 'hostname': socket.gethostname(),
  157. 'username': getuser(),
  158. 'time': datetime.utcnow().isoformat(),
  159. }
  160. data = msgpack.packb(metadata, unicode_errors='surrogateescape')
  161. self.id = self.key.id_hash(data)
  162. self.cache.add_chunk(self.id, data, self.stats)
  163. self.manifest.archives[name] = {'id': self.id, 'time': metadata['time']}
  164. self.manifest.write()
  165. self.repository.commit()
  166. self.cache.commit()
  167. def calc_stats(self, cache):
  168. def add(id):
  169. count, size, csize = self.cache.chunks[id]
  170. stats.update(size, csize, count == 1)
  171. self.cache.chunks[id] = count - 1, size, csize
  172. def add_file_chunks(chunks):
  173. for id, _, _ in chunks:
  174. add(id)
  175. # This function is a bit evil since it abuses the cache to calculate
  176. # the stats. The cache transaction must be rolled back afterwards
  177. unpacker = msgpack.Unpacker(use_list=False)
  178. cache.begin_txn()
  179. stats = Statistics()
  180. add(self.id)
  181. for id, chunk in zip(self.metadata[b'items'], self.repository.get_many(self.metadata[b'items'])):
  182. add(id)
  183. unpacker.feed(self.key.decrypt(id, chunk))
  184. for item in unpacker:
  185. if b'chunks' in item:
  186. stats.nfiles += 1
  187. add_file_chunks(item[b'chunks'])
  188. cache.rollback()
  189. return stats
  190. def extract_item(self, item, restore_attrs=True):
  191. dest = self.cwd
  192. if item[b'path'].startswith('/') or item[b'path'].startswith('..'):
  193. raise Exception('Path should be relative and local')
  194. path = os.path.join(dest, item[b'path'])
  195. # Attempt to remove existing files, ignore errors on failure
  196. try:
  197. st = os.lstat(path)
  198. if stat.S_ISDIR(st.st_mode):
  199. os.rmdir(path)
  200. else:
  201. os.unlink(path)
  202. except OSError:
  203. pass
  204. mode = item[b'mode']
  205. if stat.S_ISDIR(mode):
  206. if not os.path.exists(path):
  207. os.makedirs(path)
  208. if restore_attrs:
  209. self.restore_attrs(path, item)
  210. elif stat.S_ISREG(mode):
  211. if not os.path.exists(os.path.dirname(path)):
  212. os.makedirs(os.path.dirname(path))
  213. # Hard link?
  214. if b'source' in item:
  215. source = os.path.join(dest, item[b'source'])
  216. if os.path.exists(path):
  217. os.unlink(path)
  218. os.link(source, path)
  219. else:
  220. with open(path, 'wb') as fd:
  221. ids = [c[0] for c in item[b'chunks']]
  222. for data in self.pipeline.fetch_many(ids, is_preloaded=True):
  223. fd.write(data)
  224. fd.flush()
  225. self.restore_attrs(path, item, fd=fd.fileno())
  226. elif stat.S_ISFIFO(mode):
  227. if not os.path.exists(os.path.dirname(path)):
  228. os.makedirs(os.path.dirname(path))
  229. os.mkfifo(path)
  230. self.restore_attrs(path, item)
  231. elif stat.S_ISLNK(mode):
  232. if not os.path.exists(os.path.dirname(path)):
  233. os.makedirs(os.path.dirname(path))
  234. source = item[b'source']
  235. if os.path.exists(path):
  236. os.unlink(path)
  237. os.symlink(source, path)
  238. self.restore_attrs(path, item, symlink=True)
  239. elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode):
  240. os.mknod(path, item[b'mode'], item[b'rdev'])
  241. self.restore_attrs(path, item)
  242. else:
  243. raise Exception('Unknown archive item type %r' % item[b'mode'])
  244. def restore_attrs(self, path, item, symlink=False, fd=None):
  245. xattrs = item.get(b'xattrs')
  246. if xattrs:
  247. for k, v in xattrs.items():
  248. xattr.setxattr(fd or path, k, v)
  249. uid = gid = None
  250. if not self.numeric_owner:
  251. uid = user2uid(item[b'user'])
  252. gid = group2gid(item[b'group'])
  253. uid = uid or item[b'uid']
  254. gid = gid or item[b'gid']
  255. # This code is a bit of a mess due to os specific differences
  256. try:
  257. if fd:
  258. os.fchown(fd, uid, gid)
  259. else:
  260. os.lchown(path, uid, gid)
  261. except OSError:
  262. pass
  263. if fd:
  264. os.fchmod(fd, item[b'mode'])
  265. elif not symlink:
  266. os.chmod(path, item[b'mode'])
  267. elif has_lchmod: # Not available on Linux
  268. os.lchmod(path, item[b'mode'])
  269. if fd and utime_supports_fd: # Python >= 3.3
  270. os.utime(fd, None, ns=(item[b'mtime'], item[b'mtime']))
  271. elif utime_supports_fd: # Python >= 3.3
  272. os.utime(path, None, ns=(item[b'mtime'], item[b'mtime']), follow_symlinks=False)
  273. elif not symlink:
  274. os.utime(path, (item[b'mtime'] / 10**9, item[b'mtime'] / 10**9))
  275. def verify_file(self, item, start, result):
  276. if not item[b'chunks']:
  277. start(item)
  278. result(item, True)
  279. else:
  280. start(item)
  281. ids = [id for id, size, csize in item[b'chunks']]
  282. try:
  283. for _ in self.pipeline.fetch_many(ids, is_preloaded=True):
  284. pass
  285. except Exception:
  286. result(item, False)
  287. return
  288. result(item, True)
  289. def delete(self, cache):
  290. unpacker = msgpack.Unpacker(use_list=False)
  291. for id_, data in zip(self.metadata[b'items'], self.repository.get_many(self.metadata[b'items'])):
  292. unpacker.feed(self.key.decrypt(id_, data))
  293. self.cache.chunk_decref(id_)
  294. for item in unpacker:
  295. if b'chunks' in item:
  296. for chunk_id, size, csize in item[b'chunks']:
  297. self.cache.chunk_decref(chunk_id)
  298. self.cache.chunk_decref(self.id)
  299. del self.manifest.archives[self.name]
  300. self.manifest.write()
  301. self.repository.commit()
  302. cache.commit()
  303. def stat_attrs(self, st, path):
  304. item = {
  305. b'mode': st.st_mode,
  306. b'uid': st.st_uid, b'user': uid2user(st.st_uid),
  307. b'gid': st.st_gid, b'group': gid2group(st.st_gid),
  308. b'mtime': st_mtime_ns(st),
  309. }
  310. if self.numeric_owner:
  311. item[b'user'] = item[b'group'] = None
  312. xattrs = xattr.get_all(path, follow_symlinks=False)
  313. if xattrs:
  314. item[b'xattrs'] = xattrs
  315. return item
  316. def process_item(self, path, st):
  317. item = {b'path': make_path_safe(path)}
  318. item.update(self.stat_attrs(st, path))
  319. self.add_item(item)
  320. def process_dev(self, path, st):
  321. item = {b'path': make_path_safe(path), b'rdev': st.st_rdev}
  322. item.update(self.stat_attrs(st, path))
  323. self.add_item(item)
  324. def process_symlink(self, path, st):
  325. source = os.readlink(path)
  326. item = {b'path': make_path_safe(path), b'source': source}
  327. item.update(self.stat_attrs(st, path))
  328. self.add_item(item)
  329. def process_file(self, path, st, cache):
  330. safe_path = make_path_safe(path)
  331. # Is it a hard link?
  332. if st.st_nlink > 1:
  333. source = self.hard_links.get((st.st_ino, st.st_dev))
  334. if (st.st_ino, st.st_dev) in self.hard_links:
  335. item = self.stat_attrs(st, path)
  336. item.update({b'path': safe_path, b'source': source})
  337. self.add_item(item)
  338. return
  339. else:
  340. self.hard_links[st.st_ino, st.st_dev] = safe_path
  341. path_hash = self.key.id_hash(os.path.join(self.cwd, path).encode('utf-8', 'surrogateescape'))
  342. ids = cache.file_known_and_unchanged(path_hash, st)
  343. chunks = None
  344. if ids is not None:
  345. # Make sure all ids are available
  346. for id_ in ids:
  347. if not cache.seen_chunk(id_):
  348. break
  349. else:
  350. chunks = [cache.chunk_incref(id_, self.stats) for id_ in ids]
  351. # Only chunkify the file if needed
  352. if chunks is None:
  353. with open(path, 'rb') as fd:
  354. chunks = []
  355. for chunk in chunkify(fd, WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, self.key.chunk_seed):
  356. chunks.append(cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats))
  357. cache.memorize_file(path_hash, st, [c[0] for c in chunks])
  358. item = {b'path': safe_path, b'chunks': chunks}
  359. item.update(self.stat_attrs(st, path))
  360. self.stats.nfiles += 1
  361. self.add_item(item)
  362. @staticmethod
  363. def list_archives(repository, key, manifest, cache=None):
  364. for name, info in manifest.archives.items():
  365. yield Archive(repository, key, manifest, name, cache=cache)
  366. class ArchiveChecker:
  367. def __init__(self):
  368. self.error_found = False
  369. self.progress = True
  370. self.possibly_superseded = set()
  371. self.tmpdir = tempfile.mkdtemp()
  372. def __del__(self):
  373. shutil.rmtree(self.tmpdir)
  374. def init_chunks(self):
  375. self.chunks = ChunkIndex.create(os.path.join(self.tmpdir, 'chunks').encode('utf-8'))
  376. marker = None
  377. while True:
  378. result = self.repository.list(limit=10000, marker=marker)
  379. if not result:
  380. break
  381. marker = result[-1]
  382. for id_ in result:
  383. self.chunks[id_] = (0, 0, 0)
  384. def report_progress(self, msg, error=False):
  385. if error:
  386. self.error_found = True
  387. if error or self.progress:
  388. print(msg, file=sys.stderr)
  389. sys.stderr.flush()
  390. def identify_key(self, repository):
  391. cdata = repository.get(next(self.chunks.iteritems())[0])
  392. return key_factory(repository, cdata)
  393. def rebuild_manifest(self):
  394. self.report_progress('Rebuilding missing manifest, this might take some time...', error=True)
  395. manifest = Manifest(self.key, self.repository)
  396. for chunk_id, _ in self.chunks.iteritems():
  397. cdata = self.repository.get(chunk_id)
  398. data = self.key.decrypt(chunk_id, cdata)
  399. try:
  400. archive = msgpack.unpackb(data)
  401. except:
  402. continue
  403. if isinstance(archive, dict) and b'items' in archive and b'cmdline' in archive:
  404. self.report_progress('Found archive ' + archive[b'name'].decode('utf-8'), error=True)
  405. manifest.archives[archive[b'name'].decode('utf-8')] = {b'id': chunk_id, b'time': archive[b'time']}
  406. self.report_progress('Manifest rebuild complete', error=True)
  407. return manifest
  408. def check(self, repository, progress=True, repair=False):
  409. self.report_progress('Starting archive consistency check...')
  410. self.repair = repair
  411. self.progress = progress
  412. self.repository = repository
  413. self.init_chunks()
  414. self.key = self.identify_key(repository)
  415. if not Manifest.MANIFEST_ID in self.chunks:
  416. self.manifest = self.rebuild_manifest()
  417. else:
  418. self.manifest, _ = Manifest.load(repository)
  419. self.rebuild_chunks()
  420. self.verify_chunks()
  421. if not self.error_found:
  422. self.report_progress('Archive consistency check complete, no errors found.')
  423. return self.repair or not self.error_found
  424. def verify_chunks(self):
  425. unused = set()
  426. for id_, (count, size, csize) in self.chunks.iteritems():
  427. if count == 0:
  428. unused.add(id_)
  429. unexpected = unused - self.possibly_superseded
  430. if unexpected:
  431. self.report_progress('{} excessive objects found'.format(len(unexpected)), error=True)
  432. if self.repair:
  433. for id_ in unused:
  434. self.repository.delete(id_)
  435. self.manifest.write()
  436. self.repository.commit()
  437. def rebuild_chunks(self):
  438. # Exclude the manifest from chunks
  439. del self.chunks[Manifest.MANIFEST_ID]
  440. def record_unused(id_):
  441. if self.chunks.get(id_, (0,))[0] == 0:
  442. self.possibly_superseded.add(id_)
  443. def add_callback(chunk):
  444. id_ = self.key.id_hash(chunk)
  445. cdata = self.key.encrypt(chunk)
  446. add_reference(id_, len(chunk), len(cdata), cdata)
  447. return id_
  448. def add_reference(id_, size, csize, cdata=None):
  449. try:
  450. count, _, _ = self.chunks[id_]
  451. self.chunks[id_] = count + 1, size, csize
  452. except KeyError:
  453. assert cdata is not None
  454. self.chunks[id_] = 1, size, csize
  455. if self.repair:
  456. self.repository.put(id_, cdata)
  457. def verify_file_chunks(item):
  458. offset = 0
  459. chunk_list = []
  460. for chunk_id, size, csize in item[b'chunks']:
  461. if not chunk_id in self.chunks:
  462. # If a file chunk is missing, create an all empty replacement chunk
  463. self.report_progress('{}: Missing file chunk detected (Byte {}-{})'.format(item[b'path'].decode('utf-8', 'surrogateescape'), offset, offset + size), error=True)
  464. data = bytes(size)
  465. chunk_id = self.key.id_hash(data)
  466. cdata = self.key.encrypt(data)
  467. csize = len(cdata)
  468. add_reference(chunk_id, size, csize, cdata)
  469. else:
  470. add_reference(chunk_id, size, csize)
  471. chunk_list.append((chunk_id, size, csize))
  472. offset += size
  473. item[b'chunks'] = chunk_list
  474. def msgpack_resync(data):
  475. data = memoryview(data)
  476. while data:
  477. unpacker = msgpack.Unpacker()
  478. unpacker.feed(data)
  479. item = next(unpacker)
  480. if isinstance(item, dict) and b'path' in item:
  481. return data
  482. data = data[1:]
  483. def robust_iterator(archive):
  484. prev_state = None
  485. state = 0
  486. def missing_chunk_detector(chunk_id):
  487. nonlocal state
  488. if state % 2 != int(not chunk_id in self.chunks):
  489. state += 1
  490. return state
  491. for state, items in groupby(archive[b'items'], missing_chunk_detector):
  492. if state != prev_state:
  493. unpacker = msgpack.Unpacker()
  494. prev_state = state
  495. if state % 2:
  496. self.report_progress('Archive metadata damage detected', error=True)
  497. return
  498. items = list(items)
  499. for i, (chunk_id, cdata) in enumerate(zip(items, self.repository.get_many(items))):
  500. data = self.key.decrypt(chunk_id, cdata)
  501. if state and i == 0:
  502. data = msgpack_resync(data)
  503. unpacker.feed(data)
  504. for item in unpacker:
  505. yield item
  506. for name, info in list(self.manifest.archives.items()):
  507. self.report_progress('Analyzing archive: ' + name)
  508. archive_id = info[b'id']
  509. if not archive_id in self.chunks:
  510. self.report_progress('Archive metadata block is missing', error=True)
  511. del self.manifest.archives[name]
  512. continue
  513. items_buffer = ChunkBuffer(self.key)
  514. items_buffer.write_chunk = add_callback
  515. cdata = self.repository.get(archive_id)
  516. data = self.key.decrypt(archive_id, cdata)
  517. archive = msgpack.unpackb(data)
  518. if archive[b'version'] != 1:
  519. raise Exception('Unknown archive metadata version')
  520. decode_dict(archive, (b'name', b'hostname', b'username', b'time')) # fixme: argv
  521. for item in robust_iterator(archive):
  522. if b'chunks' in item:
  523. verify_file_chunks(item)
  524. items_buffer.add(item)
  525. items_buffer.flush(flush=True)
  526. for previous_item_id in archive[b'items']:
  527. record_unused(previous_item_id)
  528. archive[b'items'] = items_buffer.chunks
  529. data = msgpack.packb(archive, unicode_errors='surrogateescape')
  530. new_archive_id = self.key.id_hash(data)
  531. cdata = self.key.encrypt(data)
  532. add_reference(new_archive_id, len(data), len(cdata), cdata)
  533. record_unused(archive_id)
  534. info[b'id'] = new_archive_id