container.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. return truncate_id(self.full_slug)
  81. @property
  82. def full_slug(self):
  83. return self.labels.get(LABEL_SLUG)
  84. @property
  85. def ports(self):
  86. self.inspect_if_not_inspected()
  87. return self.get('NetworkSettings.Ports') or {}
  88. @property
  89. def human_readable_ports(self):
  90. def format_port(private, public):
  91. if not public:
  92. return [private]
  93. return [
  94. '{HostIp}:{HostPort}->{private}'.format(private=private, **pub)
  95. for pub in public
  96. ]
  97. return ', '.join(
  98. ','.join(format_port(*item))
  99. for item in sorted(six.iteritems(self.ports))
  100. )
  101. @property
  102. def labels(self):
  103. return self.get('Config.Labels') or {}
  104. @property
  105. def stop_signal(self):
  106. return self.get('Config.StopSignal')
  107. @property
  108. def log_config(self):
  109. return self.get('HostConfig.LogConfig') or None
  110. @property
  111. def human_readable_state(self):
  112. if self.is_paused:
  113. return 'Paused'
  114. if self.is_restarting:
  115. return 'Restarting'
  116. if self.is_running:
  117. return 'Ghost' if self.get('State.Ghost') else self.human_readable_health_status
  118. else:
  119. return 'Exit %s' % self.get('State.ExitCode')
  120. @property
  121. def human_readable_command(self):
  122. entrypoint = self.get('Config.Entrypoint') or []
  123. cmd = self.get('Config.Cmd') or []
  124. return ' '.join(entrypoint + cmd)
  125. @property
  126. def environment(self):
  127. def parse_env(var):
  128. if '=' in var:
  129. return var.split("=", 1)
  130. return var, None
  131. return dict(parse_env(var) for var in self.get('Config.Env') or [])
  132. @property
  133. def exit_code(self):
  134. return self.get('State.ExitCode')
  135. @property
  136. def is_running(self):
  137. return self.get('State.Running')
  138. @property
  139. def is_restarting(self):
  140. return self.get('State.Restarting')
  141. @property
  142. def is_paused(self):
  143. return self.get('State.Paused')
  144. @property
  145. def log_driver(self):
  146. return self.get('HostConfig.LogConfig.Type')
  147. @property
  148. def has_api_logs(self):
  149. log_type = self.log_driver
  150. return not log_type or log_type in ('json-file', 'journald')
  151. @property
  152. def human_readable_health_status(self):
  153. """ Generate UP status string with up time and health
  154. """
  155. status_string = 'Up'
  156. container_status = self.get('State.Health.Status')
  157. if container_status == 'starting':
  158. status_string += ' (health: starting)'
  159. elif container_status is not None:
  160. status_string += ' (%s)' % container_status
  161. return status_string
  162. def attach_log_stream(self):
  163. """A log stream can only be attached if the container uses a json-file
  164. log driver.
  165. """
  166. if self.has_api_logs:
  167. self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
  168. def get(self, key):
  169. """Return a value from the container or None if the value is not set.
  170. :param key: a string using dotted notation for nested dictionary
  171. lookups
  172. """
  173. self.inspect_if_not_inspected()
  174. def get_value(dictionary, key):
  175. return (dictionary or {}).get(key)
  176. return reduce(get_value, key.split('.'), self.dictionary)
  177. def get_local_port(self, port, protocol='tcp'):
  178. port = self.ports.get("%s/%s" % (port, protocol))
  179. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  180. def get_mount(self, mount_dest):
  181. for mount in self.get('Mounts'):
  182. if mount['Destination'] == mount_dest:
  183. return mount
  184. return None
  185. def start(self, **options):
  186. return self.client.start(self.id, **options)
  187. def stop(self, **options):
  188. return self.client.stop(self.id, **options)
  189. def pause(self, **options):
  190. return self.client.pause(self.id, **options)
  191. def unpause(self, **options):
  192. return self.client.unpause(self.id, **options)
  193. def kill(self, **options):
  194. return self.client.kill(self.id, **options)
  195. def restart(self, **options):
  196. return self.client.restart(self.id, **options)
  197. def remove(self, **options):
  198. return self.client.remove_container(self.id, **options)
  199. def create_exec(self, command, **options):
  200. return self.client.exec_create(self.id, command, **options)
  201. def start_exec(self, exec_id, **options):
  202. return self.client.exec_start(exec_id, **options)
  203. def rename_to_tmp_name(self):
  204. """Rename the container to a hopefully unique temporary container name
  205. by prepending the short id.
  206. """
  207. if not self.name.startswith(self.short_id):
  208. self.client.rename(
  209. self.id, '{0}_{1}'.format(self.short_id, self.name)
  210. )
  211. def inspect_if_not_inspected(self):
  212. if not self.has_been_inspected:
  213. self.inspect()
  214. def wait(self):
  215. return self.client.wait(self.id).get('StatusCode', 127)
  216. def logs(self, *args, **kwargs):
  217. return self.client.logs(self.id, *args, **kwargs)
  218. def inspect(self):
  219. self.dictionary = self.client.inspect_container(self.id)
  220. self.has_been_inspected = True
  221. return self.dictionary
  222. def image_exists(self):
  223. try:
  224. self.client.inspect_image(self.image)
  225. except ImageNotFound:
  226. return False
  227. return True
  228. def reset_image(self, img_id):
  229. """ If this container's image has been removed, temporarily replace the old image ID
  230. with `img_id`.
  231. """
  232. if not self.image_exists():
  233. self.dictionary['Image'] = img_id
  234. def attach(self, *args, **kwargs):
  235. return self.client.attach(self.id, *args, **kwargs)
  236. def has_legacy_proj_name(self, project_name):
  237. return (
  238. ComposeVersion(self.labels.get(LABEL_VERSION)) < ComposeVersion('1.21.0') and
  239. self.project != project_name
  240. )
  241. def __repr__(self):
  242. return '<Container: %s (%s)>' % (self.name, self.id[:6])
  243. def __eq__(self, other):
  244. if type(self) != type(other):
  245. return False
  246. return self.id == other.id
  247. def __hash__(self):
  248. return self.id.__hash__()
  249. def get_container_name(container):
  250. if not container.get('Name') and not container.get('Names'):
  251. return None
  252. # inspect
  253. if 'Name' in container:
  254. return container['Name']
  255. # ps
  256. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  257. return shortest_name.split('/')[-1]