-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathplugin_loader.py
More file actions
136 lines (108 loc) · 3.5 KB
/
Copy pathplugin_loader.py
File metadata and controls
136 lines (108 loc) · 3.5 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
"""
SENTINEL Shield v2.0 — Plugin Loader
Discovers and loads custom detection engine plugins
from a specified directory.
Plugin contract:
- File: <name>.py in plugins directory
- Class: must extend BaseEngine
- Class name: must end with 'Engine'
Example plugin (plugins/my_custom_engine.py):
from engines.base import BaseEngine, EngineResult, ThreatMatch
class MyCustomEngine(BaseEngine):
def __init__(self):
super().__init__("my_custom", weight=0.8)
def analyze(self, text: str) -> EngineResult:
# Custom detection logic
return EngineResult(engine_name=self.name)
"""
import sys
import importlib
import importlib.util
import logging
from pathlib import Path
from typing import Optional
logger = logging.getLogger("shield.plugins")
def discover_plugins(
directory: str,
) -> list[dict]:
"""
Discover plugin files in directory.
Returns list of dicts with name, path, module.
Does not instantiate engines yet.
"""
plugin_dir = Path(directory)
if not plugin_dir.exists():
logger.info(f"Plugin dir not found: {plugin_dir}")
return []
plugins = []
for f in sorted(plugin_dir.glob("*.py")):
if f.name.startswith("_"):
continue
plugins.append(
{
"name": f.stem,
"path": str(f),
"loaded": False,
"error": None,
}
)
logger.info(f"Discovered {len(plugins)} plugin(s) " f"in {plugin_dir}")
return plugins
def load_plugin(plugin_path: str) -> Optional[object]:
"""
Load a single plugin and return engine instance.
Looks for a class ending with 'Engine' that
extends BaseEngine.
"""
from engines.base import BaseEngine
path = Path(plugin_path)
if not path.exists():
logger.error(f"Plugin not found: {path}")
return None
module_name = f"shield_plugin_{path.stem}"
try:
spec = importlib.util.spec_from_file_location(module_name, str(path))
if spec is None or spec.loader is None:
logger.error(f"Cannot create spec for {path}")
return None
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Find engine class
for attr_name in dir(module):
if not attr_name.endswith("Engine"):
continue
cls = getattr(module, attr_name)
if (
isinstance(cls, type)
and issubclass(cls, BaseEngine)
and cls is not BaseEngine
):
engine = cls()
logger.info(
f"Loaded plugin engine: "
f"{engine.name} "
f"(weight={engine.weight}) "
f"from {path.name}"
)
return engine
logger.warning(f"No BaseEngine subclass found " f"in {path.name}")
return None
except Exception as e:
logger.error(f"Plugin load error ({path.name}): {e}")
return None
def load_all_plugins(
directory: str,
) -> list[object]:
"""
Load all plugins from directory.
Returns list of engine instances.
"""
plugins = discover_plugins(directory)
engines = []
for p in plugins:
engine = load_plugin(p["path"])
if engine:
engines.append(engine)
logger.info(f"Loaded {len(engines)}/{len(plugins)} " f"plugin engines")
return engines