service.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from collections import namedtuple
  4. import logging
  5. import re
  6. import os
  7. import sys
  8. from docker.errors import APIError
  9. from .container import Container
  10. from .progress_stream import stream_output, StreamOutputError
  11. log = logging.getLogger(__name__)
  12. DOCKER_CONFIG_KEYS = ['image', 'command', 'hostname', 'domainname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'entrypoint', 'privileged', 'volumes_from', 'net', 'working_dir']
  13. DOCKER_CONFIG_HINTS = {
  14. 'link' : 'links',
  15. 'port' : 'ports',
  16. 'privilege' : 'privileged',
  17. 'priviliged': 'privileged',
  18. 'privilige' : 'privileged',
  19. 'volume' : 'volumes',
  20. 'workdir' : 'working_dir',
  21. }
  22. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  23. class BuildError(Exception):
  24. def __init__(self, service, reason):
  25. self.service = service
  26. self.reason = reason
  27. class CannotBeScaledError(Exception):
  28. pass
  29. class ConfigError(ValueError):
  30. pass
  31. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  32. ServiceName = namedtuple('ServiceName', 'project service number')
  33. class Service(object):
  34. def __init__(self, name, client=None, project='default', links=None, volumes_from=None, **options):
  35. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  36. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  37. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  38. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  39. if 'image' in options and 'build' in options:
  40. 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)
  41. supported_options = DOCKER_CONFIG_KEYS + ['build', 'expose']
  42. for k in options:
  43. if k not in supported_options:
  44. msg = "Unsupported config option for %s service: '%s'" % (name, k)
  45. if k in DOCKER_CONFIG_HINTS:
  46. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  47. raise ConfigError(msg)
  48. self.name = name
  49. self.client = client
  50. self.project = project
  51. self.links = links or []
  52. self.volumes_from = volumes_from or []
  53. self.options = options
  54. def containers(self, stopped=False, one_off=False):
  55. return [Container.from_ps(self.client, container)
  56. for container in self.client.containers(all=stopped)
  57. if self.has_container(container, one_off=one_off)]
  58. def has_container(self, container, one_off=False):
  59. """Return True if `container` was created to fulfill this service."""
  60. name = get_container_name(container)
  61. if not name or not is_valid_name(name, one_off):
  62. return False
  63. project, name, _number = parse_name(name)
  64. return project == self.project and name == self.name
  65. def get_container(self, number=1):
  66. """Return a :class:`fig.container.Container` for this service. The
  67. container must be active, and match `number`.
  68. """
  69. for container in self.client.containers():
  70. if not self.has_container(container):
  71. continue
  72. _, _, container_number = parse_name(get_container_name(container))
  73. if container_number == number:
  74. return Container.from_ps(self.client, container)
  75. raise ValueError("No container found for %s_%s" % (self.name, number))
  76. def start(self, **options):
  77. for c in self.containers(stopped=True):
  78. self.start_container_if_stopped(c, **options)
  79. def stop(self, **options):
  80. for c in self.containers():
  81. log.info("Stopping %s..." % c.name)
  82. c.stop(**options)
  83. def kill(self, **options):
  84. for c in self.containers():
  85. log.info("Killing %s..." % c.name)
  86. c.kill(**options)
  87. def restart(self, **options):
  88. for c in self.containers():
  89. log.info("Restarting %s..." % c.name)
  90. c.restart(**options)
  91. def scale(self, desired_num):
  92. """
  93. Adjusts the number of containers to the specified number and ensures they are running.
  94. - creates containers until there are at least `desired_num`
  95. - stops containers until there are at most `desired_num` running
  96. - starts containers until there are at least `desired_num` running
  97. - removes all stopped containers
  98. """
  99. if not self.can_be_scaled():
  100. raise CannotBeScaledError()
  101. # Create enough containers
  102. containers = self.containers(stopped=True)
  103. while len(containers) < desired_num:
  104. containers.append(self.create_container())
  105. running_containers = []
  106. stopped_containers = []
  107. for c in containers:
  108. if c.is_running:
  109. running_containers.append(c)
  110. else:
  111. stopped_containers.append(c)
  112. running_containers.sort(key=lambda c: c.number)
  113. stopped_containers.sort(key=lambda c: c.number)
  114. # Stop containers
  115. while len(running_containers) > desired_num:
  116. c = running_containers.pop()
  117. log.info("Stopping %s..." % c.name)
  118. c.stop(timeout=1)
  119. stopped_containers.append(c)
  120. # Start containers
  121. while len(running_containers) < desired_num:
  122. c = stopped_containers.pop(0)
  123. log.info("Starting %s..." % c.name)
  124. self.start_container(c)
  125. running_containers.append(c)
  126. self.remove_stopped()
  127. def remove_stopped(self, **options):
  128. for c in self.containers(stopped=True):
  129. if not c.is_running:
  130. log.info("Removing %s..." % c.name)
  131. c.remove(**options)
  132. def create_container(self, one_off=False, **override_options):
  133. """
  134. Create a container for this service. If the image doesn't exist, attempt to pull
  135. it.
  136. """
  137. container_options = self._get_container_create_options(override_options, one_off=one_off)
  138. try:
  139. return Container.create(self.client, **container_options)
  140. except APIError as e:
  141. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  142. log.info('Pulling image %s...' % container_options['image'])
  143. output = self.client.pull(container_options['image'], stream=True)
  144. stream_output(output, sys.stdout)
  145. return Container.create(self.client, **container_options)
  146. raise
  147. def recreate_containers(self, **override_options):
  148. """
  149. If a container for this service doesn't exist, create and start one. If there are
  150. any, stop them, create+start new ones, and remove the old containers.
  151. """
  152. containers = self.containers(stopped=True)
  153. if not containers:
  154. log.info("Creating %s..." % self._next_container_name(containers))
  155. container = self.create_container(**override_options)
  156. self.start_container(container)
  157. return [(None, container)]
  158. else:
  159. tuples = []
  160. for c in containers:
  161. log.info("Recreating %s..." % c.name)
  162. tuples.append(self.recreate_container(c, **override_options))
  163. return tuples
  164. def recreate_container(self, container, **override_options):
  165. try:
  166. container.stop()
  167. except APIError as e:
  168. if (e.response.status_code == 500
  169. and e.explanation
  170. and 'no such process' in str(e.explanation)):
  171. pass
  172. else:
  173. raise
  174. intermediate_container = Container.create(
  175. self.client,
  176. image=container.image,
  177. entrypoint=['echo'],
  178. command=[],
  179. )
  180. intermediate_container.start(volumes_from=container.id)
  181. intermediate_container.wait()
  182. container.remove()
  183. options = dict(override_options)
  184. new_container = self.create_container(**options)
  185. self.start_container(new_container, intermediate_container=intermediate_container)
  186. intermediate_container.remove()
  187. return (intermediate_container, new_container)
  188. def start_container_if_stopped(self, container, **options):
  189. if container.is_running:
  190. return container
  191. else:
  192. log.info("Starting %s..." % container.name)
  193. return self.start_container(container, **options)
  194. def start_container(self, container=None, intermediate_container=None, **override_options):
  195. container = container or self.create_container(**override_options)
  196. options = dict(self.options, **override_options)
  197. ports = dict(split_port(port) for port in options.get('ports') or [])
  198. volume_bindings = dict(
  199. build_volume_binding(parse_volume_spec(volume))
  200. for volume in options.get('volumes') or []
  201. if ':' in volume)
  202. privileged = options.get('privileged', False)
  203. net = options.get('net', 'bridge')
  204. dns = options.get('dns', None)
  205. container.start(
  206. links=self._get_links(link_to_self=options.get('one_off', False)),
  207. port_bindings=ports,
  208. binds=volume_bindings,
  209. volumes_from=self._get_volumes_from(intermediate_container),
  210. privileged=privileged,
  211. network_mode=net,
  212. dns=dns,
  213. )
  214. return container
  215. def start_or_create_containers(self):
  216. containers = self.containers(stopped=True)
  217. if not containers:
  218. log.info("Creating %s..." % self._next_container_name(containers))
  219. new_container = self.create_container()
  220. return [self.start_container(new_container)]
  221. else:
  222. return [self.start_container_if_stopped(c) for c in containers]
  223. def get_linked_names(self):
  224. return [s.name for (s, _) in self.links]
  225. def _next_container_name(self, all_containers, one_off=False):
  226. bits = [self.project, self.name]
  227. if one_off:
  228. bits.append('run')
  229. return '_'.join(bits + [str(self._next_container_number(all_containers))])
  230. def _next_container_number(self, all_containers):
  231. numbers = [parse_name(c.name).number for c in all_containers]
  232. return 1 if not numbers else max(numbers) + 1
  233. def _get_links(self, link_to_self):
  234. links = []
  235. for service, link_name in self.links:
  236. for container in service.containers():
  237. links.append((container.name, link_name or service.name))
  238. links.append((container.name, container.name))
  239. links.append((container.name, container.name_without_project))
  240. if link_to_self:
  241. for container in self.containers():
  242. links.append((container.name, self.name))
  243. links.append((container.name, container.name))
  244. links.append((container.name, container.name_without_project))
  245. return links
  246. def _get_volumes_from(self, intermediate_container=None):
  247. volumes_from = []
  248. for v in self.volumes_from:
  249. if isinstance(v, Service):
  250. for container in v.containers(stopped=True):
  251. volumes_from.append(container.id)
  252. elif isinstance(v, Container):
  253. volumes_from.append(v.id)
  254. if intermediate_container:
  255. volumes_from.append(intermediate_container.id)
  256. return volumes_from
  257. def _get_container_create_options(self, override_options, one_off=False):
  258. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  259. container_options.update(override_options)
  260. container_options['name'] = self._next_container_name(
  261. self.containers(stopped=True, one_off=one_off),
  262. one_off)
  263. # If a qualified hostname was given, split it into an
  264. # unqualified hostname and a domainname unless domainname
  265. # was also given explicitly. This matches the behavior of
  266. # the official Docker CLI in that scenario.
  267. if ('hostname' in container_options
  268. and 'domainname' not in container_options
  269. and '.' in container_options['hostname']):
  270. parts = container_options['hostname'].partition('.')
  271. container_options['hostname'] = parts[0]
  272. container_options['domainname'] = parts[2]
  273. if 'ports' in container_options or 'expose' in self.options:
  274. ports = []
  275. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  276. for port in all_ports:
  277. port = str(port)
  278. if ':' in port:
  279. port = port.split(':')[-1]
  280. if '/' in port:
  281. port = tuple(port.split('/'))
  282. ports.append(port)
  283. container_options['ports'] = ports
  284. if 'volumes' in container_options:
  285. container_options['volumes'] = dict(
  286. (parse_volume_spec(v).internal, {})
  287. for v in container_options['volumes'])
  288. if 'environment' in container_options:
  289. if isinstance(container_options['environment'], list):
  290. container_options['environment'] = dict(split_env(e) for e in container_options['environment'])
  291. container_options['environment'] = dict(resolve_env(k, v) for k, v in container_options['environment'].iteritems())
  292. if self.can_be_built():
  293. if len(self.client.images(name=self._build_tag_name())) == 0:
  294. self.build()
  295. container_options['image'] = self._build_tag_name()
  296. # Delete options which are only used when starting
  297. for key in ['privileged', 'net', 'dns']:
  298. if key in container_options:
  299. del container_options[key]
  300. return container_options
  301. def build(self, no_cache=False):
  302. log.info('Building %s...' % self.name)
  303. build_output = self.client.build(
  304. self.options['build'],
  305. tag=self._build_tag_name(),
  306. stream=True,
  307. rm=True,
  308. nocache=no_cache,
  309. )
  310. try:
  311. all_events = stream_output(build_output, sys.stdout)
  312. except StreamOutputError, e:
  313. raise BuildError(self, unicode(e))
  314. image_id = None
  315. for event in all_events:
  316. if 'stream' in event:
  317. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  318. if match:
  319. image_id = match.group(1)
  320. if image_id is None:
  321. raise BuildError(self)
  322. return image_id
  323. def can_be_built(self):
  324. return 'build' in self.options
  325. def _build_tag_name(self):
  326. """
  327. The tag to give to images built for this service.
  328. """
  329. return '%s_%s' % (self.project, self.name)
  330. def can_be_scaled(self):
  331. for port in self.options.get('ports', []):
  332. if ':' in str(port):
  333. return False
  334. return True
  335. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  336. def is_valid_name(name, one_off=False):
  337. match = NAME_RE.match(name)
  338. if match is None:
  339. return False
  340. if one_off:
  341. return match.group(3) == 'run_'
  342. else:
  343. return match.group(3) is None
  344. def parse_name(name):
  345. match = NAME_RE.match(name)
  346. (project, service_name, _, suffix) = match.groups()
  347. return ServiceName(project, service_name, int(suffix))
  348. def get_container_name(container):
  349. if not container.get('Name') and not container.get('Names'):
  350. return None
  351. # inspect
  352. if 'Name' in container:
  353. return container['Name']
  354. # ps
  355. for name in container['Names']:
  356. if len(name.split('/')) == 2:
  357. return name[1:]
  358. def parse_volume_spec(volume_config):
  359. parts = volume_config.split(':')
  360. if len(parts) > 3:
  361. raise ConfigError("Volume %s has incorrect format, should be "
  362. "external:internal[:mode]" % volume_config)
  363. if len(parts) == 1:
  364. return VolumeSpec(None, parts[0], 'rw')
  365. if len(parts) == 2:
  366. parts.append('rw')
  367. external, internal, mode = parts
  368. if mode not in ('rw', 'ro'):
  369. raise ConfigError("Volume %s has invalid mode (%s), should be "
  370. "one of: rw, ro." % (volume_config, mode))
  371. return VolumeSpec(external, internal, mode)
  372. def build_volume_binding(volume_spec):
  373. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  374. external = os.path.expanduser(volume_spec.external)
  375. return os.path.abspath(os.path.expandvars(external)), internal
  376. def split_port(port):
  377. parts = str(port).split(':')
  378. if not 1 <= len(parts) <= 3:
  379. raise ConfigError('Invalid port "%s", should be '
  380. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  381. if len(parts) == 1:
  382. internal_port, = parts
  383. return internal_port, None
  384. if len(parts) == 2:
  385. external_port, internal_port = parts
  386. return internal_port, external_port
  387. external_ip, external_port, internal_port = parts
  388. return internal_port, (external_ip, external_port or None)
  389. def split_env(env):
  390. if '=' in env:
  391. return env.split('=', 1)
  392. else:
  393. return env, None
  394. def resolve_env(key, val):
  395. if val is not None:
  396. return key, val
  397. elif key in os.environ:
  398. return key, os.environ[key]
  399. else:
  400. return key, ''