patch_app_reporter.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """补齐新 App 容器的公开通道上报;不让心跳覆盖业务 status。"""
  2. import ast
  3. from pathlib import Path
  4. import sys
  5. MARKER = "def _fmode_channel_snapshot():"
  6. HELPER = '''def _fmode_channel_snapshot():
  7. import json as _json
  8. import os as _os
  9. import time as _time
  10. from pathlib import Path as _Path
  11. home = _Path(_os.environ.get("HERMES_HOME", "/opt/data"))
  12. try:
  13. platforms = _json.loads((home / "gateway_state.json").read_text()).get("platforms") or {}
  14. except (OSError, ValueError, TypeError, AttributeError):
  15. platforms = {}
  16. if not isinstance(platforms, dict):
  17. platforms = {}
  18. def _state(name):
  19. entry = platforms.get(name)
  20. return entry.get("state", "unknown") if isinstance(entry, dict) else "unknown"
  21. # Report every platform the gateway knows about: the status function merges
  22. # channels per key, so a Matrix-only snapshot would hide a connected WeCom bot.
  23. state = _state("matrix")
  24. snapshot = {"matrix": state == "connected", "matrixConfig": {
  25. "homeserver": _os.environ.get("MATRIX_HOMESERVER", "https://matrix.fmode.cn"),
  26. "userId": _os.environ.get("MATRIX_USER_ID", ""),
  27. "channelState": state,
  28. "listenerOk": state == "connected",
  29. }}
  30. wecom_state = _state("wecom")
  31. if "wecom" in platforms or _os.environ.get("WECOM_BOT_ID"):
  32. snapshot["wecom"] = wecom_state == "connected"
  33. snapshot["wecomConfig"] = {"botId": _os.environ.get("WECOM_BOT_ID", ""), "channelState": wecom_state}
  34. if _os.environ.get("WECOM_BOT_ID"):
  35. snapshot["wecomBotId"] = _os.environ["WECOM_BOT_ID"]
  36. snapshot["platformStates"] = {name: _state(name) for name in sorted(platforms)}
  37. snapshot["observedAt"] = int(_time.time() * 1000)
  38. return snapshot
  39. def _start_app_channels():
  40. import json as _json
  41. import threading as _threading
  42. import time as _time
  43. def publish():
  44. for _ in range(75):
  45. _time.sleep(2)
  46. channels = _fmode_channel_snapshot()
  47. if channels["matrix"]:
  48. try:
  49. if _push_with_sessions({"channels": _json.dumps(channels, ensure_ascii=False)}):
  50. _log("app matrix channels registered")
  51. return
  52. except Exception:
  53. pass
  54. _log("app matrix channels pending; heartbeat will retry")
  55. _threading.Thread(target=publish, name="app-channels", daemon=True).start()
  56. def _start_fmode_heartbeat():
  57. import os as _os
  58. import random as _random
  59. import threading as _threading
  60. import time as _time
  61. global _FMODE_HEARTBEAT_STARTED
  62. if globals().get("_FMODE_HEARTBEAT_STARTED"):
  63. return
  64. if _os.environ.get("AGENT_STATUS_ENABLED", "true").strip().lower() == "false":
  65. _log("app heartbeat disabled by configuration")
  66. return
  67. try:
  68. interval = max(60, int(_os.environ.get("AGENT_STATUS_HEARTBEAT", "3600")))
  69. jitter = max(0, min(900, int(_os.environ.get("AGENT_STATUS_JITTER", "900"))))
  70. except (TypeError, ValueError):
  71. interval, jitter = 3600, 900
  72. _FMODE_HEARTBEAT_STARTED = True
  73. def run():
  74. # Send one immediate liveness snapshot so a newly provisioned container can be verified.
  75. try:
  76. _heartbeat_once(0)
  77. except Exception as _exc:
  78. _log("app heartbeat failed: %s" % type(_exc).__name__)
  79. while True:
  80. _time.sleep(interval + _random.uniform(0, jitter))
  81. try:
  82. _heartbeat_once(0)
  83. except Exception as _exc:
  84. _log("app heartbeat failed: %s" % type(_exc).__name__)
  85. _threading.Thread(target=run, name="fmode-jittered-heartbeat", daemon=True).start()
  86. '''
  87. def patch_text(source):
  88. tree = ast.parse(source)
  89. heartbeat = next((node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_heartbeat_once"), None)
  90. if heartbeat is None:
  91. raise ValueError("Reporter heartbeat function is missing")
  92. if len(heartbeat.args.args) != 1 or heartbeat.args.args[0].arg != "jitter":
  93. raise ValueError("Reporter heartbeat signature differs from verified baseline")
  94. business_fields = {"status", "currentTask", "currentAction", "progress"}
  95. if any(isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value in business_fields
  96. for node in ast.walk(heartbeat)):
  97. raise ValueError("Unsupported reporter: heartbeat writes business state")
  98. if MARKER in source:
  99. tree = ast.parse(source)
  100. functions = {node.name: node for node in tree.body if isinstance(node, ast.FunctionDef)}
  101. register = functions.get("register")
  102. startup_calls = set()
  103. if register:
  104. startup_calls = {
  105. node.func.id for node in ast.walk(register)
  106. if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
  107. }
  108. if ("_fmode_channel_snapshot" not in functions or
  109. "_start_app_channels" not in functions or
  110. "_start_fmode_heartbeat" not in functions or
  111. 'fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)' not in source or
  112. not {"_start_app_channels", "_start_fmode_heartbeat"}.issubset(startup_calls)):
  113. raise ValueError("Reporter contains an incomplete App-channel patch")
  114. return source
  115. anchor = ' fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}'
  116. if source.count(anchor) != 1 or source.count("def _heartbeat_once(") != 1:
  117. raise ValueError("Reporter differs from verified source; refusing to patch")
  118. source = source.replace("def _heartbeat_once(", HELPER + "def _heartbeat_once(", 1)
  119. source = source.replace(anchor, anchor + '\n fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)', 1)
  120. start = " _start_heartbeat()\n"
  121. if source.count(start) != 1:
  122. raise ValueError("Reporter startup differs from verified source")
  123. source = source.replace(start, " _start_fmode_heartbeat()\n _start_app_channels()\n", 1)
  124. ast.parse(source)
  125. return source
  126. def main():
  127. if len(sys.argv) != 2:
  128. raise ValueError("Provide one copied App-container reporter path")
  129. target = Path(sys.argv[1]).resolve(strict=True)
  130. root = Path("/opt/fmode-containers").resolve(strict=True)
  131. relative = target.relative_to(root)
  132. if (not relative.parts[0].startswith("agent-node-app-") or
  133. relative.parts[1:] != ("data", "plugins", "plugin-active-reporter", "__init__.py")):
  134. raise ValueError("Only a copied App-container reporter can be patched")
  135. original = target.read_text()
  136. updated = patch_text(original)
  137. if updated != original:
  138. backup = target.with_suffix(".py.before-app-channels")
  139. if not backup.exists():
  140. backup.write_text(original)
  141. target.write_text(updated)
  142. print("Reporter channels patch verified:", relative.parts[0])
  143. if __name__ == "__main__":
  144. main()