project.py 12 KB

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