1
0

service.py 12 KB

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