utils.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import codecs
  4. import hashlib
  5. import json
  6. import json.decoder
  7. import six
  8. json_decoder = json.JSONDecoder()
  9. def get_output_stream(stream):
  10. if six.PY3:
  11. return stream
  12. return codecs.getwriter('utf-8')(stream)
  13. def stream_as_text(stream):
  14. """Given a stream of bytes or text, if any of the items in the stream
  15. are bytes convert them to text.
  16. This function can be removed once docker-py returns text streams instead
  17. of byte streams.
  18. """
  19. for data in stream:
  20. if not isinstance(data, six.text_type):
  21. data = data.decode('utf-8', 'replace')
  22. yield data
  23. def line_splitter(buffer, separator=u'\n'):
  24. index = buffer.find(six.text_type(separator))
  25. if index == -1:
  26. return None
  27. return buffer[:index + 1], buffer[index + 1:]
  28. def split_buffer(stream, splitter=None, decoder=lambda a: a):
  29. """Given a generator which yields strings and a splitter function,
  30. joins all input, splits on the separator and yields each chunk.
  31. Unlike string.split(), each chunk includes the trailing
  32. separator, except for the last one if none was found on the end
  33. of the input.
  34. """
  35. splitter = splitter or line_splitter
  36. buffered = six.text_type('')
  37. for data in stream_as_text(stream):
  38. buffered += data
  39. while True:
  40. buffer_split = splitter(buffered)
  41. if buffer_split is None:
  42. break
  43. item, buffered = buffer_split
  44. yield item
  45. if buffered:
  46. yield decoder(buffered)
  47. def json_splitter(buffer):
  48. """Attempt to parse a json object from a buffer. If there is at least one
  49. object, return it and the rest of the buffer, otherwise return None.
  50. """
  51. try:
  52. obj, index = json_decoder.raw_decode(buffer)
  53. rest = buffer[json.decoder.WHITESPACE.match(buffer, index).end():]
  54. return obj, rest
  55. except ValueError:
  56. return None
  57. def json_stream(stream):
  58. """Given a stream of text, return a stream of json objects.
  59. This handles streams which are inconsistently buffered (some entries may
  60. be newline delimited, and others are not).
  61. """
  62. return split_buffer(stream, json_splitter, json_decoder.decode)
  63. def json_hash(obj):
  64. dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
  65. h = hashlib.sha256()
  66. h.update(dump.encode('utf8'))
  67. return h.hexdigest()