container.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. from six import iteritems
  4. from six.moves import reduce
  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 name_without_project(self):
  54. return '{0}_{1}'.format(self.labels.get(LABEL_SERVICE), self.number)
  55. @property
  56. def number(self):
  57. number = self.labels.get(LABEL_CONTAINER_NUMBER)
  58. if not number:
  59. raise ValueError("Container {0} does not have a {1} label".format(
  60. self.short_id, LABEL_CONTAINER_NUMBER))
  61. return int(number)
  62. @property
  63. def ports(self):
  64. self.inspect_if_not_inspected()
  65. return self.get('NetworkSettings.Ports') or {}
  66. @property
  67. def human_readable_ports(self):
  68. def format_port(private, public):
  69. if not public:
  70. return private
  71. return '{HostIp}:{HostPort}->{private}'.format(
  72. private=private, **public[0])
  73. return ', '.join(format_port(*item)
  74. for item in sorted(iteritems(self.ports)))
  75. @property
  76. def labels(self):
  77. return self.get('Config.Labels') or {}
  78. @property
  79. def log_config(self):
  80. return self.get('HostConfig.LogConfig') or None
  81. @property
  82. def human_readable_state(self):
  83. if self.is_paused:
  84. return 'Paused'
  85. if self.is_running:
  86. return 'Ghost' if self.get('State.Ghost') else 'Up'
  87. else:
  88. return 'Exit %s' % self.get('State.ExitCode')
  89. @property
  90. def human_readable_command(self):
  91. entrypoint = self.get('Config.Entrypoint') or []
  92. cmd = self.get('Config.Cmd') or []
  93. return ' '.join(entrypoint + cmd)
  94. @property
  95. def environment(self):
  96. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  97. @property
  98. def is_running(self):
  99. return self.get('State.Running')
  100. @property
  101. def is_paused(self):
  102. return self.get('State.Paused')
  103. def get(self, key):
  104. """Return a value from the container or None if the value is not set.
  105. :param key: a string using dotted notation for nested dictionary
  106. lookups
  107. """
  108. self.inspect_if_not_inspected()
  109. def get_value(dictionary, key):
  110. return (dictionary or {}).get(key)
  111. return reduce(get_value, key.split('.'), self.dictionary)
  112. def get_local_port(self, port, protocol='tcp'):
  113. port = self.ports.get("%s/%s" % (port, protocol))
  114. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  115. def start(self, **options):
  116. return self.client.start(self.id, **options)
  117. def stop(self, **options):
  118. return self.client.stop(self.id, **options)
  119. def pause(self, **options):
  120. return self.client.pause(self.id, **options)
  121. def unpause(self, **options):
  122. return self.client.unpause(self.id, **options)
  123. def kill(self, **options):
  124. return self.client.kill(self.id, **options)
  125. def restart(self, **options):
  126. return self.client.restart(self.id, **options)
  127. def remove(self, **options):
  128. return self.client.remove_container(self.id, **options)
  129. def inspect_if_not_inspected(self):
  130. if not self.has_been_inspected:
  131. self.inspect()
  132. def wait(self):
  133. return self.client.wait(self.id)
  134. def logs(self, *args, **kwargs):
  135. return self.client.logs(self.id, *args, **kwargs)
  136. def inspect(self):
  137. self.dictionary = self.client.inspect_container(self.id)
  138. self.has_been_inspected = True
  139. return self.dictionary
  140. # TODO: only used by tests, move to test module
  141. def links(self):
  142. links = []
  143. for container in self.client.containers():
  144. for name in container['Names']:
  145. bits = name.split('/')
  146. if len(bits) > 2 and bits[1] == self.name:
  147. links.append(bits[2])
  148. return links
  149. def attach(self, *args, **kwargs):
  150. return self.client.attach(self.id, *args, **kwargs)
  151. def attach_socket(self, **kwargs):
  152. return self.client.attach_socket(self.id, **kwargs)
  153. def __repr__(self):
  154. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  155. def __eq__(self, other):
  156. if type(self) != type(other):
  157. return False
  158. return self.id == other.id
  159. def __hash__(self):
  160. return self.id.__hash__()
  161. def get_container_name(container):
  162. if not container.get('Name') and not container.get('Names'):
  163. return None
  164. # inspect
  165. if 'Name' in container:
  166. return container['Name']
  167. # ps
  168. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  169. return shortest_name.split('/')[-1]