container.py 4.9 KB

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