service.py 65 KB

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