1
0

project.py 12 KB

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