service.py 41 KB

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