container.py 6.1 KB

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