service.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. import re
  6. import sys
  7. from collections import namedtuple
  8. from operator import attrgetter
  9. import enum
  10. import six
  11. from docker.errors import APIError
  12. from docker.errors import ImageNotFound
  13. from docker.errors import NotFound
  14. from docker.types import LogConfig
  15. from docker.utils import version_lt
  16. from docker.utils.ports import build_port_bindings
  17. from docker.utils.ports import split_port
  18. from docker.utils.utils import convert_tmpfs_mounts
  19. from . import __version__
  20. from . import const
  21. from . import progress_stream
  22. from .config import DOCKER_CONFIG_KEYS
  23. from .config import merge_environment
  24. from .config.errors import DependencyError
  25. from .config.types import ServicePort
  26. from .config.types import VolumeSpec
  27. from .const import DEFAULT_TIMEOUT
  28. from .const import IS_WINDOWS_PLATFORM
  29. from .const import LABEL_CONFIG_HASH
  30. from .const import LABEL_CONTAINER_NUMBER
  31. from .const import LABEL_ONE_OFF
  32. from .const import LABEL_PROJECT
  33. from .const import LABEL_SERVICE
  34. from .const import LABEL_VERSION
  35. from .const import NANOCPUS_SCALE
  36. from .container import Container
  37. from .errors import HealthCheckFailed
  38. from .errors import NoHealthCheckConfigured
  39. from .errors import OperationFailedError
  40. from .parallel import parallel_execute
  41. from .progress_stream import stream_output
  42. from .progress_stream import StreamOutputError
  43. from .utils import json_hash
  44. from .utils import parse_bytes
  45. from .utils import parse_seconds_float
  46. log = logging.getLogger(__name__)
  47. HOST_CONFIG_KEYS = [
  48. 'cap_add',
  49. 'cap_drop',
  50. 'cgroup_parent',
  51. 'cpu_count',
  52. 'cpu_percent',
  53. 'cpu_quota',
  54. 'cpu_shares',
  55. 'cpus',
  56. 'cpuset',
  57. 'devices',
  58. 'dns',
  59. 'dns_search',
  60. 'dns_opt',
  61. 'env_file',
  62. 'extra_hosts',
  63. 'group_add',
  64. 'init',
  65. 'ipc',
  66. 'read_only',
  67. 'log_driver',
  68. 'log_opt',
  69. 'mem_limit',
  70. 'mem_reservation',
  71. 'memswap_limit',
  72. 'mem_swappiness',
  73. 'oom_kill_disable',
  74. 'oom_score_adj',
  75. 'pid',
  76. 'pids_limit',
  77. 'privileged',
  78. 'restart',
  79. 'security_opt',
  80. 'shm_size',
  81. 'storage_opt',
  82. 'sysctls',
  83. 'userns_mode',
  84. 'volumes_from',
  85. 'volume_driver',
  86. ]
  87. CONDITION_STARTED = 'service_started'
  88. CONDITION_HEALTHY = 'service_healthy'
  89. class BuildError(Exception):
  90. def __init__(self, service, reason):
  91. self.service = service
  92. self.reason = reason
  93. class NeedsBuildError(Exception):
  94. def __init__(self, service):
  95. self.service = service
  96. class NoSuchImageError(Exception):
  97. pass
  98. ServiceName = namedtuple('ServiceName', 'project service number')
  99. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  100. @enum.unique
  101. class ConvergenceStrategy(enum.Enum):
  102. """Enumeration for all possible convergence strategies. Values refer to
  103. when containers should be recreated.
  104. """
  105. changed = 1
  106. always = 2
  107. never = 3
  108. @property
  109. def allows_recreate(self):
  110. return self is not type(self).never
  111. @enum.unique
  112. class ImageType(enum.Enum):
  113. """Enumeration for the types of images known to compose."""
  114. none = 0
  115. local = 1
  116. all = 2
  117. @enum.unique
  118. class BuildAction(enum.Enum):
  119. """Enumeration for the possible build actions."""
  120. none = 0
  121. force = 1
  122. skip = 2
  123. class Service(object):
  124. def __init__(
  125. self,
  126. name,
  127. client=None,
  128. project='default',
  129. use_networking=False,
  130. links=None,
  131. volumes_from=None,
  132. network_mode=None,
  133. networks=None,
  134. secrets=None,
  135. scale=None,
  136. pid_mode=None,
  137. **options
  138. ):
  139. self.name = name
  140. self.client = client
  141. self.project = project
  142. self.use_networking = use_networking
  143. self.links = links or []
  144. self.volumes_from = volumes_from or []
  145. self.network_mode = network_mode or NetworkMode(None)
  146. self.pid_mode = pid_mode or PidMode(None)
  147. self.networks = networks or {}
  148. self.secrets = secrets or []
  149. self.scale_num = scale or 1
  150. self.options = options
  151. def __repr__(self):
  152. return '<Service: {}>'.format(self.name)
  153. def containers(self, stopped=False, one_off=False, filters={}):
  154. filters.update({'label': self.labels(one_off=one_off)})
  155. return list(filter(None, [
  156. Container.from_ps(self.client, container)
  157. for container in self.client.containers(
  158. all=stopped,
  159. filters=filters)]))
  160. def get_container(self, number=1):
  161. """Return a :class:`compose.container.Container` for this service. The
  162. container must be active, and match `number`.
  163. """
  164. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  165. for container in self.client.containers(filters={'label': labels}):
  166. return Container.from_ps(self.client, container)
  167. raise ValueError("No container found for %s_%s" % (self.name, number))
  168. def start(self, **options):
  169. containers = self.containers(stopped=True)
  170. for c in containers:
  171. self.start_container_if_stopped(c, **options)
  172. return containers
  173. def show_scale_warnings(self, desired_num):
  174. if self.custom_container_name and desired_num > 1:
  175. log.warn('The "%s" service is using the custom container name "%s". '
  176. 'Docker requires each container to have a unique name. '
  177. 'Remove the custom name to scale the service.'
  178. % (self.name, self.custom_container_name))
  179. if self.specifies_host_port() and desired_num > 1:
  180. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  181. 'for this service are created on a single host, the port will clash.'
  182. % self.name)
  183. def scale(self, desired_num, timeout=None):
  184. """
  185. Adjusts the number of containers to the specified number and ensures
  186. they are running.
  187. - creates containers until there are at least `desired_num`
  188. - stops containers until there are at most `desired_num` running
  189. - starts containers until there are at least `desired_num` running
  190. - removes all stopped containers
  191. """
  192. self.show_scale_warnings(desired_num)
  193. running_containers = self.containers(stopped=False)
  194. num_running = len(running_containers)
  195. if desired_num == num_running:
  196. # do nothing as we already have the desired number
  197. log.info('Desired container number already achieved')
  198. return
  199. if desired_num > num_running:
  200. all_containers = self.containers(stopped=True)
  201. if num_running != len(all_containers):
  202. # we have some stopped containers, check for divergences
  203. stopped_containers = [
  204. c for c in all_containers if not c.is_running
  205. ]
  206. # Remove containers that have diverged
  207. divergent_containers = [
  208. c for c in stopped_containers if self._containers_have_diverged([c])
  209. ]
  210. for c in divergent_containers:
  211. c.remove()
  212. all_containers = list(set(all_containers) - set(divergent_containers))
  213. sorted_containers = sorted(all_containers, key=attrgetter('number'))
  214. self._execute_convergence_start(
  215. sorted_containers, desired_num, timeout, True, True
  216. )
  217. if desired_num < num_running:
  218. num_to_stop = num_running - desired_num
  219. sorted_running_containers = sorted(
  220. running_containers,
  221. key=attrgetter('number'))
  222. self._downscale(sorted_running_containers[-num_to_stop:], timeout)
  223. def create_container(self,
  224. one_off=False,
  225. previous_container=None,
  226. number=None,
  227. quiet=False,
  228. **override_options):
  229. """
  230. Create a container for this service. If the image doesn't exist, attempt to pull
  231. it.
  232. """
  233. # This is only necessary for `scale` and `volumes_from`
  234. # auto-creating containers to satisfy the dependency.
  235. self.ensure_image_exists()
  236. container_options = self._get_container_create_options(
  237. override_options,
  238. number or self._next_container_number(one_off=one_off),
  239. one_off=one_off,
  240. previous_container=previous_container,
  241. )
  242. if 'name' in container_options and not quiet:
  243. log.info("Creating %s" % container_options['name'])
  244. try:
  245. return Container.create(self.client, **container_options)
  246. except APIError as ex:
  247. raise OperationFailedError("Cannot create container for service %s: %s" %
  248. (self.name, ex.explanation))
  249. def ensure_image_exists(self, do_build=BuildAction.none):
  250. if self.can_be_built() and do_build == BuildAction.force:
  251. self.build()
  252. return
  253. try:
  254. self.image()
  255. return
  256. except NoSuchImageError:
  257. pass
  258. if not self.can_be_built():
  259. self.pull()
  260. return
  261. if do_build == BuildAction.skip:
  262. raise NeedsBuildError(self)
  263. self.build()
  264. log.warn(
  265. "Image for service {} was built because it did not already exist. To "
  266. "rebuild this image you must use `docker-compose build` or "
  267. "`docker-compose up --build`.".format(self.name))
  268. def image(self):
  269. try:
  270. return self.client.inspect_image(self.image_name)
  271. except ImageNotFound:
  272. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  273. @property
  274. def image_name(self):
  275. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  276. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  277. containers = self.containers(stopped=True)
  278. if not containers:
  279. return ConvergencePlan('create', [])
  280. if strategy is ConvergenceStrategy.never:
  281. return ConvergencePlan('start', containers)
  282. if (
  283. strategy is ConvergenceStrategy.always or
  284. self._containers_have_diverged(containers)
  285. ):
  286. return ConvergencePlan('recreate', containers)
  287. stopped = [c for c in containers if not c.is_running]
  288. if stopped:
  289. return ConvergencePlan('start', stopped)
  290. return ConvergencePlan('noop', containers)
  291. def _containers_have_diverged(self, containers):
  292. config_hash = None
  293. try:
  294. config_hash = self.config_hash
  295. except NoSuchImageError as e:
  296. log.debug(
  297. 'Service %s has diverged: %s',
  298. self.name, six.text_type(e),
  299. )
  300. return True
  301. has_diverged = False
  302. for c in containers:
  303. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  304. if container_config_hash != config_hash:
  305. log.debug(
  306. '%s has diverged: %s != %s',
  307. c.name, container_config_hash, config_hash,
  308. )
  309. has_diverged = True
  310. return has_diverged
  311. def _execute_convergence_create(self, scale, detached, start, project_services=None):
  312. i = self._next_container_number()
  313. def create_and_start(service, n):
  314. container = service.create_container(number=n, quiet=True)
  315. if not detached:
  316. container.attach_log_stream()
  317. if start:
  318. self.start_container(container)
  319. return container
  320. containers, errors = parallel_execute(
  321. [ServiceName(self.project, self.name, index) for index in range(i, i + scale)],
  322. lambda service_name: create_and_start(self, service_name.number),
  323. lambda service_name: self.get_container_name(service_name.service, service_name.number),
  324. "Creating",
  325. parent_objects=project_services
  326. )
  327. for error in errors.values():
  328. raise OperationFailedError(error)
  329. return containers
  330. def _execute_convergence_recreate(self, containers, scale, timeout, detached, start):
  331. if scale is not None and len(containers) > scale:
  332. self._downscale(containers[scale:], timeout)
  333. containers = containers[:scale]
  334. def recreate(container):
  335. return self.recreate_container(
  336. container, timeout=timeout, attach_logs=not detached,
  337. start_new_container=start
  338. )
  339. containers, errors = parallel_execute(
  340. containers,
  341. recreate,
  342. lambda c: c.name,
  343. "Recreating",
  344. )
  345. for error in errors.values():
  346. raise OperationFailedError(error)
  347. if scale is not None and len(containers) < scale:
  348. containers.extend(self._execute_convergence_create(
  349. scale - len(containers), detached, start
  350. ))
  351. return containers
  352. def _execute_convergence_start(self, containers, scale, timeout, detached, start):
  353. if scale is not None and len(containers) > scale:
  354. self._downscale(containers[scale:], timeout)
  355. containers = containers[:scale]
  356. if start:
  357. _, errors = parallel_execute(
  358. containers,
  359. lambda c: self.start_container_if_stopped(c, attach_logs=not detached, quiet=True),
  360. lambda c: c.name,
  361. "Starting",
  362. )
  363. for error in errors.values():
  364. raise OperationFailedError(error)
  365. if scale is not None and len(containers) < scale:
  366. containers.extend(self._execute_convergence_create(
  367. scale - len(containers), detached, start
  368. ))
  369. return containers
  370. def _downscale(self, containers, timeout=None):
  371. def stop_and_remove(container):
  372. container.stop(timeout=self.stop_timeout(timeout))
  373. container.remove()
  374. parallel_execute(
  375. containers,
  376. stop_and_remove,
  377. lambda c: c.name,
  378. "Stopping and removing",
  379. )
  380. def execute_convergence_plan(self, plan, timeout=None, detached=False,
  381. start=True, scale_override=None, rescale=True, project_services=None):
  382. (action, containers) = plan
  383. scale = scale_override if scale_override is not None else self.scale_num
  384. containers = sorted(containers, key=attrgetter('number'))
  385. self.show_scale_warnings(scale)
  386. if action == 'create':
  387. return self._execute_convergence_create(
  388. scale, detached, start, project_services
  389. )
  390. # The create action needs always needs an initial scale, but otherwise,
  391. # we set scale to none in no-rescale scenarios (`run` dependencies)
  392. if not rescale:
  393. scale = None
  394. if action == 'recreate':
  395. return self._execute_convergence_recreate(
  396. containers, scale, timeout, detached, start
  397. )
  398. if action == 'start':
  399. return self._execute_convergence_start(
  400. containers, scale, timeout, detached, start
  401. )
  402. if action == 'noop':
  403. if scale != len(containers):
  404. return self._execute_convergence_start(
  405. containers, scale, timeout, detached, start
  406. )
  407. for c in containers:
  408. log.info("%s is up-to-date" % c.name)
  409. return containers
  410. raise Exception("Invalid action: {}".format(action))
  411. def recreate_container(
  412. self,
  413. container,
  414. timeout=None,
  415. attach_logs=False,
  416. start_new_container=True):
  417. """Recreate a container.
  418. The original container is renamed to a temporary name so that data
  419. volumes can be copied to the new container, before the original
  420. container is removed.
  421. """
  422. log.info("Recreating %s" % container.name)
  423. container.stop(timeout=self.stop_timeout(timeout))
  424. container.rename_to_tmp_name()
  425. new_container = self.create_container(
  426. previous_container=container,
  427. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  428. quiet=True,
  429. )
  430. if attach_logs:
  431. new_container.attach_log_stream()
  432. if start_new_container:
  433. self.start_container(new_container)
  434. container.remove()
  435. return new_container
  436. def stop_timeout(self, timeout):
  437. if timeout is not None:
  438. return timeout
  439. timeout = parse_seconds_float(self.options.get('stop_grace_period'))
  440. if timeout is not None:
  441. return timeout
  442. return DEFAULT_TIMEOUT
  443. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  444. if not container.is_running:
  445. if not quiet:
  446. log.info("Starting %s" % container.name)
  447. if attach_logs:
  448. container.attach_log_stream()
  449. return self.start_container(container)
  450. def start_container(self, container):
  451. self.connect_container_to_networks(container)
  452. try:
  453. container.start()
  454. except APIError as ex:
  455. raise OperationFailedError("Cannot start service %s: %s" % (self.name, ex.explanation))
  456. return container
  457. def connect_container_to_networks(self, container):
  458. connected_networks = container.get('NetworkSettings.Networks')
  459. for network, netdefs in self.networks.items():
  460. if network in connected_networks:
  461. if short_id_alias_exists(container, network):
  462. continue
  463. self.client.disconnect_container_from_network(
  464. container.id,
  465. network)
  466. self.client.connect_container_to_network(
  467. container.id, network,
  468. aliases=self._get_aliases(netdefs, container),
  469. ipv4_address=netdefs.get('ipv4_address', None),
  470. ipv6_address=netdefs.get('ipv6_address', None),
  471. links=self._get_links(False),
  472. link_local_ips=netdefs.get('link_local_ips', None),
  473. )
  474. def remove_duplicate_containers(self, timeout=None):
  475. for c in self.duplicate_containers():
  476. log.info('Removing %s' % c.name)
  477. c.stop(timeout=self.stop_timeout(timeout))
  478. c.remove()
  479. def duplicate_containers(self):
  480. containers = sorted(
  481. self.containers(stopped=True),
  482. key=lambda c: c.get('Created'),
  483. )
  484. numbers = set()
  485. for c in containers:
  486. if c.number in numbers:
  487. yield c
  488. else:
  489. numbers.add(c.number)
  490. @property
  491. def config_hash(self):
  492. return json_hash(self.config_dict())
  493. def config_dict(self):
  494. return {
  495. 'options': self.options,
  496. 'image_id': self.image()['Id'],
  497. 'links': self.get_link_names(),
  498. 'net': self.network_mode.id,
  499. 'networks': self.networks,
  500. 'volumes_from': [
  501. (v.source.name, v.mode)
  502. for v in self.volumes_from if isinstance(v.source, Service)
  503. ],
  504. }
  505. def get_dependency_names(self):
  506. net_name = self.network_mode.service_name
  507. pid_namespace = self.pid_mode.service_name
  508. return (
  509. self.get_linked_service_names() +
  510. self.get_volumes_from_names() +
  511. ([net_name] if net_name else []) +
  512. ([pid_namespace] if pid_namespace else []) +
  513. list(self.options.get('depends_on', {}).keys())
  514. )
  515. def get_dependency_configs(self):
  516. net_name = self.network_mode.service_name
  517. pid_namespace = self.pid_mode.service_name
  518. configs = dict(
  519. [(name, None) for name in self.get_linked_service_names()]
  520. )
  521. configs.update(dict(
  522. [(name, None) for name in self.get_volumes_from_names()]
  523. ))
  524. configs.update({net_name: None} if net_name else {})
  525. configs.update({pid_namespace: None} if pid_namespace else {})
  526. configs.update(self.options.get('depends_on', {}))
  527. for svc, config in self.options.get('depends_on', {}).items():
  528. if config['condition'] == CONDITION_STARTED:
  529. configs[svc] = lambda s: True
  530. elif config['condition'] == CONDITION_HEALTHY:
  531. configs[svc] = lambda s: s.is_healthy()
  532. else:
  533. # The config schema already prevents this, but it might be
  534. # bypassed if Compose is called programmatically.
  535. raise ValueError(
  536. 'depends_on condition "{}" is invalid.'.format(
  537. config['condition']
  538. )
  539. )
  540. return configs
  541. def get_linked_service_names(self):
  542. return [service.name for (service, _) in self.links]
  543. def get_link_names(self):
  544. return [(service.name, alias) for service, alias in self.links]
  545. def get_volumes_from_names(self):
  546. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  547. # TODO: this would benefit from github.com/docker/docker/pull/14699
  548. # to remove the need to inspect every container
  549. def _next_container_number(self, one_off=False):
  550. containers = filter(None, [
  551. Container.from_ps(self.client, container)
  552. for container in self.client.containers(
  553. all=True,
  554. filters={'label': self.labels(one_off=one_off)})
  555. ])
  556. numbers = [c.number for c in containers]
  557. return 1 if not numbers else max(numbers) + 1
  558. def _get_aliases(self, network, container=None):
  559. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  560. return []
  561. return list(
  562. {self.name} |
  563. ({container.short_id} if container else set()) |
  564. set(network.get('aliases', ()))
  565. )
  566. def build_default_networking_config(self):
  567. if not self.networks:
  568. return {}
  569. network = self.networks[self.network_mode.id]
  570. endpoint = {
  571. 'Aliases': self._get_aliases(network),
  572. 'IPAMConfig': {},
  573. }
  574. if network.get('ipv4_address'):
  575. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  576. if network.get('ipv6_address'):
  577. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  578. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  579. def _get_links(self, link_to_self):
  580. links = {}
  581. for service, link_name in self.links:
  582. for container in service.containers():
  583. links[link_name or service.name] = container.name
  584. links[container.name] = container.name
  585. links[container.name_without_project] = container.name
  586. if link_to_self:
  587. for container in self.containers():
  588. links[self.name] = container.name
  589. links[container.name] = container.name
  590. links[container.name_without_project] = container.name
  591. for external_link in self.options.get('external_links') or []:
  592. if ':' not in external_link:
  593. link_name = external_link
  594. else:
  595. external_link, link_name = external_link.split(':')
  596. links[link_name] = external_link
  597. return [
  598. (alias, container_name)
  599. for (container_name, alias) in links.items()
  600. ]
  601. def _get_volumes_from(self):
  602. return [build_volume_from(spec) for spec in self.volumes_from]
  603. def _get_container_create_options(
  604. self,
  605. override_options,
  606. number,
  607. one_off=False,
  608. previous_container=None):
  609. add_config_hash = (not one_off and not override_options)
  610. container_options = dict(
  611. (k, self.options[k])
  612. for k in DOCKER_CONFIG_KEYS if k in self.options)
  613. override_volumes = override_options.pop('volumes', [])
  614. container_options.update(override_options)
  615. if not container_options.get('name'):
  616. container_options['name'] = self.get_container_name(self.name, number, one_off)
  617. container_options.setdefault('detach', True)
  618. # If a qualified hostname was given, split it into an
  619. # unqualified hostname and a domainname unless domainname
  620. # was also given explicitly. This matches behavior
  621. # until Docker Engine 1.11.0 - Docker API 1.23.
  622. if (version_lt(self.client.api_version, '1.23') and
  623. 'hostname' in container_options and
  624. 'domainname' not in container_options and
  625. '.' in container_options['hostname']):
  626. parts = container_options['hostname'].partition('.')
  627. container_options['hostname'] = parts[0]
  628. container_options['domainname'] = parts[2]
  629. if 'ports' in container_options or 'expose' in self.options:
  630. container_options['ports'] = build_container_ports(
  631. formatted_ports(container_options.get('ports', [])),
  632. self.options)
  633. if 'volumes' in container_options or override_volumes:
  634. container_options['volumes'] = list(set(
  635. container_options.get('volumes', []) + override_volumes
  636. ))
  637. container_options['environment'] = merge_environment(
  638. self.options.get('environment'),
  639. override_options.get('environment'))
  640. binds, affinity = merge_volume_bindings(
  641. container_options.get('volumes') or [],
  642. self.options.get('tmpfs') or [],
  643. previous_container)
  644. override_options['binds'] = binds
  645. container_options['environment'].update(affinity)
  646. container_options['volumes'] = dict(
  647. (v.internal, {}) for v in container_options.get('volumes') or {})
  648. secret_volumes = self.get_secret_volumes()
  649. if secret_volumes:
  650. override_options['binds'].extend(v.repr() for v in secret_volumes)
  651. container_options['volumes'].update(
  652. (v.internal, {}) for v in secret_volumes)
  653. container_options['image'] = self.image_name
  654. container_options['labels'] = build_container_labels(
  655. container_options.get('labels', {}),
  656. self.labels(one_off=one_off),
  657. number,
  658. self.config_hash if add_config_hash else None)
  659. # Delete options which are only used in HostConfig
  660. for key in HOST_CONFIG_KEYS:
  661. container_options.pop(key, None)
  662. container_options['host_config'] = self._get_container_host_config(
  663. override_options,
  664. one_off=one_off)
  665. networking_config = self.build_default_networking_config()
  666. if networking_config:
  667. container_options['networking_config'] = networking_config
  668. container_options['environment'] = format_environment(
  669. container_options['environment'])
  670. return container_options
  671. def _get_container_host_config(self, override_options, one_off=False):
  672. options = dict(self.options, **override_options)
  673. logging_dict = options.get('logging', None)
  674. blkio_config = convert_blkio_config(options.get('blkio_config', None))
  675. log_config = get_log_config(logging_dict)
  676. init_path = None
  677. if isinstance(options.get('init'), six.string_types):
  678. init_path = options.get('init')
  679. options['init'] = True
  680. nano_cpus = None
  681. if 'cpus' in options:
  682. nano_cpus = int(options.get('cpus') * NANOCPUS_SCALE)
  683. return self.client.create_host_config(
  684. links=self._get_links(link_to_self=one_off),
  685. port_bindings=build_port_bindings(
  686. formatted_ports(options.get('ports', []))
  687. ),
  688. binds=options.get('binds'),
  689. volumes_from=self._get_volumes_from(),
  690. privileged=options.get('privileged', False),
  691. network_mode=self.network_mode.mode,
  692. devices=options.get('devices'),
  693. dns=options.get('dns'),
  694. dns_opt=options.get('dns_opt'),
  695. dns_search=options.get('dns_search'),
  696. restart_policy=options.get('restart'),
  697. cap_add=options.get('cap_add'),
  698. cap_drop=options.get('cap_drop'),
  699. mem_limit=options.get('mem_limit'),
  700. mem_reservation=options.get('mem_reservation'),
  701. memswap_limit=options.get('memswap_limit'),
  702. ulimits=build_ulimits(options.get('ulimits')),
  703. log_config=log_config,
  704. extra_hosts=options.get('extra_hosts'),
  705. read_only=options.get('read_only'),
  706. pid_mode=self.pid_mode.mode,
  707. security_opt=options.get('security_opt'),
  708. ipc_mode=options.get('ipc'),
  709. cgroup_parent=options.get('cgroup_parent'),
  710. cpu_quota=options.get('cpu_quota'),
  711. shm_size=options.get('shm_size'),
  712. sysctls=options.get('sysctls'),
  713. pids_limit=options.get('pids_limit'),
  714. tmpfs=options.get('tmpfs'),
  715. oom_kill_disable=options.get('oom_kill_disable'),
  716. oom_score_adj=options.get('oom_score_adj'),
  717. mem_swappiness=options.get('mem_swappiness'),
  718. group_add=options.get('group_add'),
  719. userns_mode=options.get('userns_mode'),
  720. init=options.get('init', None),
  721. init_path=init_path,
  722. isolation=options.get('isolation'),
  723. cpu_count=options.get('cpu_count'),
  724. cpu_percent=options.get('cpu_percent'),
  725. nano_cpus=nano_cpus,
  726. volume_driver=options.get('volume_driver'),
  727. cpuset_cpus=options.get('cpuset'),
  728. cpu_shares=options.get('cpu_shares'),
  729. storage_opt=options.get('storage_opt'),
  730. blkio_weight=blkio_config.get('weight'),
  731. blkio_weight_device=blkio_config.get('weight_device'),
  732. device_read_bps=blkio_config.get('device_read_bps'),
  733. device_read_iops=blkio_config.get('device_read_iops'),
  734. device_write_bps=blkio_config.get('device_write_bps'),
  735. device_write_iops=blkio_config.get('device_write_iops'),
  736. )
  737. def get_secret_volumes(self):
  738. def build_spec(secret):
  739. target = secret['secret'].target
  740. if target is None:
  741. target = '{}/{}'.format(const.SECRETS_PATH, secret['secret'].source)
  742. elif not os.path.isabs(target):
  743. target = '{}/{}'.format(const.SECRETS_PATH, target)
  744. return VolumeSpec(secret['file'], target, 'ro')
  745. return [build_spec(secret) for secret in self.secrets]
  746. def build(self, no_cache=False, pull=False, force_rm=False, build_args_override=None):
  747. log.info('Building %s' % self.name)
  748. build_opts = self.options.get('build', {})
  749. build_args = build_opts.get('args', {}).copy()
  750. if build_args_override:
  751. build_args.update(build_args_override)
  752. # python2 os.stat() doesn't support unicode on some UNIX, so we
  753. # encode it to a bytestring to be safe
  754. path = build_opts.get('context')
  755. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  756. path = path.encode('utf8')
  757. build_output = self.client.build(
  758. path=path,
  759. tag=self.image_name,
  760. stream=True,
  761. rm=True,
  762. forcerm=force_rm,
  763. pull=pull,
  764. nocache=no_cache,
  765. dockerfile=build_opts.get('dockerfile', None),
  766. cache_from=build_opts.get('cache_from', None),
  767. labels=build_opts.get('labels', None),
  768. buildargs=build_args,
  769. network_mode=build_opts.get('network', None),
  770. target=build_opts.get('target', None),
  771. shmsize=parse_bytes(build_opts.get('shm_size')) if build_opts.get('shm_size') else None,
  772. )
  773. try:
  774. all_events = stream_output(build_output, sys.stdout)
  775. except StreamOutputError as e:
  776. raise BuildError(self, six.text_type(e))
  777. # Ensure the HTTP connection is not reused for another
  778. # streaming command, as the Docker daemon can sometimes
  779. # complain about it
  780. self.client.close()
  781. image_id = None
  782. for event in all_events:
  783. if 'stream' in event:
  784. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  785. if match:
  786. image_id = match.group(1)
  787. if image_id is None:
  788. raise BuildError(self, event if all_events else 'Unknown')
  789. return image_id
  790. def can_be_built(self):
  791. return 'build' in self.options
  792. def labels(self, one_off=False):
  793. return [
  794. '{0}={1}'.format(LABEL_PROJECT, self.project),
  795. '{0}={1}'.format(LABEL_SERVICE, self.name),
  796. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  797. ]
  798. @property
  799. def custom_container_name(self):
  800. return self.options.get('container_name')
  801. def get_container_name(self, service_name, number, one_off=False):
  802. if self.custom_container_name and not one_off:
  803. return self.custom_container_name
  804. container_name = build_container_name(
  805. self.project, service_name, number, one_off,
  806. )
  807. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  808. if container_name in ext_links_origins:
  809. raise DependencyError(
  810. 'Service {0} has a self-referential external link: {1}'.format(
  811. self.name, container_name
  812. )
  813. )
  814. return container_name
  815. def remove_image(self, image_type):
  816. if not image_type or image_type == ImageType.none:
  817. return False
  818. if image_type == ImageType.local and self.options.get('image'):
  819. return False
  820. log.info("Removing image %s", self.image_name)
  821. try:
  822. self.client.remove_image(self.image_name)
  823. return True
  824. except APIError as e:
  825. log.error("Failed to remove image for service %s: %s", self.name, e)
  826. return False
  827. def specifies_host_port(self):
  828. def has_host_port(binding):
  829. if isinstance(binding, dict):
  830. external_bindings = binding.get('published')
  831. else:
  832. _, external_bindings = split_port(binding)
  833. # there are no external bindings
  834. if external_bindings is None:
  835. return False
  836. # we only need to check the first binding from the range
  837. external_binding = external_bindings[0]
  838. # non-tuple binding means there is a host port specified
  839. if not isinstance(external_binding, tuple):
  840. return True
  841. # extract actual host port from tuple of (host_ip, host_port)
  842. _, host_port = external_binding
  843. if host_port is not None:
  844. return True
  845. return False
  846. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  847. def pull(self, ignore_pull_failures=False, silent=False):
  848. if 'image' not in self.options:
  849. return
  850. repo, tag, separator = parse_repository_tag(self.options['image'])
  851. tag = tag or 'latest'
  852. if not silent:
  853. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  854. try:
  855. output = self.client.pull(repo, tag=tag, stream=True)
  856. if silent:
  857. with open(os.devnull, 'w') as devnull:
  858. return progress_stream.get_digest_from_pull(
  859. stream_output(output, devnull))
  860. else:
  861. return progress_stream.get_digest_from_pull(
  862. stream_output(output, sys.stdout))
  863. except (StreamOutputError, NotFound) as e:
  864. if not ignore_pull_failures:
  865. raise
  866. else:
  867. log.error(six.text_type(e))
  868. def push(self, ignore_push_failures=False):
  869. if 'image' not in self.options or 'build' not in self.options:
  870. return
  871. repo, tag, separator = parse_repository_tag(self.options['image'])
  872. tag = tag or 'latest'
  873. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  874. output = self.client.push(repo, tag=tag, stream=True)
  875. try:
  876. return progress_stream.get_digest_from_push(
  877. stream_output(output, sys.stdout))
  878. except StreamOutputError as e:
  879. if not ignore_push_failures:
  880. raise
  881. else:
  882. log.error(six.text_type(e))
  883. def is_healthy(self):
  884. """ Check that all containers for this service report healthy.
  885. Returns false if at least one healthcheck is pending.
  886. If an unhealthy container is detected, raise a HealthCheckFailed
  887. exception.
  888. """
  889. result = True
  890. for ctnr in self.containers():
  891. ctnr.inspect()
  892. status = ctnr.get('State.Health.Status')
  893. if status is None:
  894. raise NoHealthCheckConfigured(self.name)
  895. elif status == 'starting':
  896. result = False
  897. elif status == 'unhealthy':
  898. raise HealthCheckFailed(ctnr.short_id)
  899. return result
  900. def short_id_alias_exists(container, network):
  901. aliases = container.get(
  902. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  903. return container.short_id in aliases
  904. class PidMode(object):
  905. def __init__(self, mode):
  906. self._mode = mode
  907. @property
  908. def mode(self):
  909. return self._mode
  910. @property
  911. def service_name(self):
  912. return None
  913. class ServicePidMode(PidMode):
  914. def __init__(self, service):
  915. self.service = service
  916. @property
  917. def service_name(self):
  918. return self.service.name
  919. @property
  920. def mode(self):
  921. containers = self.service.containers()
  922. if containers:
  923. return 'container:' + containers[0].id
  924. log.warn(
  925. "Service %s is trying to use reuse the PID namespace "
  926. "of another service that is not running." % (self.service_name)
  927. )
  928. return None
  929. class ContainerPidMode(PidMode):
  930. def __init__(self, container):
  931. self.container = container
  932. self._mode = 'container:{}'.format(container.id)
  933. class NetworkMode(object):
  934. """A `standard` network mode (ex: host, bridge)"""
  935. service_name = None
  936. def __init__(self, network_mode):
  937. self.network_mode = network_mode
  938. @property
  939. def id(self):
  940. return self.network_mode
  941. mode = id
  942. class ContainerNetworkMode(object):
  943. """A network mode that uses a container's network stack."""
  944. service_name = None
  945. def __init__(self, container):
  946. self.container = container
  947. @property
  948. def id(self):
  949. return self.container.id
  950. @property
  951. def mode(self):
  952. return 'container:' + self.container.id
  953. class ServiceNetworkMode(object):
  954. """A network mode that uses a service's network stack."""
  955. def __init__(self, service):
  956. self.service = service
  957. @property
  958. def id(self):
  959. return self.service.name
  960. service_name = id
  961. @property
  962. def mode(self):
  963. containers = self.service.containers()
  964. if containers:
  965. return 'container:' + containers[0].id
  966. log.warn("Service %s is trying to use reuse the network stack "
  967. "of another service that is not running." % (self.id))
  968. return None
  969. # Names
  970. def build_container_name(project, service, number, one_off=False):
  971. bits = [project, service]
  972. if one_off:
  973. bits.append('run')
  974. return '_'.join(bits + [str(number)])
  975. # Images
  976. def parse_repository_tag(repo_path):
  977. """Splits image identification into base image path, tag/digest
  978. and it's separator.
  979. Example:
  980. >>> parse_repository_tag('user/repo@sha256:digest')
  981. ('user/repo', 'sha256:digest', '@')
  982. >>> parse_repository_tag('user/repo:v1')
  983. ('user/repo', 'v1', ':')
  984. """
  985. tag_separator = ":"
  986. digest_separator = "@"
  987. if digest_separator in repo_path:
  988. repo, tag = repo_path.rsplit(digest_separator, 1)
  989. return repo, tag, digest_separator
  990. repo, tag = repo_path, ""
  991. if tag_separator in repo_path:
  992. repo, tag = repo_path.rsplit(tag_separator, 1)
  993. if "/" in tag:
  994. repo, tag = repo_path, ""
  995. return repo, tag, tag_separator
  996. # Volumes
  997. def merge_volume_bindings(volumes, tmpfs, previous_container):
  998. """Return a list of volume bindings for a container. Container data volumes
  999. are replaced by those from the previous container.
  1000. """
  1001. affinity = {}
  1002. volume_bindings = dict(
  1003. build_volume_binding(volume)
  1004. for volume in volumes
  1005. if volume.external)
  1006. if previous_container:
  1007. old_volumes = get_container_data_volumes(previous_container, volumes, tmpfs)
  1008. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  1009. volume_bindings.update(
  1010. build_volume_binding(volume) for volume in old_volumes)
  1011. if old_volumes:
  1012. affinity = {'affinity:container': '=' + previous_container.id}
  1013. return list(volume_bindings.values()), affinity
  1014. def get_container_data_volumes(container, volumes_option, tmpfs_option):
  1015. """Find the container data volumes that are in `volumes_option`, and return
  1016. a mapping of volume bindings for those volumes.
  1017. """
  1018. volumes = []
  1019. volumes_option = volumes_option or []
  1020. container_mounts = dict(
  1021. (mount['Destination'], mount)
  1022. for mount in container.get('Mounts') or {}
  1023. )
  1024. image_volumes = [
  1025. VolumeSpec.parse(volume)
  1026. for volume in
  1027. container.image_config['ContainerConfig'].get('Volumes') or {}
  1028. ]
  1029. for volume in set(volumes_option + image_volumes):
  1030. # No need to preserve host volumes
  1031. if volume.external:
  1032. continue
  1033. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  1034. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  1035. continue
  1036. mount = container_mounts.get(volume.internal)
  1037. # New volume, doesn't exist in the old container
  1038. if not mount:
  1039. continue
  1040. # Volume was previously a host volume, now it's a container volume
  1041. if not mount.get('Name'):
  1042. continue
  1043. # Copy existing volume from old container
  1044. volume = volume._replace(external=mount['Name'])
  1045. volumes.append(volume)
  1046. return volumes
  1047. def warn_on_masked_volume(volumes_option, container_volumes, service):
  1048. container_volumes = dict(
  1049. (volume.internal, volume.external)
  1050. for volume in container_volumes)
  1051. for volume in volumes_option:
  1052. if (
  1053. volume.external and
  1054. volume.internal in container_volumes and
  1055. container_volumes.get(volume.internal) != volume.external
  1056. ):
  1057. log.warn((
  1058. "Service \"{service}\" is using volume \"{volume}\" from the "
  1059. "previous container. Host mapping \"{host_path}\" has no effect. "
  1060. "Remove the existing containers (with `docker-compose rm {service}`) "
  1061. "to use the host volume mapping."
  1062. ).format(
  1063. service=service,
  1064. volume=volume.internal,
  1065. host_path=volume.external))
  1066. def build_volume_binding(volume_spec):
  1067. return volume_spec.internal, volume_spec.repr()
  1068. def build_volume_from(volume_from_spec):
  1069. """
  1070. volume_from can be either a service or a container. We want to return the
  1071. container.id and format it into a string complete with the mode.
  1072. """
  1073. if isinstance(volume_from_spec.source, Service):
  1074. containers = volume_from_spec.source.containers(stopped=True)
  1075. if not containers:
  1076. return "{}:{}".format(
  1077. volume_from_spec.source.create_container().id,
  1078. volume_from_spec.mode)
  1079. container = containers[0]
  1080. return "{}:{}".format(container.id, volume_from_spec.mode)
  1081. elif isinstance(volume_from_spec.source, Container):
  1082. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1083. # Labels
  1084. def build_container_labels(label_options, service_labels, number, config_hash):
  1085. labels = dict(label_options or {})
  1086. labels.update(label.split('=', 1) for label in service_labels)
  1087. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1088. labels[LABEL_VERSION] = __version__
  1089. if config_hash:
  1090. log.debug("Added config hash: %s" % config_hash)
  1091. labels[LABEL_CONFIG_HASH] = config_hash
  1092. return labels
  1093. # Ulimits
  1094. def build_ulimits(ulimit_config):
  1095. if not ulimit_config:
  1096. return None
  1097. ulimits = []
  1098. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1099. if isinstance(soft_hard_values, six.integer_types):
  1100. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1101. elif isinstance(soft_hard_values, dict):
  1102. ulimit_dict = {'name': limit_name}
  1103. ulimit_dict.update(soft_hard_values)
  1104. ulimits.append(ulimit_dict)
  1105. return ulimits
  1106. def get_log_config(logging_dict):
  1107. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1108. log_options = logging_dict.get('options', None) if logging_dict else None
  1109. return LogConfig(
  1110. type=log_driver,
  1111. config=log_options
  1112. )
  1113. # TODO: remove once fix is available in docker-py
  1114. def format_environment(environment):
  1115. def format_env(key, value):
  1116. if value is None:
  1117. return key
  1118. if isinstance(value, six.binary_type):
  1119. value = value.decode('utf-8')
  1120. return '{key}={value}'.format(key=key, value=value)
  1121. return [format_env(*item) for item in environment.items()]
  1122. # Ports
  1123. def formatted_ports(ports):
  1124. result = []
  1125. for port in ports:
  1126. if isinstance(port, ServicePort):
  1127. result.append(port.legacy_repr())
  1128. else:
  1129. result.append(port)
  1130. return result
  1131. def build_container_ports(container_ports, options):
  1132. ports = []
  1133. all_ports = container_ports + options.get('expose', [])
  1134. for port_range in all_ports:
  1135. internal_range, _ = split_port(port_range)
  1136. for port in internal_range:
  1137. port = str(port)
  1138. if '/' in port:
  1139. port = tuple(port.split('/'))
  1140. ports.append(port)
  1141. return ports
  1142. def convert_blkio_config(blkio_config):
  1143. result = {}
  1144. if blkio_config is None:
  1145. return result
  1146. result['weight'] = blkio_config.get('weight')
  1147. for field in [
  1148. "device_read_bps", "device_read_iops", "device_write_bps",
  1149. "device_write_iops", "weight_device",
  1150. ]:
  1151. if field not in blkio_config:
  1152. continue
  1153. arr = []
  1154. for item in blkio_config[field]:
  1155. arr.append(dict([(k.capitalize(), v) for k, v in item.items()]))
  1156. result[field] = arr
  1157. return result