container.py 8.2 KB

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