| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159 |
- """补齐新 App 容器的公开通道上报;不让心跳覆盖业务 status。"""
- import ast
- from pathlib import Path
- import sys
- MARKER = "def _fmode_channel_snapshot():"
- HELPER = '''def _fmode_channel_snapshot():
- import json as _json
- import os as _os
- import time as _time
- from pathlib import Path as _Path
- home = _Path(_os.environ.get("HERMES_HOME", "/opt/data"))
- try:
- platforms = _json.loads((home / "gateway_state.json").read_text()).get("platforms") or {}
- except (OSError, ValueError, TypeError, AttributeError):
- platforms = {}
- if not isinstance(platforms, dict):
- platforms = {}
- def _state(name):
- entry = platforms.get(name)
- return entry.get("state", "unknown") if isinstance(entry, dict) else "unknown"
- # Report every platform the gateway knows about: the status function merges
- # channels per key, so a Matrix-only snapshot would hide a connected WeCom bot.
- state = _state("matrix")
- snapshot = {"matrix": state == "connected", "matrixConfig": {
- "homeserver": _os.environ.get("MATRIX_HOMESERVER", "https://matrix.fmode.cn"),
- "userId": _os.environ.get("MATRIX_USER_ID", ""),
- "channelState": state,
- "listenerOk": state == "connected",
- }}
- wecom_state = _state("wecom")
- if "wecom" in platforms or _os.environ.get("WECOM_BOT_ID"):
- snapshot["wecom"] = wecom_state == "connected"
- snapshot["wecomConfig"] = {"botId": _os.environ.get("WECOM_BOT_ID", ""), "channelState": wecom_state}
- if _os.environ.get("WECOM_BOT_ID"):
- snapshot["wecomBotId"] = _os.environ["WECOM_BOT_ID"]
- snapshot["platformStates"] = {name: _state(name) for name in sorted(platforms)}
- snapshot["observedAt"] = int(_time.time() * 1000)
- return snapshot
- def _start_app_channels():
- import json as _json
- import threading as _threading
- import time as _time
- def publish():
- for _ in range(75):
- _time.sleep(2)
- channels = _fmode_channel_snapshot()
- if channels["matrix"]:
- try:
- if _push_with_sessions({"channels": _json.dumps(channels, ensure_ascii=False)}):
- _log("app matrix channels registered")
- return
- except Exception:
- pass
- _log("app matrix channels pending; heartbeat will retry")
- _threading.Thread(target=publish, name="app-channels", daemon=True).start()
- def _start_fmode_heartbeat():
- import os as _os
- import random as _random
- import threading as _threading
- import time as _time
- global _FMODE_HEARTBEAT_STARTED
- if globals().get("_FMODE_HEARTBEAT_STARTED"):
- return
- if _os.environ.get("AGENT_STATUS_ENABLED", "true").strip().lower() == "false":
- _log("app heartbeat disabled by configuration")
- return
- try:
- interval = max(60, int(_os.environ.get("AGENT_STATUS_HEARTBEAT", "3600")))
- jitter = max(0, min(900, int(_os.environ.get("AGENT_STATUS_JITTER", "900"))))
- except (TypeError, ValueError):
- interval, jitter = 3600, 900
- _FMODE_HEARTBEAT_STARTED = True
- def run():
- # Send one immediate liveness snapshot so a newly provisioned container can be verified.
- try:
- _heartbeat_once(0)
- except Exception as _exc:
- _log("app heartbeat failed: %s" % type(_exc).__name__)
- while True:
- _time.sleep(interval + _random.uniform(0, jitter))
- try:
- _heartbeat_once(0)
- except Exception as _exc:
- _log("app heartbeat failed: %s" % type(_exc).__name__)
- _threading.Thread(target=run, name="fmode-jittered-heartbeat", daemon=True).start()
- '''
- def patch_text(source):
- tree = ast.parse(source)
- heartbeat = next((node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_heartbeat_once"), None)
- if heartbeat is None:
- raise ValueError("Reporter heartbeat function is missing")
- if len(heartbeat.args.args) != 1 or heartbeat.args.args[0].arg != "jitter":
- raise ValueError("Reporter heartbeat signature differs from verified baseline")
- business_fields = {"status", "currentTask", "currentAction", "progress"}
- if any(isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value in business_fields
- for node in ast.walk(heartbeat)):
- raise ValueError("Unsupported reporter: heartbeat writes business state")
- if MARKER in source:
- tree = ast.parse(source)
- functions = {node.name: node for node in tree.body if isinstance(node, ast.FunctionDef)}
- register = functions.get("register")
- startup_calls = set()
- if register:
- startup_calls = {
- node.func.id for node in ast.walk(register)
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
- }
- if ("_fmode_channel_snapshot" not in functions or
- "_start_app_channels" not in functions or
- "_start_fmode_heartbeat" not in functions or
- 'fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)' not in source or
- not {"_start_app_channels", "_start_fmode_heartbeat"}.issubset(startup_calls)):
- raise ValueError("Reporter contains an incomplete App-channel patch")
- return source
- anchor = ' fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}'
- if source.count(anchor) != 1 or source.count("def _heartbeat_once(") != 1:
- raise ValueError("Reporter differs from verified source; refusing to patch")
- source = source.replace("def _heartbeat_once(", HELPER + "def _heartbeat_once(", 1)
- source = source.replace(anchor, anchor + '\n fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)', 1)
- start = " _start_heartbeat()\n"
- if source.count(start) != 1:
- raise ValueError("Reporter startup differs from verified source")
- source = source.replace(start, " _start_fmode_heartbeat()\n _start_app_channels()\n", 1)
- ast.parse(source)
- return source
- def main():
- if len(sys.argv) != 2:
- raise ValueError("Provide one copied App-container reporter path")
- target = Path(sys.argv[1]).resolve(strict=True)
- root = Path("/opt/fmode-containers").resolve(strict=True)
- relative = target.relative_to(root)
- if (not relative.parts[0].startswith("agent-node-app-") or
- relative.parts[1:] != ("data", "plugins", "plugin-active-reporter", "__init__.py")):
- raise ValueError("Only a copied App-container reporter can be patched")
- original = target.read_text()
- updated = patch_text(original)
- if updated != original:
- backup = target.with_suffix(".py.before-app-channels")
- if not backup.exists():
- backup.write_text(original)
- target.write_text(updated)
- print("Reporter channels patch verified:", relative.parts[0])
- if __name__ == "__main__":
- main()
|