service.py 44 KB

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