project.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import datetime
  4. import logging
  5. import operator
  6. from functools import reduce
  7. import enum
  8. from docker.errors import APIError
  9. from . import parallel
  10. from .config import ConfigurationError
  11. from .config.config import V1
  12. from .config.sort_services import get_container_name_from_network_mode
  13. from .config.sort_services import get_service_name_from_network_mode
  14. from .const import IMAGE_EVENTS
  15. from .const import LABEL_ONE_OFF
  16. from .const import LABEL_PROJECT
  17. from .const import LABEL_SERVICE
  18. from .container import Container
  19. from .network import build_networks
  20. from .network import get_networks
  21. from .network import ProjectNetworks
  22. from .service import BuildAction
  23. from .service import ContainerNetworkMode
  24. from .service import ConvergenceStrategy
  25. from .service import NetworkMode
  26. from .service import Service
  27. from .service import ServiceNetworkMode
  28. from .utils import microseconds_from_time_nano
  29. from .volume import ProjectVolumes
  30. log = logging.getLogger(__name__)
  31. @enum.unique
  32. class OneOffFilter(enum.Enum):
  33. include = 0
  34. exclude = 1
  35. only = 2
  36. @classmethod
  37. def update_labels(cls, value, labels):
  38. if value == cls.only:
  39. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "True"))
  40. elif value == cls.exclude:
  41. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "False"))
  42. elif value == cls.include:
  43. pass
  44. else:
  45. raise ValueError("Invalid value for one_off: {}".format(repr(value)))
  46. class Project(object):
  47. """
  48. A collection of services.
  49. """
  50. def __init__(self, name, services, client, networks=None, volumes=None):
  51. self.name = name
  52. self.services = services
  53. self.client = client
  54. self.volumes = volumes or ProjectVolumes({})
  55. self.networks = networks or ProjectNetworks({}, False)
  56. def labels(self, one_off=OneOffFilter.exclude):
  57. labels = ['{0}={1}'.format(LABEL_PROJECT, self.name)]
  58. OneOffFilter.update_labels(one_off, labels)
  59. return labels
  60. @classmethod
  61. def from_config(cls, name, config_data, client):
  62. """
  63. Construct a Project from a config.Config object.
  64. """
  65. use_networking = (config_data.version and config_data.version != V1)
  66. networks = build_networks(name, config_data, client)
  67. project_networks = ProjectNetworks.from_services(
  68. config_data.services,
  69. networks,
  70. use_networking)
  71. volumes = ProjectVolumes.from_config(name, config_data, client)
  72. project = cls(name, [], client, project_networks, volumes)
  73. for service_dict in config_data.services:
  74. service_dict = dict(service_dict)
  75. if use_networking:
  76. service_networks = get_networks(service_dict, networks)
  77. else:
  78. service_networks = {}
  79. service_dict.pop('networks', None)
  80. links = project.get_links(service_dict)
  81. network_mode = project.get_network_mode(
  82. service_dict, list(service_networks.keys())
  83. )
  84. volumes_from = get_volumes_from(project, service_dict)
  85. if config_data.version != V1:
  86. service_dict['volumes'] = [
  87. volumes.namespace_spec(volume_spec)
  88. for volume_spec in service_dict.get('volumes', [])
  89. ]
  90. secrets = get_secrets(
  91. service_dict['name'],
  92. service_dict.pop('secrets', None) or [],
  93. config_data.secrets)
  94. project.services.append(
  95. Service(
  96. service_dict.pop('name'),
  97. client=client,
  98. project=name,
  99. use_networking=use_networking,
  100. networks=service_networks,
  101. links=links,
  102. network_mode=network_mode,
  103. volumes_from=volumes_from,
  104. secrets=secrets,
  105. **service_dict)
  106. )
  107. return project
  108. @property
  109. def service_names(self):
  110. return [service.name for service in self.services]
  111. def get_service(self, name):
  112. """
  113. Retrieve a service by name. Raises NoSuchService
  114. if the named service does not exist.
  115. """
  116. for service in self.services:
  117. if service.name == name:
  118. return service
  119. raise NoSuchService(name)
  120. def validate_service_names(self, service_names):
  121. """
  122. Validate that the given list of service names only contains valid
  123. services. Raises NoSuchService if one of the names is invalid.
  124. """
  125. valid_names = self.service_names
  126. for name in service_names:
  127. if name not in valid_names:
  128. raise NoSuchService(name)
  129. def get_services(self, service_names=None, include_deps=False):
  130. """
  131. Returns a list of this project's services filtered
  132. by the provided list of names, or all services if service_names is None
  133. or [].
  134. If include_deps is specified, returns a list including the dependencies for
  135. service_names, in order of dependency.
  136. Preserves the original order of self.services where possible,
  137. reordering as needed to resolve dependencies.
  138. Raises NoSuchService if any of the named services do not exist.
  139. """
  140. if service_names is None or len(service_names) == 0:
  141. service_names = self.service_names
  142. unsorted = [self.get_service(name) for name in service_names]
  143. services = [s for s in self.services if s in unsorted]
  144. if include_deps:
  145. services = reduce(self._inject_deps, services, [])
  146. uniques = []
  147. [uniques.append(s) for s in services if s not in uniques]
  148. return uniques
  149. def get_services_without_duplicate(self, service_names=None, include_deps=False):
  150. services = self.get_services(service_names, include_deps)
  151. for service in services:
  152. service.remove_duplicate_containers()
  153. return services
  154. def get_links(self, service_dict):
  155. links = []
  156. if 'links' in service_dict:
  157. for link in service_dict.get('links', []):
  158. if ':' in link:
  159. service_name, link_name = link.split(':', 1)
  160. else:
  161. service_name, link_name = link, None
  162. try:
  163. links.append((self.get_service(service_name), link_name))
  164. except NoSuchService:
  165. raise ConfigurationError(
  166. 'Service "%s" has a link to service "%s" which does not '
  167. 'exist.' % (service_dict['name'], service_name))
  168. del service_dict['links']
  169. return links
  170. def get_network_mode(self, service_dict, networks):
  171. network_mode = service_dict.pop('network_mode', None)
  172. if not network_mode:
  173. if self.networks.use_networking:
  174. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  175. return NetworkMode(None)
  176. service_name = get_service_name_from_network_mode(network_mode)
  177. if service_name:
  178. return ServiceNetworkMode(self.get_service(service_name))
  179. container_name = get_container_name_from_network_mode(network_mode)
  180. if container_name:
  181. try:
  182. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  183. except APIError:
  184. raise ConfigurationError(
  185. "Service '{name}' uses the network stack of container '{dep}' which "
  186. "does not exist.".format(name=service_dict['name'], dep=container_name))
  187. return NetworkMode(network_mode)
  188. def start(self, service_names=None, **options):
  189. containers = []
  190. def start_service(service):
  191. service_containers = service.start(quiet=True, **options)
  192. containers.extend(service_containers)
  193. services = self.get_services(service_names)
  194. def get_deps(service):
  195. return {
  196. (self.get_service(dep), config)
  197. for dep, config in service.get_dependency_configs().items()
  198. }
  199. parallel.parallel_execute(
  200. services,
  201. start_service,
  202. operator.attrgetter('name'),
  203. 'Starting',
  204. get_deps)
  205. return containers
  206. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  207. containers = self.containers(service_names, one_off=one_off)
  208. def get_deps(container):
  209. # actually returning inversed dependencies
  210. return {(other, None) for other in containers
  211. if container.service in
  212. self.get_service(other.service).get_dependency_names()}
  213. parallel.parallel_execute(
  214. containers,
  215. self.build_container_operation_with_timeout_func('stop', options),
  216. operator.attrgetter('name'),
  217. 'Stopping',
  218. get_deps)
  219. def pause(self, service_names=None, **options):
  220. containers = self.containers(service_names)
  221. parallel.parallel_pause(reversed(containers), options)
  222. return containers
  223. def unpause(self, service_names=None, **options):
  224. containers = self.containers(service_names)
  225. parallel.parallel_unpause(containers, options)
  226. return containers
  227. def kill(self, service_names=None, **options):
  228. parallel.parallel_kill(self.containers(service_names), options)
  229. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  230. parallel.parallel_remove(self.containers(
  231. service_names, stopped=True, one_off=one_off
  232. ), options)
  233. def down(self, remove_image_type, include_volumes, remove_orphans=False):
  234. self.stop(one_off=OneOffFilter.include)
  235. self.find_orphan_containers(remove_orphans)
  236. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  237. self.networks.remove()
  238. if include_volumes:
  239. self.volumes.remove()
  240. self.remove_images(remove_image_type)
  241. def remove_images(self, remove_image_type):
  242. for service in self.get_services():
  243. service.remove_image(remove_image_type)
  244. def restart(self, service_names=None, **options):
  245. containers = self.containers(service_names, stopped=True)
  246. parallel.parallel_execute(
  247. containers,
  248. self.build_container_operation_with_timeout_func('restart', options),
  249. operator.attrgetter('name'),
  250. 'Restarting')
  251. return containers
  252. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, build_args=None):
  253. for service in self.get_services(service_names):
  254. if service.can_be_built():
  255. service.build(no_cache, pull, force_rm, build_args)
  256. else:
  257. log.info('%s uses an image, skipping' % service.name)
  258. def create(
  259. self,
  260. service_names=None,
  261. strategy=ConvergenceStrategy.changed,
  262. do_build=BuildAction.none,
  263. ):
  264. services = self.get_services_without_duplicate(service_names, include_deps=True)
  265. for svc in services:
  266. svc.ensure_image_exists(do_build=do_build)
  267. plans = self._get_convergence_plans(services, strategy)
  268. for service in services:
  269. service.execute_convergence_plan(
  270. plans[service.name],
  271. detached=True,
  272. start=False)
  273. def events(self, service_names=None):
  274. def build_container_event(event, container):
  275. time = datetime.datetime.fromtimestamp(event['time'])
  276. time = time.replace(
  277. microsecond=microseconds_from_time_nano(event['timeNano']))
  278. return {
  279. 'time': time,
  280. 'type': 'container',
  281. 'action': event['status'],
  282. 'id': container.id,
  283. 'service': container.service,
  284. 'attributes': {
  285. 'name': container.name,
  286. 'image': event['from'],
  287. },
  288. 'container': container,
  289. }
  290. service_names = set(service_names or self.service_names)
  291. for event in self.client.events(
  292. filters={'label': self.labels()},
  293. decode=True
  294. ):
  295. # The first part of this condition is a guard against some events
  296. # broadcasted by swarm that don't have a status field.
  297. # See https://github.com/docker/compose/issues/3316
  298. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  299. # We don't receive any image events because labels aren't applied
  300. # to images
  301. continue
  302. # TODO: get labels from the API v1.22 , see github issue 2618
  303. try:
  304. # this can fail if the container has been removed
  305. container = Container.from_id(self.client, event['id'])
  306. except APIError:
  307. continue
  308. if container.service not in service_names:
  309. continue
  310. yield build_container_event(event, container)
  311. def up(self,
  312. service_names=None,
  313. start_deps=True,
  314. strategy=ConvergenceStrategy.changed,
  315. do_build=BuildAction.none,
  316. timeout=None,
  317. detached=False,
  318. remove_orphans=False,
  319. scale_override=None):
  320. warn_for_swarm_mode(self.client)
  321. self.initialize()
  322. self.find_orphan_containers(remove_orphans)
  323. if scale_override is None:
  324. scale_override = {}
  325. services = self.get_services_without_duplicate(
  326. service_names,
  327. include_deps=start_deps)
  328. for svc in services:
  329. svc.ensure_image_exists(do_build=do_build)
  330. plans = self._get_convergence_plans(services, strategy)
  331. def do(service):
  332. return service.execute_convergence_plan(
  333. plans[service.name],
  334. timeout=timeout,
  335. detached=detached,
  336. scale_override=scale_override.get(service.name)
  337. )
  338. def get_deps(service):
  339. return {
  340. (self.get_service(dep), config)
  341. for dep, config in service.get_dependency_configs().items()
  342. }
  343. results, errors = parallel.parallel_execute(
  344. services,
  345. do,
  346. operator.attrgetter('name'),
  347. None,
  348. get_deps
  349. )
  350. if errors:
  351. raise ProjectError(
  352. 'Encountered errors while bringing up the project.'
  353. )
  354. return [
  355. container
  356. for svc_containers in results
  357. if svc_containers is not None
  358. for container in svc_containers
  359. ]
  360. def initialize(self):
  361. self.networks.initialize()
  362. self.volumes.initialize()
  363. def _get_convergence_plans(self, services, strategy):
  364. plans = {}
  365. for service in services:
  366. updated_dependencies = [
  367. name
  368. for name in service.get_dependency_names()
  369. if name in plans and
  370. plans[name].action in ('recreate', 'create')
  371. ]
  372. if updated_dependencies and strategy.allows_recreate:
  373. log.debug('%s has upstream changes (%s)',
  374. service.name,
  375. ", ".join(updated_dependencies))
  376. plan = service.convergence_plan(ConvergenceStrategy.always)
  377. else:
  378. plan = service.convergence_plan(strategy)
  379. plans[service.name] = plan
  380. return plans
  381. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False):
  382. services = self.get_services(service_names, include_deps=False)
  383. if parallel_pull:
  384. def pull_service(service):
  385. service.pull(ignore_pull_failures, True)
  386. parallel.parallel_execute(
  387. services,
  388. pull_service,
  389. operator.attrgetter('name'),
  390. 'Pulling',
  391. limit=5)
  392. else:
  393. for service in services:
  394. service.pull(ignore_pull_failures)
  395. def push(self, service_names=None, ignore_push_failures=False):
  396. for service in self.get_services(service_names, include_deps=False):
  397. service.push(ignore_push_failures)
  398. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  399. return list(filter(None, [
  400. Container.from_ps(self.client, container)
  401. for container in self.client.containers(
  402. all=stopped,
  403. filters={'label': self.labels(one_off=one_off)})])
  404. )
  405. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  406. if service_names:
  407. self.validate_service_names(service_names)
  408. else:
  409. service_names = self.service_names
  410. containers = self._labeled_containers(stopped, one_off)
  411. def matches_service_names(container):
  412. return container.labels.get(LABEL_SERVICE) in service_names
  413. return [c for c in containers if matches_service_names(c)]
  414. def find_orphan_containers(self, remove_orphans):
  415. def _find():
  416. containers = self._labeled_containers()
  417. for ctnr in containers:
  418. service_name = ctnr.labels.get(LABEL_SERVICE)
  419. if service_name not in self.service_names:
  420. yield ctnr
  421. orphans = list(_find())
  422. if not orphans:
  423. return
  424. if remove_orphans:
  425. for ctnr in orphans:
  426. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  427. ctnr.kill()
  428. ctnr.remove(force=True)
  429. else:
  430. log.warning(
  431. 'Found orphan containers ({0}) for this project. If '
  432. 'you removed or renamed this service in your compose '
  433. 'file, you can run this command with the '
  434. '--remove-orphans flag to clean it up.'.format(
  435. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  436. )
  437. )
  438. def _inject_deps(self, acc, service):
  439. dep_names = service.get_dependency_names()
  440. if len(dep_names) > 0:
  441. dep_services = self.get_services(
  442. service_names=list(set(dep_names)),
  443. include_deps=True
  444. )
  445. else:
  446. dep_services = []
  447. dep_services.append(service)
  448. return acc + dep_services
  449. def build_container_operation_with_timeout_func(self, operation, options):
  450. def container_operation_with_timeout(container):
  451. if options.get('timeout') is None:
  452. service = self.get_service(container.service)
  453. options['timeout'] = service.stop_timeout(None)
  454. return getattr(container, operation)(**options)
  455. return container_operation_with_timeout
  456. def get_volumes_from(project, service_dict):
  457. volumes_from = service_dict.pop('volumes_from', None)
  458. if not volumes_from:
  459. return []
  460. def build_volume_from(spec):
  461. if spec.type == 'service':
  462. try:
  463. return spec._replace(source=project.get_service(spec.source))
  464. except NoSuchService:
  465. pass
  466. if spec.type == 'container':
  467. try:
  468. container = Container.from_id(project.client, spec.source)
  469. return spec._replace(source=container)
  470. except APIError:
  471. pass
  472. raise ConfigurationError(
  473. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  474. "of a service or container.".format(
  475. service_dict['name'],
  476. spec.source))
  477. return [build_volume_from(vf) for vf in volumes_from]
  478. def get_secrets(service, service_secrets, secret_defs):
  479. secrets = []
  480. for secret in service_secrets:
  481. secret_def = secret_defs.get(secret.source)
  482. if not secret_def:
  483. raise ConfigurationError(
  484. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  485. .format(service=service, secret=secret.source))
  486. if secret_def.get('external_name'):
  487. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  488. "External secrets are not available to containers created by "
  489. "docker-compose.".format(service=service, secret=secret.source))
  490. continue
  491. if secret.uid or secret.gid or secret.mode:
  492. log.warn(
  493. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  494. "gid, or mode. These fields are not supported by this "
  495. "implementation of the Compose file".format(
  496. service=service, secret=secret.source
  497. )
  498. )
  499. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  500. return secrets
  501. def warn_for_swarm_mode(client):
  502. info = client.info()
  503. if info.get('Swarm', {}).get('LocalNodeState') == 'active':
  504. if info.get('ServerVersion', '').startswith('ucp'):
  505. # UCP does multi-node scheduling with traditional Compose files.
  506. return
  507. log.warn(
  508. "The Docker Engine you're using is running in swarm mode.\n\n"
  509. "Compose does not use swarm mode to deploy services to multiple nodes in a swarm. "
  510. "All containers will be scheduled on the current node.\n\n"
  511. "To deploy your application across the swarm, "
  512. "use `docker stack deploy`.\n"
  513. )
  514. class NoSuchService(Exception):
  515. def __init__(self, name):
  516. self.name = name
  517. self.msg = "No such service: %s" % self.name
  518. def __str__(self):
  519. return self.msg
  520. class ProjectError(Exception):
  521. def __init__(self, msg):
  522. self.msg = msg