service.py 39 KB

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