service.py 34 KB

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