load only required plugins

This commit is contained in:
Devaev Maxim 2019-04-28 21:01:03 +03:00
parent 26338c5acf
commit e13b5027d6
7 changed files with 22 additions and 38 deletions

View File

@ -111,9 +111,9 @@ def _init_config(config_path: str, sections: List[str], override_options: List[s
config = make_config(raw_config, scheme) config = make_config(raw_config, scheme)
if "kvmd" in sections: if "kvmd" in sections:
scheme["kvmd"]["auth"]["internal"] = get_auth_service_class(config.kvmd.auth.internal_type).get_options() scheme["kvmd"]["auth"]["internal"] = get_auth_service_class(config.kvmd.auth.internal_type).get_plugin_options()
if config.kvmd.auth.external_type: if config.kvmd.auth.external_type:
scheme["kvmd"]["auth"]["external"] = get_auth_service_class(config.kvmd.auth.external_type).get_options() scheme["kvmd"]["auth"]["external"] = get_auth_service_class(config.kvmd.auth.external_type).get_plugin_options()
config = make_config(raw_config, scheme) config = make_config(raw_config, scheme)
return config return config

View File

@ -47,12 +47,12 @@ class AuthManager:
) -> None: ) -> None:
self.__internal_service = get_auth_service_class(internal_type)(**internal_kwargs) self.__internal_service = get_auth_service_class(internal_type)(**internal_kwargs)
get_logger().info("Using internal auth service %r", self.__internal_service.PLUGIN_NAME) get_logger().info("Using internal auth service %r", self.__internal_service.get_plugin_name())
self.__external_service: Optional[BaseAuthService] = None self.__external_service: Optional[BaseAuthService] = None
if external_type: if external_type:
self.__external_service = get_auth_service_class(external_type)(**external_kwargs) self.__external_service = get_auth_service_class(external_type)(**external_kwargs)
get_logger().info("Using external auth service %r", self.__external_service.PLUGIN_NAME) get_logger().info("Using external auth service %r", self.__external_service.get_plugin_name())
self.__internal_users = internal_users self.__internal_users = internal_users
@ -66,9 +66,9 @@ class AuthManager:
ok = (await service.authorize(user, passwd)) ok = (await service.authorize(user, passwd))
if ok: if ok:
get_logger().info("Authorized user %r via auth service %r", user, service.PLUGIN_NAME) get_logger().info("Authorized user %r via auth service %r", user, service.get_plugin_name())
else: else:
get_logger().error("Got access denied for user %r from auth service %r", user, service.PLUGIN_NAME) get_logger().error("Got access denied for user %r from auth service %r", user, service.get_plugin_name())
return ok return ok
async def login(self, user: str, passwd: str) -> Optional[str]: async def login(self, user: str, passwd: str) -> Optional[str]:

View File

@ -22,7 +22,6 @@
import importlib import importlib
import functools import functools
import os
from typing import Dict from typing import Dict
from typing import Type from typing import Type
@ -38,34 +37,23 @@ class UnknownPluginError(Exception):
# ===== # =====
class BasePlugin: class BasePlugin:
PLUGIN_NAME: str = ""
def __init__(self, **_: Any) -> None: def __init__(self, **_: Any) -> None:
pass # pragma: nocover pass # pragma: nocover
@classmethod @classmethod
def get_options(cls) -> Dict[str, Option]: def get_plugin_name(cls) -> str:
name = cls.__module__
return name[name.rindex(".") + 1:]
@classmethod
def get_plugin_options(cls) -> Dict[str, Option]:
return {} # pragma: nocover return {} # pragma: nocover
# =====
def get_plugin_class(sub: str, name: str) -> Type[BasePlugin]:
classes = _get_plugin_classes(sub)
try:
return classes[name]
except KeyError:
raise UnknownPluginError("Unknown plugin '%s/%s'" % (sub, name))
# =====
@functools.lru_cache() @functools.lru_cache()
def _get_plugin_classes(sub: str) -> Dict[str, Type[BasePlugin]]: def get_plugin_class(sub: str, name: str) -> Type[BasePlugin]:
classes: Dict[str, Type[BasePlugin]] = {} # noqa: E701 try:
sub_path = os.path.join(os.path.dirname(__file__), sub) module = importlib.import_module("kvmd.plugins.{}.{}".format(sub, name))
for file_name in os.listdir(sub_path): except ModuleNotFoundError:
if not file_name.startswith("__") and file_name.endswith(".py"): raise UnknownPluginError("Unknown plugin '%s/%s'" % (sub, name))
module_name = file_name[:-3] return getattr(module, "Plugin")
module = importlib.import_module("kvmd.plugins.{}.{}".format(sub, module_name))
plugin_class = getattr(module, "Plugin")
classes[plugin_class.PLUGIN_NAME] = plugin_class
return classes

View File

@ -33,13 +33,11 @@ from . import BaseAuthService
# ===== # =====
class Plugin(BaseAuthService): class Plugin(BaseAuthService):
PLUGIN_NAME = "htpasswd"
def __init__(self, path: str) -> None: # pylint: disable=super-init-not-called def __init__(self, path: str) -> None: # pylint: disable=super-init-not-called
self.__path = path self.__path = path
@classmethod @classmethod
def get_options(cls) -> Dict[str, Option]: def get_plugin_options(cls) -> Dict[str, Option]:
return { return {
"file": Option("/etc/kvmd/htpasswd", type=valid_abs_path_exists, unpack_as="path"), "file": Option("/etc/kvmd/htpasswd", type=valid_abs_path_exists, unpack_as="path"),
} }

View File

@ -40,8 +40,6 @@ from . import BaseAuthService
# ===== # =====
class Plugin(BaseAuthService): class Plugin(BaseAuthService):
PLUGIN_NAME = "http"
def __init__( # pylint: disable=super-init-not-called def __init__( # pylint: disable=super-init-not-called
self, self,
url: str, url: str,
@ -60,7 +58,7 @@ class Plugin(BaseAuthService):
self.__http_session: Optional[aiohttp.ClientSession] = None self.__http_session: Optional[aiohttp.ClientSession] = None
@classmethod @classmethod
def get_options(cls) -> Dict[str, Option]: def get_plugin_options(cls) -> Dict[str, Option]:
return { return {
"url": Option("http://localhost/auth"), "url": Option("http://localhost/auth"),
"verify": Option(True, type=valid_bool), "verify": Option(True, type=valid_bool),

View File

@ -35,7 +35,7 @@ from kvmd.plugins.auth import get_auth_service_class
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def get_configured_auth_service(name: str, **kwargs: Any) -> AsyncGenerator[BaseAuthService, None]: async def get_configured_auth_service(name: str, **kwargs: Any) -> AsyncGenerator[BaseAuthService, None]:
service_class = get_auth_service_class(name) service_class = get_auth_service_class(name)
config = make_config(kwargs, service_class.get_options()) config = make_config(kwargs, service_class.get_plugin_options())
service = service_class(**config._unpack()) # pylint: disable=protected-access service = service_class(**config._unpack()) # pylint: disable=protected-access
try: try:
yield service yield service

View File

@ -42,7 +42,7 @@ from kvmd.plugins.auth import get_auth_service_class
# ===== # =====
def _make_service_kwargs(path: str) -> Dict: def _make_service_kwargs(path: str) -> Dict:
cls = get_auth_service_class("htpasswd") cls = get_auth_service_class("htpasswd")
scheme = cls.get_options() scheme = cls.get_plugin_options()
return make_config({"file": path}, scheme)._unpack() # pylint: disable=protected-access return make_config({"file": path}, scheme)._unpack() # pylint: disable=protected-access