project.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import datetime
  4. import logging
  5. import operator
  6. import re
  7. from functools import reduce
  8. import enum
  9. import six
  10. from docker.errors import APIError
  11. from docker.utils import version_lt
  12. from . import parallel
  13. from .config import ConfigurationError
  14. from .config.config import V1
  15. from .config.sort_services import get_container_name_from_network_mode
  16. from .config.sort_services import get_service_name_from_network_mode
  17. from .const import LABEL_ONE_OFF
  18. from .const import LABEL_PROJECT
  19. from .const import LABEL_SERVICE
  20. from .container import Container
  21. from .network import build_networks
  22. from .network import get_networks
  23. from .network import ProjectNetworks
  24. from .service import BuildAction
  25. from .service import ContainerNetworkMode
  26. from .service import ContainerPidMode
  27. from .service import ConvergenceStrategy
  28. from .service import NetworkMode
  29. from .service import parse_repository_tag
  30. from .service import PidMode
  31. from .service import Service
  32. from .service import ServiceNetworkMode
  33. from .service import ServicePidMode
  34. from .utils import microseconds_from_time_nano
  35. from .utils import truncate_string
  36. from .volume import ProjectVolumes
  37. log = logging.getLogger(__name__)
  38. @enum.unique
  39. class OneOffFilter(enum.Enum):
  40. include = 0
  41. exclude = 1
  42. only = 2
  43. @classmethod
  44. def update_labels(cls, value, labels):
  45. if value == cls.only:
  46. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "True"))
  47. elif value == cls.exclude:
  48. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "False"))
  49. elif value == cls.include:
  50. pass
  51. else:
  52. raise ValueError("Invalid value for one_off: {}".format(repr(value)))
  53. class Project(object):
  54. """
  55. A collection of services.
  56. """
  57. def __init__(self, name, services, client, networks=None, volumes=None, config_version=None):
  58. self.name = name
  59. self.services = services
  60. self.client = client
  61. self.volumes = volumes or ProjectVolumes({})
  62. self.networks = networks or ProjectNetworks({}, False)
  63. self.config_version = config_version
  64. def labels(self, one_off=OneOffFilter.exclude, legacy=False):
  65. name = self.name
  66. if legacy:
  67. name = re.sub(r'[_-]', '', name)
  68. labels = ['{0}={1}'.format(LABEL_PROJECT, name)]
  69. OneOffFilter.update_labels(one_off, labels)
  70. return labels
  71. @classmethod
  72. def from_config(cls, name, config_data, client, default_platform=None):
  73. """
  74. Construct a Project from a config.Config object.
  75. """
  76. use_networking = (config_data.version and config_data.version != V1)
  77. networks = build_networks(name, config_data, client)
  78. project_networks = ProjectNetworks.from_services(
  79. config_data.services,
  80. networks,
  81. use_networking)
  82. volumes = ProjectVolumes.from_config(name, config_data, client)
  83. project = cls(name, [], client, project_networks, volumes, config_data.version)
  84. for service_dict in config_data.services:
  85. service_dict = dict(service_dict)
  86. if use_networking:
  87. service_networks = get_networks(service_dict, networks)
  88. else:
  89. service_networks = {}
  90. service_dict.pop('networks', None)
  91. links = project.get_links(service_dict)
  92. network_mode = project.get_network_mode(
  93. service_dict, list(service_networks.keys())
  94. )
  95. pid_mode = project.get_pid_mode(service_dict)
  96. volumes_from = get_volumes_from(project, service_dict)
  97. if config_data.version != V1:
  98. service_dict['volumes'] = [
  99. volumes.namespace_spec(volume_spec)
  100. for volume_spec in service_dict.get('volumes', [])
  101. ]
  102. secrets = get_secrets(
  103. service_dict['name'],
  104. service_dict.pop('secrets', None) or [],
  105. config_data.secrets)
  106. project.services.append(
  107. Service(
  108. service_dict.pop('name'),
  109. client=client,
  110. project=name,
  111. use_networking=use_networking,
  112. networks=service_networks,
  113. links=links,
  114. network_mode=network_mode,
  115. volumes_from=volumes_from,
  116. secrets=secrets,
  117. pid_mode=pid_mode,
  118. platform=service_dict.pop('platform', None),
  119. default_platform=default_platform,
  120. **service_dict)
  121. )
  122. return project
  123. @property
  124. def service_names(self):
  125. return [service.name for service in self.services]
  126. def get_service(self, name):
  127. """
  128. Retrieve a service by name. Raises NoSuchService
  129. if the named service does not exist.
  130. """
  131. for service in self.services:
  132. if service.name == name:
  133. return service
  134. raise NoSuchService(name)
  135. def validate_service_names(self, service_names):
  136. """
  137. Validate that the given list of service names only contains valid
  138. services. Raises NoSuchService if one of the names is invalid.
  139. """
  140. valid_names = self.service_names
  141. for name in service_names:
  142. if name not in valid_names:
  143. raise NoSuchService(name)
  144. def get_services(self, service_names=None, include_deps=False):
  145. """
  146. Returns a list of this project's services filtered
  147. by the provided list of names, or all services if service_names is None
  148. or [].
  149. If include_deps is specified, returns a list including the dependencies for
  150. service_names, in order of dependency.
  151. Preserves the original order of self.services where possible,
  152. reordering as needed to resolve dependencies.
  153. Raises NoSuchService if any of the named services do not exist.
  154. """
  155. if service_names is None or len(service_names) == 0:
  156. service_names = self.service_names
  157. unsorted = [self.get_service(name) for name in service_names]
  158. services = [s for s in self.services if s in unsorted]
  159. if include_deps:
  160. services = reduce(self._inject_deps, services, [])
  161. uniques = []
  162. [uniques.append(s) for s in services if s not in uniques]
  163. return uniques
  164. def get_services_without_duplicate(self, service_names=None, include_deps=False):
  165. services = self.get_services(service_names, include_deps)
  166. for service in services:
  167. service.remove_duplicate_containers()
  168. return services
  169. def get_links(self, service_dict):
  170. links = []
  171. if 'links' in service_dict:
  172. for link in service_dict.get('links', []):
  173. if ':' in link:
  174. service_name, link_name = link.split(':', 1)
  175. else:
  176. service_name, link_name = link, None
  177. try:
  178. links.append((self.get_service(service_name), link_name))
  179. except NoSuchService:
  180. raise ConfigurationError(
  181. 'Service "%s" has a link to service "%s" which does not '
  182. 'exist.' % (service_dict['name'], service_name))
  183. del service_dict['links']
  184. return links
  185. def get_network_mode(self, service_dict, networks):
  186. network_mode = service_dict.pop('network_mode', None)
  187. if not network_mode:
  188. if self.networks.use_networking:
  189. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  190. return NetworkMode(None)
  191. service_name = get_service_name_from_network_mode(network_mode)
  192. if service_name:
  193. return ServiceNetworkMode(self.get_service(service_name))
  194. container_name = get_container_name_from_network_mode(network_mode)
  195. if container_name:
  196. try:
  197. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  198. except APIError:
  199. raise ConfigurationError(
  200. "Service '{name}' uses the network stack of container '{dep}' which "
  201. "does not exist.".format(name=service_dict['name'], dep=container_name))
  202. return NetworkMode(network_mode)
  203. def get_pid_mode(self, service_dict):
  204. pid_mode = service_dict.pop('pid', None)
  205. if not pid_mode:
  206. return PidMode(None)
  207. service_name = get_service_name_from_network_mode(pid_mode)
  208. if service_name:
  209. return ServicePidMode(self.get_service(service_name))
  210. container_name = get_container_name_from_network_mode(pid_mode)
  211. if container_name:
  212. try:
  213. return ContainerPidMode(Container.from_id(self.client, container_name))
  214. except APIError:
  215. raise ConfigurationError(
  216. "Service '{name}' uses the PID namespace of container '{dep}' which "
  217. "does not exist.".format(name=service_dict['name'], dep=container_name)
  218. )
  219. return PidMode(pid_mode)
  220. def start(self, service_names=None, **options):
  221. containers = []
  222. def start_service(service):
  223. service_containers = service.start(quiet=True, **options)
  224. containers.extend(service_containers)
  225. services = self.get_services(service_names)
  226. def get_deps(service):
  227. return {
  228. (self.get_service(dep), config)
  229. for dep, config in service.get_dependency_configs().items()
  230. }
  231. parallel.parallel_execute(
  232. services,
  233. start_service,
  234. operator.attrgetter('name'),
  235. 'Starting',
  236. get_deps,
  237. fail_check=lambda obj: not obj.containers(),
  238. )
  239. return containers
  240. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  241. containers = self.containers(service_names, one_off=one_off)
  242. def get_deps(container):
  243. # actually returning inversed dependencies
  244. return {(other, None) for other in containers
  245. if container.service in
  246. self.get_service(other.service).get_dependency_names()}
  247. parallel.parallel_execute(
  248. containers,
  249. self.build_container_operation_with_timeout_func('stop', options),
  250. operator.attrgetter('name'),
  251. 'Stopping',
  252. get_deps,
  253. )
  254. def pause(self, service_names=None, **options):
  255. containers = self.containers(service_names)
  256. parallel.parallel_pause(reversed(containers), options)
  257. return containers
  258. def unpause(self, service_names=None, **options):
  259. containers = self.containers(service_names)
  260. parallel.parallel_unpause(containers, options)
  261. return containers
  262. def kill(self, service_names=None, **options):
  263. parallel.parallel_kill(self.containers(service_names), options)
  264. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  265. parallel.parallel_remove(self.containers(
  266. service_names, stopped=True, one_off=one_off
  267. ), options)
  268. def down(
  269. self,
  270. remove_image_type,
  271. include_volumes,
  272. remove_orphans=False,
  273. timeout=None,
  274. ignore_orphans=False):
  275. self.stop(one_off=OneOffFilter.include, timeout=timeout)
  276. if not ignore_orphans:
  277. self.find_orphan_containers(remove_orphans)
  278. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  279. self.networks.remove()
  280. if include_volumes:
  281. self.volumes.remove()
  282. self.remove_images(remove_image_type)
  283. def remove_images(self, remove_image_type):
  284. for service in self.get_services():
  285. service.remove_image(remove_image_type)
  286. def restart(self, service_names=None, **options):
  287. containers = self.containers(service_names, stopped=True)
  288. parallel.parallel_execute(
  289. containers,
  290. self.build_container_operation_with_timeout_func('restart', options),
  291. operator.attrgetter('name'),
  292. 'Restarting',
  293. )
  294. return containers
  295. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, memory=None,
  296. build_args=None, gzip=False, parallel_build=False):
  297. services = []
  298. for service in self.get_services(service_names):
  299. if service.can_be_built():
  300. services.append(service)
  301. else:
  302. log.info('%s uses an image, skipping' % service.name)
  303. def build_service(service):
  304. service.build(no_cache, pull, force_rm, memory, build_args, gzip)
  305. if parallel_build:
  306. _, errors = parallel.parallel_execute(
  307. services,
  308. build_service,
  309. operator.attrgetter('name'),
  310. 'Building',
  311. limit=5,
  312. )
  313. if len(errors):
  314. combined_errors = '\n'.join([
  315. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  316. ])
  317. raise ProjectError(combined_errors)
  318. else:
  319. for service in services:
  320. build_service(service)
  321. def create(
  322. self,
  323. service_names=None,
  324. strategy=ConvergenceStrategy.changed,
  325. do_build=BuildAction.none,
  326. ):
  327. services = self.get_services_without_duplicate(service_names, include_deps=True)
  328. for svc in services:
  329. svc.ensure_image_exists(do_build=do_build)
  330. plans = self._get_convergence_plans(services, strategy)
  331. for service in services:
  332. service.execute_convergence_plan(
  333. plans[service.name],
  334. detached=True,
  335. start=False)
  336. def _legacy_event_processor(self, service_names):
  337. # Only for v1 files or when Compose is forced to use an older API version
  338. def build_container_event(event, container):
  339. time = datetime.datetime.fromtimestamp(event['time'])
  340. time = time.replace(
  341. microsecond=microseconds_from_time_nano(event['timeNano'])
  342. )
  343. return {
  344. 'time': time,
  345. 'type': 'container',
  346. 'action': event['status'],
  347. 'id': container.id,
  348. 'service': container.service,
  349. 'attributes': {
  350. 'name': container.name,
  351. 'image': event['from'],
  352. },
  353. 'container': container,
  354. }
  355. service_names = set(service_names or self.service_names)
  356. for event in self.client.events(
  357. filters={'label': self.labels()},
  358. decode=True
  359. ):
  360. # This is a guard against some events broadcasted by swarm that
  361. # don't have a status field.
  362. # See https://github.com/docker/compose/issues/3316
  363. if 'status' not in event:
  364. continue
  365. try:
  366. # this can fail if the container has been removed or if the event
  367. # refers to an image
  368. container = Container.from_id(self.client, event['id'])
  369. except APIError:
  370. continue
  371. if container.service not in service_names:
  372. continue
  373. yield build_container_event(event, container)
  374. def events(self, service_names=None):
  375. if version_lt(self.client.api_version, '1.22'):
  376. # New, better event API was introduced in 1.22.
  377. return self._legacy_event_processor(service_names)
  378. def build_container_event(event):
  379. container_attrs = event['Actor']['Attributes']
  380. time = datetime.datetime.fromtimestamp(event['time'])
  381. time = time.replace(
  382. microsecond=microseconds_from_time_nano(event['timeNano'])
  383. )
  384. container = None
  385. try:
  386. container = Container.from_id(self.client, event['id'])
  387. except APIError:
  388. # Container may have been removed (e.g. if this is a destroy event)
  389. pass
  390. return {
  391. 'time': time,
  392. 'type': 'container',
  393. 'action': event['status'],
  394. 'id': event['Actor']['ID'],
  395. 'service': container_attrs.get(LABEL_SERVICE),
  396. 'attributes': dict([
  397. (k, v) for k, v in container_attrs.items()
  398. if not k.startswith('com.docker.compose.')
  399. ]),
  400. 'container': container,
  401. }
  402. def yield_loop(service_names):
  403. for event in self.client.events(
  404. filters={'label': self.labels()},
  405. decode=True
  406. ):
  407. # TODO: support other event types
  408. if event.get('Type') != 'container':
  409. continue
  410. try:
  411. if event['Actor']['Attributes'][LABEL_SERVICE] not in service_names:
  412. continue
  413. except KeyError:
  414. continue
  415. yield build_container_event(event)
  416. return yield_loop(set(service_names) if service_names else self.service_names)
  417. def up(self,
  418. service_names=None,
  419. start_deps=True,
  420. strategy=ConvergenceStrategy.changed,
  421. do_build=BuildAction.none,
  422. timeout=None,
  423. detached=False,
  424. remove_orphans=False,
  425. ignore_orphans=False,
  426. scale_override=None,
  427. rescale=True,
  428. start=True,
  429. always_recreate_deps=False,
  430. reset_container_image=False,
  431. renew_anonymous_volumes=False,
  432. silent=False,
  433. ):
  434. self.initialize()
  435. if not ignore_orphans:
  436. self.find_orphan_containers(remove_orphans)
  437. if scale_override is None:
  438. scale_override = {}
  439. services = self.get_services_without_duplicate(
  440. service_names,
  441. include_deps=start_deps)
  442. for svc in services:
  443. svc.ensure_image_exists(do_build=do_build, silent=silent)
  444. plans = self._get_convergence_plans(
  445. services, strategy, always_recreate_deps=always_recreate_deps)
  446. def do(service):
  447. return service.execute_convergence_plan(
  448. plans[service.name],
  449. timeout=timeout,
  450. detached=detached,
  451. scale_override=scale_override.get(service.name),
  452. rescale=rescale,
  453. start=start,
  454. reset_container_image=reset_container_image,
  455. renew_anonymous_volumes=renew_anonymous_volumes,
  456. )
  457. def get_deps(service):
  458. return {
  459. (self.get_service(dep), config)
  460. for dep, config in service.get_dependency_configs().items()
  461. }
  462. results, errors = parallel.parallel_execute(
  463. services,
  464. do,
  465. operator.attrgetter('name'),
  466. None,
  467. get_deps,
  468. )
  469. if errors:
  470. raise ProjectError(
  471. 'Encountered errors while bringing up the project.'
  472. )
  473. return [
  474. container
  475. for svc_containers in results
  476. if svc_containers is not None
  477. for container in svc_containers
  478. ]
  479. def initialize(self):
  480. self.networks.initialize()
  481. self.volumes.initialize()
  482. def _get_convergence_plans(self, services, strategy, always_recreate_deps=False):
  483. plans = {}
  484. for service in services:
  485. updated_dependencies = [
  486. name
  487. for name in service.get_dependency_names()
  488. if name in plans and
  489. plans[name].action in ('recreate', 'create')
  490. ]
  491. if updated_dependencies and strategy.allows_recreate:
  492. log.debug('%s has upstream changes (%s)',
  493. service.name,
  494. ", ".join(updated_dependencies))
  495. containers_stopped = any(
  496. service.containers(stopped=True, filters={'status': ['created', 'exited']}))
  497. has_links = any(c.get('HostConfig.Links') for c in service.containers())
  498. if always_recreate_deps or containers_stopped or not has_links:
  499. plan = service.convergence_plan(ConvergenceStrategy.always)
  500. else:
  501. plan = service.convergence_plan(strategy)
  502. else:
  503. plan = service.convergence_plan(strategy)
  504. plans[service.name] = plan
  505. return plans
  506. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False, silent=False,
  507. include_deps=False):
  508. services = self.get_services(service_names, include_deps)
  509. msg = not silent and 'Pulling' or None
  510. if parallel_pull:
  511. def pull_service(service):
  512. strm = service.pull(ignore_pull_failures, True, stream=True)
  513. if strm is None: # Attempting to pull service with no `image` key is a no-op
  514. return
  515. writer = parallel.get_stream_writer()
  516. for event in strm:
  517. if 'status' not in event:
  518. continue
  519. status = event['status'].lower()
  520. if 'progressDetail' in event:
  521. detail = event['progressDetail']
  522. if 'current' in detail and 'total' in detail:
  523. percentage = float(detail['current']) / float(detail['total'])
  524. status = '{} ({:.1%})'.format(status, percentage)
  525. writer.write(
  526. msg, service.name, truncate_string(status), lambda s: s
  527. )
  528. _, errors = parallel.parallel_execute(
  529. services,
  530. pull_service,
  531. operator.attrgetter('name'),
  532. msg,
  533. limit=5,
  534. )
  535. if len(errors):
  536. combined_errors = '\n'.join([
  537. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  538. ])
  539. raise ProjectError(combined_errors)
  540. else:
  541. for service in services:
  542. service.pull(ignore_pull_failures, silent=silent)
  543. def push(self, service_names=None, ignore_push_failures=False):
  544. unique_images = set()
  545. for service in self.get_services(service_names, include_deps=False):
  546. # Considering <image> and <image:latest> as the same
  547. repo, tag, sep = parse_repository_tag(service.image_name)
  548. service_image_name = sep.join((repo, tag)) if tag else sep.join((repo, 'latest'))
  549. if service_image_name not in unique_images:
  550. service.push(ignore_push_failures)
  551. unique_images.add(service_image_name)
  552. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  553. ctnrs = list(filter(None, [
  554. Container.from_ps(self.client, container)
  555. for container in self.client.containers(
  556. all=stopped,
  557. filters={'label': self.labels(one_off=one_off)})])
  558. )
  559. if ctnrs:
  560. return ctnrs
  561. return list(filter(lambda c: c.has_legacy_proj_name(self.name), filter(None, [
  562. Container.from_ps(self.client, container)
  563. for container in self.client.containers(
  564. all=stopped,
  565. filters={'label': self.labels(one_off=one_off, legacy=True)})])
  566. ))
  567. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  568. if service_names:
  569. self.validate_service_names(service_names)
  570. else:
  571. service_names = self.service_names
  572. containers = self._labeled_containers(stopped, one_off)
  573. def matches_service_names(container):
  574. return container.labels.get(LABEL_SERVICE) in service_names
  575. return [c for c in containers if matches_service_names(c)]
  576. def find_orphan_containers(self, remove_orphans):
  577. def _find():
  578. containers = self._labeled_containers()
  579. for ctnr in containers:
  580. service_name = ctnr.labels.get(LABEL_SERVICE)
  581. if service_name not in self.service_names:
  582. yield ctnr
  583. orphans = list(_find())
  584. if not orphans:
  585. return
  586. if remove_orphans:
  587. for ctnr in orphans:
  588. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  589. ctnr.kill()
  590. ctnr.remove(force=True)
  591. else:
  592. log.warning(
  593. 'Found orphan containers ({0}) for this project. If '
  594. 'you removed or renamed this service in your compose '
  595. 'file, you can run this command with the '
  596. '--remove-orphans flag to clean it up.'.format(
  597. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  598. )
  599. )
  600. def _inject_deps(self, acc, service):
  601. dep_names = service.get_dependency_names()
  602. if len(dep_names) > 0:
  603. dep_services = self.get_services(
  604. service_names=list(set(dep_names)),
  605. include_deps=True
  606. )
  607. else:
  608. dep_services = []
  609. dep_services.append(service)
  610. return acc + dep_services
  611. def build_container_operation_with_timeout_func(self, operation, options):
  612. def container_operation_with_timeout(container):
  613. if options.get('timeout') is None:
  614. service = self.get_service(container.service)
  615. options['timeout'] = service.stop_timeout(None)
  616. return getattr(container, operation)(**options)
  617. return container_operation_with_timeout
  618. def get_volumes_from(project, service_dict):
  619. volumes_from = service_dict.pop('volumes_from', None)
  620. if not volumes_from:
  621. return []
  622. def build_volume_from(spec):
  623. if spec.type == 'service':
  624. try:
  625. return spec._replace(source=project.get_service(spec.source))
  626. except NoSuchService:
  627. pass
  628. if spec.type == 'container':
  629. try:
  630. container = Container.from_id(project.client, spec.source)
  631. return spec._replace(source=container)
  632. except APIError:
  633. pass
  634. raise ConfigurationError(
  635. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  636. "of a service or container.".format(
  637. service_dict['name'],
  638. spec.source))
  639. return [build_volume_from(vf) for vf in volumes_from]
  640. def get_secrets(service, service_secrets, secret_defs):
  641. secrets = []
  642. for secret in service_secrets:
  643. secret_def = secret_defs.get(secret.source)
  644. if not secret_def:
  645. raise ConfigurationError(
  646. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  647. .format(service=service, secret=secret.source))
  648. if secret_def.get('external'):
  649. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  650. "External secrets are not available to containers created by "
  651. "docker-compose.".format(service=service, secret=secret.source))
  652. continue
  653. if secret.uid or secret.gid or secret.mode:
  654. log.warn(
  655. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  656. "gid, or mode. These fields are not supported by this "
  657. "implementation of the Compose file".format(
  658. service=service, secret=secret.source
  659. )
  660. )
  661. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  662. return secrets
  663. class NoSuchService(Exception):
  664. def __init__(self, name):
  665. if isinstance(name, six.binary_type):
  666. name = name.decode('utf-8')
  667. self.name = name
  668. self.msg = "No such service: %s" % self.name
  669. def __str__(self):
  670. return self.msg
  671. class ProjectError(Exception):
  672. def __init__(self, msg):
  673. self.msg = msg