service.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from docker.client import APIError
  2. import logging
  3. import re
  4. import sys
  5. from .container import Container
  6. log = logging.getLogger(__name__)
  7. class BuildError(Exception):
  8. pass
  9. class Service(object):
  10. def __init__(self, name, client=None, links=[], **options):
  11. if not re.match('^[a-zA-Z0-9_]+$', name):
  12. raise ValueError('Invalid name: %s' % name)
  13. if 'image' in options and 'build' in options:
  14. raise ValueError('Service %s has both an image and build path specified. A service can either be built to image or use an existing image, not both.' % name)
  15. self.name = name
  16. self.client = client
  17. self.links = links or []
  18. self.options = options
  19. def containers(self, all=False):
  20. l = []
  21. for container in self.client.containers(all=all):
  22. name = get_container_name(container)
  23. if is_valid_name(name) and parse_name(name)[0] == self.name:
  24. l.append(Container.from_ps(self.client, container))
  25. return l
  26. def start(self):
  27. if len(self.containers()) == 0:
  28. return self.start_container()
  29. def stop(self):
  30. self.scale(0)
  31. def scale(self, num):
  32. while len(self.containers()) < num:
  33. self.start_container()
  34. while len(self.containers()) > num:
  35. self.stop_container()
  36. def create_container(self, **override_options):
  37. """
  38. Create a container for this service. If the image doesn't exist, attempt to pull
  39. it.
  40. """
  41. container_options = self._get_container_options(override_options)
  42. try:
  43. return Container.create(self.client, **container_options)
  44. except APIError, e:
  45. if e.response.status_code == 404 and e.explanation and 'No such image' in e.explanation:
  46. log.info('Pulling image %s...' % container_options['image'])
  47. self.client.pull(container_options['image'])
  48. return Container.create(self.client, **container_options)
  49. raise
  50. def start_container(self, container=None, **override_options):
  51. if container is None:
  52. container = self.create_container(**override_options)
  53. options = self.options.copy()
  54. options.update(override_options)
  55. port_bindings = {}
  56. if options.get('ports', None) is not None:
  57. for port in options['ports']:
  58. port = unicode(port)
  59. if ':' in port:
  60. internal_port, external_port = port.split(':', 1)
  61. port_bindings[int(internal_port)] = int(external_port)
  62. else:
  63. port_bindings[int(port)] = None
  64. log.info("Starting %s..." % container.name)
  65. container.start(
  66. links=self._get_links(),
  67. port_bindings=port_bindings,
  68. )
  69. return container
  70. def stop_container(self):
  71. container = self.containers()[-1]
  72. log.info("Stopping and removing %s..." % container.name)
  73. container.kill()
  74. container.remove()
  75. def next_container_number(self):
  76. numbers = [parse_name(c.name)[1] for c in self.containers(all=True)]
  77. if len(numbers) == 0:
  78. return 1
  79. else:
  80. return max(numbers) + 1
  81. def _get_links(self):
  82. links = {}
  83. for service in self.links:
  84. for container in service.containers():
  85. links[container.name[1:]] = container.name[1:]
  86. return links
  87. def _get_container_options(self, override_options):
  88. keys = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from']
  89. container_options = dict((k, self.options[k]) for k in keys if k in self.options)
  90. container_options.update(override_options)
  91. number = self.next_container_number()
  92. container_options['name'] = make_name(self.name, number)
  93. if 'ports' in container_options:
  94. container_options['ports'] = [unicode(p).split(':')[0] for p in container_options['ports']]
  95. if 'build' in self.options:
  96. container_options['image'] = self.build()
  97. return container_options
  98. def build(self):
  99. log.info('Building %s...' % self.name)
  100. build_output = self.client.build(self.options['build'], stream=True)
  101. image_id = None
  102. for line in build_output:
  103. if line:
  104. match = re.search(r'Successfully built ([0-9a-f]+)', line)
  105. if match:
  106. image_id = match.group(1)
  107. sys.stdout.write(line)
  108. if image_id is None:
  109. raise BuildError()
  110. return image_id
  111. name_regex = '^(.+)_(\d+)$'
  112. def make_name(prefix, number):
  113. return '%s_%s' % (prefix, number)
  114. def is_valid_name(name):
  115. return (re.match(name_regex, name) is not None)
  116. def parse_name(name):
  117. match = re.match(name_regex, name)
  118. (service_name, suffix) = match.groups()
  119. return (service_name, int(suffix))
  120. def get_container_name(container):
  121. # inspect
  122. if 'Name' in container:
  123. return container['Name']
  124. # ps
  125. for name in container['Names']:
  126. if len(name.split('/')) == 2:
  127. return name[1:]