container.py 7.6 KB

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