service.py 5.1 KB

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