service.py 38 KB

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