service.py 47 KB

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