1
0

container.py 9.1 KB

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