service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. import six
  11. from .container import Container, get_container_name
  12. from .progress_stream import stream_output, StreamOutputError
  13. log = logging.getLogger(__name__)
  14. DOCKER_CONFIG_KEYS = [
  15. 'cap_add',
  16. 'cap_drop',
  17. 'cpu_shares',
  18. 'command',
  19. 'detach',
  20. 'dns',
  21. 'dns_search',
  22. 'domainname',
  23. 'entrypoint',
  24. 'env_file',
  25. 'environment',
  26. 'hostname',
  27. 'image',
  28. 'mem_limit',
  29. 'net',
  30. 'ports',
  31. 'privileged',
  32. 'restart',
  33. 'stdin_open',
  34. 'tty',
  35. 'user',
  36. 'volumes',
  37. 'volumes_from',
  38. 'working_dir',
  39. ]
  40. DOCKER_CONFIG_HINTS = {
  41. 'cpu_share' : 'cpu_shares',
  42. 'link' : 'links',
  43. 'port' : 'ports',
  44. 'privilege' : 'privileged',
  45. 'priviliged': 'privileged',
  46. 'privilige' : 'privileged',
  47. 'volume' : 'volumes',
  48. 'workdir' : 'working_dir',
  49. }
  50. DOCKER_START_KEYS = [
  51. 'cap_add',
  52. 'cap_drop',
  53. 'dns',
  54. 'dns_search',
  55. 'env_file',
  56. 'net',
  57. 'privileged',
  58. 'restart',
  59. ]
  60. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  61. class BuildError(Exception):
  62. def __init__(self, service, reason):
  63. self.service = service
  64. self.reason = reason
  65. class CannotBeScaledError(Exception):
  66. pass
  67. class ConfigError(ValueError):
  68. pass
  69. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  70. ServiceName = namedtuple('ServiceName', 'project service number')
  71. class Service(object):
  72. def __init__(self, name, client=None, project='default', links=None, external_links=None, volumes_from=None, **options):
  73. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  74. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  75. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  76. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  77. if 'image' in options and 'build' in options:
  78. 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)
  79. for filename in get_env_files(options):
  80. if not os.path.exists(filename):
  81. raise ConfigError("Couldn't find env file for service %s: %s" % (name, filename))
  82. supported_options = DOCKER_CONFIG_KEYS + ['build', 'expose',
  83. 'external_links']
  84. for k in options:
  85. if k not in supported_options:
  86. msg = "Unsupported config option for %s service: '%s'" % (name, k)
  87. if k in DOCKER_CONFIG_HINTS:
  88. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  89. raise ConfigError(msg)
  90. self.name = name
  91. self.client = client
  92. self.project = project
  93. self.links = links or []
  94. self.external_links = external_links or []
  95. self.volumes_from = volumes_from or []
  96. self.options = options
  97. def containers(self, stopped=False, one_off=False):
  98. return [Container.from_ps(self.client, container)
  99. for container in self.client.containers(all=stopped)
  100. if self.has_container(container, one_off=one_off)]
  101. def has_container(self, container, one_off=False):
  102. """Return True if `container` was created to fulfill this service."""
  103. name = get_container_name(container)
  104. if not name or not is_valid_name(name, one_off):
  105. return False
  106. project, name, _number = parse_name(name)
  107. return project == self.project and name == self.name
  108. def get_container(self, number=1):
  109. """Return a :class:`compose.container.Container` for this service. The
  110. container must be active, and match `number`.
  111. """
  112. for container in self.client.containers():
  113. if not self.has_container(container):
  114. continue
  115. _, _, container_number = parse_name(get_container_name(container))
  116. if container_number == number:
  117. return Container.from_ps(self.client, container)
  118. raise ValueError("No container found for %s_%s" % (self.name, number))
  119. def start(self, **options):
  120. for c in self.containers(stopped=True):
  121. self.start_container_if_stopped(c, **options)
  122. def stop(self, **options):
  123. for c in self.containers():
  124. log.info("Stopping %s..." % c.name)
  125. c.stop(**options)
  126. def kill(self, **options):
  127. for c in self.containers():
  128. log.info("Killing %s..." % c.name)
  129. c.kill(**options)
  130. def restart(self, **options):
  131. for c in self.containers():
  132. log.info("Restarting %s..." % c.name)
  133. c.restart(**options)
  134. def scale(self, desired_num):
  135. """
  136. Adjusts the number of containers to the specified number and ensures
  137. they are running.
  138. - creates containers until there are at least `desired_num`
  139. - stops containers until there are at most `desired_num` running
  140. - starts containers until there are at least `desired_num` running
  141. - removes all stopped containers
  142. """
  143. if not self.can_be_scaled():
  144. raise CannotBeScaledError()
  145. # Create enough containers
  146. containers = self.containers(stopped=True)
  147. while len(containers) < desired_num:
  148. log.info("Creating %s..." % self._next_container_name(containers))
  149. containers.append(self.create_container(detach=True))
  150. running_containers = []
  151. stopped_containers = []
  152. for c in containers:
  153. if c.is_running:
  154. running_containers.append(c)
  155. else:
  156. stopped_containers.append(c)
  157. running_containers.sort(key=lambda c: c.number)
  158. stopped_containers.sort(key=lambda c: c.number)
  159. # Stop containers
  160. while len(running_containers) > desired_num:
  161. c = running_containers.pop()
  162. log.info("Stopping %s..." % c.name)
  163. c.stop(timeout=1)
  164. stopped_containers.append(c)
  165. # Start containers
  166. while len(running_containers) < desired_num:
  167. c = stopped_containers.pop(0)
  168. log.info("Starting %s..." % c.name)
  169. self.start_container(c)
  170. running_containers.append(c)
  171. self.remove_stopped()
  172. def remove_stopped(self, **options):
  173. for c in self.containers(stopped=True):
  174. if not c.is_running:
  175. log.info("Removing %s..." % c.name)
  176. c.remove(**options)
  177. def create_container(self,
  178. one_off=False,
  179. insecure_registry=False,
  180. do_build=True,
  181. **override_options):
  182. """
  183. Create a container for this service. If the image doesn't exist, attempt to pull
  184. it.
  185. """
  186. container_options = self._get_container_create_options(
  187. override_options,
  188. one_off=one_off)
  189. if (do_build and
  190. self.can_be_built() and
  191. not self.client.images(name=self.full_name)):
  192. self.build()
  193. try:
  194. return Container.create(self.client, **container_options)
  195. except APIError as e:
  196. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  197. log.info('Pulling image %s...' % container_options['image'])
  198. output = self.client.pull(
  199. container_options['image'],
  200. stream=True,
  201. insecure_registry=insecure_registry
  202. )
  203. stream_output(output, sys.stdout)
  204. return Container.create(self.client, **container_options)
  205. raise
  206. def recreate_containers(self, insecure_registry=False, do_build=True, **override_options):
  207. """
  208. If a container for this service doesn't exist, create and start one. If there are
  209. any, stop them, create+start new ones, and remove the old containers.
  210. """
  211. containers = self.containers(stopped=True)
  212. if not containers:
  213. log.info("Creating %s..." % self._next_container_name(containers))
  214. container = self.create_container(
  215. insecure_registry=insecure_registry,
  216. do_build=do_build,
  217. **override_options)
  218. self.start_container(container)
  219. return [(None, container)]
  220. else:
  221. tuples = []
  222. for c in containers:
  223. log.info("Recreating %s..." % c.name)
  224. tuples.append(self.recreate_container(c, insecure_registry=insecure_registry, **override_options))
  225. return tuples
  226. def recreate_container(self, container, **override_options):
  227. """Recreate a container. An intermediate container is created so that
  228. the new container has the same name, while still supporting
  229. `volumes-from` the original container.
  230. """
  231. try:
  232. container.stop()
  233. except APIError as e:
  234. if (e.response.status_code == 500
  235. and e.explanation
  236. and 'no such process' in str(e.explanation)):
  237. pass
  238. else:
  239. raise
  240. intermediate_container = Container.create(
  241. self.client,
  242. image=container.image,
  243. entrypoint=['/bin/echo'],
  244. command=[],
  245. detach=True,
  246. )
  247. intermediate_container.start(volumes_from=container.id)
  248. intermediate_container.wait()
  249. container.remove()
  250. options = dict(override_options)
  251. new_container = self.create_container(do_build=False, **options)
  252. self.start_container(new_container, intermediate_container=intermediate_container)
  253. intermediate_container.remove()
  254. return (intermediate_container, new_container)
  255. def start_container_if_stopped(self, container, **options):
  256. if container.is_running:
  257. return container
  258. else:
  259. log.info("Starting %s..." % container.name)
  260. return self.start_container(container, **options)
  261. def start_container(self, container, intermediate_container=None, **override_options):
  262. options = dict(self.options, **override_options)
  263. port_bindings = build_port_bindings(options.get('ports') or [])
  264. volume_bindings = dict(
  265. build_volume_binding(parse_volume_spec(volume))
  266. for volume in options.get('volumes') or []
  267. if ':' in volume)
  268. privileged = options.get('privileged', False)
  269. net = options.get('net', 'bridge')
  270. dns = options.get('dns', None)
  271. dns_search = options.get('dns_search', None)
  272. cap_add = options.get('cap_add', None)
  273. cap_drop = options.get('cap_drop', None)
  274. restart = parse_restart_spec(options.get('restart', None))
  275. container.start(
  276. links=self._get_links(link_to_self=options.get('one_off', False)),
  277. port_bindings=port_bindings,
  278. binds=volume_bindings,
  279. volumes_from=self._get_volumes_from(intermediate_container),
  280. privileged=privileged,
  281. network_mode=net,
  282. dns=dns,
  283. dns_search=dns_search,
  284. restart_policy=restart,
  285. cap_add=cap_add,
  286. cap_drop=cap_drop,
  287. )
  288. return container
  289. def start_or_create_containers(
  290. self,
  291. insecure_registry=False,
  292. detach=False,
  293. do_build=True):
  294. containers = self.containers(stopped=True)
  295. if not containers:
  296. log.info("Creating %s..." % self._next_container_name(containers))
  297. new_container = self.create_container(
  298. insecure_registry=insecure_registry,
  299. detach=detach,
  300. do_build=do_build,
  301. )
  302. return [self.start_container(new_container)]
  303. else:
  304. return [self.start_container_if_stopped(c) for c in containers]
  305. def get_linked_names(self):
  306. return [s.name for (s, _) in self.links]
  307. def _next_container_name(self, all_containers, one_off=False):
  308. bits = [self.project, self.name]
  309. if one_off:
  310. bits.append('run')
  311. return '_'.join(bits + [str(self._next_container_number(all_containers))])
  312. def _next_container_number(self, all_containers):
  313. numbers = [parse_name(c.name).number for c in all_containers]
  314. return 1 if not numbers else max(numbers) + 1
  315. def _get_links(self, link_to_self):
  316. links = []
  317. for service, link_name in self.links:
  318. for container in service.containers():
  319. links.append((container.name, link_name or service.name))
  320. links.append((container.name, container.name))
  321. links.append((container.name, container.name_without_project))
  322. if link_to_self:
  323. for container in self.containers():
  324. links.append((container.name, self.name))
  325. links.append((container.name, container.name))
  326. links.append((container.name, container.name_without_project))
  327. for external_link in self.external_links:
  328. if ':' not in external_link:
  329. link_name = external_link
  330. else:
  331. external_link, link_name = external_link.split(':')
  332. links.append((external_link, link_name))
  333. return links
  334. def _get_volumes_from(self, intermediate_container=None):
  335. volumes_from = []
  336. for volume_source in self.volumes_from:
  337. if isinstance(volume_source, Service):
  338. containers = volume_source.containers(stopped=True)
  339. if not containers:
  340. volumes_from.append(volume_source.create_container().id)
  341. else:
  342. volumes_from.extend(map(attrgetter('id'), containers))
  343. elif isinstance(volume_source, Container):
  344. volumes_from.append(volume_source.id)
  345. if intermediate_container:
  346. volumes_from.append(intermediate_container.id)
  347. return volumes_from
  348. def _get_container_create_options(self, override_options, one_off=False):
  349. container_options = dict(
  350. (k, self.options[k])
  351. for k in DOCKER_CONFIG_KEYS if k in self.options)
  352. container_options.update(override_options)
  353. container_options['name'] = self._next_container_name(
  354. self.containers(stopped=True, one_off=one_off),
  355. one_off)
  356. # If a qualified hostname was given, split it into an
  357. # unqualified hostname and a domainname unless domainname
  358. # was also given explicitly. This matches the behavior of
  359. # the official Docker CLI in that scenario.
  360. if ('hostname' in container_options
  361. and 'domainname' not in container_options
  362. and '.' in container_options['hostname']):
  363. parts = container_options['hostname'].partition('.')
  364. container_options['hostname'] = parts[0]
  365. container_options['domainname'] = parts[2]
  366. if 'ports' in container_options or 'expose' in self.options:
  367. ports = []
  368. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  369. for port in all_ports:
  370. port = str(port)
  371. if ':' in port:
  372. port = port.split(':')[-1]
  373. if '/' in port:
  374. port = tuple(port.split('/'))
  375. ports.append(port)
  376. container_options['ports'] = ports
  377. if 'volumes' in container_options:
  378. container_options['volumes'] = dict(
  379. (parse_volume_spec(v).internal, {})
  380. for v in container_options['volumes'])
  381. container_options['environment'] = build_environment(container_options)
  382. if self.can_be_built():
  383. container_options['image'] = self.full_name
  384. else:
  385. container_options['image'] = self._get_image_name(container_options['image'])
  386. # Delete options which are only used when starting
  387. for key in DOCKER_START_KEYS:
  388. container_options.pop(key, None)
  389. return container_options
  390. def _get_image_name(self, image):
  391. repo, tag = parse_repository_tag(image)
  392. if tag == "":
  393. tag = "latest"
  394. return '%s:%s' % (repo, tag)
  395. def build(self, no_cache=False):
  396. log.info('Building %s...' % self.name)
  397. build_output = self.client.build(
  398. self.options['build'],
  399. tag=self.full_name,
  400. stream=True,
  401. rm=True,
  402. nocache=no_cache,
  403. )
  404. try:
  405. all_events = stream_output(build_output, sys.stdout)
  406. except StreamOutputError as e:
  407. raise BuildError(self, unicode(e))
  408. image_id = None
  409. for event in all_events:
  410. if 'stream' in event:
  411. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  412. if match:
  413. image_id = match.group(1)
  414. if image_id is None:
  415. raise BuildError(self, event if all_events else 'Unknown')
  416. return image_id
  417. def can_be_built(self):
  418. return 'build' in self.options
  419. @property
  420. def full_name(self):
  421. """
  422. The tag to give to images built for this service.
  423. """
  424. return '%s_%s' % (self.project, self.name)
  425. def can_be_scaled(self):
  426. for port in self.options.get('ports', []):
  427. if ':' in str(port):
  428. return False
  429. return True
  430. def pull(self, insecure_registry=False):
  431. if 'image' in self.options:
  432. image_name = self._get_image_name(self.options['image'])
  433. log.info('Pulling %s (%s)...' % (self.name, image_name))
  434. self.client.pull(
  435. image_name,
  436. insecure_registry=insecure_registry
  437. )
  438. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  439. def is_valid_name(name, one_off=False):
  440. match = NAME_RE.match(name)
  441. if match is None:
  442. return False
  443. if one_off:
  444. return match.group(3) == 'run_'
  445. else:
  446. return match.group(3) is None
  447. def parse_name(name):
  448. match = NAME_RE.match(name)
  449. (project, service_name, _, suffix) = match.groups()
  450. return ServiceName(project, service_name, int(suffix))
  451. def parse_restart_spec(restart_config):
  452. if not restart_config:
  453. return None
  454. parts = restart_config.split(':')
  455. if len(parts) > 2:
  456. raise ConfigError("Restart %s has incorrect format, should be "
  457. "mode[:max_retry]" % restart_config)
  458. if len(parts) == 2:
  459. name, max_retry_count = parts
  460. else:
  461. name, = parts
  462. max_retry_count = 0
  463. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  464. def parse_volume_spec(volume_config):
  465. parts = volume_config.split(':')
  466. if len(parts) > 3:
  467. raise ConfigError("Volume %s has incorrect format, should be "
  468. "external:internal[:mode]" % volume_config)
  469. if len(parts) == 1:
  470. return VolumeSpec(None, parts[0], 'rw')
  471. if len(parts) == 2:
  472. parts.append('rw')
  473. external, internal, mode = parts
  474. if mode not in ('rw', 'ro'):
  475. raise ConfigError("Volume %s has invalid mode (%s), should be "
  476. "one of: rw, ro." % (volume_config, mode))
  477. return VolumeSpec(external, internal, mode)
  478. def parse_repository_tag(s):
  479. if ":" not in s:
  480. return s, ""
  481. repo, tag = s.rsplit(":", 1)
  482. if "/" in tag:
  483. return s, ""
  484. return repo, tag
  485. def build_volume_binding(volume_spec):
  486. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  487. external = os.path.expanduser(volume_spec.external)
  488. return os.path.abspath(os.path.expandvars(external)), internal
  489. def build_port_bindings(ports):
  490. port_bindings = {}
  491. for port in ports:
  492. internal_port, external = split_port(port)
  493. if internal_port in port_bindings:
  494. port_bindings[internal_port].append(external)
  495. else:
  496. port_bindings[internal_port] = [external]
  497. return port_bindings
  498. def split_port(port):
  499. parts = str(port).split(':')
  500. if not 1 <= len(parts) <= 3:
  501. raise ConfigError('Invalid port "%s", should be '
  502. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  503. if len(parts) == 1:
  504. internal_port, = parts
  505. return internal_port, None
  506. if len(parts) == 2:
  507. external_port, internal_port = parts
  508. return internal_port, external_port
  509. external_ip, external_port, internal_port = parts
  510. return internal_port, (external_ip, external_port or None)
  511. def get_env_files(options):
  512. env_files = options.get('env_file', [])
  513. if not isinstance(env_files, list):
  514. env_files = [env_files]
  515. return env_files
  516. def build_environment(options):
  517. env = {}
  518. for f in get_env_files(options):
  519. env.update(env_vars_from_file(f))
  520. env.update(parse_environment(options.get('environment')))
  521. return dict(resolve_env(k, v) for k, v in six.iteritems(env))
  522. def parse_environment(environment):
  523. if not environment:
  524. return {}
  525. if isinstance(environment, list):
  526. return dict(split_env(e) for e in environment)
  527. if isinstance(environment, dict):
  528. return environment
  529. raise ConfigError("environment \"%s\" must be a list or mapping," %
  530. environment)
  531. def split_env(env):
  532. if '=' in env:
  533. return env.split('=', 1)
  534. else:
  535. return env, None
  536. def resolve_env(key, val):
  537. if val is not None:
  538. return key, val
  539. elif key in os.environ:
  540. return key, os.environ[key]
  541. else:
  542. return key, ''
  543. def env_vars_from_file(filename):
  544. """
  545. Read in a line delimited file of environment variables.
  546. """
  547. env = {}
  548. for line in open(filename, 'r'):
  549. line = line.strip()
  550. if line and not line.startswith('#'):
  551. k, v = split_env(line)
  552. env[k] = v
  553. return env