service.py 44 KB

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