project.py 14 KB

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