Skip to content

register_plugins

Plugin registration module

This is a simple prototype for registering plugins provided by ayon addons.

Each addon should have, in the same spirit as ayon_core, a plugins/workflow/__init__.py file with a get_plugins() function that returns a list of plugin descriptions.

The init.py should be as imports-free as possible to avoid import errors.

The actual function object used by the execution engine would be retrieved lazily through another standard API point to avoid importing un-necessary stuff. Something like:

func = ayon_test_A.plugins.workflow.get_plugin_function("plugin1")

PluginRegistry

Source code in client/ayon_workflow/plugin_system/register_plugins.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class PluginRegistry:
    _plugins = {}

    # singleton
    def __new__(cls):
        if not hasattr(cls, "instance"):
            cls.instance = super(PluginRegistry, cls).__new__(cls)
        return cls.instance

    @classmethod
    def _register_new_plugin(
            cls,
            plugin: WorkflowNode,
        ) -> Optional[WorkflowNode]:
        """ Register a new plugin from a dictionary definition.
        """
        if plugin.name in cls._plugins:
            log.warning(f"Plugin {plugin.name} is already registered.")
            return None

        PluginRegistry._plugins[plugin.name] = plugin
        return plugin

    @classmethod
    def register_plugin_from_class(
            cls,
            plugin: Union[WorkflowNode, type[WorkflowTaskNode]],
        ) -> Optional[WorkflowNode]:
        """ Register a new plugin from a WorkflowNode class type.
        """
        if issubclass(plugin, WorkflowTaskNode):
            plugin = plugin.to_workflow_node()

        elif not issubclass(plugin, WorkflowNode):
            raise ValueError("Invalid plugin class: %s" % plugin)

        return cls._register_new_plugin(plugin)

    @classmethod
    def register_plugin_from_dict(
            cls,
            module,
            plugin_as_dict: dict,
        ) -> Optional[WorkflowNode]:
        """ Register a new plugin from a dictionary definition.
        """
        if (
            not isinstance(plugin_as_dict, dict)
            or "name" not in plugin_as_dict
        ):
            raise ValueError("Invalid plugin definition")

        # Retrieve execution function
        plugin_name = plugin_as_dict["name"]
        try:
            exe_func = module.get_plugin_function(plugin_name)
        except Exception:
            log.warning(
                "No execution function found for plugin %s",
                plugin_name
            )
            exe_func = None

        # Retrieve revert function
        try:
            revert_func = module.get_plugin_revert_function(plugin_name)
        except Exception:
            log.warning(
                "No revert function found for plugin %s",
                plugin_name
            )
            revert_func = None

        impl = WorkflowNodeImplementation(
            module=module,
            func=exe_func,
            revert_func=revert_func,
        )
        inputs = []
        for plg_input in plugin_as_dict.get("inputs", []):
            multi = plg_input.get("allow_multi_connection") or False
            inputs.append(
                InputAttribute(
                    name=plg_input.get("name"),
                    type=plg_input.get("type"),
                    description=plg_input.get("description"),
                    default=plg_input.get("default"),
                    allow_multi_connection=multi,
                    widget=plg_input.get("widget"),
                )
            )

        outputs = []
        for plg_output in plugin_as_dict.get("outputs", []):
            outputs.append(
                OutputAttribute(
                    name=plg_output.get("name"),
                    type=plg_output.get("type"),
                    description=plg_output.get("description"),
                )
            )

        plugin = WorkflowNode(
            name=plugin_name,
            description=plugin_as_dict.get("description", ""),
            version=plugin_as_dict.get("version", "0.0.1"),
            inputs=inputs,
            outputs=outputs,
            implementation=impl,
        )
        return cls._register_new_plugin(plugin)

    @classmethod
    def is_initialized(cls) -> bool:
        return bool(PluginRegistry._plugins)

    @classmethod
    def plugin_names(cls) -> list[str]:
        return list(PluginRegistry._plugins.keys())

    @classmethod
    def plugin_list(cls) -> dict[str, WorkflowNode]:
        return PluginRegistry._plugins

    @classmethod
    def get_plugin_desc(cls, plugin_name: str) -> Optional[WorkflowNode]:
        return cls._plugins.get(plugin_name)

register_plugin_from_class(plugin) classmethod

Register a new plugin from a WorkflowNode class type.

Source code in client/ayon_workflow/plugin_system/register_plugins.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def register_plugin_from_class(
        cls,
        plugin: Union[WorkflowNode, type[WorkflowTaskNode]],
    ) -> Optional[WorkflowNode]:
    """ Register a new plugin from a WorkflowNode class type.
    """
    if issubclass(plugin, WorkflowTaskNode):
        plugin = plugin.to_workflow_node()

    elif not issubclass(plugin, WorkflowNode):
        raise ValueError("Invalid plugin class: %s" % plugin)

    return cls._register_new_plugin(plugin)

register_plugin_from_dict(module, plugin_as_dict) classmethod

Register a new plugin from a dictionary definition.

