container.py 5.3 KB

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