project.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. from functools import reduce
  5. from docker.errors import APIError
  6. from docker.errors import NotFound
  7. from . import parallel
  8. from .config import ConfigurationError
  9. from .config.sort_services import get_service_name_from_net
  10. from .const import DEFAULT_TIMEOUT
  11. from .const import LABEL_ONE_OFF
  12. from .const import LABEL_PROJECT
  13. from .const import LABEL_SERVICE
  14. from .container import Container
  15. from .service import ContainerNet
  16. from .service import ConvergenceStrategy
  17. from .service import Net
  18. from .service import Service
  19. from .service import ServiceNet
  20. log = logging.getLogger(__name__)
  21. class Project(object):
  22. """
  23. A collection of services.
  24. """
  25. def __init__(self, name, services, client, use_networking=False, network_driver=None):
  26. self.name = name
  27. self.services = services
  28. self.client = client
  29. self.use_networking = use_networking
  30. self.network_driver = network_driver
  31. def labels(self, one_off=False):
  32. return [
  33. '{0}={1}'.format(LABEL_PROJECT, self.name),
  34. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False"),
  35. ]
  36. @classmethod
  37. def from_dicts(cls, name, service_dicts, client, use_networking=False, network_driver=None):
  38. """
  39. Construct a ServiceCollection from a list of dicts representing services.
  40. """
  41. project = cls(name, [], client, use_networking=use_networking, network_driver=network_driver)
  42. if use_networking:
  43. remove_links(service_dicts)
  44. for service_dict in service_dicts:
  45. links = project.get_links(service_dict)
  46. volumes_from = project.get_volumes_from(service_dict)
  47. net = project.get_net(service_dict)
  48. project.services.append(
  49. Service(
  50. client=client,
  51. project=name,
  52. use_networking=use_networking,
  53. links=links,
  54. net=net,
  55. volumes_from=volumes_from,
  56. **service_dict))
  57. return project
  58. @property
  59. def service_names(self):
  60. return [service.name for service in self.services]
  61. def get_service(self, name):
  62. """
  63. Retrieve a service by name. Raises NoSuchService
  64. if the named service does not exist.
  65. """
  66. for service in self.services:
  67. if service.name == name:
  68. return service
  69. raise NoSuchService(name)
  70. def validate_service_names(self, service_names):
  71. """
  72. Validate that the given list of service names only contains valid
  73. services. Raises NoSuchService if one of the names is invalid.
  74. """
  75. valid_names = self.service_names
  76. for name in service_names:
  77. if name not in valid_names:
  78. raise NoSuchService(name)
  79. def get_services(self, service_names=None, include_deps=False):
  80. """
  81. Returns a list of this project's services filtered
  82. by the provided list of names, or all services if service_names is None
  83. or [].
  84. If include_deps is specified, returns a list including the dependencies for
  85. service_names, in order of dependency.
  86. Preserves the original order of self.services where possible,
  87. reordering as needed to resolve dependencies.
  88. Raises NoSuchService if any of the named services do not exist.
  89. """
  90. if service_names is None or len(service_names) == 0:
  91. return self.get_services(
  92. service_names=self.service_names,
  93. include_deps=include_deps
  94. )
  95. else:
  96. unsorted = [self.get_service(name) for name in service_names]
  97. services = [s for s in self.services if s in unsorted]
  98. if include_deps:
  99. services = reduce(self._inject_deps, services, [])
  100. uniques = []
  101. [uniques.append(s) for s in services if s not in uniques]
  102. return uniques
  103. def get_links(self, service_dict):
  104. links = []
  105. if 'links' in service_dict:
  106. for link in service_dict.get('links', []):
  107. if ':' in link:
  108. service_name, link_name = link.split(':', 1)
  109. else:
  110. service_name, link_name = link, None
  111. try:
  112. links.append((self.get_service(service_name), link_name))
  113. except NoSuchService:
  114. raise ConfigurationError(
  115. 'Service "%s" has a link to service "%s" which does not '
  116. 'exist.' % (service_dict['name'], service_name))
  117. del service_dict['links']
  118. return links
  119. def get_volumes_from(self, service_dict):
  120. volumes_from = []
  121. if 'volumes_from' in service_dict:
  122. for volume_from_spec in service_dict.get('volumes_from', []):
  123. # Get service
  124. try:
  125. service = self.get_service(volume_from_spec.source)
  126. volume_from_spec = volume_from_spec._replace(source=service)
  127. except NoSuchService:
  128. try:
  129. container = Container.from_id(self.client, volume_from_spec.source)
  130. volume_from_spec = volume_from_spec._replace(source=container)
  131. except APIError:
  132. raise ConfigurationError(
  133. 'Service "%s" mounts volumes from "%s", which is '
  134. 'not the name of a service or container.' % (
  135. service_dict['name'],
  136. volume_from_spec.source))
  137. volumes_from.append(volume_from_spec)
  138. del service_dict['volumes_from']
  139. return volumes_from
  140. def get_net(self, service_dict):
  141. net = service_dict.pop('net', None)
  142. if not net:
  143. if self.use_networking:
  144. return Net(self.name)
  145. return Net(None)
  146. net_name = get_service_name_from_net(net)
  147. if not net_name:
  148. return Net(net)
  149. try:
  150. return ServiceNet(self.get_service(net_name))
  151. except NoSuchService:
  152. pass
  153. try:
  154. return ContainerNet(Container.from_id(self.client, net_name))
  155. except APIError:
  156. raise ConfigurationError(
  157. 'Service "%s" is trying to use the network of "%s", '
  158. 'which is not the name of a service or container.' % (
  159. service_dict['name'],
  160. net_name))
  161. def start(self, service_names=None, **options):
  162. for service in self.get_services(service_names):
  163. service.start(**options)
  164. def stop(self, service_names=None, **options):
  165. parallel.parallel_stop(self.containers(service_names), options)
  166. def pause(self, service_names=None, **options):
  167. parallel.parallel_pause(reversed(self.containers(service_names)), options)
  168. def unpause(self, service_names=None, **options):
  169. parallel.parallel_unpause(self.containers(service_names), options)
  170. def kill(self, service_names=None, **options):
  171. parallel.parallel_kill(self.containers(service_names), options)
  172. def remove_stopped(self, service_names=None, **options):
  173. parallel.parallel_remove(self.containers(service_names, stopped=True), options)
  174. def restart(self, service_names=None, **options):
  175. parallel.parallel_restart(self.containers(service_names, stopped=True), options)
  176. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  177. for service in self.get_services(service_names):
  178. if service.can_be_built():
  179. service.build(no_cache, pull, force_rm)
  180. else:
  181. log.info('%s uses an image, skipping' % service.name)
  182. def up(self,
  183. service_names=None,
  184. start_deps=True,
  185. strategy=ConvergenceStrategy.changed,
  186. do_build=True,
  187. timeout=DEFAULT_TIMEOUT,
  188. detached=False):
  189. services = self.get_services(service_names, include_deps=start_deps)
  190. for service in services:
  191. service.remove_duplicate_containers()
  192. plans = self._get_convergence_plans(services, strategy)
  193. if self.use_networking and self.uses_default_network():
  194. self.ensure_network_exists()
  195. return [
  196. container
  197. for service in services
  198. for container in service.execute_convergence_plan(
  199. plans[service.name],
  200. do_build=do_build,
  201. timeout=timeout,
  202. detached=detached
  203. )
  204. ]
  205. def _get_convergence_plans(self, services, strategy):
  206. plans = {}
  207. for service in services:
  208. updated_dependencies = [
  209. name
  210. for name in service.get_dependency_names()
  211. if name in plans
  212. and plans[name].action in ('recreate', 'create')
  213. ]
  214. if updated_dependencies and strategy.allows_recreate:
  215. log.debug('%s has upstream changes (%s)',
  216. service.name,
  217. ", ".join(updated_dependencies))
  218. plan = service.convergence_plan(ConvergenceStrategy.always)
  219. else:
  220. plan = service.convergence_plan(strategy)
  221. plans[service.name] = plan
  222. return plans
  223. def pull(self, service_names=None, ignore_pull_failures=False):
  224. for service in self.get_services(service_names, include_deps=False):
  225. service.pull(ignore_pull_failures)
  226. def containers(self, service_names=None, stopped=False, one_off=False):
  227. if service_names:
  228. self.validate_service_names(service_names)
  229. else:
  230. service_names = self.service_names
  231. containers = list(filter(None, [
  232. Container.from_ps(self.client, container)
  233. for container in self.client.containers(
  234. all=stopped,
  235. filters={'label': self.labels(one_off=one_off)})]))
  236. def matches_service_names(container):
  237. return container.labels.get(LABEL_SERVICE) in service_names
  238. return [c for c in containers if matches_service_names(c)]
  239. def get_network(self):
  240. try:
  241. return self.client.inspect_network(self.name)
  242. except NotFound:
  243. return None
  244. def ensure_network_exists(self):
  245. # TODO: recreate network if driver has changed?
  246. if self.get_network() is None:
  247. driver_name = 'the default driver'
  248. if self.network_driver:
  249. driver_name = 'driver "{}"'.format(self.network_driver)
  250. log.info(
  251. 'Creating network "{}" with {}'
  252. .format(self.name, driver_name)
  253. )
  254. self.client.create_network(self.name, driver=self.network_driver)
  255. def remove_network(self):
  256. network = self.get_network()
  257. if network:
  258. self.client.remove_network(network['Id'])
  259. def uses_default_network(self):
  260. return any(service.net.mode == self.name for service in self.services)
  261. def _inject_deps(self, acc, service):
  262. dep_names = service.get_dependency_names()
  263. if len(dep_names) > 0:
  264. dep_services = self.get_services(
  265. service_names=list(set(dep_names)),
  266. include_deps=True
  267. )
  268. else:
  269. dep_services = []
  270. dep_services.append(service)
  271. return acc + dep_services
  272. def remove_links(service_dicts):
  273. services_with_links = [s for s in service_dicts if 'links' in s]
  274. if not services_with_links:
  275. return
  276. if len(services_with_links) == 1:
  277. prefix = '"{}" defines'.format(services_with_links[0]['name'])
  278. else:
  279. prefix = 'Some services ({}) define'.format(
  280. ", ".join('"{}"'.format(s['name']) for s in services_with_links))
  281. log.warn(
  282. '\n{} links, which are not compatible with Docker networking and will be ignored.\n'
  283. 'Future versions of Docker will not support links - you should remove them for '
  284. 'forwards-compatibility.\n'.format(prefix))
  285. for s in services_with_links:
  286. del s['links']
  287. class NoSuchService(Exception):
  288. def __init__(self, name):
  289. self.name = name
  290. self.msg = "No such service: %s" % self.name
  291. def __str__(self):
  292. return self.msg