service.py 68 KB

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