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