container.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. def get(self, key):
  112. """Return a value from the container or None if the value is not set.
  113. :param key: a string using dotted notation for nested dictionary
  114. lookups
  115. """
  116. self.inspect_if_not_inspected()
  117. def get_value(dictionary, key):
  118. return (dictionary or {}).get(key)
  119. return reduce(get_value, key.split('.'), self.dictionary)
  120. def get_local_port(self, port, protocol='tcp'):
  121. port = self.ports.get("%s/%s" % (port, protocol))
  122. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  123. def start(self, **options):
  124. return self.client.start(self.id, **options)
  125. def stop(self, **options):
  126. return self.client.stop(self.id, **options)
  127. def pause(self, **options):
  128. return self.client.pause(self.id, **options)
  129. def unpause(self, **options):
  130. return self.client.unpause(self.id, **options)
  131. def kill(self, **options):
  132. return self.client.kill(self.id, **options)
  133. def restart(self, **options):
  134. return self.client.restart(self.id, **options)
  135. def remove(self, **options):
  136. return self.client.remove_container(self.id, **options)
  137. def inspect_if_not_inspected(self):
  138. if not self.has_been_inspected:
  139. self.inspect()
  140. def wait(self):
  141. return self.client.wait(self.id)
  142. def logs(self, *args, **kwargs):
  143. return self.client.logs(self.id, *args, **kwargs)
  144. def inspect(self):
  145. self.dictionary = self.client.inspect_container(self.id)
  146. self.has_been_inspected = True
  147. return self.dictionary
  148. # TODO: only used by tests, move to test module
  149. def links(self):
  150. links = []
  151. for container in self.client.containers():
  152. for name in container['Names']:
  153. bits = name.split('/')
  154. if len(bits) > 2 and bits[1] == self.name:
  155. links.append(bits[2])
  156. return links
  157. def attach(self, *args, **kwargs):
  158. return self.client.attach(self.id, *args, **kwargs)
  159. def attach_socket(self, **kwargs):
  160. return self.client.attach_socket(self.id, **kwargs)
  161. def __repr__(self):
  162. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  163. def __eq__(self, other):
  164. if type(self) != type(other):
  165. return False
  166. return self.id == other.id
  167. def __hash__(self):
  168. return self.id.__hash__()
  169. def get_container_name(container):
  170. if not container.get('Name') and not container.get('Names'):
  171. return None
  172. # inspect
  173. if 'Name' in container:
  174. return container['Name']
  175. # ps
  176. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  177. return shortest_name.split('/')[-1]