service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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', 'net']
  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. self.start_container_if_stopped(c, **options)
  62. def stop(self, **options):
  63. for c in self.containers():
  64. log.info("Stopping %s..." % c.name)
  65. c.stop(**options)
  66. def kill(self, **options):
  67. for c in self.containers():
  68. log.info("Killing %s..." % c.name)
  69. c.kill(**options)
  70. def scale(self, desired_num):
  71. """
  72. Adjusts the number of containers to the specified number and ensures they are running.
  73. - creates containers until there are at least `desired_num`
  74. - stops containers until there are at most `desired_num` running
  75. - starts containers until there are at least `desired_num` running
  76. - removes all stopped containers
  77. """
  78. if not self.can_be_scaled():
  79. raise CannotBeScaledError()
  80. # Create enough containers
  81. containers = self.containers(stopped=True)
  82. while len(containers) < desired_num:
  83. containers.append(self.create_container())
  84. running_containers = []
  85. stopped_containers = []
  86. for c in containers:
  87. if c.is_running:
  88. running_containers.append(c)
  89. else:
  90. stopped_containers.append(c)
  91. running_containers.sort(key=lambda c: c.number)
  92. stopped_containers.sort(key=lambda c: c.number)
  93. # Stop containers
  94. while len(running_containers) > desired_num:
  95. c = running_containers.pop()
  96. log.info("Stopping %s..." % c.name)
  97. c.stop(timeout=1)
  98. stopped_containers.append(c)
  99. # Start containers
  100. while len(running_containers) < desired_num:
  101. c = stopped_containers.pop(0)
  102. log.info("Starting %s..." % c.name)
  103. self.start_container(c)
  104. running_containers.append(c)
  105. self.remove_stopped()
  106. def remove_stopped(self, **options):
  107. for c in self.containers(stopped=True):
  108. if not c.is_running:
  109. log.info("Removing %s..." % c.name)
  110. c.remove(**options)
  111. def create_container(self, one_off=False, **override_options):
  112. """
  113. Create a container for this service. If the image doesn't exist, attempt to pull
  114. it.
  115. """
  116. container_options = self._get_container_create_options(override_options, one_off=one_off)
  117. try:
  118. return Container.create(self.client, **container_options)
  119. except APIError as e:
  120. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  121. log.info('Pulling image %s...' % container_options['image'])
  122. output = self.client.pull(container_options['image'], stream=True)
  123. stream_output(output, sys.stdout)
  124. return Container.create(self.client, **container_options)
  125. raise
  126. def recreate_containers(self, **override_options):
  127. """
  128. If a container for this service doesn't exist, create and start one. If there are
  129. any, stop them, create+start new ones, and remove the old containers.
  130. """
  131. containers = self.containers(stopped=True)
  132. if len(containers) == 0:
  133. log.info("Creating %s..." % self.next_container_name())
  134. container = self.create_container(**override_options)
  135. self.start_container(container)
  136. return [(None, container)]
  137. else:
  138. tuples = []
  139. for c in containers:
  140. log.info("Recreating %s..." % c.name)
  141. tuples.append(self.recreate_container(c, **override_options))
  142. return tuples
  143. def recreate_container(self, container, **override_options):
  144. if container.is_running:
  145. container.stop(timeout=1)
  146. intermediate_container = Container.create(
  147. self.client,
  148. image=container.image,
  149. entrypoint=['echo'],
  150. command=[],
  151. )
  152. intermediate_container.start(volumes_from=container.id)
  153. intermediate_container.wait()
  154. container.remove()
  155. options = dict(override_options)
  156. new_container = self.create_container(**options)
  157. self.start_container(new_container, volumes_from=intermediate_container.id)
  158. intermediate_container.remove()
  159. return (intermediate_container, new_container)
  160. def start_container_if_stopped(self, container, **options):
  161. if container.is_running:
  162. return container
  163. else:
  164. log.info("Starting %s..." % container.name)
  165. return self.start_container(container, **options)
  166. def start_container(self, container=None, volumes_from=None, **override_options):
  167. if container is None:
  168. container = self.create_container(**override_options)
  169. options = self.options.copy()
  170. options.update(override_options)
  171. port_bindings = {}
  172. if options.get('ports', None) is not None:
  173. for port in options['ports']:
  174. port = str(port)
  175. if ':' in port:
  176. external_port, internal_port = port.split(':', 1)
  177. else:
  178. external_port, internal_port = (None, port)
  179. port_bindings[internal_port] = external_port
  180. volume_bindings = {}
  181. if options.get('volumes', None) is not None:
  182. for volume in options['volumes']:
  183. if ':' in volume:
  184. external_dir, internal_dir = volume.split(':')
  185. volume_bindings[os.path.abspath(external_dir)] = {
  186. 'bind': internal_dir,
  187. 'ro': False,
  188. }
  189. privileged = options.get('privileged', False)
  190. net = options.get('net', 'bridge')
  191. container.start(
  192. links=self._get_links(link_to_self=override_options.get('one_off', False)),
  193. port_bindings=port_bindings,
  194. binds=volume_bindings,
  195. volumes_from=volumes_from,
  196. privileged=privileged,
  197. network_mode=net,
  198. )
  199. return container
  200. def start_or_create_containers(self):
  201. containers = self.containers(stopped=True)
  202. if len(containers) == 0:
  203. log.info("Creating %s..." % self.next_container_name())
  204. new_container = self.create_container()
  205. return [self.start_container(new_container)]
  206. else:
  207. return [self.start_container_if_stopped(c) for c in containers]
  208. def get_linked_names(self):
  209. return [s.name for (s, _) in self.links]
  210. def next_container_name(self, one_off=False):
  211. bits = [self.project, self.name]
  212. if one_off:
  213. bits.append('run')
  214. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  215. def next_container_number(self, one_off=False):
  216. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  217. if len(numbers) == 0:
  218. return 1
  219. else:
  220. return max(numbers) + 1
  221. def _get_links(self, link_to_self):
  222. links = []
  223. for service, link_name in self.links:
  224. for container in service.containers():
  225. if link_name:
  226. links.append((container.name, link_name))
  227. links.append((container.name, container.name))
  228. links.append((container.name, container.name_without_project))
  229. if link_to_self:
  230. for container in self.containers():
  231. links.append((container.name, container.name))
  232. links.append((container.name, container.name_without_project))
  233. return links
  234. def _get_container_create_options(self, override_options, one_off=False):
  235. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  236. container_options.update(override_options)
  237. container_options['name'] = self.next_container_name(one_off)
  238. if 'ports' in container_options or 'expose' in self.options:
  239. ports = []
  240. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  241. for port in all_ports:
  242. port = str(port)
  243. if ':' in port:
  244. port = port.split(':')[-1]
  245. if '/' in port:
  246. port = tuple(port.split('/'))
  247. ports.append(port)
  248. container_options['ports'] = ports
  249. if 'volumes' in container_options:
  250. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  251. if self.can_be_built():
  252. if len(self.client.images(name=self._build_tag_name())) == 0:
  253. self.build()
  254. container_options['image'] = self._build_tag_name()
  255. # Priviliged is only required for starting containers, not for creating them
  256. if 'privileged' in container_options:
  257. del container_options['privileged']
  258. # net is only required for starting containers, not for creating them
  259. if 'net' in container_options:
  260. del container_options['net']
  261. return container_options
  262. def build(self):
  263. log.info('Building %s...' % self.name)
  264. build_output = self.client.build(
  265. self.options['build'],
  266. tag=self._build_tag_name(),
  267. stream=True,
  268. rm=True
  269. )
  270. try:
  271. all_events = stream_output(build_output, sys.stdout)
  272. except StreamOutputError, e:
  273. raise BuildError(self, unicode(e))
  274. image_id = None
  275. for event in all_events:
  276. if 'stream' in event:
  277. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  278. if match:
  279. image_id = match.group(1)
  280. if image_id is None:
  281. raise BuildError(self)
  282. return image_id
  283. def can_be_built(self):
  284. return 'build' in self.options
  285. def _build_tag_name(self):
  286. """
  287. The tag to give to images built for this service.
  288. """
  289. return '%s_%s' % (self.project, self.name)
  290. def can_be_scaled(self):
  291. for port in self.options.get('ports', []):
  292. if ':' in str(port):
  293. return False
  294. return True
  295. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  296. def is_valid_name(name, one_off=False):
  297. match = NAME_RE.match(name)
  298. if match is None:
  299. return False
  300. if one_off:
  301. return match.group(3) == 'run_'
  302. else:
  303. return match.group(3) is None
  304. def parse_name(name, one_off=False):
  305. match = NAME_RE.match(name)
  306. (project, service_name, _, suffix) = match.groups()
  307. return (project, service_name, int(suffix))
  308. def get_container_name(container):
  309. if not container.get('Name') and not container.get('Names'):
  310. return None
  311. # inspect
  312. if 'Name' in container:
  313. return container['Name']
  314. # ps
  315. for name in container['Names']:
  316. if len(name.split('/')) == 2:
  317. return name[1:]
  318. def split_volume(v):
  319. """
  320. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  321. If v is of the format INTERNAL, returns (None, INTERNAL).
  322. """
  323. if ':' in v:
  324. return v.split(':', 1)
  325. else:
  326. return (None, v)