service.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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, insecure_registry=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(
  145. container_options['image'],
  146. stream=True,
  147. insecure_registry=insecure_registry
  148. )
  149. stream_output(output, sys.stdout)
  150. return Container.create(self.client, **container_options)
  151. raise
  152. def recreate_containers(self, **override_options):
  153. """
  154. If a container for this service doesn't exist, create and start one. If there are
  155. any, stop them, create+start new ones, and remove the old containers.
  156. """
  157. containers = self.containers(stopped=True)
  158. if not containers:
  159. log.info("Creating %s..." % self._next_container_name(containers))
  160. container = self.create_container(**override_options)
  161. self.start_container(container)
  162. return [(None, container)]
  163. else:
  164. tuples = []
  165. for c in containers:
  166. log.info("Recreating %s..." % c.name)
  167. tuples.append(self.recreate_container(c, **override_options))
  168. return tuples
  169. def recreate_container(self, container, **override_options):
  170. """Recreate a container. An intermediate container is created so that
  171. the new container has the same name, while still supporting
  172. `volumes-from` the original container.
  173. """
  174. try:
  175. container.stop()
  176. except APIError as e:
  177. if (e.response.status_code == 500
  178. and e.explanation
  179. and 'no such process' in str(e.explanation)):
  180. pass
  181. else:
  182. raise
  183. intermediate_container = Container.create(
  184. self.client,
  185. image=container.image,
  186. entrypoint=['/bin/echo'],
  187. command=[],
  188. )
  189. intermediate_container.start(volumes_from=container.id)
  190. intermediate_container.wait()
  191. container.remove()
  192. options = dict(override_options)
  193. new_container = self.create_container(**options)
  194. self.start_container(new_container, intermediate_container=intermediate_container)
  195. intermediate_container.remove()
  196. return (intermediate_container, new_container)
  197. def start_container_if_stopped(self, container, **options):
  198. if container.is_running:
  199. return container
  200. else:
  201. log.info("Starting %s..." % container.name)
  202. return self.start_container(container, **options)
  203. def start_container(self, container=None, intermediate_container=None, **override_options):
  204. container = container or self.create_container(**override_options)
  205. options = dict(self.options, **override_options)
  206. ports = dict(split_port(port) for port in options.get('ports') or [])
  207. volume_bindings = dict(
  208. build_volume_binding(parse_volume_spec(volume))
  209. for volume in options.get('volumes') or []
  210. if ':' in volume)
  211. privileged = options.get('privileged', False)
  212. net = options.get('net', 'bridge')
  213. dns = options.get('dns', None)
  214. container.start(
  215. links=self._get_links(link_to_self=options.get('one_off', False)),
  216. port_bindings=ports,
  217. binds=volume_bindings,
  218. volumes_from=self._get_volumes_from(intermediate_container),
  219. privileged=privileged,
  220. network_mode=net,
  221. dns=dns,
  222. )
  223. return container
  224. def start_or_create_containers(self, insecure_registry=False):
  225. containers = self.containers(stopped=True)
  226. if not containers:
  227. log.info("Creating %s..." % self._next_container_name(containers))
  228. new_container = self.create_container(insecure_registry=insecure_registry)
  229. return [self.start_container(new_container)]
  230. else:
  231. return [self.start_container_if_stopped(c) for c in containers]
  232. def get_linked_names(self):
  233. return [s.name for (s, _) in self.links]
  234. def _next_container_name(self, all_containers, one_off=False):
  235. bits = [self.project, self.name]
  236. if one_off:
  237. bits.append('run')
  238. return '_'.join(bits + [str(self._next_container_number(all_containers))])
  239. def _next_container_number(self, all_containers):
  240. numbers = [parse_name(c.name).number for c in all_containers]
  241. return 1 if not numbers else max(numbers) + 1
  242. def _get_links(self, link_to_self):
  243. links = []
  244. for service, link_name in self.links:
  245. for container in service.containers():
  246. links.append((container.name, link_name or service.name))
  247. links.append((container.name, container.name))
  248. links.append((container.name, container.name_without_project))
  249. if link_to_self:
  250. for container in self.containers():
  251. links.append((container.name, self.name))
  252. links.append((container.name, container.name))
  253. links.append((container.name, container.name_without_project))
  254. return links
  255. def _get_volumes_from(self, intermediate_container=None):
  256. volumes_from = []
  257. for volume_source in self.volumes_from:
  258. if isinstance(volume_source, Service):
  259. containers = volume_source.containers(stopped=True)
  260. if not containers:
  261. volumes_from.append(volume_source.create_container().id)
  262. else:
  263. volumes_from.extend(map(attrgetter('id'), containers))
  264. elif isinstance(volume_source, Container):
  265. volumes_from.append(volume_source.id)
  266. if intermediate_container:
  267. volumes_from.append(intermediate_container.id)
  268. return volumes_from
  269. def _get_container_create_options(self, override_options, one_off=False):
  270. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  271. container_options.update(override_options)
  272. container_options['name'] = self._next_container_name(
  273. self.containers(stopped=True, one_off=one_off),
  274. one_off)
  275. # If a qualified hostname was given, split it into an
  276. # unqualified hostname and a domainname unless domainname
  277. # was also given explicitly. This matches the behavior of
  278. # the official Docker CLI in that scenario.
  279. if ('hostname' in container_options
  280. and 'domainname' not in container_options
  281. and '.' in container_options['hostname']):
  282. parts = container_options['hostname'].partition('.')
  283. container_options['hostname'] = parts[0]
  284. container_options['domainname'] = parts[2]
  285. if 'ports' in container_options or 'expose' in self.options:
  286. ports = []
  287. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  288. for port in all_ports:
  289. port = str(port)
  290. if ':' in port:
  291. port = port.split(':')[-1]
  292. if '/' in port:
  293. port = tuple(port.split('/'))
  294. ports.append(port)
  295. container_options['ports'] = ports
  296. if 'volumes' in container_options:
  297. container_options['volumes'] = dict(
  298. (parse_volume_spec(v).internal, {})
  299. for v in container_options['volumes'])
  300. if 'environment' in container_options:
  301. if isinstance(container_options['environment'], list):
  302. container_options['environment'] = dict(split_env(e) for e in container_options['environment'])
  303. container_options['environment'] = dict(resolve_env(k, v) for k, v in container_options['environment'].iteritems())
  304. if self.can_be_built():
  305. if len(self.client.images(name=self._build_tag_name())) == 0:
  306. self.build()
  307. container_options['image'] = self._build_tag_name()
  308. # Delete options which are only used when starting
  309. for key in ['privileged', 'net', 'dns']:
  310. if key in container_options:
  311. del container_options[key]
  312. return container_options
  313. def build(self, no_cache=False):
  314. log.info('Building %s...' % self.name)
  315. build_output = self.client.build(
  316. self.options['build'],
  317. tag=self._build_tag_name(),
  318. stream=True,
  319. rm=True,
  320. nocache=no_cache,
  321. )
  322. try:
  323. all_events = stream_output(build_output, sys.stdout)
  324. except StreamOutputError, e:
  325. raise BuildError(self, unicode(e))
  326. image_id = None
  327. for event in all_events:
  328. if 'stream' in event:
  329. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  330. if match:
  331. image_id = match.group(1)
  332. if image_id is None:
  333. raise BuildError(self)
  334. return image_id
  335. def can_be_built(self):
  336. return 'build' in self.options
  337. def _build_tag_name(self):
  338. """
  339. The tag to give to images built for this service.
  340. """
  341. return '%s_%s' % (self.project, self.name)
  342. def can_be_scaled(self):
  343. for port in self.options.get('ports', []):
  344. if ':' in str(port):
  345. return False
  346. return True
  347. def pull(self, insecure_registry=False):
  348. if 'image' in self.options:
  349. log.info('Pulling %s (%s)...' % (self.name, self.options.get('image')))
  350. self.client.pull(
  351. self.options.get('image'),
  352. insecure_registry=insecure_registry
  353. )
  354. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  355. def is_valid_name(name, one_off=False):
  356. match = NAME_RE.match(name)
  357. if match is None:
  358. return False
  359. if one_off:
  360. return match.group(3) == 'run_'
  361. else:
  362. return match.group(3) is None
  363. def parse_name(name):
  364. match = NAME_RE.match(name)
  365. (project, service_name, _, suffix) = match.groups()
  366. return ServiceName(project, service_name, int(suffix))
  367. def get_container_name(container):
  368. if not container.get('Name') and not container.get('Names'):
  369. return None
  370. # inspect
  371. if 'Name' in container:
  372. return container['Name']
  373. # ps
  374. for name in container['Names']:
  375. if len(name.split('/')) == 2:
  376. return name[1:]
  377. def parse_volume_spec(volume_config):
  378. parts = volume_config.split(':')
  379. if len(parts) > 3:
  380. raise ConfigError("Volume %s has incorrect format, should be "
  381. "external:internal[:mode]" % volume_config)
  382. if len(parts) == 1:
  383. return VolumeSpec(None, parts[0], 'rw')
  384. if len(parts) == 2:
  385. parts.append('rw')
  386. external, internal, mode = parts
  387. if mode not in ('rw', 'ro'):
  388. raise ConfigError("Volume %s has invalid mode (%s), should be "
  389. "one of: rw, ro." % (volume_config, mode))
  390. return VolumeSpec(external, internal, mode)
  391. def build_volume_binding(volume_spec):
  392. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  393. external = os.path.expanduser(volume_spec.external)
  394. return os.path.abspath(os.path.expandvars(external)), internal
  395. def split_port(port):
  396. parts = str(port).split(':')
  397. if not 1 <= len(parts) <= 3:
  398. raise ConfigError('Invalid port "%s", should be '
  399. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  400. if len(parts) == 1:
  401. internal_port, = parts
  402. return internal_port, None
  403. if len(parts) == 2:
  404. external_port, internal_port = parts
  405. return internal_port, external_port
  406. external_ip, external_port, internal_port = parts
  407. return internal_port, (external_ip, external_port or None)
  408. def split_env(env):
  409. if '=' in env:
  410. return env.split('=', 1)
  411. else:
  412. return env, None
  413. def resolve_env(key, val):
  414. if val is not None:
  415. return key, val
  416. elif key in os.environ:
  417. return key, os.environ[key]
  418. else:
  419. return key, ''