container.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. from functools import reduce
  4. import six
  5. from .const import LABEL_CONTAINER_NUMBER
  6. from .const import LABEL_PROJECT
  7. from .const import LABEL_SERVICE
  8. class Container(object):
  9. """
  10. Represents a Docker container, constructed from the output of
  11. GET /containers/:id:/json.
  12. """
  13. def __init__(self, client, dictionary, has_been_inspected=False):
  14. self.client = client
  15. self.dictionary = dictionary
  16. self.has_been_inspected = has_been_inspected
  17. self.log_stream = None
  18. @classmethod
  19. def from_ps(cls, client, dictionary, **kwargs):
  20. """
  21. Construct a container object from the output of GET /containers/json.
  22. """
  23. name = get_container_name(dictionary)
  24. if name is None:
  25. return None
  26. new_dictionary = {
  27. 'Id': dictionary['Id'],
  28. 'Image': dictionary['Image'],
  29. 'Name': '/' + name,
  30. }
  31. return cls(client, new_dictionary, **kwargs)
  32. @classmethod
  33. def from_id(cls, client, id):
  34. return cls(client, client.inspect_container(id))
  35. @classmethod
  36. def create(cls, client, **options):
  37. response = client.create_container(**options)
  38. return cls.from_id(client, response['Id'])
  39. @property
  40. def id(self):
  41. return self.dictionary['Id']
  42. @property
  43. def image(self):
  44. return self.dictionary['Image']
  45. @property
  46. def image_config(self):
  47. return self.client.inspect_image(self.image)
  48. @property
  49. def short_id(self):
  50. return self.id[:10]
  51. @property
  52. def name(self):
  53. return self.dictionary['Name'][1:]
  54. @property
  55. def service(self):
  56. return self.labels.get(LABEL_SERVICE)
  57. @property
  58. def name_without_project(self):
  59. project = self.labels.get(LABEL_PROJECT)
  60. if self.name.startswith('{0}_{1}'.format(project, self.service)):
  61. return '{0}_{1}'.format(self.service, self.number)
  62. else:
  63. return self.name
  64. @property
  65. def number(self):
  66. number = self.labels.get(LABEL_CONTAINER_NUMBER)
  67. if not number:
  68. raise ValueError("Container {0} does not have a {1} label".format(
  69. self.short_id, LABEL_CONTAINER_NUMBER))
  70. return int(number)
  71. @property
  72. def ports(self):
  73. self.inspect_if_not_inspected()
  74. return self.get('NetworkSettings.Ports') or {}
  75. @property
  76. def human_readable_ports(self):
  77. def format_port(private, public):
  78. if not public:
  79. return private
  80. return '{HostIp}:{HostPort}->{private}'.format(
  81. private=private, **public[0])
  82. return ', '.join(format_port(*item)
  83. for item in sorted(six.iteritems(self.ports)))
  84. @property
  85. def labels(self):
  86. return self.get('Config.Labels') or {}
  87. @property
  88. def log_config(self):
  89. return self.get('HostConfig.LogConfig') or None
  90. @property
  91. def human_readable_state(self):
  92. if self.is_paused:
  93. return 'Paused'
  94. if self.is_restarting:
  95. return 'Restarting'
  96. if self.is_running:
  97. return 'Ghost' if self.get('State.Ghost') else 'Up'
  98. else:
  99. return 'Exit %s' % self.get('State.ExitCode')
  100. @property
  101. def human_readable_command(self):
  102. entrypoint = self.get('Config.Entrypoint') or []
  103. cmd = self.get('Config.Cmd') or []
  104. return ' '.join(entrypoint + cmd)
  105. @property
  106. def environment(self):
  107. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  108. @property
  109. def is_running(self):
  110. return self.get('State.Running')
  111. @property
  112. def is_restarting(self):
  113. return self.get('State.Restarting')
  114. @property
  115. def is_paused(self):
  116. return self.get('State.Paused')
  117. @property
  118. def log_driver(self):
  119. return self.get('HostConfig.LogConfig.Type')
  120. @property
  121. def has_api_logs(self):
  122. log_type = self.log_driver
  123. return not log_type or log_type != 'none'
  124. def attach_log_stream(self):
  125. """A log stream can only be attached if the container uses a json-file
  126. log driver.
  127. """
  128. if self.has_api_logs:
  129. self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
  130. def get(self, key):
  131. """Return a value from the container or None if the value is not set.
  132. :param key: a string using dotted notation for nested dictionary
  133. lookups
  134. """
  135. self.inspect_if_not_inspected()
  136. def get_value(dictionary, key):
  137. return (dictionary or {}).get(key)
  138. return reduce(get_value, key.split('.'), self.dictionary)
  139. def get_local_port(self, port, protocol='tcp'):
  140. port = self.ports.get("%s/%s" % (port, protocol))
  141. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  142. def start(self, **options):
  143. return self.client.start(self.id, **options)
  144. def stop(self, **options):
  145. return self.client.stop(self.id, **options)
  146. def pause(self, **options):
  147. return self.client.pause(self.id, **options)
  148. def unpause(self, **options):
  149. return self.client.unpause(self.id, **options)
  150. def kill(self, **options):
  151. return self.client.kill(self.id, **options)
  152. def restart(self, **options):
  153. return self.client.restart(self.id, **options)
  154. def remove(self, **options):
  155. return self.client.remove_container(self.id, **options)
  156. def rename_to_tmp_name(self):
  157. """Rename the container to a hopefully unique temporary container name
  158. by prepending the short id.
  159. """
  160. self.client.rename(
  161. self.id,
  162. '%s_%s' % (self.short_id, self.name)
  163. )
  164. def inspect_if_not_inspected(self):
  165. if not self.has_been_inspected:
  166. self.inspect()
  167. def wait(self):
  168. return self.client.wait(self.id)
  169. def logs(self, *args, **kwargs):
  170. return self.client.logs(self.id, *args, **kwargs)
  171. def inspect(self):
  172. self.dictionary = self.client.inspect_container(self.id)
  173. self.has_been_inspected = True
  174. return self.dictionary
  175. # TODO: only used by tests, move to test module
  176. def links(self):
  177. links = []
  178. for container in self.client.containers():
  179. for name in container['Names']:
  180. bits = name.split('/')
  181. if len(bits) > 2 and bits[1] == self.name:
  182. links.append(bits[2])
  183. return links
  184. def attach(self, *args, **kwargs):
  185. return self.client.attach(self.id, *args, **kwargs)
  186. def __repr__(self):
  187. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  188. def __eq__(self, other):
  189. if type(self) != type(other):
  190. return False
  191. return self.id == other.id
  192. def __hash__(self):
  193. return self.id.__hash__()
  194. def get_container_name(container):
  195. if not container.get('Name') and not container.get('Names'):
  196. return None
  197. # inspect
  198. if 'Name' in container:
  199. return container['Name']
  200. # ps
  201. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  202. return shortest_name.split('/')[-1]