service.py 45 KB

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