container.py 7.5 KB

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