service.py 62 KB

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