container.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. class Container(object):
  4. """
  5. Represents a Docker container, constructed from the output of
  6. GET /containers/:id:/json.
  7. """
  8. def __init__(self, client, dictionary, has_been_inspected=False):
  9. self.client = client
  10. self.dictionary = dictionary
  11. self.has_been_inspected = has_been_inspected
  12. @classmethod
  13. def from_ps(cls, client, dictionary, **kwargs):
  14. """
  15. Construct a container object from the output of GET /containers/json.
  16. """
  17. new_dictionary = {
  18. 'Id': dictionary['Id'],
  19. 'Image': dictionary['Image'],
  20. }
  21. for name in dictionary.get('Names', []):
  22. if len(name.split('/')) == 2:
  23. new_dictionary['Name'] = name
  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 human_readable_ports(self):
  55. self.inspect_if_not_inspected()
  56. if not self.dictionary['NetworkSettings']['Ports']:
  57. return ''
  58. ports = []
  59. for private, public in list(self.dictionary['NetworkSettings']['Ports'].items()):
  60. if public:
  61. ports.append('%s->%s' % (public[0]['HostPort'], private))
  62. else:
  63. ports.append(private)
  64. return ', '.join(ports)
  65. @property
  66. def human_readable_state(self):
  67. self.inspect_if_not_inspected()
  68. if self.dictionary['State']['Running']:
  69. if self.dictionary['State'].get('Ghost'):
  70. return 'Ghost'
  71. else:
  72. return 'Up'
  73. else:
  74. return 'Exit %s' % self.dictionary['State']['ExitCode']
  75. @property
  76. def human_readable_command(self):
  77. self.inspect_if_not_inspected()
  78. if self.dictionary['Config']['Cmd']:
  79. return ' '.join(self.dictionary['Config']['Cmd'])
  80. else:
  81. return ''
  82. @property
  83. def environment(self):
  84. self.inspect_if_not_inspected()
  85. out = {}
  86. for var in self.dictionary.get('Config', {}).get('Env', []):
  87. k, v = var.split('=', 1)
  88. out[k] = v
  89. return out
  90. @property
  91. def is_running(self):
  92. self.inspect_if_not_inspected()
  93. return self.dictionary['State']['Running']
  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):
  99. return self.client.kill(self.id)
  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. return self.dictionary
  114. def links(self):
  115. links = []
  116. for container in self.client.containers():
  117. for name in container['Names']:
  118. bits = name.split('/')
  119. if len(bits) > 2 and bits[1] == self.name:
  120. links.append(bits[2])
  121. return links
  122. def attach(self, *args, **kwargs):
  123. return self.client.attach(self.id, *args, **kwargs)
  124. def attach_socket(self, **kwargs):
  125. return self.client.attach_socket(self.id, **kwargs)
  126. def __repr__(self):
  127. return '<Container: %s>' % self.name
  128. def __eq__(self, other):
  129. if type(self) != type(other):
  130. return False
  131. return self.id == other.id