project.py 23 KB

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