service.py 39 KB

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