container.py 5.1 KB

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