Cluster: mehrere Instanzen auf einem Port, Drain bei SIGTERM, gemeinsamer Cache
Drei Teile, die zusammengehören, ohne dass ein Dienst dazwischen nötig wäre. so_reuseport: mehrere Instanzen binden dieselbe Adresse, der Kernel verteilt. Zusammen mit dem neuen Drain ergibt das ein Rolling Update — die neue Instanz nimmt Verkehr an, während die alte noch bedient. SIGTERM schließt zuerst den Listener, bedient Laufendes fertig und beendet dann; ein Request, der nach drain_timeout (Standard 15 s) noch hängt, wird verworfen und geloggt. Vorher war SIGTERM ein Abbruch mitten in der Antwort. packaging/junction@.service macht daraus zwei Befehle (start junction@blue, stop junction@green); auf n95 durchgespielt: zwei Listener auf einem Port, blue loggt draining/drained, green antwortet weiter mit 200. Gemeinsamer Cache ohne Redis: jeder Knoten gibt seinen Speicher über einen eigenen Port aus, cache_peer fragt ihn bei einem lokalen Fehlschlag, ein Fill wird asynchron weitergereicht (höchstens vier gleichzeitig, ein verworfener Push ist kein Fehler). Der Transport ist eine kleine HTTP-Teilmenge mit einem Rahmen aus zwei 32-Bit-Längen — Head und Body so, wie der Knoten sie gesendet hätte. Ein Treffer beim Nachbarn landet mit der Restlaufzeit lokal, damit der nächste Aufruf nicht wieder fragt. Ohne cache_secret_env öffnet der Port gar nicht erst. Zwei echte Funde dabei: SO_REUSEPORT ist unter -D_POSIX_C_SOURCE=200809L nicht deklariert, ein #ifdef darum kompiliert stillschweigend weg (Symptom: "Address already in use" trotz so_reuseport on) — der Makefile setzt jetzt -D_DEFAULT_SOURCE. Und ein Peer-Aufruf ohne Half-Close lässt den Nachbarn auf seinen Empfangs-Timeout warten, womit jeder Lookup in den 150 ms verhungert und der Mesh wie kaputt aussieht. --check prüft die Konfiguration jetzt wirklich, ohne zu binden (stand schon als Behauptung in den Beispielen). Tests: neuer Abschnitt 33/34 (15 Prüfungen, eigener Portbereich PORT+200…207): Peer-Treffer ohne Anbieter-Aufruf, Geheimnis erzwungen, fehlendes Geheimnis = kein Port, stiller Peer kostet genau den Timeout (203 ms gemessen), zwei Instanzen auf einem Port, Drain, Übergabe ohne Ausfall, exclusiver Port ohne so_reuseport. make test: PASS, 210 Prüfungen, 154 s.
This commit is contained in:
1 parent
2e409d709a
commit
c8b4e51a16
12 files changed
+1227
-14
No files matched your search
@@ -2,14 +2,17 @@
|
||||
# and a TLS listener; J_WITH_TLS=0 gives a dependency-free binary.
|
||||
CC ?= cc
|
||||
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Wpedantic -Wshadow -Wconversion
|
||||
CPPFLAGS += -D_POSIX_C_SOURCE=200809L
|
||||
# _DEFAULT_SOURCE next to strict POSIX: without it glibc hides SO_REUSEPORT, and an
|
||||
# #ifdef around a hidden constant compiles to nothing without a word — the symptom is
|
||||
# "Address already in use" instead of two instances on one port.
|
||||
CPPFLAGS += -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE
|
||||
CFLAGS += -pthread
|
||||
LDFLAGS += -pthread
|
||||
LDFLAGS ?=
|
||||
PREFIX ?= /usr/local
|
||||
J_WITH_TLS ?= auto
|
||||
|
||||
SRC = src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/junction.c
|
||||
SRC = src/mesh.c src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/junction.c
|
||||
OBJ = $(SRC:.c=.o)
|
||||
TOOLS = tools/junction-wol
|
||||
|
||||
|
||||
@@ -458,13 +458,72 @@ Everything else is proxied to the endpoint the rules choose.
|
||||
`make install` also installs `junction-wol` (C, 100 lines) for the `wake-wol.sh`
|
||||
hook — building a magic packet should not need an interpreter either.
|
||||
|
||||
## Cluster: several instances, one port, one cache
|
||||
|
||||
No Redis, no etcd, no proxy in front — the cluster is two mechanisms, both optional.
|
||||
|
||||
**SO_REUSEPORT** (`so_reuseport on`) lets several instances bind the same address; the
|
||||
kernel distributes the connections. A new instance takes traffic while the old one is
|
||||
still serving.
|
||||
|
||||
**Drain** (`drain_timeout`, default 15 s): on `SIGTERM` junction closes the listening
|
||||
socket first, finishes the requests it is already serving, and only then exits. Once
|
||||
the socket is closed the kernel hands new connections to the remaining instance of the
|
||||
group, so there is no window where nothing answers. A request that is still running
|
||||
after `drain_timeout` is abandoned with a `drain_timeout` log line — an update must not
|
||||
depend on a stuck upstream.
|
||||
|
||||
With a templated unit (`packaging/junction.service` copied to `junction@.service` and
|
||||
one config per colour) a rolling update is two commands:
|
||||
|
||||
```sh
|
||||
systemctl start junction@blue # new binary, same port, same rules
|
||||
systemctl stop junction@green # old instance drains, then exits
|
||||
```
|
||||
|
||||
**Shared cache** (`cache tcp`, `cache_secret_env`, `cache_peer`, `cache_peer_timeout_ms`):
|
||||
every instance keeps its cache in its own memory and hands it out over a port of its
|
||||
own. A node that misses locally asks its peers before it pays the provider; a node that
|
||||
fills an entry pushes it to its peers. The transport is a small HTTP subset — a second
|
||||
implementation does not need the binary:
|
||||
|
||||
```
|
||||
GET /cache/<16 hex> -> 200, X-Age: <s>, then the frame
|
||||
PUT /cache/<16 hex> -> 204, request body is the frame, X-TTL: <s>
|
||||
GET /cache/stats -> 200, JSON: entries, bytes, hits, misses
|
||||
|
||||
frame = 4 byte head length, 4 byte body length (big endian), head, body
|
||||
```
|
||||
|
||||
The head is the exact HTTP head the node would have sent, so a peer hit is served
|
||||
without rebuilding anything. A hit is stored locally with the remaining TTL, so the
|
||||
next caller does not ask the peer again. Fills are pushed asynchronously, at most four
|
||||
at a time; a dropped push is not an error, the entry is in the local cache either way.
|
||||
`X-Junction-Peer: <secret>` (from the variable named by `cache_secret_env`) guards the
|
||||
port; without a secret the listener does not open at all, and the log says so.
|
||||
|
||||
`cache_peer_timeout_ms` (default 150) is the whole cost of a peer that accepts and then
|
||||
says nothing — measured at 203 ms in the suite. Peers are a shortcut, never a
|
||||
dependency: if every peer is dead, the request goes to the provider as if the mesh did
|
||||
not exist.
|
||||
|
||||
What it is not: **no coherence protocol**. `POST /admin/flush/cache` flushes one node;
|
||||
the others converge by TTL only. No TLS on the peer port — it belongs on loopback or a
|
||||
trusted LAN, and the secret is the only authorization.
|
||||
|
||||
Counters: `/status` has `cache_peers` (peers, lookups, hits, pushes, errors) and
|
||||
`draining`/`reuseport`; `/metrics` has `junction_cache_peer_lookups_total`,
|
||||
`junction_cache_peer_hits_total`, `junction_cache_peer_pushes_total`,
|
||||
`junction_cache_peer_errors_total`, `junction_cache_peers` and `junction_draining`.
|
||||
|
||||
## Known limits (v0.1, deliberately named)
|
||||
|
||||
- **The queue is FIFO-ish**: `max_inflight` slots go to whoever asks next; there is no
|
||||
prioritisation and no fairness guarantee beyond that.
|
||||
- **HTTP/1.1 only** — no HTTP/2, no h2c.
|
||||
- **The cache is memory-only** and lost on restart; it is not shared between
|
||||
processes and does not survive `SIGHUP`.
|
||||
- **The cache is memory-only** and lost on restart; it does not survive `SIGHUP`.
|
||||
Across instances it is shared by peers (see above), but without coherence: the only
|
||||
invalidation is the TTL.
|
||||
- **TLS client is verified** against the system store or `tls_ca`; there is no
|
||||
certificate pinning and no client-certificate auth.
|
||||
- **junction does not tokenise.** It sees only the numbers the client writes, so a
|
||||
@@ -506,7 +565,17 @@ priced request through a key shows up in the log file, in `/status` and in `/met
|
||||
The offline wait has its own section too: with the only endpoint missing the first
|
||||
request fails as before, and once the endpoint is back the next request waits out the
|
||||
offline hold (measured ~2 s) and is served instead of refused.
|
||||
Pass = `PASS` (195 checks), including two that would have caught the two mistakes this
|
||||
Two more sections cover the cluster. The shared cache is tested with two instances:
|
||||
node A answers a request and fills, node B answers the same request from A's cache
|
||||
(`via=peer` in the log) without calling the provider at all, and keeps the entry for
|
||||
the next caller; the peer port refuses a caller without the secret and with a wrong one;
|
||||
a node without a secret does not open the port; and a peer that accepts but never
|
||||
answers costs exactly the timeout (203 ms measured) instead of stalling the request.
|
||||
The rolling update is tested for real: a second instance binds the same port while the
|
||||
first serves, `SIGTERM` on the first logs `draining` and `drained` and it exits, the
|
||||
second serves during and after the handover, and without `so_reuseport` the port stays
|
||||
exclusive.
|
||||
Pass = `PASS` (210 checks), including two that would have caught the two mistakes this
|
||||
design invites: a serial stub making a concurrent router look serialised, and a
|
||||
"waiting" comment leaking into a caller that never asked for a stream.
|
||||
|
||||
|
||||
@@ -42,6 +42,15 @@ retry_backoff 0.5
|
||||
# scrape the numbers here without reaching the model port (and /admin) at all.
|
||||
# metrics tcp 192.168.1.148:9180
|
||||
|
||||
# --- cluster, without a service in between -----------------------------------
|
||||
# Several instances may share one port, and each may hand its cache to the others.
|
||||
# so_reuseport on
|
||||
# drain_timeout 15
|
||||
# cache tcp 127.0.0.1:8170
|
||||
# cache_secret_env JUNCTION_CACHE_KEY
|
||||
# cache_peer 127.0.0.1:8171
|
||||
# cache_peer_timeout_ms 150
|
||||
|
||||
cache_ttl 300
|
||||
cache_entries 128
|
||||
cache_bytes 33554432
|
||||
|
||||
@@ -74,6 +74,35 @@ offline_wait 20
|
||||
metrics tcp 192.168.1.148:9180
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- cluster
|
||||
#
|
||||
# Several instances on one port and one cache shared between them — no Redis, no
|
||||
# etcd, no proxy in front. Both halves are optional and independent.
|
||||
#
|
||||
# so_reuseport: the kernel distributes the connections over the instances that bound
|
||||
# the same address. A new instance takes traffic while the old one still serves.
|
||||
#
|
||||
# drain_timeout: on SIGTERM the listening socket is closed first, the running requests
|
||||
# are finished, then the process exits. A request still running after this many seconds
|
||||
# is abandoned (logged as drain_timeout) — an update must not hang on an upstream.
|
||||
so_reuseport on
|
||||
drain_timeout 15
|
||||
|
||||
# The cache peer port of THIS instance. It answers three paths and nothing else:
|
||||
# GET /cache/<16 hex> a cached response (head and body, framed)
|
||||
# PUT /cache/<16 hex> store one (pushed by another instance)
|
||||
# GET /cache/stats its own counters
|
||||
# Without cache_secret_env this port does not open at all: an unprotected peer port on
|
||||
# a LAN is a way to read responses you never paid for, and to fill someone's memory.
|
||||
cache tcp 127.0.0.1:8170
|
||||
cache_secret_env JUNCTION_CACHE_KEY
|
||||
|
||||
# The other instances, asked on a local miss and pushed to on a fill. Repeated line per
|
||||
# peer. cache_peer_timeout_ms is the entire cost of a peer that accepts and then says
|
||||
# nothing; 150 ms is a LAN round trip with room to spare.
|
||||
cache_peer 127.0.0.1:8171
|
||||
cache_peer_timeout_ms 150
|
||||
|
||||
# ---------------------------------------------------------------- guard
|
||||
#
|
||||
# A command that sees every request before it is routed: exit 0 = let it through,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
[Unit]
|
||||
# One instance of a rolling update. Copy to /etc/systemd/system/junction@.service and
|
||||
# keep one configuration per colour, e.g. /etc/junction/junction-blue.conf:
|
||||
#
|
||||
# systemctl start junction@blue # new binary, same port
|
||||
# systemctl stop junction@green # old instance drains, then exits
|
||||
#
|
||||
# That only works with so_reuseport on in the configuration: without it the new instance
|
||||
# cannot bind while the old one is still holding the port, and the update has a window
|
||||
# with no listener at all.
|
||||
Description=junction instance %i — model router
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=0
|
||||
StartLimitBurst=0
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=lotherk
|
||||
Group=lotherk
|
||||
Environment=HOME=/home/lotherk
|
||||
# The cloud key lives in Hermes' .env; junction only reads it from the environment and
|
||||
# never logs it.
|
||||
EnvironmentFile=/home/lotherk/.hermes/.env
|
||||
EnvironmentFile=-/etc/junction/junction.env
|
||||
# Separate runtime directories per instance, so the control sockets do not collide:
|
||||
# /run/junction/blue, /run/junction/green. Without this the second instance cannot
|
||||
# create its socket and silently serves TCP only.
|
||||
RuntimeDirectory=junction/%i
|
||||
RuntimeDirectoryMode=0750
|
||||
ExecStart=/usr/local/bin/junction --config /etc/junction/junction-%i.conf
|
||||
# SIGTERM is not a kill switch here: junction closes the listening socket, finishes the
|
||||
# running requests and exits. Give it the drain timeout plus a little room before
|
||||
# systemd escalates.
|
||||
TimeoutStopSec=40
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -90,6 +90,8 @@ void j_config_defaults(j_config *cfg)
|
||||
cfg->cache_bytes = 32L * 1024 * 1024;
|
||||
cfg->ctx_chars_per_token = 0;
|
||||
cfg->cache_deterministic_only = 1;
|
||||
cfg->cache_peer_timeout_ms = 150;
|
||||
cfg->drain_timeout_s = 15.0;
|
||||
snprintf(cfg->prices_path, sizeof cfg->prices_path, "/etc/junction/prices.conf");
|
||||
cfg->compress = J_COMPRESS_OFF;
|
||||
cfg->compress_keep = 4;
|
||||
@@ -258,6 +260,70 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size
|
||||
if (cfg->metrics_tcp_port <= 0 || cfg->metrics_tcp_port > 65535) goto bad;
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(k, "cache") || !strcmp(k, "cache_peer") ||
|
||||
!strcmp(k, "cache_secret_env") || !strcmp(k, "cache_peer_timeout_ms")) {
|
||||
/* cache tcp 127.0.0.1:8170 (dieser Knoten liefert seinen Cache aus)
|
||||
* cache_secret_env JUNCTION_CACHE_KEY
|
||||
* cache_peer 127.0.0.1:8171 (wiederholbar, andere Knoten fragen)
|
||||
* cache_peer_timeout_ms 150
|
||||
*
|
||||
* Der gemeinsame Antwortspeicher ohne Dienst dazwischen: jeder Knoten hält
|
||||
* seinen Cache im eigenen Speicher und gibt ihn über einen eigenen Port an die
|
||||
* anderen. Ein Treffer bei einem Nachbarn spart den Aufruf beim Anbieter, ein
|
||||
* Fehlschlag kostet nur die Wartezeit — deshalb ist der Zeitablauf kurz und
|
||||
* ein nicht erreichbarer Nachbar kein Fehler. */
|
||||
if (!strcmp(k, "cache") && n == 3 && !strcmp(w[1], "tcp")) {
|
||||
const char *colon = strrchr(w[2], ':');
|
||||
if (!colon) goto bad;
|
||||
snprintf(cfg->cache_tcp_host, sizeof cfg->cache_tcp_host,
|
||||
"%.*s", (int)(colon - w[2]), w[2]);
|
||||
cfg->cache_tcp_port = atoi(colon + 1);
|
||||
if (cfg->cache_tcp_port <= 0 || cfg->cache_tcp_port > 65535) goto bad;
|
||||
return 0;
|
||||
}
|
||||
if (n == 2 && !strcmp(k, "cache_peer")) {
|
||||
if (cfg->cache_peer_count >= J_MAX_CACHE_PEERS) goto bad;
|
||||
if (!strrchr(w[1], ':')) goto bad;
|
||||
snprintf(cfg->cache_peer[cfg->cache_peer_count],
|
||||
sizeof cfg->cache_peer[0], "%s", w[1]);
|
||||
cfg->cache_peer_count++;
|
||||
return 0;
|
||||
}
|
||||
if (n == 2 && !strcmp(k, "cache_secret_env")) {
|
||||
snprintf(cfg->cache_secret_env, sizeof cfg->cache_secret_env, "%s", w[1]);
|
||||
return 0;
|
||||
}
|
||||
if (n == 2 && !strcmp(k, "cache_peer_timeout_ms")) {
|
||||
cfg->cache_peer_timeout_ms = atoi(w[1]);
|
||||
if (cfg->cache_peer_timeout_ms <= 0 || cfg->cache_peer_timeout_ms > 60000)
|
||||
goto bad;
|
||||
return 0;
|
||||
}
|
||||
goto bad;
|
||||
}
|
||||
if (!strcmp(k, "so_reuseport")) {
|
||||
/* so_reuseport on
|
||||
*
|
||||
* Mehrere Instanzen dürfen denselben Port binden, der Kernel verteilt die
|
||||
* Verbindungen. Das ist die Voraussetzung für ein Rolling Update ohne
|
||||
* Vorschaltgerät: die neue Instanz bindet, während die alte noch bedient. */
|
||||
if (n != 2) goto bad;
|
||||
if (!strcmp(w[1], "on")) cfg->so_reuseport = 1;
|
||||
else if (!strcmp(w[1], "off")) cfg->so_reuseport = 0;
|
||||
else goto bad;
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(k, "drain_timeout")) {
|
||||
/* drain_timeout 15
|
||||
*
|
||||
* Bei SIGTERM gibt junction den Port auf und bedient nur noch, was schon läuft.
|
||||
* Länger als diese Zeit wartet es nicht — ein Rolling Update darf nicht an
|
||||
* einer hängenden Anfrage scheitern. */
|
||||
if (n != 2) goto bad;
|
||||
cfg->drain_timeout_s = atof(w[1]);
|
||||
if (cfg->drain_timeout_s < 0 || cfg->drain_timeout_s > 3600) goto bad;
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(k, "control")) {
|
||||
/* control unix /run/junction/control.sock [mode 0660]
|
||||
* control tcp 127.0.0.1:8091
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
#define J_MAX_KEY_ENVS 8
|
||||
#define J_MAX_POOLS 16
|
||||
#define J_MAX_MCP 16
|
||||
#define J_MAX_CACHE_PEERS 8
|
||||
|
||||
/* Balance modes: how targets inside one rule are ordered. */
|
||||
enum { J_BALANCE_FIRST = 0, J_BALANCE_RR = 1, J_BALANCE_USAGE = 2, J_BALANCE_COST = 3 };
|
||||
@@ -267,6 +268,23 @@ typedef struct {
|
||||
long cache_entries;
|
||||
long cache_bytes;
|
||||
|
||||
/* Shared cache across instances, without a service in between: every node can
|
||||
* hand out its own memory over a port of its own. Peers are asked on a local miss
|
||||
* and pushed on a fill. No Redis, no network daemon, no extra package. */
|
||||
char cache_tcp_host[J_NAME_MAX];
|
||||
int cache_tcp_port;
|
||||
char cache_secret_env[J_NAME_MAX]; /* name of the variable holding the secret */
|
||||
char cache_peer[J_MAX_CACHE_PEERS][J_URL_MAX]; /* host:port of the other nodes */
|
||||
int cache_peer_count;
|
||||
int cache_peer_timeout_ms;
|
||||
|
||||
/* Cluster without dependencies: several instances may bind the same port
|
||||
* (SO_REUSEPORT), then the kernel distributes. Together with the drain on SIGTERM
|
||||
* this gives a rolling update: the new instance binds, the old one gives the port
|
||||
* up and finishes only the requests it is still serving. */
|
||||
int so_reuseport;
|
||||
double drain_timeout_s;
|
||||
|
||||
/* Zeichen pro Token für die Prompt-Schätzung. 0 = aus, dann kann keine Regel eine
|
||||
* ctx-Bedingung tragen. Der Wert ist eine Annahme über die Tokenisierung, keine
|
||||
* Messung — deshalb steht er in der Konfiguration und nicht im Code. */
|
||||
|
||||
+130
-8
@@ -9,6 +9,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
|
||||
#include "cache.h"
|
||||
#include "mesh.h"
|
||||
#include "opencode.h"
|
||||
#include "price.h"
|
||||
#include "compress.h"
|
||||
@@ -74,6 +75,27 @@ static struct {
|
||||
int waiting;
|
||||
} SLOTS = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0 };
|
||||
|
||||
/* Drain: bei SIGTERM gibt junction den Port auf und beendet nur noch, was schon
|
||||
* läuft. g_stop wird vom Signalhandler gesetzt, g_draining von der Hauptschleife —
|
||||
* /status und /metrics lesen es, ohne den Handler zu kennen. */
|
||||
static volatile sig_atomic_t g_stop;
|
||||
static volatile sig_atomic_t g_draining;
|
||||
|
||||
static void on_term(int sig)
|
||||
{
|
||||
(void)sig;
|
||||
g_stop = 1;
|
||||
g_draining = 1;
|
||||
}
|
||||
|
||||
static int drain_inflight(void)
|
||||
{
|
||||
pthread_mutex_lock(&SLOTS.mu);
|
||||
int n = SLOTS.inflight;
|
||||
pthread_mutex_unlock(&SLOTS.mu);
|
||||
return n;
|
||||
}
|
||||
|
||||
static double now_s(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
@@ -679,9 +701,17 @@ static char *build_status(size_t *len_out)
|
||||
pthread_mutex_lock(&SLOTS.mu);
|
||||
int inflight = SLOTS.inflight, waiting = SLOTS.waiting;
|
||||
pthread_mutex_unlock(&SLOTS.mu);
|
||||
unsigned long mesh_lookups = 0, mesh_hits = 0, mesh_pushes = 0, mesh_errors = 0;
|
||||
int mesh_peers = 0;
|
||||
j_mesh_stats(&mesh_lookups, &mesh_hits, &mesh_pushes, &mesh_errors, &mesh_peers);
|
||||
used += (size_t)snprintf(out + used, cap - used,
|
||||
"\"queue\":{\"inflight\":%d,\"waiting\":%d,\"max_inflight\":%d,\"timeout_s\":%.0f},\"rules\":[",
|
||||
inflight, waiting, CFG.max_inflight, CFG.queue_timeout_s);
|
||||
"\"queue\":{\"inflight\":%d,\"waiting\":%d,\"max_inflight\":%d,\"timeout_s\":%.0f},"
|
||||
"\"draining\":%s,\"reuseport\":%s,"
|
||||
"\"cache_peers\":{\"peers\":%d,\"lookups\":%lu,\"hits\":%lu,\"pushes\":%lu,"
|
||||
"\"errors\":%lu},\"rules\":[",
|
||||
inflight, waiting, CFG.max_inflight, CFG.queue_timeout_s,
|
||||
g_draining ? "true" : "false", CFG.so_reuseport ? "true" : "false",
|
||||
mesh_peers, mesh_lookups, mesh_hits, mesh_pushes, mesh_errors);
|
||||
for (int i = 0; i < CFG.rule_count; i++) {
|
||||
j_rule *r = &CFG.rules[i];
|
||||
/* all targets, each with the model it is asked for ("ep" or "ep as M") */
|
||||
@@ -942,6 +972,9 @@ static char *build_metrics(size_t *len_out)
|
||||
size_t entries = 0, bytes = 0;
|
||||
unsigned long hits = 0, misses = 0;
|
||||
j_cache_stats(&entries, &bytes, &hits, &misses);
|
||||
unsigned long m_lookups = 0, m_hits = 0, m_pushes = 0, m_errors = 0;
|
||||
int m_peers = 0;
|
||||
j_mesh_stats(&m_lookups, &m_hits, &m_pushes, &m_errors, &m_peers);
|
||||
pthread_mutex_lock(&SLOTS.mu);
|
||||
int inflight = SLOTS.inflight, waiting = SLOTS.waiting;
|
||||
pthread_mutex_unlock(&SLOTS.mu);
|
||||
@@ -987,12 +1020,24 @@ static char *build_metrics(size_t *len_out)
|
||||
"junction_cache_misses_total %lu\n"
|
||||
"# TYPE junction_cache_joined_total counter\n"
|
||||
"junction_cache_joined_total %lu\n"
|
||||
"# TYPE junction_cache_peer_lookups_total counter\n"
|
||||
"junction_cache_peer_lookups_total %lu\n"
|
||||
"# TYPE junction_cache_peer_hits_total counter\n"
|
||||
"junction_cache_peer_hits_total %lu\n"
|
||||
"# TYPE junction_cache_peer_pushes_total counter\n"
|
||||
"junction_cache_peer_pushes_total %lu\n"
|
||||
"# TYPE junction_cache_peer_errors_total counter\n"
|
||||
"junction_cache_peer_errors_total %lu\n"
|
||||
"# TYPE junction_cache_peers gauge\n"
|
||||
"junction_cache_peers %d\n"
|
||||
"# TYPE junction_inflight gauge\n"
|
||||
"junction_inflight %d\n"
|
||||
"# TYPE junction_waiting gauge\n"
|
||||
"junction_waiting %d\n"
|
||||
"# TYPE junction_max_inflight gauge\n"
|
||||
"junction_max_inflight %d\n"
|
||||
"# TYPE junction_draining gauge\n"
|
||||
"junction_draining %d\n"
|
||||
"# HELP junction_compress_bytes_total Tool output removed before the model saw it.\n"
|
||||
"# TYPE junction_compress_bytes_total counter\n"
|
||||
"junction_compress_requests_total %lu\n"
|
||||
@@ -1008,7 +1053,8 @@ static char *build_metrics(size_t *len_out)
|
||||
g_cost_usd, g_cost_unknown,
|
||||
g_latency_n ? g_latency_ms_sum / (double)g_latency_n : -1.0, g_latency_n,
|
||||
entries, bytes, hits, misses, j_cache_flight_joined(),
|
||||
inflight, waiting, CFG.max_inflight,
|
||||
m_lookups, m_hits, m_pushes, m_errors, m_peers,
|
||||
inflight, waiting, CFG.max_inflight, g_draining ? 1 : 0,
|
||||
g_compress_reqs, g_compress_bytes_in, g_compress_bytes_out,
|
||||
t - g_started_at, g_req_bytes, g_resp_bytes);
|
||||
|
||||
@@ -2440,8 +2486,11 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
j_hdrs tmp = r.hdrs;
|
||||
headused += j_hdrs_serialize(&tmp, headcopy + headused, HDR_BLOCK_MAX - headused,
|
||||
1, 1);
|
||||
j_cache_put(j_cache_key(rq->method, rq->path, rq_model, out_body, out_len),
|
||||
headcopy, headused, body, body_len, CFG.cache_ttl_s);
|
||||
uint64_t fill_key = j_cache_key(rq->method, rq->path, rq_model, out_body, out_len);
|
||||
j_cache_put(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s);
|
||||
/* Der Nachbar soll dieselbe Antwort nicht noch einmal bezahlen. Der Aufruf
|
||||
* kehrt sofort zurück; ein nicht erreichbarer Nachbar kostet hier nichts. */
|
||||
j_mesh_store(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s);
|
||||
free(headcopy);
|
||||
}
|
||||
int rc = send_head(client, r.status, r.reason, &r.hdrs, (long)body_len, err, errlen);
|
||||
@@ -2799,6 +2848,21 @@ static void handle_client(j_conn *client)
|
||||
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age);
|
||||
goto done;
|
||||
}
|
||||
/* Lokal nichts — aber vielleicht hat ein anderer Knoten dieselbe Frage schon
|
||||
* beantwortet. Ein Treffer spart den Aufruf beim Anbieter; ein Fehlschlag
|
||||
* kostet nur den kurzen Zeitablauf. */
|
||||
{
|
||||
char *mhead = NULL, *mbody = NULL;
|
||||
size_t mhl = 0, mbl = 0;
|
||||
double mage = 0;
|
||||
if (j_mesh_lookup(ckey, &mhead, &mhl, &mbody, &mbl, &mage) == 0) {
|
||||
jlog("cache_hit", "path=%s model=%s age_s=%.0f via=peer", rq.path, model, mage);
|
||||
serve_from_cache(client, mhead, mhl, mbody, mbl, rq.path, model, mage);
|
||||
free(mhead);
|
||||
free(mbody);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
|
||||
/* Läuft dieselbe Anfrage schon? Dann warten und ihr Ergebnis mitbenutzen,
|
||||
* statt ein zweites Mal zu bezahlen. */
|
||||
@@ -3103,6 +3167,13 @@ static int make_listener(const j_config *cfg, char *err, size_t errlen)
|
||||
if (lfd < 0) continue;
|
||||
int one = 1;
|
||||
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
|
||||
#ifdef SO_REUSEPORT
|
||||
/* Mehrere Instanzen auf demselben Port: der Kernel verteilt die Verbindungen.
|
||||
* Ohne das könnte eine neue Instanz erst binden, wenn die alte den Port
|
||||
* aufgegeben hat — ein Rolling Update hätte dann ein Fenster ohne Bedienung. */
|
||||
if (cfg->so_reuseport)
|
||||
setsockopt(lfd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof one);
|
||||
#endif
|
||||
if (!bind(lfd, ai->ai_addr, ai->ai_addrlen) && !listen(lfd, 32)) break;
|
||||
close(lfd);
|
||||
lfd = -1;
|
||||
@@ -3125,16 +3196,18 @@ int main(int argc, char **argv)
|
||||
{
|
||||
const char *config_path = NULL;
|
||||
int port_override = 0;
|
||||
int check_only = 0;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--config") && i + 1 < argc) config_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--port") && i + 1 < argc) port_override = atoi(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--check")) check_only = 1;
|
||||
else {
|
||||
fprintf(stderr, "usage: junction --config <file> [--port N]\n");
|
||||
fprintf(stderr, "usage: junction --config <file> [--port N] [--check]\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (!config_path) {
|
||||
fprintf(stderr, "usage: junction --config <file> [--port N]\n");
|
||||
fprintf(stderr, "usage: junction --config <file> [--port N] [--check]\n");
|
||||
return 2;
|
||||
}
|
||||
char err[512] = "";
|
||||
@@ -3142,6 +3215,14 @@ int main(int argc, char **argv)
|
||||
fprintf(stderr, "config error: %s\n", err);
|
||||
return 1;
|
||||
}
|
||||
/* --check: die Datei prüfen, ohne zu binden. Damit ist "vor dem Neustart
|
||||
* einmal durch den Parser" ein Befehl und kein Handgriff in der Erinnerung. */
|
||||
if (check_only) {
|
||||
printf("config ok: %d endpoints, %d rules, %d vkeys, listen %s:%d%s\n",
|
||||
CFG.endpoint_count, CFG.rule_count, CFG.vkey_count,
|
||||
CFG.listen_host, CFG.listen_port, CFG.listen_tls ? " tls" : "");
|
||||
return 0;
|
||||
}
|
||||
j_mcp_set_log(mcp_log_bridge);
|
||||
g_started_at = now_s();
|
||||
if (port_override) CFG.listen_port = port_override;
|
||||
@@ -3181,6 +3262,18 @@ int main(int argc, char **argv)
|
||||
* einmal je Endpunkt die Modellliste geholt -- im Hintergrund, siehe unten. */
|
||||
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
/* Kein SA_RESTART: accept() soll mit EINTR zurückkommen, damit die Hauptschleife
|
||||
* das Signal sieht. Ein Router, der auf einen abbauenden Client wartet, ist beim
|
||||
* Herunterfahren nicht zu gebrauchen. */
|
||||
{
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof sa);
|
||||
sa.sa_handler = on_term;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_flags = 0;
|
||||
sigaction(SIGTERM, &sa, NULL);
|
||||
sigaction(SIGINT, &sa, NULL);
|
||||
}
|
||||
j_set_progress(progress_log);
|
||||
|
||||
/* Budgets brauchen einen eigenen Faden: die Abfrage darf keinen Request aufhalten. */
|
||||
@@ -3216,6 +3309,11 @@ int main(int argc, char **argv)
|
||||
if (pthread_create(&th, NULL, metrics_thread, NULL) == 0)
|
||||
pthread_detach(th);
|
||||
}
|
||||
/* Gemeinsamer Cache: eigener Port für die Nachbarn, optional. Scheitert er, läuft
|
||||
* der Router weiter — ein Cache ist eine Ersparnis, keine Bedingung. */
|
||||
if (j_mesh_start())
|
||||
jlog("cache_peer", "mesh active peers=%d port=%d", CFG.cache_peer_count,
|
||||
CFG.cache_tcp_port);
|
||||
jlog("listening", "addr=%s:%d endpoints=%d rules=%d tls=%d cache_ttl=%.0f",
|
||||
CFG.listen_host, CFG.listen_port, CFG.endpoint_count, CFG.rule_count,
|
||||
CFG.listen_tls, CFG.cache_ttl_s);
|
||||
@@ -3234,7 +3332,11 @@ int main(int argc, char **argv)
|
||||
|
||||
for (;;) {
|
||||
int cfd = accept(lfd, NULL, NULL);
|
||||
if (cfd < 0) { if (errno == EINTR) continue; break; }
|
||||
if (cfd < 0) {
|
||||
if (errno == EINTR && !g_stop) continue;
|
||||
if (errno == EINTR && g_stop) break;
|
||||
break;
|
||||
}
|
||||
int *arg = malloc(sizeof *arg);
|
||||
if (!arg) { close(cfd); continue; }
|
||||
*arg = cfd;
|
||||
@@ -3249,5 +3351,25 @@ int main(int argc, char **argv)
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
close(lfd);
|
||||
|
||||
/* Drain: der Port ist aufgegeben, was schon läuft, darf fertig werden. Neue
|
||||
* Verbindungen bekommt bei SO_REUSEPORT die nächste Instanz; ohne sie laufen sie
|
||||
* ins Leere — deshalb gehört drain_timeout dazu und nicht in ein Handbuch. */
|
||||
g_draining = 1;
|
||||
int waiting = drain_inflight();
|
||||
jlog("draining", "closed_listener inflight=%d timeout_s=%.1f", waiting,
|
||||
CFG.drain_timeout_s);
|
||||
double deadline = now_s() + CFG.drain_timeout_s;
|
||||
while (drain_inflight() > 0 && now_s() < deadline) {
|
||||
struct timespec ts = { 0, 50 * 1000 * 1000 };
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
j_mesh_stop();
|
||||
int left = drain_inflight();
|
||||
if (left > 0)
|
||||
jlog("drain_timeout", "inflight=%d after_s=%.1f — beendet trotzdem",
|
||||
left, CFG.drain_timeout_s);
|
||||
else
|
||||
jlog("drained", "inflight=0 waited_ok=1");
|
||||
return 0;
|
||||
}
|
||||
+614
@@ -0,0 +1,614 @@
|
||||
/* junction/mesh.c — the shared cache across instances (see mesh.h).
|
||||
*
|
||||
* Wire format, deliberately tiny:
|
||||
*
|
||||
* GET /cache/<16 hex> -> 200, X-Age: <s>, then the frame
|
||||
* PUT /cache/<16 hex> -> 204, request body is the frame, X-TTL: <s>
|
||||
* GET /cache/stats -> 200, JSON of that node
|
||||
*
|
||||
* frame = 4 byte head length, 4 byte body length (both big endian), head, body
|
||||
*
|
||||
* The head is the full HTTP response head the node would have sent (status line and
|
||||
* headers), so a peer hit can be served without rebuilding anything. Numbers are
|
||||
* big endian because both ends are the same program today, but a second
|
||||
* implementation should not have to guess a byte order.
|
||||
*
|
||||
* Authorization: `X-Junction-Peer: <secret>`, the secret from the environment variable
|
||||
* named by `cache_secret_env`. Without that line in the configuration the port is
|
||||
* open to whoever can reach it — so the default is: no secret, no listener.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "cache.h"
|
||||
#include "config.h"
|
||||
#include "mesh.h"
|
||||
|
||||
extern j_config CFG;
|
||||
|
||||
/* A single entry above this is not transferred: the cache is a speedup, and moving
|
||||
* eight megabytes over the mesh costs more than the request it saves. */
|
||||
#define MESH_MAX_XFER (8u * 1024u * 1024u)
|
||||
#define MESH_HEAD_MAX 8192
|
||||
#define MESH_MAX_PUSH 4 /* pushes on their way at once, then dropped */
|
||||
|
||||
static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static unsigned long g_lookups, g_hits, g_pushes, g_errors;
|
||||
static int g_running;
|
||||
static int g_lfd = -1;
|
||||
static int g_push_inflight;
|
||||
static char g_secret[256];
|
||||
|
||||
static void mlog(const char *event, const char *fmt, ...)
|
||||
{
|
||||
char line[900];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(line, sizeof line, fmt, ap);
|
||||
va_end(ap);
|
||||
fprintf(stderr, "[%s] %s %s\n", CFG.log_prefix, event, line);
|
||||
}
|
||||
|
||||
static void count(unsigned long *which)
|
||||
{
|
||||
pthread_mutex_lock(&g_mu);
|
||||
(*which)++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ framing */
|
||||
|
||||
static void put_u32(unsigned char *p, uint32_t v)
|
||||
{
|
||||
p[0] = (unsigned char)((v >> 24) & 0xffu);
|
||||
p[1] = (unsigned char)((v >> 16) & 0xffu);
|
||||
p[2] = (unsigned char)((v >> 8) & 0xffu);
|
||||
p[3] = (unsigned char)(v & 0xffu);
|
||||
}
|
||||
|
||||
static uint32_t get_u32(const unsigned char *p)
|
||||
{
|
||||
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
|
||||
((uint32_t)p[2] << 8) | (uint32_t)p[3];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ small io */
|
||||
|
||||
/* Reads until the peer closes or `cap` is reached. Returns the byte count, or -1. */
|
||||
static ssize_t read_until_close(int fd, char *buf, size_t cap)
|
||||
{
|
||||
size_t used = 0;
|
||||
while (used < cap) {
|
||||
ssize_t n = recv(fd, buf + used, cap - used, 0);
|
||||
if (n > 0) { used += (size_t)n; continue; }
|
||||
if (n == 0) break;
|
||||
if (errno == EINTR) continue;
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
|
||||
return -1;
|
||||
}
|
||||
return (ssize_t)used;
|
||||
}
|
||||
|
||||
static int write_all(int fd, const void *buf, size_t len)
|
||||
{
|
||||
const char *p = buf;
|
||||
while (len) {
|
||||
ssize_t n = send(fd, p, len, MSG_NOSIGNAL);
|
||||
if (n > 0) { p += n; len -= (size_t)n; continue; }
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Splits "host:port" without touching CFG.cache_peer (which is shared state). */
|
||||
static int split_hostport(const char *s, char *host, size_t hlen, int *port)
|
||||
{
|
||||
const char *colon = strrchr(s, ':');
|
||||
if (!colon || colon == s) return -1;
|
||||
size_t n = (size_t)(colon - s);
|
||||
if (n >= hlen) return -1;
|
||||
memcpy(host, s, n);
|
||||
host[n] = '\0';
|
||||
*port = atoi(colon + 1);
|
||||
return (*port > 0 && *port <= 65535) ? 0 : -1;
|
||||
}
|
||||
|
||||
/* Connecting must not cost a request more than the configured timeout: the mesh is a
|
||||
* shortcut, not a hop that may hang. */
|
||||
static int connect_timeout(const char *host, int port, int timeout_ms)
|
||||
{
|
||||
struct addrinfo hints, *res = NULL;
|
||||
char portstr[16];
|
||||
memset(&hints, 0, sizeof hints);
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
snprintf(portstr, sizeof portstr, "%d", port);
|
||||
if (getaddrinfo(host, portstr, &hints, &res) != 0 || !res) return -1;
|
||||
|
||||
int fd = -1;
|
||||
for (struct addrinfo *ai = res; ai; ai = ai->ai_next) {
|
||||
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
|
||||
if (fd < 0) continue;
|
||||
int flags = fcntl(fd, F_GETFL, 0);
|
||||
if (flags >= 0) (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||
int rc = connect(fd, ai->ai_addr, ai->ai_addrlen);
|
||||
if (rc != 0 && errno == EINPROGRESS) {
|
||||
struct pollfd pfd = { fd, POLLOUT, 0 };
|
||||
rc = poll(&pfd, 1, timeout_ms);
|
||||
if (rc == 0) { close(fd); fd = -1; continue; } /* timeout */
|
||||
if (rc < 0) { close(fd); fd = -1; continue; }
|
||||
int soerr = 0;
|
||||
socklen_t sl = sizeof soerr;
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &sl) != 0 || soerr != 0) {
|
||||
close(fd);
|
||||
fd = -1;
|
||||
continue;
|
||||
}
|
||||
} else if (rc != 0) {
|
||||
close(fd);
|
||||
fd = -1;
|
||||
continue;
|
||||
}
|
||||
if (flags >= 0) (void)fcntl(fd, F_SETFL, flags);
|
||||
break;
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
if (fd < 0) return -1;
|
||||
struct timeval tv;
|
||||
tv.tv_sec = timeout_ms / 1000;
|
||||
tv.tv_usec = (timeout_ms % 1000) * 1000;
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
|
||||
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ client side */
|
||||
|
||||
/* Fetches one entry from one peer. 0 = hit, everything else = no answer. */
|
||||
static int peer_get(const char *hostport, uint64_t key, char **head_out,
|
||||
size_t *head_len, char **body_out, size_t *body_len, double *age)
|
||||
{
|
||||
char host[256];
|
||||
int port = 0;
|
||||
if (split_hostport(hostport, host, sizeof host, &port) != 0) return -1;
|
||||
int fd = connect_timeout(host, port, CFG.cache_peer_timeout_ms);
|
||||
if (fd < 0) return -1;
|
||||
|
||||
char req[512];
|
||||
int n = snprintf(req, sizeof req,
|
||||
"GET /cache/%016llx HTTP/1.0\r\nX-Junction-Peer: %s\r\n\r\n",
|
||||
(unsigned long long)key, g_secret);
|
||||
if (n <= 0 || write_all(fd, req, (size_t)n) != 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
/* Half close: the peer reads the request until EOF and answers at once. Without
|
||||
* this the peer waits for its receive timeout and the lookup costs seconds
|
||||
* instead of a round trip. */
|
||||
(void)shutdown(fd, SHUT_WR);
|
||||
|
||||
char *buf = malloc(MESH_MAX_XFER);
|
||||
if (!buf) { close(fd); return -1; }
|
||||
ssize_t got = read_until_close(fd, buf, MESH_MAX_XFER);
|
||||
close(fd);
|
||||
if (got <= 0) { free(buf); return -1; }
|
||||
|
||||
char *split = strstr(buf, "\r\n\r\n");
|
||||
if (!split || strncmp(buf, "HTTP/1.", 7) != 0) { free(buf); return -1; }
|
||||
if (strncmp(buf + 9, "200", 3) != 0) { free(buf); return -1; }
|
||||
|
||||
const unsigned char *frame = (const unsigned char *)split + 4;
|
||||
size_t frame_avail = (size_t)got - (size_t)(split + 4 - buf);
|
||||
if (frame_avail < 8) { free(buf); return -1; }
|
||||
uint32_t hl = get_u32(frame), bl = get_u32(frame + 4);
|
||||
if ((size_t)hl + (size_t)bl + 8 > frame_avail || hl > MESH_HEAD_MAX) { free(buf); return -1; }
|
||||
|
||||
char *h = malloc(hl ? hl : 1);
|
||||
char *b = malloc(bl ? bl : 1);
|
||||
if (!h || !b) { free(h); free(b); free(buf); return -1; }
|
||||
memcpy(h, frame + 8, hl);
|
||||
memcpy(b, frame + 8 + hl, bl);
|
||||
|
||||
double a = 0;
|
||||
char *ag = strstr(buf, "X-Age:");
|
||||
if (ag) a = atof(ag + 6);
|
||||
free(buf);
|
||||
|
||||
*head_out = h;
|
||||
*head_len = hl;
|
||||
*body_out = b;
|
||||
*body_len = bl;
|
||||
if (age) *age = a;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Pushes one entry to one peer. Best effort: the answer is read only to keep the
|
||||
* connection tidy. */
|
||||
static void peer_put(const char *hostport, uint64_t key, const char *head,
|
||||
size_t head_len, const char *body, size_t body_len, double ttl_s)
|
||||
{
|
||||
if (head_len > MESH_HEAD_MAX || head_len + body_len > MESH_MAX_XFER) return;
|
||||
char host[256];
|
||||
int port = 0;
|
||||
if (split_hostport(hostport, host, sizeof host, &port) != 0) return;
|
||||
int fd = connect_timeout(host, port, CFG.cache_peer_timeout_ms);
|
||||
if (fd < 0) { count(&g_errors); return; }
|
||||
|
||||
size_t total = 8 + head_len + body_len;
|
||||
unsigned char *frame = malloc(total);
|
||||
if (!frame) { close(fd); return; }
|
||||
put_u32(frame, (uint32_t)head_len);
|
||||
put_u32(frame + 4, (uint32_t)body_len);
|
||||
memcpy(frame + 8, head, head_len);
|
||||
memcpy(frame + 8 + head_len, body, body_len);
|
||||
|
||||
char req[512];
|
||||
int n = snprintf(req, sizeof req,
|
||||
"PUT /cache/%016llx HTTP/1.0\r\nX-Junction-Peer: %s\r\n"
|
||||
"X-TTL: %.0f\r\nContent-Length: %zu\r\n\r\n",
|
||||
(unsigned long long)key, g_secret, ttl_s, total);
|
||||
if (n <= 0 || write_all(fd, req, (size_t)n) != 0 ||
|
||||
write_all(fd, frame, total) != 0) {
|
||||
count(&g_errors);
|
||||
}
|
||||
(void)shutdown(fd, SHUT_WR); /* the peer answers as soon as it has everything */
|
||||
free(frame);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
struct push_job {
|
||||
char hostport[J_URL_MAX];
|
||||
uint64_t key;
|
||||
char *head;
|
||||
size_t head_len;
|
||||
char *body;
|
||||
size_t body_len;
|
||||
double ttl_s;
|
||||
};
|
||||
|
||||
static void *push_thread(void *arg)
|
||||
{
|
||||
struct push_job *j = arg;
|
||||
peer_put(j->hostport, j->key, j->head, j->head_len, j->body, j->body_len, j->ttl_s);
|
||||
free(j->head);
|
||||
free(j->body);
|
||||
free(j);
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_push_inflight--;
|
||||
g_pushes++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int j_mesh_lookup(uint64_t key, char **head, size_t *head_len,
|
||||
char **body, size_t *body_len, double *age)
|
||||
{
|
||||
if (!g_running || CFG.cache_peer_count == 0) return -1;
|
||||
count(&g_lookups);
|
||||
for (int i = 0; i < CFG.cache_peer_count; i++) {
|
||||
double a = 0;
|
||||
if (peer_get(CFG.cache_peer[i], key, head, head_len, body, body_len, &a) == 0) {
|
||||
count(&g_hits);
|
||||
/* Keep only what is left of the entry's life: a peer that reports age 40
|
||||
* of 60 s leaves 20 s here, not another 60. */
|
||||
double left = CFG.cache_ttl_s - a;
|
||||
if (left > 0) (void)j_cache_put(key, *head, *head_len, *body, *body_len, left);
|
||||
if (age) *age = a;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void j_mesh_store(uint64_t key, const char *head, size_t head_len,
|
||||
const char *body, size_t body_len, double ttl_s)
|
||||
{
|
||||
if (!g_running || CFG.cache_peer_count == 0 || ttl_s <= 0) return;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (g_push_inflight >= MESH_MAX_PUSH) {
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
return; /* the entry is in the local cache; a dropped push is not a loss */
|
||||
}
|
||||
g_push_inflight++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
|
||||
for (int i = 0; i < CFG.cache_peer_count; i++) {
|
||||
struct push_job *j = calloc(1, sizeof *j);
|
||||
if (!j) break;
|
||||
snprintf(j->hostport, sizeof j->hostport, "%s", CFG.cache_peer[i]);
|
||||
j->key = key;
|
||||
j->head = malloc(head_len ? head_len : 1);
|
||||
j->body = malloc(body_len ? body_len : 1);
|
||||
if (!j->head || !j->body) {
|
||||
free(j->head);
|
||||
free(j->body);
|
||||
free(j);
|
||||
break;
|
||||
}
|
||||
memcpy(j->head, head, head_len);
|
||||
memcpy(j->body, body, body_len);
|
||||
j->head_len = head_len;
|
||||
j->body_len = body_len;
|
||||
j->ttl_s = ttl_s;
|
||||
|
||||
pthread_t th;
|
||||
pthread_attr_t at;
|
||||
pthread_attr_init(&at);
|
||||
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
|
||||
pthread_attr_setstacksize(&at, 128 * 1024);
|
||||
if (pthread_create(&th, &at, push_thread, j) != 0) {
|
||||
free(j->head);
|
||||
free(j->body);
|
||||
free(j);
|
||||
}
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_push_inflight--; /* the per-peer threads count on their own; this releases the
|
||||
slot held for the whole fan-out */
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ server side */
|
||||
|
||||
static void send_simple_mesh(int fd, int code, const char *reason, const char *body,
|
||||
size_t len)
|
||||
{
|
||||
char head[256];
|
||||
int n = snprintf(head, sizeof head,
|
||||
"HTTP/1.0 %d %s\r\nContent-Type: application/json\r\n"
|
||||
"Content-Length: %zu\r\nConnection: close\r\n\r\n",
|
||||
code, reason, len);
|
||||
if (n <= 0) return;
|
||||
if (write_all(fd, head, (size_t)n) == 0 && len) (void)write_all(fd, body, len);
|
||||
}
|
||||
|
||||
static int secret_ok(const char *req)
|
||||
{
|
||||
if (!g_secret[0]) return 1; /* no secret configured: listener stays off anyway */
|
||||
const char *h = strstr(req, "X-Junction-Peer:");
|
||||
if (!h) return 0;
|
||||
h += strlen("X-Junction-Peer:");
|
||||
while (*h == ' ') h++;
|
||||
size_t n = 0;
|
||||
while (h[n] && h[n] != '\r' && h[n] != '\n') n++;
|
||||
size_t have = strlen(g_secret);
|
||||
if (n != have) return 0;
|
||||
unsigned char diff = 0;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
diff |= (unsigned char)(h[i] ^ g_secret[i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
static void mesh_conn(int fd)
|
||||
{
|
||||
char req[MESH_HEAD_MAX];
|
||||
ssize_t got = read_until_close(fd, req, sizeof req - 1);
|
||||
if (got <= 0) { close(fd); return; }
|
||||
req[got] = '\0';
|
||||
char *end = strstr(req, "\r\n\r\n");
|
||||
if (!end) { close(fd); return; }
|
||||
|
||||
if (!secret_ok(req)) {
|
||||
send_simple_mesh(fd, 401, "Unauthorized", "{\"error\":\"peer secret\"}", 23);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
char method[8] = "", path[128] = "";
|
||||
if (sscanf(req, "%7s %127s", method, path) != 2) { close(fd); return; }
|
||||
|
||||
if (!strcmp(method, "GET") && !strcmp(path, "/cache/stats")) {
|
||||
size_t entries = 0, bytes = 0;
|
||||
unsigned long hits = 0, misses = 0;
|
||||
j_cache_stats(&entries, &bytes, &hits, &misses);
|
||||
char body[256];
|
||||
int n = snprintf(body, sizeof body,
|
||||
"{\"entries\":%zu,\"bytes\":%zu,\"hits\":%lu,\"misses\":%lu}\n",
|
||||
entries, bytes, hits, misses);
|
||||
send_simple_mesh(fd, 200, "OK", body, n > 0 ? (size_t)n : 0);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
uint64_t key = 0;
|
||||
if (strncmp(path, "/cache/", 7) != 0 ||
|
||||
sscanf(path + 7, "%16llx", (unsigned long long *)&key) != 1) {
|
||||
send_simple_mesh(fd, 404, "Not Found", "{\"error\":\"no such path\"}", 23);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!strcmp(method, "GET")) {
|
||||
const char *head = NULL, *body = NULL;
|
||||
size_t head_len = 0, body_len = 0;
|
||||
double age = 0;
|
||||
if (j_cache_get(key, &head, &head_len, &body, &body_len, &age) != 0) {
|
||||
send_simple_mesh(fd, 404, "Not Found", "{\"error\":\"miss\"}", 16);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
size_t total = 8 + head_len + body_len;
|
||||
unsigned char *frame = malloc(total);
|
||||
if (!frame) { close(fd); return; }
|
||||
put_u32(frame, (uint32_t)head_len);
|
||||
put_u32(frame + 4, (uint32_t)body_len);
|
||||
memcpy(frame + 8, head, head_len);
|
||||
memcpy(frame + 8 + head_len, body, body_len);
|
||||
|
||||
char hd[256];
|
||||
int hn = snprintf(hd, sizeof hd,
|
||||
"HTTP/1.0 200 OK\r\nX-Age: %.1f\r\nContent-Type: "
|
||||
"application/octet-stream\r\nContent-Length: %zu\r\n"
|
||||
"Connection: close\r\n\r\n", age, total);
|
||||
if (hn > 0 && write_all(fd, hd, (size_t)hn) == 0)
|
||||
(void)write_all(fd, frame, total);
|
||||
free(frame);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!strcmp(method, "PUT")) {
|
||||
const char *cl = strstr(req, "Content-Length:");
|
||||
if (!cl) { send_simple_mesh(fd, 400, "Bad Request", "{\"error\":\"length\"}", 18); close(fd); return; }
|
||||
size_t want = (size_t)strtoul(cl + 15, NULL, 10);
|
||||
if (want < 8 || want > MESH_MAX_XFER) {
|
||||
send_simple_mesh(fd, 400, "Bad Request", "{\"error\":\"too large\"}", 20);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
size_t have = (size_t)((const char *)end + 4 - req);
|
||||
size_t body_got = (size_t)got - have;
|
||||
unsigned char *frame = malloc(want);
|
||||
if (!frame) { close(fd); return; }
|
||||
memcpy(frame, (const char *)end + 4, body_got < want ? body_got : want);
|
||||
while (body_got < want) {
|
||||
ssize_t n = recv(fd, frame + body_got, want - body_got, 0);
|
||||
if (n > 0) { body_got += (size_t)n; continue; }
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
break;
|
||||
}
|
||||
if (body_got < want) { free(frame); close(fd); return; }
|
||||
|
||||
uint32_t hl = get_u32(frame), bl = get_u32(frame + 4);
|
||||
if (hl > MESH_HEAD_MAX || (size_t)hl + (size_t)bl + 8 > want) { free(frame); close(fd); return; }
|
||||
const char *ttlh = strstr(req, "X-TTL:");
|
||||
double ttl = ttlh ? atof(ttlh + 6) : 0;
|
||||
if (ttl <= 0) ttl = CFG.cache_ttl_s;
|
||||
/* Übertragen wird nur, was hier auch gelten würde: die eigene Obergrenze
|
||||
* entscheidet, nicht die des Nachbarn. */
|
||||
if (ttl > 0 && ttl <= CFG.cache_ttl_s + 1)
|
||||
(void)j_cache_put(key, (const char *)frame + 8, hl,
|
||||
(const char *)frame + 8 + hl, bl, ttl);
|
||||
free(frame);
|
||||
send_simple_mesh(fd, 204, "No Content", "", 0);
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
send_simple_mesh(fd, 405, "Method Not Allowed", "{\"error\":\"method\"}", 19);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
static void *mesh_conn_thread(void *arg)
|
||||
{
|
||||
mesh_conn((int)(long)arg);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void *mesh_listen_thread(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
int cfd = accept(g_lfd, NULL, NULL);
|
||||
if (cfd < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
mlog("cache_peer", "accept failed: %s", strerror(errno));
|
||||
break;
|
||||
}
|
||||
struct timeval tv = { 3, 0 };
|
||||
setsockopt(cfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
|
||||
setsockopt(cfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
|
||||
|
||||
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, mesh_conn_thread, (void *)(long)cfd) != 0)
|
||||
close(cfd);
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int j_mesh_start(void)
|
||||
{
|
||||
const char *sec = NULL;
|
||||
if (CFG.cache_secret_env[0]) {
|
||||
sec = getenv(CFG.cache_secret_env);
|
||||
if (!sec || !sec[0]) {
|
||||
mlog("cache_peer", "disabled: %s is not set (a peer port without a secret "
|
||||
"is an open door)", CFG.cache_secret_env);
|
||||
return 0;
|
||||
}
|
||||
snprintf(g_secret, sizeof g_secret, "%s", sec);
|
||||
}
|
||||
|
||||
if (CFG.cache_tcp_port > 0) {
|
||||
if (!g_secret[0]) {
|
||||
mlog("cache_peer", "disabled: cache tcp without cache secret_env");
|
||||
return 0;
|
||||
}
|
||||
struct sockaddr_in addr;
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) { mlog("cache_peer", "socket failed: %s", strerror(errno)); return 0; }
|
||||
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.cache_tcp_port);
|
||||
if (inet_pton(AF_INET, CFG.cache_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, 32) != 0) {
|
||||
mlog("cache_peer", "tcp %s:%d failed: %s", CFG.cache_tcp_host,
|
||||
CFG.cache_tcp_port, strerror(errno));
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
g_lfd = fd;
|
||||
pthread_t th;
|
||||
if (pthread_create(&th, NULL, mesh_listen_thread, NULL) == 0)
|
||||
pthread_detach(th);
|
||||
mlog("cache_peer", "serving tcp %s:%d peers=%d", CFG.cache_tcp_host,
|
||||
CFG.cache_tcp_port, CFG.cache_peer_count);
|
||||
} else if (CFG.cache_peer_count == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (CFG.cache_peer_count && CFG.cache_ttl_s <= 0) {
|
||||
mlog("cache_peer", "peers configured but cache_ttl is 0 — nobody fills anything");
|
||||
}
|
||||
g_running = 1;
|
||||
if (CFG.cache_peer_count)
|
||||
mlog("cache_peer", "peers=%d timeout_ms=%d ttl_s=%.0f", CFG.cache_peer_count,
|
||||
CFG.cache_peer_timeout_ms, CFG.cache_ttl_s);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void j_mesh_stop(void)
|
||||
{
|
||||
g_running = 0;
|
||||
if (g_lfd >= 0) {
|
||||
int fd = g_lfd;
|
||||
g_lfd = -1;
|
||||
(void)shutdown(fd, SHUT_RDWR);
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
void j_mesh_stats(unsigned long *lookups, unsigned long *hits,
|
||||
unsigned long *pushes, unsigned long *errors, int *peers)
|
||||
{
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (lookups) *lookups = g_lookups;
|
||||
if (hits) *hits = g_hits;
|
||||
if (pushes) *pushes = g_pushes;
|
||||
if (errors) *errors = g_errors;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (peers) *peers = CFG.cache_peer_count;
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/* junction/mesh.h — shared response cache across instances, without a service in
|
||||
* between.
|
||||
*
|
||||
* Every node keeps its cache in its own memory and hands it out over a port of its
|
||||
* own. A node that misses locally asks its peers before it pays the provider; a node
|
||||
* that fills a cache entry pushes it to its peers. No Redis, no memcached, no daemon:
|
||||
* the transport is a very small HTTP subset with a binary frame inside.
|
||||
*
|
||||
* Replication is a speedup, never a dependency. A peer that is slow, dead or has a
|
||||
* different key costs the timeout and nothing else — the request goes to the provider
|
||||
* as if the mesh did not exist. That is why the timeouts are short and the push is
|
||||
* fire-and-forget.
|
||||
*/
|
||||
#ifndef J_MESH_H
|
||||
#define J_MESH_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Starts the listener if the configuration names one. Returns 1 when the mesh is
|
||||
* running, 0 when it is off or the port could not be bound. */
|
||||
int j_mesh_start(void);
|
||||
void j_mesh_stop(void);
|
||||
|
||||
/* 0 = a peer had it; the buffers are malloc'd and belong to the caller.
|
||||
* Everything else = nobody had it, or nobody answered. */
|
||||
int j_mesh_lookup(uint64_t key, char **head, size_t *head_len,
|
||||
char **body, size_t *body_len, double *age);
|
||||
|
||||
/* Hands one filled entry to the peers. Returns immediately; the transfer runs in its
|
||||
* own thread and is dropped when too many are already on their way. */
|
||||
void j_mesh_store(uint64_t key, const char *head, size_t head_len,
|
||||
const char *body, size_t body_len, double ttl_s);
|
||||
|
||||
/* Counters for /status and /metrics. Any pointer may be NULL. */
|
||||
void j_mesh_stats(unsigned long *lookups, unsigned long *hits,
|
||||
unsigned long *pushes, unsigned long *errors, int *peers);
|
||||
|
||||
#endif /* J_MESH_H */
|
||||
Executable
+200
@@ -0,0 +1,200 @@
|
||||
#!/bin/bash
|
||||
# Wird von tests/run.sh eingebunden: mehrere Instanzen, gemeinsamer Cache,
|
||||
# SO_REUSEPORT und Drain.
|
||||
#
|
||||
# Eigener Portbereich (PORT+200 … PORT+207): die kleinen Offsets sind längst vergeben,
|
||||
# und eine Kollision sieht nicht wie ein Fehler im Code aus, sondern wie ein 501 von
|
||||
# irgendeinem anderen Test.
|
||||
|
||||
echo
|
||||
echo "== 33. Zwei Knoten, ein Cache (kein Dienst dazwischen) =="
|
||||
|
||||
CA=$((PORT+200)) # Knoten A
|
||||
CB=$((PORT+201)) # Knoten B
|
||||
PCA=$((PORT+202)) # Cache-Port von A
|
||||
PCB=$((PORT+203)) # Cache-Port von B
|
||||
SECRET="clustertest-$RANDOM"
|
||||
|
||||
MESH=$(echo '{"model":"m","messages":[{"role":"user","content":"wo war ich"}],"max_tokens":5,"temperature":0}')
|
||||
|
||||
# A liefert seinen Cache aus, B fragt A. Beide cachen 300 s.
|
||||
cat > "$TMP/meshA.conf" <<CFG
|
||||
listen 127.0.0.1:$CA
|
||||
log_prefix meshA
|
||||
cache_ttl 300
|
||||
cache_entries 50
|
||||
cache_bytes 2000000
|
||||
cache tcp 127.0.0.1:$PCA
|
||||
cache_secret_env J_MESH_SECRET
|
||||
cache_peer_timeout_ms 300
|
||||
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
|
||||
req for "*" pass a
|
||||
CFG
|
||||
cat > "$TMP/meshB.conf" <<CFG
|
||||
listen 127.0.0.1:$CB
|
||||
log_prefix meshB
|
||||
cache_ttl 300
|
||||
cache_entries 50
|
||||
cache_bytes 2000000
|
||||
cache tcp 127.0.0.1:$PCB
|
||||
cache_secret_env J_MESH_SECRET
|
||||
cache_peer 127.0.0.1:$PCA
|
||||
cache_peer_timeout_ms 300
|
||||
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
|
||||
req for "*" pass a
|
||||
CFG
|
||||
|
||||
J_MESH_SECRET="$SECRET" ./junction --config "$TMP/meshA.conf" > "$TMP/meshA.log" 2>&1 &
|
||||
PIDS+=($!)
|
||||
J_MESH_SECRET="$SECRET" ./junction --config "$TMP/meshB.conf" > "$TMP/meshB.log" 2>&1 &
|
||||
PIDS+=($!)
|
||||
wait_port "$CA" 10 || bad "node A did not come up"
|
||||
wait_port "$CB" 10 || bad "node B did not come up"
|
||||
|
||||
# Der Secret-Schutz ist keine Zierde: ohne Kopfzeile gibt es nichts.
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -m 5 "http://127.0.0.1:$PCA/cache/stats")
|
||||
[ "$code" = "401" ] && ok "cache port refuses a caller without the peer secret" \
|
||||
|| bad "cache port answered $code without the peer secret"
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -m 5 -H "X-Junction-Peer: falsch" \
|
||||
"http://127.0.0.1:$PCA/cache/stats")
|
||||
[ "$code" = "401" ] && ok "a wrong peer secret is refused too" \
|
||||
|| bad "a wrong secret was accepted ($code)"
|
||||
|
||||
# Anfrage an A: füllt den Cache und stößt die Weitergabe an B an.
|
||||
c1=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' \
|
||||
-d "$MESH" "http://127.0.0.1:$CA/v1/chat/completions" \
|
||||
| tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p')
|
||||
[ "$c1" = "miss" ] && ok "node A misses and pays the provider" \
|
||||
|| bad "node A answered cache=$c1 on the first request"
|
||||
|
||||
sleep 0.4 # die Weitergabe läuft in einem eigenen Faden
|
||||
|
||||
# Dieselbe Anfrage an B: sie darf den Anbieter nicht mehr fragen.
|
||||
c2=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' \
|
||||
-d "$MESH" "http://127.0.0.1:$CB/v1/chat/completions" \
|
||||
| tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p')
|
||||
[ "$c2" = "hit" ] && ok "node B answers the same question from the shared cache" \
|
||||
|| bad "node B answered cache=$c2 instead of a hit from the peer"
|
||||
|
||||
log_has "$TMP/meshB.log" "via=peer" "node B names the peer as the source"
|
||||
if grep -q "served_by" "$TMP/meshB.log"; then
|
||||
bad "node B asked the provider although the peer had the answer"
|
||||
else
|
||||
ok "node B did not call the provider at all"
|
||||
fi
|
||||
|
||||
# Ein Treffer beim Nachbarn ist auch lokal gelandet — der zweite Aufruf ist billig.
|
||||
c3=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' \
|
||||
-d "$MESH" "http://127.0.0.1:$CB/v1/chat/completions" \
|
||||
| tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p')
|
||||
[ "$c3" = "hit" ] && ok "the peer hit stayed in B's own cache" \
|
||||
|| bad "the peer hit was not kept locally (cache=$c3)"
|
||||
|
||||
# Und der Cache-Port gibt Auskunft, wenn man das Geheimnis hat.
|
||||
stats=$(curl -s -m 5 -H "X-Junction-Peer: $SECRET" "http://127.0.0.1:$PCA/cache/stats")
|
||||
contains "$stats" '"entries"' "the cache port reports its own numbers"
|
||||
|
||||
# Ein Nachbar, der nicht antwortet, darf eine Anfrage nicht aufhalten: der Zeitablauf
|
||||
# ist die Obergrenze, und danach geht es zum Anbieter wie ohne Mesh.
|
||||
cat > "$TMP/meshD.conf" <<CFG
|
||||
listen 127.0.0.1:$((PORT+207))
|
||||
log_prefix meshD
|
||||
cache_ttl 300
|
||||
cache_secret_env J_MESH_SECRET
|
||||
cache_peer 127.0.0.1:$P_SLOW
|
||||
cache_peer_timeout_ms 200
|
||||
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
|
||||
req for "*" pass a
|
||||
CFG
|
||||
J_MESH_SECRET="$SECRET" ./junction --config "$TMP/meshD.conf" > "$TMP/meshD.log" 2>&1 &
|
||||
PIDS+=($!)
|
||||
wait_port "$((PORT+207))" 10 || bad "node D did not come up"
|
||||
read -r dcode dtime < <(curl -s -o /dev/null -m 10 -w '%{http_code} %{time_total}' \
|
||||
-X POST -H 'Content-Type: application/json' -d "$MESH" \
|
||||
"http://127.0.0.1:$((PORT+207))/v1/chat/completions")
|
||||
if [ "$dcode" = "200" ] && awk "BEGIN{exit !($dtime < 2.0)}"; then
|
||||
ok "a silent peer costs only the timeout ($dtime s), the request still succeeds"
|
||||
else
|
||||
bad "a silent peer stalled the request (http=$dcode after ${dtime}s)"
|
||||
fi
|
||||
|
||||
# Ein Knoten ohne Geheimnis öffnet den Port gar nicht erst.
|
||||
cat > "$TMP/meshC.conf" <<CFG
|
||||
listen 127.0.0.1:$((PORT+204))
|
||||
log_prefix meshC
|
||||
cache_ttl 60
|
||||
cache tcp 127.0.0.1:$((PORT+205))
|
||||
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
|
||||
req for "*" pass a
|
||||
CFG
|
||||
./junction --config "$TMP/meshC.conf" > "$TMP/meshC.log" 2>&1 &
|
||||
PIDS+=($!)
|
||||
sleep 0.6
|
||||
log_has "$TMP/meshC.log" "disabled: cache tcp without cache secret_env" \
|
||||
"a peer port without a secret stays closed"
|
||||
|
||||
echo
|
||||
echo "== 34. Rolling Update: zwei Instanzen auf einem Port, Drain bei SIGTERM =="
|
||||
|
||||
RP=$((PORT+206))
|
||||
cat > "$TMP/roll1.conf" <<CFG
|
||||
listen 127.0.0.1:$RP
|
||||
log_prefix roll1
|
||||
so_reuseport on
|
||||
drain_timeout 5
|
||||
cache_ttl 60
|
||||
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
|
||||
req for "*" pass a
|
||||
CFG
|
||||
sed 's/roll1/roll2/' "$TMP/roll1.conf" > "$TMP/roll2.conf"
|
||||
|
||||
./junction --config "$TMP/roll1.conf" > "$TMP/roll1.log" 2>&1 &
|
||||
R1=$!
|
||||
PIDS+=($R1)
|
||||
wait_port "$RP" 10 || bad "instance 1 did not come up"
|
||||
./junction --config "$TMP/roll2.conf" > "$TMP/roll2.log" 2>&1 &
|
||||
R2=$!
|
||||
PIDS+=($R2)
|
||||
|
||||
# Beide müssen gleichzeitig auf demselben Port hören — das ist SO_REUSEPORT.
|
||||
both=0 i=0
|
||||
while [ "$i" -lt 40 ]; do
|
||||
if grep -q "listening addr=127.0.0.1:$RP" "$TMP/roll2.log" 2>/dev/null; then both=1; break; fi
|
||||
sleep 0.05; i=$((i+1))
|
||||
done
|
||||
if [ "$both" = "1" ]; then
|
||||
ok "a second instance binds the same port while the first serves"
|
||||
else
|
||||
bad "the second instance could not bind the same port"
|
||||
sed 's/^/ /' "$TMP/roll2.log" | tail -3
|
||||
fi
|
||||
|
||||
# Ein hängender Upstream, damit beim Drain wirklich etwas läuft.
|
||||
SHORT='{"model":"m","messages":[{"role":"user","content":"drain"}],"max_tokens":5,"temperature":0}'
|
||||
( curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' -d "$SHORT" \
|
||||
"http://127.0.0.1:$RP/v1/chat/completions" ) &
|
||||
CURLPID=$!
|
||||
|
||||
kill -TERM "$R1" 2>/dev/null
|
||||
i=0
|
||||
while [ "$i" -lt 60 ]; do kill -0 "$R1" 2>/dev/null || break; sleep 0.05; i=$((i+1)); done
|
||||
log_has "$TMP/roll1.log" "draining closed_listener" "the retired instance stops accepting"
|
||||
log_has "$TMP/roll1.log" "drained " "it finishes what was running and exits"
|
||||
wait "$CURLPID" 2>/dev/null
|
||||
|
||||
# Derweil bedient die zweite Instanz weiter — ohne Ausfall.
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -m 10 -X POST -H 'Content-Type: application/json' \
|
||||
-d "$SHORT" "http://127.0.0.1:$RP/v1/chat/completions")
|
||||
[ "$code" = "200" ] && ok "the new instance serves during and after the handover" \
|
||||
|| bad "requests failed after the handover (http=$code)"
|
||||
|
||||
# Ein zweiter Start ohne so_reuseport darf nicht mehr binden.
|
||||
sed 's/so_reuseport on/so_reuseport off/; s/roll1/roll3/' "$TMP/roll1.conf" > "$TMP/roll3.conf"
|
||||
./junction --config "$TMP/roll3.conf" > "$TMP/roll3.log" 2>&1 &
|
||||
PIDS+=($!)
|
||||
sleep 0.6
|
||||
log_has "$TMP/roll3.log" "Address already in use" \
|
||||
"without so_reuseport the port stays exclusive"
|
||||
|
||||
kill -TERM "$R2" 2>/dev/null
|
||||
+5
-1
@@ -46,7 +46,7 @@ log_has() {
|
||||
# answer requests with somebody else's config), so fail loudly and early.
|
||||
# 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem
|
||||
# Test benutzt, also darf er die Suite nicht aufhalten.
|
||||
for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do
|
||||
for port in 8335 8336 8337 8338 8339 8340 8341 8342 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do
|
||||
if ss -tln 2>/dev/null | grep -q ":$port "; then
|
||||
echo "port $port is busy — a leftover junction/stub is still running:"
|
||||
ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /'
|
||||
@@ -699,6 +699,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected"
|
||||
# shellcheck source=tests/usage.sh
|
||||
. "$(dirname "$0")/usage.sh"
|
||||
|
||||
# Mehrere Instanzen, gemeinsamer Cache, SO_REUSEPORT, Drain.
|
||||
# shellcheck source=tests/cluster.sh
|
||||
. "$(dirname "$0")/cluster.sh"
|
||||
|
||||
# junction als MCP-Server: Werkzeuge der angebundenen Server bündeln und
|
||||
# Aufrufe an den richtigen Server weiterreichen. Eigenes Programm, weil zwei
|
||||
# erfundene MCP-Server gebraucht werden.
|
||||
|
||||
Reference in new issue
Block a user