service.py 65 KB

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