utils.py 3.2 KB

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