container.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 human_readable_state(self):
  71. if self.is_running:
  72. return 'Ghost' if self.get('State.Ghost') else 'Up'
  73. else:
  74. return 'Exit %s' % self.get('State.ExitCode')
  75. @property
  76. def human_readable_command(self):
  77. entrypoint = self.get('Config.Entrypoint') or []
  78. cmd = self.get('Config.Cmd') or []
  79. return ' '.join(entrypoint + cmd)
  80. @property
  81. def environment(self):
  82. return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
  83. @property
  84. def is_running(self):
  85. return self.get('State.Running')
  86. def get(self, key):
  87. """Return a value from the container or None if the value is not set.
  88. :param key: a string using dotted notation for nested dictionary
  89. lookups
  90. """
  91. self.inspect_if_not_inspected()
  92. def get_value(dictionary, key):
  93. return (dictionary or {}).get(key)
  94. return reduce(get_value, key.split('.'), self.dictionary)
  95. def get_local_port(self, port, protocol='tcp'):
  96. port = self.ports.get("%s/%s" % (port, protocol))
  97. return "{HostIp}:{HostPort}".format(**port[0]) if port else None
  98. def start(self, **options):
  99. return self.client.start(self.id, **options)
  100. def stop(self, **options):
  101. return self.client.stop(self.id, **options)
  102. def kill(self, **options):
  103. return self.client.kill(self.id, **options)
  104. def restart(self, **options):
  105. return self.client.restart(self.id, **options)
  106. def remove(self, **options):
  107. return self.client.remove_container(self.id, **options)
  108. def inspect_if_not_inspected(self):
  109. if not self.has_been_inspected:
  110. self.inspect()
  111. def wait(self):
  112. return self.client.wait(self.id)
  113. def logs(self, *args, **kwargs):
  114. return self.client.logs(self.id, *args, **kwargs)
  115. def inspect(self):
  116. self.dictionary = self.client.inspect_container(self.id)
  117. self.has_been_inspected = True
  118. return self.dictionary
  119. def links(self):
  120. links = []
  121. for container in self.client.containers():
  122. for name in container['Names']:
  123. bits = name.split('/')
  124. if len(bits) > 2 and bits[1] == self.name:
  125. links.append(bits[2])
  126. return links
  127. def attach(self, *args, **kwargs):
  128. return self.client.attach(self.id, *args, **kwargs)
  129. def attach_socket(self, **kwargs):
  130. return self.client.attach_socket(self.id, **kwargs)
  131. def __repr__(self):
  132. return '<Container: %s>' % self.name
  133. def __eq__(self, other):
  134. if type(self) != type(other):
  135. return False
  136. return self.id == other.id
  137. def get_container_name(container):
  138. if not container.get('Name') and not container.get('Names'):
  139. return None
  140. # inspect
  141. if 'Name' in container:
  142. return container['Name']
  143. # ps
  144. shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
  145. return shortest_name.split('/')[-1]