project.py 15 KB

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