1
0

service.py 56 KB

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