container.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. class Container(object):
  2. """
  3. Represents a Docker container, constructed from the output of
  4. GET /containers/:id:/json.
  5. """
  6. def __init__(self, client, dictionary, has_been_inspected=False):
  7. self.client = client
  8. self.dictionary = dictionary
  9. self.has_been_inspected = has_been_inspected
  10. @classmethod
  11. def from_ps(cls, client, dictionary, **kwargs):
  12. """
  13. Construct a container object from the output of GET /containers/json.
  14. """
  15. new_dictionary = {
  16. 'ID': dictionary['Id'],
  17. 'Image': dictionary['Image'],
  18. }
  19. for name in dictionary.get('Names', []):
  20. if len(name.split('/')) == 2:
  21. new_dictionary['Name'] = name
  22. return cls(client, new_dictionary, **kwargs)
  23. @classmethod
  24. def from_id(cls, client, id):
  25. return cls(client, client.inspect_container(id))
  26. @classmethod
  27. def create(cls, client, **options):
  28. response = client.create_container(**options)
  29. return cls.from_id(client, response['Id'])
  30. @property
  31. def id(self):
  32. return self.dictionary['ID']
  33. @property
  34. def name(self):
  35. return self.dictionary['Name']
  36. @property
  37. def environment(self):
  38. self.inspect_if_not_inspected()
  39. out = {}
  40. for var in self.dictionary.get('Config', {}).get('Env', []):
  41. k, v = var.split('=', 1)
  42. out[k] = v
  43. return out
  44. def start(self, **options):
  45. return self.client.start(self.id, **options)
  46. def stop(self):
  47. return self.client.stop(self.id)
  48. def kill(self):
  49. return self.client.kill(self.id)
  50. def remove(self):
  51. return self.client.remove_container(self.id)
  52. def inspect_if_not_inspected(self):
  53. if not self.has_been_inspected:
  54. self.inspect()
  55. def wait(self):
  56. return self.client.wait(self.id)
  57. def logs(self, *args, **kwargs):
  58. return self.client.logs(self.id, *args, **kwargs)
  59. def inspect(self):
  60. self.dictionary = self.client.inspect_container(self.id)
  61. return self.dictionary
  62. def links(self):
  63. links = []
  64. for container in self.client.containers():
  65. for name in container['Names']:
  66. bits = name.split('/')
  67. if len(bits) > 2 and bits[1] == self.name[1:]:
  68. links.append(bits[2])
  69. return links