service.py 56 KB

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