project.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. )
  229. return containers
  230. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  231. containers = self.containers(service_names, one_off=one_off)
  232. def get_deps(container):
  233. # actually returning inversed dependencies
  234. return {(other, None) for other in containers
  235. if container.service in
  236. self.get_service(other.service).get_dependency_names()}
  237. parallel.parallel_execute(
  238. containers,
  239. self.build_container_operation_with_timeout_func('stop', options),
  240. operator.attrgetter('name'),
  241. 'Stopping',
  242. get_deps,
  243. )
  244. def pause(self, service_names=None, **options):
  245. containers = self.containers(service_names)
  246. parallel.parallel_pause(reversed(containers), options)
  247. return containers
  248. def unpause(self, service_names=None, **options):
  249. containers = self.containers(service_names)
  250. parallel.parallel_unpause(containers, options)
  251. return containers
  252. def kill(self, service_names=None, **options):
  253. parallel.parallel_kill(self.containers(service_names), options)
  254. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  255. parallel.parallel_remove(self.containers(
  256. service_names, stopped=True, one_off=one_off
  257. ), options)
  258. def down(self, remove_image_type, include_volumes, remove_orphans=False):
  259. self.stop(one_off=OneOffFilter.include)
  260. self.find_orphan_containers(remove_orphans)
  261. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  262. self.networks.remove()
  263. if include_volumes:
  264. self.volumes.remove()
  265. self.remove_images(remove_image_type)
  266. def remove_images(self, remove_image_type):
  267. for service in self.get_services():
  268. service.remove_image(remove_image_type)
  269. def restart(self, service_names=None, **options):
  270. containers = self.containers(service_names, stopped=True)
  271. parallel.parallel_execute(
  272. containers,
  273. self.build_container_operation_with_timeout_func('restart', options),
  274. operator.attrgetter('name'),
  275. 'Restarting',
  276. )
  277. return containers
  278. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, build_args=None):
  279. for service in self.get_services(service_names):
  280. if service.can_be_built():
  281. service.build(no_cache, pull, force_rm, build_args)
  282. else:
  283. log.info('%s uses an image, skipping' % service.name)
  284. def create(
  285. self,
  286. service_names=None,
  287. strategy=ConvergenceStrategy.changed,
  288. do_build=BuildAction.none,
  289. ):
  290. services = self.get_services_without_duplicate(service_names, include_deps=True)
  291. for svc in services:
  292. svc.ensure_image_exists(do_build=do_build)
  293. plans = self._get_convergence_plans(services, strategy)
  294. for service in services:
  295. service.execute_convergence_plan(
  296. plans[service.name],
  297. detached=True,
  298. start=False)
  299. def events(self, service_names=None):
  300. def build_container_event(event, container):
  301. time = datetime.datetime.fromtimestamp(event['time'])
  302. time = time.replace(
  303. microsecond=microseconds_from_time_nano(event['timeNano']))
  304. return {
  305. 'time': time,
  306. 'type': 'container',
  307. 'action': event['status'],
  308. 'id': container.id,
  309. 'service': container.service,
  310. 'attributes': {
  311. 'name': container.name,
  312. 'image': event['from'],
  313. },
  314. 'container': container,
  315. }
  316. service_names = set(service_names or self.service_names)
  317. for event in self.client.events(
  318. filters={'label': self.labels()},
  319. decode=True
  320. ):
  321. # The first part of this condition is a guard against some events
  322. # broadcasted by swarm that don't have a status field.
  323. # See https://github.com/docker/compose/issues/3316
  324. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  325. # We don't receive any image events because labels aren't applied
  326. # to images
  327. continue
  328. # TODO: get labels from the API v1.22 , see github issue 2618
  329. try:
  330. # this can fail if the container has been removed
  331. container = Container.from_id(self.client, event['id'])
  332. except APIError:
  333. continue
  334. if container.service not in service_names:
  335. continue
  336. yield build_container_event(event, container)
  337. def up(self,
  338. service_names=None,
  339. start_deps=True,
  340. strategy=ConvergenceStrategy.changed,
  341. do_build=BuildAction.none,
  342. timeout=None,
  343. detached=False,
  344. remove_orphans=False,
  345. scale_override=None,
  346. rescale=True):
  347. warn_for_swarm_mode(self.client)
  348. self.initialize()
  349. self.find_orphan_containers(remove_orphans)
  350. if scale_override is None:
  351. scale_override = {}
  352. services = self.get_services_without_duplicate(
  353. service_names,
  354. include_deps=start_deps)
  355. for svc in services:
  356. svc.ensure_image_exists(do_build=do_build)
  357. plans = self._get_convergence_plans(services, strategy)
  358. def do(service):
  359. return service.execute_convergence_plan(
  360. plans[service.name],
  361. timeout=timeout,
  362. detached=detached,
  363. scale_override=scale_override.get(service.name),
  364. rescale=rescale
  365. )
  366. def get_deps(service):
  367. return {
  368. (self.get_service(dep), config)
  369. for dep, config in service.get_dependency_configs().items()
  370. }
  371. results, errors = parallel.parallel_execute(
  372. services,
  373. do,
  374. operator.attrgetter('name'),
  375. None,
  376. get_deps,
  377. )
  378. if errors:
  379. raise ProjectError(
  380. 'Encountered errors while bringing up the project.'
  381. )
  382. return [
  383. container
  384. for svc_containers in results
  385. if svc_containers is not None
  386. for container in svc_containers
  387. ]
  388. def initialize(self):
  389. self.networks.initialize()
  390. self.volumes.initialize()
  391. def _get_convergence_plans(self, services, strategy):
  392. plans = {}
  393. for service in services:
  394. updated_dependencies = [
  395. name
  396. for name in service.get_dependency_names()
  397. if name in plans and
  398. plans[name].action in ('recreate', 'create')
  399. ]
  400. if updated_dependencies and strategy.allows_recreate:
  401. log.debug('%s has upstream changes (%s)',
  402. service.name,
  403. ", ".join(updated_dependencies))
  404. plan = service.convergence_plan(ConvergenceStrategy.always)
  405. else:
  406. plan = service.convergence_plan(strategy)
  407. plans[service.name] = plan
  408. return plans
  409. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False, silent=False):
  410. services = self.get_services(service_names, include_deps=False)
  411. if parallel_pull:
  412. def pull_service(service):
  413. service.pull(ignore_pull_failures, True)
  414. parallel.parallel_execute(
  415. services,
  416. pull_service,
  417. operator.attrgetter('name'),
  418. 'Pulling',
  419. limit=5,
  420. )
  421. else:
  422. for service in services:
  423. service.pull(ignore_pull_failures, silent=silent)
  424. def push(self, service_names=None, ignore_push_failures=False):
  425. for service in self.get_services(service_names, include_deps=False):
  426. service.push(ignore_push_failures)
  427. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  428. return list(filter(None, [
  429. Container.from_ps(self.client, container)
  430. for container in self.client.containers(
  431. all=stopped,
  432. filters={'label': self.labels(one_off=one_off)})])
  433. )
  434. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  435. if service_names:
  436. self.validate_service_names(service_names)
  437. else:
  438. service_names = self.service_names
  439. containers = self._labeled_containers(stopped, one_off)
  440. def matches_service_names(container):
  441. return container.labels.get(LABEL_SERVICE) in service_names
  442. return [c for c in containers if matches_service_names(c)]
  443. def find_orphan_containers(self, remove_orphans):
  444. def _find():
  445. containers = self._labeled_containers()
  446. for ctnr in containers:
  447. service_name = ctnr.labels.get(LABEL_SERVICE)
  448. if service_name not in self.service_names:
  449. yield ctnr
  450. orphans = list(_find())
  451. if not orphans:
  452. return
  453. if remove_orphans:
  454. for ctnr in orphans:
  455. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  456. ctnr.kill()
  457. ctnr.remove(force=True)
  458. else:
  459. log.warning(
  460. 'Found orphan containers ({0}) for this project. If '
  461. 'you removed or renamed this service in your compose '
  462. 'file, you can run this command with the '
  463. '--remove-orphans flag to clean it up.'.format(
  464. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  465. )
  466. )
  467. def _inject_deps(self, acc, service):
  468. dep_names = service.get_dependency_names()
  469. if len(dep_names) > 0:
  470. dep_services = self.get_services(
  471. service_names=list(set(dep_names)),
  472. include_deps=True
  473. )
  474. else:
  475. dep_services = []
  476. dep_services.append(service)
  477. return acc + dep_services
  478. def build_container_operation_with_timeout_func(self, operation, options):
  479. def container_operation_with_timeout(container):
  480. if options.get('timeout') is None:
  481. service = self.get_service(container.service)
  482. options['timeout'] = service.stop_timeout(None)
  483. return getattr(container, operation)(**options)
  484. return container_operation_with_timeout
  485. def get_volumes_from(project, service_dict):
  486. volumes_from = service_dict.pop('volumes_from', None)
  487. if not volumes_from:
  488. return []
  489. def build_volume_from(spec):
  490. if spec.type == 'service':
  491. try:
  492. return spec._replace(source=project.get_service(spec.source))
  493. except NoSuchService:
  494. pass
  495. if spec.type == 'container':
  496. try:
  497. container = Container.from_id(project.client, spec.source)
  498. return spec._replace(source=container)
  499. except APIError:
  500. pass
  501. raise ConfigurationError(
  502. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  503. "of a service or container.".format(
  504. service_dict['name'],
  505. spec.source))
  506. return [build_volume_from(vf) for vf in volumes_from]
  507. def get_secrets(service, service_secrets, secret_defs):
  508. secrets = []
  509. for secret in service_secrets:
  510. secret_def = secret_defs.get(secret.source)
  511. if not secret_def:
  512. raise ConfigurationError(
  513. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  514. .format(service=service, secret=secret.source))
  515. if secret_def.get('external_name'):
  516. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  517. "External secrets are not available to containers created by "
  518. "docker-compose.".format(service=service, secret=secret.source))
  519. continue
  520. if secret.uid or secret.gid or secret.mode:
  521. log.warn(
  522. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  523. "gid, or mode. These fields are not supported by this "
  524. "implementation of the Compose file".format(
  525. service=service, secret=secret.source
  526. )
  527. )
  528. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  529. return secrets
  530. def warn_for_swarm_mode(client):
  531. info = client.info()
  532. if info.get('Swarm', {}).get('LocalNodeState') == 'active':
  533. if info.get('ServerVersion', '').startswith('ucp'):
  534. # UCP does multi-node scheduling with traditional Compose files.
  535. return
  536. log.warn(
  537. "The Docker Engine you're using is running in swarm mode.\n\n"
  538. "Compose does not use swarm mode to deploy services to multiple nodes in a swarm. "
  539. "All containers will be scheduled on the current node.\n\n"
  540. "To deploy your application across the swarm, "
  541. "use `docker stack deploy`.\n"
  542. )
  543. class NoSuchService(Exception):
  544. def __init__(self, name):
  545. self.name = name
  546. self.msg = "No such service: %s" % self.name
  547. def __str__(self):
  548. return self.msg
  549. class ProjectError(Exception):
  550. def __init__(self, msg):
  551. self.msg = msg