service.py 41 KB

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