project.py 15 KB

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