service.py 67 KB

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