-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_supervisor.py
More file actions
executable file
·2407 lines (2187 loc) · 87.5 KB
/
stack_supervisor.py
File metadata and controls
executable file
·2407 lines (2187 loc) · 87.5 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import fcntl
import html
import json
import os
import re
import signal
import socket
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from dataclasses import asdict, dataclass, field
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from typing import Any
try:
import tomllib
except ModuleNotFoundError: # pragma: no cover
import tomli as tomllib # type: ignore
ROOT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = ROOT_DIR / "stack-supervisor.toml"
def load_env(env_path: Path) -> dict[str, str]:
env = dict(os.environ)
if not env_path.exists():
return env
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
env[key.strip()] = value.strip()
return env
@dataclass
class SupervisorConfig:
default_profile: str
poll_interval_seconds: int
status_host: str
status_port: int
runtime_dir: Path
profiles: dict[str, list[str]]
memory_auto_start_soft_limit_gb: float
memory_hard_limit_gb: float
min_free_percent_for_conditional_start: float
max_swap_used_gb: float
heavy_model_budget_threshold_gb: float
max_auto_heavy_models: int
@dataclass
class ServiceConfig:
name: str
kind: str
command: list[str]
cwd: Path
port: int
health_url: str
health_headers: dict[str, str]
startup_grace_seconds: int
startup_timeout_seconds: int
restart_backoff_seconds: int
unhealthy_threshold: int
stop_timeout_seconds: int
watch_files: list[Path]
memory_budget_gb: float
on_demand: bool
pinned: bool
heavy_group: str | None = None
@dataclass
class ServiceRuntime:
name: str
desired: bool = False
desired_reason: str = "stopped"
status: str = "stopped"
pid: int | None = None
managed: bool = False
adopted: bool = False
healthy: bool = False
health_failures: int = 0
restart_count: int = 0
last_error: str | None = None
last_exit_code: int | None = None
last_start_time: float | None = None
last_healthy_time: float | None = None
next_restart_time: float = 0.0
startup_deadline: float = 0.0
observed_command: str | None = None
watch_fingerprint: dict[str, int] = field(default_factory=dict)
blocked_reason: str | None = None
log_path: str | None = None
last_probe_time: float | None = None
last_probe_ok: bool | None = None
last_probe_summary: str | None = None
last_probe_payload: dict[str, Any] | None = None
last_auto_start_time: float | None = None
last_used_time: float | None = None
last_denied_reason: str | None = None
eviction_protected: bool = False
def read_config(path: Path) -> tuple[SupervisorConfig, dict[str, ServiceConfig]]:
with path.open("rb") as handle:
raw = tomllib.load(handle)
supervisor_raw = raw["supervisor"]
memory_policy_raw = raw.get("memory_policy", {})
runtime_dir = (path.parent / supervisor_raw.get("runtime_dir", "./runtime")).resolve()
supervisor = SupervisorConfig(
default_profile=supervisor_raw["default_profile"],
poll_interval_seconds=int(supervisor_raw.get("poll_interval_seconds", 5)),
status_host=supervisor_raw.get("status_host", "127.0.0.1"),
status_port=int(supervisor_raw.get("status_port", 4060)),
runtime_dir=runtime_dir,
profiles={name: list(values) for name, values in raw.get("profiles", {}).items()},
memory_auto_start_soft_limit_gb=float(memory_policy_raw.get("auto_start_soft_limit_gb", 88)),
memory_hard_limit_gb=float(memory_policy_raw.get("hard_limit_gb", 96)),
min_free_percent_for_conditional_start=float(memory_policy_raw.get("min_free_percent_for_conditional_start", 8)),
max_swap_used_gb=float(memory_policy_raw.get("max_swap_used_gb", 8)),
heavy_model_budget_threshold_gb=float(memory_policy_raw.get("heavy_model_budget_threshold_gb", 30)),
max_auto_heavy_models=int(memory_policy_raw.get("max_auto_heavy_models", 2)),
)
services: dict[str, ServiceConfig] = {}
for entry in raw.get("services", []):
headers: dict[str, str] = {}
for header in entry.get("health_headers", []):
key, value = header.split(":", 1)
headers[key.strip()] = value.strip()
services[entry["name"]] = ServiceConfig(
name=entry["name"],
kind=entry.get("kind", "service"),
command=list(entry["command"]),
cwd=(path.parent / entry.get("cwd", ".")).resolve(),
port=int(entry["port"]),
health_url=entry["health_url"],
health_headers=headers,
startup_grace_seconds=int(entry.get("startup_grace_seconds", 30)),
startup_timeout_seconds=int(entry.get("startup_timeout_seconds", 300)),
restart_backoff_seconds=int(entry.get("restart_backoff_seconds", 10)),
unhealthy_threshold=int(entry.get("unhealthy_threshold", 3)),
stop_timeout_seconds=int(entry.get("stop_timeout_seconds", 20)),
watch_files=[(path.parent / item).resolve() for item in entry.get("watch_files", [])],
memory_budget_gb=float(entry.get("memory_budget_gb", 0)),
on_demand=bool(entry.get("on_demand", False)),
pinned=bool(entry.get("pinned", False)),
heavy_group=entry.get("heavy_group"),
)
return supervisor, services
def now_ts() -> float:
return time.time()
def is_pid_alive(pid: int | None) -> bool:
if pid is None:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def is_port_open(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(0.5)
return sock.connect_ex(("127.0.0.1", port)) == 0
def find_listener_pid(port: int) -> int | None:
result = subprocess.run(
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return None
for line in result.stdout.splitlines():
line = line.strip()
if line.isdigit():
return int(line)
return None
def find_lock_holder_pid(lock_path: Path) -> int | None:
result = subprocess.run(
["lsof", "-t", str(lock_path)],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return None
for line in result.stdout.splitlines():
line = line.strip()
if line.isdigit():
return int(line)
return None
def read_lock_file_pid(lock_path: Path) -> int | None:
try:
raw = lock_path.read_text(encoding="utf-8").strip()
except FileNotFoundError:
return None
except OSError:
return None
if raw.isdigit():
return int(raw)
return None
def lock_file_is_stale(lock_path: Path) -> bool:
if not lock_path.exists():
return False
holder_pid = find_lock_holder_pid(lock_path)
if holder_pid is not None and is_pid_alive(holder_pid):
return False
file_pid = read_lock_file_pid(lock_path)
if file_pid is not None and is_pid_alive(file_pid):
return False
return True
def get_process_command(pid: int | None) -> str | None:
if pid is None:
return None
result = subprocess.run(
["ps", "-p", str(pid), "-o", "command="],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return None
command = result.stdout.strip()
return command or None
def request_ok(url: str, headers: dict[str, str], timeout: float = 3.0) -> tuple[bool, str | None]:
request = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.getcode()
if 200 <= status < 300:
return True, None
return False, f"http_status={status}"
except urllib.error.HTTPError as exc:
return False, f"http_status={exc.code}"
except Exception as exc: # noqa: BLE001
return False, str(exc)
def request_json(
method: str,
url: str,
headers: dict[str, str] | None = None,
payload: dict[str, Any] | None = None,
timeout: float = 10.0,
) -> tuple[bool, dict[str, Any] | None, str | None]:
body = None
request_headers = dict(headers or {})
if payload is not None:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
request_headers.setdefault("Content-Type", "application/json")
request = urllib.request.Request(url, data=body, headers=request_headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
parsed = json.loads(response.read().decode("utf-8"))
return True, parsed, None
except urllib.error.HTTPError as exc:
try:
parsed = json.loads(exc.read().decode("utf-8"))
return False, parsed, f"http_status={exc.code}"
except Exception: # noqa: BLE001
return False, None, f"http_status={exc.code}"
except Exception as exc: # noqa: BLE001
return False, None, str(exc)
def parse_memory_pressure_snapshot(output: str) -> dict[str, Any]:
snapshot: dict[str, Any] = {"raw": output}
total_match = re.search(r"The system has (\d+)", output)
if total_match:
snapshot["total_bytes"] = int(total_match.group(1))
free_match = re.search(r"System-wide memory free percentage:\s*(\d+)%", output)
if free_match:
snapshot["free_percent"] = int(free_match.group(1))
pageouts_match = re.search(r"Pageouts:\s*(\d+)", output)
if pageouts_match:
snapshot["pageouts"] = int(pageouts_match.group(1))
swapins_match = re.search(r"Swapins:\s*(\d+)", output)
if swapins_match:
snapshot["swapins"] = int(swapins_match.group(1))
swapouts_match = re.search(r"Swapouts:\s*(\d+)", output)
if swapouts_match:
snapshot["swapouts"] = int(swapouts_match.group(1))
return snapshot
def get_swap_used_gb() -> float | None:
result = subprocess.run(
["sysctl", "vm.swapusage"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return None
match = re.search(r"used = ([0-9.]+)([MG])", result.stdout)
if not match:
return None
value = float(match.group(1))
unit = match.group(2)
if unit == "M":
return round(value / 1024, 2)
return round(value, 2)
def get_memory_snapshot() -> dict[str, Any]:
result = subprocess.run(
["memory_pressure"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return {
"ok": False,
"error": (result.stderr or result.stdout or "memory_pressure failed").strip(),
}
snapshot = parse_memory_pressure_snapshot(result.stdout)
snapshot["ok"] = True
snapshot["swap_used_gb"] = get_swap_used_gb()
return snapshot
class StatusHandler(BaseHTTPRequestHandler):
supervisor: "StackSupervisor"
def do_GET(self) -> None: # noqa: N802
parsed = urlparse(self.path)
if parsed.path in {"/", "/ui"}:
html_text = self.supervisor.render_dashboard()
encoded = html_text.encode("utf-8")
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
return
if parsed.path == "/status":
payload = self.supervisor.build_status_payload()
self._write_json(payload)
return
if parsed.path.startswith("/logs/"):
service_name = parsed.path.split("/logs/", 1)[1]
if not service_name:
self.send_error(HTTPStatus.NOT_FOUND)
return
log_path = self.supervisor.log_path_for(service_name)
if log_path is None or not log_path.exists():
self.send_error(HTTPStatus.NOT_FOUND)
return
params = parse_qs(parsed.query)
requested_lines = params.get("lines", ["200"])[0]
try:
line_count = max(20, min(1000, int(requested_lines)))
except ValueError:
line_count = 200
text = tail_text(log_path, line_count)
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(text.encode("utf-8"))
return
self.send_error(HTTPStatus.NOT_FOUND)
def do_POST(self) -> None: # noqa: N802
parsed = urlparse(self.path)
try:
length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self.send_error(HTTPStatus.BAD_REQUEST)
return
raw_body = self.rfile.read(length)
try:
payload = json.loads(raw_body.decode("utf-8")) if raw_body else {}
except Exception: # noqa: BLE001
self.send_error(HTTPStatus.BAD_REQUEST)
return
if parsed.path == "/control":
action = str(payload.get("action", "")).strip()
service_name = str(payload.get("service", "")).strip()
ok, response = self.supervisor.control_service(service_name, action)
elif parsed.path == "/ensure-service":
service_name = str(payload.get("service", "")).strip()
timeout_seconds = float(payload.get("timeout_seconds", 60) or 60)
ok, response = self.supervisor.ensure_service_ready(service_name, timeout_seconds)
elif parsed.path == "/profile":
profile_name = str(payload.get("profile", "")).strip()
ok, response = self.supervisor.apply_profile(profile_name)
elif parsed.path == "/probe":
service_name = str(payload.get("service", "")).strip()
ok, response = self.supervisor.probe_service(service_name)
else:
self.send_error(HTTPStatus.NOT_FOUND)
return
encoded = json.dumps(response, ensure_ascii=False, indent=2).encode("utf-8")
self.send_response(HTTPStatus.OK if ok else HTTPStatus.BAD_REQUEST)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
def log_message(self, fmt: str, *args: Any) -> None: # noqa: A003
return
def _write_json(self, payload: Any) -> None:
data = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def tail_text(path: Path, line_count: int) -> str:
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
return "\n".join(lines[-line_count:])
class StackSupervisor:
def __init__(
self,
supervisor_config: SupervisorConfig,
services: dict[str, ServiceConfig],
desired_services: set[str],
env: dict[str, str],
current_profile: str,
) -> None:
self.config = supervisor_config
self.services = services
self.desired_services = desired_services
self.env = env
self.current_profile = current_profile
self.processes: dict[str, subprocess.Popen[str]] = {}
self.runtimes: dict[str, ServiceRuntime] = {
name: ServiceRuntime(
name=name,
desired=(name in desired_services),
desired_reason="profile" if name in desired_services else "stopped",
eviction_protected=(name in desired_services),
)
for name in services
}
self.shutdown_requested = threading.Event()
self.state_lock = threading.RLock()
self.status_server: ThreadingHTTPServer | None = None
self.status_thread: threading.Thread | None = None
self.runtime_dir = self.config.runtime_dir
self.logs_dir = self.runtime_dir / "logs"
self.state_path = self.runtime_dir / "supervisor-status.json"
self.lock_path = self.runtime_dir / "supervisor.lock"
self.lock_handle = None
self.ensure_locks: dict[str, threading.Lock] = {
name: threading.Lock() for name in services
}
self.heavy_start_lock = threading.Lock()
self.runtime_dir.mkdir(parents=True, exist_ok=True)
self.logs_dir.mkdir(parents=True, exist_ok=True)
def acquire_lock(self) -> None:
if lock_file_is_stale(self.lock_path):
self.lock_path.unlink(missing_ok=True)
self.lock_handle = self.lock_path.open("w", encoding="utf-8")
try:
fcntl.flock(self.lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
self.lock_handle.close()
self.lock_handle = None
if lock_file_is_stale(self.lock_path):
self.lock_path.unlink(missing_ok=True)
self.lock_handle = self.lock_path.open("w", encoding="utf-8")
fcntl.flock(self.lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
else:
raise RuntimeError(f"supervisor already running: {self.lock_path}") from None
self.lock_handle.write(str(os.getpid()))
self.lock_handle.flush()
def release_lock(self) -> None:
if self.lock_handle is None:
return
try:
fcntl.flock(self.lock_handle.fileno(), fcntl.LOCK_UN)
finally:
self.lock_handle.close()
self.lock_handle = None
def log_path_for(self, service_name: str) -> Path | None:
if service_name not in self.services:
return None
return self.logs_dir / f"{service_name}.log"
def compute_watch_fingerprint(self, config: ServiceConfig) -> dict[str, int]:
fingerprint: dict[str, int] = {}
for path in config.watch_files:
key = str(path)
try:
fingerprint[key] = path.stat().st_mtime_ns
except FileNotFoundError:
fingerprint[key] = -1
return fingerprint
def is_heavy_service(self, service_name: str) -> bool:
config = self.services[service_name]
if config.heavy_group:
return True
return config.memory_budget_gb >= self.config.heavy_model_budget_threshold_gb
def mark_service_used(self, service_name: str, ts: float | None = None) -> None:
runtime = self.runtimes[service_name]
runtime.last_used_time = ts or now_ts()
def set_desired_reason(self, service_name: str, reason: str) -> None:
runtime = self.runtimes[service_name]
runtime.desired_reason = reason
runtime.eviction_protected = reason in {"profile", "manual"}
def get_running_budget_gb_locked(self) -> float:
total = 0.0
for name, runtime in self.runtimes.items():
if runtime.pid is not None:
total += self.services[name].memory_budget_gb
return round(total, 2)
def count_running_heavy_services_locked(self, exclude: str | None = None) -> int:
count = 0
for name, runtime in self.runtimes.items():
if name == exclude:
continue
if runtime.pid is None:
continue
if self.is_heavy_service(name):
count += 1
return count
def get_memory_health(self) -> tuple[bool, str, dict[str, Any]]:
snapshot = get_memory_snapshot()
if not snapshot.get("ok"):
return False, f"无法读取 memory_pressure:{snapshot.get('error', 'unknown error')}", snapshot
free_percent = snapshot.get("free_percent")
if isinstance(free_percent, int) and free_percent < self.config.min_free_percent_for_conditional_start:
return (
False,
f"当前可用内存比例仅 {free_percent}%,低于条件准入阈值 {self.config.min_free_percent_for_conditional_start}%",
snapshot,
)
swap_used_gb = snapshot.get("swap_used_gb")
if isinstance(swap_used_gb, (float, int)) and swap_used_gb > self.config.max_swap_used_gb:
return (
False,
f"当前 swap 已使用 {swap_used_gb}GB,高于条件准入阈值 {self.config.max_swap_used_gb}GB",
snapshot,
)
return True, "当前内存压力满足条件准入", snapshot
def build_admission_report_locked(self, service_name: str) -> dict[str, Any]:
current_budget_gb = self.get_running_budget_gb_locked()
target_budget_gb = self.services[service_name].memory_budget_gb
projected_budget_gb = round(current_budget_gb + (0 if self.runtimes[service_name].pid else target_budget_gb), 2)
current_heavy_count = self.count_running_heavy_services_locked(exclude=service_name if self.runtimes[service_name].pid else None)
projected_heavy_count = current_heavy_count + (
0 if self.runtimes[service_name].pid or not self.is_heavy_service(service_name) else 1
)
return {
"service": service_name,
"current_budget_gb": current_budget_gb,
"target_budget_gb": target_budget_gb,
"projected_budget_gb": projected_budget_gb,
"soft_limit_gb": self.config.memory_auto_start_soft_limit_gb,
"hard_limit_gb": self.config.memory_hard_limit_gb,
"current_heavy_count": current_heavy_count,
"projected_heavy_count": projected_heavy_count,
"max_auto_heavy_models": self.config.max_auto_heavy_models,
}
def get_protected_running_services_locked(self, exclude: str | None = None) -> list[str]:
protected: list[str] = []
for name, runtime in self.runtimes.items():
if name == exclude or runtime.pid is None or not runtime.eviction_protected:
continue
protected.append(name)
protected.sort()
return protected
def _eviction_candidates_locked(self, target_service: str) -> list[str]:
candidates: list[str] = []
for name, runtime in self.runtimes.items():
if name == target_service or runtime.pid is None:
continue
config = self.services[name]
if not config.on_demand or config.pinned or runtime.eviction_protected:
continue
candidates.append(name)
target_is_heavy = self.is_heavy_service(target_service)
target_group = self.services[target_service].heavy_group
def sort_key(name: str) -> tuple[int, float, float]:
config = self.services[name]
runtime = self.runtimes[name]
same_heavy_group = int(not (target_is_heavy and self.is_heavy_service(name)))
exact_group_penalty = int(not (target_group and config.heavy_group == target_group))
last_used = runtime.last_used_time or 0.0
return (same_heavy_group + exact_group_penalty, last_used, -config.memory_budget_gb)
candidates.sort(key=sort_key)
return candidates
def explain_admission_failure_locked(
self,
service_name: str,
admission: dict[str, Any],
evicted_services: list[str],
) -> str:
runtime = self.runtimes[service_name]
protected_running = self.get_protected_running_services_locked(exclude=service_name if runtime.pid else None)
protected_suffix = ""
if protected_running:
protected_suffix = f";当前受保护服务:{', '.join(protected_running)}"
if evicted_services:
protected_suffix += f";已自动腾退:{', '.join(evicted_services)}"
if admission["projected_heavy_count"] > admission["max_auto_heavy_models"]:
return (
f"自动拉起 {service_name} 后,重型模型并存数将达到 {admission['projected_heavy_count']},"
f"超过上限 {admission['max_auto_heavy_models']},已拒绝本次自动拉起"
f"{protected_suffix}"
)
if admission["projected_budget_gb"] > admission["hard_limit_gb"]:
return (
f"自动拉起 {service_name} 后,预计总预算 {admission['projected_budget_gb']}GB,"
f"超过硬上限 {admission['hard_limit_gb']}GB,已拒绝本次自动拉起"
f"{protected_suffix}"
)
return (
f"自动拉起 {service_name} 未通过准入检查"
f"{protected_suffix}"
)
def try_evict_for_service_locked(self, target_service: str) -> list[str]:
stopped: list[str] = []
while True:
report = self.build_admission_report_locked(target_service)
over_soft = report["projected_budget_gb"] > report["soft_limit_gb"]
over_hard = report["projected_budget_gb"] > report["hard_limit_gb"]
over_heavy = report["projected_heavy_count"] > report["max_auto_heavy_models"]
if not (over_soft or over_hard or over_heavy):
break
candidates = self._eviction_candidates_locked(target_service)
if not candidates:
break
victim = candidates[0]
self.stop_service(victim, f"evicted for {target_service}")
self.desired_services.discard(victim)
self.runtimes[victim].desired = False
self.set_desired_reason(victim, "stopped")
stopped.append(victim)
return stopped
def build_status_payload(self) -> dict[str, Any]:
with self.state_lock:
memory_snapshot = get_memory_snapshot()
items: list[dict[str, Any]] = []
for name in sorted(self.runtimes):
runtime = self.runtimes[name]
service = self.services[name]
item = asdict(runtime)
item["kind"] = service.kind
item["port"] = service.port
item["health_url"] = service.health_url
item["command"] = service.command
item["memory_budget_gb"] = service.memory_budget_gb
item["on_demand"] = service.on_demand
item["pinned"] = service.pinned
item["heavy_group"] = service.heavy_group
items.append(item)
return {
"updated_at": int(now_ts()),
"desired_services": sorted(self.desired_services),
"current_profile": self.current_profile,
"profiles": self.config.profiles,
"status_host": self.config.status_host,
"status_port": self.config.status_port,
"gateway_base_url": self.env.get("LOCAL_GATEWAY_BASE_URL", "http://127.0.0.1:4000/v1"),
"gateway_api_key": self.env.get("LITELLM_MASTER_KEY", ""),
"llama_api_key": self.env.get("LOCAL_LLAMA_API_KEY", ""),
"memory_policy": {
"soft_limit_gb": self.config.memory_auto_start_soft_limit_gb,
"hard_limit_gb": self.config.memory_hard_limit_gb,
"min_free_percent_for_conditional_start": self.config.min_free_percent_for_conditional_start,
"max_swap_used_gb": self.config.max_swap_used_gb,
"heavy_model_budget_threshold_gb": self.config.heavy_model_budget_threshold_gb,
"max_auto_heavy_models": self.config.max_auto_heavy_models,
},
"memory_snapshot": memory_snapshot,
"running_budget_gb": self.get_running_budget_gb_locked(),
"services": items,
}
def control_service(self, service_name: str, action: str) -> tuple[bool, dict[str, Any]]:
if service_name not in self.services:
return False, {"ok": False, "error": f"unknown service: {service_name}"}
if action not in {"start", "stop", "restart"}:
return False, {"ok": False, "error": f"unsupported action: {action}"}
with self.state_lock:
runtime = self.runtimes[service_name]
self.current_profile = "custom"
if action == "start":
self.desired_services.add(service_name)
runtime.desired = True
self.set_desired_reason(service_name, "manual")
runtime.blocked_reason = None
runtime.next_restart_time = 0.0
if runtime.pid is None:
self.ensure_started(service_name, now_ts())
elif action == "stop":
self.desired_services.discard(service_name)
runtime.desired = False
self.set_desired_reason(service_name, "stopped")
runtime.blocked_reason = None
runtime.next_restart_time = 0.0
if runtime.pid is not None:
self.stop_service(service_name, "stopped via dashboard")
runtime.next_restart_time = 0.0
runtime.status = "stopped"
runtime.healthy = False
elif action == "restart":
self.desired_services.add(service_name)
runtime.desired = True
self.set_desired_reason(service_name, "manual")
runtime.blocked_reason = None
runtime.next_restart_time = 0.0
if runtime.pid is not None:
self.stop_service(service_name, "restarted via dashboard")
runtime.next_restart_time = 0.0
self.ensure_started(service_name, now_ts())
self.write_status()
return True, {
"ok": True,
"service": service_name,
"action": action,
"status": self.build_status_payload(),
}
def ensure_service_ready(self, service_name: str, timeout_seconds: float) -> tuple[bool, dict[str, Any]]:
if service_name not in self.services:
return False, {"ok": False, "error": f"unknown service: {service_name}"}
service_lock = self.ensure_locks[service_name]
heavy_lock = self.heavy_start_lock if self.is_heavy_service(service_name) else None
timeout_seconds = max(5.0, min(timeout_seconds, 1800.0))
if heavy_lock is not None:
heavy_lock.acquire()
service_lock.acquire()
try:
with self.state_lock:
runtime = self.runtimes[service_name]
service = self.services[service_name]
self.mark_service_used(service_name)
if runtime.healthy:
runtime.last_denied_reason = None
self.write_status()
return True, {
"ok": True,
"ready": True,
"service": service_name,
"reason": "already_healthy",
"status": self.build_status_payload(),
}
evicted_services = self.try_evict_for_service_locked(service_name)
admission = self.build_admission_report_locked(service_name)
if admission["projected_heavy_count"] > admission["max_auto_heavy_models"]:
reason = self.explain_admission_failure_locked(service_name, admission, evicted_services)
runtime.last_denied_reason = reason
self.write_status()
return False, {
"ok": False,
"error": reason,
"admission": admission,
"evicted_services": evicted_services,
"status": self.build_status_payload(),
}
if admission["projected_budget_gb"] > admission["hard_limit_gb"]:
reason = self.explain_admission_failure_locked(service_name, admission, evicted_services)
runtime.last_denied_reason = reason
self.write_status()
return False, {
"ok": False,
"error": reason,
"admission": admission,
"evicted_services": evicted_services,
"status": self.build_status_payload(),
}
memory_health: dict[str, Any] | None = None
if admission["projected_budget_gb"] > admission["soft_limit_gb"]:
healthy, health_reason, memory_health = self.get_memory_health()
if not healthy:
runtime.last_denied_reason = health_reason
self.write_status()
return False, {
"ok": False,
"error": health_reason,
"admission": admission,
"memory_snapshot": memory_health,
"evicted_services": evicted_services,
"status": self.build_status_payload(),
}
self.desired_services.add(service_name)
runtime.desired = True
self.set_desired_reason(service_name, "auto")
runtime.last_denied_reason = None
runtime.last_auto_start_time = now_ts()
runtime.blocked_reason = None
runtime.next_restart_time = 0.0
if runtime.pid is None:
self.ensure_started(service_name, now_ts())
self.write_status()
deadline = time.time() + timeout_seconds
last_error = ""
while time.time() < deadline:
with self.state_lock:
runtime = self.runtimes[service_name]
service = self.services[service_name]
self.refresh_process_state(service_name)
if runtime.pid is None and time.time() >= runtime.next_restart_time:
self.ensure_started(service_name, now_ts())
if runtime.pid is not None:
ok, error = request_ok(service.health_url, service.health_headers, timeout=2.0)
if ok:
runtime.status = "healthy"
runtime.healthy = True
runtime.health_failures = 0
runtime.last_error = None
runtime.blocked_reason = None
runtime.last_healthy_time = now_ts()
self.mark_service_used(service_name)
self.write_status()
return True, {
"ok": True,
"ready": True,
"service": service_name,
"admission": admission,
"evicted_services": evicted_services,
"memory_snapshot": memory_health,
"status": self.build_status_payload(),
}
last_error = error or "health check failed"
runtime.healthy = False
runtime.last_error = last_error
if runtime.last_start_time is None:
runtime.last_start_time = now_ts()
if time.time() < runtime.last_start_time + service.startup_grace_seconds:
runtime.status = "starting"
else:
runtime.status = "degraded"
self.write_status()
time.sleep(0.5)
with self.state_lock:
runtime = self.runtimes[service_name]
runtime.last_denied_reason = last_error or "startup timeout"
self.write_status()
return False, {
"ok": False,
"error": f"服务 {service_name} 在 {int(timeout_seconds)} 秒内未就绪",
"last_error": last_error or "startup timeout",
"status": self.build_status_payload(),
}
finally:
service_lock.release()
if heavy_lock is not None:
heavy_lock.release()
def record_probe_result(
self,
service_name: str,
ok: bool,
summary: str,
payload: dict[str, Any],
) -> None:
with self.state_lock:
runtime = self.runtimes[service_name]
runtime.last_probe_time = now_ts()
runtime.last_probe_ok = ok
runtime.last_probe_summary = summary
runtime.last_probe_payload = payload
self.write_status()
def apply_profile(self, profile_name: str) -> tuple[bool, dict[str, Any]]:
if profile_name not in self.config.profiles:
return False, {"ok": False, "error": f"unknown profile: {profile_name}"}
with self.state_lock:
new_desired = set(self.config.profiles[profile_name])
self.current_profile = profile_name
self.desired_services = set(new_desired)
for name, runtime in self.runtimes.items():
runtime.desired = name in new_desired
self.set_desired_reason(name, "profile" if name in new_desired else "stopped")
runtime.blocked_reason = None
for name in self.services:
runtime = self.runtimes[name]
if name not in new_desired:
runtime.next_restart_time = 0.0
if runtime.pid is not None:
self.stop_service(name, f"disabled by profile {profile_name}")
runtime.next_restart_time = 0.0
runtime.status = "stopped"
runtime.healthy = False
elif runtime.pid is None:
runtime.next_restart_time = 0.0
self.ensure_started(name, now_ts())
self.write_status()
return True, {
"ok": True,
"profile": profile_name,
"status": self.build_status_payload(),
}
def probe_service(self, service_name: str) -> tuple[bool, dict[str, Any]]:
if service_name not in self.services:
return False, {"ok": False, "error": f"unknown service: {service_name}"}
service = self.services[service_name]
runtime = self.runtimes[service_name]
if service.kind == "gateway":
return False, {"ok": False, "error": "gateway service has no model probe"}
gateway_base = self.env.get("LOCAL_GATEWAY_BASE_URL", "http://127.0.0.1:4000/v1").rstrip("/")
headers = {