plugin.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- test-case-name: twisted.test.test_plugin -*-
  2. # Copyright (c) 2005 Divmod, Inc.
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. Plugin system for Twisted.
  7. @author: Jp Calderone
  8. @author: Glyph Lefkowitz
  9. """
  10. import os
  11. import pickle
  12. import sys
  13. import types
  14. from typing import Iterable, Optional, Type, TypeVar
  15. from zope.interface import Interface, providedBy
  16. from twisted.python import log
  17. from twisted.python.components import getAdapterFactory
  18. from twisted.python.modules import getModule
  19. from twisted.python.reflect import namedAny
  20. class IPlugin(Interface):
  21. """
  22. Interface that must be implemented by all plugins.
  23. Only objects which implement this interface will be considered for return
  24. by C{getPlugins}. To be useful, plugins should also implement some other
  25. application-specific interface.
  26. """
  27. class CachedPlugin:
  28. def __init__(self, dropin, name, description, provided):
  29. self.dropin = dropin
  30. self.name = name
  31. self.description = description
  32. self.provided = provided
  33. self.dropin.plugins.append(self)
  34. def __repr__(self) -> str:
  35. return "<CachedPlugin {!r}/{!r} (provides {!r})>".format(
  36. self.name,
  37. self.dropin.moduleName,
  38. ", ".join([i.__name__ for i in self.provided]),
  39. )
  40. def load(self):
  41. return namedAny(self.dropin.moduleName + "." + self.name)
  42. def __conform__(self, interface, registry=None, default=None):
  43. for providedInterface in self.provided:
  44. if providedInterface.isOrExtends(interface):
  45. return self.load()
  46. if getAdapterFactory(providedInterface, interface, None) is not None:
  47. return interface(self.load(), default)
  48. return default
  49. # backwards compat HOORJ
  50. getComponent = __conform__
  51. class CachedDropin:
  52. """
  53. A collection of L{CachedPlugin} instances from a particular module in a
  54. plugin package.
  55. @type moduleName: C{str}
  56. @ivar moduleName: The fully qualified name of the plugin module this
  57. represents.
  58. @type description: C{str} or L{None}
  59. @ivar description: A brief explanation of this collection of plugins
  60. (probably the plugin module's docstring).
  61. @type plugins: C{list}
  62. @ivar plugins: The L{CachedPlugin} instances which were loaded from this
  63. dropin.
  64. """
  65. def __init__(self, moduleName, description):
  66. self.moduleName = moduleName
  67. self.description = description
  68. self.plugins = []
  69. def _generateCacheEntry(provider):
  70. dropin = CachedDropin(provider.__name__, provider.__doc__)
  71. for k, v in provider.__dict__.items():
  72. plugin = IPlugin(v, None)
  73. if plugin is not None:
  74. # Instantiated for its side-effects.
  75. CachedPlugin(dropin, k, v.__doc__, list(providedBy(plugin)))
  76. return dropin
  77. try:
  78. fromkeys = dict.fromkeys
  79. except AttributeError:
  80. def fromkeys(keys, value=None):
  81. d = {}
  82. for k in keys:
  83. d[k] = value
  84. return d
  85. def getCache(module):
  86. """
  87. Compute all the possible loadable plugins, while loading as few as
  88. possible and hitting the filesystem as little as possible.
  89. @param module: a Python module object. This represents a package to search
  90. for plugins.
  91. @return: a dictionary mapping module names to L{CachedDropin} instances.
  92. """
  93. allCachesCombined = {}
  94. mod = getModule(module.__name__)
  95. # don't want to walk deep, only immediate children.
  96. buckets = {}
  97. # Fill buckets with modules by related entry on the given package's
  98. # __path__. There's an abstraction inversion going on here, because this
  99. # information is already represented internally in twisted.python.modules,
  100. # but it's simple enough that I'm willing to live with it. If anyone else
  101. # wants to fix up this iteration so that it's one path segment at a time,
  102. # be my guest. --glyph
  103. for plugmod in mod.iterModules():
  104. fpp = plugmod.filePath.parent()
  105. if fpp not in buckets:
  106. buckets[fpp] = []
  107. bucket = buckets[fpp]
  108. bucket.append(plugmod)
  109. for pseudoPackagePath, bucket in buckets.items():
  110. dropinPath = pseudoPackagePath.child("dropin.cache")
  111. try:
  112. lastCached = dropinPath.getModificationTime()
  113. with dropinPath.open("r") as f:
  114. dropinDotCache = pickle.load(f)
  115. except BaseException:
  116. dropinDotCache = {}
  117. lastCached = 0
  118. needsWrite = False
  119. existingKeys = {}
  120. for pluginModule in bucket:
  121. pluginKey = pluginModule.name.split(".")[-1]
  122. existingKeys[pluginKey] = True
  123. if (pluginKey not in dropinDotCache) or (
  124. pluginModule.filePath.getModificationTime() >= lastCached
  125. ):
  126. needsWrite = True
  127. try:
  128. provider = pluginModule.load()
  129. except BaseException:
  130. # dropinDotCache.pop(pluginKey, None)
  131. log.err()
  132. else:
  133. entry = _generateCacheEntry(provider)
  134. dropinDotCache[pluginKey] = entry
  135. # Make sure that the cache doesn't contain any stale plugins.
  136. for pluginKey in list(dropinDotCache.keys()):
  137. if pluginKey not in existingKeys:
  138. del dropinDotCache[pluginKey]
  139. needsWrite = True
  140. if needsWrite:
  141. try:
  142. dropinPath.setContent(pickle.dumps(dropinDotCache))
  143. except OSError as e:
  144. log.msg(
  145. format=(
  146. "Unable to write to plugin cache %(path)s: error "
  147. "number %(errno)d"
  148. ),
  149. path=dropinPath.path,
  150. errno=e.errno,
  151. )
  152. except BaseException:
  153. log.err(None, "Unexpected error while writing cache file")
  154. allCachesCombined.update(dropinDotCache)
  155. return allCachesCombined
  156. def _pluginsPackage() -> types.ModuleType:
  157. import twisted.plugins as package
  158. return package
  159. _TInterface = TypeVar("_TInterface", bound=Interface)
  160. def getPlugins(
  161. interface: Type[_TInterface], package: Optional[types.ModuleType] = None
  162. ) -> Iterable[_TInterface]:
  163. """
  164. Retrieve all plugins implementing the given interface beneath the given module.
  165. @param interface: An interface class. Only plugins which implement this
  166. interface will be returned.
  167. @param package: A package beneath which plugins are installed. For
  168. most uses, the default value is correct.
  169. @return: An iterator of plugins.
  170. """
  171. if package is None:
  172. package = _pluginsPackage()
  173. allDropins = getCache(package)
  174. for key, dropin in allDropins.items():
  175. for plugin in dropin.plugins:
  176. try:
  177. adapted = interface(plugin, None)
  178. except BaseException:
  179. log.err()
  180. else:
  181. if adapted is not None:
  182. yield adapted
  183. # Old, backwards compatible name. Don't use this.
  184. getPlugIns = getPlugins
  185. def pluginPackagePaths(name):
  186. """
  187. Return a list of additional directories which should be searched for
  188. modules to be included as part of the named plugin package.
  189. @type name: C{str}
  190. @param name: The fully-qualified Python name of a plugin package, eg
  191. C{'twisted.plugins'}.
  192. @rtype: C{list} of C{str}
  193. @return: The absolute paths to other directories which may contain plugin
  194. modules for the named plugin package.
  195. """
  196. package = name.split(".")
  197. # Note that this may include directories which do not exist. It may be
  198. # preferable to remove such directories at this point, rather than allow
  199. # them to be searched later on.
  200. #
  201. # Note as well that only '__init__.py' will be considered to make a
  202. # directory a package (and thus exclude it from this list). This means
  203. # that if you create a master plugin package which has some other kind of
  204. # __init__ (eg, __init__.pyc) it will be incorrectly treated as a
  205. # supplementary plugin directory.
  206. return [
  207. os.path.abspath(os.path.join(x, *package))
  208. for x in sys.path
  209. if not os.path.exists(os.path.join(x, *package + ["__init__.py"]))
  210. ]
  211. __all__ = ["getPlugins", "pluginPackagePaths"]