Files
junction/src/control.c
T
Hermes b71bfb5a0a Dashboard zeigt die letzten Anfragen — Dauer, Cache-Quelle, p95, Trefferquote
Die Zeilen aus dem Anfrage-Log lagen bisher nur in der Datei. Jetzt gibt es sie über den
Steuerkanal (`requests.tail`, Standard 20, Deckel 200) und das Dashboard zeigt sie:
Zeit, Modell, Ziel, Status, Millisekunden, Cache-Quelle, Tokens, Kosten — dazu p95 und
Trefferquote, ausdrücklich nur über die angezeigten Zeilen gerechnet.

Gelesen wird der letzte Block der Datei (256 KB), nicht die ganze: ein Ledger wächst, und
das Dashboard fragt regelmäßig. Die erste, womöglich angeschnittene Zeile fällt weg; bei
mehr Zeilen als gefragt bleiben die neuesten, nicht die ersten (Ringpuffer, geprüft mit
500 Zeilen und count 9999: n=200, erste m300, letzte m499).

Auf n95 live: control-Socket beantwortet requests.tail, Dashboard zeigt vier echte
Anfragen mit 714–751 ms, Karte "Letzte Anfragen" im HTML, app.js liest sie über
/api/requests.

Tests: control.py prüft requests.tail gegen ein vorbereitetes Ledger und den Deckel —
11 statt 9 Prüfungen. make test: PASS, 222 Prüfungen, 154 s.
2026-11-08 12:25:22 +00:00

556 lines
16 KiB
C

