service.py 18 KB

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