container.py 9.4 KB

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