service.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from .packages.docker.client import APIError
  4. import logging
  5. import re
  6. import os
  7. import sys
  8. from .container import Container
  9. log = logging.getLogger(__name__)
  10. class BuildError(Exception):
  11. pass
  12. class CannotBeScaledError(Exception):
  13. pass
  14. class Service(object):
  15. def __init__(self, name, client=None, project='default', links=[], **options):
  16. if not re.match('^[a-zA-Z0-9]+$', name):
  17. raise ValueError('Invalid name: %s' % name)
  18. if not re.match('^[a-zA-Z0-9]+$', project):
  19. raise ValueError('Invalid project: %s' % project)
  20. if 'image' in options and 'build' in options:
  21. 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)
  22. self.name = name
  23. self.client = client
  24. self.project = project
  25. self.links = links or []
  26. self.options = options
  27. def containers(self, stopped=False, one_off=False):
  28. l = []
  29. for container in self.client.containers(all=stopped):
  30. name = get_container_name(container)
  31. if not name or not is_valid_name(name, one_off):
  32. continue
  33. project, name, number = parse_name(name)
  34. if project == self.project and name == self.name:
  35. l.append(Container.from_ps(self.client, container))
  36. return l
  37. def start(self, **options):
  38. for c in self.containers(stopped=True):
  39. if not c.is_running:
  40. log.info("Starting %s..." % c.name)
  41. self.start_container(c, **options)
  42. def stop(self, **options):
  43. for c in self.containers():
  44. log.info("Stopping %s..." % c.name)
  45. c.stop(**options)
  46. def kill(self, **options):
  47. for c in self.containers():
  48. log.info("Killing %s..." % c.name)
  49. c.kill(**options)
  50. def scale(self, desired_num):
  51. if not self.can_be_scaled():
  52. raise CannotBeScaledError()
  53. # Create enough containers
  54. containers = self.containers(stopped=True)
  55. while len(containers) < desired_num:
  56. containers.append(self.create_container())
  57. running_containers = []
  58. stopped_containers = []
  59. for c in containers:
  60. if c.is_running:
  61. running_containers.append(c)
  62. else:
  63. stopped_containers.append(c)
  64. running_containers.sort(key=lambda c: c.number)
  65. stopped_containers.sort(key=lambda c: c.number)
  66. # Stop containers
  67. while len(running_containers) > desired_num:
  68. c = running_containers.pop()
  69. log.info("Stopping %s..." % c.name)
  70. c.stop(timeout=1)
  71. stopped_containers.append(c)
  72. # Start containers
  73. while len(running_containers) < desired_num:
  74. c = stopped_containers.pop(0)
  75. log.info("Starting %s..." % c.name)
  76. c.start()
  77. running_containers.append(c)
  78. def remove_stopped(self, **options):
  79. for c in self.containers(stopped=True):
  80. if not c.is_running:
  81. log.info("Removing %s..." % c.name)
  82. c.remove(**options)
  83. def create_container(self, one_off=False, **override_options):
  84. """
  85. Create a container for this service. If the image doesn't exist, attempt to pull
  86. it.
  87. """
  88. container_options = self._get_container_options(override_options, one_off=one_off)
  89. try:
  90. return Container.create(self.client, **container_options)
  91. except APIError as e:
  92. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  93. log.info('Pulling image %s...' % container_options['image'])
  94. self.client.pull(container_options['image'])
  95. return Container.create(self.client, **container_options)
  96. raise
  97. def recreate_containers(self, **override_options):
  98. """
  99. If a container for this service doesn't exist, create one. If there are
  100. any, stop them and create new ones. Does not remove the old containers.
  101. """
  102. containers = self.containers(stopped=True)
  103. if len(containers) == 0:
  104. log.info("Creating %s..." % self.next_container_name())
  105. return ([], [self.create_container(**override_options)])
  106. else:
  107. old_containers = []
  108. new_containers = []
  109. for c in containers:
  110. log.info("Recreating %s..." % c.name)
  111. (old_container, new_container) = self.recreate_container(c, **override_options)
  112. old_containers.append(old_container)
  113. new_containers.append(new_container)
  114. return (old_containers, new_containers)
  115. def recreate_container(self, container, **override_options):
  116. if container.is_running:
  117. container.stop(timeout=1)
  118. intermediate_container = Container.create(
  119. self.client,
  120. image='ubuntu',
  121. command='echo',
  122. volumes_from=container.id,
  123. )
  124. intermediate_container.start()
  125. intermediate_container.wait()
  126. container.remove()
  127. options = dict(override_options)
  128. options['volumes_from'] = intermediate_container.id
  129. new_container = self.create_container(**options)
  130. return (intermediate_container, new_container)
  131. def start_container(self, container=None, **override_options):
  132. if container is None:
  133. container = self.create_container(**override_options)
  134. options = self.options.copy()
  135. options.update(override_options)
  136. port_bindings = {}
  137. if options.get('ports', None) is not None:
  138. for port in options['ports']:
  139. port = str(port)
  140. if ':' in port:
  141. external_port, internal_port = port.split(':', 1)
  142. port_bindings[int(internal_port)] = int(external_port)
  143. else:
  144. port_bindings[int(port)] = None
  145. volume_bindings = {}
  146. if options.get('volumes', None) is not None:
  147. for volume in options['volumes']:
  148. if ':' in volume:
  149. external_dir, internal_dir = volume.split(':')
  150. volume_bindings[os.path.abspath(external_dir)] = internal_dir
  151. container.start(
  152. links=self._get_links(),
  153. port_bindings=port_bindings,
  154. binds=volume_bindings,
  155. )
  156. return container
  157. def next_container_name(self, one_off=False):
  158. bits = [self.project, self.name]
  159. if one_off:
  160. bits.append('run')
  161. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  162. def next_container_number(self, one_off=False):
  163. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  164. if len(numbers) == 0:
  165. return 1
  166. else:
  167. return max(numbers) + 1
  168. def _get_links(self):
  169. links = {}
  170. for service in self.links:
  171. for container in service.containers():
  172. links[container.name] = container.name
  173. return links
  174. def _get_container_options(self, override_options, one_off=False):
  175. keys = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from']
  176. container_options = dict((k, self.options[k]) for k in keys if k in self.options)
  177. container_options.update(override_options)
  178. container_options['name'] = self.next_container_name(one_off)
  179. if 'ports' in container_options:
  180. ports = []
  181. for port in container_options['ports']:
  182. port = str(port)
  183. if ':' in port:
  184. port = port.split(':')[-1]
  185. ports.append(port)
  186. container_options['ports'] = ports
  187. if 'volumes' in container_options:
  188. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  189. if self.can_be_built():
  190. if len(self.client.images(name=self._build_tag_name())) == 0:
  191. self.build()
  192. container_options['image'] = self._build_tag_name()
  193. return container_options
  194. def build(self):
  195. log.info('Building %s...' % self.name)
  196. build_output = self.client.build(
  197. self.options['build'],
  198. tag=self._build_tag_name(),
  199. stream=True
  200. )
  201. image_id = None
  202. for line in build_output:
  203. if line:
  204. match = re.search(r'Successfully built ([0-9a-f]+)', line)
  205. if match:
  206. image_id = match.group(1)
  207. sys.stdout.write(line)
  208. if image_id is None:
  209. raise BuildError()
  210. return image_id
  211. def can_be_built(self):
  212. return 'build' in self.options
  213. def _build_tag_name(self):
  214. """
  215. The tag to give to images built for this service.
  216. """
  217. return '%s_%s' % (self.project, self.name)
  218. def can_be_scaled(self):
  219. for port in self.options.get('ports', []):
  220. if ':' in str(port):
  221. return False
  222. return True
  223. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  224. def is_valid_name(name, one_off=False):
  225. match = NAME_RE.match(name)
  226. if match is None:
  227. return False
  228. if one_off:
  229. return match.group(3) == 'run_'
  230. else:
  231. return match.group(3) is None
  232. def parse_name(name, one_off=False):
  233. match = NAME_RE.match(name)
  234. (project, service_name, _, suffix) = match.groups()
  235. return (project, service_name, int(suffix))
  236. def get_container_name(container):
  237. if not container.get('Name') and not container.get('Names'):
  238. return None
  239. # inspect
  240. if 'Name' in container:
  241. return container['Name']
  242. # ps
  243. for name in container['Names']:
  244. if len(name.split('/')) == 2:
  245. return name[1:]
  246. def split_volume(v):
  247. """
  248. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  249. If v is of the format INTERNAL, returns (None, INTERNAL).
  250. """
  251. if ':' in v:
  252. return v.split(':', 1)
  253. else:
  254. return (None, v)