Fix & Docs: Plugins may only have one mixin implementation
Multiple mixins are allowed of course. Allowing multiple implementations lead to too many problems due to plugin names for referring to the APIs of SimpleApiPlugins or the assets of AssetPlugins. Hence __plugin_implementations__ has been deprecated in favor of __plugin_implementation__. The plugin subsystem will automatically copy the first implementation from __plugin_implementations__ to __plugin_implementation__ and log a deprecation warning. Adjusted documentation accordingly. Also added docs for helpers.
This commit is contained in:
1 parent
79336ca108
commit
8ff0096eb6
24 files changed
+404
-146
No files matched your search
@@ -164,16 +164,16 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
kwargs = dict()
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
for name, plugin in plugins.items():
|
||||
for plugin in plugins:
|
||||
if hasattr(plugin, method):
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % name)
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
|
||||
if error_callback:
|
||||
error_callback(name, plugin, exc)
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
|
||||
class PluginSettings(object):
|
||||
|
||||
+193
-58
@@ -70,8 +70,20 @@ class PluginInfo(object):
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
""" Module attribute from which to retrieve the plugin's provided hooks. """
|
||||
|
||||
attr_implementation = '__plugin_implementation__'
|
||||
""" Module attribute from which to retrieve the plugin's provided mixin implementation. """
|
||||
|
||||
attr_implementations = '__plugin_implementations__'
|
||||
""" Module attribute from which to retrieve the plugin's provided implementations. """
|
||||
"""
|
||||
Module attribute from which to retrieve the plugin's provided implementations.
|
||||
|
||||
This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the
|
||||
first entry will be evaluated.
|
||||
|
||||
.. deprecated:: 1.2.0-dev-694
|
||||
|
||||
Use :attr:`attr_implementation` instead.
|
||||
"""
|
||||
|
||||
attr_helpers = '__plugin_helpers__'
|
||||
""" Module attribute from which to retrieve the plugin's provided helpers. """
|
||||
@@ -97,6 +109,25 @@ class PluginInfo(object):
|
||||
self._url = url
|
||||
self._license = license
|
||||
|
||||
self._validate()
|
||||
|
||||
def _validate(self):
|
||||
# if the plugin still uses __plugin_implementations__, log a deprecation warning and put the first
|
||||
# item into __plugin_implementation__
|
||||
if hasattr(self.instance, self.__class__.attr_implementations):
|
||||
if not hasattr(self.instance, self.__class__.attr_implementation):
|
||||
# deprecation warning
|
||||
import warnings
|
||||
warnings.warn("{name} uses deprecated control property __plugin_implementations__, use __plugin_implementation__ instead - only the first implementation of {name} will be recognized".format(name=self.key), DeprecationWarning)
|
||||
|
||||
# put first item into __plugin_implementation__
|
||||
implementations = getattr(self.instance, self.__class__.attr_implementations)
|
||||
if len(implementations) > 0:
|
||||
setattr(self.instance, self.__class__.attr_implementation, implementations[0])
|
||||
|
||||
# delete __plugin_implementations__
|
||||
delattr(self.instance, self.__class__.attr_implementations)
|
||||
|
||||
def __str__(self):
|
||||
if self.version:
|
||||
return "{name} ({version})".format(name=self.name, version=self.version)
|
||||
@@ -134,24 +165,23 @@ class PluginInfo(object):
|
||||
return None
|
||||
return self.hooks[hook]
|
||||
|
||||
def get_implementations(self, *types):
|
||||
def get_implementation(self, *types):
|
||||
"""
|
||||
Arguments:
|
||||
types (list): List of :class:`Plugin` sub classes all returned implementations need to implement.
|
||||
|
||||
Returns:
|
||||
~__builtin__.set: The plugin's implementations matching all of the requested ``types``. Might be empty.
|
||||
object: The plugin's implementation if it matches all of the requested ``types``, None otherwise.
|
||||
"""
|
||||
|
||||
result = set()
|
||||
for implementation in self.implementations:
|
||||
matches_all = True
|
||||
for type in types:
|
||||
if not isinstance(implementation, type):
|
||||
matches_all = False
|
||||
if matches_all:
|
||||
result.add(implementation)
|
||||
return result
|
||||
if not self.implementation:
|
||||
return None
|
||||
|
||||
for t in types:
|
||||
if not isinstance(self.implementation, t):
|
||||
return None
|
||||
|
||||
return self.implementation
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -232,7 +262,7 @@ class PluginInfo(object):
|
||||
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
|
||||
|
||||
@property
|
||||
def implementations(self):
|
||||
def implementation(self):
|
||||
"""
|
||||
Implementations provided by the plugin. Will be taken from the implementations attribute of the plugin module
|
||||
as defined in :attr:`attr_implementations` if available, otherwise an empty list is returned.
|
||||
@@ -240,7 +270,7 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
list: Implementations provided by the plugin.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_implementations, default=[])
|
||||
return self._get_instance_attribute(self.__class__.attr_implementation, default=None)
|
||||
|
||||
@property
|
||||
def helpers(self):
|
||||
@@ -310,7 +340,7 @@ class PluginManager(object):
|
||||
|
||||
self.plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(set)
|
||||
self.plugin_implementations = dict()
|
||||
self.plugin_implementations_by_type = defaultdict(list)
|
||||
|
||||
self.disabled_plugins = dict()
|
||||
@@ -460,12 +490,13 @@ class PluginManager(object):
|
||||
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
implementation = plugin.get_implementation(plugin_type)
|
||||
if implementation is not None:
|
||||
self.plugin_implementations_by_type[plugin_type].append((name, implementation))
|
||||
|
||||
plugin_implementations = plugin.get_implementations()
|
||||
if len(plugin_implementations):
|
||||
self.plugin_implementations[name].update(plugin_implementations)
|
||||
plugin_implementation = plugin.get_implementation()
|
||||
if plugin_implementation is not None:
|
||||
self.plugin_implementations[name] = plugin_implementation
|
||||
except:
|
||||
self.logger.exception("There was an error loading plugin %s" % name)
|
||||
|
||||
@@ -474,7 +505,7 @@ class PluginManager(object):
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format(
|
||||
count=len(self.plugins) + len(self.disabled_plugins),
|
||||
implementations=sum(map(lambda x: len(x), self.plugin_implementations.values())),
|
||||
implementations=len(self.plugin_implementations),
|
||||
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
|
||||
))
|
||||
|
||||
@@ -484,40 +515,40 @@ class PluginManager(object):
|
||||
if additional_inject_factories is None:
|
||||
additional_inject_factories = []
|
||||
|
||||
for name, implementations in self.plugin_implementations.items():
|
||||
for name, implementation in self.plugin_implementations.items():
|
||||
plugin = self.plugins[name]
|
||||
for implementation in implementations:
|
||||
try:
|
||||
kwargs = dict(additional_injects)
|
||||
try:
|
||||
kwargs = dict(additional_injects)
|
||||
|
||||
kwargs.update(dict(
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
kwargs.update(dict(
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
|
||||
# inject the additional_injects
|
||||
for arg, value in kwargs.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
# inject the additional_injects
|
||||
for arg, value in kwargs.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
# inject any injects produced in the additional_inject_factories
|
||||
for factory in additional_inject_factories:
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
for arg, value in return_value.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
# inject any injects produced in the additional_inject_factories
|
||||
for factory in additional_inject_factories:
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
for arg, value in return_value.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
implementation.initialize()
|
||||
except:
|
||||
self.logger.exception("Exception while initializing plugin")
|
||||
# TODO disable plugin!
|
||||
# allow implementations to be disabled here if False is returned
|
||||
implementation.initialize()
|
||||
except:
|
||||
self.logger.exception("Exception while initializing plugin")
|
||||
# TODO disable plugin!
|
||||
|
||||
self.logger.debug("Initialized {count} plugin mixin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
@@ -539,17 +570,72 @@ class PluginManager(object):
|
||||
)
|
||||
)))
|
||||
|
||||
def get_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
return self.plugins[name].instance
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
"""
|
||||
Retrieves the module of the plugin identified by ``identifier``. If the plugin is not registered or disabled and
|
||||
``required_enabled`` is True (the default) None will be returned.
|
||||
|
||||
Arguments:
|
||||
identifier (str): The identifier of the plugin to retrieve.
|
||||
require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's
|
||||
disabled.
|
||||
|
||||
Returns:
|
||||
module: The requested plugin module or None
|
||||
"""
|
||||
|
||||
plugin_info = self.get_plugin_info(identifier, require_enabled=require_enabled)
|
||||
if plugin_info is not None:
|
||||
return plugin_info.instance
|
||||
return None
|
||||
|
||||
def get_plugin_info(self, identifier, require_enabled=True):
|
||||
"""
|
||||
Retrieves the :class:`PluginInfo` instance identified by ``identifier``. If the plugin is not registered or
|
||||
disabled and ``required_enabled`` is True (the default) None will be returned.
|
||||
|
||||
Arguments:
|
||||
identifier (str): The identifier of the plugin to retrieve.
|
||||
require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's
|
||||
disabled.
|
||||
|
||||
Returns:
|
||||
~.PluginInfo: The requested :class:`PluginInfo` or None
|
||||
"""
|
||||
|
||||
if identifier in self.plugins:
|
||||
return self.plugins[identifier]
|
||||
elif not require_enabled and identifier in self.disabled_plugins:
|
||||
return self.disabled_plugins[identifier]
|
||||
|
||||
return None
|
||||
|
||||
def get_hooks(self, hook):
|
||||
"""
|
||||
Retrieves all registered handlers for the specified hook.
|
||||
|
||||
Arguments:
|
||||
hook (str): The hook for which to retrieve the handlers.
|
||||
|
||||
Returns:
|
||||
dict: A dict containing all registered handlers mapped by their plugin's identifier.
|
||||
"""
|
||||
|
||||
if not hook in self.plugin_hooks:
|
||||
return dict()
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
"""
|
||||
Get all mixin implementations that implement *all* of the provided ``types``.
|
||||
|
||||
Arguments:
|
||||
types (one or more type): The types a mixin implementation needs to implement in order to be returned.
|
||||
|
||||
Returns:
|
||||
list: A list of all found implementations
|
||||
"""
|
||||
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
@@ -561,9 +647,40 @@ class PluginManager(object):
|
||||
|
||||
if result is None:
|
||||
return dict()
|
||||
return {impl[0]: impl[1] for impl in result}
|
||||
return [impl[1] for impl in result]
|
||||
|
||||
def get_filtered_implementations(self, f, *types):
|
||||
"""
|
||||
Get all mixin implementation that implementat *all* of the provided ``types`` and match the provided filter `f`.
|
||||
|
||||
Arguments:
|
||||
f (callable): A filter function returning True for implementations to return and False for those to exclude.
|
||||
types (one or more type): The types a mixin implementation needs to implement in order to be returned.
|
||||
|
||||
Returns:
|
||||
list: A list of all found and matching implementations.
|
||||
"""
|
||||
|
||||
assert callable(f)
|
||||
implementations = self.get_implementations(*types)
|
||||
return filter(f, implementations)
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
"""
|
||||
Retrieves the named ``helpers`` for the plugin with identifier ``name``.
|
||||
|
||||
If the plugin is not available, returns None. Otherwise returns a :class:`dict` with the requested plugin
|
||||
helper names mapped to the method - if a helper could not be resolved, it will be missing from the dict.
|
||||
|
||||
Arguments:
|
||||
name (str): Identifier of the plugin for which to look up the ``helpers``.
|
||||
helpers (one or more str): Identifiers of the helpers of plugin ``name`` to return.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary of all resolved helpers, mapped by their identifiers, or None if the plugin was not
|
||||
registered with the system.
|
||||
"""
|
||||
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
plugin = self.plugins[name]
|
||||
@@ -574,17 +691,35 @@ class PluginManager(object):
|
||||
else:
|
||||
return all_helpers
|
||||
|
||||
def register_client(self, client):
|
||||
def register_message_receiver(self, client):
|
||||
"""
|
||||
Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two
|
||||
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself).
|
||||
"""
|
||||
|
||||
if client is None:
|
||||
return
|
||||
self.registered_clients.append(client)
|
||||
|
||||
def unregister_client(self, client):
|
||||
def unregister_message_receiver(self, client):
|
||||
"""
|
||||
Unregisters a ``client`` for receiving plugin messages.
|
||||
"""
|
||||
|
||||
self.registered_clients.remove(client)
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
"""
|
||||
Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them
|
||||
with the two arguments.
|
||||
|
||||
Arguments:
|
||||
plugin (str): The sending plugin's identifier.
|
||||
data (object): The message.
|
||||
"""
|
||||
|
||||
for client in self.registered_clients:
|
||||
try: client.sendPluginMessage(plugin, data)
|
||||
try: client(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
|
||||
|
||||
@@ -522,7 +522,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
def on_api_get(self, request):
|
||||
return flask.jsonify(foo="bar")
|
||||
|
||||
__plugin_implementations__ = [MySimpleApiPlugin()]
|
||||
__plugin_implementation__ = MySimpleApiPlugin()
|
||||
|
||||
|
||||
Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one
|
||||
@@ -635,7 +635,7 @@ class BlueprintPlugin(OctoPrintPlugin):
|
||||
return flask.make_response("Expected a text to echo back.", 400)
|
||||
return flask.request.values["text"]
|
||||
|
||||
__plugin_implementations__ = [MyBlueprintPlugin()]
|
||||
__plugin_implementation__ = MyBlueprintPlugin()
|
||||
|
||||
Your blueprint will be published by OctoPrint under the base URL ``/plugin/<plugin identifier>/``, so the above
|
||||
example of a plugin with the identifier "myblueprintplugin" would be reachable under
|
||||
@@ -761,7 +761,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
some_flag = self._settings.get_boolean(["sub", "some_flag"])
|
||||
self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals())
|
||||
|
||||
__plugin_implementations__ = [MySettingsPlugin()]
|
||||
__plugin_implementation__ = MySettingsPlugin()
|
||||
|
||||
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
|
||||
default implementations do not fit your requirements.
|
||||
|
||||
Reference in new issue
Block a user