service.py 42 KB

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