service.py 40 KB

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