service.py 40 KB

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