container.py 6.6 KB

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