container.py 5.1 KB

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