-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathplugin_loader.py
More file actions
297 lines (230 loc) · 10.6 KB
/
plugin_loader.py
File metadata and controls
297 lines (230 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
167
168
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
Some help functions to load satosa backend and frontend modules
"""
import json
import logging
import sys
from contextlib import contextmanager
from pydoc import locate
from satosa.yaml import load as yaml_load
from satosa.yaml import YAMLError
from .backends.base import BackendModule
from .exception import SATOSAConfigurationError
from .frontends.base import FrontendModule
from .micro_services.base import (MicroService, RequestMicroService, ResponseMicroService)
logger = logging.getLogger(__name__)
names = []
@contextmanager
def prepend_to_import_path(import_paths):
import_paths = import_paths or []
for p in reversed(import_paths): # insert the specified plugin paths in the same order
sys.path.insert(0, p)
yield
del sys.path[0:len(import_paths)] # restore sys.path
def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
"""
backend_modules = _load_plugins(
config.get("CUSTOM_PLUGIN_MODULE_PATHS"),
config["BACKEND_MODULES"],
backend_filter, config["BASE"],
internal_attributes, callback)
for backend in backend_modules:
if backend.name in names:
raise SATOSAConfigurationError("The name " + backend.name + " is taken!")
else:
names.append(backend.name)
logger.info("Setup backends: {}".format([backend.name for backend in backend_modules]))
return backend_modules
def load_frontends(config, callback, internal_attributes):
"""
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
"""
frontend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["FRONTEND_MODULES"],
frontend_filter, config["BASE"], internal_attributes, callback)
for frontend in frontend_modules:
if frontend.name in names:
raise SATOSAConfigurationError("The name " + frontend.name + " is taken!")
else:
names.append(frontend.name)
logger.info("Setup frontends: {}".format([frontend.name for frontend in frontend_modules]))
return frontend_modules
def backend_filter(cls):
"""
Verify that the type proper subclass of BackendModule.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
return issubclass(cls, BackendModule) and cls != BackendModule
def frontend_filter(cls):
"""
Verify that the type proper subclass of FrontendModule.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
return issubclass(cls, FrontendModule) and cls != FrontendModule
def _micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
is_microservice_module = issubclass(cls, MicroService)
is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService
return is_microservice_module and is_correct_subclass
def _request_micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of RequestMicroService.
Use this filter to only find frontend plugins
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
return issubclass(cls, RequestMicroService) and cls != RequestMicroService
def _response_micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of ResponseMicroService.
Use this filter to only find frontend plugins
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
return issubclass(cls, ResponseMicroService) and cls != ResponseMicroService
def _load_plugin_config(config):
try:
return yaml_load(config)
except YAMLError as exc:
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
logger.error("Error position: ({line}:{column})".format(line=mark.line + 1, column=mark.column + 1))
raise SATOSAConfigurationError("The configuration is corrupt.") from exc
def _load_plugins(plugin_paths, plugins, plugin_filter, base_url, internal_attributes, callback):
"""
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
"""
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_endpoint_module(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
module_config = _replace_variables_in_plugin_module_config(plugin_config["config"], base_url,
plugin_config["name"])
instance = module_class(callback, internal_attributes, module_config, base_url,
plugin_config["name"])
loaded_plugin_modules.append(instance)
return loaded_plugin_modules
def _load_endpoint_module(plugin_config, plugin_filter):
_mandatory_params = ("name", "module", "config")
if not all(k in plugin_config for k in _mandatory_params):
raise SATOSAConfigurationError(
"Missing mandatory plugin configuration parameter: {}".format(_mandatory_params))
return _load_plugin_module(plugin_config, plugin_filter)
def _load_plugin_module(plugin_config, plugin_filter):
module_class = locate(plugin_config["module"])
if not module_class:
raise ValueError("Can't find module '%s'" % plugin_config["module"])
if not plugin_filter(module_class):
return None
return module_class
def _load_microservice(plugin_config, plugin_filter):
_mandatory_params = ("name", "module")
if not all(k in plugin_config for k in _mandatory_params):
raise SATOSAConfigurationError(
"Missing mandatory plugin configuration parameter: {}".format(_mandatory_params))
return _load_plugin_module(plugin_config, plugin_filter)
def _load_microservices(plugin_paths, plugins, plugin_filter, internal_attributes, base_url):
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_microservice(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
instance = module_class(internal_attributes=internal_attributes, config=plugin_config.get("config"),
name=plugin_config["name"], base_url=base_url)
loaded_plugin_modules.append(instance)
return loaded_plugin_modules
def _replace_variables_in_plugin_module_config(module_config, base_url, name):
config = json.dumps(module_config)
replace = [
("<base_url>", base_url),
("<name>", name)
]
for _replace in replace:
config = config.replace(_replace[0], _replace[1])
return json.loads(config)
def load_request_microservices(plugin_path, plugins, internal_attributes, base_url):
"""
Loads request micro services (handling incoming requests).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.RequestMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Request micro service
"""
request_services = _load_microservices(plugin_path, plugins, _request_micro_service_filter, internal_attributes,
base_url)
logger.info("Loaded request micro services: {}".format([type(k).__name__ for k in request_services]))
return request_services
def load_response_microservices(plugin_path, plugins, internal_attributes, base_url):
"""
Loads response micro services (handling outgoing responses).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.ResponseMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Response micro service
"""
response_services = _load_microservices(plugin_path, plugins, _response_micro_service_filter, internal_attributes,
base_url)
logger.info("Loaded response micro services:{}".format([type(k).__name__ for k in response_services]))
return response_services