service.py 33 KB

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