service.py 47 KB

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