-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdaemon.py
More file actions
293 lines (243 loc) · 8.18 KB
/
daemon.py
File metadata and controls
293 lines (243 loc) · 8.18 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
"""Daemon process: runs orchestrator + web dashboard in background."""
import datetime
import logging
import os
import signal
import subprocess
import sys
import time
from typing import Optional
import uvicorn
from core.config import load_config
from core.orchestrator import Orchestrator
from web.app import app, set_orchestrator
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
def _pid_file_path(config: dict) -> str:
configured = str(config.get("regression", {}).get("pid_file", "")).strip()
if configured:
return configured
return os.path.join(PROJECT_ROOT, "data", "daemon.pid")
def setup_logging(config: dict) -> str:
"""Configure logging to a timestamped file. Returns the actual log file path."""
base = config["logging"]["file"] # e.g. logs/agent.log
stem, ext = os.path.splitext(base)
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = f"{stem}_{ts}{ext}"
os.makedirs(os.path.dirname(log_file), exist_ok=True)
level = getattr(logging, config["logging"]["level"].upper(), logging.INFO)
logging.basicConfig(
level=level,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.FileHandler(log_file),
],
)
return log_file
def write_pid(pid_file: str):
os.makedirs(os.path.dirname(pid_file), exist_ok=True)
with open(pid_file, "w") as f:
f.write(str(os.getpid()))
def remove_pid(pid_file: str):
if os.path.exists(pid_file):
os.remove(pid_file)
def read_pid(pid_file: str) -> int:
if os.path.exists(pid_file):
with open(pid_file) as f:
try:
return int(f.read().strip())
except ValueError:
return 0
return 0
def _is_pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def _find_listener_pid(port: int) -> int:
"""Return the process id listening on *port* (0 if none/unknown)."""
try:
result = subprocess.run(
["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"],
capture_output=True,
text=True,
timeout=3,
check=False,
)
except Exception:
return 0
for line in result.stdout.splitlines():
s = line.strip()
if s.isdigit():
return int(s)
return 0
def _pid_matches_project(pid: int) -> bool:
"""Best-effort check whether PID belongs to this project's daemon process."""
if pid <= 0:
return False
try:
cwd = os.readlink(f"/proc/{pid}/cwd")
except OSError:
cwd = ""
if cwd.startswith(PROJECT_ROOT):
return True
try:
with open(f"/proc/{pid}/cmdline", "rb") as f:
cmdline = f.read().replace(b"\x00", b" ").decode(errors="ignore")
except OSError:
cmdline = ""
return "multi-agent-todo" in cmdline
def _wait_until_stopped(pid: int, timeout_sec: float = 5.0) -> bool:
deadline = time.time() + timeout_sec
while time.time() < deadline:
if not _is_pid_alive(pid):
return True
time.sleep(0.1)
return not _is_pid_alive(pid)
def _terminate_pid(pid: int) -> bool:
"""Terminate process politely, then force kill if needed."""
if not _is_pid_alive(pid):
return True
try:
os.kill(pid, signal.SIGTERM)
except OSError:
return True
if _wait_until_stopped(pid, timeout_sec=5.0):
return True
try:
os.kill(pid, signal.SIGKILL)
except OSError:
return True
return _wait_until_stopped(pid, timeout_sec=2.0)
def is_running() -> bool:
config = load_config(None)
pid = read_pid(_pid_file_path(config))
return _is_pid_alive(pid)
def start(config_path: Optional[str] = None, foreground: bool = False):
"""Start the daemon."""
config = load_config(config_path)
port = int(config["web"]["port"])
pid_file = _pid_file_path(config)
pid = read_pid(pid_file)
if pid and _is_pid_alive(pid):
print(f"Daemon already running (pid={pid})")
return
if pid and not _is_pid_alive(pid):
remove_pid(pid_file)
listener_pid = _find_listener_pid(port)
if listener_pid:
if _pid_matches_project(listener_pid):
print(f"Daemon already running (pid={listener_pid})")
else:
print(
f"Cannot start daemon: port {port} is already in use by pid={listener_pid}."
)
return
if not foreground:
# Fork to background — logging is set up only in the child
pid = os.fork()
if pid > 0:
# Parent: wait briefly to verify child actually bound the port.
deadline = time.time() + 5.0
started = False
while time.time() < deadline:
if not _is_pid_alive(pid):
break
if _find_listener_pid(port) == pid:
started = True
break
time.sleep(0.1)
if started:
print(f"Daemon started (pid={pid})")
print(f"Dashboard: http://localhost:{config['web']['port']}")
print(
f"Logs: {os.path.dirname(os.path.abspath(config['logging']['file']))}"
)
else:
print(
f"Daemon failed to start (pid={pid}). "
f"Check logs under {os.path.dirname(os.path.abspath(config['logging']['file']))}."
)
return
# Child process
os.setsid()
log_file = setup_logging(config)
log = logging.getLogger("daemon")
log.info("Log file: %s", log_file)
write_pid(pid_file)
log.info("Daemon starting (pid=%d)", os.getpid())
def handle_signal(signum, frame):
log.info("Received signal %d, shutting down...", signum)
orch.stop()
remove_pid(pid_file)
sys.exit(0)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
# Initialize orchestrator
orch = Orchestrator(config)
set_orchestrator(orch)
# Start orchestrator loop
orch.start()
log.info(
"Orchestrator started, launching web dashboard on port %d",
config["web"]["port"],
)
# Run web server (blocks)
try:
uvicorn.run(
app,
host=config["web"]["host"],
port=config["web"]["port"],
log_level="warning",
)
finally:
try:
orch.stop()
except Exception:
pass
remove_pid(pid_file)
def stop(config_path: Optional[str] = None):
"""Stop the daemon."""
config = load_config(config_path)
port = int(config["web"]["port"])
pid_file = _pid_file_path(config)
pid = read_pid(pid_file)
stopped_pids = []
if pid and _is_pid_alive(pid):
if _terminate_pid(pid):
stopped_pids.append(pid)
elif pid:
remove_pid(pid_file)
listener_pid = _find_listener_pid(port)
if listener_pid and listener_pid not in stopped_pids:
if _pid_matches_project(listener_pid):
if _terminate_pid(listener_pid):
stopped_pids.append(listener_pid)
else:
print(
f"Port {port} is occupied by non-project pid={listener_pid}; not terminating it."
)
if stopped_pids:
print("Daemon stopped (pid=" + ",".join(str(p) for p in stopped_pids) + ")")
else:
print("Daemon is not running")
remove_pid(pid_file)
def status(config_path: Optional[str] = None):
"""Check daemon status."""
config = load_config(config_path)
port = int(config["web"]["port"])
pid_file = _pid_file_path(config)
pid = read_pid(pid_file)
running = _is_pid_alive(pid)
listener_pid = _find_listener_pid(port)
if running:
print(f"Daemon is running (pid={pid})")
else:
print("Daemon is not running")
if pid:
remove_pid(pid_file)
if listener_pid and listener_pid != pid:
owner = "project" if _pid_matches_project(listener_pid) else "non-project"
print(f"Port {port} listener detected (pid={listener_pid}, owner={owner})")