service.py 65 KB

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