project.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. project.services.append(
  91. Service(
  92. service_dict.pop('name'),
  93. client=client,
  94. project=name,
  95. use_networking=use_networking,
  96. networks=service_networks,
  97. links=links,
  98. network_mode=network_mode,
  99. volumes_from=volumes_from,
  100. **service_dict)
  101. )
  102. return project
  103. @property
  104. def service_names(self):
  105. return [service.name for service in self.services]
  106. def get_service(self, name):
  107. """
  108. Retrieve a service by name. Raises NoSuchService
  109. if the named service does not exist.
  110. """
  111. for service in self.services:
  112. if service.name == name:
  113. return service
  114. raise NoSuchService(name)
  115. def validate_service_names(self, service_names):
  116. """
  117. Validate that the given list of service names only contains valid
  118. services. Raises NoSuchService if one of the names is invalid.
  119. """
  120. valid_names = self.service_names
  121. for name in service_names:
  122. if name not in valid_names:
  123. raise NoSuchService(name)
  124. def get_services(self, service_names=None, include_deps=False):
  125. """
  126. Returns a list of this project's services filtered
  127. by the provided list of names, or all services if service_names is None
  128. or [].
  129. If include_deps is specified, returns a list including the dependencies for
  130. service_names, in order of dependency.
  131. Preserves the original order of self.services where possible,
  132. reordering as needed to resolve dependencies.
  133. Raises NoSuchService if any of the named services do not exist.
  134. """
  135. if service_names is None or len(service_names) == 0:
  136. service_names = self.service_names
  137. unsorted = [self.get_service(name) for name in service_names]
  138. services = [s for s in self.services if s in unsorted]
  139. if include_deps:
  140. services = reduce(self._inject_deps, services, [])
  141. uniques = []
  142. [uniques.append(s) for s in services if s not in uniques]
  143. return uniques
  144. def get_services_without_duplicate(self, service_names=None, include_deps=False):
  145. services = self.get_services(service_names, include_deps)
  146. for service in services:
  147. service.remove_duplicate_containers()
  148. return services
  149. def get_links(self, service_dict):
  150. links = []
  151. if 'links' in service_dict:
  152. for link in service_dict.get('links', []):
  153. if ':' in link:
  154. service_name, link_name = link.split(':', 1)
  155. else:
  156. service_name, link_name = link, None
  157. try:
  158. links.append((self.get_service(service_name), link_name))
  159. except NoSuchService:
  160. raise ConfigurationError(
  161. 'Service "%s" has a link to service "%s" which does not '
  162. 'exist.' % (service_dict['name'], service_name))
  163. del service_dict['links']
  164. return links
  165. def get_network_mode(self, service_dict, networks):
  166. network_mode = service_dict.pop('network_mode', None)
  167. if not network_mode:
  168. if self.networks.use_networking:
  169. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  170. return NetworkMode(None)
  171. service_name = get_service_name_from_network_mode(network_mode)
  172. if service_name:
  173. return ServiceNetworkMode(self.get_service(service_name))
  174. container_name = get_container_name_from_network_mode(network_mode)
  175. if container_name:
  176. try:
  177. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  178. except APIError:
  179. raise ConfigurationError(
  180. "Service '{name}' uses the network stack of container '{dep}' which "
  181. "does not exist.".format(name=service_dict['name'], dep=container_name))
  182. return NetworkMode(network_mode)
  183. def start(self, service_names=None, **options):
  184. containers = []
  185. def start_service(service):
  186. service_containers = service.start(quiet=True, **options)
  187. containers.extend(service_containers)
  188. services = self.get_services(service_names)
  189. def get_deps(service):
  190. return {
  191. (self.get_service(dep), config)
  192. for dep, config in service.get_dependency_configs().items()
  193. }
  194. parallel.parallel_execute(
  195. services,
  196. start_service,
  197. operator.attrgetter('name'),
  198. 'Starting',
  199. get_deps)
  200. return containers
  201. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  202. containers = self.containers(service_names, one_off=one_off)
  203. def get_deps(container):
  204. # actually returning inversed dependencies
  205. return {(other, None) for other in containers
  206. if container.service in
  207. self.get_service(other.service).get_dependency_names()}
  208. parallel.parallel_execute(
  209. containers,
  210. self.build_container_operation_with_timeout_func('stop', options),
  211. operator.attrgetter('name'),
  212. 'Stopping',
  213. get_deps)
  214. def pause(self, service_names=None, **options):
  215. containers = self.containers(service_names)
  216. parallel.parallel_pause(reversed(containers), options)
  217. return containers
  218. def unpause(self, service_names=None, **options):
  219. containers = self.containers(service_names)
  220. parallel.parallel_unpause(containers, options)
  221. return containers
  222. def kill(self, service_names=None, **options):
  223. parallel.parallel_kill(self.containers(service_names), options)
  224. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  225. parallel.parallel_remove(self.containers(
  226. service_names, stopped=True, one_off=one_off
  227. ), options)
  228. def down(self, remove_image_type, include_volumes, remove_orphans=False):
  229. self.stop(one_off=OneOffFilter.include)
  230. self.find_orphan_containers(remove_orphans)
  231. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  232. self.networks.remove()
  233. if include_volumes:
  234. self.volumes.remove()
  235. self.remove_images(remove_image_type)
  236. def remove_images(self, remove_image_type):
  237. for service in self.get_services():
  238. service.remove_image(remove_image_type)
  239. def restart(self, service_names=None, **options):
  240. containers = self.containers(service_names, stopped=True)
  241. parallel.parallel_execute(
  242. containers,
  243. self.build_container_operation_with_timeout_func('restart', options),
  244. operator.attrgetter('name'),
  245. 'Restarting')
  246. return containers
  247. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  248. for service in self.get_services(service_names):
  249. if service.can_be_built():
  250. service.build(no_cache, pull, force_rm)
  251. else:
  252. log.info('%s uses an image, skipping' % service.name)
  253. def create(
  254. self,
  255. service_names=None,
  256. strategy=ConvergenceStrategy.changed,
  257. do_build=BuildAction.none,
  258. ):
  259. services = self.get_services_without_duplicate(service_names, include_deps=True)
  260. for svc in services:
  261. svc.ensure_image_exists(do_build=do_build)
  262. plans = self._get_convergence_plans(services, strategy)
  263. for service in services:
  264. service.execute_convergence_plan(
  265. plans[service.name],
  266. detached=True,
  267. start=False)
  268. def events(self, service_names=None):
  269. def build_container_event(event, container):
  270. time = datetime.datetime.fromtimestamp(event['time'])
  271. time = time.replace(
  272. microsecond=microseconds_from_time_nano(event['timeNano']))
  273. return {
  274. 'time': time,
  275. 'type': 'container',
  276. 'action': event['status'],
  277. 'id': container.id,
  278. 'service': container.service,
  279. 'attributes': {
  280. 'name': container.name,
  281. 'image': event['from'],
  282. },
  283. 'container': container,
  284. }
  285. service_names = set(service_names or self.service_names)
  286. for event in self.client.events(
  287. filters={'label': self.labels()},
  288. decode=True
  289. ):
  290. # The first part of this condition is a guard against some events
  291. # broadcasted by swarm that don't have a status field.
  292. # See https://github.com/docker/compose/issues/3316
  293. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  294. # We don't receive any image events because labels aren't applied
  295. # to images
  296. continue
  297. # TODO: get labels from the API v1.22 , see github issue 2618
  298. try:
  299. # this can fail if the conatiner has been removed
  300. container = Container.from_id(self.client, event['id'])
  301. except APIError:
  302. continue
  303. if container.service not in service_names:
  304. continue
  305. yield build_container_event(event, container)
  306. def up(self,
  307. service_names=None,
  308. start_deps=True,
  309. strategy=ConvergenceStrategy.changed,
  310. do_build=BuildAction.none,
  311. timeout=None,
  312. detached=False,
  313. remove_orphans=False):
  314. warn_for_swarm_mode(self.client)
  315. self.initialize()
  316. self.find_orphan_containers(remove_orphans)
  317. services = self.get_services_without_duplicate(
  318. service_names,
  319. include_deps=start_deps)
  320. for svc in services:
  321. svc.ensure_image_exists(do_build=do_build)
  322. plans = self._get_convergence_plans(services, strategy)
  323. def do(service):
  324. return service.execute_convergence_plan(
  325. plans[service.name],
  326. timeout=timeout,
  327. detached=detached
  328. )
  329. def get_deps(service):
  330. return {
  331. (self.get_service(dep), config)
  332. for dep, config in service.get_dependency_configs().items()
  333. }
  334. results, errors = parallel.parallel_execute(
  335. services,
  336. do,
  337. operator.attrgetter('name'),
  338. None,
  339. get_deps
  340. )
  341. if errors:
  342. raise ProjectError(
  343. 'Encountered errors while bringing up the project.'
  344. )
  345. return [
  346. container
  347. for svc_containers in results
  348. if svc_containers is not None
  349. for container in svc_containers
  350. ]
  351. def initialize(self):
  352. self.networks.initialize()
  353. self.volumes.initialize()
  354. def _get_convergence_plans(self, services, strategy):
  355. plans = {}
  356. for service in services:
  357. updated_dependencies = [
  358. name
  359. for name in service.get_dependency_names()
  360. if name in plans and
  361. plans[name].action in ('recreate', 'create')
  362. ]
  363. if updated_dependencies and strategy.allows_recreate:
  364. log.debug('%s has upstream changes (%s)',
  365. service.name,
  366. ", ".join(updated_dependencies))
  367. plan = service.convergence_plan(ConvergenceStrategy.always)
  368. else:
  369. plan = service.convergence_plan(strategy)
  370. plans[service.name] = plan
  371. return plans
  372. def pull(self, service_names=None, ignore_pull_failures=False):
  373. for service in self.get_services(service_names, include_deps=False):
  374. service.pull(ignore_pull_failures)
  375. def push(self, service_names=None, ignore_push_failures=False):
  376. for service in self.get_services(service_names, include_deps=False):
  377. service.push(ignore_push_failures)
  378. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  379. return list(filter(None, [
  380. Container.from_ps(self.client, container)
  381. for container in self.client.containers(
  382. all=stopped,
  383. filters={'label': self.labels(one_off=one_off)})])
  384. )
  385. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  386. if service_names:
  387. self.validate_service_names(service_names)
  388. else:
  389. service_names = self.service_names
  390. containers = self._labeled_containers(stopped, one_off)
  391. def matches_service_names(container):
  392. return container.labels.get(LABEL_SERVICE) in service_names
  393. return [c for c in containers if matches_service_names(c)]
  394. def find_orphan_containers(self, remove_orphans):
  395. def _find():
  396. containers = self._labeled_containers()
  397. for ctnr in containers:
  398. service_name = ctnr.labels.get(LABEL_SERVICE)
  399. if service_name not in self.service_names:
  400. yield ctnr
  401. orphans = list(_find())
  402. if not orphans:
  403. return
  404. if remove_orphans:
  405. for ctnr in orphans:
  406. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  407. ctnr.kill()
  408. ctnr.remove(force=True)
  409. else:
  410. log.warning(
  411. 'Found orphan containers ({0}) for this project. If '
  412. 'you removed or renamed this service in your compose '
  413. 'file, you can run this command with the '
  414. '--remove-orphans flag to clean it up.'.format(
  415. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  416. )
  417. )
  418. def _inject_deps(self, acc, service):
  419. dep_names = service.get_dependency_names()
  420. if len(dep_names) > 0:
  421. dep_services = self.get_services(
  422. service_names=list(set(dep_names)),
  423. include_deps=True
  424. )
  425. else:
  426. dep_services = []
  427. dep_services.append(service)
  428. return acc + dep_services
  429. def build_container_operation_with_timeout_func(self, operation, options):
  430. def container_operation_with_timeout(container):
  431. if options.get('timeout') is None:
  432. service = self.get_service(container.service)
  433. options['timeout'] = service.stop_timeout(None)
  434. return getattr(container, operation)(**options)
  435. return container_operation_with_timeout
  436. def get_volumes_from(project, service_dict):
  437. volumes_from = service_dict.pop('volumes_from', None)
  438. if not volumes_from:
  439. return []
  440. def build_volume_from(spec):
  441. if spec.type == 'service':
  442. try:
  443. return spec._replace(source=project.get_service(spec.source))
  444. except NoSuchService:
  445. pass
  446. if spec.type == 'container':
  447. try:
  448. container = Container.from_id(project.client, spec.source)
  449. return spec._replace(source=container)
  450. except APIError:
  451. pass
  452. raise ConfigurationError(
  453. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  454. "of a service or container.".format(
  455. service_dict['name'],
  456. spec.source))
  457. return [build_volume_from(vf) for vf in volumes_from]
  458. def warn_for_swarm_mode(client):
  459. info = client.info()
  460. if info.get('Swarm', {}).get('LocalNodeState') == 'active':
  461. if info.get('ServerVersion', '').startswith('ucp'):
  462. # UCP does multi-node scheduling with traditional Compose files.
  463. return
  464. log.warn(
  465. "The Docker Engine you're using is running in swarm mode.\n\n"
  466. "Compose does not use swarm mode to deploy services to multiple nodes in a swarm. "
  467. "All containers will be scheduled on the current node.\n\n"
  468. "To deploy your application across the swarm, "
  469. "use `docker stack deploy`.\n"
  470. )
  471. class NoSuchService(Exception):
  472. def __init__(self, name):
  473. self.name = name
  474. self.msg = "No such service: %s" % self.name
  475. def __str__(self):
  476. return self.msg
  477. class ProjectError(Exception):
  478. def __init__(self, msg):
  479. self.msg = msg