container.py 7.1 KB

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