service.py 55 KB

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