project.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import datetime
  4. import logging
  5. from functools import reduce
  6. from docker.errors import APIError
  7. from . import parallel
  8. from .config import ConfigurationError
  9. from .config.config import V1
  10. from .config.sort_services import get_container_name_from_network_mode
  11. from .config.sort_services import get_service_name_from_network_mode
  12. from .const import DEFAULT_TIMEOUT
  13. from .const import IMAGE_EVENTS
  14. from .const import LABEL_ONE_OFF
  15. from .const import LABEL_PROJECT
  16. from .const import LABEL_SERVICE
  17. from .container import Container
  18. from .network import build_networks
  19. from .network import get_networks
  20. from .network import ProjectNetworks
  21. from .service import ContainerNetworkMode
  22. from .service import ConvergenceStrategy
  23. from .service import NetworkMode
  24. from .service import Service
  25. from .service import ServiceNetworkMode
  26. from .utils import microseconds_from_time_nano
  27. from .volume import ProjectVolumes
  28. log = logging.getLogger(__name__)
  29. class Project(object):
  30. """
  31. A collection of services.
  32. """
  33. def __init__(self, name, services, client, networks=None, volumes=None):
  34. self.name = name
  35. self.services = services
  36. self.client = client
  37. self.volumes = volumes or ProjectVolumes({})
  38. self.networks = networks or ProjectNetworks({}, False)
  39. def labels(self, one_off=False):
  40. return [
  41. '{0}={1}'.format(LABEL_PROJECT, self.name),
  42. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False"),
  43. ]
  44. @classmethod
  45. def from_config(cls, name, config_data, client):
  46. """
  47. Construct a Project from a config.Config object.
  48. """
  49. use_networking = (config_data.version and config_data.version != V1)
  50. networks = build_networks(name, config_data, client)
  51. project_networks = ProjectNetworks.from_services(
  52. config_data.services,
  53. networks,
  54. use_networking)
  55. volumes = ProjectVolumes.from_config(name, config_data, client)
  56. project = cls(name, [], client, project_networks, volumes)
  57. for service_dict in config_data.services:
  58. service_dict = dict(service_dict)
  59. if use_networking:
  60. service_networks = get_networks(service_dict, networks)
  61. else:
  62. service_networks = {}
  63. service_dict.pop('networks', None)
  64. links = project.get_links(service_dict)
  65. network_mode = project.get_network_mode(service_dict, service_networks.keys())
  66. volumes_from = get_volumes_from(project, service_dict)
  67. if config_data.version != V1:
  68. service_dict['volumes'] = [
  69. volumes.namespace_spec(volume_spec)
  70. for volume_spec in service_dict.get('volumes', [])
  71. ]
  72. project.services.append(
  73. Service(
  74. service_dict.pop('name'),
  75. client=client,
  76. project=name,
  77. use_networking=use_networking,
  78. networks=service_networks,
  79. links=links,
  80. network_mode=network_mode,
  81. volumes_from=volumes_from,
  82. **service_dict)
  83. )
  84. return project
  85. @property
  86. def service_names(self):
  87. return [service.name for service in self.services]
  88. def get_service(self, name):
  89. """
  90. Retrieve a service by name. Raises NoSuchService
  91. if the named service does not exist.
  92. """
  93. for service in self.services:
  94. if service.name == name:
  95. return service
  96. raise NoSuchService(name)
  97. def validate_service_names(self, service_names):
  98. """
  99. Validate that the given list of service names only contains valid
  100. services. Raises NoSuchService if one of the names is invalid.
  101. """
  102. valid_names = self.service_names
  103. for name in service_names:
  104. if name not in valid_names:
  105. raise NoSuchService(name)
  106. def get_services(self, service_names=None, include_deps=False):
  107. """
  108. Returns a list of this project's services filtered
  109. by the provided list of names, or all services if service_names is None
  110. or [].
  111. If include_deps is specified, returns a list including the dependencies for
  112. service_names, in order of dependency.
  113. Preserves the original order of self.services where possible,
  114. reordering as needed to resolve dependencies.
  115. Raises NoSuchService if any of the named services do not exist.
  116. """
  117. if service_names is None or len(service_names) == 0:
  118. service_names = self.service_names
  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_services_without_duplicate(self, service_names=None, include_deps=False):
  127. services = self.get_services(service_names, include_deps)
  128. for service in services:
  129. service.remove_duplicate_containers()
  130. return services
  131. def get_links(self, service_dict):
  132. links = []
  133. if 'links' in service_dict:
  134. for link in service_dict.get('links', []):
  135. if ':' in link:
  136. service_name, link_name = link.split(':', 1)
  137. else:
  138. service_name, link_name = link, None
  139. try:
  140. links.append((self.get_service(service_name), link_name))
  141. except NoSuchService:
  142. raise ConfigurationError(
  143. 'Service "%s" has a link to service "%s" which does not '
  144. 'exist.' % (service_dict['name'], service_name))
  145. del service_dict['links']
  146. return links
  147. def get_network_mode(self, service_dict, networks):
  148. network_mode = service_dict.pop('network_mode', None)
  149. if not network_mode:
  150. if self.networks.use_networking:
  151. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  152. return NetworkMode(None)
  153. service_name = get_service_name_from_network_mode(network_mode)
  154. if service_name:
  155. return ServiceNetworkMode(self.get_service(service_name))
  156. container_name = get_container_name_from_network_mode(network_mode)
  157. if container_name:
  158. try:
  159. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  160. except APIError:
  161. raise ConfigurationError(
  162. "Service '{name}' uses the network stack of container '{dep}' which "
  163. "does not exist.".format(name=service_dict['name'], dep=container_name))
  164. return NetworkMode(network_mode)
  165. def start(self, service_names=None, **options):
  166. containers = []
  167. for service in self.get_services(service_names):
  168. service_containers = service.start(**options)
  169. containers.extend(service_containers)
  170. return containers
  171. def stop(self, service_names=None, **options):
  172. parallel.parallel_stop(self.containers(service_names), options)
  173. def pause(self, service_names=None, **options):
  174. containers = self.containers(service_names)
  175. parallel.parallel_pause(reversed(containers), options)
  176. return containers
  177. def unpause(self, service_names=None, **options):
  178. containers = self.containers(service_names)
  179. parallel.parallel_unpause(containers, options)
  180. return containers
  181. def kill(self, service_names=None, **options):
  182. parallel.parallel_kill(self.containers(service_names), options)
  183. def remove_stopped(self, service_names=None, **options):
  184. parallel.parallel_remove(self.containers(service_names, stopped=True), options)
  185. def down(self, remove_image_type, include_volumes):
  186. self.stop()
  187. self.remove_stopped(v=include_volumes)
  188. self.networks.remove()
  189. if include_volumes:
  190. self.volumes.remove()
  191. self.remove_images(remove_image_type)
  192. def remove_images(self, remove_image_type):
  193. for service in self.get_services():
  194. service.remove_image(remove_image_type)
  195. def restart(self, service_names=None, **options):
  196. containers = self.containers(service_names, stopped=True)
  197. parallel.parallel_restart(containers, options)
  198. return containers
  199. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  200. for service in self.get_services(service_names):
  201. if service.can_be_built():
  202. service.build(no_cache, pull, force_rm)
  203. else:
  204. log.info('%s uses an image, skipping' % service.name)
  205. def create(self, service_names=None, strategy=ConvergenceStrategy.changed, do_build=True):
  206. services = self.get_services_without_duplicate(service_names, include_deps=True)
  207. plans = self._get_convergence_plans(services, strategy)
  208. for service in services:
  209. service.execute_convergence_plan(
  210. plans[service.name],
  211. do_build,
  212. detached=True,
  213. start=False)
  214. def events(self):
  215. def build_container_event(event, container):
  216. time = datetime.datetime.fromtimestamp(event['time'])
  217. time = time.replace(
  218. microsecond=microseconds_from_time_nano(event['timeNano']))
  219. return {
  220. 'time': time,
  221. 'type': 'container',
  222. 'action': event['status'],
  223. 'id': container.id,
  224. 'service': container.service,
  225. 'attributes': {
  226. 'name': container.name,
  227. 'image': event['from'],
  228. }
  229. }
  230. service_names = set(self.service_names)
  231. for event in self.client.events(
  232. filters={'label': self.labels()},
  233. decode=True
  234. ):
  235. if event['status'] in IMAGE_EVENTS:
  236. # We don't receive any image events because labels aren't applied
  237. # to images
  238. continue
  239. # TODO: get labels from the API v1.22 , see github issue 2618
  240. container = Container.from_id(self.client, event['id'])
  241. if container.service not in service_names:
  242. continue
  243. yield build_container_event(event, container)
  244. def up(self,
  245. service_names=None,
  246. start_deps=True,
  247. strategy=ConvergenceStrategy.changed,
  248. do_build=True,
  249. timeout=DEFAULT_TIMEOUT,
  250. detached=False):
  251. self.initialize()
  252. services = self.get_services_without_duplicate(
  253. service_names,
  254. include_deps=start_deps)
  255. plans = self._get_convergence_plans(services, strategy)
  256. return [
  257. container
  258. for service in services
  259. for container in service.execute_convergence_plan(
  260. plans[service.name],
  261. do_build=do_build,
  262. timeout=timeout,
  263. detached=detached
  264. )
  265. ]
  266. def initialize(self):
  267. self.networks.initialize()
  268. self.volumes.initialize()
  269. def _get_convergence_plans(self, services, strategy):
  270. plans = {}
  271. for service in services:
  272. updated_dependencies = [
  273. name
  274. for name in service.get_dependency_names()
  275. if name in plans and
  276. plans[name].action in ('recreate', 'create')
  277. ]
  278. if updated_dependencies and strategy.allows_recreate:
  279. log.debug('%s has upstream changes (%s)',
  280. service.name,
  281. ", ".join(updated_dependencies))
  282. plan = service.convergence_plan(ConvergenceStrategy.always)
  283. else:
  284. plan = service.convergence_plan(strategy)
  285. plans[service.name] = plan
  286. return plans
  287. def pull(self, service_names=None, ignore_pull_failures=False):
  288. for service in self.get_services(service_names, include_deps=False):
  289. service.pull(ignore_pull_failures)
  290. def containers(self, service_names=None, stopped=False, one_off=False):
  291. if service_names:
  292. self.validate_service_names(service_names)
  293. else:
  294. service_names = self.service_names
  295. containers = list(filter(None, [
  296. Container.from_ps(self.client, container)
  297. for container in self.client.containers(
  298. all=stopped,
  299. filters={'label': self.labels(one_off=one_off)})]))
  300. def matches_service_names(container):
  301. return container.labels.get(LABEL_SERVICE) in service_names
  302. return [c for c in containers if matches_service_names(c)]
  303. def _inject_deps(self, acc, service):
  304. dep_names = service.get_dependency_names()
  305. if len(dep_names) > 0:
  306. dep_services = self.get_services(
  307. service_names=list(set(dep_names)),
  308. include_deps=True
  309. )
  310. else:
  311. dep_services = []
  312. dep_services.append(service)
  313. return acc + dep_services
  314. def get_volumes_from(project, service_dict):
  315. volumes_from = service_dict.pop('volumes_from', None)
  316. if not volumes_from:
  317. return []
  318. def build_volume_from(spec):
  319. if spec.type == 'service':
  320. try:
  321. return spec._replace(source=project.get_service(spec.source))
  322. except NoSuchService:
  323. pass
  324. if spec.type == 'container':
  325. try:
  326. container = Container.from_id(project.client, spec.source)
  327. return spec._replace(source=container)
  328. except APIError:
  329. pass
  330. raise ConfigurationError(
  331. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  332. "of a service or container.".format(
  333. service_dict['name'],
  334. spec.source))
  335. return [build_volume_from(vf) for vf in volumes_from]
  336. class NoSuchService(Exception):
  337. def __init__(self, name):
  338. self.name = name
  339. self.msg = "No such service: %s" % self.name
  340. def __str__(self):
  341. return self.msg