junction: per-target 'as', example config for the van, C WoL helper
- A rule may send a different model name per target: 'pass peer-a as M, peer-b, cloud' rewrites only for peer-a, so a mixed local/cloud rule still asks the cloud for the name the client wanted. - examples/olivia.conf: peers on the tunnel, embedding box, sleeping workstation with WoL + energy gate, cloud fallback, and the policy rules each with its reason. - tools/junction-wol.c replaces the Python magic-packet helper; hooks stay shell. - Forwarding no longer duplicates Host/Content-Length/X-Forwarded-*: Ollama answered 400 to a request that was valid because it arrived with two Host headers. - need_tokens: embeddings produce a vector, not tokens, so they are not charged default_max_tokens (a 2048-context embed endpoint refused every request). - /status lists every target with its model, plus the rule's need window.
This commit is contained in:
1 parent
dc31481914
commit
87e6348642
10 files changed
+407
-97
No files matched your search
@@ -9,6 +9,7 @@ J_WITH_TLS ?= auto
|
||||
|
||||
SRC = src/config.c src/conn.c src/http.c src/cache.c src/junction.c
|
||||
OBJ = $(SRC:.c=.o)
|
||||
TOOLS = tools/junction-wol
|
||||
|
||||
ifeq ($(J_WITH_TLS),0)
|
||||
TLS_LIBS =
|
||||
@@ -21,7 +22,10 @@ TLS_LIBS = -lssl -lcrypto
|
||||
endif
|
||||
endif
|
||||
|
||||
all: junction
|
||||
all: junction $(TOOLS)
|
||||
|
||||
tools/junction-wol: tools/junction-wol.c
|
||||
$(CC) -std=c99 -O2 -Wall -Wextra -Wpedantic $< -o $@
|
||||
|
||||
junction: $(OBJ)
|
||||
$(CC) $(CFLAGS) $(OBJ) -o $@ $(LDFLAGS) $(TLS_LIBS)
|
||||
@@ -32,13 +36,17 @@ src/%.o: src/%.c src/config.h src/conn.h src/http.h src/cache.h
|
||||
test: junction
|
||||
tests/run.sh
|
||||
|
||||
install: junction
|
||||
install: junction $(TOOLS)
|
||||
install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/share/junction/hooks
|
||||
install -m 0755 junction $(DESTDIR)$(PREFIX)/bin/junction
|
||||
install -m 0755 $(TOOLS) $(DESTDIR)$(PREFIX)/bin/junction-wol
|
||||
install -m 0755 hooks/*.sh $(DESTDIR)$(PREFIX)/share/junction/hooks/
|
||||
install -m 0755 $(TOOLS) $(DESTDIR)$(PREFIX)/share/junction/hooks/
|
||||
install -m 0644 config.example $(DESTDIR)$(PREFIX)/share/junction/junction.conf
|
||||
install -d $(DESTDIR)$(PREFIX)/share/junction/examples
|
||||
install -m 0644 examples/*.conf $(DESTDIR)$(PREFIX)/share/junction/examples/
|
||||
|
||||
clean:
|
||||
rm -f $(OBJ) junction
|
||||
rm -f $(OBJ) junction $(TOOLS)
|
||||
|
||||
.PHONY: all test install clean
|
||||
@@ -31,6 +31,9 @@ serves it — and what to do when none of them wants to.
|
||||
headers can be added per endpoint, and `X-Forwarded-For`/`Proto` are appended.
|
||||
Every response carries `X-Junction-Endpoint`, `X-Junction-Ms`, `X-Junction-Cache`.
|
||||
|
||||
A worked, annotated configuration for a mixed local/cloud setup is in
|
||||
`examples/olivia.conf`; `config.example` is the same grammar, reduced to the bones.
|
||||
|
||||
## Build / run
|
||||
|
||||
```bash
|
||||
@@ -114,7 +117,9 @@ req [for <model-glob>] [path <glob>] [need >N | <N | N]
|
||||
- `check hooks|none` — override the endpoint's hook list for this rule.
|
||||
- `retry <s>` — override `hook_retry` ("wait up to N s for the box").
|
||||
- `pass a, b` — try `a`, then `b` on failure.
|
||||
- `as <model>` — rewrite the `model` field before forwarding.
|
||||
- `as <model>` — **after a target**, rewrite the `model` field for that target only:
|
||||
`pass peer-a as "qwen3.8-flash-next-q1m", peer-b, cloud` sends the local id to the
|
||||
peers and the requested id to the cloud.
|
||||
- `block` — refuse with `403`.
|
||||
|
||||
No matching rule → `503 no_matching_rule`: an unmatched request is a config gap, not
|
||||
@@ -171,6 +176,9 @@ Exit non-zero and print the reason on stdout — it lands in `/status` and in th
|
||||
|
||||
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.
|
||||
|
||||
## Known limits (v0.1, deliberately named)
|
||||
|
||||
- **One request at a time.** The accept loop handles a request to completion before
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# ============================================================================
|
||||
# junction.conf — Olivia
|
||||
#
|
||||
# One front door for every model endpoint in the van. Clients (Hermes, scripts,
|
||||
# editors) talk to 127.0.0.1:8090 and never learn which machine answered.
|
||||
#
|
||||
# Shape of the file: keyword, arguments, braces. '#' comments, "" groups words,
|
||||
# first matching rule wins. A typo is a hard error with a line number — this file
|
||||
# decides where requests go, so silence would be the worst behaviour.
|
||||
# ============================================================================
|
||||
|
||||
listen 0.0.0.0:8090
|
||||
# Same thing over TLS, no proxy in front (clients must then use https://):
|
||||
# listen 0.0.0.0:8443 tls /etc/junction/tls/olivia-cert.pem /etc/junction/tls/olivia-key.pem
|
||||
|
||||
log_prefix olivia
|
||||
|
||||
chars_per_token 4 # rough, only used to pick an endpoint
|
||||
default_max_tokens 4096 # assumed when the request does not say
|
||||
connect_timeout_ms 1200 # a box that cannot answer a SYN in 1.2 s is asleep
|
||||
offline_hold_s 20 # stop retrying a dead box for this long
|
||||
max_body_bytes 67108864 # 64 MiB: a long conversation, not a file upload
|
||||
|
||||
# Answers to identical requests, kept in RAM. Only complete, non-streamed 200s are
|
||||
# stored; streams and "no-store" responses never are. 0 disables the cache.
|
||||
cache_ttl 120
|
||||
cache_entries 256
|
||||
cache_bytes 67108864
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The two peers on the workstation, over the WireGuard tunnel. They serve the big
|
||||
# local model when its kanban is idle, so "reachable" is not the same as "free":
|
||||
# check-http.sh asks /v1/models, and hook_retry gives them a moment to finish.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
endpoint peer-a {
|
||||
base http://172.25.206.3:8081/v1
|
||||
kind local
|
||||
context 64000
|
||||
priority 10
|
||||
timeout 1800 # long jobs are fine: 30 minutes of wall clock
|
||||
idle_timeout 45 # ... as long as something arrives every 45 s
|
||||
cooldown 60
|
||||
hook /usr/local/share/junction/hooks/check-http.sh
|
||||
hook_retry 45 # up to 45 s of "kanban still running, wait"
|
||||
hook_backoff 5
|
||||
header "X-Junction-Peer: a"
|
||||
}
|
||||
|
||||
endpoint peer-b {
|
||||
base http://172.25.206.3:8082/v1
|
||||
kind local
|
||||
context 64000
|
||||
priority 20
|
||||
timeout 1800
|
||||
idle_timeout 45
|
||||
cooldown 60
|
||||
hook /usr/local/share/junction/hooks/check-http.sh
|
||||
hook_retry 45
|
||||
hook_backoff 5
|
||||
header "X-Junction-Peer: b"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The embedding model on the other machine: small, always on, never woken.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
endpoint kitt-embed {
|
||||
base http://192.168.1.116:11434/v1
|
||||
kind local
|
||||
context 2048
|
||||
priority 5
|
||||
timeout 120
|
||||
idle_timeout 15
|
||||
cooldown 120
|
||||
cache off # embeddings are cheap to repeat, not worth the RAM
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A machine that sleeps. The hooks decide whether it is worth waking, the wake
|
||||
# command is run once, and the request waits up to four minutes for it to come
|
||||
# back. WoL is layer 2: junction-wol sends to a broadcast address, so this works
|
||||
# on the segment n95 sits on, not across the tunnel.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
endpoint desk {
|
||||
base http://192.168.1.99:8080/v1
|
||||
kind local
|
||||
context 128000
|
||||
priority 5
|
||||
timeout 3600
|
||||
idle_timeout 60
|
||||
cooldown 120
|
||||
wake /usr/local/share/junction/hooks/wake-wol.sh
|
||||
hook_retry 240
|
||||
hook_backoff 10
|
||||
hook /usr/local/share/junction/hooks/check-http.sh
|
||||
hook /usr/local/share/junction/hooks/check-budget.sh # only when the sun pays
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The cloud. Last resort for context that does not fit, models the van does not
|
||||
# have, and anything the local boxes refuse. Key never lives in this file.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
endpoint cloud {
|
||||
base https://opencode.ai/zen/go/v1
|
||||
kind cloud
|
||||
context 200000
|
||||
priority 90
|
||||
timeout 900
|
||||
idle_timeout 120
|
||||
cache off # never store answers from outside
|
||||
tls_verify on
|
||||
api_key_env OPENCODE_API_KEY
|
||||
}
|
||||
|
||||
# ===========================================================================
|
||||
# Rules. Read top to bottom, first match wins. Everything below is a policy
|
||||
# decision, so each line says what it is for.
|
||||
# ===========================================================================
|
||||
|
||||
# Metadata calls are cheap and must never wake anything.
|
||||
req path "/v1/models" check none pass peer-a, peer-b, cloud
|
||||
|
||||
# Embeddings stay local. No cloud fallback: a travelling text does not belong
|
||||
# in a request to a third party, and the local box has the model.
|
||||
req for "*embed*" check none pass kitt-embed
|
||||
|
||||
# Nothing needs more than the peers' 64k? Then the peers are not a candidate at
|
||||
# all — pick the only boxes that can hold the request.
|
||||
req need >64000 pass desk, cloud
|
||||
|
||||
# Coding work wants the big context local box; the workstation gets woken for it,
|
||||
# then the peers, then (reluctantly) the cloud.
|
||||
req for "*coder*" check hooks retry 300 pass desk, peer-a, peer-b, cloud
|
||||
|
||||
# The peers answer to a different id than clients ask for: "as <model>" after a target
|
||||
# rewrites the model field for THAT target only, so the cloud still gets the name the
|
||||
# client asked for.
|
||||
req for "Qwen3.8-Flash-Next*" retry 60 pass peer-a as "qwen3.8-flash-next-q1m", peer-b as "qwen3.8-flash-next-q1m", cloud
|
||||
|
||||
# Anything with the local-only prefix never leaves the van, and if the vans own
|
||||
# boxes are down the request fails loudly instead of going out.
|
||||
req for "local-only-*" pass peer-a, peer-b
|
||||
|
||||
# Cloud-only model ids.
|
||||
req for "deepseek-*" pass cloud
|
||||
req for "gpt-*" pass cloud
|
||||
|
||||
# A model that must never be called at all. Refused with 403 and the rule's line
|
||||
# number, which is the fastest way to answer "why is this not working?".
|
||||
req for "blocked-*" block
|
||||
|
||||
# Everything else: local first, cloud only when nothing local answers.
|
||||
req for "*" pass peer-a, peer-b, desk, cloud
|
||||
+25
-16
@@ -1,22 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Example "may I spend energy on this?" hook.
|
||||
# Reads a JSON document (any URL) and refuses below a threshold.
|
||||
# JUNCTION_BUDGET_URL e.g. http://127.0.0.1:8123/api/states/sensor.battery
|
||||
# JUNCTION_BUDGET_FIELD e.g. state
|
||||
# JUNCTION_BUDGET_MIN e.g. 55
|
||||
url="${JUNCTION_BUDGET_URL:-}"; min="${JUNCTION_BUDGET_MIN:-0}"
|
||||
[ -z "$url" ] && { echo "no_budget_url_configured"; exit 0; }
|
||||
body=$(curl -s -m 4 "$url" 2>/dev/null) || { echo "budget_source_unreachable"; exit 1; }
|
||||
value=$(printf '%s' "$body" | python3 -c '
|
||||
import json,sys
|
||||
doc=json.load(sys.stdin)
|
||||
if isinstance(doc,dict):
|
||||
print(doc.get("state", doc.get("value","")))
|
||||
' 2>/dev/null)
|
||||
# "May I spend energy on this?" — refuse when a number from a JSON document is below
|
||||
# a threshold. Typical source: a Home Assistant sensor state.
|
||||
# JUNCTION_BUDGET_URL http://127.0.0.1:8123/api/states/sensor.smartshunt_soc
|
||||
# JUNCTION_BUDGET_MIN 55
|
||||
# JUNCTION_BUDGET_TOKEN optional bearer token for that URL
|
||||
#
|
||||
# Pure sh + sed/awk: a hook has no business starting an interpreter.
|
||||
url="${JUNCTION_BUDGET_URL:-}"
|
||||
min="${JUNCTION_BUDGET_MIN:-0}"
|
||||
[ -z "$url" ] && exit 0 # not configured = do not gate
|
||||
|
||||
if [ -n "${JUNCTION_BUDGET_TOKEN:-}" ]; then
|
||||
body=$(curl -s -m 4 -H "Authorization: Bearer $JUNCTION_BUDGET_TOKEN" "$url" 2>/dev/null)
|
||||
else
|
||||
body=$(curl -s -m 4 "$url" 2>/dev/null)
|
||||
fi
|
||||
[ -n "$body" ] || { echo "budget_source_unreachable"; exit 1; }
|
||||
|
||||
value=$(printf '%s' "$body" | tr -d '\n' |
|
||||
sed -n 's/.*"state"[[:space:]]*:[[:space:]]*"\{0,1\}\([-0-9.][0-9.]*\)"\{0,1\}.*/\1/p' |
|
||||
head -n 1)
|
||||
case "$value" in
|
||||
''|*[!0-9.]*) echo "budget_unreadable: ${value:-empty}"; exit 1 ;;
|
||||
esac
|
||||
if python3 -c "import sys; sys.exit(0 if float('$value') >= float('$min') else 1)"; then
|
||||
|
||||
if awk -v v="$value" -v m="$min" 'BEGIN { exit !(v + 0 >= m + 0) }'; then
|
||||
exit 0
|
||||
fi
|
||||
echo "budget_${value}_below_${min}"; exit 1
|
||||
echo "budget_${value}_below_${min}"
|
||||
exit 1
|
||||
+18
-18
@@ -1,19 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Wake a machine with a magic packet. Needs JUNCTION_WAKE_MAC (aa:bb:cc:dd:ee:ff).
|
||||
# Uses `wakeonlan` when installed; otherwise sends the packet itself.
|
||||
[ -z "${JUNCTION_WAKE_MAC:-}" ] && { echo "no_JUNCTION_WAKE_MAC"; exit 1; }
|
||||
if command -v wakeonlan >/dev/null 2>&1; then
|
||||
exec wakeonlan "$JUNCTION_WAKE_MAC"
|
||||
fi
|
||||
python3 - "$JUNCTION_WAKE_MAC" <<'PY'
|
||||
import socket, sys
|
||||
mac = sys.argv[1].replace(":", "").replace("-", "")
|
||||
if len(mac) != 12:
|
||||
print("bad_mac"); sys.exit(1)
|
||||
pkt = b"\xff" * 6 + bytes.fromhex(mac) * 16
|
||||
for addr in ("255.255.255.255",):
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
s.sendto(pkt, (addr, 9)); s.close()
|
||||
print("sent")
|
||||
PY
|
||||
# Wake a machine with a magic packet.
|
||||
# JUNCTION_WAKE_MAC aa:bb:cc:dd:ee:ff (required)
|
||||
# JUNCTION_WAKE_BCAST 255.255.255.255 (optional, use the subnet broadcast
|
||||
# when directed broadcast is filtered)
|
||||
# Needs junction-wol next to this script (installed with the package) or in $PATH.
|
||||
mac="${JUNCTION_WAKE_MAC:-}"
|
||||
[ -z "$mac" ] && { echo "no_JUNCTION_WAKE_MAC"; exit 1; }
|
||||
bcast="${JUNCTION_WAKE_BCAST:-255.255.255.255}"
|
||||
|
||||
here=$(dirname "$0")
|
||||
# installed next to the hook, or in the source tree's tools/ when run from the repo
|
||||
for wol in "$here/junction-wol" "$here/../tools/junction-wol" \
|
||||
"$(command -v junction-wol 2>/dev/null)"; do
|
||||
[ -n "$wol" ] && [ -x "$wol" ] || continue
|
||||
exec "$wol" "$mac" "$bcast"
|
||||
done
|
||||
echo "junction-wol_not_found"
|
||||
exit 1
|
||||
+26
-26
@@ -302,37 +302,37 @@ static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t
|
||||
return 0;
|
||||
} else if (!strcmp(k, "pass")) {
|
||||
if (i + 1 >= n) goto bad;
|
||||
/* targets run until "as" or the end of the line; they may be written as
|
||||
* one comma list, as separate words, or both. */
|
||||
int j = i + 1;
|
||||
char joined[J_CMD_MAX] = "";
|
||||
size_t ju = 0;
|
||||
for (; j < n && strcmp(w[j], "as"); j++) {
|
||||
int wrote = snprintf(joined + ju, sizeof joined - ju, "%s%s",
|
||||
ju ? "," : "", w[j]);
|
||||
if (wrote < 0) break;
|
||||
ju += (size_t)wrote;
|
||||
}
|
||||
char *save = NULL;
|
||||
for (char *tok = strtok_r(joined, ",", &save); tok;
|
||||
tok = strtok_r(NULL, ",", &save)) {
|
||||
while (*tok == ' ') tok++;
|
||||
if (!*tok) continue;
|
||||
/* Targets run to the end of the line. Each may carry its own model:
|
||||
* pass peer-a as "local-id", peer-b, cloud
|
||||
* A trailing comma on a target or a model is accepted, so both
|
||||
* "peer-a as M, peer-b" and "peer-a, as M" parse the same way. */
|
||||
for (int j = i + 1; j < n; ) {
|
||||
char name[J_NAME_MAX];
|
||||
snprintf(name, sizeof name, "%s", w[j++]);
|
||||
size_t nl = strlen(name);
|
||||
while (nl && (name[nl - 1] == ',' || name[nl - 1] == ' ')) name[--nl] = '\0';
|
||||
if (!nl) continue; /* a lone comma */
|
||||
if (r->target_count >= J_MAX_TARGETS) {
|
||||
snprintf(err, errlen, "line %d: more than %d pass targets", lineno, J_MAX_TARGETS);
|
||||
snprintf(err, errlen, "line %d: more than %d targets", lineno, J_MAX_TARGETS);
|
||||
return -1;
|
||||
}
|
||||
snprintf(r->targets[r->target_count++], J_NAME_MAX, "%s", tok);
|
||||
int idx = r->target_count;
|
||||
snprintf(r->targets[idx], sizeof r->targets[idx], "%s", name);
|
||||
r->target_as[idx][0] = '\0';
|
||||
if (j < n && !strcmp(w[j], "as")) {
|
||||
if (j + 1 >= n) goto bad;
|
||||
char model[J_GLOB_MAX];
|
||||
snprintf(model, sizeof model, "%s", w[j + 1]);
|
||||
size_t ml = strlen(model);
|
||||
while (ml && (model[ml - 1] == ',' || model[ml - 1] == ' ')) model[--ml] = '\0';
|
||||
if (!ml) goto bad;
|
||||
snprintf(r->target_as[idx], sizeof r->target_as[idx], "%s", model);
|
||||
j += 2;
|
||||
}
|
||||
r->target_count++;
|
||||
}
|
||||
if (!r->target_count) goto bad;
|
||||
i = j;
|
||||
/* optional: as MODEL */
|
||||
if (i < n && !strcmp(w[i], "as")) {
|
||||
if (i + 1 >= n) goto bad;
|
||||
snprintf(r->rewrite_model, sizeof r->rewrite_model, "%s", w[i + 1]);
|
||||
i += 2;
|
||||
}
|
||||
if (i != n) goto bad;
|
||||
i = n;
|
||||
return 0;
|
||||
} else {
|
||||
snprintf(err, errlen, "line %d: unknown rule keyword '%s'", lineno, k);
|
||||
|
||||
+5
-2
@@ -40,7 +40,7 @@
|
||||
#define J_MAX_ENDPOINTS 32
|
||||
#define J_MAX_HOOKS 8
|
||||
#define J_MAX_RULES 64
|
||||
#define J_MAX_TARGETS 4
|
||||
#define J_MAX_TARGETS 8
|
||||
#define J_NAME_MAX 64
|
||||
#define J_URL_MAX 512
|
||||
#define J_CMD_MAX 512
|
||||
@@ -96,8 +96,11 @@ typedef struct {
|
||||
|
||||
int block; /* 1 = refuse the request */
|
||||
char targets[J_MAX_TARGETS][J_NAME_MAX];
|
||||
/* Per target: the model name to send instead of the requested one. Boxes serve
|
||||
* different ids ("Qwen3.8-Flash-Next" is loaded as "qwen3.8-flash-next-q1m"), so
|
||||
* the rewrite belongs to the target, not to the rule. */
|
||||
char target_as[J_MAX_TARGETS][J_GLOB_MAX];
|
||||
int target_count;
|
||||
char rewrite_model[J_GLOB_MAX];/* "" = pass the model through unchanged */
|
||||
int line;
|
||||
} j_rule;
|
||||
|
||||
|
||||
+79
-31
@@ -132,16 +132,27 @@ static void json_str_value(const char *body, const char *key, char *out, size_t
|
||||
out[i] = '\0';
|
||||
}
|
||||
|
||||
static long need_tokens(const char *body)
|
||||
/* How much context does this request need?
|
||||
*
|
||||
* Input is estimated from the text; the output side has to be guessed. For a
|
||||
* completion the default output size applies, but an embeddings request produces a
|
||||
* vector, not tokens — charging it `default_max_tokens` made every embedding request
|
||||
* "too large" for a small-context embedding endpoint. */
|
||||
static long need_tokens(const char *body, const char *path)
|
||||
{
|
||||
size_t chars = 0;
|
||||
if (body) {
|
||||
chars += count_value_chars(body, "content");
|
||||
chars += count_value_chars(body, "prompt");
|
||||
chars += count_value_chars(body, "input");
|
||||
}
|
||||
long mt = body ? json_int_value(body, "max_tokens") : -1;
|
||||
if (mt < 0 && body) mt = json_int_value(body, "max_completion_tokens");
|
||||
if (mt < 0) mt = CFG.default_max_tokens;
|
||||
|
||||
int embeddings = (path && strstr(path, "embedding")) ||
|
||||
(body && strstr(body, "\"input\"") && !strstr(body, "\"messages\""));
|
||||
if (mt < 0) mt = embeddings ? 0 : CFG.default_max_tokens;
|
||||
|
||||
long cpt = CFG.chars_per_token > 0 ? CFG.chars_per_token : 4;
|
||||
return (long)(chars / (size_t)cpt) + mt;
|
||||
}
|
||||
@@ -274,10 +285,22 @@ static void status_page(j_conn *c)
|
||||
CFG.cache_ttl_s, entries, bytes, hits, misses, CFG.listen_tls ? "true" : "false");
|
||||
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") */
|
||||
char chain[1024] = "";
|
||||
size_t cu = 0;
|
||||
for (int tgt = 0; tgt < r->target_count && cu < sizeof chain - 1; tgt++) {
|
||||
int wrote = snprintf(chain + cu, sizeof chain - cu, "%s%s%s%s",
|
||||
tgt ? ", " : "", r->targets[tgt],
|
||||
r->target_as[tgt][0] ? " as " : "",
|
||||
r->target_as[tgt]);
|
||||
if (wrote < 0) break;
|
||||
cu += (size_t)wrote;
|
||||
}
|
||||
used += (size_t)snprintf(out + used, cap - used,
|
||||
"%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"targets\":\"%s\"}",
|
||||
"%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"need_min\":%ld,"
|
||||
"\"need_max\":%ld,\"targets\":\"%s\"}",
|
||||
i ? "," : "", r->line, r->model_glob, r->path_glob,
|
||||
r->block ? "true" : "false", r->targets[0]);
|
||||
r->block ? "true" : "false", r->need_min, r->need_max, chain);
|
||||
}
|
||||
snprintf(out + used, cap - used, "]}");
|
||||
send_simple(c, 200, "OK", out);
|
||||
@@ -628,8 +651,9 @@ static int read_response(j_conn *up, j_upstream_resp *r, double idle_s, double d
|
||||
/* Returns 0 = served, -1 = endpoint failed (fail over), -2 = bytes already sent to the
|
||||
* client, so failing over is impossible. */
|
||||
static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
const char *out_body, size_t out_len, const char *out_model,
|
||||
const char *cache_state, double req_started, char *err, size_t errlen)
|
||||
const char *out_body, size_t out_len, const char *as_model,
|
||||
const char *rq_model, const char *cache_state, double req_started,
|
||||
char *err, size_t errlen)
|
||||
{
|
||||
char host[J_NAME_MAX], port[16], prefix[J_URL_MAX];
|
||||
int tls = 0;
|
||||
@@ -638,10 +662,19 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* the model this endpoint answers to may differ from what was asked for */
|
||||
char *rewritten = NULL;
|
||||
if (as_model && as_model[0] && out_body) {
|
||||
rewritten = rewrite_model(out_body, as_model);
|
||||
if (rewritten) { out_body = rewritten; out_len = strlen(rewritten); }
|
||||
}
|
||||
|
||||
j_conn up = J_CONN_INIT;
|
||||
if (j_conn_open(&up, host, port, tls, tls ? ep->tls_verify : 0, ep->tls_ca,
|
||||
CFG.connect_timeout_ms, err, errlen))
|
||||
CFG.connect_timeout_ms, err, errlen)) {
|
||||
free(rewritten);
|
||||
return -1;
|
||||
}
|
||||
up.role = "upstream";
|
||||
|
||||
char target[4096];
|
||||
@@ -651,9 +684,26 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
snprintf(target, sizeof target, "%s%s", prefix, rq->path);
|
||||
|
||||
char *req = malloc(HDR_BLOCK_MAX);
|
||||
if (!req) { snprintf(err, errlen, "oom"); j_conn_close(&up); return -1; }
|
||||
if (!req) { snprintf(err, errlen, "oom"); j_conn_close(&up); free(rewritten); return -1; }
|
||||
size_t used = (size_t)snprintf(req, HDR_BLOCK_MAX, "%s %s HTTP/1.1\r\n", rq->method, target);
|
||||
used += j_hdrs_serialize(&rq->hdrs, req + used, HDR_BLOCK_MAX - used, 1, 0);
|
||||
|
||||
/* Forward the client's headers, but not the ones we own. Forwarding the client's
|
||||
* Host gave the upstream TWO Host headers, and its Content-Length plus ours gave
|
||||
* it two lengths — Ollama answered 400 for a request that was valid. */
|
||||
for (int i = 0; i < rq->hdrs.n; i++) {
|
||||
const char *name = rq->hdrs.it[i].name;
|
||||
if (j_is_hop_by_hop(&rq->hdrs, name)) continue;
|
||||
if (!strcasecmp(name, "Host") || !strcasecmp(name, "Content-Length") ||
|
||||
!strcasecmp(name, "Transfer-Encoding") ||
|
||||
!strcasecmp(name, "X-Forwarded-For") || !strcasecmp(name, "X-Forwarded-Proto") ||
|
||||
!strncasecmp(name, "X-Junction-", 11))
|
||||
continue;
|
||||
int n = snprintf(req + used, HDR_BLOCK_MAX - used, "%s: %s\r\n", name,
|
||||
rq->hdrs.it[i].value);
|
||||
if (n < 0) break;
|
||||
used += (size_t)n;
|
||||
if (used >= HDR_BLOCK_MAX - 256) break;
|
||||
}
|
||||
|
||||
char hosthdr[300];
|
||||
if ((!tls && !strcmp(port, "80")) || (tls && !strcmp(port, "443")))
|
||||
@@ -676,12 +726,10 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
"X-Forwarded-Proto: %s\r\nX-Junction-Endpoint: %s\r\n",
|
||||
tls ? "https" : "http", ep->name);
|
||||
char xff[J_HDR_VALUE];
|
||||
if (!j_hdrs_find(&rq->hdrs, "X-Forwarded-For", xff, sizeof xff))
|
||||
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
||||
"X-Forwarded-For: 127.0.0.1\r\n");
|
||||
else
|
||||
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
||||
"X-Forwarded-For: %s, 127.0.0.1\r\n", xff);
|
||||
int have_xff = (j_hdrs_find(&rq->hdrs, "X-Forwarded-For", xff, sizeof xff) == 0 &&
|
||||
xff[0] != '\0');
|
||||
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "X-Forwarded-For: %s%s127.0.0.1\r\n",
|
||||
have_xff ? xff : "", have_xff ? ", " : "");
|
||||
if (out_body && out_len)
|
||||
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
||||
"Content-Length: %zu\r\n", out_len);
|
||||
@@ -691,12 +739,14 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
snprintf(err, errlen, "request_headers_too_large");
|
||||
free(req);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return -1;
|
||||
}
|
||||
if (j_conn_write(&up, req, used, err, errlen) < 0 ||
|
||||
(out_body && out_len && j_conn_write(&up, out_body, out_len, err, errlen) < 0)) {
|
||||
free(req);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return -1;
|
||||
}
|
||||
free(req);
|
||||
@@ -705,6 +755,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
j_upstream_resp r;
|
||||
if (read_response(&up, &r, ep->idle_timeout_s, deadline, err, errlen)) {
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return -1;
|
||||
}
|
||||
if (r.status >= 500 || r.status == 429) {
|
||||
@@ -712,6 +763,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", r.status);
|
||||
resp_free(&r);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -734,6 +786,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
ep->idle_timeout_s, deadline, &body, &body_len, err, errlen)) {
|
||||
resp_free(&r);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return -1; /* nothing sent yet, failover is safe */
|
||||
}
|
||||
/* cache the serialized head *with* its final headers, then send the same bytes */
|
||||
@@ -745,7 +798,7 @@ 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, out_model, out_body, out_len),
|
||||
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);
|
||||
free(headcopy);
|
||||
}
|
||||
@@ -755,6 +808,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
free(body);
|
||||
resp_free(&r);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
return rc == 0 ? 0 : -2;
|
||||
}
|
||||
|
||||
@@ -770,6 +824,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
||||
r.chunked ? -1 : r.content_length, ep->idle_timeout_s, deadline);
|
||||
resp_free(&r);
|
||||
j_conn_close(&up);
|
||||
free(rewritten);
|
||||
if (rc) {
|
||||
snprintf(err, errlen, "relay_failed");
|
||||
return -2;
|
||||
@@ -839,7 +894,7 @@ static void handle_client(j_conn *client)
|
||||
if (!strcmp(rq.path, "/status")) { status_page(client); goto done; }
|
||||
if (!strncmp(rq.path, "/admin/", 7)) { admin(client, rq.path); goto done; }
|
||||
|
||||
long need = need_tokens(rq.body);
|
||||
long need = need_tokens(rq.body, rq.path);
|
||||
char model[J_GLOB_MAX];
|
||||
json_str_value(rq.body, "model", model, sizeof model);
|
||||
|
||||
@@ -864,13 +919,10 @@ static void handle_client(j_conn *client)
|
||||
goto done;
|
||||
}
|
||||
|
||||
/* The body goes out unchanged; a target that needs a different model name does
|
||||
* that rewrite itself (forward_step), so a rule may mix targets with and
|
||||
* without a rewrite. */
|
||||
const char *out_body = rq.body;
|
||||
char *rewritten = NULL;
|
||||
const char *out_model = model;
|
||||
if (rule->rewrite_model[0] && rq.body) {
|
||||
rewritten = rewrite_model(rq.body, rule->rewrite_model);
|
||||
if (rewritten) { out_body = rewritten; out_model = rule->rewrite_model; }
|
||||
}
|
||||
size_t out_len = out_body ? strlen(out_body) : 0;
|
||||
double started = now_s();
|
||||
|
||||
@@ -878,13 +930,12 @@ static void handle_client(j_conn *client)
|
||||
uint64_t ckey = 0;
|
||||
int may_cache = request_is_cacheable(&rq, err, sizeof err);
|
||||
if (may_cache) {
|
||||
ckey = j_cache_key(rq.method, rq.path, out_model, out_body, out_len);
|
||||
ckey = j_cache_key(rq.method, rq.path, model, out_body, out_len);
|
||||
const char *head = NULL, *cbody = NULL;
|
||||
size_t head_len = 0, cbody_len = 0;
|
||||
double age = 0;
|
||||
if (j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) {
|
||||
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, out_model, age);
|
||||
free(rewritten);
|
||||
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
@@ -904,7 +955,7 @@ static void handle_client(j_conn *client)
|
||||
int use_hooks = (rule->check == J_CHECK_HOOKS) ||
|
||||
(rule->check == J_CHECK_INHERIT && ep->hook_count > 0);
|
||||
double retry = rule->retry_s >= 0 ? rule->retry_s : ep->hook_retry_s;
|
||||
int ready = wait_until_ready(ep, rq.path, out_model, need, retry, use_hooks);
|
||||
int ready = wait_until_ready(ep, rq.path, model, need, retry, use_hooks);
|
||||
if (ready != 0) {
|
||||
jlog("hooks_failed", "endpoint=%s reason=%s", ep->name, ep->last_hook_reason);
|
||||
strncat(attempts, " hooks", sizeof attempts - strlen(attempts) - 1);
|
||||
@@ -912,7 +963,7 @@ static void handle_client(j_conn *client)
|
||||
}
|
||||
|
||||
ep->inflight++;
|
||||
int rc = forward_step(client, ep, &rq, out_body, out_len, out_model,
|
||||
int rc = forward_step(client, ep, &rq, out_body, out_len, rule->target_as[t], model,
|
||||
may_cache ? "miss" : "off", started, err, sizeof err);
|
||||
ep->inflight--;
|
||||
if (rc == 0) {
|
||||
@@ -921,14 +972,12 @@ static void handle_client(j_conn *client)
|
||||
jlog("served_by", "endpoint=%s ms=%ld need_tokens=%ld rule_line=%d tls=%d cache=%s",
|
||||
ep->name, ep->last_ms, need, rule->line,
|
||||
!strncmp(ep->base, "https://", 8), may_cache ? "miss" : "off");
|
||||
free(rewritten);
|
||||
goto done;
|
||||
}
|
||||
if (rc == -2) {
|
||||
ep->fail_count++;
|
||||
snprintf(ep->last_error, sizeof ep->last_error, "%s", err);
|
||||
jlog("aborted", "endpoint=%s error=%s", ep->name, err);
|
||||
free(rewritten);
|
||||
goto done;
|
||||
}
|
||||
ep->fail_count++;
|
||||
@@ -949,7 +998,6 @@ static void handle_client(j_conn *client)
|
||||
"{\"error\":\"no_endpoint_available\",\"need_tokens\":%ld,\"rule_line\":%d,\"attempts\":\"%s\"}",
|
||||
need, rule->line, attempts[0] ? attempts + 1 : "none");
|
||||
send_simple(client, 503, "Service Unavailable", body);
|
||||
free(rewritten);
|
||||
|
||||
done:
|
||||
free(rq.body);
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,78 @@
|
||||
/* tools/junction-wol.c — send a Wake-on-LAN magic packet.
|
||||
*
|
||||
* junction-wol aa:bb:cc:dd:ee:ff [broadcast] [port]
|
||||
*
|
||||
* C99 + POSIX like the router itself. Hooks may be shell, but they are not allowed
|
||||
* to need a Python interpreter to build a 102-byte packet.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int hexval(int c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "usage: junction-wol aa:bb:cc:dd:ee:ff [broadcast] [port]\n");
|
||||
return 2;
|
||||
}
|
||||
unsigned char mac[6];
|
||||
int n = 0;
|
||||
for (const char *p = argv[1]; *p && n < 6; ) {
|
||||
int hi = hexval((unsigned char)*p++);
|
||||
int lo = *p ? hexval((unsigned char)*p) : -1;
|
||||
if (hi < 0 || lo < 0) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; }
|
||||
mac[n++] = (unsigned char)((hi << 4) | lo);
|
||||
if (*p) p++;
|
||||
if (*p == ':' || *p == '-') { p++; continue; }
|
||||
if (*p) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; }
|
||||
}
|
||||
if (n != 6) { fprintf(stderr, "bad_mac: %s\n", argv[1]); return 2; }
|
||||
|
||||
unsigned char pkt[102];
|
||||
memset(pkt, 0xff, 6);
|
||||
for (int i = 0; i < 16; i++) memcpy(pkt + 6 + i * 6, mac, 6);
|
||||
|
||||
const char *bcast = argc > 2 ? argv[2] : "255.255.255.255";
|
||||
int port = argc > 3 ? atoi(argv[3]) : 9;
|
||||
|
||||
int fd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (fd < 0) { perror("socket"); return 1; }
|
||||
int one = 1;
|
||||
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one);
|
||||
|
||||
struct sockaddr_in to;
|
||||
memset(&to, 0, sizeof to);
|
||||
to.sin_family = AF_INET;
|
||||
to.sin_port = htons((unsigned short)port);
|
||||
if (inet_pton(AF_INET, bcast, &to.sin_addr) != 1) {
|
||||
fprintf(stderr, "bad_broadcast: %s\n", bcast);
|
||||
close(fd);
|
||||
return 2;
|
||||
}
|
||||
if (sendto(fd, pkt, sizeof pkt, 0, (struct sockaddr *)&to, sizeof to) < 0) {
|
||||
perror("sendto");
|
||||
close(fd);
|
||||
return 1;
|
||||
}
|
||||
if (port == 9) { /* many NICs listen on 7, a few only there */
|
||||
to.sin_port = htons(7);
|
||||
(void)sendto(fd, pkt, sizeof pkt, 0, (struct sockaddr *)&to, sizeof to);
|
||||
}
|
||||
close(fd);
|
||||
printf("sent %s via %s:%d\n", argv[1], bcast, port);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user