container.py 9.3 KB

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