service.py 44 KB

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