service.py 11 KB

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