service.py 56 KB

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