service.py 34 KB

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