service.py 56 KB

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