service.py 43 KB

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