/* control.c - der Steuerkanal.
*
* Warum überhaupt ein eigener Kanal: die admin-Routen können pausieren und fortsetzen,
* aber eine Regel im Betrieb ändern heißt den Router neu starten — und ein
* Neustart ist ein Loch in der Vermittlung. Hier wird stattdessen unter Sperre
* geschrieben, während gelesen wird.
*
* Die Sprache ist absichtlich JSON pro Zeile: printf ... | socat - UNIX-CONNECT:...
* reicht zum Ausprobieren, und ein Dashboard braucht keinen zweiten Parser.
*/
#include "control.h"
#include "config.h"
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define CTRL_MAX_LINE (4u * 1024u * 1024u)
#define CTRL_MAX_CLIENTS 16
extern j_config CFG; /* der Router hält genau eine Konfiguration */
static const j_control_ops *OPS;
static int g_unix_fd = -1;
static int g_tcp_fd = -1;
static void ctrllog(const char *fmt, ...)
{
char line[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(line, sizeof line, fmt, ap);
va_end(ap);
fprintf(stderr, "[%s] control %s\n", CFG.log_prefix, line);
fflush(stderr);
}
/* ------------------------------------------------------------------ JSON */
/* Sucht einen Schlüssel auf oberster Ebene. Reicht für Befehle wie
* {"cmd":"rules.set","text":"…"} — alles, was tiefer liegt, kommt als Text. */
static int json_str(const char *s, size_t n, const char *key, char *out, size_t cap)
{
size_t klen = strlen(key);
out[0] = '\0';
for (size_t i = 0; i < n; i++) {
if (s[i] != '"')
continue;
size_t kstart = i + 1, j = kstart;
while (j < n && s[j] != '"') {
if (s[j] == '\\')
j++;
j++;
}
if (j >= n)
return 0;
size_t here = j - kstart;
size_t k = j + 1;
while (k < n && (s[k] == ' ' || s[k] == '\t'))
k++;
if (k >= n || s[k] != ':')
continue;
k++;
while (k < n && (s[k] == ' ' || s[k] == '\t'))
k++;
if (k >= n)
return 0;
if (here != klen || strncmp(s + kstart, key, klen)) {
i = j;
continue;
}
if (s[k] != '"')
return 0;
size_t vstart = k + 1, o = 0;
for (size_t p = vstart; p < n && s[p] != '"' && o + 1 < cap; p++) {
if (s[p] == '\\' && p + 1 < n) {
p++;
switch (s[p]) {
case 'n': out[o++] = '\n'; break;
case 't': out[o++] = '\t'; break;
case 'r': out[o++] = '\r'; break;
default: out[o++] = s[p];
}
continue;
}
out[o++] = s[p];
}
out[o] = '\0';
return 1;
}
return 0;
}
static int json_int(const char *s, size_t n, const char *key, long *out)
{
char raw[32];
if (!json_str(s, n, key, raw, sizeof raw)) {
/* Zahl statt Zeichenkette: von Hand lesen. */
size_t klen = strlen(key);
const char *p = strstr(s, key);
if (!p)
return 0;
p += klen;
while (*p == '"' || *p == ' ' || *p == ':')
p++;
*out = strtol(p, NULL, 10);
return 1;
}
*out = strtol(raw, NULL, 10);
return 1;
}
static void json_esc(const char *in, char *out, size_t cap)
{
size_t o = 0;
for (const char *p = in; *p && o + 8 < cap; p++) {
unsigned char c = (unsigned char)*p;
if (c == '"' || c == '\\') {
out[o++] = '\\';
out[o++] = (char)c;
} else if (c == '\n') {
out[o++] = '\\';
out[o++] = 'n';
} else if (c == '\r') {
out[o++] = '\\';
out[o++] = 'r';
} else if (c == '\t') {
out[o++] = '\\';
out[o++] = 't';
} else if (c < 0x20) {
out[o++] = ' ';
} else {
out[o++] = (char)c;
}
}
out[o] = '\0';
}
/* ------------------------------------------------------------------ Kanäle */
static int write_all(int fd, const char *buf, size_t len)
{
size_t off = 0;
while (off < len) {
ssize_t n = write(fd, buf + off, len - off);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
off += (size_t)n;
}
return 0;
}
/* Eine Zeile lesen; gibt malloc'ten Text ohne Zeilenende zurück. */
static char *read_line(int fd)
{
char *buf = malloc(CTRL_MAX_LINE);
size_t len = 0;
if (!buf)
return NULL;
while (len + 1 < CTRL_MAX_LINE) {
char c;
ssize_t n = read(fd, &c, 1);
if (n < 0) {
if (errno == EINTR)
continue;
free(buf);
return NULL;
}
if (n == 0)
break;
if (c == '\n')
break;
if (c == '\r')
continue;
buf[len++] = c;
}
buf[len] = '\0';
return buf;
}
/* ------------------------------------------------------------------ Befehle */
static char *dispatch(const char *req, size_t n)
{
char cmd[64], err[512] = "";
if (!json_str(req, n, "cmd", cmd, sizeof cmd))
return strdup("{\"ok\":false,\"error\":\"no cmd\"}\n");
if (!strcmp(cmd, "ping"))
return strdup("{\"ok\":true,\"pong\":true}\n");
if (!strcmp(cmd, "status")) {
size_t len = 0;
char *st = OPS->status(&len);
if (!st)
return strdup("{\"ok\":false,\"error\":\"no status\"}\n");
char *out = malloc(len + 24);
if (!out) {
free(st);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
snprintf(out, len + 24, "{\"ok\":true,\"status\":%s}\n", st);
free(st);
return out;
}
if (!strcmp(cmd, "rules.list")) {
size_t len = 0;
char *rl = OPS->rules_list(&len);
if (!rl)
return strdup("{\"ok\":false,\"error\":\"no rules\"}\n");
char *out = malloc(len + 24);
if (!out) {
free(rl);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
snprintf(out, len + 24, "{\"ok\":true,\"rules\":%s}\n", rl);
free(rl);
return out;
}
if (!strcmp(cmd, "rules.set")) {
char text[8192];
if (!json_str(req, n, "text", text, sizeof text))
return strdup("{\"ok\":false,\"error\":\"no text\"}\n");
if (OPS->rule_set(text, err, sizeof err) != 0)
goto fail;
return strdup("{\"ok\":true,\"saved\":false}\n");
}
if (!strcmp(cmd, "rules.delete")) {
char name[J_NAME_MAX] = "";
long index = -1;
int have_index = json_int(req, n, "index", &index);
json_str(req, n, "name", name, sizeof name);
if (!name[0] && !have_index)
return strdup("{\"ok\":false,\"error\":\"need name or index\"}\n");
if (OPS->rule_delete(name, have_index ? (int)index : -1, err, sizeof err) != 0)
goto fail;
return strdup("{\"ok\":true}\n");
}
if (!strcmp(cmd, "endpoint.pause") || !strcmp(cmd, "endpoint.resume")) {
char name[J_NAME_MAX];
if (!json_str(req, n, "name", name, sizeof name))
return strdup("{\"ok\":false,\"error\":\"no name\"}\n");
if (OPS->endpoint_pause(name, cmd[9] == 'p', err, sizeof err) != 0)
goto fail;
return strdup("{\"ok\":true}\n");
}
if (!strcmp(cmd, "mcp.tools")) {
size_t len = 0;
char *tl = OPS->mcp_tools(&len);
if (!tl)
return strdup("{\"ok\":false,\"error\":\"no tool list\"}\n");
char *out = malloc(len + 24);
if (!out) {
free(tl);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
sprintf(out, "{\"ok\":true,\"tools\":%.*s}\n", (int)len, tl);
free(tl);
return out;
}
if (!strcmp(cmd, "spend.get")) {
char month[16] = "";
size_t len = 0;
json_str(req, n, "month", month, sizeof month);
char *sp = OPS->spend ? OPS->spend(month, &len) : NULL;
if (!sp)
return strdup("{\"ok\":false,\"error\":\"no spend data\"}\n");
char *out = malloc(len + 24);
if (!out) {
free(sp);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
snprintf(out, len + 24, "{\"ok\":true,\"spend\":%.*s}\n", (int)len, sp);
free(sp);
return out;
}
if (!strcmp(cmd, "requests.tail")) {
char count[16] = "";
size_t len = 0;
json_str(req, n, "count", count, sizeof count);
char *rq_str = OPS->requests ? OPS->requests(count, &len) : NULL;
if (!rq_str)
return strdup("{\"ok\":false,\"error\":\"no request log\"}\n");
char *out = malloc(len + 32);
if (!out) {
free(rq_str);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
snprintf(out, len + 32, "{\"ok\":true,\"requests\":%.*s}\n", (int)len, rq_str);
free(rq_str);
return out;
}
if (!strcmp(cmd, "config.get")) {
size_t len = 0;
char *txt = OPS->config_text(&len);
if (!txt)
return strdup("{\"ok\":false,\"error\":\"no config\"}\n");
char *esc = malloc(len * 2 + 2);
char *out;
if (!esc) {
free(txt);
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
json_esc(txt, esc, len * 2 + 1);
out = malloc(strlen(esc) + 64);
if (out)
sprintf(out, "{\"ok\":true,\"text\":\"%s\"}\n", esc);
free(esc);
free(txt);
return out ? out : strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
}
if (!strcmp(cmd, "config.set")) {
/* Der Text kann groß sein: die Anfrage wird als Ganzes übergeben. */
char *text = malloc(n + 1);
if (!text)
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
if (!json_str(req, n, "text", text, n + 1)) {
free(text);
return strdup("{\"ok\":false,\"error\":\"no text\"}\n");
}
int rc = OPS->config_apply(text, err, sizeof err);
free(text);
if (rc != 0)
goto fail;
return strdup("{\"ok\":true,\"saved\":true}\n");
}
snprintf(err, sizeof err, "unknown command: %s", cmd);
fail: {
char esc[600], out[768];
json_esc(err, esc, sizeof esc);
snprintf(out, sizeof out, "{\"ok\":false,\"error\":\"%s\"}\n", esc);
return strdup(out);
}
}
static void serve_client(int fd)
{
for (;;) {
struct pollfd pfd = { .fd = fd, .events = POLLIN, .revents = 0 };
int pr = poll(&pfd, 1, 120000); /* zwei Minuten, dann ist Ruhe */
if (pr < 0) {
if (errno == EINTR)
continue;
break;
}
if (pr == 0)
break;
char *line = read_line(fd);
if (!line)
break;
if (!line[0]) {
free(line);
break;
}
char *resp = dispatch(line, strlen(line));
free(line);
if (!resp)
break;
int bad = write_all(fd, resp, strlen(resp));
free(resp);
if (bad)
break;
}
close(fd);
}
static void *client_thread(void *arg)
{
int fd = *(int *)arg;
free(arg);
serve_client(fd);
return NULL;
}
static void *unix_thread(void *arg)
{
(void)arg;
struct sockaddr_un addr;
mode_t old;
unlink(CFG.control_unix);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
ctrllog("unix socket failed: %s", strerror(errno));
return NULL;
}
memset(&addr, 0, sizeof addr);
addr.sun_family = AF_UNIX;
if (strlen(CFG.control_unix) >= sizeof addr.sun_path) {
ctrllog("unix path too long: %s", CFG.control_unix);
close(fd);
return NULL;
}
memcpy(addr.sun_path, CFG.control_unix, strlen(CFG.control_unix) + 1);
/* Kurz mit weiter Wurzel anlegen, dann auf die gewünschten Rechte setzen:
* das Socket soll nicht für jeden offen sein, nur für die Gruppe. */
old = umask(0);
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) != 0) {
umask(old);
ctrllog("bind %s failed: %s", CFG.control_unix, strerror(errno));
close(fd);
return NULL;
}
umask(old);
chmod(CFG.control_unix, (mode_t)(CFG.control_unix_mode ? CFG.control_unix_mode : 0660));
if (listen(fd, CTRL_MAX_CLIENTS) != 0) {
ctrllog("listen %s failed: %s", CFG.control_unix, strerror(errno));
close(fd);
return NULL;
}
g_unix_fd = fd;
ctrllog("listening unix %s mode %04o", CFG.control_unix,
CFG.control_unix_mode ? CFG.control_unix_mode : 0660);
for (;;) {
int cfd = accept(fd, NULL, NULL);
if (cfd < 0) {
if (errno == EINTR)
continue;
ctrllog("accept failed: %s", strerror(errno));
break;
}
int *slot = malloc(sizeof *slot);
if (!slot) {
close(cfd);
continue;
}
*slot = cfd;
pthread_t th;
pthread_attr_t at;
pthread_attr_init(&at);
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&at, 256 * 1024);
if (pthread_create(&th, &at, client_thread, slot) != 0) {
close(cfd);
free(slot);
}
pthread_attr_destroy(&at);
}
close(fd);
unlink(CFG.control_unix);
return NULL;
}
static void *tcp_thread(void *arg)
{
(void)arg;
struct sockaddr_in addr;
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
ctrllog("tcp socket failed: %s", strerror(errno));
return NULL;
}
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons((uint16_t)CFG.control_tcp_port);
if (inet_pton(AF_INET, CFG.control_tcp_host, &addr.sin_addr) != 1)
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) != 0 ||
listen(fd, CTRL_MAX_CLIENTS) != 0) {
ctrllog("tcp %s:%d failed: %s", CFG.control_tcp_host, CFG.control_tcp_port,
strerror(errno));
close(fd);
return NULL;
}
g_tcp_fd = fd;
ctrllog("listening tcp %s:%d", CFG.control_tcp_host, CFG.control_tcp_port);
for (;;) {
int cfd = accept(fd, NULL, NULL);
if (cfd < 0) {
if (errno == EINTR)
continue;
ctrllog("accept failed: %s", strerror(errno));
break;
}
int *slot = malloc(sizeof *slot);
if (!slot) {
close(cfd);
continue;
}
*slot = cfd;
pthread_t th;
pthread_attr_t at;
pthread_attr_init(&at);
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&at, 256 * 1024);
if (pthread_create(&th, &at, client_thread, slot) != 0) {
close(cfd);
free(slot);
}
pthread_attr_destroy(&at);
}
close(fd);
return NULL;
}
void j_control_start(const j_control_ops *ops)
{
OPS = ops;
if (CFG.control_unix[0]) {
pthread_t th;
pthread_create(&th, NULL, unix_thread, NULL);
pthread_detach(th);
}
if (CFG.control_tcp_port > 0) {
pthread_t th;
pthread_create(&th, NULL, tcp_thread, NULL);
pthread_detach(th);
}
if (!CFG.control_unix[0] && CFG.control_tcp_port <= 0)
ctrllog("no channel configured (control unix … / control tcp …)");
}