Physical ops-neko binds to VPS assign cards; assign UI switches local vs remote open without removing douyinweb-neko-*. Co-authored-by: Cursor <cursoragent@cursor.com>
384 lines
15 KiB
Python
384 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Ops-tab Neko Docker fleet — isolated from youtube_neko (assign).
|
||
|
||
Containers: douyinweb-ops-neko-{slot}
|
||
HTTP ports: 18200+(slot-1) (assign uses 9200+)
|
||
WebRTC mux: 62300+(slot-1) (assign uses 52300+)
|
||
Path for Caddy: /ops-neko/{slot}/ → host:1820x
|
||
|
||
Create always leaves containers stopped unless start() is called.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import shutil
|
||
import subprocess
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from . import ops_neko_db
|
||
from .config import settings
|
||
|
||
|
||
HTTP_BASE = 18200
|
||
MUX_BASE = 62300
|
||
UDP_BASE = 62500
|
||
UDP_SPAN = 10
|
||
|
||
|
||
def _run(cmd: list[str], timeout: int = 60) -> tuple[int, str]:
|
||
try:
|
||
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
||
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
|
||
except Exception as exc:
|
||
return 1, str(exc)
|
||
|
||
|
||
def _root() -> Path:
|
||
p = settings.data_dir / "ops_neko"
|
||
p.mkdir(parents=True, exist_ok=True)
|
||
(p / "profiles").mkdir(parents=True, exist_ok=True)
|
||
return p
|
||
|
||
|
||
def _compose_path() -> Path:
|
||
return _root() / "docker-compose.yml"
|
||
|
||
|
||
def _container_name(slot: int) -> str:
|
||
return f"douyinweb-ops-neko-{int(slot)}"
|
||
|
||
|
||
def _http_port(slot: int) -> int:
|
||
return HTTP_BASE + int(slot) - 1
|
||
|
||
|
||
def _mux(slot: int) -> int:
|
||
return MUX_BASE + int(slot) - 1
|
||
|
||
|
||
def _udp_range(slot: int) -> str:
|
||
lo = UDP_BASE + (int(slot) - 1) * UDP_SPAN
|
||
hi = lo + UDP_SPAN - 1
|
||
return f"{lo}-{hi}"
|
||
|
||
|
||
def _q(value: str) -> str:
|
||
return json.dumps(str(value), ensure_ascii=False)
|
||
|
||
|
||
def _http_bind() -> str:
|
||
return str(getattr(settings, "neko_http_bind", "") or "127.0.0.1").strip() or "127.0.0.1"
|
||
|
||
|
||
def _profile(slot: int) -> Path:
|
||
p = _root() / "profiles" / str(int(slot))
|
||
p.mkdir(parents=True, exist_ok=True)
|
||
return p
|
||
|
||
|
||
def _instance_id_file(slot: int) -> Path:
|
||
p = _root() / "instance_ids"
|
||
p.mkdir(parents=True, exist_ok=True)
|
||
f = p / f"{int(slot)}.txt"
|
||
f.write_text(f"ops-{int(slot)}\n", encoding="utf-8")
|
||
return f
|
||
|
||
|
||
def _compose_cmd(*args: str) -> list[str]:
|
||
path = str(_compose_path())
|
||
if shutil.which("docker-compose"):
|
||
return ["docker-compose", "-f", path, *args]
|
||
code, _ = _run(["docker", "compose", "version"], timeout=15)
|
||
if code == 0:
|
||
return ["docker", "compose", "-f", path, *args]
|
||
raise RuntimeError("未找到 docker compose")
|
||
|
||
|
||
def _render_compose(max_slot: int) -> str:
|
||
from . import youtube_neko as yn
|
||
|
||
image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0")
|
||
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
|
||
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "neko")
|
||
nat1to1 = yn._detect_public_ip() # noqa: SLF001
|
||
shm = str(getattr(settings, "neko_shm_size", "") or "512mb")
|
||
screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15")
|
||
max_fps = str(getattr(settings, "neko_max_fps", "") or "15")
|
||
bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200")
|
||
icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0")
|
||
start_url = str(
|
||
getattr(settings, "neko_start_url", "")
|
||
or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
|
||
)
|
||
assets = yn._asset_root() # noqa: SLF001
|
||
managed = yn._managed_policies_enabled() # noqa: SLF001
|
||
policy_dir = assets / ("policies" if managed else "no-managed-policies")
|
||
seed_dir = assets / "tampermonkey-seed"
|
||
live_ops_dir = assets / "live-ops-extension"
|
||
provisioning_dir = assets / "provisioning"
|
||
browser_launch = assets / "browser-launch.sh"
|
||
supervisor = assets / yn._supervisor_conf_name() # noqa: SLF001
|
||
for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir):
|
||
if not required.exists():
|
||
raise RuntimeError(f"Neko asset missing: {required}")
|
||
yn._ensure_browser_launch_exec() # noqa: SLF001
|
||
proxy = yn._neko_browser_proxy_value() # noqa: SLF001
|
||
|
||
lines = ["# Generated by douyinWEB ops_neko — independent of assign fleet", "services:"]
|
||
n = max(1, int(max_slot))
|
||
for idx in range(1, n + 1):
|
||
http_port = _http_port(idx)
|
||
mux = _mux(idx)
|
||
udp = _udp_range(idx)
|
||
profile = _profile(idx)
|
||
id_file = _instance_id_file(idx)
|
||
lines.extend(
|
||
[
|
||
f" opsneko{idx}:",
|
||
f" image: {_q(image)}",
|
||
' restart: "no"',
|
||
f" shm_size: {_q(shm)}",
|
||
" cap_add:",
|
||
" - SYS_ADMIN",
|
||
" security_opt:",
|
||
" - apparmor:unconfined",
|
||
" extra_hosts:",
|
||
' - "host.docker.internal:host-gateway"',
|
||
f" container_name: {_container_name(idx)}",
|
||
" environment:",
|
||
' TZ: "America/Chicago"',
|
||
' DISPLAY: ":99.0"',
|
||
' NEKO_SERVER_BIND: ":8080"',
|
||
' NEKO_SERVER_PROXY: "true"',
|
||
' NEKO_MEMBER_PROVIDER: "multiuser"',
|
||
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
|
||
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
|
||
f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
|
||
f" NEKO_MAX_FPS: {_q(max_fps)}",
|
||
f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
|
||
f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
|
||
f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
|
||
f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
|
||
f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
|
||
f" NEKO_WEBRTC_EPR: {_q(udp)}",
|
||
f" NEKO_START_URL: {_q(start_url)}",
|
||
f" NEKO_BROWSER_PROXY: {_q(proxy)}",
|
||
f" NEKO_INSTANCE_ID: {_q(f'ops-{idx}')}",
|
||
" ports:",
|
||
f' - "{_http_bind()}:{http_port}:8080"',
|
||
f' - "{mux}:{mux}/tcp"',
|
||
f' - "{mux}:{mux}/udp"',
|
||
f' - "{udp}:{udp}/udp"',
|
||
" volumes:",
|
||
f" - {_q(f'{profile}:/home/neko/.config/chromium')}",
|
||
f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}",
|
||
f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
|
||
f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
|
||
f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
|
||
f" - {_q(f'{id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}",
|
||
f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}",
|
||
f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}",
|
||
f" - {_q(f'{supervisor}:/etc/neko/supervisord/{yn._supervisor_conf_name()}:ro')}", # noqa: SLF001
|
||
]
|
||
)
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def _container_running(slot: int) -> bool:
|
||
code, out = _run(
|
||
["docker", "inspect", "-f", "{{.State.Running}}", _container_name(slot)],
|
||
timeout=8,
|
||
)
|
||
return code == 0 and "true" in (out or "").lower()
|
||
|
||
|
||
def _public_neko_url(slot: int) -> str:
|
||
from . import db
|
||
|
||
cfg = db.get_settings_map()
|
||
base = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/")
|
||
if not base:
|
||
base = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/")
|
||
if not base:
|
||
return f"/ops-neko/{int(slot)}/"
|
||
return f"{base}/ops-neko/{int(slot)}/"
|
||
|
||
|
||
def sync_compose(*, start_slots: set[int] | None = None) -> dict[str, Any]:
|
||
"""Rewrite compose for current max slot; create containers; start only requested."""
|
||
max_slot = max(ops_neko_db.max_slot(), 1) if ops_neko_db.list_instances() else 0
|
||
if max_slot < 1:
|
||
return {"ok": True, "skipped": "no_instances"}
|
||
text = _render_compose(max_slot)
|
||
_compose_path().write_text(text, encoding="utf-8")
|
||
start_slots = start_slots or set()
|
||
code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600)
|
||
if code != 0 and "--no-start" in (out or "").lower():
|
||
code, out = _run(_compose_cmd("up", "-d"), timeout=600)
|
||
if code == 0:
|
||
for idx in range(1, max_slot + 1):
|
||
if idx not in start_slots:
|
||
_run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
|
||
if code != 0:
|
||
return {"ok": False, "error": (out or "compose up failed")[:500]}
|
||
started: list[int] = []
|
||
for idx in sorted(start_slots):
|
||
if 1 <= idx <= max_slot:
|
||
c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90)
|
||
if c2 == 0:
|
||
started.append(idx)
|
||
else:
|
||
return {"ok": False, "error": (o2 or "start failed")[:300], "started": started}
|
||
return {"ok": True, "max_slot": max_slot, "started": started}
|
||
|
||
|
||
def create_and_provision(*, name: str = "", note: str = "") -> dict[str, Any]:
|
||
row = ops_neko_db.create_instance(name=name, note=note)
|
||
sync = sync_compose(start_slots=set()) # always stopped after create
|
||
return {"ok": True, "instance": enrich(row), "docker": sync}
|
||
|
||
|
||
def start_slot(slot: int) -> dict[str, Any]:
|
||
inst = next((r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == int(slot)), None)
|
||
if not inst:
|
||
return {"ok": False, "error": "instance not found"}
|
||
sync = sync_compose(start_slots={int(slot)})
|
||
if not sync.get("ok"):
|
||
return sync
|
||
ops_neko_db.update_instance(str(inst["id"]), want_running=True)
|
||
return {"ok": True, "instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst), "docker": sync}
|
||
|
||
|
||
def stop_slot(slot: int) -> dict[str, Any]:
|
||
inst = next((r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == int(slot)), None)
|
||
if not inst:
|
||
return {"ok": False, "error": "instance not found"}
|
||
code, out = _run(["docker", "stop", "-t", "8", _container_name(int(slot))], timeout=45)
|
||
ops_neko_db.update_instance(str(inst["id"]), want_running=False)
|
||
return {
|
||
"ok": code == 0 or "no such container" in (out or "").lower(),
|
||
"detail": out[:200],
|
||
"instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst),
|
||
}
|
||
|
||
|
||
def remove_instance(instance_id: str) -> dict[str, Any]:
|
||
inst = ops_neko_db.get_instance(instance_id)
|
||
if not inst:
|
||
return {"ok": False, "error": "not found"}
|
||
slot = int(inst.get("slot") or 0)
|
||
_run(["docker", "rm", "-f", _container_name(slot)], timeout=45)
|
||
ops_neko_db.delete_instance(instance_id)
|
||
# refresh compose without deleted slot
|
||
if ops_neko_db.list_instances():
|
||
sync_compose(start_slots=set())
|
||
return {"ok": True, "deleted": instance_id, "slot": slot}
|
||
|
||
|
||
def enrich(row: dict[str, Any] | None) -> dict[str, Any]:
|
||
if not row:
|
||
return {}
|
||
out = dict(row)
|
||
slot = int(out.get("slot") or 0)
|
||
out["running"] = _container_running(slot) if slot else False
|
||
out["container"] = _container_name(slot) if slot else ""
|
||
out["http_port"] = _http_port(slot) if slot else 0
|
||
out["open_url"] = _public_neko_url(slot) if slot else ""
|
||
out["want_running"] = bool(out.get("want_running"))
|
||
return out
|
||
|
||
|
||
def list_enriched() -> list[dict[str, Any]]:
|
||
return [enrich(r) for r in ops_neko_db.list_instances()]
|
||
|
||
|
||
def hub_assign_cards() -> list[dict[str, Any]]:
|
||
"""Cards published by hub for edge manual binding (YouTube 分配 groups)."""
|
||
from . import yt_assign_db
|
||
|
||
cards = []
|
||
for g in yt_assign_db.list_groups(include_urls=False):
|
||
cards.append(
|
||
{
|
||
"id": str(g.get("id") or ""),
|
||
"name": str(g.get("name") or ""),
|
||
"youtube_channel_id": str(g.get("youtube_channel_id") or ""),
|
||
"enabled": bool(g.get("enabled")),
|
||
"neko_instance_id": int(g.get("neko_instance_id") or 0),
|
||
"assign_neko_enabled": bool(g.get("neko_enabled")),
|
||
"has_stream_key": bool(str(g.get("stream_key") or "").strip()),
|
||
# Native always exists on hub; remote bind is additive.
|
||
"neko_local_studio_url": str(g.get("neko_local_studio_url") or g.get("neko_studio_url") or ""),
|
||
"ops_neko_open_url": str(g.get("ops_neko_open_url") or ""),
|
||
"ops_neko_bound": bool(g.get("ops_neko_bound")),
|
||
"neko_open_prefer": str(g.get("neko_open_prefer") or "local"),
|
||
}
|
||
)
|
||
return cards
|
||
|
||
|
||
def pull_remote_cards() -> dict[str, Any]:
|
||
"""Edge: HTTP pull hub assign cards using peer URL + token."""
|
||
import httpx
|
||
|
||
from . import db
|
||
|
||
st = ops_neko_db.peer_status()
|
||
if st.get("role") != "edge":
|
||
return {"ok": False, "error": "peer role is not edge"}
|
||
base = str(st.get("peer_base_url") or "").strip().rstrip("/")
|
||
cfg = db.get_settings_map()
|
||
token = str(cfg.get("ops_neko_peer_token") or "").strip()
|
||
if not base or not token:
|
||
return {"ok": False, "error": "请填写 hub 域名与 token"}
|
||
url = f"{base}/api/ops/neko/hub/assign-cards"
|
||
try:
|
||
with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client:
|
||
r = client.get(url, headers={"X-Ops-Neko-Token": token})
|
||
if r.status_code != 200:
|
||
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}"}
|
||
data = r.json()
|
||
return {"ok": True, "cards": data.get("cards") or [], "hub": base, "fetched_at": data.get("time")}
|
||
except Exception as exc:
|
||
return {"ok": False, "error": str(exc)[:300]}
|
||
|
||
|
||
def push_bind_to_hub(instance_id: str) -> dict[str, Any]:
|
||
"""Edge → hub: register this ops-neko open URL onto the VPS assign group."""
|
||
import httpx
|
||
|
||
from . import db
|
||
|
||
st = ops_neko_db.peer_status()
|
||
if st.get("role") != "edge":
|
||
return {"ok": False, "error": "仅 edge(物理机)向 hub 登记绑定"}
|
||
base = str(st.get("peer_base_url") or "").strip().rstrip("/")
|
||
cfg = db.get_settings_map()
|
||
token = str(cfg.get("ops_neko_peer_token") or "").strip()
|
||
if not base or not token:
|
||
return {"ok": False, "error": "请填写 hub 域名与 token"}
|
||
inst = ops_neko_db.get_instance(instance_id)
|
||
if not inst:
|
||
return {"ok": False, "error": "instance not found"}
|
||
gid = str(inst.get("bind_remote_group_id") or "").strip()
|
||
if not gid:
|
||
return {"ok": False, "error": "尚未选择要绑定的 VPS 分配频道"}
|
||
open_url = _public_neko_url(int(inst.get("slot") or 0))
|
||
payload = {
|
||
"group_id": gid,
|
||
"open_url": open_url,
|
||
"slot": int(inst.get("slot") or 0),
|
||
"edge_label": str(inst.get("name") or f"ops-{inst.get('slot')}"),
|
||
"running": _container_running(int(inst.get("slot") or 0)),
|
||
}
|
||
url = f"{base}/api/ops/neko/hub/bind"
|
||
try:
|
||
with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client:
|
||
r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload)
|
||
if r.status_code != 200:
|
||
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload}
|
||
return {"ok": True, "hub": base, "payload": payload, "response": r.json()}
|
||
except Exception as exc:
|
||
return {"ok": False, "error": str(exc)[:300], "payload": payload}
|