service.py 46 KB

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