Source code in client/ayon_workflow/plugin_system/register_plugins.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@classmethod
def register_plugin_from_dict(
        cls,
        module,
        plugin_as_dict: dict,
    ) -> Optional[WorkflowNode]:
    """ Register a new plugin from a dictionary definition.
    """
    if (
        not isinstance(plugin_as_dict, dict)
        or "name" not in plugin_as_dict
    ):
        raise ValueError("Invalid plugin definition")

    # Retrieve execution function
    plugin_name = plugin_as_dict["name"]
    try:
        exe_func = module.get_plugin_function(plugin_name)
    except Exception:
        log.warning(
            "No execution function found for plugin %s",
            plugin_name
        )
        exe_func = None

    # Retrieve revert function
    try:
        revert_func = module.get_plugin_revert_function(plugin_name)
    except Exception:
        log.warning(
            "No revert function found for plugin %s",
            plugin_name
        )
        revert_func = None

    impl = WorkflowNodeImplementation(
        module=module,
        func=exe_func,
        revert_func=revert_func,
    )
    inputs = []
    for plg_input in plugin_as_dict.get("inputs", []):
        multi = plg_input.get("allow_multi_connection") or False
        inputs.append(
            InputAttribute(
                name=plg_input.get("name"),
                type=plg_input.get("type"),
                description=plg_input.get("description"),
                default=plg_input.get("default"),
                allow_multi_connection=multi,
                widget=plg_input.get("widget"),
            )
        )

    outputs = []
    for plg_output in plugin_as_dict.get("outputs", []):
        outputs.append(
            OutputAttribute(
                name=plg_output.get("name"),
                type=plg_output.get("type"),
                description=plg_output.get("description"),
            )
        )

    plugin = WorkflowNode(
        name=plugin_name,
        description=plugin_as_dict.get("description", ""),
        version=plugin_as_dict.get("version", "0.0.1"),
        inputs=inputs,
        outputs=outputs,
        implementation=impl,
    )
    return cls._register_new_plugin(plugin)

register_plugins(force=False)

This function imports all modules that start with 'ayon_' and register plugins from them.

Source code in client/ayon_workflow/plugin_system/register_plugins.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def register_plugins(force: bool = False):
    """
    This function imports all modules that start with 'ayon_'
    and register plugins from them.
    """
    registry = PluginRegistry()
    if not force and registry.is_initialized():
        # Already initialized, no need to force register plugins.
        return

    # Additional plugin paths for plugin discovery can be provided via the
    # `AYON_WORKFLOW_ADDITIONAL_PLUGIN_PATH` environment variable.
    additional_plugin_path = os.environ.get(
        "AYON_WORKFLOW_ADDITIONAL_PLUGIN_PATH",
        ""
    )
    additional_paths = [
        str(pathlib.Path(path)) for path  # normalize paths
        in additional_plugin_path.split(os.pathsep) if path
    ]

    # Place additional paths on sys.path so dependent modules placed
    # under the same path can also be imported.
    for path_str in additional_paths:
        if path_str not in sys.path:
            sys.path.insert(0, path_str)

    log.info("Register Plugins -----------------------------------------")

    # Get AYON default modules
    modules = []
    for __, name, _ in pkgutil.iter_modules():
        if not name.startswith("ayon_"):
            continue

        module_name = f"{name}.plugins.workflow"
        try:
            module = importlib.import_module(module_name)
            modules.append(module)

        except ModuleNotFoundError as e:
            if (
                e.name
                and not e.name.startswith(f"{name}.plugins.workflow")
            ):
                log.warning(
                    f"Error while importing {name}.plugins.workflow: {e}"
                )
            # else, ayon_*.plugins.workflow is missing, no need to log.
            continue

        except Exception as error:
            log.warning(f"Could not import module {name}: {error}")
            continue

    # Look for modules from additional paths
    if additional_paths:
        for __, module_name, _ in pkgutil.iter_modules(additional_paths):
            try:
                module = importlib.import_module(module_name)
                modules.append(module)
            except Exception as error:
                log.warning(f"Could not import module {module_name}: {error}")

    # Attempt to register plugins from modules.
    for module in modules:
        log.info(f" - Imported {module.__name__}")

        # Retrieve expected get_plugin function.
        if not callable(getattr(module, "get_plugins", None)):
            log.debug(
                f"Module {module.__name__} is missing 'get_plugins'"
            )
            continue

        for plugin in module.get_plugins():
            if (
                isinstance(plugin, type)
                and (
                    issubclass(plugin, WorkflowNode)
                    or issubclass(plugin, WorkflowTaskNode)
                )
            ):
                registered_plg = registry.register_plugin_from_class(plugin)
            elif(
                isinstance(plugin, dict)
                and callable(getattr(module, "get_plugin_function", None))
            ):
                registered_plg = registry.register_plugin_from_dict(
                    module,
                    plugin
                )
            else:
                log.warning(
                    f"Cannot register plugin from {module.__name__}: "
                    f"Unexpected plugin type: {type(plugin)}"
                )
                registered_plg = None

            if registered_plg:
                log.info(f"   + Registered plugin: {registered_plg.name}")