service.py 55 KB

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