service.py 44 KB

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