project.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from functools import reduce
  4. import logging
  5. from docker.errors import APIError
  6. from .config import get_service_name_from_net, ConfigurationError
  7. from .const import DEFAULT_TIMEOUT, LABEL_PROJECT, LABEL_SERVICE, LABEL_ONE_OFF
  8. from .container import Container
  9. from .legacy import check_for_legacy_containers
  10. from .service import Service
  11. from .utils import parallel_execute
  12. log = logging.getLogger(__name__)
  13. def sort_service_dicts(services):
  14. # Topological sort (Cormen/Tarjan algorithm).
  15. unmarked = services[:]
  16. temporary_marked = set()
  17. sorted_services = []
  18. def get_service_names(links):
  19. return [link.split(':')[0] for link in links]
  20. def get_service_dependents(service_dict, services):
  21. name = service_dict['name']
  22. return [
  23. service for service in services
  24. if (name in get_service_names(service.get('links', [])) or
  25. name in service.get('volumes_from', []) or
  26. name == get_service_name_from_net(service.get('net')))
  27. ]
  28. def visit(n):
  29. if n['name'] in temporary_marked:
  30. if n['name'] in get_service_names(n.get('links', [])):
  31. raise DependencyError('A service can not link to itself: %s' % n['name'])
  32. if n['name'] in n.get('volumes_from', []):
  33. raise DependencyError('A service can not mount itself as volume: %s' % n['name'])
  34. else:
  35. raise DependencyError('Circular import between %s' % ' and '.join(temporary_marked))
  36. if n in unmarked:
  37. temporary_marked.add(n['name'])
  38. for m in get_service_dependents(n, services):
  39. visit(m)
  40. temporary_marked.remove(n['name'])
  41. unmarked.remove(n)
  42. sorted_services.insert(0, n)
  43. while unmarked:
  44. visit(unmarked[-1])
  45. return sorted_services
  46. class Project(object):
  47. """
  48. A collection of services.
  49. """
  50. def __init__(self, name, services, client):
  51. self.name = name
  52. self.services = services
  53. self.client = client
  54. def labels(self, one_off=False):
  55. return [
  56. '{0}={1}'.format(LABEL_PROJECT, self.name),
  57. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False"),
  58. ]
  59. @classmethod
  60. def from_dicts(cls, name, service_dicts, client):
  61. """
  62. Construct a ServiceCollection from a list of dicts representing services.
  63. """
  64. project = cls(name, [], client)
  65. for service_dict in sort_service_dicts(service_dicts):
  66. links = project.get_links(service_dict)
  67. volumes_from = project.get_volumes_from(service_dict)
  68. net = project.get_net(service_dict)
  69. project.services.append(Service(client=client, project=name, links=links, net=net,
  70. volumes_from=volumes_from, **service_dict))
  71. return project
  72. @property
  73. def service_names(self):
  74. return [service.name for service in self.services]
  75. def get_service(self, name):
  76. """
  77. Retrieve a service by name. Raises NoSuchService
  78. if the named service does not exist.
  79. """
  80. for service in self.services:
  81. if service.name == name:
  82. return service
  83. raise NoSuchService(name)
  84. def validate_service_names(self, service_names):
  85. """
  86. Validate that the given list of service names only contains valid
  87. services. Raises NoSuchService if one of the names is invalid.
  88. """
  89. valid_names = self.service_names
  90. for name in service_names:
  91. if name not in valid_names:
  92. raise NoSuchService(name)
  93. def get_services(self, service_names=None, include_deps=False):
  94. """
  95. Returns a list of this project's services filtered
  96. by the provided list of names, or all services if service_names is None
  97. or [].
  98. If include_deps is specified, returns a list including the dependencies for
  99. service_names, in order of dependency.
  100. Preserves the original order of self.services where possible,
  101. reordering as needed to resolve dependencies.
  102. Raises NoSuchService if any of the named services do not exist.
  103. """
  104. if service_names is None or len(service_names) == 0:
  105. return self.get_services(
  106. service_names=self.service_names,
  107. include_deps=include_deps
  108. )
  109. else:
  110. unsorted = [self.get_service(name) for name in service_names]
  111. services = [s for s in self.services if s in unsorted]
  112. if include_deps:
  113. services = reduce(self._inject_deps, services, [])
  114. uniques = []
  115. [uniques.append(s) for s in services if s not in uniques]
  116. return uniques
  117. def get_links(self, service_dict):
  118. links = []
  119. if 'links' in service_dict:
  120. for link in service_dict.get('links', []):
  121. if ':' in link:
  122. service_name, link_name = link.split(':', 1)
  123. else:
  124. service_name, link_name = link, None
  125. try:
  126. links.append((self.get_service(service_name), link_name))
  127. except NoSuchService:
  128. raise ConfigurationError('Service "%s" has a link to service "%s" which does not exist.' % (service_dict['name'], service_name))
  129. del service_dict['links']
  130. return links
  131. def get_volumes_from(self, service_dict):
  132. volumes_from = []
  133. if 'volumes_from' in service_dict:
  134. for volume_name in service_dict.get('volumes_from', []):
  135. try:
  136. service = self.get_service(volume_name)
  137. volumes_from.append(service)
  138. except NoSuchService:
  139. try:
  140. container = Container.from_id(self.client, volume_name)
  141. volumes_from.append(container)
  142. except APIError:
  143. raise ConfigurationError('Service "%s" mounts volumes from "%s", which is not the name of a service or container.' % (service_dict['name'], volume_name))
  144. del service_dict['volumes_from']
  145. return volumes_from
  146. def get_net(self, service_dict):
  147. if 'net' in service_dict:
  148. net_name = get_service_name_from_net(service_dict.get('net'))
  149. if net_name:
  150. try:
  151. net = self.get_service(net_name)
  152. except NoSuchService:
  153. try:
  154. net = Container.from_id(self.client, net_name)
  155. except APIError:
  156. raise ConfigurationError('Service "%s" is trying to use the network of "%s", which is not the name of a service or container.' % (service_dict['name'], net_name))
  157. else:
  158. net = service_dict['net']
  159. del service_dict['net']
  160. else:
  161. net = None
  162. return net
  163. def start(self, service_names=None, **options):
  164. for service in self.get_services(service_names):
  165. service.start(**options)
  166. def stop(self, service_names=None, **options):
  167. parallel_execute("stop", self.containers(service_names), "Stopping", "Stopped", **options)
  168. def kill(self, service_names=None, **options):
  169. parallel_execute("kill", self.containers(service_names), "Killing", "Killed", **options)
  170. def remove_stopped(self, service_names=None, **options):
  171. all_containers = self.containers(service_names, stopped=True)
  172. stopped_containers = [c for c in all_containers if not c.is_running]
  173. parallel_execute("remove", stopped_containers, "Removing", "Removed", **options)
  174. def restart(self, service_names=None, **options):
  175. for service in self.get_services(service_names):
  176. service.restart(**options)
  177. def build(self, service_names=None, no_cache=False):
  178. for service in self.get_services(service_names):
  179. if service.can_be_built():
  180. service.build(no_cache)
  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. allow_recreate=True,
  187. force_recreate=False,
  188. insecure_registry=False,
  189. do_build=True,
  190. timeout=DEFAULT_TIMEOUT):
  191. if force_recreate and not allow_recreate:
  192. raise ValueError("force_recreate and allow_recreate are in conflict")
  193. services = self.get_services(service_names, include_deps=start_deps)
  194. for service in services:
  195. service.remove_duplicate_containers()
  196. plans = self._get_convergence_plans(
  197. services,
  198. allow_recreate=allow_recreate,
  199. force_recreate=force_recreate,
  200. )
  201. return [
  202. container
  203. for service in services
  204. for container in service.execute_convergence_plan(
  205. plans[service.name],
  206. insecure_registry=insecure_registry,
  207. do_build=do_build,
  208. timeout=timeout
  209. )
  210. ]
  211. def _get_convergence_plans(self,
  212. services,
  213. allow_recreate=True,
  214. force_recreate=False):
  215. plans = {}
  216. for service in services:
  217. updated_dependencies = [
  218. name
  219. for name in service.get_dependency_names()
  220. if name in plans
  221. and plans[name].action == 'recreate'
  222. ]
  223. if updated_dependencies and allow_recreate:
  224. log.debug(
  225. '%s has upstream changes (%s)',
  226. service.name, ", ".join(updated_dependencies),
  227. )
  228. plan = service.convergence_plan(
  229. allow_recreate=allow_recreate,
  230. force_recreate=True,
  231. )
  232. else:
  233. plan = service.convergence_plan(
  234. allow_recreate=allow_recreate,
  235. force_recreate=force_recreate,
  236. )
  237. plans[service.name] = plan
  238. return plans
  239. def pull(self, service_names=None, insecure_registry=False):
  240. for service in self.get_services(service_names, include_deps=True):
  241. service.pull(insecure_registry=insecure_registry)
  242. def containers(self, service_names=None, stopped=False, one_off=False):
  243. if service_names:
  244. self.validate_service_names(service_names)
  245. else:
  246. service_names = self.service_names
  247. containers = [
  248. Container.from_ps(self.client, container)
  249. for container in self.client.containers(
  250. all=stopped,
  251. filters={'label': self.labels(one_off=one_off)})]
  252. def matches_service_names(container):
  253. return container.labels.get(LABEL_SERVICE) in service_names
  254. if not containers:
  255. check_for_legacy_containers(
  256. self.client,
  257. self.name,
  258. self.service_names,
  259. )
  260. return filter(matches_service_names, containers)
  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. class NoSuchService(Exception):
  273. def __init__(self, name):
  274. self.name = name
  275. self.msg = "No such service: %s" % self.name
  276. def __str__(self):
  277. return self.msg
  278. class DependencyError(ConfigurationError):
  279. pass