inferx-autoreg: GitHub OAuth via Keycloak, ix_ keys, new-api injection
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""inject_iishko.py — заливка ключей InferX каналами в new-api (PostgreSQL) на проде.
|
||||
|
||||
Что делает:
|
||||
1. читает живой банк (ok=true, ключ ix_*)
|
||||
2. генерит SQL: delete/insert канала на каждый ключ + abilities из channels.models
|
||||
3. кладёт файл в /tmp на сервере (postgres не читает /root), применяет через su postgres
|
||||
4. рестарт new-api (кэш abilities)
|
||||
|
||||
Env:
|
||||
INFERX_BANK банк ключей (default ./inferx_bank.jsonl)
|
||||
INFERX_SSH_HOST root@host (обязательно)
|
||||
INFERX_SSH_KEY путь к приватному ключу (обязательно)
|
||||
INFERX_BASE base_url канала (default https://model.inferx.net/endpoints)
|
||||
INFERX_MODELS модели через запятую (default набор ниже)
|
||||
INFERX_PRIO priority канала (default 700)
|
||||
INFERX_TAG tag каналов (default inferx)
|
||||
|
||||
Внимание: new-api сам добавляет /v1 к base_url, поэтому в канале /endpoints БЕЗ /v1.
|
||||
Условие приёмки — chat/completions 200 и после инжекта, и в апстриме.
|
||||
"""
|
||||
import json, os, subprocess, sys, time
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BANK = os.environ.get("INFERX_BANK", os.path.join(HERE, "inferx_bank.jsonl"))
|
||||
HOST = os.environ.get("INFERX_SSH_HOST", "")
|
||||
KEYFILE = os.environ.get("INFERX_SSH_KEY", "")
|
||||
BASE = os.environ.get("INFERX_BASE", "https://model.inferx.net/endpoints")
|
||||
MODELS = [m.strip() for m in os.environ.get(
|
||||
"INFERX_MODELS",
|
||||
"deepseek-v4.1-flash-1017,deepseek-v4.1-flash,glm-5.3-flash,gpt-oss-20b,"
|
||||
"Qwen3.8-27B-FP8,kimi-k3,qwen3.8-max,gemma-4-31B-it-fp8").split(",") if m.strip()]
|
||||
PRIO = int(os.environ.get("INFERX_PRIO", "700"))
|
||||
TAG = os.environ.get("INFERX_TAG", "inferx")
|
||||
|
||||
|
||||
def ssh(cmd, timeout=240):
|
||||
r = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20",
|
||||
"-i", KEYFILE, HOST, cmd],
|
||||
capture_output=True, text=True, timeout=timeout, encoding='utf-8', errors='replace')
|
||||
return (r.stdout or "") + (r.stderr or "")
|
||||
|
||||
|
||||
def main():
|
||||
if not HOST or not KEYFILE:
|
||||
print("нужны INFERX_SSH_HOST и INFERX_SSH_KEY")
|
||||
sys.exit(2)
|
||||
keys, seen = [], set()
|
||||
for line in open(BANK, encoding='utf-8'):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
k = d.get('key', '')
|
||||
if d.get('ok') and k.startswith('ix_') and k not in seen:
|
||||
seen.add(k)
|
||||
keys.append(k)
|
||||
print("keys:", len(keys))
|
||||
if not keys:
|
||||
sys.exit(0)
|
||||
|
||||
models = ",".join(MODELS)
|
||||
sql = []
|
||||
for i, k in enumerate(keys, 1):
|
||||
name = "%s-%02d" % (TAG, i)
|
||||
sql.append("delete from channels where name='%s';" % name)
|
||||
sql.append(
|
||||
"insert into channels (type,name,\"key\",base_url,models,\"group\",priority,weight,status,"
|
||||
"auto_ban,model_mapping,created_time,tag) values "
|
||||
"(1,'%s','%s','%s','%s','default,premium,t1,t2,t3,t4',%d,0,1,0,'',%d,'%s');"
|
||||
% (name, k, BASE, models, PRIO, int(time.time()), TAG))
|
||||
sql.append("""
|
||||
insert into abilities ("group",model,channel_id,enabled,priority,weight,tag)
|
||||
select g.grp, trim(m.model), c.id, true, c.priority, 0, c.tag
|
||||
from channels c
|
||||
cross join lateral unnest(string_to_array(c."group",',')) g(grp)
|
||||
cross join lateral unnest(string_to_array(c.models,',')) m(model)
|
||||
where c.tag='%s' and c.status=1 and trim(m.model)<>''
|
||||
on conflict ("group",model,channel_id) do update set enabled=true, priority=excluded.priority;
|
||||
""" % TAG)
|
||||
|
||||
local = os.path.join(HERE, "inject.sql")
|
||||
open(local, "w", encoding="utf-8").write("\n".join(sql))
|
||||
print("sql bytes:", os.path.getsize(local))
|
||||
r = subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-i", KEYFILE, local, HOST + ":/tmp/inject.sql"],
|
||||
capture_output=True, text=True, timeout=120, encoding='utf-8', errors='replace')
|
||||
print("scp rc", r.returncode, (r.stderr or '').strip()[:120])
|
||||
out = ssh("chmod 644 /tmp/inject.sql; su postgres -c 'psql -d newapi -At -f /tmp/inject.sql' 2>&1 | tail -4; "
|
||||
"su postgres -c \"psql -d newapi -At -c \\\"select id,name,status,priority from channels where tag='%s' order by id\\\"\" 2>&1" % TAG)
|
||||
print(out[-900:])
|
||||
print("restart:", ssh("systemctl restart new-api.service; sleep 6; systemctl is-active new-api.service").strip()[:80])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user