service.py 63 KB

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