archive.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. from datetime import datetime, timedelta
  2. from getpass import getuser
  3. from itertools import zip_longest
  4. import msgpack
  5. import os
  6. import socket
  7. import stat
  8. import sys
  9. import time
  10. from io import BytesIO
  11. from attic import xattr
  12. from attic.chunker import chunkify
  13. from attic.helpers import uid2user, user2uid, gid2group, group2gid, \
  14. Statistics, decode_dict, st_mtime_ns, make_path_safe
  15. ITEMS_BUFFER = 1024 * 1024
  16. CHUNK_MIN = 1024
  17. WINDOW_SIZE = 0xfff
  18. CHUNK_MASK = 0xffff
  19. utime_supports_fd = os.utime in getattr(os, 'supports_fd', {})
  20. has_mtime_ns = sys.version >= '3.3'
  21. has_lchmod = hasattr(os, 'lchmod')
  22. class ItemIter(object):
  23. def __init__(self, unpacker, filter):
  24. self.unpacker = iter(unpacker)
  25. self.filter = filter
  26. self.stack = []
  27. self.peeks = 0
  28. self._peek_iter = None
  29. def __iter__(self):
  30. return self
  31. def __next__(self):
  32. if self.stack:
  33. item = self.stack.pop(0)
  34. else:
  35. self._peek_iter = None
  36. item = self.get_next()
  37. self.peeks = max(0, self.peeks - len(item.get(b'chunks', [])))
  38. return item
  39. def get_next(self):
  40. while True:
  41. n = next(self.unpacker)
  42. decode_dict(n, (b'path', b'source', b'user', b'group'))
  43. if not self.filter or self.filter(n):
  44. return n
  45. def peek(self):
  46. while True:
  47. while not self._peek_iter:
  48. if self.peeks > 100:
  49. raise StopIteration
  50. _peek = self.get_next()
  51. self.stack.append(_peek)
  52. if b'chunks' in _peek:
  53. self._peek_iter = iter(_peek[b'chunks'])
  54. else:
  55. self._peek_iter = None
  56. try:
  57. item = next(self._peek_iter)
  58. self.peeks += 1
  59. return item
  60. except StopIteration:
  61. self._peek_iter = None
  62. class Archive(object):
  63. class DoesNotExist(Exception):
  64. pass
  65. class AlreadyExists(Exception):
  66. pass
  67. def __init__(self, repository, key, manifest, name, cache=None, create=False,
  68. checkpoint_interval=300, numeric_owner=False):
  69. self.cwd = os.getcwd()
  70. self.key = key
  71. self.repository = repository
  72. self.cache = cache
  73. self.manifest = manifest
  74. self.items = BytesIO()
  75. self.items_ids = []
  76. self.hard_links = {}
  77. self.stats = Statistics()
  78. self.name = name
  79. self.checkpoint_interval = checkpoint_interval
  80. self.numeric_owner = numeric_owner
  81. if create:
  82. if name in manifest.archives:
  83. raise self.AlreadyExists(name)
  84. self.last_checkpoint = time.time()
  85. i = 0
  86. while True:
  87. self.checkpoint_name = '%s.checkpoint%s' % (name, i and ('.%d' % i) or '')
  88. if not self.checkpoint_name in manifest.archives:
  89. break
  90. i += 1
  91. else:
  92. if name not in self.manifest.archives:
  93. raise self.DoesNotExist(name)
  94. info = self.manifest.archives[name]
  95. self.load(info[b'id'])
  96. def load(self, id):
  97. self.id = id
  98. data = self.key.decrypt(self.id, self.repository.get(self.id))
  99. self.metadata = msgpack.unpackb(data)
  100. if self.metadata[b'version'] != 1:
  101. raise Exception('Unknown archive metadata version')
  102. decode_dict(self.metadata, (b'name', b'hostname', b'username', b'time'))
  103. self.metadata[b'cmdline'] = [arg.decode('utf-8', 'surrogateescape') for arg in self.metadata[b'cmdline']]
  104. self.name = self.metadata[b'name']
  105. @property
  106. def ts(self):
  107. """Timestamp of archive creation in UTC"""
  108. t, f = self.metadata[b'time'].split('.', 1)
  109. return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S') + timedelta(seconds=float('.' + f))
  110. def __repr__(self):
  111. return 'Archive(%r)' % self.name
  112. def iter_items(self, filter=None):
  113. unpacker = msgpack.Unpacker(use_list=False)
  114. i = 0
  115. n = 20
  116. while True:
  117. items = self.metadata[b'items'][i:i + n]
  118. i += n
  119. if not items:
  120. break
  121. for id, chunk in [(id, chunk) for id, chunk in zip_longest(items, self.repository.get_many(items))]:
  122. unpacker.feed(self.key.decrypt(id, chunk))
  123. iter = ItemIter(unpacker, filter)
  124. for item in iter:
  125. yield item, iter.peek
  126. def add_item(self, item):
  127. self.items.write(msgpack.packb(item, unicode_errors='surrogateescape'))
  128. now = time.time()
  129. if now - self.last_checkpoint > self.checkpoint_interval:
  130. self.last_checkpoint = now
  131. self.write_checkpoint()
  132. if self.items.tell() > ITEMS_BUFFER:
  133. self.flush_items()
  134. def flush_items(self, flush=False):
  135. if self.items.tell() == 0:
  136. return
  137. self.items.seek(0)
  138. chunks = list(bytes(s) for s in chunkify(self.items, WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, self.key.chunk_seed))
  139. self.items.seek(0)
  140. self.items.truncate()
  141. for chunk in chunks[:-1]:
  142. id, _, _ = self.cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats)
  143. self.items_ids.append(id)
  144. if flush or len(chunks) == 1:
  145. id, _, _ = self.cache.add_chunk(self.key.id_hash(chunks[-1]), chunks[-1], self.stats)
  146. self.items_ids.append(id)
  147. else:
  148. self.items.write(chunks[-1])
  149. def write_checkpoint(self):
  150. self.save(self.checkpoint_name)
  151. del self.manifest.archives[self.checkpoint_name]
  152. self.cache.chunk_decref(self.id)
  153. def save(self, name=None):
  154. name = name or self.name
  155. if name in self.manifest.archives:
  156. raise self.AlreadyExists(name)
  157. self.flush_items(flush=True)
  158. metadata = {
  159. 'version': 1,
  160. 'name': name,
  161. 'items': self.items_ids,
  162. 'cmdline': sys.argv,
  163. 'hostname': socket.gethostname(),
  164. 'username': getuser(),
  165. 'time': datetime.utcnow().isoformat(),
  166. }
  167. data = msgpack.packb(metadata, unicode_errors='surrogateescape')
  168. self.id = self.key.id_hash(data)
  169. self.cache.add_chunk(self.id, data, self.stats)
  170. self.manifest.archives[name] = {'id': self.id, 'time': metadata['time']}
  171. self.manifest.write()
  172. self.repository.commit()
  173. self.cache.commit()
  174. def calc_stats(self, cache):
  175. def add(id):
  176. count, size, csize = self.cache.chunks[id]
  177. stats.update(size, csize, count == 1)
  178. self.cache.chunks[id] = count - 1, size, csize
  179. # This function is a bit evil since it abuses the cache to calculate
  180. # the stats. The cache transaction must be rolled back afterwards
  181. unpacker = msgpack.Unpacker(use_list=False)
  182. cache.begin_txn()
  183. stats = Statistics()
  184. add(self.id)
  185. for id, chunk in zip_longest(self.metadata[b'items'], self.repository.get_many(self.metadata[b'items'])):
  186. add(id)
  187. unpacker.feed(self.key.decrypt(id, chunk))
  188. for item in unpacker:
  189. try:
  190. for id, size, csize in item[b'chunks']:
  191. add(id)
  192. stats.nfiles += 1
  193. except KeyError:
  194. pass
  195. cache.rollback()
  196. return stats
  197. def extract_item(self, item, restore_attrs=True, peek=None):
  198. dest = self.cwd
  199. if item[b'path'].startswith('/') or item[b'path'].startswith('..'):
  200. raise Exception('Path should be relative and local')
  201. path = os.path.join(dest, item[b'path'])
  202. # Attempt to remove existing files, ignore errors on failure
  203. try:
  204. st = os.lstat(path)
  205. if stat.S_ISDIR(st.st_mode):
  206. os.rmdir(path)
  207. else:
  208. os.unlink(path)
  209. except OSError:
  210. pass
  211. mode = item[b'mode']
  212. if stat.S_ISDIR(mode):
  213. if not os.path.exists(path):
  214. os.makedirs(path)
  215. if restore_attrs:
  216. self.restore_attrs(path, item)
  217. elif stat.S_ISREG(mode):
  218. if not os.path.exists(os.path.dirname(path)):
  219. os.makedirs(os.path.dirname(path))
  220. # Hard link?
  221. if b'source' in item:
  222. source = os.path.join(dest, item[b'source'])
  223. if os.path.exists(path):
  224. os.unlink(path)
  225. os.link(source, path)
  226. else:
  227. with open(path, 'wb') as fd:
  228. ids = [id for id, size, csize in item[b'chunks']]
  229. for id, chunk in zip_longest(ids, self.repository.get_many(ids, peek)):
  230. data = self.key.decrypt(id, chunk)
  231. fd.write(data)
  232. fd.flush()
  233. self.restore_attrs(path, item, fd=fd.fileno())
  234. elif stat.S_ISFIFO(mode):
  235. if not os.path.exists(os.path.dirname(path)):
  236. os.makedirs(os.path.dirname(path))
  237. os.mkfifo(path)
  238. self.restore_attrs(path, item)
  239. elif stat.S_ISLNK(mode):
  240. if not os.path.exists(os.path.dirname(path)):
  241. os.makedirs(os.path.dirname(path))
  242. source = item[b'source']
  243. if os.path.exists(path):
  244. os.unlink(path)
  245. os.symlink(source, path)
  246. self.restore_attrs(path, item, symlink=True)
  247. elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode):
  248. os.mknod(path, item[b'mode'], item[b'rdev'])
  249. self.restore_attrs(path, item)
  250. else:
  251. raise Exception('Unknown archive item type %r' % item[b'mode'])
  252. def restore_attrs(self, path, item, symlink=False, fd=None):
  253. xattrs = item.get(b'xattrs')
  254. if xattrs:
  255. for k, v in xattrs.items():
  256. xattr.setxattr(fd or path, k, v)
  257. uid = gid = None
  258. if not self.numeric_owner:
  259. uid = user2uid(item[b'user'])
  260. gid = group2gid(item[b'group'])
  261. uid = uid or item[b'uid']
  262. gid = gid or item[b'gid']
  263. # This code is a bit of a mess due to os specific differences
  264. try:
  265. if fd:
  266. os.fchown(fd, uid, gid)
  267. else:
  268. os.lchown(path, uid, gid)
  269. except OSError:
  270. pass
  271. if fd:
  272. os.fchmod(fd, item[b'mode'])
  273. elif not symlink:
  274. os.chmod(path, item[b'mode'])
  275. elif has_lchmod: # Not available on Linux
  276. os.lchmod(path, item[b'mode'])
  277. if fd and utime_supports_fd: # Python >= 3.3
  278. os.utime(fd, None, ns=(item[b'mtime'], item[b'mtime']))
  279. elif utime_supports_fd: # Python >= 3.3
  280. os.utime(path, None, ns=(item[b'mtime'], item[b'mtime']), follow_symlinks=False)
  281. elif not symlink:
  282. os.utime(path, (item[b'mtime'] / 10**9, item[b'mtime'] / 10**9))
  283. def verify_file(self, item, start, result, peek=None):
  284. if not item[b'chunks']:
  285. start(item)
  286. result(item, True)
  287. else:
  288. start(item)
  289. ids = [id for id, size, csize in item[b'chunks']]
  290. try:
  291. for id, chunk in zip_longest(ids, self.repository.get_many(ids, peek)):
  292. self.key.decrypt(id, chunk)
  293. except Exception:
  294. result(item, False)
  295. return
  296. result(item, True)
  297. def delete(self, cache):
  298. unpacker = msgpack.Unpacker(use_list=False)
  299. for id in self.metadata[b'items']:
  300. unpacker.feed(self.key.decrypt(id, self.repository.get(id)))
  301. for item in unpacker:
  302. try:
  303. for chunk_id, size, csize in item[b'chunks']:
  304. self.cache.chunk_decref(chunk_id)
  305. except KeyError:
  306. pass
  307. self.cache.chunk_decref(id)
  308. self.cache.chunk_decref(self.id)
  309. del self.manifest.archives[self.name]
  310. self.manifest.write()
  311. self.repository.commit()
  312. cache.commit()
  313. def stat_attrs(self, st, path):
  314. item = {
  315. b'mode': st.st_mode,
  316. b'uid': st.st_uid, b'user': uid2user(st.st_uid),
  317. b'gid': st.st_gid, b'group': gid2group(st.st_gid),
  318. b'mtime': st_mtime_ns(st),
  319. }
  320. if self.numeric_owner:
  321. item[b'user'] = item[b'group'] = None
  322. xattrs = xattr.get_all(path, follow_symlinks=False)
  323. if xattrs:
  324. item[b'xattrs'] = xattrs
  325. return item
  326. def process_item(self, path, st):
  327. item = {b'path': make_path_safe(path)}
  328. item.update(self.stat_attrs(st, path))
  329. self.add_item(item)
  330. def process_dev(self, path, st):
  331. item = {b'path': make_path_safe(path), b'rdev': st.st_rdev}
  332. item.update(self.stat_attrs(st, path))
  333. self.add_item(item)
  334. def process_symlink(self, path, st):
  335. source = os.readlink(path)
  336. item = {b'path': make_path_safe(path), b'source': source}
  337. item.update(self.stat_attrs(st, path))
  338. self.add_item(item)
  339. def process_file(self, path, st, cache):
  340. safe_path = make_path_safe(path)
  341. # Is it a hard link?
  342. if st.st_nlink > 1:
  343. source = self.hard_links.get((st.st_ino, st.st_dev))
  344. if (st.st_ino, st.st_dev) in self.hard_links:
  345. item = self.stat_attrs(st, path)
  346. item.update({b'path': safe_path, b'source': source})
  347. self.add_item(item)
  348. return
  349. else:
  350. self.hard_links[st.st_ino, st.st_dev] = safe_path
  351. path_hash = self.key.id_hash(os.path.join(self.cwd, path).encode('utf-8', 'surrogateescape'))
  352. ids = cache.file_known_and_unchanged(path_hash, st)
  353. chunks = None
  354. if ids is not None:
  355. # Make sure all ids are available
  356. for id in ids:
  357. if not cache.seen_chunk(id):
  358. break
  359. else:
  360. chunks = [cache.chunk_incref(id, self.stats) for id in ids]
  361. # Only chunkify the file if needed
  362. if chunks is None:
  363. with open(path, 'rb') as fd:
  364. chunks = []
  365. for chunk in chunkify(fd, WINDOW_SIZE, CHUNK_MASK, CHUNK_MIN, self.key.chunk_seed):
  366. chunks.append(cache.add_chunk(self.key.id_hash(chunk), chunk, self.stats))
  367. ids = [id for id, _, _ in chunks]
  368. cache.memorize_file(path_hash, st, ids)
  369. item = {b'path': safe_path, b'chunks': chunks}
  370. item.update(self.stat_attrs(st, path))
  371. self.stats.nfiles += 1
  372. self.add_item(item)
  373. @staticmethod
  374. def list_archives(repository, key, manifest, cache=None):
  375. for name, info in manifest.archives.items():
  376. yield Archive(repository, key, manifest, name, cache=cache)