service.py 66 KB

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