container.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. import six
  4. from functools import reduce
  5. from .const import LABEL_CONTAINER_NUMBER, LABEL_SERVICE
  6. class Container(object):
  7. """
  8. Represents a Docker container, constructed from the output of
  9. GET /containers/:id:/json.
  10. """
  11. def __init__(self, client, dictionary, has_been_inspected=False):
  12. self.client = client
  13. self.dictionary = dictionary
  14. self.has_been_inspected = has_been_inspected
  15. @classmethod
  16. def from_ps(cls, client, dictionary, **kwargs):
  17. """
  18. Construct a container object from the output of GET /containers/json.
  19. """
  20. new_dictionary = {
  21. 'Id': dictionary['Id'],
  22. 'Image': dictionary['Image'],
  23. 'Name': '/' + get_container_name(dictionary),
  24. }
  25. return cls(client, new_dictionary, **kwargs)
  26. @classmethod
  27. def from_id(cls, client, id):
  28. return cls(client, client.inspect_container(id))
  29. @classmethod
  30. def create(cls, client, **options):
  31. response = client.create_container(**options)
  32. return cls.from_id(client, response['Id'])
  33. @property
  34. def id(self):
  35. return self.dictionary['Id']
  36. @property
  37. def image(self):
  38. return self.dictionary['Image']
  39. @property
  40. def image_config(self):
  41. return self.client.inspect_image(self.image)
  42. @property
  43. def short_id(self):
  44. return self.id[:10]
  45. @property
  46. def name(self):
  47. return self.dictionary['Name'][1:]
  48. @property
  49. def name_without_project(self):
  50. return '{0}_{1}'.format(self.labels.get(LABEL_SERVICE), self.number)
  51. @property
  52. def number(self):
  53. return int(self.labels.get(LABEL_CONTAINER_NUMBER) or 0)
  54. @property
  55. def ports(self):
  56. self.inspect_if_not_inspected()
  57. return self.get('NetworkSettings.Ports') or {}
  58. @property
  59. def human_readable_ports(self):
  60. def format_port(private, public):
  61. if not public:
  62. return private
  63. return '{HostIp}:{HostPort}->{private}'.format(
  64. private=private, **public[0])
  65. return ', '.join(format_port(*item)
  66. for item in sorted(six.iteritems(self.ports)))
  67. @property
  68. def labels(self):
  69. return self.get('Config.Labels') or {}
  70. @property
  71. def log_config(self):
  72. return self.get('HostConfig.LogConfig') or None
  73. @property
  74. def human_readable_state(self):
  75. if self.is_running:
  76. return 'Ghost' if self.get('State.Ghost') else 'Up'
  77. else:
  78. return 'Exit %s' % self.get('State.ExitCode')
  79. @property
  80. def human_readable_command(self):
  81. entrypoint = self.get('Config.Entrypoint') or []
  82. cmd = self.get('Config.Cmd') or []
  83. return ' '.join(entrypoint + cmd)
  84. @property
  85. def environment(self):
  86. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  87. @property
  88. def is_running(self):
  89. return self.get('State.Running')
  90. def get(self, key):
  91. """Return a value from the container or None if the value is not set.
  92. :param key: a string using dotted notation for nested dictionary
  93. lookups
  94. """
  95. self.inspect_if_not_inspected()
  96. def get_value(dictionary, key):
  97. return (dictionary or {}).get(key)
  98. return reduce(get_value, key.split('.'), self.dictionary)
  99. def get_local_port(self, port, protocol='tcp'):
  100. port = self.ports.get("%s/%s" % (port, protocol))
  101. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  102. def start(self, **options):
  103. return self.client.start(self.id, **options)
  104. def stop(self, **options):
  105. return self.client.stop(self.id, **options)
  106. def kill(self, **options):
  107. return self.client.kill(self.id, **options)
  108. def restart(self, **options):
  109. return self.client.restart(self.id, **options)
  110. def remove(self, **options):
  111. return self.client.remove_container(self.id, **options)
  112. def inspect_if_not_inspected(self):
  113. if not self.has_been_inspected:
  114. self.inspect()
  115. def wait(self):
  116. return self.client.wait(self.id)
  117. def logs(self, *args, **kwargs):
  118. return self.client.logs(self.id, *args, **kwargs)
  119. def inspect(self):
  120. self.dictionary = self.client.inspect_container(self.id)
  121. self.has_been_inspected = True
  122. return self.dictionary
  123. # TODO: only used by tests, move to test module
  124. def links(self):
  125. links = []
  126. for container in self.client.containers():
  127. for name in container['Names']:
  128. bits = name.split('/')
  129. if len(bits) > 2 and bits[1] == self.name:
  130. links.append(bits[2])
  131. return links
  132. def attach(self, *args, **kwargs):
  133. return self.client.attach(self.id, *args, **kwargs)
  134. def attach_socket(self, **kwargs):
  135. return self.client.attach_socket(self.id, **kwargs)
  136. def __repr__(self):
  137. return '<Container: %s>' % self.name
  138. def __eq__(self, other):
  139. if type(self) != type(other):
  140. return False
  141. return self.id == other.id
  142. def get_container_name(container):
  143. if not container.get('Name') and not container.get('Names'):
  144. return None
  145. # inspect
  146. if 'Name' in container:
  147. return container['Name']
  148. # ps
  149. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  150. return shortest_name.split('/')[-1]