utils.py 3.5 KB

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