service.py 39 KB

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