service.py 64 KB

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