utils.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import codecs
  4. import hashlib
  5. import json.decoder
  6. import logging
  7. import ntpath
  8. import random
  9. import six
  10. from docker.errors import DockerException
  11. from docker.utils import parse_bytes as sdk_parse_bytes
  12. from .errors import StreamParseError
  13. from .timeparse import MULTIPLIERS
  14. from .timeparse import timeparse
  15. json_decoder = json.JSONDecoder()
  16. log = logging.getLogger(__name__)
  17. def get_output_stream(stream):
  18. if six.PY3:
  19. return stream
  20. return codecs.getwriter('utf-8')(stream)
  21. def stream_as_text(stream):
  22. """Given a stream of bytes or text, if any of the items in the stream
  23. are bytes convert them to text.
  24. This function can be removed once docker-py returns text streams instead
  25. of byte streams.
  26. """
  27. for data in stream:
  28. if not isinstance(data, six.text_type):
  29. data = data.decode('utf-8', 'replace')
  30. yield data
  31. def line_splitter(buffer, separator=u'\n'):
  32. index = buffer.find(six.text_type(separator))
  33. if index == -1:
  34. return None
  35. return buffer[:index + 1], buffer[index + 1:]
  36. def split_buffer(stream, splitter=None, decoder=lambda a: a):
  37. """Given a generator which yields strings and a splitter function,
  38. joins all input, splits on the separator and yields each chunk.
  39. Unlike string.split(), each chunk includes the trailing
  40. separator, except for the last one if none was found on the end
  41. of the input.
  42. """
  43. splitter = splitter or line_splitter
  44. buffered = six.text_type('')
  45. for data in stream_as_text(stream):
  46. buffered += data
  47. while True:
  48. buffer_split = splitter(buffered)
  49. if buffer_split is None:
  50. break
  51. item, buffered = buffer_split
  52. yield item
  53. if buffered:
  54. try:
  55. yield decoder(buffered)
  56. except Exception as e:
  57. log.error(
  58. 'Compose tried decoding the following data chunk, but failed:'
  59. '\n%s' % repr(buffered)
  60. )
  61. raise StreamParseError(e)
  62. def json_splitter(buffer):
  63. """Attempt to parse a json object from a buffer. If there is at least one
  64. object, return it and the rest of the buffer, otherwise return None.
  65. """
  66. buffer = buffer.strip()
  67. try:
  68. obj, index = json_decoder.raw_decode(buffer)
  69. rest = buffer[json.decoder.WHITESPACE.match(buffer, index).end():]
  70. return obj, rest
  71. except ValueError:
  72. return None
  73. def json_stream(stream):
  74. """Given a stream of text, return a stream of json objects.
  75. This handles streams which are inconsistently buffered (some entries may
  76. be newline delimited, and others are not).
  77. """
  78. return split_buffer(stream, json_splitter, json_decoder.decode)
  79. def json_hash(obj):
  80. dump = json.dumps(obj, sort_keys=True, separators=(',', ':'), default=lambda x: x.repr())
  81. h = hashlib.sha256()
  82. h.update(dump.encode('utf8'))
  83. return h.hexdigest()
  84. def microseconds_from_time_nano(time_nano):
  85. return int(time_nano % 1000000000 / 1000)
  86. def nanoseconds_from_time_seconds(time_seconds):
  87. return int(time_seconds / MULTIPLIERS['nano'])
  88. def parse_seconds_float(value):
  89. return timeparse(value or '')
  90. def parse_nanoseconds_int(value):
  91. parsed = timeparse(value or '')
  92. if parsed is None:
  93. return None
  94. return nanoseconds_from_time_seconds(parsed)
  95. def build_string_dict(source_dict):
  96. return dict((k, str(v if v is not None else '')) for k, v in source_dict.items())
  97. def splitdrive(path):
  98. if len(path) == 0:
  99. return ('', '')
  100. if path[0] in ['.', '\\', '/', '~']:
  101. return ('', path)
  102. return ntpath.splitdrive(path)
  103. def parse_bytes(n):
  104. try:
  105. return sdk_parse_bytes(n)
  106. except DockerException:
  107. return None
  108. def unquote_path(s):
  109. if not s:
  110. return s
  111. if s[0] == '"' and s[-1] == '"':
  112. return s[1:-1]
  113. return s
  114. def generate_random_id():
  115. while True:
  116. val = hex(random.getrandbits(32 * 8))[2:-1]
  117. try:
  118. int(truncate_id(val))
  119. continue
  120. except ValueError:
  121. return val
  122. def truncate_id(value):
  123. if ':' in value:
  124. value = value[value.index(':') + 1:]
  125. if len(value) > 12:
  126. return value[:12]
  127. return value
  128. def unique_everseen(iterable, key=lambda x: x):
  129. "List unique elements, preserving order. Remember all elements ever seen."
  130. seen = set()
  131. for element in iterable:
  132. unique_key = key(element)
  133. if unique_key not in seen:
  134. seen.add(unique_key)
  135. yield element
  136. def truncate_string(s, max_chars=35):
  137. if len(s) > max_chars:
  138. return s[:max_chars - 2] + '...'
  139. return s