The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI
This commit is contained in:
commit
f631386618
71 files changed
+14616
No files matched your search
@@ -0,0 +1,104 @@
|
||||
"""Runs Strata's OpenAI-compatible server for The Kurgan.
|
||||
|
||||
Started by The Kurgan with Strata's own venv (terminal\\.venv\\Scripts\\pythonw.exe), not
|
||||
imported by it. Does what Strata's local-service-tray.py did, without the tray icon:
|
||||
the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop
|
||||
by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing
|
||||
or cancelling the current request within --shutdown-timeout) and ends its engine processes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import _thread
|
||||
import argparse
|
||||
import contextlib
|
||||
import ctypes
|
||||
from ctypes import wintypes as wt
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LOG = logging.getLogger("kurgan-strata")
|
||||
K32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE
|
||||
K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE
|
||||
K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE, wt.DWORD], wt.DWORD
|
||||
K32.CloseHandle.argtypes = [wt.HANDLE]
|
||||
|
||||
|
||||
def watch_stop(event: int, stopping: threading.Event) -> None:
|
||||
while K32.WaitForSingleObject(event, 1000) != 0:
|
||||
pass
|
||||
LOG.info("The Kurgan asked Strata to stop")
|
||||
stopping.set()
|
||||
_thread.interrupt_main()
|
||||
|
||||
|
||||
def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int:
|
||||
home = root / "terminal"
|
||||
sys.path.insert(0, str(home))
|
||||
os.chdir(home)
|
||||
from serve import lifeline, server
|
||||
|
||||
config = home / config_name
|
||||
with config.open(encoding="utf-8-sig") as source:
|
||||
model_id = json.load(source)["model_name"]
|
||||
# Same name as Strata's own tray uses, so the two can never serve one port at once.
|
||||
mutex = K32.CreateMutexW(None, False, f"Local\\StrataLocalService-{port}")
|
||||
if not mutex:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
if ctypes.get_last_error() == 183:
|
||||
K32.CloseHandle(mutex)
|
||||
raise RuntimeError(f"Strata is already running for port {port}.")
|
||||
stop_event = K32.CreateEventW(None, True, False, stop_name)
|
||||
if not stop_event:
|
||||
K32.CloseHandle(mutex)
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
stopping = threading.Event()
|
||||
threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start()
|
||||
try:
|
||||
LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid())
|
||||
os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1"
|
||||
os.environ["STRATA_NO_CONSOLE"] = "1"
|
||||
return server.main([
|
||||
"--engine", "strata", "--config", str(config), "--host", "127.0.0.1",
|
||||
"--port", str(port), "--lazy", "--idle-unload", str(idle_unload), "--shutdown-timeout", "30",
|
||||
])
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
lifeline.end_children()
|
||||
K32.CloseHandle(stop_event)
|
||||
K32.CloseHandle(mutex)
|
||||
LOG.info("Strata stopped")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--config", required=True, help="run config file name in terminal\\")
|
||||
parser.add_argument("--port", type=int, required=True)
|
||||
parser.add_argument("--idle-unload", type=int, default=2000)
|
||||
parser.add_argument("--stop-event", required=True)
|
||||
args = parser.parse_args()
|
||||
logs = args.root / "logs"
|
||||
logs.mkdir(exist_ok=True)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
|
||||
logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s")
|
||||
with (logs / f"local-service-stdout-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stdout, \
|
||||
(logs / f"local-service-stderr-{stamp}.log").open("w", encoding="utf-8", buffering=1) as stderr, \
|
||||
contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
||||
try:
|
||||
return run(args.root, args.config, args.port, args.idle_unload, args.stop_event)
|
||||
except (OSError, ValueError, KeyError, RuntimeError):
|
||||
LOG.exception("Strata startup failed")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user