utils.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import hashlib
  2. import json.decoder
  3. import logging
  4. import ntpath
  5. import random
  6. from docker.errors import DockerException
  7. from docker.utils import parse_bytes as sdk_parse_bytes
  8. from .errors import StreamParseError
  9. from .timeparse import MULTIPLIERS
  10. from .timeparse import timeparse
  11. json_decoder = json.JSONDecoder()
  12. log = logging.getLogger(__name__)
  13. def get_output_stream(stream):
  14. return 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, str):
  23. data = data.decode('utf-8', 'replace')
  24. yield data
  25. def line_splitter(buffer, separator=u'\n'):
  26. index = buffer.find(str(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 = str('')
  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 Exception as e:
  51. log.error(
  52. 'Compose tried decoding the following data chunk, but failed:'
  53. '\n%s' % repr(buffered)
  54. )
  55. raise StreamParseError(e)
  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=(',', ':'), default=lambda x: x.repr())
  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 nanoseconds_from_time_seconds(time_seconds):
  81. return int(time_seconds / MULTIPLIERS['nano'])
  82. def parse_seconds_float(value):
  83. return timeparse(value or '')
  84. def parse_nanoseconds_int(value):
  85. parsed = timeparse(value or '')
  86. if parsed is None:
  87. return None
  88. return nanoseconds_from_time_seconds(parsed)
  89. def build_string_dict(source_dict):
  90. return dict((k, str(v if v is not None else '')) for k, v in source_dict.items())
  91. def splitdrive(path):
  92. if len(path) == 0:
  93. return ('', '')
  94. if path[0] in ['.', '\\', '/', '~']:
  95. return ('', path)
  96. return ntpath.splitdrive(path)
  97. def parse_bytes(n):
  98. try:
  99. return sdk_parse_bytes(n)
  100. except DockerException:
  101. return None
  102. def unquote_path(s):
  103. if not s:
  104. return s
  105. if s[0] == '"' and s[-1] == '"':
  106. return s[1:-1]
  107. return s
  108. def generate_random_id():
  109. while True:
  110. val = hex(random.getrandbits(32 * 8))[2:-1]
  111. try:
  112. int(truncate_id(val))
  113. continue
  114. except ValueError:
  115. return val
  116. def truncate_id(value):
  117. if ':' in value:
  118. value = value[value.index(':') + 1:]
  119. if len(value) > 12:
  120. return value[:12]
  121. return value
  122. def unique_everseen(iterable, key=lambda x: x):
  123. "List unique elements, preserving order. Remember all elements ever seen."
  124. seen = set()
  125. for element in iterable:
  126. unique_key = key(element)
  127. if unique_key not in seen:
  128. seen.add(unique_key)
  129. yield element
  130. def truncate_string(s, max_chars=35):
  131. if len(s) > max_chars:
  132. return s[:max_chars - 2] + '...'
  133. return s