-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
334 lines (285 loc) · 11.2 KB
/
main.py
File metadata and controls
334 lines (285 loc) · 11.2 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import subprocess
import threading
import argparse
import time
import json
import queue
import websocket
import asyncio
from pathlib import Path
from typing import Dict, Any
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, Request, Form, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
import uvicorn
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
SCRIPTS_DB = Path("scripts.json")
# -------------------- Persistence --------------------
def load_scripts() -> Dict[str, Any]:
if not SCRIPTS_DB.exists():
return {}
try:
return json.loads(SCRIPTS_DB.read_text())
except Exception:
return {}
def save_scripts(data: Dict[str, Any]):
SCRIPTS_DB.write_text(json.dumps(data, indent=2))
# -------------------- Runtime State --------------------
# processes[name] = {
# process, thread, status, start_time, output (str), returncode,
# policy, should_stop (bool), subscribers (set of Queue[str])
# }
processes: Dict[str, Dict[str, Any]] = {}
lock = threading.Lock()
def _broadcast_line(name: str, line: str):
with lock:
subs = processes.get(name, {}).get("subscribers", set()).copy()
for q in subs:
try:
q.put_nowait(line)
except queue.Full:
# drop if subscriber is slow
pass
def monitor_script(name: str, cmd: list, policy: str):
"""Run and monitor a script, restart based on policy, and stream output."""
while True:
with lock:
should_stop = processes[name].get("should_stop", False)
if should_stop:
with lock:
processes[name]["status"] = "stopped"
break
start_time = time.time()
# Merge stdout/stderr; decode as text
# proc = subprocess.Popen(
# cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
# )
script_path = Path(cmd[1]) # cmd looks like ["python3", path, ...]
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
cwd=script_path.parent # run in the script’s folder
)
with lock:
processes[name]["process"] = proc
processes[name]["status"] = "running"
processes[name]["start_time"] = start_time
processes[name].setdefault("output", "")
# Read live output line-by-line
assert proc.stdout is not None
for line in proc.stdout:
with lock:
processes[name]["output"] = (processes[name]["output"] + line)[-20000:] # keep last 20k chars
_broadcast_line(name, line)
proc.wait()
code = proc.returncode
with lock:
processes[name]["returncode"] = code
with lock:
should_stop = processes[name].get("should_stop", False)
if should_stop:
with lock:
processes[name]["status"] = "stopped"
break
if code != 0:
with lock:
processes[name]["status"] = "error"
if policy in ("on-failure", "always"):
time.sleep(2)
continue # restart
else:
with lock:
processes[name]["status"] = "stopped"
if policy == "always":
time.sleep(2)
continue
break
# -------------------- Pages & API --------------------
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
scripts = load_scripts()
# initialize runtime entries for known scripts
with lock:
for name, meta in scripts.items():
processes.setdefault(name, {"status": "stopped", "policy": meta.get("policy", "on-failure"), "subscribers": set(), "should_stop": False})
statuses = {}
with lock:
for name in scripts:
statuses[name] = processes.get(name, {}).get("status", "stopped")
return templates.TemplateResponse(
"index.html",
{"request": request, "scripts": scripts, "statuses": statuses},
)
@app.get("/script/{name}", response_class=HTMLResponse)
async def script_detail(request: Request, name: str):
scripts = load_scripts()
if name not in scripts:
return HTMLResponse("Script not found", status_code=404)
with lock:
pinfo = processes.get(name, {})
runtime = {
"status": pinfo.get("status", "stopped"),
"start_time": pinfo.get("start_time"),
"running_time": time.time() - pinfo["start_time"] if pinfo.get("start_time") else None,
"returncode": pinfo.get("returncode"),
"output": pinfo.get("output", "")[-2000:],
}
return templates.TemplateResponse(
"detail.html",
{"request": request, "name": name, "script": scripts[name], "runtime": runtime},
)
@app.get("/start/{name}")
async def start_script(name: str):
scripts = load_scripts()
if name not in scripts:
return HTMLResponse("Script not found", status_code=404)
with lock:
if processes.get(name, {}).get("status") == "running":
return RedirectResponse("/script/" + name, status_code=303)
# reset stop flag, output buffer
processes.setdefault(name, {}).update({
"should_stop": False,
"output": "",
"policy": scripts[name].get("policy", "on-failure"),
"subscribers": processes.get(name, {}).get("subscribers", set())
})
path = scripts[name]["path"]
args = scripts[name].get("args", [])
policy = scripts[name].get("policy", "on-failure")
with lock:
processes[name]["thread"] = t
t.start()
return RedirectResponse("/script/" + name, status_code=303)
@app.get("/stop/{name}")
async def stop_script(name: str):
with lock:
if name not in processes:
return RedirectResponse("/", status_code=303)
processes[name]["should_stop"] = True
proc = processes[name].get("process")
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except Exception:
proc.kill()
with lock:
processes[name]["status"] = "stopped"
return RedirectResponse("/script/" + name, status_code=303)
@app.get("/add", response_class=HTMLResponse)
async def add_form(request: Request):
return templates.TemplateResponse("add.html", {"request": request})
@app.post("/add")
async def add_script(path: str = Form(...), args: str = Form(""), policy: str = Form("on-failure")):
scripts = load_scripts()
name = Path(path).name
scripts[name] = {"path": path, "args": args.split() if args else [], "policy": policy}
save_scripts(scripts)
return RedirectResponse("/", status_code=303)
@app.post("/edit/{name}")
async def edit_script(name: str, args: str = Form(...), policy: str = Form(...)):
"""Update a script's arguments and policy."""
scripts = load_scripts()
if name in scripts:
scripts[name]["args"] = args.split() if args else []
scripts[name]["policy"] = policy
save_scripts(scripts)
# Update policy in runtime
with lock:
if name in processes:
processes[name]["policy"] = policy
return RedirectResponse(f"/script/{name}", status_code=303)
@app.post("/delete/{name}")
async def delete_script(name: str):
"""Delete a script: stop it and remove from config."""
# Stop the script if it's running
with lock:
if name in processes and processes[name].get("status") == "running":
processes[name]["should_stop"] = True
proc = processes[name].get("process")
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=2)
except Exception:
proc.kill()
processes.pop(name, None) # Remove from runtime
# Remove from config
scripts = load_scripts()
if name in scripts:
scripts.pop(name)
save_scripts(scripts)
return RedirectResponse("/", status_code=303)
# # -------------------- WebSockets --------------------
# @app.websocket("/ws/logs/{name}")
# async def ws_logs(websocket: WebSocket, name: str):
# await websocket.accept()
# # Subscribe this client to live lines
# q: queue.Queue[str] = queue.Queue(maxsize=1000)
# with lock:
# processes.setdefault(name, {}).setdefault("subscribers", set()).add(q)
# # send recent tail for context
# tail = processes.get(name, {}).get("output", "")[-2000:]
# if tail:
# await websocket.send_text(tail)
# try:
# while True:
# # Block until a new line arrives from the producer thread
# line = await websocket.loop.run_in_executor(None, q.get)
# await websocket.send_text(line)
# except WebSocketDisconnect:
# pass
# finally:
# with lock:
# subs = processes.get(name, {}).get("subscribers", set())
# if q in subs:
# subs.remove(q)
@app.websocket("/ws/logs/{name}")
async def ws_logs(websocket: WebSocket, name: str):
await websocket.accept()
q: queue.Queue[str] = queue.Queue(maxsize=1000)
with lock:
processes.setdefault(name, {}).setdefault("subscribers", set()).add(q)
tail = processes.get(name, {}).get("output", "")[-2000:]
if tail:
await websocket.send_text(tail)
try:
while True:
loop = asyncio.get_running_loop()
line = await loop.run_in_executor(None, q.get)
await websocket.send_text(line)
except WebSocketDisconnect:
pass
finally:
with lock:
subs = processes.get(name, {}).get("subscribers", set())
if q in subs:
subs.remove(q)
@app.websocket("/ws/status")
async def ws_status(websocket: WebSocket):
await websocket.accept()
try:
while True:
scripts = load_scripts()
snapshot = {}
with lock:
for name in scripts:
snapshot[name] = processes.get(name, {}).get("status", "stopped")
await websocket.send_json(snapshot)
await websocket.receive_text() # optional ping from client to keep alive
except Exception:
# Client disconnected or error; nothing to do
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Flask + D3 tree visualizer")
parser.add_argument("--file", default="dependencies.txt", help="Path to dependencies file")
parser.add_argument("--host", default="192.168.158.51", help="Host to bind")
parser.add_argument("--port", type=int, default=8000, help="Port to bind")
args = parser.parse_args()
uvicorn.run(app, host=args.host, port=args.port)