container.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from fig.packages 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.dictionary['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. self.inspect_if_not_inspected()
  70. if self.dictionary['State']['Running']:
  71. if self.dictionary['State'].get('Ghost'):
  72. return 'Ghost'
  73. else:
  74. return 'Up'
  75. else:
  76. return 'Exit %s' % self.dictionary['State']['ExitCode']
  77. @property
  78. def human_readable_command(self):
  79. self.inspect_if_not_inspected()
  80. if self.dictionary['Config']['Cmd']:
  81. return ' '.join(self.dictionary['Config']['Cmd'])
  82. else:
  83. return ''
  84. @property
  85. def environment(self):
  86. self.inspect_if_not_inspected()
  87. return dict(var.split("=", 1)
  88. for var in self.dictionary.get('Config', {}).get('Env', []))
  89. @property
  90. def is_running(self):
  91. self.inspect_if_not_inspected()
  92. return self.dictionary['State']['Running']
  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):
  101. return self.client.kill(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