1
0

service.py 57 KB

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