service.py 47 KB

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