container.py 4.0 KB

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