service.py 14 KB

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