service.py 47 KB

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