utils.py 3.0 KB

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