service.py 55 KB

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