service.py 56 KB

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