service.py 5.5 KB

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