1
0

utils.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 logging
  8. import six
  9. json_decoder = json.JSONDecoder()
  10. log = logging.getLogger(__name__)
  11. def get_output_stream(stream):
  12. if six.PY3:
  13. return stream
  14. return codecs.getwriter('utf-8')(stream)
  15. def stream_as_text(stream):
  16. """Given a stream of bytes or text, if any of the items in the stream
  17. are bytes convert them to text.
  18. This function can be removed once docker-py returns text streams instead
  19. of byte streams.
  20. """
  21. for data in stream:
  22. if not isinstance(data, six.text_type):
  23. data = data.decode('utf-8', 'replace')
  24. yield data
  25. def line_splitter(buffer, separator=u'\n'):
  26. index = buffer.find(six.text_type(separator))
  27. if index == -1:
  28. return None
  29. return buffer[:index + 1], buffer[index + 1:]
  30. def split_buffer(stream, splitter=None, decoder=lambda a: a):
  31. """Given a generator which yields strings and a splitter function,
  32. joins all input, splits on the separator and yields each chunk.
  33. Unlike string.split(), each chunk includes the trailing
  34. separator, except for the last one if none was found on the end
  35. of the input.
  36. """
  37. splitter = splitter or line_splitter
  38. buffered = six.text_type('')
  39. for data in stream_as_text(stream):
  40. buffered += data
  41. while True:
  42. buffer_split = splitter(buffered)
  43. if buffer_split is None:
  44. break
  45. item, buffered = buffer_split
  46. yield item
  47. if buffered:
  48. try:
  49. yield decoder(buffered)
  50. except ValueError:
  51. log.error(
  52. 'Compose tried parsing the following chunk as a JSON object, '
  53. 'but failed:\n%s' % repr(buffered)
  54. )
  55. raise
  56. def json_splitter(buffer):
  57. """Attempt to parse a json object from a buffer. If there is at least one
  58. object, return it and the rest of the buffer, otherwise return None.
  59. """
  60. buffer = buffer.strip()
  61. try:
  62. obj, index = json_decoder.raw_decode(buffer)
  63. rest = buffer[json.decoder.WHITESPACE.match(buffer, index).end():]
  64. return obj, rest
  65. except ValueError:
  66. return None
  67. def json_stream(stream):
  68. """Given a stream of text, return a stream of json objects.
  69. This handles streams which are inconsistently buffered (some entries may
  70. be newline delimited, and others are not).
  71. """
  72. return split_buffer(stream, json_splitter, json_decoder.decode)
  73. def json_hash(obj):
  74. dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
  75. h = hashlib.sha256()
  76. h.update(dump.encode('utf8'))
  77. return h.hexdigest()
  78. def microseconds_from_time_nano(time_nano):
  79. return int(time_nano % 1000000000 / 1000)
  80. def build_string_dict(source_dict):
  81. return dict((k, str(v if v is not None else '')) for k, v in source_dict.items())