container.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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_running:
  83. return 'Ghost' if self.get('State.Ghost') else 'Up'
  84. else:
  85. return 'Exit %s' % self.get('State.ExitCode')
  86. @property
  87. def human_readable_command(self):
  88. entrypoint = self.get('Config.Entrypoint') or []
  89. cmd = self.get('Config.Cmd') or []
  90. return ' '.join(entrypoint + cmd)
  91. @property
  92. def environment(self):
  93. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  94. @property
  95. def is_running(self):
  96. return self.get('State.Running')
  97. def get(self, key):
  98. """Return a value from the container or None if the value is not set.
  99. :param key: a string using dotted notation for nested dictionary
  100. lookups
  101. """
  102. self.inspect_if_not_inspected()
  103. def get_value(dictionary, key):
  104. return (dictionary or {}).get(key)
  105. return reduce(get_value, key.split('.'), self.dictionary)
  106. def get_local_port(self, port, protocol='tcp'):
  107. port = self.ports.get("%s/%s" % (port, protocol))
  108. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  109. def start(self, **options):
  110. return self.client.start(self.id, **options)
  111. def stop(self, **options):
  112. return self.client.stop(self.id, **options)
  113. def kill(self, **options):
  114. return self.client.kill(self.id, **options)
  115. def restart(self, **options):
  116. return self.client.restart(self.id, **options)
  117. def remove(self, **options):
  118. return self.client.remove_container(self.id, **options)
  119. def inspect_if_not_inspected(self):
  120. if not self.has_been_inspected:
  121. self.inspect()
  122. def wait(self):
  123. return self.client.wait(self.id)
  124. def logs(self, *args, **kwargs):
  125. return self.client.logs(self.id, *args, **kwargs)
  126. def inspect(self):
  127. self.dictionary = self.client.inspect_container(self.id)
  128. self.has_been_inspected = True
  129. return self.dictionary
  130. # TODO: only used by tests, move to test module
  131. def links(self):
  132. links = []
  133. for container in self.client.containers():
  134. for name in container['Names']:
  135. bits = name.split('/')
  136. if len(bits) > 2 and bits[1] == self.name:
  137. links.append(bits[2])
  138. return links
  139. def attach(self, *args, **kwargs):
  140. return self.client.attach(self.id, *args, **kwargs)
  141. def attach_socket(self, **kwargs):
  142. return self.client.attach_socket(self.id, **kwargs)
  143. def __repr__(self):
  144. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  145. def __eq__(self, other):
  146. if type(self) != type(other):
  147. return False
  148. return self.id == other.id
  149. def __hash__(self):
  150. return self.id.__hash__()
  151. def get_container_name(container):
  152. if not container.get('Name') and not container.get('Names'):
  153. return None
  154. # inspect
  155. if 'Name' in container:
  156. return container['Name']
  157. # ps
  158. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  159. return shortest_name.split('/')[-1]