container.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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[:12]
  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 stop_signal(self):
  89. return self.get('Config.StopSignal')
  90. @property
  91. def log_config(self):
  92. return self.get('HostConfig.LogConfig') or None
  93. @property
  94. def human_readable_state(self):
  95. if self.is_paused:
  96. return 'Paused'
  97. if self.is_restarting:
  98. return 'Restarting'
  99. if self.is_running:
  100. return 'Ghost' if self.get('State.Ghost') else 'Up'
  101. else:
  102. return 'Exit %s' % self.get('State.ExitCode')
  103. @property
  104. def human_readable_command(self):
  105. entrypoint = self.get('Config.Entrypoint') or []
  106. cmd = self.get('Config.Cmd') or []
  107. return ' '.join(entrypoint + cmd)
  108. @property
  109. def environment(self):
  110. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  111. @property
  112. def exit_code(self):
  113. return self.get('State.ExitCode')
  114. @property
  115. def is_running(self):
  116. return self.get('State.Running')
  117. @property
  118. def is_restarting(self):
  119. return self.get('State.Restarting')
  120. @property
  121. def is_paused(self):
  122. return self.get('State.Paused')
  123. @property
  124. def log_driver(self):
  125. return self.get('HostConfig.LogConfig.Type')
  126. @property
  127. def has_api_logs(self):
  128. log_type = self.log_driver
  129. return not log_type or log_type != 'none'
  130. def attach_log_stream(self):
  131. """A log stream can only be attached if the container uses a json-file
  132. log driver.
  133. """
  134. if self.has_api_logs:
  135. self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
  136. def get(self, key):
  137. """Return a value from the container or None if the value is not set.
  138. :param key: a string using dotted notation for nested dictionary
  139. lookups
  140. """
  141. self.inspect_if_not_inspected()
  142. def get_value(dictionary, key):
  143. return (dictionary or {}).get(key)
  144. return reduce(get_value, key.split('.'), self.dictionary)
  145. def get_local_port(self, port, protocol='tcp'):
  146. port = self.ports.get("%s/%s" % (port, protocol))
  147. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  148. def get_mount(self, mount_dest):
  149. for mount in self.get('Mounts'):
  150. if mount['Destination'] == mount_dest:
  151. return mount
  152. return None
  153. def start(self, **options):
  154. return self.client.start(self.id, **options)
  155. def stop(self, **options):
  156. return self.client.stop(self.id, **options)
  157. def pause(self, **options):
  158. return self.client.pause(self.id, **options)
  159. def unpause(self, **options):
  160. return self.client.unpause(self.id, **options)
  161. def kill(self, **options):
  162. return self.client.kill(self.id, **options)
  163. def restart(self, **options):
  164. return self.client.restart(self.id, **options)
  165. def remove(self, **options):
  166. return self.client.remove_container(self.id, **options)
  167. def rename_to_tmp_name(self):
  168. """Rename the container to a hopefully unique temporary container name
  169. by prepending the short id.
  170. """
  171. self.client.rename(
  172. self.id,
  173. '%s_%s' % (self.short_id, self.name)
  174. )
  175. def inspect_if_not_inspected(self):
  176. if not self.has_been_inspected:
  177. self.inspect()
  178. def wait(self):
  179. return self.client.wait(self.id)
  180. def logs(self, *args, **kwargs):
  181. return self.client.logs(self.id, *args, **kwargs)
  182. def inspect(self):
  183. self.dictionary = self.client.inspect_container(self.id)
  184. self.has_been_inspected = True
  185. return self.dictionary
  186. def attach(self, *args, **kwargs):
  187. return self.client.attach(self.id, *args, **kwargs)
  188. def __repr__(self):
  189. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  190. def __eq__(self, other):
  191. if type(self) != type(other):
  192. return False
  193. return self.id == other.id
  194. def __hash__(self):
  195. return self.id.__hash__()
  196. def get_container_name(container):
  197. if not container.get('Name') and not container.get('Names'):
  198. return None
  199. # inspect
  200. if 'Name' in container:
  201. return container['Name']
  202. # ps
  203. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  204. return shortest_name.split('/')[-1]