service.py 56 KB

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