service.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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):
  353. if not container.is_running:
  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, aliases in self.networks.items():
  365. if network in connected_networks:
  366. self.client.disconnect_container_from_network(
  367. container.id, network)
  368. self.client.connect_container_to_network(
  369. container.id, network,
  370. aliases=list(self._get_aliases(container).union(aliases)),
  371. links=self._get_links(False),
  372. )
  373. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  374. for c in self.duplicate_containers():
  375. log.info('Removing %s' % c.name)
  376. c.stop(timeout=timeout)
  377. c.remove()
  378. def duplicate_containers(self):
  379. containers = sorted(
  380. self.containers(stopped=True),
  381. key=lambda c: c.get('Created'),
  382. )
  383. numbers = set()
  384. for c in containers:
  385. if c.number in numbers:
  386. yield c
  387. else:
  388. numbers.add(c.number)
  389. @property
  390. def config_hash(self):
  391. return json_hash(self.config_dict())
  392. def config_dict(self):
  393. return {
  394. 'options': self.options,
  395. 'image_id': self.image()['Id'],
  396. 'links': self.get_link_names(),
  397. 'net': self.network_mode.id,
  398. 'networks': list(self.networks.keys()),
  399. 'volumes_from': [
  400. (v.source.name, v.mode)
  401. for v in self.volumes_from if isinstance(v.source, Service)
  402. ],
  403. }
  404. def get_dependency_names(self):
  405. net_name = self.network_mode.service_name
  406. return (self.get_linked_service_names() +
  407. self.get_volumes_from_names() +
  408. ([net_name] if net_name else []) +
  409. self.options.get('depends_on', []))
  410. def get_linked_service_names(self):
  411. return [service.name for (service, _) in self.links]
  412. def get_link_names(self):
  413. return [(service.name, alias) for service, alias in self.links]
  414. def get_volumes_from_names(self):
  415. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  416. # TODO: this would benefit from github.com/docker/docker/pull/14699
  417. # to remove the need to inspect every container
  418. def _next_container_number(self, one_off=False):
  419. containers = filter(None, [
  420. Container.from_ps(self.client, container)
  421. for container in self.client.containers(
  422. all=True,
  423. filters={'label': self.labels(one_off=one_off)})
  424. ])
  425. numbers = [c.number for c in containers]
  426. return 1 if not numbers else max(numbers) + 1
  427. def _get_aliases(self, container):
  428. if container.labels.get(LABEL_ONE_OFF) == "True":
  429. return set()
  430. return {self.name, container.short_id}
  431. def _get_links(self, link_to_self):
  432. links = {}
  433. for service, link_name in self.links:
  434. for container in service.containers():
  435. links[link_name or service.name] = container.name
  436. links[container.name] = container.name
  437. links[container.name_without_project] = container.name
  438. if link_to_self:
  439. for container in self.containers():
  440. links[self.name] = container.name
  441. links[container.name] = container.name
  442. links[container.name_without_project] = container.name
  443. for external_link in self.options.get('external_links') or []:
  444. if ':' not in external_link:
  445. link_name = external_link
  446. else:
  447. external_link, link_name = external_link.split(':')
  448. links[link_name] = external_link
  449. return [
  450. (alias, container_name)
  451. for (container_name, alias) in links.items()
  452. ]
  453. def _get_volumes_from(self):
  454. return [build_volume_from(spec) for spec in self.volumes_from]
  455. def _get_container_create_options(
  456. self,
  457. override_options,
  458. number,
  459. one_off=False,
  460. previous_container=None):
  461. add_config_hash = (not one_off and not override_options)
  462. container_options = dict(
  463. (k, self.options[k])
  464. for k in DOCKER_CONFIG_KEYS if k in self.options)
  465. container_options.update(override_options)
  466. if not container_options.get('name'):
  467. container_options['name'] = self.get_container_name(number, one_off)
  468. container_options.setdefault('detach', True)
  469. # If a qualified hostname was given, split it into an
  470. # unqualified hostname and a domainname unless domainname
  471. # was also given explicitly. This matches the behavior of
  472. # the official Docker CLI in that scenario.
  473. if ('hostname' in container_options and
  474. 'domainname' not in container_options and
  475. '.' in container_options['hostname']):
  476. parts = container_options['hostname'].partition('.')
  477. container_options['hostname'] = parts[0]
  478. container_options['domainname'] = parts[2]
  479. if 'ports' in container_options or 'expose' in self.options:
  480. container_options['ports'] = build_container_ports(
  481. container_options,
  482. self.options)
  483. container_options['environment'] = merge_environment(
  484. self.options.get('environment'),
  485. override_options.get('environment'))
  486. binds, affinity = merge_volume_bindings(
  487. container_options.get('volumes') or [],
  488. previous_container)
  489. override_options['binds'] = binds
  490. container_options['environment'].update(affinity)
  491. if 'volumes' in container_options:
  492. container_options['volumes'] = dict(
  493. (v.internal, {}) for v in container_options['volumes'])
  494. container_options['image'] = self.image_name
  495. container_options['labels'] = build_container_labels(
  496. container_options.get('labels', {}),
  497. self.labels(one_off=one_off),
  498. number,
  499. self.config_hash if add_config_hash else None)
  500. # Delete options which are only used when starting
  501. for key in DOCKER_START_KEYS:
  502. container_options.pop(key, None)
  503. container_options['host_config'] = self._get_container_host_config(
  504. override_options,
  505. one_off=one_off)
  506. container_options['environment'] = format_environment(
  507. container_options['environment'])
  508. return container_options
  509. def _get_container_host_config(self, override_options, one_off=False):
  510. options = dict(self.options, **override_options)
  511. logging_dict = options.get('logging', None)
  512. log_config = get_log_config(logging_dict)
  513. return self.client.create_host_config(
  514. links=self._get_links(link_to_self=one_off),
  515. port_bindings=build_port_bindings(options.get('ports') or []),
  516. binds=options.get('binds'),
  517. volumes_from=self._get_volumes_from(),
  518. privileged=options.get('privileged', False),
  519. network_mode=self.network_mode.mode,
  520. devices=options.get('devices'),
  521. dns=options.get('dns'),
  522. dns_search=options.get('dns_search'),
  523. restart_policy=options.get('restart'),
  524. cap_add=options.get('cap_add'),
  525. cap_drop=options.get('cap_drop'),
  526. mem_limit=options.get('mem_limit'),
  527. memswap_limit=options.get('memswap_limit'),
  528. ulimits=build_ulimits(options.get('ulimits')),
  529. log_config=log_config,
  530. extra_hosts=options.get('extra_hosts'),
  531. read_only=options.get('read_only'),
  532. pid_mode=options.get('pid'),
  533. security_opt=options.get('security_opt'),
  534. ipc_mode=options.get('ipc'),
  535. cgroup_parent=options.get('cgroup_parent'),
  536. cpu_quota=options.get('cpu_quota'),
  537. shm_size=options.get('shm_size'),
  538. )
  539. def build(self, no_cache=False, pull=False, force_rm=False):
  540. log.info('Building %s' % self.name)
  541. build_opts = self.options.get('build', {})
  542. path = build_opts.get('context')
  543. # python2 os.path() doesn't support unicode, so we need to encode it to
  544. # a byte string
  545. if not six.PY3:
  546. path = path.encode('utf8')
  547. build_output = self.client.build(
  548. path=path,
  549. tag=self.image_name,
  550. stream=True,
  551. rm=True,
  552. forcerm=force_rm,
  553. pull=pull,
  554. nocache=no_cache,
  555. dockerfile=build_opts.get('dockerfile', None),
  556. buildargs=build_opts.get('args', None),
  557. )
  558. try:
  559. all_events = stream_output(build_output, sys.stdout)
  560. except StreamOutputError as e:
  561. raise BuildError(self, six.text_type(e))
  562. # Ensure the HTTP connection is not reused for another
  563. # streaming command, as the Docker daemon can sometimes
  564. # complain about it
  565. self.client.close()
  566. image_id = None
  567. for event in all_events:
  568. if 'stream' in event:
  569. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  570. if match:
  571. image_id = match.group(1)
  572. if image_id is None:
  573. raise BuildError(self, event if all_events else 'Unknown')
  574. return image_id
  575. def can_be_built(self):
  576. return 'build' in self.options
  577. def labels(self, one_off=False):
  578. return [
  579. '{0}={1}'.format(LABEL_PROJECT, self.project),
  580. '{0}={1}'.format(LABEL_SERVICE, self.name),
  581. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  582. ]
  583. @property
  584. def custom_container_name(self):
  585. return self.options.get('container_name')
  586. def get_container_name(self, number, one_off=False):
  587. if self.custom_container_name and not one_off:
  588. return self.custom_container_name
  589. return build_container_name(self.project, self.name, number, one_off)
  590. def remove_image(self, image_type):
  591. if not image_type or image_type == ImageType.none:
  592. return False
  593. if image_type == ImageType.local and self.options.get('image'):
  594. return False
  595. log.info("Removing image %s", self.image_name)
  596. try:
  597. self.client.remove_image(self.image_name)
  598. return True
  599. except APIError as e:
  600. log.error("Failed to remove image for service %s: %s", self.name, e)
  601. return False
  602. def specifies_host_port(self):
  603. def has_host_port(binding):
  604. _, external_bindings = split_port(binding)
  605. # there are no external bindings
  606. if external_bindings is None:
  607. return False
  608. # we only need to check the first binding from the range
  609. external_binding = external_bindings[0]
  610. # non-tuple binding means there is a host port specified
  611. if not isinstance(external_binding, tuple):
  612. return True
  613. # extract actual host port from tuple of (host_ip, host_port)
  614. _, host_port = external_binding
  615. if host_port is not None:
  616. return True
  617. return False
  618. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  619. def pull(self, ignore_pull_failures=False):
  620. if 'image' not in self.options:
  621. return
  622. repo, tag, separator = parse_repository_tag(self.options['image'])
  623. tag = tag or 'latest'
  624. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  625. output = self.client.pull(
  626. repo,
  627. tag=tag,
  628. stream=True,
  629. )
  630. try:
  631. stream_output(output, sys.stdout)
  632. except StreamOutputError as e:
  633. if not ignore_pull_failures:
  634. raise
  635. else:
  636. log.error(six.text_type(e))
  637. class NetworkMode(object):
  638. """A `standard` network mode (ex: host, bridge)"""
  639. service_name = None
  640. def __init__(self, network_mode):
  641. self.network_mode = network_mode
  642. @property
  643. def id(self):
  644. return self.network_mode
  645. mode = id
  646. class ContainerNetworkMode(object):
  647. """A network mode that uses a container's network stack."""
  648. service_name = None
  649. def __init__(self, container):
  650. self.container = container
  651. @property
  652. def id(self):
  653. return self.container.id
  654. @property
  655. def mode(self):
  656. return 'container:' + self.container.id
  657. class ServiceNetworkMode(object):
  658. """A network mode that uses a service's network stack."""
  659. def __init__(self, service):
  660. self.service = service
  661. @property
  662. def id(self):
  663. return self.service.name
  664. service_name = id
  665. @property
  666. def mode(self):
  667. containers = self.service.containers()
  668. if containers:
  669. return 'container:' + containers[0].id
  670. log.warn("Service %s is trying to use reuse the network stack "
  671. "of another service that is not running." % (self.id))
  672. return None
  673. # Names
  674. def build_container_name(project, service, number, one_off=False):
  675. bits = [project, service]
  676. if one_off:
  677. bits.append('run')
  678. return '_'.join(bits + [str(number)])
  679. # Images
  680. def parse_repository_tag(repo_path):
  681. """Splits image identification into base image path, tag/digest
  682. and it's separator.
  683. Example:
  684. >>> parse_repository_tag('user/repo@sha256:digest')
  685. ('user/repo', 'sha256:digest', '@')
  686. >>> parse_repository_tag('user/repo:v1')
  687. ('user/repo', 'v1', ':')
  688. """
  689. tag_separator = ":"
  690. digest_separator = "@"
  691. if digest_separator in repo_path:
  692. repo, tag = repo_path.rsplit(digest_separator, 1)
  693. return repo, tag, digest_separator
  694. repo, tag = repo_path, ""
  695. if tag_separator in repo_path:
  696. repo, tag = repo_path.rsplit(tag_separator, 1)
  697. if "/" in tag:
  698. repo, tag = repo_path, ""
  699. return repo, tag, tag_separator
  700. # Volumes
  701. def merge_volume_bindings(volumes, previous_container):
  702. """Return a list of volume bindings for a container. Container data volumes
  703. are replaced by those from the previous container.
  704. """
  705. affinity = {}
  706. volume_bindings = dict(
  707. build_volume_binding(volume)
  708. for volume in volumes
  709. if volume.external)
  710. if previous_container:
  711. old_volumes = get_container_data_volumes(previous_container, volumes)
  712. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  713. volume_bindings.update(
  714. build_volume_binding(volume) for volume in old_volumes)
  715. if old_volumes:
  716. affinity = {'affinity:container': '=' + previous_container.id}
  717. return list(volume_bindings.values()), affinity
  718. def get_container_data_volumes(container, volumes_option):
  719. """Find the container data volumes that are in `volumes_option`, and return
  720. a mapping of volume bindings for those volumes.
  721. """
  722. volumes = []
  723. volumes_option = volumes_option or []
  724. container_mounts = dict(
  725. (mount['Destination'], mount)
  726. for mount in container.get('Mounts') or {}
  727. )
  728. image_volumes = [
  729. VolumeSpec.parse(volume)
  730. for volume in
  731. container.image_config['ContainerConfig'].get('Volumes') or {}
  732. ]
  733. for volume in set(volumes_option + image_volumes):
  734. # No need to preserve host volumes
  735. if volume.external:
  736. continue
  737. mount = container_mounts.get(volume.internal)
  738. # New volume, doesn't exist in the old container
  739. if not mount:
  740. continue
  741. # Volume was previously a host volume, now it's a container volume
  742. if not mount.get('Name'):
  743. continue
  744. # Copy existing volume from old container
  745. volume = volume._replace(external=mount['Name'])
  746. volumes.append(volume)
  747. return volumes
  748. def warn_on_masked_volume(volumes_option, container_volumes, service):
  749. container_volumes = dict(
  750. (volume.internal, volume.external)
  751. for volume in container_volumes)
  752. for volume in volumes_option:
  753. if (
  754. volume.external and
  755. volume.internal in container_volumes and
  756. container_volumes.get(volume.internal) != volume.external
  757. ):
  758. log.warn((
  759. "Service \"{service}\" is using volume \"{volume}\" from the "
  760. "previous container. Host mapping \"{host_path}\" has no effect. "
  761. "Remove the existing containers (with `docker-compose rm {service}`) "
  762. "to use the host volume mapping."
  763. ).format(
  764. service=service,
  765. volume=volume.internal,
  766. host_path=volume.external))
  767. def build_volume_binding(volume_spec):
  768. return volume_spec.internal, volume_spec.repr()
  769. def build_volume_from(volume_from_spec):
  770. """
  771. volume_from can be either a service or a container. We want to return the
  772. container.id and format it into a string complete with the mode.
  773. """
  774. if isinstance(volume_from_spec.source, Service):
  775. containers = volume_from_spec.source.containers(stopped=True)
  776. if not containers:
  777. return "{}:{}".format(
  778. volume_from_spec.source.create_container().id,
  779. volume_from_spec.mode)
  780. container = containers[0]
  781. return "{}:{}".format(container.id, volume_from_spec.mode)
  782. elif isinstance(volume_from_spec.source, Container):
  783. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  784. # Labels
  785. def build_container_labels(label_options, service_labels, number, config_hash):
  786. labels = dict(label_options or {})
  787. labels.update(label.split('=', 1) for label in service_labels)
  788. labels[LABEL_CONTAINER_NUMBER] = str(number)
  789. labels[LABEL_VERSION] = __version__
  790. if config_hash:
  791. log.debug("Added config hash: %s" % config_hash)
  792. labels[LABEL_CONFIG_HASH] = config_hash
  793. return labels
  794. # Ulimits
  795. def build_ulimits(ulimit_config):
  796. if not ulimit_config:
  797. return None
  798. ulimits = []
  799. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  800. if isinstance(soft_hard_values, six.integer_types):
  801. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  802. elif isinstance(soft_hard_values, dict):
  803. ulimit_dict = {'name': limit_name}
  804. ulimit_dict.update(soft_hard_values)
  805. ulimits.append(ulimit_dict)
  806. return ulimits
  807. def get_log_config(logging_dict):
  808. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  809. log_options = logging_dict.get('options', None) if logging_dict else None
  810. return LogConfig(
  811. type=log_driver,
  812. config=log_options
  813. )
  814. # TODO: remove once fix is available in docker-py
  815. def format_environment(environment):
  816. def format_env(key, value):
  817. if value is None:
  818. return key
  819. return '{key}={value}'.format(key=key, value=value)
  820. return [format_env(*item) for item in environment.items()]
  821. # Ports
  822. def build_container_ports(container_options, options):
  823. ports = []
  824. all_ports = container_options.get('ports', []) + options.get('expose', [])
  825. for port_range in all_ports:
  826. internal_range, _ = split_port(port_range)
  827. for port in internal_range:
  828. port = str(port)
  829. if '/' in port:
  830. port = tuple(port.split('/'))
  831. ports.append(port)
  832. return ports