container.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. from functools import reduce
  4. import six
  5. from docker.errors import ImageNotFound
  6. from .const import LABEL_CONTAINER_NUMBER
  7. from .const import LABEL_PROJECT
  8. from .const import LABEL_SERVICE
  9. from .const import LABEL_VERSION
  10. from .version import ComposeVersion
  11. class Container(object):
  12. """
  13. Represents a Docker container, constructed from the output of
  14. GET /containers/:id:/json.
  15. """
  16. def __init__(self, client, dictionary, has_been_inspected=False):
  17. self.client = client
  18. self.dictionary = dictionary
  19. self.has_been_inspected = has_been_inspected
  20. self.log_stream = None
  21. @classmethod
  22. def from_ps(cls, client, dictionary, **kwargs):
  23. """
  24. Construct a container object from the output of GET /containers/json.
  25. """
  26. name = get_container_name(dictionary)
  27. if name is None:
  28. return None
  29. new_dictionary = {
  30. 'Id': dictionary['Id'],
  31. 'Image': dictionary['Image'],
  32. 'Name': '/' + name,
  33. }
  34. return cls(client, new_dictionary, **kwargs)
  35. @classmethod
  36. def from_id(cls, client, id):
  37. return cls(client, client.inspect_container(id), has_been_inspected=True)
  38. @classmethod
  39. def create(cls, client, **options):
  40. response = client.create_container(**options)
  41. return cls.from_id(client, response['Id'])
  42. @property
  43. def id(self):
  44. return self.dictionary['Id']
  45. @property
  46. def image(self):
  47. return self.dictionary['Image']
  48. @property
  49. def image_config(self):
  50. return self.client.inspect_image(self.image)
  51. @property
  52. def short_id(self):
  53. return self.id[:12]
  54. @property
  55. def name(self):
  56. return self.dictionary['Name'][1:]
  57. @property
  58. def project(self):
  59. return self.labels.get(LABEL_PROJECT)
  60. @property
  61. def service(self):
  62. return self.labels.get(LABEL_SERVICE)
  63. @property
  64. def name_without_project(self):
  65. if self.name.startswith('{0}_{1}'.format(self.project, self.service)):
  66. return '{0}_{1}'.format(self.service, self.number)
  67. else:
  68. return self.name
  69. @property
  70. def number(self):
  71. number = self.labels.get(LABEL_CONTAINER_NUMBER)
  72. if not number:
  73. raise ValueError("Container {0} does not have a {1} label".format(
  74. self.short_id, LABEL_CONTAINER_NUMBER))
  75. return int(number)
  76. @property
  77. def ports(self):
  78. self.inspect_if_not_inspected()
  79. return self.get('NetworkSettings.Ports') or {}
  80. @property
  81. def human_readable_ports(self):
  82. def format_port(private, public):
  83. if not public:
  84. return [private]
  85. return [
  86. '{HostIp}:{HostPort}->{private}'.format(private=private, **pub)
  87. for pub in public
  88. ]
  89. return ', '.join(
  90. ','.join(format_port(*item))
  91. for item in sorted(six.iteritems(self.ports))
  92. )
  93. @property
  94. def labels(self):
  95. return self.get('Config.Labels') or {}
  96. @property
  97. def stop_signal(self):
  98. return self.get('Config.StopSignal')
  99. @property
  100. def log_config(self):
  101. return self.get('HostConfig.LogConfig') or None
  102. @property
  103. def human_readable_state(self):
  104. if self.is_paused:
  105. return 'Paused'
  106. if self.is_restarting:
  107. return 'Restarting'
  108. if self.is_running:
  109. return 'Ghost' if self.get('State.Ghost') else self.human_readable_health_status
  110. else:
  111. return 'Exit %s' % self.get('State.ExitCode')
  112. @property
  113. def human_readable_command(self):
  114. entrypoint = self.get('Config.Entrypoint') or []
  115. cmd = self.get('Config.Cmd') or []
  116. return ' '.join(entrypoint + cmd)
  117. @property
  118. def environment(self):
  119. def parse_env(var):
  120. if '=' in var:
  121. return var.split("=", 1)
  122. return var, None
  123. return dict(parse_env(var) for var in self.get('Config.Env') or [])
  124. @property
  125. def exit_code(self):
  126. return self.get('State.ExitCode')
  127. @property
  128. def is_running(self):
  129. return self.get('State.Running')
  130. @property
  131. def is_restarting(self):
  132. return self.get('State.Restarting')
  133. @property
  134. def is_paused(self):
  135. return self.get('State.Paused')
  136. @property
  137. def log_driver(self):
  138. return self.get('HostConfig.LogConfig.Type')
  139. @property
  140. def has_api_logs(self):
  141. log_type = self.log_driver
  142. return not log_type or log_type in ('json-file', 'journald')
  143. @property
  144. def human_readable_health_status(self):
  145. """ Generate UP status string with up time and health
  146. """
  147. status_string = 'Up'
  148. container_status = self.get('State.Health.Status')
  149. if container_status == 'starting':
  150. status_string += ' (health: starting)'
  151. elif container_status is not None:
  152. status_string += ' (%s)' % container_status
  153. return status_string
  154. def attach_log_stream(self):
  155. """A log stream can only be attached if the container uses a json-file
  156. log driver.
  157. """
  158. if self.has_api_logs:
  159. self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
  160. def get(self, key):
  161. """Return a value from the container or None if the value is not set.
  162. :param key: a string using dotted notation for nested dictionary
  163. lookups
  164. """
  165. self.inspect_if_not_inspected()
  166. def get_value(dictionary, key):
  167. return (dictionary or {}).get(key)
  168. return reduce(get_value, key.split('.'), self.dictionary)
  169. def get_local_port(self, port, protocol='tcp'):
  170. port = self.ports.get("%s/%s" % (port, protocol))
  171. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  172. def get_mount(self, mount_dest):
  173. for mount in self.get('Mounts'):
  174. if mount['Destination'] == mount_dest:
  175. return mount
  176. return None
  177. def start(self, **options):
  178. return self.client.start(self.id, **options)
  179. def stop(self, **options):
  180. return self.client.stop(self.id, **options)
  181. def pause(self, **options):
  182. return self.client.pause(self.id, **options)
  183. def unpause(self, **options):
  184. return self.client.unpause(self.id, **options)
  185. def kill(self, **options):
  186. return self.client.kill(self.id, **options)
  187. def restart(self, **options):
  188. return self.client.restart(self.id, **options)
  189. def remove(self, **options):
  190. return self.client.remove_container(self.id, **options)
  191. def create_exec(self, command, **options):
  192. return self.client.exec_create(self.id, command, **options)
  193. def start_exec(self, exec_id, **options):
  194. return self.client.exec_start(exec_id, **options)
  195. def rename_to_tmp_name(self):
  196. """Rename the container to a hopefully unique temporary container name
  197. by prepending the short id.
  198. """
  199. if not self.name.startswith(self.short_id):
  200. self.client.rename(
  201. self.id, '{0}_{1}'.format(self.short_id, self.name)
  202. )
  203. def inspect_if_not_inspected(self):
  204. if not self.has_been_inspected:
  205. self.inspect()
  206. def wait(self):
  207. return self.client.wait(self.id).get('StatusCode', 127)
  208. def logs(self, *args, **kwargs):
  209. return self.client.logs(self.id, *args, **kwargs)
  210. def inspect(self):
  211. self.dictionary = self.client.inspect_container(self.id)
  212. self.has_been_inspected = True
  213. return self.dictionary
  214. def image_exists(self):
  215. try:
  216. self.client.inspect_image(self.image)
  217. except ImageNotFound:
  218. return False
  219. return True
  220. def reset_image(self, img_id):
  221. """ If this container's image has been removed, temporarily replace the old image ID
  222. with `img_id`.
  223. """
  224. if not self.image_exists():
  225. self.dictionary['Image'] = img_id
  226. def attach(self, *args, **kwargs):
  227. return self.client.attach(self.id, *args, **kwargs)
  228. def has_legacy_proj_name(self, project_name):
  229. return (
  230. ComposeVersion(self.labels.get(LABEL_VERSION)) < ComposeVersion('1.21.0') and
  231. self.project != project_name
  232. )
  233. def __repr__(self):
  234. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  235. def __eq__(self, other):
  236. if type(self) != type(other):
  237. return False
  238. return self.id == other.id
  239. def __hash__(self):
  240. return self.id.__hash__()
  241. def get_container_name(container):
  242. if not container.get('Name') and not container.get('Names'):
  243. return None
  244. # inspect
  245. if 'Name' in container:
  246. return container['Name']
  247. # ps
  248. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  249. return shortest_name.split('/')[-1]