service.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. def image_id():
  548. try:
  549. return self.image()['Id']
  550. except NoSuchImageError:
  551. return None
  552. return {
  553. 'options': self.options,
  554. 'image_id': image_id(),
  555. 'links': self.get_link_names(),
  556. 'net': self.network_mode.id,
  557. 'networks': self.networks,
  558. 'volumes_from': [
  559. (v.source.name, v.mode)
  560. for v in self.volumes_from if isinstance(v.source, Service)
  561. ],
  562. }
  563. def get_dependency_names(self):
  564. net_name = self.network_mode.service_name
  565. pid_namespace = self.pid_mode.service_name
  566. return (
  567. self.get_linked_service_names() +
  568. self.get_volumes_from_names() +
  569. ([net_name] if net_name else []) +
  570. ([pid_namespace] if pid_namespace else []) +
  571. list(self.options.get('depends_on', {}).keys())
  572. )
  573. def get_dependency_configs(self):
  574. net_name = self.network_mode.service_name
  575. pid_namespace = self.pid_mode.service_name
  576. configs = dict(
  577. [(name, None) for name in self.get_linked_service_names()]
  578. )
  579. configs.update(dict(
  580. [(name, None) for name in self.get_volumes_from_names()]
  581. ))
  582. configs.update({net_name: None} if net_name else {})
  583. configs.update({pid_namespace: None} if pid_namespace else {})
  584. configs.update(self.options.get('depends_on', {}))
  585. for svc, config in self.options.get('depends_on', {}).items():
  586. if config['condition'] == CONDITION_STARTED:
  587. configs[svc] = lambda s: True
  588. elif config['condition'] == CONDITION_HEALTHY:
  589. configs[svc] = lambda s: s.is_healthy()
  590. else:
  591. # The config schema already prevents this, but it might be
  592. # bypassed if Compose is called programmatically.
  593. raise ValueError(
  594. 'depends_on condition "{}" is invalid.'.format(
  595. config['condition']
  596. )
  597. )
  598. return configs
  599. def get_linked_service_names(self):
  600. return [service.name for (service, _) in self.links]
  601. def get_link_names(self):
  602. return [(service.name, alias) for service, alias in self.links]
  603. def get_volumes_from_names(self):
  604. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  605. # TODO: this would benefit from github.com/docker/docker/pull/14699
  606. # to remove the need to inspect every container
  607. def _next_container_number(self, one_off=False):
  608. containers = itertools.chain(
  609. self._fetch_containers(
  610. all=True,
  611. filters={'label': self.labels(one_off=one_off)}
  612. ), self._fetch_containers(
  613. all=True,
  614. filters={'label': self.labels(one_off=one_off, legacy=True)}
  615. )
  616. )
  617. numbers = [c.number for c in containers]
  618. return 1 if not numbers else max(numbers) + 1
  619. def _fetch_containers(self, **fetch_options):
  620. # Account for containers that might have been removed since we fetched
  621. # the list.
  622. def soft_inspect(container):
  623. try:
  624. return Container.from_id(self.client, container['Id'])
  625. except NotFound:
  626. return None
  627. return filter(None, [
  628. soft_inspect(container)
  629. for container in self.client.containers(**fetch_options)
  630. ])
  631. def _get_aliases(self, network, container=None):
  632. return list(
  633. {self.name} |
  634. ({container.short_id} if container else set()) |
  635. set(network.get('aliases', ()))
  636. )
  637. def build_default_networking_config(self):
  638. if not self.networks:
  639. return {}
  640. network = self.networks[self.network_mode.id]
  641. endpoint = {
  642. 'Aliases': self._get_aliases(network),
  643. 'IPAMConfig': {},
  644. }
  645. if network.get('ipv4_address'):
  646. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  647. if network.get('ipv6_address'):
  648. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  649. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  650. def _get_links(self, link_to_self):
  651. links = {}
  652. for service, link_name in self.links:
  653. for container in service.containers():
  654. links[link_name or service.name] = container.name
  655. links[container.name] = container.name
  656. links[container.name_without_project] = container.name
  657. if link_to_self:
  658. for container in self.containers():
  659. links[self.name] = container.name
  660. links[container.name] = container.name
  661. links[container.name_without_project] = container.name
  662. for external_link in self.options.get('external_links') or []:
  663. if ':' not in external_link:
  664. link_name = external_link
  665. else:
  666. external_link, link_name = external_link.split(':')
  667. links[link_name] = external_link
  668. return [
  669. (alias, container_name)
  670. for (container_name, alias) in links.items()
  671. ]
  672. def _get_volumes_from(self):
  673. return [build_volume_from(spec) for spec in self.volumes_from]
  674. def _get_container_create_options(
  675. self,
  676. override_options,
  677. number,
  678. one_off=False,
  679. previous_container=None):
  680. add_config_hash = (not one_off and not override_options)
  681. container_options = dict(
  682. (k, self.options[k])
  683. for k in DOCKER_CONFIG_KEYS if k in self.options)
  684. override_volumes = override_options.pop('volumes', [])
  685. container_options.update(override_options)
  686. if not container_options.get('name'):
  687. container_options['name'] = self.get_container_name(self.name, number, one_off)
  688. container_options.setdefault('detach', True)
  689. # If a qualified hostname was given, split it into an
  690. # unqualified hostname and a domainname unless domainname
  691. # was also given explicitly. This matches behavior
  692. # until Docker Engine 1.11.0 - Docker API 1.23.
  693. if (version_lt(self.client.api_version, '1.23') and
  694. 'hostname' in container_options and
  695. 'domainname' not in container_options and
  696. '.' in container_options['hostname']):
  697. parts = container_options['hostname'].partition('.')
  698. container_options['hostname'] = parts[0]
  699. container_options['domainname'] = parts[2]
  700. if (version_gte(self.client.api_version, '1.25') and
  701. 'stop_grace_period' in self.options):
  702. container_options['stop_timeout'] = self.stop_timeout(None)
  703. if 'ports' in container_options or 'expose' in self.options:
  704. container_options['ports'] = build_container_ports(
  705. formatted_ports(container_options.get('ports', [])),
  706. self.options)
  707. if 'volumes' in container_options or override_volumes:
  708. container_options['volumes'] = list(set(
  709. container_options.get('volumes', []) + override_volumes
  710. ))
  711. container_options['environment'] = merge_environment(
  712. self._parse_proxy_config(),
  713. merge_environment(
  714. self.options.get('environment'),
  715. override_options.get('environment')
  716. )
  717. )
  718. container_options['labels'] = merge_labels(
  719. self.options.get('labels'),
  720. override_options.get('labels'))
  721. container_options, override_options = self._build_container_volume_options(
  722. previous_container, container_options, override_options
  723. )
  724. container_options['image'] = self.image_name
  725. container_options['labels'] = build_container_labels(
  726. container_options.get('labels', {}),
  727. self.labels(one_off=one_off),
  728. number,
  729. self.config_hash if add_config_hash else None)
  730. # Delete options which are only used in HostConfig
  731. for key in HOST_CONFIG_KEYS:
  732. container_options.pop(key, None)
  733. container_options['host_config'] = self._get_container_host_config(
  734. override_options,
  735. one_off=one_off)
  736. networking_config = self.build_default_networking_config()
  737. if networking_config:
  738. container_options['networking_config'] = networking_config
  739. container_options['environment'] = format_environment(
  740. container_options['environment'])
  741. return container_options
  742. def _build_container_volume_options(self, previous_container, container_options, override_options):
  743. container_volumes = []
  744. container_mounts = []
  745. if 'volumes' in container_options:
  746. container_volumes = [
  747. v for v in container_options.get('volumes') if isinstance(v, VolumeSpec)
  748. ]
  749. container_mounts = [v for v in container_options.get('volumes') if isinstance(v, MountSpec)]
  750. binds, affinity = merge_volume_bindings(
  751. container_volumes, self.options.get('tmpfs') or [], previous_container,
  752. container_mounts
  753. )
  754. container_options['environment'].update(affinity)
  755. container_options['volumes'] = dict((v.internal, {}) for v in container_volumes or {})
  756. if version_gte(self.client.api_version, '1.30'):
  757. override_options['mounts'] = [build_mount(v) for v in container_mounts] or None
  758. else:
  759. # Workaround for 3.2 format
  760. override_options['tmpfs'] = self.options.get('tmpfs') or []
  761. for m in container_mounts:
  762. if m.is_tmpfs:
  763. override_options['tmpfs'].append(m.target)
  764. else:
  765. binds.append(m.legacy_repr())
  766. container_options['volumes'][m.target] = {}
  767. secret_volumes = self.get_secret_volumes()
  768. if secret_volumes:
  769. if version_lt(self.client.api_version, '1.30'):
  770. binds.extend(v.legacy_repr() for v in secret_volumes)
  771. container_options['volumes'].update(
  772. (v.target, {}) for v in secret_volumes
  773. )
  774. else:
  775. override_options['mounts'] = override_options.get('mounts') or []
  776. override_options['mounts'].extend([build_mount(v) for v in secret_volumes])
  777. # Remove possible duplicates (see e.g. https://github.com/docker/compose/issues/5885)
  778. override_options['binds'] = list(set(binds))
  779. return container_options, override_options
  780. def _get_container_host_config(self, override_options, one_off=False):
  781. options = dict(self.options, **override_options)
  782. logging_dict = options.get('logging', None)
  783. blkio_config = convert_blkio_config(options.get('blkio_config', None))
  784. log_config = get_log_config(logging_dict)
  785. init_path = None
  786. if isinstance(options.get('init'), six.string_types):
  787. init_path = options.get('init')
  788. options['init'] = True
  789. security_opt = [
  790. o.value for o in options.get('security_opt')
  791. ] if options.get('security_opt') else None
  792. nano_cpus = None
  793. if 'cpus' in options:
  794. nano_cpus = int(options.get('cpus') * NANOCPUS_SCALE)
  795. return self.client.create_host_config(
  796. links=self._get_links(link_to_self=one_off),
  797. port_bindings=build_port_bindings(
  798. formatted_ports(options.get('ports', []))
  799. ),
  800. binds=options.get('binds'),
  801. volumes_from=self._get_volumes_from(),
  802. privileged=options.get('privileged', False),
  803. network_mode=self.network_mode.mode,
  804. devices=options.get('devices'),
  805. dns=options.get('dns'),
  806. dns_opt=options.get('dns_opt'),
  807. dns_search=options.get('dns_search'),
  808. restart_policy=options.get('restart'),
  809. runtime=options.get('runtime'),
  810. cap_add=options.get('cap_add'),
  811. cap_drop=options.get('cap_drop'),
  812. mem_limit=options.get('mem_limit'),
  813. mem_reservation=options.get('mem_reservation'),
  814. memswap_limit=options.get('memswap_limit'),
  815. ulimits=build_ulimits(options.get('ulimits')),
  816. log_config=log_config,
  817. extra_hosts=options.get('extra_hosts'),
  818. read_only=options.get('read_only'),
  819. pid_mode=self.pid_mode.mode,
  820. security_opt=security_opt,
  821. ipc_mode=options.get('ipc'),
  822. cgroup_parent=options.get('cgroup_parent'),
  823. cpu_quota=options.get('cpu_quota'),
  824. shm_size=options.get('shm_size'),
  825. sysctls=options.get('sysctls'),
  826. pids_limit=options.get('pids_limit'),
  827. tmpfs=options.get('tmpfs'),
  828. oom_kill_disable=options.get('oom_kill_disable'),
  829. oom_score_adj=options.get('oom_score_adj'),
  830. mem_swappiness=options.get('mem_swappiness'),
  831. group_add=options.get('group_add'),
  832. userns_mode=options.get('userns_mode'),
  833. init=options.get('init', None),
  834. init_path=init_path,
  835. isolation=options.get('isolation'),
  836. cpu_count=options.get('cpu_count'),
  837. cpu_percent=options.get('cpu_percent'),
  838. nano_cpus=nano_cpus,
  839. volume_driver=options.get('volume_driver'),
  840. cpuset_cpus=options.get('cpuset'),
  841. cpu_shares=options.get('cpu_shares'),
  842. storage_opt=options.get('storage_opt'),
  843. blkio_weight=blkio_config.get('weight'),
  844. blkio_weight_device=blkio_config.get('weight_device'),
  845. device_read_bps=blkio_config.get('device_read_bps'),
  846. device_read_iops=blkio_config.get('device_read_iops'),
  847. device_write_bps=blkio_config.get('device_write_bps'),
  848. device_write_iops=blkio_config.get('device_write_iops'),
  849. mounts=options.get('mounts'),
  850. device_cgroup_rules=options.get('device_cgroup_rules'),
  851. cpu_period=options.get('cpu_period'),
  852. cpu_rt_period=options.get('cpu_rt_period'),
  853. cpu_rt_runtime=options.get('cpu_rt_runtime'),
  854. )
  855. def get_secret_volumes(self):
  856. def build_spec(secret):
  857. target = secret['secret'].target
  858. if target is None:
  859. target = '{}/{}'.format(const.SECRETS_PATH, secret['secret'].source)
  860. elif not os.path.isabs(target):
  861. target = '{}/{}'.format(const.SECRETS_PATH, target)
  862. return MountSpec('bind', secret['file'], target, read_only=True)
  863. return [build_spec(secret) for secret in self.secrets]
  864. def build(self, no_cache=False, pull=False, force_rm=False, memory=None, build_args_override=None,
  865. gzip=False):
  866. log.info('Building %s' % self.name)
  867. build_opts = self.options.get('build', {})
  868. build_args = build_opts.get('args', {}).copy()
  869. if build_args_override:
  870. build_args.update(build_args_override)
  871. for k, v in self._parse_proxy_config().items():
  872. build_args.setdefault(k, v)
  873. # python2 os.stat() doesn't support unicode on some UNIX, so we
  874. # encode it to a bytestring to be safe
  875. path = build_opts.get('context')
  876. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  877. path = path.encode('utf8')
  878. if self.platform and version_lt(self.client.api_version, '1.35'):
  879. raise OperationFailedError(
  880. 'Impossible to perform platform-targeted builds for API version < 1.35'
  881. )
  882. build_output = self.client.build(
  883. path=path,
  884. tag=self.image_name,
  885. rm=True,
  886. forcerm=force_rm,
  887. pull=pull,
  888. nocache=no_cache,
  889. dockerfile=build_opts.get('dockerfile', None),
  890. cache_from=build_opts.get('cache_from', None),
  891. labels=build_opts.get('labels', None),
  892. buildargs=build_args,
  893. network_mode=build_opts.get('network', None),
  894. target=build_opts.get('target', None),
  895. shmsize=parse_bytes(build_opts.get('shm_size')) if build_opts.get('shm_size') else None,
  896. extra_hosts=build_opts.get('extra_hosts', None),
  897. container_limits={
  898. 'memory': parse_bytes(memory) if memory else None
  899. },
  900. gzip=gzip,
  901. isolation=build_opts.get('isolation', self.options.get('isolation', None)),
  902. platform=self.platform,
  903. )
  904. try:
  905. all_events = stream_output(build_output, sys.stdout)
  906. except StreamOutputError as e:
  907. raise BuildError(self, six.text_type(e))
  908. # Ensure the HTTP connection is not reused for another
  909. # streaming command, as the Docker daemon can sometimes
  910. # complain about it
  911. self.client.close()
  912. image_id = None
  913. for event in all_events:
  914. if 'stream' in event:
  915. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  916. if match:
  917. image_id = match.group(1)
  918. if image_id is None:
  919. raise BuildError(self, event if all_events else 'Unknown')
  920. return image_id
  921. def can_be_built(self):
  922. return 'build' in self.options
  923. def labels(self, one_off=False, legacy=False):
  924. proj_name = self.project if not legacy else re.sub(r'[_-]', '', self.project)
  925. return [
  926. '{0}={1}'.format(LABEL_PROJECT, proj_name),
  927. '{0}={1}'.format(LABEL_SERVICE, self.name),
  928. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False"),
  929. ]
  930. @property
  931. def custom_container_name(self):
  932. return self.options.get('container_name')
  933. def get_container_name(self, service_name, number, one_off=False):
  934. if self.custom_container_name and not one_off:
  935. return self.custom_container_name
  936. container_name = build_container_name(
  937. self.project, service_name, number, one_off,
  938. )
  939. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  940. if container_name in ext_links_origins:
  941. raise DependencyError(
  942. 'Service {0} has a self-referential external link: {1}'.format(
  943. self.name, container_name
  944. )
  945. )
  946. return container_name
  947. def remove_image(self, image_type):
  948. if not image_type or image_type == ImageType.none:
  949. return False
  950. if image_type == ImageType.local and self.options.get('image'):
  951. return False
  952. log.info("Removing image %s", self.image_name)
  953. try:
  954. self.client.remove_image(self.image_name)
  955. return True
  956. except APIError as e:
  957. log.error("Failed to remove image for service %s: %s", self.name, e)
  958. return False
  959. def specifies_host_port(self):
  960. def has_host_port(binding):
  961. if isinstance(binding, dict):
  962. external_bindings = binding.get('published')
  963. else:
  964. _, external_bindings = split_port(binding)
  965. # there are no external bindings
  966. if external_bindings is None:
  967. return False
  968. # we only need to check the first binding from the range
  969. external_binding = external_bindings[0]
  970. # non-tuple binding means there is a host port specified
  971. if not isinstance(external_binding, tuple):
  972. return True
  973. # extract actual host port from tuple of (host_ip, host_port)
  974. _, host_port = external_binding
  975. if host_port is not None:
  976. return True
  977. return False
  978. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  979. def pull(self, ignore_pull_failures=False, silent=False):
  980. if 'image' not in self.options:
  981. return
  982. repo, tag, separator = parse_repository_tag(self.options['image'])
  983. kwargs = {
  984. 'tag': tag or 'latest',
  985. 'stream': True,
  986. 'platform': self.platform,
  987. }
  988. if not silent:
  989. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  990. if kwargs['platform'] and version_lt(self.client.api_version, '1.35'):
  991. raise OperationFailedError(
  992. 'Impossible to perform platform-targeted pulls for API version < 1.35'
  993. )
  994. try:
  995. output = self.client.pull(repo, **kwargs)
  996. if silent:
  997. with open(os.devnull, 'w') as devnull:
  998. return progress_stream.get_digest_from_pull(
  999. stream_output(output, devnull))
  1000. else:
  1001. return progress_stream.get_digest_from_pull(
  1002. stream_output(output, sys.stdout))
  1003. except (StreamOutputError, NotFound) as e:
  1004. if not ignore_pull_failures:
  1005. raise
  1006. else:
  1007. log.error(six.text_type(e))
  1008. def push(self, ignore_push_failures=False):
  1009. if 'image' not in self.options or 'build' not in self.options:
  1010. return
  1011. repo, tag, separator = parse_repository_tag(self.options['image'])
  1012. tag = tag or 'latest'
  1013. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  1014. output = self.client.push(repo, tag=tag, stream=True)
  1015. try:
  1016. return progress_stream.get_digest_from_push(
  1017. stream_output(output, sys.stdout))
  1018. except StreamOutputError as e:
  1019. if not ignore_push_failures:
  1020. raise
  1021. else:
  1022. log.error(six.text_type(e))
  1023. def is_healthy(self):
  1024. """ Check that all containers for this service report healthy.
  1025. Returns false if at least one healthcheck is pending.
  1026. If an unhealthy container is detected, raise a HealthCheckFailed
  1027. exception.
  1028. """
  1029. result = True
  1030. for ctnr in self.containers():
  1031. ctnr.inspect()
  1032. status = ctnr.get('State.Health.Status')
  1033. if status is None:
  1034. raise NoHealthCheckConfigured(self.name)
  1035. elif status == 'starting':
  1036. result = False
  1037. elif status == 'unhealthy':
  1038. raise HealthCheckFailed(ctnr.short_id)
  1039. return result
  1040. def _parse_proxy_config(self):
  1041. client = self.client
  1042. if 'proxies' not in client._general_configs:
  1043. return {}
  1044. docker_host = getattr(client, '_original_base_url', client.base_url)
  1045. proxy_config = client._general_configs['proxies'].get(
  1046. docker_host, client._general_configs['proxies'].get('default')
  1047. ) or {}
  1048. permitted = {
  1049. 'ftpProxy': 'FTP_PROXY',
  1050. 'httpProxy': 'HTTP_PROXY',
  1051. 'httpsProxy': 'HTTPS_PROXY',
  1052. 'noProxy': 'NO_PROXY',
  1053. }
  1054. result = {}
  1055. for k, v in proxy_config.items():
  1056. if k not in permitted:
  1057. continue
  1058. result[permitted[k]] = result[permitted[k].lower()] = v
  1059. return result
  1060. def short_id_alias_exists(container, network):
  1061. aliases = container.get(
  1062. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  1063. return container.short_id in aliases
  1064. class PidMode(object):
  1065. def __init__(self, mode):
  1066. self._mode = mode
  1067. @property
  1068. def mode(self):
  1069. return self._mode
  1070. @property
  1071. def service_name(self):
  1072. return None
  1073. class ServicePidMode(PidMode):
  1074. def __init__(self, service):
  1075. self.service = service
  1076. @property
  1077. def service_name(self):
  1078. return self.service.name
  1079. @property
  1080. def mode(self):
  1081. containers = self.service.containers()
  1082. if containers:
  1083. return 'container:' + containers[0].id
  1084. log.warn(
  1085. "Service %s is trying to use reuse the PID namespace "
  1086. "of another service that is not running." % (self.service_name)
  1087. )
  1088. return None
  1089. class ContainerPidMode(PidMode):
  1090. def __init__(self, container):
  1091. self.container = container
  1092. self._mode = 'container:{}'.format(container.id)
  1093. class NetworkMode(object):
  1094. """A `standard` network mode (ex: host, bridge)"""
  1095. service_name = None
  1096. def __init__(self, network_mode):
  1097. self.network_mode = network_mode
  1098. @property
  1099. def id(self):
  1100. return self.network_mode
  1101. mode = id
  1102. class ContainerNetworkMode(object):
  1103. """A network mode that uses a container's network stack."""
  1104. service_name = None
  1105. def __init__(self, container):
  1106. self.container = container
  1107. @property
  1108. def id(self):
  1109. return self.container.id
  1110. @property
  1111. def mode(self):
  1112. return 'container:' + self.container.id
  1113. class ServiceNetworkMode(object):
  1114. """A network mode that uses a service's network stack."""
  1115. def __init__(self, service):
  1116. self.service = service
  1117. @property
  1118. def id(self):
  1119. return self.service.name
  1120. service_name = id
  1121. @property
  1122. def mode(self):
  1123. containers = self.service.containers()
  1124. if containers:
  1125. return 'container:' + containers[0].id
  1126. log.warn("Service %s is trying to use reuse the network stack "
  1127. "of another service that is not running." % (self.id))
  1128. return None
  1129. # Names
  1130. def build_container_name(project, service, number, one_off=False):
  1131. bits = [project.lstrip('-_'), service]
  1132. if one_off:
  1133. bits.append('run')
  1134. return '_'.join(bits + [str(number)])
  1135. # Images
  1136. def parse_repository_tag(repo_path):
  1137. """Splits image identification into base image path, tag/digest
  1138. and it's separator.
  1139. Example:
  1140. >>> parse_repository_tag('user/repo@sha256:digest')
  1141. ('user/repo', 'sha256:digest', '@')
  1142. >>> parse_repository_tag('user/repo:v1')
  1143. ('user/repo', 'v1', ':')
  1144. """
  1145. tag_separator = ":"
  1146. digest_separator = "@"
  1147. if digest_separator in repo_path:
  1148. repo, tag = repo_path.rsplit(digest_separator, 1)
  1149. return repo, tag, digest_separator
  1150. repo, tag = repo_path, ""
  1151. if tag_separator in repo_path:
  1152. repo, tag = repo_path.rsplit(tag_separator, 1)
  1153. if "/" in tag:
  1154. repo, tag = repo_path, ""
  1155. return repo, tag, tag_separator
  1156. # Volumes
  1157. def merge_volume_bindings(volumes, tmpfs, previous_container, mounts):
  1158. """
  1159. Return a list of volume bindings for a container. Container data volumes
  1160. are replaced by those from the previous container.
  1161. Anonymous mounts are updated in place.
  1162. """
  1163. affinity = {}
  1164. volume_bindings = dict(
  1165. build_volume_binding(volume)
  1166. for volume in volumes
  1167. if volume.external
  1168. )
  1169. if previous_container:
  1170. old_volumes, old_mounts = get_container_data_volumes(
  1171. previous_container, volumes, tmpfs, mounts
  1172. )
  1173. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  1174. volume_bindings.update(
  1175. build_volume_binding(volume) for volume in old_volumes
  1176. )
  1177. if old_volumes or old_mounts:
  1178. affinity = {'affinity:container': '=' + previous_container.id}
  1179. return list(volume_bindings.values()), affinity
  1180. def get_container_data_volumes(container, volumes_option, tmpfs_option, mounts_option):
  1181. """
  1182. Find the container data volumes that are in `volumes_option`, and return
  1183. a mapping of volume bindings for those volumes.
  1184. Anonymous volume mounts are updated in place instead.
  1185. """
  1186. volumes = []
  1187. volumes_option = volumes_option or []
  1188. container_mounts = dict(
  1189. (mount['Destination'], mount)
  1190. for mount in container.get('Mounts') or {}
  1191. )
  1192. image_volumes = [
  1193. VolumeSpec.parse(volume)
  1194. for volume in
  1195. container.image_config['ContainerConfig'].get('Volumes') or {}
  1196. ]
  1197. for volume in set(volumes_option + image_volumes):
  1198. # No need to preserve host volumes
  1199. if volume.external:
  1200. continue
  1201. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  1202. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  1203. continue
  1204. mount = container_mounts.get(volume.internal)
  1205. # New volume, doesn't exist in the old container
  1206. if not mount:
  1207. continue
  1208. # Volume was previously a host volume, now it's a container volume
  1209. if not mount.get('Name'):
  1210. continue
  1211. # Copy existing volume from old container
  1212. volume = volume._replace(external=mount['Name'])
  1213. volumes.append(volume)
  1214. updated_mounts = False
  1215. for mount in mounts_option:
  1216. if mount.type != 'volume':
  1217. continue
  1218. ctnr_mount = container_mounts.get(mount.target)
  1219. if not ctnr_mount or not ctnr_mount.get('Name'):
  1220. continue
  1221. mount.source = ctnr_mount['Name']
  1222. updated_mounts = True
  1223. return volumes, updated_mounts
  1224. def warn_on_masked_volume(volumes_option, container_volumes, service):
  1225. container_volumes = dict(
  1226. (volume.internal, volume.external)
  1227. for volume in container_volumes)
  1228. for volume in volumes_option:
  1229. if (
  1230. volume.external and
  1231. volume.internal in container_volumes and
  1232. container_volumes.get(volume.internal) != volume.external
  1233. ):
  1234. log.warn((
  1235. "Service \"{service}\" is using volume \"{volume}\" from the "
  1236. "previous container. Host mapping \"{host_path}\" has no effect. "
  1237. "Remove the existing containers (with `docker-compose rm {service}`) "
  1238. "to use the host volume mapping."
  1239. ).format(
  1240. service=service,
  1241. volume=volume.internal,
  1242. host_path=volume.external))
  1243. def build_volume_binding(volume_spec):
  1244. return volume_spec.internal, volume_spec.repr()
  1245. def build_volume_from(volume_from_spec):
  1246. """
  1247. volume_from can be either a service or a container. We want to return the
  1248. container.id and format it into a string complete with the mode.
  1249. """
  1250. if isinstance(volume_from_spec.source, Service):
  1251. containers = volume_from_spec.source.containers(stopped=True)
  1252. if not containers:
  1253. return "{}:{}".format(
  1254. volume_from_spec.source.create_container().id,
  1255. volume_from_spec.mode)
  1256. container = containers[0]
  1257. return "{}:{}".format(container.id, volume_from_spec.mode)
  1258. elif isinstance(volume_from_spec.source, Container):
  1259. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1260. def build_mount(mount_spec):
  1261. kwargs = {}
  1262. if mount_spec.options:
  1263. for option, sdk_name in mount_spec.options_map[mount_spec.type].items():
  1264. if option in mount_spec.options:
  1265. kwargs[sdk_name] = mount_spec.options[option]
  1266. return Mount(
  1267. type=mount_spec.type, target=mount_spec.target, source=mount_spec.source,
  1268. read_only=mount_spec.read_only, consistency=mount_spec.consistency, **kwargs
  1269. )
  1270. # Labels
  1271. def build_container_labels(label_options, service_labels, number, config_hash):
  1272. labels = dict(label_options or {})
  1273. labels.update(label.split('=', 1) for label in service_labels)
  1274. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1275. labels[LABEL_VERSION] = __version__
  1276. if config_hash:
  1277. log.debug("Added config hash: %s" % config_hash)
  1278. labels[LABEL_CONFIG_HASH] = config_hash
  1279. return labels
  1280. # Ulimits
  1281. def build_ulimits(ulimit_config):
  1282. if not ulimit_config:
  1283. return None
  1284. ulimits = []
  1285. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1286. if isinstance(soft_hard_values, six.integer_types):
  1287. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1288. elif isinstance(soft_hard_values, dict):
  1289. ulimit_dict = {'name': limit_name}
  1290. ulimit_dict.update(soft_hard_values)
  1291. ulimits.append(ulimit_dict)
  1292. return ulimits
  1293. def get_log_config(logging_dict):
  1294. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1295. log_options = logging_dict.get('options', None) if logging_dict else None
  1296. return LogConfig(
  1297. type=log_driver,
  1298. config=log_options
  1299. )
  1300. # TODO: remove once fix is available in docker-py
  1301. def format_environment(environment):
  1302. def format_env(key, value):
  1303. if value is None:
  1304. return key
  1305. if isinstance(value, six.binary_type):
  1306. value = value.decode('utf-8')
  1307. return '{key}={value}'.format(key=key, value=value)
  1308. return [format_env(*item) for item in environment.items()]
  1309. # Ports
  1310. def formatted_ports(ports):
  1311. result = []
  1312. for port in ports:
  1313. if isinstance(port, ServicePort):
  1314. result.append(port.legacy_repr())
  1315. else:
  1316. result.append(port)
  1317. return result
  1318. def build_container_ports(container_ports, options):
  1319. ports = []
  1320. all_ports = container_ports + options.get('expose', [])
  1321. for port_range in all_ports:
  1322. internal_range, _ = split_port(port_range)
  1323. for port in internal_range:
  1324. port = str(port)
  1325. if '/' in port:
  1326. port = tuple(port.split('/'))
  1327. ports.append(port)
  1328. return ports
  1329. def convert_blkio_config(blkio_config):
  1330. result = {}
  1331. if blkio_config is None:
  1332. return result
  1333. result['weight'] = blkio_config.get('weight')
  1334. for field in [
  1335. "device_read_bps", "device_read_iops", "device_write_bps",
  1336. "device_write_iops", "weight_device",
  1337. ]:
  1338. if field not in blkio_config:
  1339. continue
  1340. arr = []
  1341. for item in blkio_config[field]:
  1342. arr.append(dict([(k.capitalize(), v) for k, v in item.items()]))
  1343. result[field] = arr
  1344. return result