g3w-admin-plugins 0.0.1__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.
g3w_plugins/manager.py ADDED
@@ -0,0 +1,281 @@
1
+ """Maintain the plugin catalog, isolated installations and desired application state."""
2
+
3
+ import contextlib
4
+ import importlib.metadata
5
+ import importlib.util
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import uuid
14
+
15
+ from packaging.version import InvalidVersion, Version
16
+
17
+
18
+ CATALOG = {
19
+ "g3w-admin-authjwt": "authjwt",
20
+ "g3w-admin-panoramax": "panoramax",
21
+ "g3w-admin-pdnd": "qpdnd",
22
+ "g3w-admin-portal": "portal",
23
+ "g3w-admin-processing": "qprocessing",
24
+ "g3w-admin-ps-timeseries": "qps_timeseries",
25
+ "g3w-admin-sentry-monitor": "sentry_monitor",
26
+ }
27
+ BUNDLED = {name: name for name in ("editing", "filemanager", "qplotly", "qtimeseries")}
28
+ MANAGED = {**CATALOG, **BUNDLED}
29
+
30
+ DOCKER_PLUGIN_DIR = Path("/shared-volume/.g3w_plugins")
31
+
32
+ configured_state = None
33
+
34
+
35
+ def in_docker():
36
+ return Path("/.dockerenv").is_file()
37
+
38
+
39
+ def directory():
40
+ """Resolve the persistent state directory, using the Docker default when available."""
41
+ value = os.environ.get("G3W_PLUGINS_DIR")
42
+ if not value and in_docker():
43
+ value = str(DOCKER_PLUGIN_DIR)
44
+ os.environ["G3W_PLUGINS_DIR"] = value
45
+ if not value:
46
+ raise RuntimeError("Set G3W_PLUGINS_DIR to a persistent, writable directory")
47
+ return Path(value).resolve()
48
+
49
+
50
+ def read_state(path=None):
51
+ """Read and validate a published or candidate state; missing state preserves existing apps."""
52
+ path = path or directory() / "state.json"
53
+ if not path.exists():
54
+ return {"plugins": {}, "site": None}
55
+ with path.open(encoding="utf-8") as file:
56
+ state = json.load(file)
57
+ if (
58
+ not isinstance(state, dict)
59
+ or not isinstance(state.get("plugins"), dict)
60
+ or any(name not in MANAGED or type(enabled) is not bool
61
+ for name, enabled in state["plugins"].items())
62
+ or (state.get("site") is not None
63
+ and (not isinstance(state["site"], str)
64
+ or not state["site"].startswith("site-")
65
+ or len(state["site"]) != 37
66
+ or any(c not in "0123456789abcdef" for c in state["site"][5:])))
67
+ or (any(enabled for name, enabled in state["plugins"].items() if name in CATALOG)
68
+ and state.get("site") is None)
69
+ ):
70
+ raise ValueError(f"Invalid plugin state: {path}")
71
+ return state
72
+
73
+
74
+ @contextlib.contextmanager
75
+ def locked(root, blocking=True):
76
+ """Serialize configuration changes across processes sharing the state directory."""
77
+ root.mkdir(parents=True, exist_ok=True)
78
+ if os.name == "nt":
79
+ from .windows_locks import Lock
80
+ with Lock(root, "change", blocking) as lock:
81
+ yield lock
82
+ return
83
+ with (root / ".lock").open("a+b") as lock:
84
+ import fcntl
85
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
86
+ try:
87
+ yield lock
88
+ finally:
89
+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
90
+
91
+
92
+ @contextlib.contextmanager
93
+ def child_lock_options(lock):
94
+ """Keep the change and background-job locks alive in preparation subprocesses."""
95
+ if os.name == "nt":
96
+ from .windows_locks import inherited
97
+ handles = [lock.handle]
98
+ job_handle = os.environ.get("G3W_PLUGINS_JOB_HANDLE")
99
+ if job_handle:
100
+ handles.append(int(job_handle))
101
+ with inherited(handles) as options:
102
+ yield options
103
+ else:
104
+ job_fd = os.environ.get("G3W_PLUGINS_JOB_FD")
105
+ yield {"pass_fds": (lock.fileno(),) + ((int(job_fd),) if job_fd else ())}
106
+
107
+
108
+ def normalized(name):
109
+ return name.lower().replace("_", "-").replace(".", "-")
110
+
111
+
112
+ def validate_change(name, enabled):
113
+ if name not in MANAGED:
114
+ raise ValueError(f"Unknown plugin: {name}")
115
+ if name == "editing" and not enabled:
116
+ from django.apps import apps
117
+ if not apps.ready:
118
+ raise RuntimeError("Django must be initialized to check dependencies before disabling editing")
119
+ if apps.is_installed("qes"):
120
+ raise RuntimeError("qes requires editing. Disable qes before disabling editing.")
121
+
122
+
123
+ def change(name, enabled, prepare=None, progress=None, update_version=None, unmanaged_enabled=False):
124
+ """Prepare a change under lock and publish its candidate state only after preparation succeeds.
125
+
126
+ Preparation may change the database or static files even if publication fails. Installed
127
+ package directories are retained for workers still using the previous configuration.
128
+ """
129
+ validate_change(name, enabled)
130
+ if update_version is not None and name in BUNDLED:
131
+ raise ValueError("Bundled modules are updated with G3W-SUITE, not PyPI")
132
+ root = directory()
133
+ with locked(root) as lock:
134
+ state = read_state()
135
+ if name in BUNDLED and enabled:
136
+ try:
137
+ available = importlib.util.find_spec(name) is not None
138
+ except (ImportError, ValueError) as error:
139
+ raise RuntimeError(f"Cannot locate bundled module {name}: {error}") from error
140
+ if not available:
141
+ raise RuntimeError(f"Bundled module {name} is not available in this G3W-SUITE installation")
142
+ if update_version is not None:
143
+ if not state["plugins"].get(name, unmanaged_enabled):
144
+ raise ValueError("Only enabled plugins can be updated")
145
+ try:
146
+ requested = Version(update_version)
147
+ except InvalidVersion as error:
148
+ raise ValueError("Invalid update version") from error
149
+ if requested.is_prerelease or requested.is_devrelease:
150
+ raise ValueError("Only stable plugin releases can be installed")
151
+ if name in state["plugins"]:
152
+ site = root / state["site"]
153
+ versions = {
154
+ normalized(dist.metadata["Name"]): dist.version
155
+ for dist in importlib.metadata.distributions(path=[str(site)])
156
+ if dist.metadata.get("Name")
157
+ }
158
+ current = versions.get(name)
159
+ else:
160
+ try:
161
+ current = importlib.metadata.version(name)
162
+ except importlib.metadata.PackageNotFoundError:
163
+ current = None
164
+ versions = {}
165
+ try:
166
+ if not current or requested <= Version(current):
167
+ raise ValueError("The requested version is not newer than the installed version")
168
+ except InvalidVersion as error:
169
+ raise ValueError("The installed plugin version is invalid") from error
170
+ state["plugins"][name] = enabled
171
+ selected = [plugin for plugin, active in state["plugins"].items() if active and plugin in CATALOG]
172
+ if enabled and name in CATALOG:
173
+ if progress:
174
+ progress("install")
175
+ site = "site-" + uuid.uuid4().hex
176
+ target = root / site
177
+ # Keep G3W's existing dependency versions; incompatible plugins fail installation.
178
+ constraints = root / ("constraints-" + uuid.uuid4().hex + ".txt")
179
+ try:
180
+ packages = {}
181
+ for dist in importlib.metadata.distributions():
182
+ package = dist.metadata.get("Name")
183
+ if package and normalized(package) not in CATALOG:
184
+ packages.setdefault(normalized(package), dist.version)
185
+ constraints.write_text(
186
+ "".join(f"{package}=={version}\n" for package, version in packages.items()),
187
+ encoding="utf-8",
188
+ )
189
+ if update_version is not None:
190
+ if state["site"] and not versions:
191
+ versions = {
192
+ normalized(dist.metadata["Name"]): dist.version
193
+ for dist in importlib.metadata.distributions(path=[str(root / state["site"])])
194
+ if dist.metadata.get("Name")
195
+ }
196
+ for plugin in selected:
197
+ if plugin != name and plugin not in versions:
198
+ raise RuntimeError(f"Installed version of {plugin} is missing; update aborted")
199
+ try:
200
+ selected = [
201
+ f"{plugin}=={requested if plugin == name else Version(versions[plugin])}"
202
+ for plugin in selected
203
+ ]
204
+ except InvalidVersion as error:
205
+ raise RuntimeError("Invalid installed plugin version; update aborted") from error
206
+ with child_lock_options(lock) as options:
207
+ subprocess.run(
208
+ [sys.executable, "-m", "pip", "install", "--disable-pip-version-check",
209
+ "--target", str(target), "--constraint", str(constraints), *selected],
210
+ check=True, capture_output=True, text=True, **options,
211
+ )
212
+ except subprocess.CalledProcessError as error:
213
+ shutil.rmtree(target, ignore_errors=True)
214
+ raise RuntimeError(f"Plugin installation failed:\n{error.stderr or error.stdout}") from error
215
+ finally:
216
+ constraints.unlink(missing_ok=True)
217
+ state["site"] = site
218
+ elif name in CATALOG and not selected:
219
+ state["site"] = None
220
+ with tempfile.NamedTemporaryFile(
221
+ mode="w", encoding="utf-8", dir=root, prefix=".state-", delete=False
222
+ ) as file:
223
+ temporary = Path(file.name)
224
+ try:
225
+ json.dump(state, file, sort_keys=True)
226
+ file.flush()
227
+ os.fsync(file.fileno())
228
+ except BaseException:
229
+ temporary.unlink(missing_ok=True)
230
+ raise
231
+ try:
232
+ if prepare:
233
+ prepare(temporary, lock)
234
+ if progress:
235
+ progress("save")
236
+ os.replace(temporary, root / "state.json")
237
+ finally:
238
+ temporary.unlink(missing_ok=True)
239
+ return state
240
+
241
+
242
+ def configure(apps):
243
+ """Apply published or candidate state before settings that depend on managed apps."""
244
+ global configured_state
245
+ candidate = os.environ.get("G3W_PLUGINS_CANDIDATE")
246
+ if candidate:
247
+ candidate = Path(candidate).resolve()
248
+ if candidate.parent != directory() or not candidate.name.startswith(".state-"):
249
+ raise RuntimeError("Invalid plugin preparation state")
250
+ if not candidate.is_file():
251
+ raise RuntimeError("Plugin preparation state is missing")
252
+ state = read_state(candidate)
253
+ if state["site"]:
254
+ site = directory() / state["site"]
255
+ if not site.is_dir():
256
+ raise RuntimeError(f"Plugin installation is missing: {site}")
257
+ base = {}
258
+ for dist in importlib.metadata.distributions():
259
+ name = dist.metadata.get("Name")
260
+ if name:
261
+ base.setdefault(normalized(name), dist.version)
262
+ for dist in importlib.metadata.distributions(path=[str(site)]):
263
+ name = dist.metadata.get("Name")
264
+ if name:
265
+ package = normalized(name)
266
+ if package not in CATALOG and package in base and base[package] != dist.version:
267
+ raise RuntimeError(
268
+ f"Plugin dependency {package}=={dist.version} conflicts with "
269
+ f"the installed version {base[package]}; reinstall the managed plugins"
270
+ )
271
+ sys.path.insert(0, str(site))
272
+ for package, enabled in state["plugins"].items():
273
+ app = MANAGED[package]
274
+ if not enabled or package in CATALOG:
275
+ apps[:] = [item for item in apps if item != app]
276
+ if enabled and app not in apps:
277
+ apps.append(app)
278
+ apps[:] = [app for app in apps if app != "g3w_plugins"]
279
+ if "g3w_plugins" not in apps:
280
+ apps.append("g3w_plugins")
281
+ configured_state = state
g3w_plugins/reload.py ADDED
@@ -0,0 +1,185 @@
1
+ """Prepare candidate configurations and coordinate web and consumer reloads."""
2
+
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ import time
14
+
15
+ from django.conf import settings
16
+
17
+ from . import manager
18
+ from .manager import child_lock_options, directory, locked, read_state
19
+
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def fingerprint(state):
25
+ return hashlib.sha256(json.dumps(state, sort_keys=True).encode()).hexdigest()
26
+
27
+
28
+ def write_json(path, value):
29
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as file:
30
+ temporary = Path(file.name)
31
+ try:
32
+ json.dump(value, file)
33
+ except BaseException:
34
+ temporary.unlink(missing_ok=True)
35
+ raise
36
+ try:
37
+ os.replace(temporary, path)
38
+ finally:
39
+ temporary.unlink(missing_ok=True)
40
+
41
+
42
+ def prepare(candidate, lock, progress=None):
43
+ """Run setup commands against the candidate without publishing it."""
44
+ manage = Path(settings.BASE_DIR).parent / "manage.py"
45
+ env = dict(os.environ, G3W_PLUGINS_CANDIDATE=str(candidate))
46
+ for args in (("migrate", "--noinput"), ("collectstatic", "--noinput"),
47
+ ("sitetree_resync_apps",)):
48
+ if progress:
49
+ progress(args[0])
50
+ try:
51
+ with child_lock_options(lock) as options:
52
+ subprocess.run([sys.executable, str(manage), *args], env=env, check=True,
53
+ capture_output=True, text=True, timeout=600, **options)
54
+ except subprocess.CalledProcessError as error:
55
+ detail = error.stderr or error.stdout
56
+ raise RuntimeError(
57
+ f"Preparation failed during {args[0]}: {detail}. "
58
+ "Some database or static changes may already have been applied."
59
+ ) from error
60
+ except subprocess.TimeoutExpired as error:
61
+ raise RuntimeError(
62
+ f"Preparation timed out during {args[0]}; some changes may already have been applied."
63
+ ) from error
64
+
65
+
66
+ def available():
67
+ return sys.platform.startswith("linux") and os.environ.get("G3WSUITE_CONSUMER") == "1"
68
+
69
+
70
+ def consumer_enabled():
71
+ return os.environ.get("G3WSUITE_RUN_HUEY", "").lower() == "true"
72
+
73
+
74
+ def consumer_applied(target, requested_at, now):
75
+ if not target or not isinstance(requested_at, (int, float)):
76
+ return False
77
+ try:
78
+ with (directory() / "consumer-heartbeat.json").open(encoding="utf-8") as file:
79
+ heartbeat = json.load(file)
80
+ timestamp = heartbeat["time"]
81
+ return (
82
+ isinstance(timestamp, (int, float))
83
+ and requested_at <= timestamp <= now
84
+ and now - timestamp <= 15
85
+ and heartbeat.get("ready") is True
86
+ and heartbeat.get("state") == target
87
+ )
88
+ except FileNotFoundError:
89
+ return False
90
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
91
+ logger.warning("Cannot read consumer heartbeat", exc_info=True)
92
+ return False
93
+
94
+
95
+ def master_pid():
96
+ if not available():
97
+ raise RuntimeError("Process reload is available only in the G3W Docker web service")
98
+ pid = os.getppid()
99
+ command = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
100
+ if not any(Path(os.fsdecode(arg)).name in ("gunicorn", "granian") for arg in command if arg):
101
+ raise RuntimeError("Cannot identify the Gunicorn or Granian master process")
102
+ return pid
103
+
104
+
105
+ def open_master():
106
+ if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):
107
+ raise RuntimeError("Automatic reload requires Linux pidfd support")
108
+ pid = master_pid()
109
+ fd = os.pidfd_open(pid)
110
+ try:
111
+ if master_pid() != pid:
112
+ raise RuntimeError("The web master changed while starting preparation")
113
+ except BaseException:
114
+ os.close(fd)
115
+ raise
116
+ return fd
117
+
118
+
119
+ def request_reload(pidfd=None, expected_state=None):
120
+ """Request reload only while the published configuration remains unchanged."""
121
+ pid = master_pid() if pidfd is None else None
122
+ root = directory()
123
+ try:
124
+ with locked(root, blocking=False):
125
+ state = read_state()
126
+ if expected_state is not None and fingerprint(state) != expected_state:
127
+ raise RuntimeError("The plugin configuration changed after preparation; retry the reload")
128
+ if consumer_enabled():
129
+ try:
130
+ with (root / "consumer-heartbeat.json").open(encoding="utf-8") as file:
131
+ heartbeat = json.load(file)
132
+ if time.time() - heartbeat["time"] > 15:
133
+ raise ValueError("heartbeat expired")
134
+ except (OSError, ValueError, KeyError, TypeError) as error:
135
+ raise RuntimeError(
136
+ "The consumer reload watcher is unavailable. Restart the consumer manually once."
137
+ ) from error
138
+ write_json(root / "reload-request.json", {"state": fingerprint(state)})
139
+ try:
140
+ if pidfd is None:
141
+ os.kill(pid, signal.SIGHUP)
142
+ else:
143
+ signal.pidfd_send_signal(pidfd, signal.SIGHUP)
144
+ except OSError as error:
145
+ raise RuntimeError(
146
+ f"Web reload failed: {error}. Restart the web and consumer manually."
147
+ ) from error
148
+ return fingerprint(state)
149
+ except BlockingIOError as error:
150
+ raise RuntimeError("A plugin change is still running; retry after preparation completes") from error
151
+
152
+
153
+ def watch_consumer(initial_state):
154
+ root = directory()
155
+ heartbeat = root / "consumer-heartbeat.json"
156
+ request = root / "reload-request.json"
157
+ while True:
158
+ try:
159
+ handler = signal.getsignal(signal.SIGHUP)
160
+ if getattr(handler, "__name__", "") == "_handle_restart_signal":
161
+ root.mkdir(parents=True, exist_ok=True)
162
+ consumer = handler.__self__
163
+ ready = (
164
+ not consumer._received_signal
165
+ and consumer.environment.is_alive(consumer.scheduler)
166
+ and all(consumer.environment.is_alive(worker) for _, worker in consumer.worker_threads)
167
+ )
168
+ write_json(heartbeat, {"time": time.time(), "state": initial_state, "ready": ready})
169
+ if request.exists():
170
+ with request.open(encoding="utf-8") as file:
171
+ target = json.load(file)["state"]
172
+ if target != initial_state and target == fingerprint(read_state()):
173
+ os.kill(os.getpid(), signal.SIGHUP)
174
+ return
175
+ except (OSError, ValueError, KeyError, TypeError):
176
+ logger.exception("Plugin consumer reload watcher failed; retrying")
177
+ time.sleep(2)
178
+
179
+
180
+ def start_consumer_watcher():
181
+ if manager.configured_state is None:
182
+ logger.error("Plugin consumer reload watcher unavailable: manager was not configured")
183
+ return
184
+ initial_state = fingerprint(manager.configured_state)
185
+ threading.Thread(target=watch_consumer, args=(initial_state,), daemon=True).start()
@@ -0,0 +1,20 @@
1
+ from sitetree.utils import item
2
+ from core.utils.tree import G3Wtree
3
+
4
+
5
+ sitetrees = (
6
+ G3Wtree(
7
+ "plugins",
8
+ title="Plugin",
9
+ module="g3w_plugins",
10
+ items=[item("Plugin", "g3w-plugins", url_as_pattern=True,
11
+ icon_css_class="fa fa-puzzle-piece", access_by_perms=["auth.change_user"])],
12
+ ),
13
+ G3Wtree(
14
+ "plugins_en",
15
+ title="Plugins",
16
+ module="g3w_plugins",
17
+ items=[item("Plugin", "g3w-plugins", url_as_pattern=True,
18
+ icon_css_class="fa fa-puzzle-piece", access_by_perms=["auth.change_user"])],
19
+ ),
20
+ )