service.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. import re
  6. import sys
  7. from collections import namedtuple
  8. from operator import attrgetter
  9. import enum
  10. import six
  11. from docker.errors import APIError
  12. from docker.errors import ImageNotFound
  13. from docker.errors import NotFound
  14. from docker.types import LogConfig
  15. from docker.utils.ports import build_port_bindings
  16. from docker.utils.ports import split_port
  17. from docker.utils.utils import convert_tmpfs_mounts
  18. from . import __version__
  19. from . import const
  20. from . import progress_stream
  21. from .config import DOCKER_CONFIG_KEYS
  22. from .config import merge_environment
  23. from .config.errors import DependencyError
  24. from .config.types import ServicePort
  25. from .config.types import VolumeSpec
  26. from .const import DEFAULT_TIMEOUT
  27. from .const import IS_WINDOWS_PLATFORM
  28. from .const import LABEL_CONFIG_HASH
  29. from .const import LABEL_CONTAINER_NUMBER
  30. from .const import LABEL_ONE_OFF
  31. from .const import LABEL_PROJECT
  32. from .const import LABEL_SERVICE
  33. from .const import LABEL_VERSION
  34. from .const import NANOCPUS_SCALE
  35. from .container import Container
  36. from .errors import HealthCheckFailed
  37. from .errors import NoHealthCheckConfigured
  38. from .errors import OperationFailedError
  39. from .parallel import parallel_execute
  40. from .progress_stream import stream_output
  41. from .progress_stream import StreamOutputError
  42. from .utils import json_hash
  43. from .utils import parse_seconds_float
  44. log = logging.getLogger(__name__)
  45. HOST_CONFIG_KEYS = [
  46. 'cap_add',
  47. 'cap_drop',
  48. 'cgroup_parent',
  49. 'cpu_count',
  50. 'cpu_percent',
  51. 'cpu_quota',
  52. 'cpu_shares',
  53. 'cpus',
  54. 'cpuset',
  55. 'devices',
  56. 'dns',
  57. 'dns_search',
  58. 'dns_opt',
  59. 'env_file',
  60. 'extra_hosts',
  61. 'group_add',
  62. 'init',
  63. 'ipc',
  64. 'read_only',
  65. 'log_driver',
  66. 'log_opt',
  67. 'mem_limit',
  68. 'mem_reservation',
  69. 'memswap_limit',
  70. 'mem_swappiness',
  71. 'oom_score_adj',
  72. 'pid',
  73. 'pids_limit',
  74. 'privileged',
  75. 'restart',
  76. 'security_opt',
  77. 'shm_size',
  78. 'storage_opt',
  79. 'sysctls',
  80. 'userns_mode',
  81. 'volumes_from',
  82. 'volume_driver',
  83. ]
  84. CONDITION_STARTED = 'service_started'
  85. CONDITION_HEALTHY = 'service_healthy'
  86. class BuildError(Exception):
  87. def __init__(self, service, reason):
  88. self.service = service
  89. self.reason = reason
  90. class NeedsBuildError(Exception):
  91. def __init__(self, service):
  92. self.service = service
  93. class NoSuchImageError(Exception):
  94. pass
  95. ServiceName = namedtuple('ServiceName', 'project service number')
  96. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  97. @enum.unique
  98. class ConvergenceStrategy(enum.Enum):
  99. """Enumeration for all possible convergence strategies. Values refer to
  100. when containers should be recreated.
  101. """
  102. changed = 1
  103. always = 2
  104. never = 3
  105. @property
  106. def allows_recreate(self):
  107. return self is not type(self).never
  108. @enum.unique
  109. class ImageType(enum.Enum):
  110. """Enumeration for the types of images known to compose."""
  111. none = 0
  112. local = 1
  113. all = 2
  114. @enum.unique
  115. class BuildAction(enum.Enum):
  116. """Enumeration for the possible build actions."""
  117. none = 0
  118. force = 1
  119. skip = 2
  120. class Service(object):
  121. def __init__(
  122. self,
  123. name,
  124. client=None,
  125. project='default',
  126. use_networking=False,
  127. links=None,
  128. volumes_from=None,
  129. network_mode=None,
  130. networks=None,
  131. secrets=None,
  132. scale=None,
  133. pid_mode=None,
  134. **options
  135. ):
  136. self.name = name
  137. self.client = client
  138. self.project = project
  139. self.use_networking = use_networking
  140. self.links = links or []
  141. self.volumes_from = volumes_from or []
  142. self.network_mode = network_mode or NetworkMode(None)
  143. self.pid_mode = pid_mode or PidMode(None)
  144. self.networks = networks or {}
  145. self.secrets = secrets or []
  146. self.scale_num = scale or 1
  147. self.options = options
  148. def __repr__(self):
  149. return '<Service: {}>'.format(self.name)
  150. def containers(self, stopped=False, one_off=False, filters={}):
  151. filters.update({'label': self.labels(one_off=one_off)})
  152. return list(filter(None, [
  153. Container.from_ps(self.client, container)
  154. for container in self.client.containers(
  155. all=stopped,
  156. filters=filters)]))
  157. def get_container(self, number=1):
  158. """Return a :class:`compose.container.Container` for this service. The
  159. container must be active, and match `number`.
  160. """
  161. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  162. for container in self.client.containers(filters={'label': labels}):
  163. return Container.from_ps(self.client, container)
  164. raise ValueError("No container found for %s_%s" % (self.name, number))
  165. def start(self, **options):
  166. containers = self.containers(stopped=True)
  167. for c in containers:
  168. self.start_container_if_stopped(c, **options)
  169. return containers
  170. def show_scale_warnings(self, desired_num):
  171. if self.custom_container_name and desired_num > 1:
  172. log.warn('The "%s" service is using the custom container name "%s". '
  173. 'Docker requires each container to have a unique name. '
  174. 'Remove the custom name to scale the service.'
  175. % (self.name, self.custom_container_name))
  176. if self.specifies_host_port() and desired_num > 1:
  177. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  178. 'for this service are created on a single host, the port will clash.'
  179. % self.name)
  180. def scale(self, desired_num, timeout=None):
  181. """
  182. Adjusts the number of containers to the specified number and ensures
  183. they are running.
  184. - creates containers until there are at least `desired_num`
  185. - stops containers until there are at most `desired_num` running
  186. - starts containers until there are at least `desired_num` running
  187. - removes all stopped containers
  188. """
  189. self.show_scale_warnings(desired_num)
  190. running_containers = self.containers(stopped=False)
  191. num_running = len(running_containers)
  192. if desired_num == num_running:
  193. # do nothing as we already have the desired number
  194. log.info('Desired container number already achieved')
  195. return
  196. if desired_num > num_running:
  197. all_containers = self.containers(stopped=True)
  198. if num_running != len(all_containers):
  199. # we have some stopped containers, check for divergences
  200. stopped_containers = [
  201. c for c in all_containers if not c.is_running
  202. ]
  203. # Remove containers that have diverged
  204. divergent_containers = [
  205. c for c in stopped_containers if self._containers_have_diverged([c])
  206. ]
  207. for c in divergent_containers:
  208. c.remove()
  209. all_containers = list(set(all_containers) - set(divergent_containers))
  210. sorted_containers = sorted(all_containers, key=attrgetter('number'))
  211. self._execute_convergence_start(
  212. sorted_containers, desired_num, timeout, True, True
  213. )
  214. if desired_num < num_running:
  215. num_to_stop = num_running - desired_num
  216. sorted_running_containers = sorted(
  217. running_containers,
  218. key=attrgetter('number'))
  219. self._downscale(sorted_running_containers[-num_to_stop:], timeout)
  220. def create_container(self,
  221. one_off=False,
  222. previous_container=None,
  223. number=None,
  224. quiet=False,
  225. **override_options):
  226. """
  227. Create a container for this service. If the image doesn't exist, attempt to pull
  228. it.
  229. """
  230. # This is only necessary for `scale` and `volumes_from`
  231. # auto-creating containers to satisfy the dependency.
  232. self.ensure_image_exists()
  233. container_options = self._get_container_create_options(
  234. override_options,
  235. number or self._next_container_number(one_off=one_off),
  236. one_off=one_off,
  237. previous_container=previous_container,
  238. )
  239. if 'name' in container_options and not quiet:
  240. log.info("Creating %s" % container_options['name'])
  241. try:
  242. return Container.create(self.client, **container_options)
  243. except APIError as ex:
  244. raise OperationFailedError("Cannot create container for service %s: %s" %
  245. (self.name, ex.explanation))
  246. def ensure_image_exists(self, do_build=BuildAction.none):
  247. if self.can_be_built() and do_build == BuildAction.force:
  248. self.build()
  249. return
  250. try:
  251. self.image()
  252. return
  253. except NoSuchImageError:
  254. pass
  255. if not self.can_be_built():
  256. self.pull()
  257. return
  258. if do_build == BuildAction.skip:
  259. raise NeedsBuildError(self)
  260. self.build()
  261. log.warn(
  262. "Image for service {} was built because it did not already exist. To "
  263. "rebuild this image you must use `docker-compose build` or "
  264. "`docker-compose up --build`.".format(self.name))
  265. def image(self):
  266. try:
  267. return self.client.inspect_image(self.image_name)
  268. except ImageNotFound:
  269. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  270. @property
  271. def image_name(self):
  272. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  273. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  274. containers = self.containers(stopped=True)
  275. if not containers:
  276. return ConvergencePlan('create', [])
  277. if strategy is ConvergenceStrategy.never:
  278. return ConvergencePlan('start', containers)
  279. if (
  280. strategy is ConvergenceStrategy.always or
  281. self._containers_have_diverged(containers)
  282. ):
  283. return ConvergencePlan('recreate', containers)
  284. stopped = [c for c in containers if not c.is_running]
  285. if stopped:
  286. return ConvergencePlan('start', stopped)
  287. return ConvergencePlan('noop', containers)
  288. def _containers_have_diverged(self, containers):
  289. config_hash = None
  290. try:
  291. config_hash = self.config_hash
  292. except NoSuchImageError as e:
  293. log.debug(
  294. 'Service %s has diverged: %s',
  295. self.name, six.text_type(e),
  296. )
  297. return True
  298. has_diverged = False
  299. for c in containers:
  300. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  301. if container_config_hash != config_hash:
  302. log.debug(
  303. '%s has diverged: %s != %s',
  304. c.name, container_config_hash, config_hash,
  305. )
  306. has_diverged = True
  307. return has_diverged
  308. def _execute_convergence_create(self, scale, detached, start):
  309. i = self._next_container_number()
  310. def create_and_start(service, n):
  311. container = service.create_container(number=n)
  312. if not detached:
  313. container.attach_log_stream()
  314. if start:
  315. self.start_container(container)
  316. return container
  317. containers, errors = parallel_execute(
  318. range(i, i + scale),
  319. lambda n: create_and_start(self, n),
  320. lambda n: self.get_container_name(n),
  321. "Creating"
  322. )
  323. for error in errors.values():
  324. raise OperationFailedError(error)
  325. return containers
  326. def _execute_convergence_recreate(self, containers, scale, timeout, detached, start):
  327. if scale is not None and len(containers) > scale:
  328. self._downscale(containers[scale:], timeout)
  329. containers = containers[:scale]
  330. def recreate(container):
  331. return self.recreate_container(
  332. container, timeout=timeout, attach_logs=not detached,
  333. start_new_container=start
  334. )
  335. containers, errors = parallel_execute(
  336. containers,
  337. recreate,
  338. lambda c: c.name,
  339. "Recreating"
  340. )
  341. for error in errors.values():
  342. raise OperationFailedError(error)
  343. if scale is not None and len(containers) < scale:
  344. containers.extend(self._execute_convergence_create(
  345. scale - len(containers), detached, start
  346. ))
  347. return containers
  348. def _execute_convergence_start(self, containers, scale, timeout, detached, start):
  349. if scale is not None and len(containers) > scale:
  350. self._downscale(containers[scale:], timeout)
  351. containers = containers[:scale]
  352. if start:
  353. _, errors = parallel_execute(
  354. containers,
  355. lambda c: self.start_container_if_stopped(c, attach_logs=not detached),
  356. lambda c: c.name,
  357. "Starting"
  358. )
  359. for error in errors.values():
  360. raise OperationFailedError(error)
  361. if scale is not None and len(containers) < scale:
  362. containers.extend(self._execute_convergence_create(
  363. scale - len(containers), detached, start
  364. ))
  365. return containers
  366. def _downscale(self, containers, timeout=None):
  367. def stop_and_remove(container):
  368. container.stop(timeout=self.stop_timeout(timeout))
  369. container.remove()
  370. parallel_execute(
  371. containers,
  372. stop_and_remove,
  373. lambda c: c.name,
  374. "Stopping and removing",
  375. )
  376. def execute_convergence_plan(self, plan, timeout=None, detached=False,
  377. start=True, scale_override=None, rescale=True):
  378. (action, containers) = plan
  379. scale = scale_override if scale_override is not None else self.scale_num
  380. containers = sorted(containers, key=attrgetter('number'))
  381. self.show_scale_warnings(scale)
  382. if action == 'create':
  383. return self._execute_convergence_create(
  384. scale, detached, start
  385. )
  386. # The create action needs always needs an initial scale, but otherwise,
  387. # we set scale to none in no-rescale scenarios (`run` dependencies)
  388. if not rescale:
  389. scale = None
  390. if action == 'recreate':
  391. return self._execute_convergence_recreate(
  392. containers, scale, timeout, detached, start
  393. )
  394. if action == 'start':
  395. return self._execute_convergence_start(
  396. containers, scale, timeout, detached, start
  397. )
  398. if action == 'noop':
  399. if scale != len(containers):
  400. return self._execute_convergence_start(
  401. containers, scale, timeout, detached, start
  402. )
  403. for c in containers:
  404. log.info("%s is up-to-date" % c.name)
  405. return containers
  406. raise Exception("Invalid action: {}".format(action))
  407. def recreate_container(
  408. self,
  409. container,
  410. timeout=None,
  411. attach_logs=False,
  412. start_new_container=True):
  413. """Recreate a container.
  414. The original container is renamed to a temporary name so that data
  415. volumes can be copied to the new container, before the original
  416. container is removed.
  417. """
  418. log.info("Recreating %s" % container.name)
  419. container.stop(timeout=self.stop_timeout(timeout))
  420. container.rename_to_tmp_name()
  421. new_container = self.create_container(
  422. previous_container=container,
  423. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  424. quiet=True,
  425. )
  426. if attach_logs:
  427. new_container.attach_log_stream()
  428. if start_new_container:
  429. self.start_container(new_container)
  430. container.remove()
  431. return new_container
  432. def stop_timeout(self, timeout):
  433. if timeout is not None:
  434. return timeout
  435. timeout = parse_seconds_float(self.options.get('stop_grace_period'))
  436. if timeout is not None:
  437. return timeout
  438. return DEFAULT_TIMEOUT
  439. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  440. if not container.is_running:
  441. if not quiet:
  442. log.info("Starting %s" % container.name)
  443. if attach_logs:
  444. container.attach_log_stream()
  445. return self.start_container(container)
  446. def start_container(self, container):
  447. self.connect_container_to_networks(container)
  448. try:
  449. container.start()
  450. except APIError as ex:
  451. raise OperationFailedError("Cannot start service %s: %s" % (self.name, ex.explanation))
  452. return container
  453. def connect_container_to_networks(self, container):
  454. connected_networks = container.get('NetworkSettings.Networks')
  455. for network, netdefs in self.networks.items():
  456. if network in connected_networks:
  457. if short_id_alias_exists(container, network):
  458. continue
  459. self.client.disconnect_container_from_network(
  460. container.id,
  461. network)
  462. self.client.connect_container_to_network(
  463. container.id, network,
  464. aliases=self._get_aliases(netdefs, container),
  465. ipv4_address=netdefs.get('ipv4_address', None),
  466. ipv6_address=netdefs.get('ipv6_address', None),
  467. links=self._get_links(False),
  468. link_local_ips=netdefs.get('link_local_ips', None),
  469. )
  470. def remove_duplicate_containers(self, timeout=None):
  471. for c in self.duplicate_containers():
  472. log.info('Removing %s' % c.name)
  473. c.stop(timeout=self.stop_timeout(timeout))
  474. c.remove()
  475. def duplicate_containers(self):
  476. containers = sorted(
  477. self.containers(stopped=True),
  478. key=lambda c: c.get('Created'),
  479. )
  480. numbers = set()
  481. for c in containers:
  482. if c.number in numbers:
  483. yield c
  484. else:
  485. numbers.add(c.number)
  486. @property
  487. def config_hash(self):
  488. return json_hash(self.config_dict())
  489. def config_dict(self):
  490. return {
  491. 'options': self.options,
  492. 'image_id': self.image()['Id'],
  493. 'links': self.get_link_names(),
  494. 'net': self.network_mode.id,
  495. 'networks': self.networks,
  496. 'volumes_from': [
  497. (v.source.name, v.mode)
  498. for v in self.volumes_from if isinstance(v.source, Service)
  499. ],
  500. }
  501. def get_dependency_names(self):
  502. net_name = self.network_mode.service_name
  503. pid_namespace = self.pid_mode.service_name
  504. return (
  505. self.get_linked_service_names() +
  506. self.get_volumes_from_names() +
  507. ([net_name] if net_name else []) +
  508. ([pid_namespace] if pid_namespace else []) +
  509. list(self.options.get('depends_on', {}).keys())
  510. )
  511. def get_dependency_configs(self):
  512. net_name = self.network_mode.service_name
  513. pid_namespace = self.pid_mode.service_name
  514. configs = dict(
  515. [(name, None) for name in self.get_linked_service_names()]
  516. )
  517. configs.update(dict(
  518. [(name, None) for name in self.get_volumes_from_names()]
  519. ))
  520. configs.update({net_name: None} if net_name else {})
  521. configs.update({pid_namespace: None} if pid_namespace else {})
  522. configs.update(self.options.get('depends_on', {}))
  523. for svc, config in self.options.get('depends_on', {}).items():
  524. if config['condition'] == CONDITION_STARTED:
  525. configs[svc] = lambda s: True
  526. elif config['condition'] == CONDITION_HEALTHY:
  527. configs[svc] = lambda s: s.is_healthy()
  528. else:
  529. # The config schema already prevents this, but it might be
  530. # bypassed if Compose is called programmatically.
  531. raise ValueError(
  532. 'depends_on condition "{}" is invalid.'.format(
  533. config['condition']
  534. )
  535. )
  536. return configs
  537. def get_linked_service_names(self):
  538. return [service.name for (service, _) in self.links]
  539. def get_link_names(self):
  540. return [(service.name, alias) for service, alias in self.links]
  541. def get_volumes_from_names(self):
  542. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  543. # TODO: this would benefit from github.com/docker/docker/pull/14699
  544. # to remove the need to inspect every container
  545. def _next_container_number(self, one_off=False):
  546. containers = filter(None, [
  547. Container.from_ps(self.client, container)
  548. for container in self.client.containers(
  549. all=True,
  550. filters={'label': self.labels(one_off=one_off)})
  551. ])
  552. numbers = [c.number for c in containers]
  553. return 1 if not numbers else max(numbers) + 1
  554. def _get_aliases(self, network, container=None):
  555. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  556. return []
  557. return list(
  558. {self.name} |
  559. ({container.short_id} if container else set()) |
  560. set(network.get('aliases', ()))
  561. )
  562. def build_default_networking_config(self):
  563. if not self.networks:
  564. return {}
  565. network = self.networks[self.network_mode.id]
  566. endpoint = {
  567. 'Aliases': self._get_aliases(network),
  568. 'IPAMConfig': {},
  569. }
  570. if network.get('ipv4_address'):
  571. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  572. if network.get('ipv6_address'):
  573. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  574. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  575. def _get_links(self, link_to_self):
  576. links = {}
  577. for service, link_name in self.links:
  578. for container in service.containers():
  579. links[link_name or service.name] = container.name
  580. links[container.name] = container.name
  581. links[container.name_without_project] = container.name
  582. if link_to_self:
  583. for container in self.containers():
  584. links[self.name] = container.name
  585. links[container.name] = container.name
  586. links[container.name_without_project] = container.name
  587. for external_link in self.options.get('external_links') or []:
  588. if ':' not in external_link:
  589. link_name = external_link
  590. else:
  591. external_link, link_name = external_link.split(':')
  592. links[link_name] = external_link
  593. return [
  594. (alias, container_name)
  595. for (container_name, alias) in links.items()
  596. ]
  597. def _get_volumes_from(self):
  598. return [build_volume_from(spec) for spec in self.volumes_from]
  599. def _get_container_create_options(
  600. self,
  601. override_options,
  602. number,
  603. one_off=False,
  604. previous_container=None):
  605. add_config_hash = (not one_off and not override_options)
  606. container_options = dict(
  607. (k, self.options[k])
  608. for k in DOCKER_CONFIG_KEYS if k in self.options)
  609. override_options['volumes'] = (container_options.get('volumes', []) +
  610. override_options.get('volumes', []))
  611. container_options.update(override_options)
  612. if not container_options.get('name'):
  613. container_options['name'] = self.get_container_name(number, one_off)
  614. container_options.setdefault('detach', True)
  615. # If a qualified hostname was given, split it into an
  616. # unqualified hostname and a domainname unless domainname
  617. # was also given explicitly. This matches the behavior of
  618. # the official Docker CLI in that scenario.
  619. if ('hostname' in container_options and
  620. 'domainname' not in container_options and
  621. '.' in container_options['hostname']):
  622. parts = container_options['hostname'].partition('.')
  623. container_options['hostname'] = parts[0]
  624. container_options['domainname'] = parts[2]
  625. if 'ports' in container_options or 'expose' in self.options:
  626. container_options['ports'] = build_container_ports(
  627. formatted_ports(container_options.get('ports', [])),
  628. self.options)
  629. container_options['environment'] = merge_environment(
  630. self.options.get('environment'),
  631. override_options.get('environment'))
  632. binds, affinity = merge_volume_bindings(
  633. container_options.get('volumes') or [],
  634. self.options.get('tmpfs') or [],
  635. previous_container)
  636. override_options['binds'] = binds
  637. container_options['environment'].update(affinity)
  638. container_options['volumes'] = dict(
  639. (v.internal, {}) for v in container_options.get('volumes') or {})
  640. secret_volumes = self.get_secret_volumes()
  641. if secret_volumes:
  642. override_options['binds'].extend(v.repr() for v in secret_volumes)
  643. container_options['volumes'].update(
  644. (v.internal, {}) for v in secret_volumes)
  645. container_options['image'] = self.image_name
  646. container_options['labels'] = build_container_labels(
  647. container_options.get('labels', {}),
  648. self.labels(one_off=one_off),
  649. number,
  650. self.config_hash if add_config_hash else None)
  651. # Delete options which are only used in HostConfig
  652. for key in HOST_CONFIG_KEYS:
  653. container_options.pop(key, None)
  654. container_options['host_config'] = self._get_container_host_config(
  655. override_options,
  656. one_off=one_off)
  657. networking_config = self.build_default_networking_config()
  658. if networking_config:
  659. container_options['networking_config'] = networking_config
  660. container_options['environment'] = format_environment(
  661. container_options['environment'])
  662. return container_options
  663. def _get_container_host_config(self, override_options, one_off=False):
  664. options = dict(self.options, **override_options)
  665. logging_dict = options.get('logging', None)
  666. log_config = get_log_config(logging_dict)
  667. init_path = None
  668. if isinstance(options.get('init'), six.string_types):
  669. init_path = options.get('init')
  670. options['init'] = True
  671. nano_cpus = None
  672. if 'cpus' in options:
  673. nano_cpus = int(options.get('cpus') * NANOCPUS_SCALE)
  674. return self.client.create_host_config(
  675. links=self._get_links(link_to_self=one_off),
  676. port_bindings=build_port_bindings(
  677. formatted_ports(options.get('ports', []))
  678. ),
  679. binds=options.get('binds'),
  680. volumes_from=self._get_volumes_from(),
  681. privileged=options.get('privileged', False),
  682. network_mode=self.network_mode.mode,
  683. devices=options.get('devices'),
  684. dns=options.get('dns'),
  685. dns_opt=options.get('dns_opt'),
  686. dns_search=options.get('dns_search'),
  687. restart_policy=options.get('restart'),
  688. cap_add=options.get('cap_add'),
  689. cap_drop=options.get('cap_drop'),
  690. mem_limit=options.get('mem_limit'),
  691. mem_reservation=options.get('mem_reservation'),
  692. memswap_limit=options.get('memswap_limit'),
  693. ulimits=build_ulimits(options.get('ulimits')),
  694. log_config=log_config,
  695. extra_hosts=options.get('extra_hosts'),
  696. read_only=options.get('read_only'),
  697. pid_mode=self.pid_mode.mode,
  698. security_opt=options.get('security_opt'),
  699. ipc_mode=options.get('ipc'),
  700. cgroup_parent=options.get('cgroup_parent'),
  701. cpu_quota=options.get('cpu_quota'),
  702. shm_size=options.get('shm_size'),
  703. sysctls=options.get('sysctls'),
  704. pids_limit=options.get('pids_limit'),
  705. tmpfs=options.get('tmpfs'),
  706. oom_score_adj=options.get('oom_score_adj'),
  707. mem_swappiness=options.get('mem_swappiness'),
  708. group_add=options.get('group_add'),
  709. userns_mode=options.get('userns_mode'),
  710. init=options.get('init', None),
  711. init_path=init_path,
  712. isolation=options.get('isolation'),
  713. cpu_count=options.get('cpu_count'),
  714. cpu_percent=options.get('cpu_percent'),
  715. nano_cpus=nano_cpus,
  716. volume_driver=options.get('volume_driver'),
  717. cpuset_cpus=options.get('cpuset'),
  718. cpu_shares=options.get('cpu_shares'),
  719. storage_opt=options.get('storage_opt')
  720. )
  721. def get_secret_volumes(self):
  722. def build_spec(secret):
  723. target = '{}/{}'.format(
  724. const.SECRETS_PATH,
  725. secret['secret'].target or secret['secret'].source)
  726. return VolumeSpec(secret['file'], target, 'ro')
  727. return [build_spec(secret) for secret in self.secrets]
  728. def build(self, no_cache=False, pull=False, force_rm=False, build_args_override=None):
  729. log.info('Building %s' % self.name)
  730. build_opts = self.options.get('build', {})
  731. build_args = build_opts.get('args', {}).copy()
  732. if build_args_override:
  733. build_args.update(build_args_override)
  734. # python2 os.stat() doesn't support unicode on some UNIX, so we
  735. # encode it to a bytestring to be safe
  736. path = build_opts.get('context')
  737. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  738. path = path.encode('utf8')
  739. build_output = self.client.build(
  740. path=path,
  741. tag=self.image_name,
  742. stream=True,
  743. rm=True,
  744. forcerm=force_rm,
  745. pull=pull,
  746. nocache=no_cache,
  747. dockerfile=build_opts.get('dockerfile', None),
  748. cache_from=build_opts.get('cache_from', None),
  749. labels=build_opts.get('labels', None),
  750. buildargs=build_args
  751. )
  752. try:
  753. all_events = stream_output(build_output, sys.stdout)
  754. except StreamOutputError as e:
  755. raise BuildError(self, six.text_type(e))
  756. # Ensure the HTTP connection is not reused for another
  757. # streaming command, as the Docker daemon can sometimes
  758. # complain about it
  759. self.client.close()
  760. image_id = None
  761. for event in all_events:
  762. if 'stream' in event:
  763. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  764. if match:
  765. image_id = match.group(1)
  766. if image_id is None:
  767. raise BuildError(self, event if all_events else 'Unknown')
  768. return image_id
  769. def can_be_built(self):
  770. return 'build' in self.options
  771. def labels(self, one_off=False):
  772. return [
  773. '{0}={1}'.format(LABEL_PROJECT, self.project),
  774. '{0}={1}'.format(LABEL_SERVICE, self.name),
  775. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  776. ]
  777. @property
  778. def custom_container_name(self):
  779. return self.options.get('container_name')
  780. def get_container_name(self, number, one_off=False):
  781. if self.custom_container_name and not one_off:
  782. return self.custom_container_name
  783. container_name = build_container_name(
  784. self.project, self.name, number, one_off,
  785. )
  786. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  787. if container_name in ext_links_origins:
  788. raise DependencyError(
  789. 'Service {0} has a self-referential external link: {1}'.format(
  790. self.name, container_name
  791. )
  792. )
  793. return container_name
  794. def remove_image(self, image_type):
  795. if not image_type or image_type == ImageType.none:
  796. return False
  797. if image_type == ImageType.local and self.options.get('image'):
  798. return False
  799. log.info("Removing image %s", self.image_name)
  800. try:
  801. self.client.remove_image(self.image_name)
  802. return True
  803. except APIError as e:
  804. log.error("Failed to remove image for service %s: %s", self.name, e)
  805. return False
  806. def specifies_host_port(self):
  807. def has_host_port(binding):
  808. if isinstance(binding, dict):
  809. external_bindings = binding.get('published')
  810. else:
  811. _, external_bindings = split_port(binding)
  812. # there are no external bindings
  813. if external_bindings is None:
  814. return False
  815. # we only need to check the first binding from the range
  816. external_binding = external_bindings[0]
  817. # non-tuple binding means there is a host port specified
  818. if not isinstance(external_binding, tuple):
  819. return True
  820. # extract actual host port from tuple of (host_ip, host_port)
  821. _, host_port = external_binding
  822. if host_port is not None:
  823. return True
  824. return False
  825. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  826. def pull(self, ignore_pull_failures=False, silent=False):
  827. if 'image' not in self.options:
  828. return
  829. repo, tag, separator = parse_repository_tag(self.options['image'])
  830. tag = tag or 'latest'
  831. if not silent:
  832. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  833. try:
  834. output = self.client.pull(repo, tag=tag, stream=True)
  835. if silent:
  836. with open(os.devnull, 'w') as devnull:
  837. return progress_stream.get_digest_from_pull(
  838. stream_output(output, devnull))
  839. else:
  840. return progress_stream.get_digest_from_pull(
  841. stream_output(output, sys.stdout))
  842. except (StreamOutputError, NotFound) as e:
  843. if not ignore_pull_failures:
  844. raise
  845. else:
  846. log.error(six.text_type(e))
  847. def push(self, ignore_push_failures=False):
  848. if 'image' not in self.options or 'build' not in self.options:
  849. return
  850. repo, tag, separator = parse_repository_tag(self.options['image'])
  851. tag = tag or 'latest'
  852. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  853. output = self.client.push(repo, tag=tag, stream=True)
  854. try:
  855. return progress_stream.get_digest_from_push(
  856. stream_output(output, sys.stdout))
  857. except StreamOutputError as e:
  858. if not ignore_push_failures:
  859. raise
  860. else:
  861. log.error(six.text_type(e))
  862. def is_healthy(self):
  863. """ Check that all containers for this service report healthy.
  864. Returns false if at least one healthcheck is pending.
  865. If an unhealthy container is detected, raise a HealthCheckFailed
  866. exception.
  867. """
  868. result = True
  869. for ctnr in self.containers():
  870. ctnr.inspect()
  871. status = ctnr.get('State.Health.Status')
  872. if status is None:
  873. raise NoHealthCheckConfigured(self.name)
  874. elif status == 'starting':
  875. result = False
  876. elif status == 'unhealthy':
  877. raise HealthCheckFailed(ctnr.short_id)
  878. return result
  879. def short_id_alias_exists(container, network):
  880. aliases = container.get(
  881. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  882. return container.short_id in aliases
  883. class PidMode(object):
  884. def __init__(self, mode):
  885. self._mode = mode
  886. @property
  887. def mode(self):
  888. return self._mode
  889. @property
  890. def service_name(self):
  891. return None
  892. class ServicePidMode(PidMode):
  893. def __init__(self, service):
  894. self.service = service
  895. @property
  896. def service_name(self):
  897. return self.service.name
  898. @property
  899. def mode(self):
  900. containers = self.service.containers()
  901. if containers:
  902. return 'container:' + containers[0].id
  903. log.warn(
  904. "Service %s is trying to use reuse the PID namespace "
  905. "of another service that is not running." % (self.service_name)
  906. )
  907. return None
  908. class ContainerPidMode(PidMode):
  909. def __init__(self, container):
  910. self.container = container
  911. self._mode = 'container:{}'.format(container.id)
  912. class NetworkMode(object):
  913. """A `standard` network mode (ex: host, bridge)"""
  914. service_name = None
  915. def __init__(self, network_mode):
  916. self.network_mode = network_mode
  917. @property
  918. def id(self):
  919. return self.network_mode
  920. mode = id
  921. class ContainerNetworkMode(object):
  922. """A network mode that uses a container's network stack."""
  923. service_name = None
  924. def __init__(self, container):
  925. self.container = container
  926. @property
  927. def id(self):
  928. return self.container.id
  929. @property
  930. def mode(self):
  931. return 'container:' + self.container.id
  932. class ServiceNetworkMode(object):
  933. """A network mode that uses a service's network stack."""
  934. def __init__(self, service):
  935. self.service = service
  936. @property
  937. def id(self):
  938. return self.service.name
  939. service_name = id
  940. @property
  941. def mode(self):
  942. containers = self.service.containers()
  943. if containers:
  944. return 'container:' + containers[0].id
  945. log.warn("Service %s is trying to use reuse the network stack "
  946. "of another service that is not running." % (self.id))
  947. return None
  948. # Names
  949. def build_container_name(project, service, number, one_off=False):
  950. bits = [project, service]
  951. if one_off:
  952. bits.append('run')
  953. return '_'.join(bits + [str(number)])
  954. # Images
  955. def parse_repository_tag(repo_path):
  956. """Splits image identification into base image path, tag/digest
  957. and it's separator.
  958. Example:
  959. >>> parse_repository_tag('user/repo@sha256:digest')
  960. ('user/repo', 'sha256:digest', '@')
  961. >>> parse_repository_tag('user/repo:v1')
  962. ('user/repo', 'v1', ':')
  963. """
  964. tag_separator = ":"
  965. digest_separator = "@"
  966. if digest_separator in repo_path:
  967. repo, tag = repo_path.rsplit(digest_separator, 1)
  968. return repo, tag, digest_separator
  969. repo, tag = repo_path, ""
  970. if tag_separator in repo_path:
  971. repo, tag = repo_path.rsplit(tag_separator, 1)
  972. if "/" in tag:
  973. repo, tag = repo_path, ""
  974. return repo, tag, tag_separator
  975. # Volumes
  976. def merge_volume_bindings(volumes, tmpfs, previous_container):
  977. """Return a list of volume bindings for a container. Container data volumes
  978. are replaced by those from the previous container.
  979. """
  980. affinity = {}
  981. volume_bindings = dict(
  982. build_volume_binding(volume)
  983. for volume in volumes
  984. if volume.external)
  985. if previous_container:
  986. old_volumes = get_container_data_volumes(previous_container, volumes, tmpfs)
  987. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  988. volume_bindings.update(
  989. build_volume_binding(volume) for volume in old_volumes)
  990. if old_volumes:
  991. affinity = {'affinity:container': '=' + previous_container.id}
  992. return list(volume_bindings.values()), affinity
  993. def get_container_data_volumes(container, volumes_option, tmpfs_option):
  994. """Find the container data volumes that are in `volumes_option`, and return
  995. a mapping of volume bindings for those volumes.
  996. """
  997. volumes = []
  998. volumes_option = volumes_option or []
  999. container_mounts = dict(
  1000. (mount['Destination'], mount)
  1001. for mount in container.get('Mounts') or {}
  1002. )
  1003. image_volumes = [
  1004. VolumeSpec.parse(volume)
  1005. for volume in
  1006. container.image_config['ContainerConfig'].get('Volumes') or {}
  1007. ]
  1008. for volume in set(volumes_option + image_volumes):
  1009. # No need to preserve host volumes
  1010. if volume.external:
  1011. continue
  1012. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  1013. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  1014. continue
  1015. mount = container_mounts.get(volume.internal)
  1016. # New volume, doesn't exist in the old container
  1017. if not mount:
  1018. continue
  1019. # Volume was previously a host volume, now it's a container volume
  1020. if not mount.get('Name'):
  1021. continue
  1022. # Copy existing volume from old container
  1023. volume = volume._replace(external=mount['Name'])
  1024. volumes.append(volume)
  1025. return volumes
  1026. def warn_on_masked_volume(volumes_option, container_volumes, service):
  1027. container_volumes = dict(
  1028. (volume.internal, volume.external)
  1029. for volume in container_volumes)
  1030. for volume in volumes_option:
  1031. if (
  1032. volume.external and
  1033. volume.internal in container_volumes and
  1034. container_volumes.get(volume.internal) != volume.external
  1035. ):
  1036. log.warn((
  1037. "Service \"{service}\" is using volume \"{volume}\" from the "
  1038. "previous container. Host mapping \"{host_path}\" has no effect. "
  1039. "Remove the existing containers (with `docker-compose rm {service}`) "
  1040. "to use the host volume mapping."
  1041. ).format(
  1042. service=service,
  1043. volume=volume.internal,
  1044. host_path=volume.external))
  1045. def build_volume_binding(volume_spec):
  1046. return volume_spec.internal, volume_spec.repr()
  1047. def build_volume_from(volume_from_spec):
  1048. """
  1049. volume_from can be either a service or a container. We want to return the
  1050. container.id and format it into a string complete with the mode.
  1051. """
  1052. if isinstance(volume_from_spec.source, Service):
  1053. containers = volume_from_spec.source.containers(stopped=True)
  1054. if not containers:
  1055. return "{}:{}".format(
  1056. volume_from_spec.source.create_container().id,
  1057. volume_from_spec.mode)
  1058. container = containers[0]
  1059. return "{}:{}".format(container.id, volume_from_spec.mode)
  1060. elif isinstance(volume_from_spec.source, Container):
  1061. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1062. # Labels
  1063. def build_container_labels(label_options, service_labels, number, config_hash):
  1064. labels = dict(label_options or {})
  1065. labels.update(label.split('=', 1) for label in service_labels)
  1066. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1067. labels[LABEL_VERSION] = __version__
  1068. if config_hash:
  1069. log.debug("Added config hash: %s" % config_hash)
  1070. labels[LABEL_CONFIG_HASH] = config_hash
  1071. return labels
  1072. # Ulimits
  1073. def build_ulimits(ulimit_config):
  1074. if not ulimit_config:
  1075. return None
  1076. ulimits = []
  1077. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1078. if isinstance(soft_hard_values, six.integer_types):
  1079. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1080. elif isinstance(soft_hard_values, dict):
  1081. ulimit_dict = {'name': limit_name}
  1082. ulimit_dict.update(soft_hard_values)
  1083. ulimits.append(ulimit_dict)
  1084. return ulimits
  1085. def get_log_config(logging_dict):
  1086. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1087. log_options = logging_dict.get('options', None) if logging_dict else None
  1088. return LogConfig(
  1089. type=log_driver,
  1090. config=log_options
  1091. )
  1092. # TODO: remove once fix is available in docker-py
  1093. def format_environment(environment):
  1094. def format_env(key, value):
  1095. if value is None:
  1096. return key
  1097. if isinstance(value, six.binary_type):
  1098. value = value.decode('utf-8')
  1099. return '{key}={value}'.format(key=key, value=value)
  1100. return [format_env(*item) for item in environment.items()]
  1101. # Ports
  1102. def formatted_ports(ports):
  1103. result = []
  1104. for port in ports:
  1105. if isinstance(port, ServicePort):
  1106. result.append(port.legacy_repr())
  1107. else:
  1108. result.append(port)
  1109. return result
  1110. def build_container_ports(container_ports, options):
  1111. ports = []
  1112. all_ports = container_ports + options.get('expose', [])
  1113. for port_range in all_ports:
  1114. internal_range, _ = split_port(port_range)
  1115. for port in internal_range:
  1116. port = str(port)
  1117. if '/' in port:
  1118. port = tuple(port.split('/'))
  1119. ports.append(port)
  1120. return ports