-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·185 lines (169 loc) · 7.94 KB
/
Copy pathserver.py
File metadata and controls
executable file
·185 lines (169 loc) · 7.94 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#!/usr/bin/env python3
import http.server
import socketserver
import json
import urllib.request
import os
import sys
# Helper to load .env file manually without external dependencies
def load_dotenv():
# Look for .env in the same directory as the script
script_dir = os.path.dirname(os.path.abspath(__file__))
env_path = os.path.join(script_dir, ".env")
if os.path.exists(env_path):
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, val = line.split("=", 1)
# Strip quotes if present
val = val.strip().strip("'").strip('"')
os.environ[key.strip()] = val
# Load .env variables
load_dotenv()
# Make the Gemini Orchestrator + Splunk MCP layer importable from ./agent
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "agent"))
try:
from app import GeminiOrchestrator
ORCHESTRATOR_AVAILABLE = True
except Exception as _e: # pragma: no cover - keeps the static dashboard usable alone
print(f"[server] Orchestrator import failed ({_e}); /api/triage disabled.")
ORCHESTRATOR_AVAILABLE = False
PORT = int(os.environ.get("PORT", 8050))
SPLUNK_HEC_URL = os.environ.get("SPLUNK_HEC_URL", "https://<your-stack>.splunkcloud.com:8088/services/collector")
SPLUNK_HEC_TOKEN = os.environ.get("SPLUNK_HEC_TOKEN", "")
class DashboardHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, format, *args):
# Suppress logging to stdout to keep console clean
pass
def do_GET(self):
if self.path == "/" or self.path == "/index.html":
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
try:
# Change directory to script location to load dashboard.html
script_dir = os.path.dirname(os.path.abspath(__file__))
dashboard_path = os.path.join(script_dir, "dashboard.html")
with open(dashboard_path, "r", encoding="utf-8") as f:
self.wfile.write(f.read().encode("utf-8"))
except Exception as e:
self.wfile.write(f"Error loading dashboard.html: {str(e)}".encode("utf-8"))
elif self.path == "/fleetmng" or self.path == "/fleetmng/":
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
fleetmng_path = os.path.join(script_dir, "fleetmng.html")
with open(fleetmng_path, "r", encoding="utf-8") as f:
self.wfile.write(f.read().encode("utf-8"))
except Exception as e:
self.wfile.write(f"Error loading fleetmng.html: {str(e)}".encode("utf-8"))
elif self.path in ["/architecture_diagram.png", "/robot_fleet_digital_twin.png"]:
self.send_response(200)
self.send_header("Content-type", "image/png")
self.end_headers()
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
img_path = os.path.join(script_dir, self.path.lstrip("/"))
with open(img_path, "rb") as f:
self.wfile.write(f.read())
except Exception as e:
self.wfile.write(f"Error loading image {self.path}: {str(e)}".encode("utf-8"))
elif self.path == "/api/status":
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
status = {
"fleet_telemetry": "LIVE",
"splunk_hec": "ACTIVE",
"mcp_server": "ACTIVE",
"gemini_orchestrator": "ACTIVE"
}
self.wfile.write(json.dumps(status).encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
if self.path == "/api/triage":
# Run the real closed loop: Splunk MCP context -> Gemini triage -> action plan.
content_length = int(self.headers.get('Content-Length', 0))
post_data = self.rfile.read(content_length).decode('utf-8') if content_length else "{}"
try:
req = json.loads(post_data) if post_data.strip() else {}
channel = req.get("channel", "Operational")
robot_id = req.get("robot_id")
site_id = req.get("site_id")
if not ORCHESTRATOR_AVAILABLE:
raise RuntimeError("Orchestrator not available on this server")
orchestrator = GeminiOrchestrator()
result = orchestrator.run_triage_loop(
query_type=channel, robot_id=robot_id, site_id=site_id, verbose=False
)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({
"status": "success",
"mode": result["mode"],
"mcp_logs": result["mcp_logs"],
"decision": result["decision"],
"dispatch": result["dispatch"],
}).encode('utf-8'))
except Exception as e:
self.send_response(500)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode('utf-8'))
elif self.path == "/api/trigger":
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
try:
payload = json.loads(post_data)
# Wrap the event for Splunk HEC
splunk_payload = {
"event": payload,
"index": "main",
"sourcetype": "_json"
}
# Post to Splunk HEC using urllib
req = urllib.request.Request(
SPLUNK_HEC_URL,
data=json.dumps(splunk_payload).encode('utf-8'),
headers={
"Authorization": f"Splunk {SPLUNK_HEC_TOKEN}",
"Content-Type": "application/json"
},
method="POST"
)
with urllib.request.urlopen(req) as response:
res_data = response.read().decode('utf-8')
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({
"status": "success",
"splunk_response": json.loads(res_data)
}).encode('utf-8'))
except Exception as e:
self.send_response(500)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({
"status": "error",
"message": str(e)
}).encode('utf-8'))
else:
self.send_response(404)
self.end_headers()
if __name__ == "__main__":
# Change working directory to script location
os.chdir(os.path.dirname(os.path.abspath(__file__)))
socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(("", PORT), DashboardHandler) as httpd:
print(f"Forenly Splunk-Agentic-Ops Dashboard serving on port {PORT}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass