container.py 9.5 KB

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