service.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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.errors import ImageNotFound
  13. from docker.errors import NotFound
  14. from docker.types import LogConfig
  15. from docker.utils.ports import build_port_bindings
  16. from docker.utils.ports import split_port
  17. from docker.utils.utils import convert_tmpfs_mounts
  18. from . import __version__
  19. from . import const
  20. from . import progress_stream
  21. from .config import DOCKER_CONFIG_KEYS
  22. from .config import merge_environment
  23. from .config.errors import DependencyError
  24. from .config.types import ServicePort
  25. from .config.types import VolumeSpec
  26. from .const import DEFAULT_TIMEOUT
  27. from .const import IS_WINDOWS_PLATFORM
  28. from .const import LABEL_CONFIG_HASH
  29. from .const import LABEL_CONTAINER_NUMBER
  30. from .const import LABEL_ONE_OFF
  31. from .const import LABEL_PROJECT
  32. from .const import LABEL_SERVICE
  33. from .const import LABEL_VERSION
  34. from .container import Container
  35. from .errors import HealthCheckFailed
  36. from .errors import NoHealthCheckConfigured
  37. from .errors import OperationFailedError
  38. from .parallel import parallel_execute
  39. from .progress_stream import stream_output
  40. from .progress_stream import StreamOutputError
  41. from .utils import json_hash
  42. from .utils import parse_seconds_float
  43. log = logging.getLogger(__name__)
  44. HOST_CONFIG_KEYS = [
  45. 'cap_add',
  46. 'cap_drop',
  47. 'cgroup_parent',
  48. 'cpu_quota',
  49. 'devices',
  50. 'dns',
  51. 'dns_search',
  52. 'dns_opt',
  53. 'env_file',
  54. 'extra_hosts',
  55. 'group_add',
  56. 'init',
  57. 'ipc',
  58. 'read_only',
  59. 'log_driver',
  60. 'log_opt',
  61. 'mem_limit',
  62. 'mem_reservation',
  63. 'memswap_limit',
  64. 'mem_swappiness',
  65. 'oom_score_adj',
  66. 'pid',
  67. 'pids_limit',
  68. 'privileged',
  69. 'restart',
  70. 'security_opt',
  71. 'shm_size',
  72. 'sysctls',
  73. 'userns_mode',
  74. 'volumes_from',
  75. ]
  76. CONDITION_STARTED = 'service_started'
  77. CONDITION_HEALTHY = 'service_healthy'
  78. class BuildError(Exception):
  79. def __init__(self, service, reason):
  80. self.service = service
  81. self.reason = reason
  82. class NeedsBuildError(Exception):
  83. def __init__(self, service):
  84. self.service = service
  85. class NoSuchImageError(Exception):
  86. pass
  87. ServiceName = namedtuple('ServiceName', 'project service number')
  88. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  89. @enum.unique
  90. class ConvergenceStrategy(enum.Enum):
  91. """Enumeration for all possible convergence strategies. Values refer to
  92. when containers should be recreated.
  93. """
  94. changed = 1
  95. always = 2
  96. never = 3
  97. @property
  98. def allows_recreate(self):
  99. return self is not type(self).never
  100. @enum.unique
  101. class ImageType(enum.Enum):
  102. """Enumeration for the types of images known to compose."""
  103. none = 0
  104. local = 1
  105. all = 2
  106. @enum.unique
  107. class BuildAction(enum.Enum):
  108. """Enumeration for the possible build actions."""
  109. none = 0
  110. force = 1
  111. skip = 2
  112. class Service(object):
  113. def __init__(
  114. self,
  115. name,
  116. client=None,
  117. project='default',
  118. use_networking=False,
  119. links=None,
  120. volumes_from=None,
  121. network_mode=None,
  122. networks=None,
  123. secrets=None,
  124. scale=None,
  125. **options
  126. ):
  127. self.name = name
  128. self.client = client
  129. self.project = project
  130. self.use_networking = use_networking
  131. self.links = links or []
  132. self.volumes_from = volumes_from or []
  133. self.network_mode = network_mode or NetworkMode(None)
  134. self.networks = networks or {}
  135. self.secrets = secrets or []
  136. self.scale_num = scale or 1
  137. self.options = options
  138. def __repr__(self):
  139. return '<Service: {}>'.format(self.name)
  140. def containers(self, stopped=False, one_off=False, filters={}):
  141. filters.update({'label': self.labels(one_off=one_off)})
  142. return list(filter(None, [
  143. Container.from_ps(self.client, container)
  144. for container in self.client.containers(
  145. all=stopped,
  146. filters=filters)]))
  147. def get_container(self, number=1):
  148. """Return a :class:`compose.container.Container` for this service. The
  149. container must be active, and match `number`.
  150. """
  151. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  152. for container in self.client.containers(filters={'label': labels}):
  153. return Container.from_ps(self.client, container)
  154. raise ValueError("No container found for %s_%s" % (self.name, number))
  155. def start(self, **options):
  156. containers = self.containers(stopped=True)
  157. for c in containers:
  158. self.start_container_if_stopped(c, **options)
  159. return containers
  160. def show_scale_warnings(self, desired_num):
  161. if self.custom_container_name and desired_num > 1:
  162. log.warn('The "%s" service is using the custom container name "%s". '
  163. 'Docker requires each container to have a unique name. '
  164. 'Remove the custom name to scale the service.'
  165. % (self.name, self.custom_container_name))
  166. if self.specifies_host_port() and desired_num > 1:
  167. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  168. 'for this service are created on a single host, the port will clash.'
  169. % self.name)
  170. def scale(self, desired_num, timeout=None):
  171. """
  172. Adjusts the number of containers to the specified number and ensures
  173. they are running.
  174. - creates containers until there are at least `desired_num`
  175. - stops containers until there are at most `desired_num` running
  176. - starts containers until there are at least `desired_num` running
  177. - removes all stopped containers
  178. """
  179. self.show_scale_warnings(desired_num)
  180. running_containers = self.containers(stopped=False)
  181. num_running = len(running_containers)
  182. if desired_num == num_running:
  183. # do nothing as we already have the desired number
  184. log.info('Desired container number already achieved')
  185. return
  186. if desired_num > num_running:
  187. all_containers = self.containers(stopped=True)
  188. if num_running != len(all_containers):
  189. # we have some stopped containers, check for divergences
  190. stopped_containers = [
  191. c for c in all_containers if not c.is_running
  192. ]
  193. # Remove containers that have diverged
  194. divergent_containers = [
  195. c for c in stopped_containers if self._containers_have_diverged([c])
  196. ]
  197. for c in divergent_containers:
  198. c.remove()
  199. all_containers = list(set(all_containers) - set(divergent_containers))
  200. sorted_containers = sorted(all_containers, key=attrgetter('number'))
  201. self._execute_convergence_start(
  202. sorted_containers, desired_num, timeout, True, True
  203. )
  204. if desired_num < num_running:
  205. num_to_stop = num_running - desired_num
  206. sorted_running_containers = sorted(
  207. running_containers,
  208. key=attrgetter('number'))
  209. self._downscale(sorted_running_containers[-num_to_stop:], timeout)
  210. def create_container(self,
  211. one_off=False,
  212. previous_container=None,
  213. number=None,
  214. quiet=False,
  215. **override_options):
  216. """
  217. Create a container for this service. If the image doesn't exist, attempt to pull
  218. it.
  219. """
  220. # This is only necessary for `scale` and `volumes_from`
  221. # auto-creating containers to satisfy the dependency.
  222. self.ensure_image_exists()
  223. container_options = self._get_container_create_options(
  224. override_options,
  225. number or self._next_container_number(one_off=one_off),
  226. one_off=one_off,
  227. previous_container=previous_container,
  228. )
  229. if 'name' in container_options and not quiet:
  230. log.info("Creating %s" % container_options['name'])
  231. try:
  232. return Container.create(self.client, **container_options)
  233. except APIError as ex:
  234. raise OperationFailedError("Cannot create container for service %s: %s" %
  235. (self.name, ex.explanation))
  236. def ensure_image_exists(self, do_build=BuildAction.none):
  237. if self.can_be_built() and do_build == BuildAction.force:
  238. self.build()
  239. return
  240. try:
  241. self.image()
  242. return
  243. except NoSuchImageError:
  244. pass
  245. if not self.can_be_built():
  246. self.pull()
  247. return
  248. if do_build == BuildAction.skip:
  249. raise NeedsBuildError(self)
  250. self.build()
  251. log.warn(
  252. "Image for service {} was built because it did not already exist. To "
  253. "rebuild this image you must use `docker-compose build` or "
  254. "`docker-compose up --build`.".format(self.name))
  255. def image(self):
  256. try:
  257. return self.client.inspect_image(self.image_name)
  258. except ImageNotFound:
  259. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  260. @property
  261. def image_name(self):
  262. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  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_create(self, scale, detached, start):
  299. i = self._next_container_number()
  300. def create_and_start(service, n):
  301. container = service.create_container(number=n)
  302. if not detached:
  303. container.attach_log_stream()
  304. if start:
  305. self.start_container(container)
  306. return container
  307. containers, errors = parallel_execute(
  308. range(i, i + scale),
  309. lambda n: create_and_start(self, n),
  310. lambda n: self.get_container_name(n),
  311. "Creating"
  312. )
  313. for error in errors.values():
  314. raise OperationFailedError(error)
  315. return containers
  316. def _execute_convergence_recreate(self, containers, scale, timeout, detached, start):
  317. if len(containers) > scale:
  318. self._downscale(containers[scale:], timeout)
  319. containers = containers[:scale]
  320. def recreate(container):
  321. return self.recreate_container(
  322. container, timeout=timeout, attach_logs=not detached,
  323. start_new_container=start
  324. )
  325. containers, errors = parallel_execute(
  326. containers,
  327. recreate,
  328. lambda c: c.name,
  329. "Recreating"
  330. )
  331. for error in errors.values():
  332. raise OperationFailedError(error)
  333. if len(containers) < scale:
  334. containers.extend(self._execute_convergence_create(
  335. scale - len(containers), detached, start
  336. ))
  337. return containers
  338. def _execute_convergence_start(self, containers, scale, timeout, detached, start):
  339. if len(containers) > scale:
  340. self._downscale(containers[scale:], timeout)
  341. containers = containers[:scale]
  342. if start:
  343. _, errors = parallel_execute(
  344. containers,
  345. lambda c: self.start_container_if_stopped(c, attach_logs=not detached),
  346. lambda c: c.name,
  347. "Starting"
  348. )
  349. for error in errors.values():
  350. raise OperationFailedError(error)
  351. if len(containers) < scale:
  352. containers.extend(self._execute_convergence_create(
  353. scale - len(containers), detached, start
  354. ))
  355. return containers
  356. def _downscale(self, containers, timeout=None):
  357. def stop_and_remove(container):
  358. container.stop(timeout=self.stop_timeout(timeout))
  359. container.remove()
  360. parallel_execute(
  361. containers,
  362. stop_and_remove,
  363. lambda c: c.name,
  364. "Stopping and removing",
  365. )
  366. def execute_convergence_plan(self, plan, timeout=None, detached=False,
  367. start=True, scale_override=None):
  368. (action, containers) = plan
  369. scale = scale_override if scale_override is not None else self.scale_num
  370. containers = sorted(containers, key=attrgetter('number'))
  371. self.show_scale_warnings(scale)
  372. if action == 'create':
  373. return self._execute_convergence_create(
  374. scale, detached, start
  375. )
  376. if action == 'recreate':
  377. return self._execute_convergence_recreate(
  378. containers, scale, timeout, detached, start
  379. )
  380. if action == 'start':
  381. return self._execute_convergence_start(
  382. containers, scale, timeout, detached, start
  383. )
  384. if action == 'noop':
  385. if scale != len(containers):
  386. return self._execute_convergence_start(
  387. containers, scale, timeout, detached, start
  388. )
  389. for c in containers:
  390. log.info("%s is up-to-date" % c.name)
  391. return containers
  392. raise Exception("Invalid action: {}".format(action))
  393. def recreate_container(
  394. self,
  395. container,
  396. timeout=None,
  397. attach_logs=False,
  398. start_new_container=True):
  399. """Recreate a container.
  400. The original container is renamed to a temporary name so that data
  401. volumes can be copied to the new container, before the original
  402. container is removed.
  403. """
  404. log.info("Recreating %s" % container.name)
  405. container.stop(timeout=self.stop_timeout(timeout))
  406. container.rename_to_tmp_name()
  407. new_container = self.create_container(
  408. previous_container=container,
  409. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  410. quiet=True,
  411. )
  412. if attach_logs:
  413. new_container.attach_log_stream()
  414. if start_new_container:
  415. self.start_container(new_container)
  416. container.remove()
  417. return new_container
  418. def stop_timeout(self, timeout):
  419. if timeout is not None:
  420. return timeout
  421. timeout = parse_seconds_float(self.options.get('stop_grace_period'))
  422. if timeout is not None:
  423. return timeout
  424. return DEFAULT_TIMEOUT
  425. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  426. if not container.is_running:
  427. if not quiet:
  428. log.info("Starting %s" % container.name)
  429. if attach_logs:
  430. container.attach_log_stream()
  431. return self.start_container(container)
  432. def start_container(self, container):
  433. self.connect_container_to_networks(container)
  434. try:
  435. container.start()
  436. except APIError as ex:
  437. raise OperationFailedError("Cannot start service %s: %s" % (self.name, ex.explanation))
  438. return container
  439. def connect_container_to_networks(self, container):
  440. connected_networks = container.get('NetworkSettings.Networks')
  441. for network, netdefs in self.networks.items():
  442. if network in connected_networks:
  443. if short_id_alias_exists(container, network):
  444. continue
  445. self.client.disconnect_container_from_network(
  446. container.id,
  447. network)
  448. self.client.connect_container_to_network(
  449. container.id, network,
  450. aliases=self._get_aliases(netdefs, container),
  451. ipv4_address=netdefs.get('ipv4_address', None),
  452. ipv6_address=netdefs.get('ipv6_address', None),
  453. links=self._get_links(False),
  454. link_local_ips=netdefs.get('link_local_ips', None),
  455. )
  456. def remove_duplicate_containers(self, timeout=None):
  457. for c in self.duplicate_containers():
  458. log.info('Removing %s' % c.name)
  459. c.stop(timeout=self.stop_timeout(timeout))
  460. c.remove()
  461. def duplicate_containers(self):
  462. containers = sorted(
  463. self.containers(stopped=True),
  464. key=lambda c: c.get('Created'),
  465. )
  466. numbers = set()
  467. for c in containers:
  468. if c.number in numbers:
  469. yield c
  470. else:
  471. numbers.add(c.number)
  472. @property
  473. def config_hash(self):
  474. return json_hash(self.config_dict())
  475. def config_dict(self):
  476. return {
  477. 'options': self.options,
  478. 'image_id': self.image()['Id'],
  479. 'links': self.get_link_names(),
  480. 'net': self.network_mode.id,
  481. 'networks': self.networks,
  482. 'volumes_from': [
  483. (v.source.name, v.mode)
  484. for v in self.volumes_from if isinstance(v.source, Service)
  485. ],
  486. }
  487. def get_dependency_names(self):
  488. net_name = self.network_mode.service_name
  489. return (
  490. self.get_linked_service_names() +
  491. self.get_volumes_from_names() +
  492. ([net_name] if net_name else []) +
  493. list(self.options.get('depends_on', {}).keys())
  494. )
  495. def get_dependency_configs(self):
  496. net_name = self.network_mode.service_name
  497. configs = dict(
  498. [(name, None) for name in self.get_linked_service_names()]
  499. )
  500. configs.update(dict(
  501. [(name, None) for name in self.get_volumes_from_names()]
  502. ))
  503. configs.update({net_name: None} if net_name else {})
  504. configs.update(self.options.get('depends_on', {}))
  505. for svc, config in self.options.get('depends_on', {}).items():
  506. if config['condition'] == CONDITION_STARTED:
  507. configs[svc] = lambda s: True
  508. elif config['condition'] == CONDITION_HEALTHY:
  509. configs[svc] = lambda s: s.is_healthy()
  510. else:
  511. # The config schema already prevents this, but it might be
  512. # bypassed if Compose is called programmatically.
  513. raise ValueError(
  514. 'depends_on condition "{}" is invalid.'.format(
  515. config['condition']
  516. )
  517. )
  518. return configs
  519. def get_linked_service_names(self):
  520. return [service.name for (service, _) in self.links]
  521. def get_link_names(self):
  522. return [(service.name, alias) for service, alias in self.links]
  523. def get_volumes_from_names(self):
  524. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  525. # TODO: this would benefit from github.com/docker/docker/pull/14699
  526. # to remove the need to inspect every container
  527. def _next_container_number(self, one_off=False):
  528. containers = filter(None, [
  529. Container.from_ps(self.client, container)
  530. for container in self.client.containers(
  531. all=True,
  532. filters={'label': self.labels(one_off=one_off)})
  533. ])
  534. numbers = [c.number for c in containers]
  535. return 1 if not numbers else max(numbers) + 1
  536. def _get_aliases(self, network, container=None):
  537. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  538. return []
  539. return list(
  540. {self.name} |
  541. ({container.short_id} if container else set()) |
  542. set(network.get('aliases', ()))
  543. )
  544. def build_default_networking_config(self):
  545. if not self.networks:
  546. return {}
  547. network = self.networks[self.network_mode.id]
  548. endpoint = {
  549. 'Aliases': self._get_aliases(network),
  550. 'IPAMConfig': {},
  551. }
  552. if network.get('ipv4_address'):
  553. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  554. if network.get('ipv6_address'):
  555. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  556. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  557. def _get_links(self, link_to_self):
  558. links = {}
  559. for service, link_name in self.links:
  560. for container in service.containers():
  561. links[link_name or service.name] = container.name
  562. links[container.name] = container.name
  563. links[container.name_without_project] = container.name
  564. if link_to_self:
  565. for container in self.containers():
  566. links[self.name] = container.name
  567. links[container.name] = container.name
  568. links[container.name_without_project] = container.name
  569. for external_link in self.options.get('external_links') or []:
  570. if ':' not in external_link:
  571. link_name = external_link
  572. else:
  573. external_link, link_name = external_link.split(':')
  574. links[link_name] = external_link
  575. return [
  576. (alias, container_name)
  577. for (container_name, alias) in links.items()
  578. ]
  579. def _get_volumes_from(self):
  580. return [build_volume_from(spec) for spec in self.volumes_from]
  581. def _get_container_create_options(
  582. self,
  583. override_options,
  584. number,
  585. one_off=False,
  586. previous_container=None):
  587. add_config_hash = (not one_off and not override_options)
  588. container_options = dict(
  589. (k, self.options[k])
  590. for k in DOCKER_CONFIG_KEYS if k in self.options)
  591. container_options.update(override_options)
  592. if not container_options.get('name'):
  593. container_options['name'] = self.get_container_name(number, one_off)
  594. container_options.setdefault('detach', True)
  595. # If a qualified hostname was given, split it into an
  596. # unqualified hostname and a domainname unless domainname
  597. # was also given explicitly. This matches the behavior of
  598. # the official Docker CLI in that scenario.
  599. if ('hostname' in container_options and
  600. 'domainname' not in container_options and
  601. '.' in container_options['hostname']):
  602. parts = container_options['hostname'].partition('.')
  603. container_options['hostname'] = parts[0]
  604. container_options['domainname'] = parts[2]
  605. if 'ports' in container_options or 'expose' in self.options:
  606. container_options['ports'] = build_container_ports(
  607. formatted_ports(container_options.get('ports', [])),
  608. self.options)
  609. container_options['environment'] = merge_environment(
  610. self.options.get('environment'),
  611. override_options.get('environment'))
  612. binds, affinity = merge_volume_bindings(
  613. container_options.get('volumes') or [],
  614. self.options.get('tmpfs') or [],
  615. previous_container)
  616. override_options['binds'] = binds
  617. container_options['environment'].update(affinity)
  618. container_options['volumes'] = dict(
  619. (v.internal, {}) for v in container_options.get('volumes') or {})
  620. secret_volumes = self.get_secret_volumes()
  621. if secret_volumes:
  622. override_options['binds'].extend(v.repr() for v in secret_volumes)
  623. container_options['volumes'].update(
  624. (v.internal, {}) for v in secret_volumes)
  625. container_options['image'] = self.image_name
  626. container_options['labels'] = build_container_labels(
  627. container_options.get('labels', {}),
  628. self.labels(one_off=one_off),
  629. number,
  630. self.config_hash if add_config_hash else None)
  631. # Delete options which are only used in HostConfig
  632. for key in HOST_CONFIG_KEYS:
  633. container_options.pop(key, None)
  634. container_options['host_config'] = self._get_container_host_config(
  635. override_options,
  636. one_off=one_off)
  637. networking_config = self.build_default_networking_config()
  638. if networking_config:
  639. container_options['networking_config'] = networking_config
  640. container_options['environment'] = format_environment(
  641. container_options['environment'])
  642. return container_options
  643. def _get_container_host_config(self, override_options, one_off=False):
  644. options = dict(self.options, **override_options)
  645. logging_dict = options.get('logging', None)
  646. log_config = get_log_config(logging_dict)
  647. init_path = None
  648. if isinstance(options.get('init'), six.string_types):
  649. init_path = options.get('init')
  650. options['init'] = True
  651. return self.client.create_host_config(
  652. links=self._get_links(link_to_self=one_off),
  653. port_bindings=build_port_bindings(
  654. formatted_ports(options.get('ports', []))
  655. ),
  656. binds=options.get('binds'),
  657. volumes_from=self._get_volumes_from(),
  658. privileged=options.get('privileged', False),
  659. network_mode=self.network_mode.mode,
  660. devices=options.get('devices'),
  661. dns=options.get('dns'),
  662. dns_opt=options.get('dns_opt'),
  663. dns_search=options.get('dns_search'),
  664. restart_policy=options.get('restart'),
  665. cap_add=options.get('cap_add'),
  666. cap_drop=options.get('cap_drop'),
  667. mem_limit=options.get('mem_limit'),
  668. mem_reservation=options.get('mem_reservation'),
  669. memswap_limit=options.get('memswap_limit'),
  670. ulimits=build_ulimits(options.get('ulimits')),
  671. log_config=log_config,
  672. extra_hosts=options.get('extra_hosts'),
  673. read_only=options.get('read_only'),
  674. pid_mode=options.get('pid'),
  675. security_opt=options.get('security_opt'),
  676. ipc_mode=options.get('ipc'),
  677. cgroup_parent=options.get('cgroup_parent'),
  678. cpu_quota=options.get('cpu_quota'),
  679. shm_size=options.get('shm_size'),
  680. sysctls=options.get('sysctls'),
  681. pids_limit=options.get('pids_limit'),
  682. tmpfs=options.get('tmpfs'),
  683. oom_score_adj=options.get('oom_score_adj'),
  684. mem_swappiness=options.get('mem_swappiness'),
  685. group_add=options.get('group_add'),
  686. userns_mode=options.get('userns_mode'),
  687. init=options.get('init', None),
  688. init_path=init_path,
  689. isolation=options.get('isolation'),
  690. )
  691. def get_secret_volumes(self):
  692. def build_spec(secret):
  693. target = '{}/{}'.format(
  694. const.SECRETS_PATH,
  695. secret['secret'].target or secret['secret'].source)
  696. return VolumeSpec(secret['file'], target, 'ro')
  697. return [build_spec(secret) for secret in self.secrets]
  698. def build(self, no_cache=False, pull=False, force_rm=False, build_args_override=None):
  699. log.info('Building %s' % self.name)
  700. build_opts = self.options.get('build', {})
  701. build_args = build_opts.get('args', {}).copy()
  702. if build_args_override:
  703. build_args.update(build_args_override)
  704. # python2 os.stat() doesn't support unicode on some UNIX, so we
  705. # encode it to a bytestring to be safe
  706. path = build_opts.get('context')
  707. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  708. path = path.encode('utf8')
  709. build_output = self.client.build(
  710. path=path,
  711. tag=self.image_name,
  712. stream=True,
  713. rm=True,
  714. forcerm=force_rm,
  715. pull=pull,
  716. nocache=no_cache,
  717. dockerfile=build_opts.get('dockerfile', None),
  718. cache_from=build_opts.get('cache_from', None),
  719. buildargs=build_args
  720. )
  721. try:
  722. all_events = stream_output(build_output, sys.stdout)
  723. except StreamOutputError as e:
  724. raise BuildError(self, six.text_type(e))
  725. # Ensure the HTTP connection is not reused for another
  726. # streaming command, as the Docker daemon can sometimes
  727. # complain about it
  728. self.client.close()
  729. image_id = None
  730. for event in all_events:
  731. if 'stream' in event:
  732. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  733. if match:
  734. image_id = match.group(1)
  735. if image_id is None:
  736. raise BuildError(self, event if all_events else 'Unknown')
  737. return image_id
  738. def can_be_built(self):
  739. return 'build' in self.options
  740. def labels(self, one_off=False):
  741. return [
  742. '{0}={1}'.format(LABEL_PROJECT, self.project),
  743. '{0}={1}'.format(LABEL_SERVICE, self.name),
  744. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  745. ]
  746. @property
  747. def custom_container_name(self):
  748. return self.options.get('container_name')
  749. def get_container_name(self, number, one_off=False):
  750. if self.custom_container_name and not one_off:
  751. return self.custom_container_name
  752. container_name = build_container_name(
  753. self.project, self.name, number, one_off,
  754. )
  755. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  756. if container_name in ext_links_origins:
  757. raise DependencyError(
  758. 'Service {0} has a self-referential external link: {1}'.format(
  759. self.name, container_name
  760. )
  761. )
  762. return container_name
  763. def remove_image(self, image_type):
  764. if not image_type or image_type == ImageType.none:
  765. return False
  766. if image_type == ImageType.local and self.options.get('image'):
  767. return False
  768. log.info("Removing image %s", self.image_name)
  769. try:
  770. self.client.remove_image(self.image_name)
  771. return True
  772. except APIError as e:
  773. log.error("Failed to remove image for service %s: %s", self.name, e)
  774. return False
  775. def specifies_host_port(self):
  776. def has_host_port(binding):
  777. if isinstance(binding, dict):
  778. external_bindings = binding.get('published')
  779. else:
  780. _, external_bindings = split_port(binding)
  781. # there are no external bindings
  782. if external_bindings is None:
  783. return False
  784. # we only need to check the first binding from the range
  785. external_binding = external_bindings[0]
  786. # non-tuple binding means there is a host port specified
  787. if not isinstance(external_binding, tuple):
  788. return True
  789. # extract actual host port from tuple of (host_ip, host_port)
  790. _, host_port = external_binding
  791. if host_port is not None:
  792. return True
  793. return False
  794. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  795. def pull(self, ignore_pull_failures=False, silent=False):
  796. if 'image' not in self.options:
  797. return
  798. repo, tag, separator = parse_repository_tag(self.options['image'])
  799. tag = tag or 'latest'
  800. if not silent:
  801. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  802. try:
  803. output = self.client.pull(repo, tag=tag, stream=True)
  804. if silent:
  805. with open(os.devnull, 'w') as devnull:
  806. return progress_stream.get_digest_from_pull(
  807. stream_output(output, devnull))
  808. else:
  809. return progress_stream.get_digest_from_pull(
  810. stream_output(output, sys.stdout))
  811. except (StreamOutputError, NotFound) as e:
  812. if not ignore_pull_failures:
  813. raise
  814. else:
  815. log.error(six.text_type(e))
  816. def push(self, ignore_push_failures=False):
  817. if 'image' not in self.options or 'build' not in self.options:
  818. return
  819. repo, tag, separator = parse_repository_tag(self.options['image'])
  820. tag = tag or 'latest'
  821. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  822. output = self.client.push(repo, tag=tag, stream=True)
  823. try:
  824. return progress_stream.get_digest_from_push(
  825. stream_output(output, sys.stdout))
  826. except StreamOutputError as e:
  827. if not ignore_push_failures:
  828. raise
  829. else:
  830. log.error(six.text_type(e))
  831. def is_healthy(self):
  832. """ Check that all containers for this service report healthy.
  833. Returns false if at least one healthcheck is pending.
  834. If an unhealthy container is detected, raise a HealthCheckFailed
  835. exception.
  836. """
  837. result = True
  838. for ctnr in self.containers():
  839. ctnr.inspect()
  840. status = ctnr.get('State.Health.Status')
  841. if status is None:
  842. raise NoHealthCheckConfigured(self.name)
  843. elif status == 'starting':
  844. result = False
  845. elif status == 'unhealthy':
  846. raise HealthCheckFailed(ctnr.short_id)
  847. return result
  848. def short_id_alias_exists(container, network):
  849. aliases = container.get(
  850. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  851. return container.short_id in aliases
  852. class NetworkMode(object):
  853. """A `standard` network mode (ex: host, bridge)"""
  854. service_name = None
  855. def __init__(self, network_mode):
  856. self.network_mode = network_mode
  857. @property
  858. def id(self):
  859. return self.network_mode
  860. mode = id
  861. class ContainerNetworkMode(object):
  862. """A network mode that uses a container's network stack."""
  863. service_name = None
  864. def __init__(self, container):
  865. self.container = container
  866. @property
  867. def id(self):
  868. return self.container.id
  869. @property
  870. def mode(self):
  871. return 'container:' + self.container.id
  872. class ServiceNetworkMode(object):
  873. """A network mode that uses a service's network stack."""
  874. def __init__(self, service):
  875. self.service = service
  876. @property
  877. def id(self):
  878. return self.service.name
  879. service_name = id
  880. @property
  881. def mode(self):
  882. containers = self.service.containers()
  883. if containers:
  884. return 'container:' + containers[0].id
  885. log.warn("Service %s is trying to use reuse the network stack "
  886. "of another service that is not running." % (self.id))
  887. return None
  888. # Names
  889. def build_container_name(project, service, number, one_off=False):
  890. bits = [project, service]
  891. if one_off:
  892. bits.append('run')
  893. return '_'.join(bits + [str(number)])
  894. # Images
  895. def parse_repository_tag(repo_path):
  896. """Splits image identification into base image path, tag/digest
  897. and it's separator.
  898. Example:
  899. >>> parse_repository_tag('user/repo@sha256:digest')
  900. ('user/repo', 'sha256:digest', '@')
  901. >>> parse_repository_tag('user/repo:v1')
  902. ('user/repo', 'v1', ':')
  903. """
  904. tag_separator = ":"
  905. digest_separator = "@"
  906. if digest_separator in repo_path:
  907. repo, tag = repo_path.rsplit(digest_separator, 1)
  908. return repo, tag, digest_separator
  909. repo, tag = repo_path, ""
  910. if tag_separator in repo_path:
  911. repo, tag = repo_path.rsplit(tag_separator, 1)
  912. if "/" in tag:
  913. repo, tag = repo_path, ""
  914. return repo, tag, tag_separator
  915. # Volumes
  916. def merge_volume_bindings(volumes, tmpfs, previous_container):
  917. """Return a list of volume bindings for a container. Container data volumes
  918. are replaced by those from the previous container.
  919. """
  920. affinity = {}
  921. volume_bindings = dict(
  922. build_volume_binding(volume)
  923. for volume in volumes
  924. if volume.external)
  925. if previous_container:
  926. old_volumes = get_container_data_volumes(previous_container, volumes, tmpfs)
  927. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  928. volume_bindings.update(
  929. build_volume_binding(volume) for volume in old_volumes)
  930. if old_volumes:
  931. affinity = {'affinity:container': '=' + previous_container.id}
  932. return list(volume_bindings.values()), affinity
  933. def get_container_data_volumes(container, volumes_option, tmpfs_option):
  934. """Find the container data volumes that are in `volumes_option`, and return
  935. a mapping of volume bindings for those volumes.
  936. """
  937. volumes = []
  938. volumes_option = volumes_option or []
  939. container_mounts = dict(
  940. (mount['Destination'], mount)
  941. for mount in container.get('Mounts') or {}
  942. )
  943. image_volumes = [
  944. VolumeSpec.parse(volume)
  945. for volume in
  946. container.image_config['ContainerConfig'].get('Volumes') or {}
  947. ]
  948. for volume in set(volumes_option + image_volumes):
  949. # No need to preserve host volumes
  950. if volume.external:
  951. continue
  952. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  953. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  954. continue
  955. mount = container_mounts.get(volume.internal)
  956. # New volume, doesn't exist in the old container
  957. if not mount:
  958. continue
  959. # Volume was previously a host volume, now it's a container volume
  960. if not mount.get('Name'):
  961. continue
  962. # Copy existing volume from old container
  963. volume = volume._replace(external=mount['Name'])
  964. volumes.append(volume)
  965. return volumes
  966. def warn_on_masked_volume(volumes_option, container_volumes, service):
  967. container_volumes = dict(
  968. (volume.internal, volume.external)
  969. for volume in container_volumes)
  970. for volume in volumes_option:
  971. if (
  972. volume.external and
  973. volume.internal in container_volumes and
  974. container_volumes.get(volume.internal) != volume.external
  975. ):
  976. log.warn((
  977. "Service \"{service}\" is using volume \"{volume}\" from the "
  978. "previous container. Host mapping \"{host_path}\" has no effect. "
  979. "Remove the existing containers (with `docker-compose rm {service}`) "
  980. "to use the host volume mapping."
  981. ).format(
  982. service=service,
  983. volume=volume.internal,
  984. host_path=volume.external))
  985. def build_volume_binding(volume_spec):
  986. return volume_spec.internal, volume_spec.repr()
  987. def build_volume_from(volume_from_spec):
  988. """
  989. volume_from can be either a service or a container. We want to return the
  990. container.id and format it into a string complete with the mode.
  991. """
  992. if isinstance(volume_from_spec.source, Service):
  993. containers = volume_from_spec.source.containers(stopped=True)
  994. if not containers:
  995. return "{}:{}".format(
  996. volume_from_spec.source.create_container().id,
  997. volume_from_spec.mode)
  998. container = containers[0]
  999. return "{}:{}".format(container.id, volume_from_spec.mode)
  1000. elif isinstance(volume_from_spec.source, Container):
  1001. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1002. # Labels
  1003. def build_container_labels(label_options, service_labels, number, config_hash):
  1004. labels = dict(label_options or {})
  1005. labels.update(label.split('=', 1) for label in service_labels)
  1006. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1007. labels[LABEL_VERSION] = __version__
  1008. if config_hash:
  1009. log.debug("Added config hash: %s" % config_hash)
  1010. labels[LABEL_CONFIG_HASH] = config_hash
  1011. return labels
  1012. # Ulimits
  1013. def build_ulimits(ulimit_config):
  1014. if not ulimit_config:
  1015. return None
  1016. ulimits = []
  1017. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1018. if isinstance(soft_hard_values, six.integer_types):
  1019. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1020. elif isinstance(soft_hard_values, dict):
  1021. ulimit_dict = {'name': limit_name}
  1022. ulimit_dict.update(soft_hard_values)
  1023. ulimits.append(ulimit_dict)
  1024. return ulimits
  1025. def get_log_config(logging_dict):
  1026. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1027. log_options = logging_dict.get('options', None) if logging_dict else None
  1028. return LogConfig(
  1029. type=log_driver,
  1030. config=log_options
  1031. )
  1032. # TODO: remove once fix is available in docker-py
  1033. def format_environment(environment):
  1034. def format_env(key, value):
  1035. if value is None:
  1036. return key
  1037. if isinstance(value, six.binary_type):
  1038. value = value.decode('utf-8')
  1039. return '{key}={value}'.format(key=key, value=value)
  1040. return [format_env(*item) for item in environment.items()]
  1041. # Ports
  1042. def formatted_ports(ports):
  1043. result = []
  1044. for port in ports:
  1045. if isinstance(port, ServicePort):
  1046. result.append(port.legacy_repr())
  1047. else:
  1048. result.append(port)
  1049. return result
  1050. def build_container_ports(container_ports, options):
  1051. ports = []
  1052. all_ports = container_ports + options.get('expose', [])
  1053. for port_range in all_ports:
  1054. internal_range, _ = split_port(port_range)
  1055. for port in internal_range:
  1056. port = str(port)
  1057. if '/' in port:
  1058. port = tuple(port.split('/'))
  1059. ports.append(port)
  1060. return ports