container.py 6.2 KB

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