project.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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_services_without_duplicate(self, service_names=None, include_deps=False):
  104. services = self.get_services(service_names, include_deps)
  105. for service in services:
  106. service.remove_duplicate_containers()
  107. return services
  108. def get_links(self, service_dict):
  109. links = []
  110. if 'links' in service_dict:
  111. for link in service_dict.get('links', []):
  112. if ':' in link:
  113. service_name, link_name = link.split(':', 1)
  114. else:
  115. service_name, link_name = link, None
  116. try:
  117. links.append((self.get_service(service_name), link_name))
  118. except NoSuchService:
  119. raise ConfigurationError(
  120. 'Service "%s" has a link to service "%s" which does not '
  121. 'exist.' % (service_dict['name'], service_name))
  122. del service_dict['links']
  123. return links
  124. def get_volumes_from(self, service_dict):
  125. volumes_from = []
  126. if 'volumes_from' in service_dict:
  127. for volume_from_spec in service_dict.get('volumes_from', []):
  128. # Get service
  129. try:
  130. service = self.get_service(volume_from_spec.source)
  131. volume_from_spec = volume_from_spec._replace(source=service)
  132. except NoSuchService:
  133. try:
  134. container = Container.from_id(self.client, volume_from_spec.source)
  135. volume_from_spec = volume_from_spec._replace(source=container)
  136. except APIError:
  137. raise ConfigurationError(
  138. 'Service "%s" mounts volumes from "%s", which is '
  139. 'not the name of a service or container.' % (
  140. service_dict['name'],
  141. volume_from_spec.source))
  142. volumes_from.append(volume_from_spec)
  143. del service_dict['volumes_from']
  144. return volumes_from
  145. def get_net(self, service_dict):
  146. net = service_dict.pop('net', None)
  147. if not net:
  148. if self.use_networking:
  149. return Net(self.name)
  150. return Net(None)
  151. net_name = get_service_name_from_net(net)
  152. if not net_name:
  153. return Net(net)
  154. try:
  155. return ServiceNet(self.get_service(net_name))
  156. except NoSuchService:
  157. pass
  158. try:
  159. return ContainerNet(Container.from_id(self.client, net_name))
  160. except APIError:
  161. raise ConfigurationError(
  162. 'Service "%s" is trying to use the network of "%s", '
  163. 'which is not the name of a service or container.' % (
  164. service_dict['name'],
  165. net_name))
  166. def start(self, service_names=None, **options):
  167. containers = []
  168. for service in self.get_services(service_names):
  169. service_containers = service.start(**options)
  170. containers.extend(service_containers)
  171. return containers
  172. def stop(self, service_names=None, **options):
  173. parallel.parallel_stop(self.containers(service_names), options)
  174. def pause(self, service_names=None, **options):
  175. containers = self.containers(service_names)
  176. parallel.parallel_pause(reversed(containers), options)
  177. return containers
  178. def unpause(self, service_names=None, **options):
  179. containers = self.containers(service_names)
  180. parallel.parallel_unpause(containers, options)
  181. return containers
  182. def kill(self, service_names=None, **options):
  183. parallel.parallel_kill(self.containers(service_names), options)
  184. def remove_stopped(self, service_names=None, **options):
  185. parallel.parallel_remove(self.containers(service_names, stopped=True), options)
  186. def restart(self, service_names=None, **options):
  187. containers = self.containers(service_names, stopped=True)
  188. parallel.parallel_restart(containers, options)
  189. return containers
  190. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  191. for service in self.get_services(service_names):
  192. if service.can_be_built():
  193. service.build(no_cache, pull, force_rm)
  194. else:
  195. log.info('%s uses an image, skipping' % service.name)
  196. def create(self, service_names=None, strategy=ConvergenceStrategy.changed, do_build=True):
  197. services = self.get_services_without_duplicate(service_names, include_deps=True)
  198. plans = self._get_convergence_plans(services, strategy)
  199. for service in services:
  200. service.execute_convergence_plan(plans[service.name], do_build, detached=True, start=False)
  201. def up(self,
  202. service_names=None,
  203. start_deps=True,
  204. strategy=ConvergenceStrategy.changed,
  205. do_build=True,
  206. timeout=DEFAULT_TIMEOUT,
  207. detached=False):
  208. services = self.get_services_without_duplicate(service_names, include_deps=start_deps)
  209. plans = self._get_convergence_plans(services, strategy)
  210. if self.use_networking and self.uses_default_network():
  211. self.ensure_network_exists()
  212. return [
  213. container
  214. for service in services
  215. for container in service.execute_convergence_plan(
  216. plans[service.name],
  217. do_build=do_build,
  218. timeout=timeout,
  219. detached=detached
  220. )
  221. ]
  222. def _get_convergence_plans(self, services, strategy):
  223. plans = {}
  224. for service in services:
  225. updated_dependencies = [
  226. name
  227. for name in service.get_dependency_names()
  228. if name in plans
  229. and plans[name].action in ('recreate', 'create')
  230. ]
  231. if updated_dependencies and strategy.allows_recreate:
  232. log.debug('%s has upstream changes (%s)',
  233. service.name,
  234. ", ".join(updated_dependencies))
  235. plan = service.convergence_plan(ConvergenceStrategy.always)
  236. else:
  237. plan = service.convergence_plan(strategy)
  238. plans[service.name] = plan
  239. return plans
  240. def pull(self, service_names=None, ignore_pull_failures=False):
  241. for service in self.get_services(service_names, include_deps=False):
  242. service.pull(ignore_pull_failures)
  243. def containers(self, service_names=None, stopped=False, one_off=False):
  244. if service_names:
  245. self.validate_service_names(service_names)
  246. else:
  247. service_names = self.service_names
  248. containers = list(filter(None, [
  249. Container.from_ps(self.client, container)
  250. for container in self.client.containers(
  251. all=stopped,
  252. filters={'label': self.labels(one_off=one_off)})]))
  253. def matches_service_names(container):
  254. return container.labels.get(LABEL_SERVICE) in service_names
  255. return [c for c in containers if matches_service_names(c)]
  256. def get_network(self):
  257. try:
  258. return self.client.inspect_network(self.name)
  259. except NotFound:
  260. return None
  261. def ensure_network_exists(self):
  262. # TODO: recreate network if driver has changed?
  263. if self.get_network() is None:
  264. driver_name = 'the default driver'
  265. if self.network_driver:
  266. driver_name = 'driver "{}"'.format(self.network_driver)
  267. log.info(
  268. 'Creating network "{}" with {}'
  269. .format(self.name, driver_name)
  270. )
  271. self.client.create_network(self.name, driver=self.network_driver)
  272. def remove_network(self):
  273. network = self.get_network()
  274. if network:
  275. self.client.remove_network(network['Id'])
  276. def uses_default_network(self):
  277. return any(service.net.mode == self.name for service in self.services)
  278. def _inject_deps(self, acc, service):
  279. dep_names = service.get_dependency_names()
  280. if len(dep_names) > 0:
  281. dep_services = self.get_services(
  282. service_names=list(set(dep_names)),
  283. include_deps=True
  284. )
  285. else:
  286. dep_services = []
  287. dep_services.append(service)
  288. return acc + dep_services
  289. def remove_links(service_dicts):
  290. services_with_links = [s for s in service_dicts if 'links' in s]
  291. if not services_with_links:
  292. return
  293. if len(services_with_links) == 1:
  294. prefix = '"{}" defines'.format(services_with_links[0]['name'])
  295. else:
  296. prefix = 'Some services ({}) define'.format(
  297. ", ".join('"{}"'.format(s['name']) for s in services_with_links))
  298. log.warn(
  299. '\n{} links, which are not compatible with Docker networking and will be ignored.\n'
  300. 'Future versions of Docker will not support links - you should remove them for '
  301. 'forwards-compatibility.\n'.format(prefix))
  302. for s in services_with_links:
  303. del s['links']
  304. class NoSuchService(Exception):
  305. def __init__(self, name):
  306. self.name = name
  307. self.msg = "No such service: %s" % self.name
  308. def __str__(self):
  309. return self.msg