reactors.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- test-case-name: twisted.test.test_application -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Plugin-based system for enumerating available reactors and installing one of
  6. them.
  7. """
  8. from __future__ import absolute_import, division
  9. from zope.interface import Interface, Attribute, implementer
  10. from twisted.plugin import IPlugin, getPlugins
  11. from twisted.python.reflect import namedAny
  12. class IReactorInstaller(Interface):
  13. """
  14. Definition of a reactor which can probably be installed.
  15. """
  16. shortName = Attribute("""
  17. A brief string giving the user-facing name of this reactor.
  18. """)
  19. description = Attribute("""
  20. A longer string giving a user-facing description of this reactor.
  21. """)
  22. def install():
  23. """
  24. Install this reactor.
  25. """
  26. # TODO - A method which provides a best-guess as to whether this reactor
  27. # can actually be used in the execution environment.
  28. class NoSuchReactor(KeyError):
  29. """
  30. Raised when an attempt is made to install a reactor which cannot be found.
  31. """
  32. @implementer(IPlugin, IReactorInstaller)
  33. class Reactor(object):
  34. """
  35. @ivar moduleName: The fully-qualified Python name of the module of which
  36. the install callable is an attribute.
  37. """
  38. def __init__(self, shortName, moduleName, description):
  39. self.shortName = shortName
  40. self.moduleName = moduleName
  41. self.description = description
  42. def install(self):
  43. namedAny(self.moduleName).install()
  44. def getReactorTypes():
  45. """
  46. Return an iterator of L{IReactorInstaller} plugins.
  47. """
  48. return getPlugins(IReactorInstaller)
  49. def installReactor(shortName):
  50. """
  51. Install the reactor with the given C{shortName} attribute.
  52. @raise NoSuchReactor: If no reactor is found with a matching C{shortName}.
  53. @raise: anything that the specified reactor can raise when installed.
  54. """
  55. for installer in getReactorTypes():
  56. if installer.shortName == shortName:
  57. installer.install()
  58. from twisted.internet import reactor
  59. return reactor
  60. raise NoSuchReactor(shortName)