service.py 64 KB

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