service.py 65 KB

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