container.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. import logging
  4. log = logging.getLogger(__name__)
  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. }
  23. for name in dictionary.get('Names', []):
  24. if len(name.split('/')) == 2:
  25. new_dictionary['Name'] = name
  26. return cls(client, new_dictionary, **kwargs)
  27. @classmethod
  28. def from_id(cls, client, id):
  29. return cls(client, client.inspect_container(id))
  30. @classmethod
  31. def create(cls, client, **options):
  32. response = client.create_container(**options)
  33. return cls.from_id(client, response['Id'])
  34. @property
  35. def id(self):
  36. return self.dictionary['ID']
  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 human_readable_ports(self):
  45. self.inspect_if_not_inspected()
  46. if not self.dictionary['NetworkSettings']['Ports']:
  47. return ''
  48. ports = []
  49. for private, public in list(self.dictionary['NetworkSettings']['Ports'].items()):
  50. if public:
  51. ports.append('%s->%s' % (public[0]['HostPort'], private))
  52. return ', '.join(ports)
  53. @property
  54. def human_readable_state(self):
  55. self.inspect_if_not_inspected()
  56. if self.dictionary['State']['Running']:
  57. if self.dictionary['State']['Ghost']:
  58. return 'Ghost'
  59. else:
  60. return 'Up'
  61. else:
  62. return 'Exit %s' % self.dictionary['State']['ExitCode']
  63. @property
  64. def human_readable_command(self):
  65. self.inspect_if_not_inspected()
  66. return ' '.join(self.dictionary['Config']['Cmd'])
  67. @property
  68. def environment(self):
  69. self.inspect_if_not_inspected()
  70. out = {}
  71. for var in self.dictionary.get('Config', {}).get('Env', []):
  72. k, v = var.split('=', 1)
  73. out[k] = v
  74. return out
  75. @property
  76. def is_running(self):
  77. self.inspect_if_not_inspected()
  78. return self.dictionary['State']['Running']
  79. def start(self, **options):
  80. log.info("Starting %s..." % self.name)
  81. return self.client.start(self.id, **options)
  82. def stop(self, **options):
  83. log.info("Stopping %s..." % self.name)
  84. return self.client.stop(self.id, **options)
  85. def kill(self):
  86. log.info("Killing %s..." % self.name)
  87. return self.client.kill(self.id)
  88. def remove(self):
  89. log.info("Removing %s..." % self.name)
  90. return self.client.remove_container(self.id)
  91. def inspect_if_not_inspected(self):
  92. if not self.has_been_inspected:
  93. self.inspect()
  94. def wait(self):
  95. return self.client.wait(self.id)
  96. def logs(self, *args, **kwargs):
  97. return self.client.logs(self.id, *args, **kwargs)
  98. def inspect(self):
  99. self.dictionary = self.client.inspect_container(self.id)
  100. return self.dictionary
  101. def links(self):
  102. links = []
  103. for container in self.client.containers():
  104. for name in container['Names']:
  105. bits = name.split('/')
  106. if len(bits) > 2 and bits[1] == self.name:
  107. links.append(bits[2])
  108. return links
  109. def attach_socket(self, **kwargs):
  110. return self.client.attach_socket(self.id, **kwargs)
  111. def __repr__(self):
  112. return '<Container: %s>' % self.name
  113. def __eq__(self, other):
  114. if type(self) != type(other):
  115. return False
  116. return self.id == other.id