service.py 13 KB

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