keepup-admin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/plugins/base.py ADDED
@@ -0,0 +1,234 @@
1
+ """The plugin contract and the manager that loads plugins.
2
+
3
+ The manager knows nothing about which application it serves: the directory to
4
+ load from is supplied by that application. Resolving it from this module's own
5
+ location would point inside the framework package, where no plugin lives.
6
+ """
7
+
8
+ import importlib.util
9
+ import logging
10
+ import os
11
+ from abc import ABC, abstractmethod
12
+ from typing import Dict, Any, List, Optional
13
+
14
+ from keepup.plugins import enablement
15
+
16
+ #: What an application may import from this module. Everything else is
17
+ #: internal and may change without notice -- see doc/keepup.md.
18
+ __all__ = [
19
+ "BasePlugin",
20
+ "MODULES_CONFIG_FILE",
21
+ "OUTCOME_DISABLED",
22
+ "OUTCOME_FAILED",
23
+ "OUTCOME_INITIALIZED",
24
+ "OUTCOME_NOT_FOUND",
25
+ "PluginManager",
26
+ ]
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ MODULES_CONFIG_FILE = "modules.json"
31
+
32
+ #: Outcome of a declared plugin, as reported to the admin plugin list.
33
+ OUTCOME_INITIALIZED = "initialized"
34
+ OUTCOME_DISABLED = "disabled"
35
+ OUTCOME_NOT_FOUND = "not_found"
36
+ OUTCOME_FAILED = "failed"
37
+
38
+
39
+ class BasePlugin(ABC):
40
+ """Base class for every plugin."""
41
+
42
+ def __init__(self, plugin_id: str, name: str, config: Dict = None):
43
+ self.plugin_id = plugin_id
44
+ self.name = name
45
+ self.config = config or {}
46
+ self.plugin_manager = None
47
+ self.initialized = False
48
+ self.priority = 0
49
+
50
+ def set_plugin_manager(self, plugin_manager):
51
+ """Store the reference to the plugin manager."""
52
+ self.plugin_manager = plugin_manager
53
+
54
+ def set_priority(self, priority: int):
55
+ """Set the plugin priority."""
56
+ self.priority = priority
57
+
58
+ @abstractmethod
59
+ async def initialize(self) -> bool:
60
+ """Initialise the plugin."""
61
+ pass
62
+
63
+ async def post_construct(self):
64
+ """Called once the application is fully initialised and all endpoints registered.
65
+
66
+ Use it for self-checks that need a running server.
67
+ """
68
+ pass
69
+
70
+ def get_websocket_routes(self) -> List[Dict]:
71
+ """Return the plugin's WebSocket routes.
72
+
73
+ Each route is a dict with:
74
+ - path: str -- the WebSocket endpoint path
75
+ - handler: callable -- async handler taking the WebSocket and its parameters
76
+ """
77
+ return []
78
+
79
+ @abstractmethod
80
+ def get_api_routes(self) -> List[Dict]:
81
+ """Return the plugin's API routes."""
82
+ pass
83
+
84
+ @abstractmethod
85
+ def get_handlers(self) -> Dict[str, Any]:
86
+ """Return the plugin's named handlers."""
87
+ pass
88
+
89
+ async def cleanup(self):
90
+ """Release the plugin's resources."""
91
+ pass
92
+
93
+
94
+ class PluginManager:
95
+ """Loads and manages plugins, honouring their priorities."""
96
+
97
+ def __init__(self, plugins_dir: str, config_file: str = MODULES_CONFIG_FILE):
98
+ self.plugins_dir = plugins_dir
99
+ self.config_file = config_file
100
+ #: Loaded, in the order they were loaded.
101
+ self.plugins: Dict[str, BasePlugin] = {}
102
+ #: The subset that initialised; only these answer get_plugin().
103
+ self.loaded_plugins: Dict[str, BasePlugin] = {}
104
+ #: Outcome per declared plugin id: (outcome, reason or None).
105
+ #: A plugin that loaded but failed to initialise looks exactly like a
106
+ #: disabled one from outside -- its routes are simply absent -- so the
107
+ #: difference is kept here rather than only in the log.
108
+ self.outcomes: Dict[str, tuple] = {}
109
+ #: What the deployment decided about each declared plugin at start-up,
110
+ #: for the administrative list. It belongs to this manager and not to
111
+ #: the module that computes it: a process may hold more than one
112
+ #: application, and a module-level snapshot would be the last one's.
113
+ self.resolution = enablement.Resolution()
114
+
115
+ def record_outcome(self, plugin_id: str, outcome: str, reason: str = None):
116
+ """Remember how a declared plugin ended up."""
117
+ self.outcomes[plugin_id] = (outcome, reason)
118
+
119
+ def get_outcome(self, plugin_id: str) -> tuple:
120
+ """Return (outcome, reason) for a declared plugin, or (None, None)."""
121
+ return self.outcomes.get(plugin_id, (None, None))
122
+
123
+ def load_plugin(self, plugin_id: str, plugin_config: Dict, priority: int = 0) -> bool:
124
+ """Load a single plugin by its id and give it its priority.
125
+
126
+ The priority is what initialize_plugins() orders by; it comes from the
127
+ plugin's description in modules.json and was, until it arrived here,
128
+ declared and never applied.
129
+ """
130
+ try:
131
+ plugin_file = os.path.join(self.plugins_dir, f"{plugin_id}.py")
132
+
133
+ if not os.path.exists(plugin_file):
134
+ logger.warning(f"Plugin file not found: {plugin_file}")
135
+ self.record_outcome(plugin_id, OUTCOME_NOT_FOUND, f"file not found: {plugin_file}")
136
+ return False
137
+ spec = importlib.util.spec_from_file_location(plugin_id, plugin_file)
138
+ plugin_module = importlib.util.module_from_spec(spec)
139
+ spec.loader.exec_module(plugin_module)
140
+
141
+ plugin_class_name = f"{plugin_id.capitalize()}Plugin"
142
+ plugin_class = getattr(plugin_module, plugin_class_name, None)
143
+ if not plugin_class:
144
+ logger.warning(f"Plugin class {plugin_class_name} not found for: {plugin_id}")
145
+ self.record_outcome(plugin_id, OUTCOME_NOT_FOUND, f"class {plugin_class_name} not found")
146
+ return False
147
+
148
+ plugin_instance = plugin_class(plugin_config)
149
+ plugin_instance.set_plugin_manager(self)
150
+ plugin_instance.set_priority(priority)
151
+ self.plugins[plugin_id] = plugin_instance
152
+ logger.info(f"Plugin loaded: {plugin_id}")
153
+ return True
154
+
155
+ except Exception as e:
156
+ logger.error(f"Error loading plugin {plugin_id}: {str(e)}")
157
+ self.record_outcome(plugin_id, OUTCOME_FAILED, f"load error: {e}")
158
+ return False
159
+
160
+ async def initialize_plugins(self) -> bool:
161
+ """Initialise every loaded plugin, lowest priority first.
162
+
163
+ Stable for equal priorities, so ties keep the load order -- the order
164
+ of description in modules.json. A plugin whose initialize() fails is
165
+ logged and left out of loaded_plugins; the rest still come up.
166
+ """
167
+ ordered = sorted(self.plugins.items(), key=lambda item: item[1].priority)
168
+ logger.info(f"Initializing plugins in order: {[plugin_id for plugin_id, _ in ordered]}")
169
+
170
+ success = True
171
+ for plugin_id, plugin in ordered:
172
+ try:
173
+ initialized = await plugin.initialize()
174
+ failure_reason = "initialize() returned false"
175
+ except Exception as e:
176
+ # An exception used to escape into the caller and stop the rest
177
+ # of the plugins from initialising at all.
178
+ initialized = False
179
+ failure_reason = f"{type(e).__name__}: {e}"
180
+ logger.exception(f"Error initializing plugin {plugin_id}")
181
+
182
+ if initialized:
183
+ self.loaded_plugins[plugin_id] = plugin
184
+ self.record_outcome(plugin_id, OUTCOME_INITIALIZED)
185
+ logger.info(f"Plugin initialized ({plugin.priority}): {plugin_id}")
186
+ else:
187
+ logger.error(f"Failed to initialize plugin: {plugin_id}")
188
+ self.record_outcome(plugin_id, OUTCOME_FAILED, failure_reason)
189
+ success = False
190
+ return success
191
+
192
+ def get_plugin(self, plugin_id: str) -> Optional[BasePlugin]:
193
+ """Return a plugin instance by id."""
194
+ return self.loaded_plugins.get(plugin_id)
195
+
196
+ def get_all_api_routes(self) -> List[Dict]:
197
+ """Return the API routes of every plugin."""
198
+ routes = []
199
+ for plugin in self.loaded_plugins.values():
200
+ routes.extend(plugin.get_api_routes())
201
+ return routes
202
+
203
+ def get_all_websocket_routes(self) -> List[Dict]:
204
+ """Collect the WebSocket routes of every plugin that initialised.
205
+
206
+ The initialised ones, like get_all_api_routes -- this used to walk the
207
+ loaded ones instead. A plugin whose initialize() failed lost its HTTP
208
+ routes and kept its sockets, so the admin surface reported it failed
209
+ while a socket of its went on listening against an object with no
210
+ tables and no connections behind it (keepup-12).
211
+ """
212
+ all_routes = []
213
+ for plugin in self.loaded_plugins.values():
214
+ if hasattr(plugin, 'get_websocket_routes') and callable(plugin.get_websocket_routes):
215
+ try:
216
+ routes = plugin.get_websocket_routes()
217
+ if routes:
218
+ all_routes.extend(routes)
219
+ except Exception as e:
220
+ logger.error(f"Error getting WebSocket routes from plugin {plugin.name}: {e}")
221
+ return all_routes
222
+
223
+ async def cleanup_all(self):
224
+ """Clean up every plugin."""
225
+ for plugin in self.loaded_plugins.values():
226
+ await plugin.cleanup()
227
+ self.loaded_plugins.clear()
228
+
229
+ def get_plugins_by_priority(self) -> List[BasePlugin]:
230
+ """Return the loaded plugins sorted by priority."""
231
+ return sorted(
232
+ self.loaded_plugins.values(),
233
+ key=lambda x: x.priority
234
+ )
@@ -0,0 +1,184 @@
1
+ """Which declared plugins run, and where that decision came from.
2
+
3
+ Until this module the answer was the union of the roles' plugin lists in
4
+ modules.json: a plugin unrelated to any role -- the websocket channel, the
5
+ Telegram bot -- had to be granted to one or it silently did not start, and
6
+ four of twenty declared plugins ran. That glued two different decisions
7
+ together: what runs on the server, and what a role is shown.
8
+
9
+ Here the decision is explicit. A plugin runs when its own description says
10
+ ``enabled: true`` or the deployment's environment names it; a role's list
11
+ means visibility only. Pure: configuration and environment come in as
12
+ mappings, decisions go out, nothing is read or loaded -- which is what lets
13
+ the cases be checked without an application.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Dict, List, Mapping
20
+
21
+ #: Comma-separated plugin ids the deployment enables regardless of the file.
22
+ ENABLE_ENV = "PLUGINS_ENABLE"
23
+ #: Comma-separated plugin ids the deployment disables regardless of the file.
24
+ #: Wins over ENABLE_ENV: the safe outcome of a contradiction is "off".
25
+ DISABLE_ENV = "PLUGINS_DISABLE"
26
+
27
+ #: Where a decision came from.
28
+ SOURCE_CONFIG = "config" # the plugin's own ``enabled`` flag in modules.json
29
+ SOURCE_ENV = "env" # PLUGINS_ENABLE / PLUGINS_DISABLE
30
+ SOURCE_PANEL = "panel" # an administrator's override, kept in the database
31
+ SOURCE_DEFAULT = "default" # the flag is absent: not enabled
32
+
33
+ #: The flag in a plugin's description. Absent means "off": the alternative
34
+ #: would have switched on all twenty the day the mechanism changed.
35
+ ENABLED_FLAG = "enabled"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Decision:
40
+ """Whether one declared plugin is on, and who decided it."""
41
+
42
+ plugin_id: str
43
+ enabled: bool
44
+ source: str
45
+
46
+
47
+ @dataclass
48
+ class Resolution:
49
+ """The decision for every declared plugin, plus ids nobody declared."""
50
+
51
+ #: In declaration order, one per declared plugin.
52
+ decisions: Dict[str, Decision] = field(default_factory=dict)
53
+ #: Ids named in the environment that no declaration matches. Reported,
54
+ #: never fatal: a typo in a deployment must not take the server down.
55
+ unknown: List[str] = field(default_factory=list)
56
+
57
+
58
+ def parse_id_list(value: Any) -> List[str]:
59
+ """Ids from a comma-separated variable, blanks dropped, order kept."""
60
+ if not value:
61
+ return []
62
+ return [item.strip() for item in str(value).split(",") if item.strip()]
63
+
64
+
65
+ def declared_plugins(config: Mapping[str, Any]) -> List[Mapping[str, Any]]:
66
+ """The plugin descriptions of modules.json, in file order."""
67
+ return [p for p in (config.get("plugins") or []) if isinstance(p, Mapping) and p.get("id")]
68
+
69
+
70
+ def decided_by_environment(plugin_id: str, environ: Mapping[str, Any]) -> bool:
71
+ """Whether the deployment has already decided about this plugin.
72
+
73
+ What the panel's refusal is built on: an override that the environment
74
+ would overrule is a trap, so it is not accepted at all.
75
+ """
76
+ return (plugin_id in parse_id_list(environ.get(DISABLE_ENV))
77
+ or plugin_id in parse_id_list(environ.get(ENABLE_ENV)))
78
+
79
+
80
+ def resolve(config: Mapping[str, Any], environ: Mapping[str, Any],
81
+ overrides: Mapping[str, bool] = None) -> Resolution:
82
+ """Decide, for every declared plugin, whether it runs.
83
+
84
+ Three sources, strongest first. The environment belongs to one deployment
85
+ and protects that stand, so it wins; disable wins over enable, because the
86
+ safe outcome of a contradiction is "off". Then an administrator's override
87
+ from the panel, kept in this deployment's database. Then the file, which is
88
+ committed and shared between deployments. Absent everywhere means off.
89
+
90
+ ``overrides`` for a plugin nobody declared is ignored, like an unknown id
91
+ in the environment: a stale row must not conjure a plugin.
92
+ """
93
+ enable = parse_id_list(environ.get(ENABLE_ENV))
94
+ disable = parse_id_list(environ.get(DISABLE_ENV))
95
+ overrides = overrides or {}
96
+ declared = declared_plugins(config)
97
+ known = {p["id"] for p in declared}
98
+
99
+ resolution = Resolution()
100
+ for plugin in declared:
101
+ pid = plugin["id"]
102
+ if pid in disable:
103
+ decision = Decision(pid, False, SOURCE_ENV)
104
+ elif pid in enable:
105
+ decision = Decision(pid, True, SOURCE_ENV)
106
+ elif isinstance(overrides.get(pid), bool):
107
+ decision = Decision(pid, overrides[pid], SOURCE_PANEL)
108
+ elif isinstance(plugin.get(ENABLED_FLAG), bool):
109
+ decision = Decision(pid, plugin[ENABLED_FLAG], SOURCE_CONFIG)
110
+ else:
111
+ decision = Decision(pid, False, SOURCE_DEFAULT)
112
+ resolution.decisions[pid] = decision
113
+
114
+ resolution.unknown = [pid for pid in enable + disable if pid not in known]
115
+ return resolution
116
+
117
+
118
+ def enabled_ids(resolution: Resolution) -> List[str]:
119
+ """The ids that run, in declaration order."""
120
+ return [d.plugin_id for d in resolution.decisions.values() if d.enabled]
121
+
122
+
123
+ def summary_line(resolution: Resolution) -> str:
124
+ """One line for the start-up log naming what did not get enabled.
125
+
126
+ A plugin that does not start is otherwise invisible: the loader logs
127
+ nothing about a plugin it was never asked to load.
128
+ """
129
+ enabled = enabled_ids(resolution)
130
+ total = len(resolution.decisions)
131
+ line = f"Plugins: enabled {len(enabled)} of {total} declared"
132
+ silent = [pid for pid in resolution.decisions if pid not in enabled]
133
+ if silent:
134
+ line += "; not enabled: " + ", ".join(silent)
135
+ return line
136
+
137
+
138
+ def status_report(config: Mapping[str, Any], resolution: Resolution, manager: Any,
139
+ desired: Resolution = None,
140
+ environ: Mapping[str, Any] = None) -> List[Dict[str, Any]]:
141
+ """One row per declared plugin: the decision and what became of it.
142
+
143
+ ``manager`` is the plugin manager: ``plugins`` holds what was loaded,
144
+ ``loaded_plugins`` what initialised, and ``outcomes`` why each declared
145
+ plugin ended up where it did. An enabled plugin that is loaded and not
146
+ initialised is the case that used to be visible only in the log; it now
147
+ carries its outcome and the reason it failed.
148
+
149
+ ``resolution`` is the snapshot taken at start-up -- what is actually
150
+ running, because routes are built once and not removed. ``desired`` is the
151
+ decision in force now, overrides included; where the two differ, the row
152
+ is marked as awaiting a restart. The mark is that difference and not a
153
+ stored column, which would have to be cleared when an override is put back
154
+ and would not be.
155
+ """
156
+ loaded = getattr(manager, "plugins", {}) or {}
157
+ initialized = getattr(manager, "loaded_plugins", {}) or {}
158
+ outcomes = getattr(manager, "outcomes", {}) or {}
159
+ environ = environ or {}
160
+ rows = []
161
+ for plugin in declared_plugins(config):
162
+ pid = plugin["id"]
163
+ decision = resolution.decisions.get(pid) or Decision(pid, False, SOURCE_DEFAULT)
164
+ wanted = decision if desired is None else (
165
+ desired.decisions.get(pid) or Decision(pid, False, SOURCE_DEFAULT))
166
+ rows.append({
167
+ "id": pid,
168
+ "name": plugin.get("name") or pid,
169
+ "priority": plugin.get("priority") or 0,
170
+ "enabled": decision.enabled,
171
+ "source": decision.source,
172
+ "loaded": pid in loaded,
173
+ "initialized": pid in initialized,
174
+ "desired_enabled": wanted.enabled,
175
+ "desired_source": wanted.source,
176
+ "pending_restart": wanted.enabled != decision.enabled,
177
+ "decided_by_environment": decided_by_environment(pid, environ),
178
+ # Why the plugin is in the state it is in. "loaded and not
179
+ # initialized" is the case an administrator cannot otherwise tell
180
+ # from "switched off": both answer 404 on the plugin's routes.
181
+ "outcome": outcomes.get(pid, (None, None))[0],
182
+ "failure_reason": outcomes.get(pid, (None, None))[1],
183
+ })
184
+ return rows
@@ -0,0 +1,171 @@
1
+ """Assembling the plugins of an application, and the package's way in.
2
+
3
+ What happens here is the start-up itself: read the declaration, ask
4
+ ``keepup.plugins.admin`` which of the declared plugins this deployment runs,
5
+ load and initialise them in priority order, hand their routes to
6
+ ``keepup.plugins.routes``, and afterwards run the self-checks that need a live
7
+ server.
8
+
9
+ This module is also **the address the package publishes**. The two modules the
10
+ work moved into are internal: an application imports ``initialize_plugins``,
11
+ ``register_plugin_routes`` and the rest from here, as it always has, and a
12
+ rearrangement inside the package is not a breaking change for anybody who
13
+ installed it (keepup-21).
14
+ """
15
+
16
+ import asyncio
17
+ import concurrent.futures
18
+ import json
19
+ import logging
20
+ import os
21
+
22
+ from keepup.plugins import enablement
23
+ from keepup.plugins.admin import (
24
+ MODULES_CONFIG_PATH,
25
+ clear_plugin_override,
26
+ get_plugins,
27
+ get_plugins_status,
28
+ read_plugin_overrides,
29
+ register_plugin_admin_routes,
30
+ write_plugin_override,
31
+ )
32
+ from keepup.plugins.base import (
33
+ OUTCOME_DISABLED,
34
+ OUTCOME_INITIALIZED,
35
+ )
36
+ from keepup.plugins.routes import (
37
+ accepted_params,
38
+ admit_params,
39
+ raw_request_wrapper,
40
+ register_plugin_routes,
41
+ signed_in_websocket,
42
+ )
43
+
44
+ #: What an application may import from this module. Everything else is
45
+ #: internal and may change without notice -- see doc/keepup.md.
46
+ #:
47
+ #: The names below live in keepup.plugins.routes and keepup.plugins.admin and
48
+ #: are published here: one address outwards, whatever the layout inside.
49
+ __all__ = [
50
+ "accepted_params",
51
+ "admit_params",
52
+ "clear_plugin_override",
53
+ "get_plugins",
54
+ "get_plugins_status",
55
+ "initialize_plugins",
56
+ "raw_request_wrapper",
57
+ "read_plugin_overrides",
58
+ "register_plugin_admin_routes",
59
+ "register_plugin_routes",
60
+ "run_post_construct_processors",
61
+ "signed_in_websocket",
62
+ "write_plugin_override",
63
+ ]
64
+
65
+ logger = logging.getLogger(__name__)
66
+
67
+
68
+ async def initialize_plugins(app, manager, config_path=MODULES_CONFIG_PATH, environ=None):
69
+ """Load and initialise the plugins the configuration and environment enable.
70
+
71
+ Which plugins run is decided by keepup.plugins.enablement -- the plugin's own
72
+ ``enabled`` flag, an administrator's override kept in this deployment's
73
+ database, and PLUGINS_ENABLE / PLUGINS_DISABLE -- never by the roles'
74
+ plugin lists, which only say what a role is shown.
75
+ """
76
+ try:
77
+ with open(config_path, 'r', encoding='utf-8') as f:
78
+ config = json.load(f)
79
+
80
+ resolution = enablement.resolve(
81
+ config, environ if environ is not None else os.environ,
82
+ overrides=read_plugin_overrides())
83
+ # On the manager rather than in this module: the administrative list
84
+ # reads it through the manager it is already given, and a process may
85
+ # hold more than one application (keepup-21).
86
+ manager.resolution = resolution
87
+ for unknown in resolution.unknown:
88
+ logger.warning(
89
+ f"{enablement.ENABLE_ENV}/{enablement.DISABLE_ENV} name "
90
+ f"an undeclared plugin: {unknown}"
91
+ )
92
+ logger.info(enablement.summary_line(resolution))
93
+
94
+ enabled = set(enablement.enabled_ids(resolution))
95
+ for plugin_config in enablement.declared_plugins(config):
96
+ plugin_id = plugin_config['id']
97
+ if plugin_id in enabled:
98
+ manager.load_plugin(
99
+ plugin_id,
100
+ plugin_config.get('config', {}),
101
+ priority=plugin_config.get('priority') or 0,
102
+ )
103
+ else:
104
+ # Recorded rather than passed over: a plugin switched off and a
105
+ # plugin that fell over look the same from outside.
106
+ manager.record_outcome(plugin_id, OUTCOME_DISABLED)
107
+
108
+ if await manager.initialize_plugins():
109
+ logger.info("All plugins initialized successfully")
110
+ else:
111
+ logger.error("Some plugins failed to initialize")
112
+
113
+ initialized = sum(1 for plugin_id in enablement.declared_plugins(config)
114
+ if manager.get_outcome(plugin_id['id'])[0] == OUTCOME_INITIALIZED)
115
+ declared = len(enablement.declared_plugins(config))
116
+ logger.info(f"Plugins: initialized {initialized} of {declared} declared")
117
+
118
+ await register_plugin_routes(app, manager)
119
+ return resolution
120
+
121
+ except Exception as e:
122
+ logger.error(f"Error initializing plugins: {str(e)}")
123
+
124
+
125
+ async def run_post_construct_processors(manager):
126
+ """Run every plugin's post-construct method in a separate executor."""
127
+ try:
128
+ logger.info("Starting post-construct processors in background...")
129
+
130
+ with concurrent.futures.ThreadPoolExecutor(max_workers=3, thread_name_prefix="post_construct") as executor:
131
+ tasks = []
132
+
133
+ for plugin_id, plugin in manager.plugins.items():
134
+ if plugin.initialized and callable(getattr(plugin, 'post_construct', None)):
135
+ task = asyncio.get_event_loop().run_in_executor(
136
+ executor,
137
+ _run_plugin_post_construct_sync,
138
+ plugin_id, plugin
139
+ )
140
+ tasks.append(task)
141
+ if tasks:
142
+ done, pending = await asyncio.wait(tasks, timeout=300)
143
+
144
+ for task in pending:
145
+ task.cancel()
146
+
147
+ logger.info(f"Post-construct completed: {len(done)} successful, {len(pending)} timed out/cancelled")
148
+
149
+ logger.info("All post-construct processors completed")
150
+
151
+ except Exception as e:
152
+ logger.error(f"Error running post-construct processors: {str(e)}")
153
+
154
+
155
+ def _run_plugin_post_construct_sync(plugin_id: str, plugin):
156
+ """Synchronous wrapper running post_construct in its own thread."""
157
+ try:
158
+ logger.info(f"Running post-construct for plugin: {plugin_id}")
159
+ loop = asyncio.new_event_loop()
160
+ asyncio.set_event_loop(loop)
161
+
162
+ try:
163
+ result = loop.run_until_complete(plugin.post_construct())
164
+ logger.info(f"Post-construct completed for plugin: {plugin_id}")
165
+ return result
166
+ finally:
167
+ loop.close()
168
+
169
+ except Exception as e:
170
+ logger.error(f"Error in post-construct for plugin {plugin_id}: {str(e)}")
171
+ return None