service.py 40 KB

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