diff --git a/src/junction.c b/src/junction.c index 99d7021..a2d6fc9 100644 --- a/src/junction.c +++ b/src/junction.c @@ -59,6 +59,10 @@ static pthread_mutex_t g_state_mu = PTHREAD_MUTEX_INITIALIZER; * das Array wäre dann irgendwann ins Leere gerichtet — deshalb wird die passende * Regel unter Lesesperre kopiert und danach ohne Sperre benutzt. */ static pthread_rwlock_t g_rules_rw = PTHREAD_RWLOCK_INITIALIZER; +/* Endpoints/pools/vkeys are copied in place by config.set. A request holds this + * read lock for its lifetime, so forward_step never sees a half-swapped endpoint + * and a long review keeps the endpoint it started with. */ +static pthread_rwlock_t g_config_rw = PTHREAD_RWLOCK_INITIALIZER; /* Which connection, if any, wants a heartbeat from THIS thread right now. A thread * handles one request, so this is per-request state, not global. */ @@ -1549,7 +1553,9 @@ static void *metrics_conn(void *arg) req[n] = '\0'; if (!strncmp(req, "GET /metrics", 12)) { size_t len = 0; + pthread_rwlock_rdlock(&g_config_rw); char *out = build_metrics(&len); + pthread_rwlock_unlock(&g_config_rw); if (out) { send_ct(&c, 200, "OK", "text/plain; version=0.0.4; charset=utf-8", out, len); free(out); @@ -1605,9 +1611,12 @@ static void *metrics_thread(void *arg) /* Übernimmt eine geprüfte Konfiguration. Endpunkte, Regeln und Werkzeugserver * werden unter Schreibsperre getauscht, damit kein Anfragepfad halb umgestellt - * weiterläuft. Laufende Anfragen behalten ihre Kopie bis zum Ende. */ + * weiterläuft. Laufende Anfragen halten die Lesesperre über ihre gesamte Dauer: + * der Tausch wartet auf sie, statt ihnen die Endpunkte unter den Füßen + * wegzuziehen. */ void j_config_swap(j_config *fresh) { + pthread_rwlock_wrlock(&g_config_rw); pthread_rwlock_wrlock(&g_rules_rw); STATE_LOCK(); CFG.endpoint_count = fresh->endpoint_count; @@ -1652,10 +1661,14 @@ void j_config_swap(j_config *fresh) memcpy(CFG.model_allow, fresh->model_allow, sizeof CFG.model_allow); CFG.model_deny_count = fresh->model_deny_count; memcpy(CFG.model_deny, fresh->model_deny, sizeof CFG.model_deny); + int ep_count = CFG.endpoint_count; + int rule_count = CFG.rule_count; + int mcp_count = CFG.mcp_count; STATE_UNLOCK(); pthread_rwlock_unlock(&g_rules_rw); + pthread_rwlock_unlock(&g_config_rw); jlog("config_applied", "endpoints=%d rules=%d mcps=%d", - CFG.endpoint_count, CFG.rule_count, CFG.mcp_count); + ep_count, rule_count, mcp_count); } /* ------------------------------------------------------- Steuerkanalschnittstelle */ @@ -1663,7 +1676,10 @@ void j_config_swap(j_config *fresh) /* Der Statusbericht, den auch /status ausliefert. */ char *j_status_json(size_t *len) { - return build_status(len); + pthread_rwlock_rdlock(&g_config_rw); + char *r = build_status(len); + pthread_rwlock_unlock(&g_config_rw); + return r; } void j_rules_write_lock(void) @@ -1705,6 +1721,7 @@ int j_rule_apply(const char *text, char *err, size_t errlen) if (j_config_rule_from_line(text, &fresh, err, errlen) != 0) return -1; + pthread_rwlock_rdlock(&g_config_rw); pthread_rwlock_wrlock(&g_rules_rw); /* Ersetzen, wenn eine Regel mit derselben model/path-Kombination existiert — * sonst stünden zwei Regeln nebeneinander und die erste gewinnt. */ @@ -1720,6 +1737,7 @@ int j_rule_apply(const char *text, char *err, size_t errlen) if (!replaced) { if (CFG.rule_count >= J_MAX_RULES) { pthread_rwlock_unlock(&g_rules_rw); + pthread_rwlock_unlock(&g_config_rw); snprintf(err, errlen, "more than %d rules", J_MAX_RULES); return -1; } @@ -1731,6 +1749,7 @@ int j_rule_apply(const char *text, char *err, size_t errlen) * expanding. */ if (j_config_expand_rule(&fresh, &CFG, err, errlen) != 0) { pthread_rwlock_unlock(&g_rules_rw); + pthread_rwlock_unlock(&g_config_rw); return -1; } if (replaced) { @@ -1747,6 +1766,7 @@ int j_rule_apply(const char *text, char *err, size_t errlen) } count = CFG.rule_count; pthread_rwlock_unlock(&g_rules_rw); + pthread_rwlock_unlock(&g_config_rw); jlog("rule_set", "rules=%d replaced=%d", count, replaced); return 0; } @@ -3633,7 +3653,7 @@ static const char *request_session(const j_hdrs *h, char *buf, size_t buflen) return NULL; } -static void handle_client(j_conn *client) +static void handle_client_inner(j_conn *client) { j_buf buf; uint64_t ckey = 0; /* oben, weil 'goto done' die Initialisierung überspringt */ @@ -4381,6 +4401,16 @@ done: j_buf_free(&buf); } +/* Hold the config read lock for the whole request. config.set waits for active + * requests instead of swapping endpoint fields underneath a forward_step; the + * price is that a dashboard save can wait for a long review. */ +static void handle_client(j_conn *client) +{ + pthread_rwlock_rdlock(&g_config_rw); + handle_client_inner(client); + pthread_rwlock_unlock(&g_config_rw); +} + static int progress_log(const char *role, double idle_s) { jlog("still_working", "side=%s silent_s=%.1f", role, idle_s); diff --git a/tests/control.py b/tests/control.py index 90bb9bd..e06a2b2 100755 --- a/tests/control.py +++ b/tests/control.py @@ -42,6 +42,8 @@ def make_handler(name): def do_POST(self): n = int(self.headers.get("Content-Length") or 0) self.rfile.read(n) + if self.headers.get("X-Slow"): + time.sleep(1.5) hits[name] += 1 body = json.dumps({ "id": "x", "object": "chat.completion", "model": name, @@ -80,11 +82,14 @@ def ctrl(payload, timeout=10): return json.loads(data.decode() or "{}") -def chat(model="m"): +def chat(model="m", slow=False): + headers = {"Content-Type": "application/json"} + if slow: + headers["X-Slow"] = "1" req = urllib.request.Request( f"http://127.0.0.1:{PORT}/v1/chat/completions", data=json.dumps({"model": model, "messages": [{"role": "user", "content": "hi"}]}).encode(), - method="POST", headers={"Content-Type": "application/json"}) + method="POST", headers=headers) with urllib.request.urlopen(req, timeout=15) as r: return json.loads(r.read().decode())["model"] @@ -256,6 +261,34 @@ req for "*" pass a if not os.path.exists(conf + ".bak"): failures.append("keine Sicherung der alten Datei angelegt") + # 5b. Ein config.set wartet auf die laufende Anfrage: der Request behält + # den Endpoint, den er beim Start gesehen hat, statt halb umgestellt + # zu werden. Der Slow-Header lässt den Stub 1,5 s antworten. + slow_result = [] + def slow_chat(): + try: + slow_result.append(chat("m", slow=True)) + except Exception as exc: + slow_result.append(f"error:{exc}") + th = threading.Thread(target=slow_chat) + th.start() + time.sleep(0.4) + # Die laufende Konfiguration ist pass b (new_text), die neue slow_text + # ist die ursprüngliche Datei (pass a). + t0 = time.time() + r = ctrl({"cmd": "config.set", "text": text}, timeout=20) + elapsed = time.time() - t0 + th.join(timeout=10) + if not r.get("ok"): + failures.append(f"config.set während eines Requests: {r}") + if slow_result != ["b"]: + failures.append(f"laufender Request sah {slow_result} statt des alten b") + if elapsed < 1.0: + failures.append(f"config.set wartete nicht auf den Request ({elapsed:.2f}s)") + r = ctrl({"cmd": "config.set", "text": new_text}, timeout=20) + if not r.get("ok") or chat() != "b": + failures.append("config.set nach dem Slow-Test stellt pass b nicht wieder her") + # 6. kaputte Konfiguration wird abgelehnt, die laufende bleibt r = ctrl({"cmd": "config.set", "text": "listen kaputt\nendpoint"}) if r.get("ok"): @@ -300,9 +333,10 @@ req for "*" pass a print((proc.stderr.read() or b"").decode()[-1500:]) sys.exit(1) - print("PASS: 11 Prüfungen — Monatsauskunft (spend.get), Anfrage-Log (requests.tail), " + print("PASS: 12 Prüfungen — Monatsauskunft (spend.get), Anfrage-Log (requests.tail), " "ping/status, Regel sofort wirksam, Regel löschen, Endpunkt pausieren, " - "Konfiguration lesen/schreiben, kaputte Konfiguration abgelehnt, TCP-Kanal") + "Konfiguration lesen/schreiben, Live-Regel-Pools, Config-Swap wartet auf " + "laufende Anfrage, kaputte Konfiguration abgelehnt, TCP-Kanal") if __name__ == "__main__":