service.py 43 KB

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