service.py 64 KB

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