# -*- coding: utf-8 -*- """Ops-tab Neko Docker fleet — same runtime as assign youtube_neko. 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 Compose env/assets/proxy/Studio URL come from youtube_neko.compose_service_lines so YouTube live tooling matches the assign page. Ports/names stay isolated. 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 _http_bind() -> str: """Same bind policy as assign youtube_neko (physical → 0.0.0.0 for WG edges).""" from . import youtube_neko as yn return yn._http_bind() # noqa: SLF001 def _profile(slot: int) -> Path: p = _root() / "profiles" / str(int(slot)) p.mkdir(parents=True, exist_ok=True) try: import os os.chmod(p, 0o777) except OSError: pass 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" # Same live-ops telemetry format as assign fleet (numeric id string when possible). # Prefix ops- so Studio events from tab fleet don't collide with assign neko-N. 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: """Mirror assign youtube_neko runtime (Studio / TM / live-ops / proxy / ICE).""" from . import youtube_neko as yn lines = [ "# Generated by douyinWEB ops_neko — same runtime as assign youtube_neko", "services:", ] n = max(1, int(max_slot)) for idx in range(1, n + 1): lines.extend( yn.compose_service_lines( service_key=f"opsneko{idx}", container_name=_container_name(idx), instance_id_label=f"ops-{idx}", http_port=_http_port(idx), mux=_mux(idx), udp=_udp_range(idx), profile=_profile(idx), instance_id_file=_instance_id_file(idx), http_bind=_http_bind(), ) ) 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 from . import youtube_neko as yn cfg = db.get_settings_map() override = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") base = yn.preferred_neko_public_base(override=override) 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, force_recreate: bool = True) -> dict[str, Any]: """Rewrite compose for current max slot; create containers; start only requested. force_recreate default True so env (proxy / NAT1TO1 / TM) matches assign fleet. Already-running slots are restarted after recreate (same as youtube_neko egress refresh). """ 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 = set(start_slots or set()) was_running = {idx for idx in range(1, max_slot + 1) if _container_running(idx)} resume = was_running | start_slots up_args = ["up", "-d", "--no-start"] if force_recreate: up_args.insert(2, "--force-recreate") code, out = _run(_compose_cmd(*up_args), timeout=600) if code != 0 and "--no-start" in (out or "").lower(): code, out = _run( _compose_cmd("up", "-d", *(["--force-recreate"] if force_recreate else [])), timeout=600, ) if code == 0: for idx in range(1, max_slot + 1): if idx not in resume: _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] = [] errors: list[str] = [] for idx in sorted(resume): if 1 <= idx <= max_slot: c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90) if c2 == 0: started.append(idx) else: errors.append(f"ops-{idx}: {(o2 or 'start failed')[:160]}") if errors: return {"ok": False, "error": "; ".join(errors)[:500], "started": started, "max_slot": max_slot} 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 try: from . import ops_neko_sync ops_neko_sync.kick() except Exception: pass 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) try: from . import ops_neko_sync ops_neko_sync.kick() except Exception: pass 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) try: from . import ops_neko_sync ops_neko_sync.kick() except Exception: pass 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")), "ops_neko_slot": int(g.get("ops_neko_slot") or 0), "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, *, also_catalog: bool = True) -> 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} cat = push_catalog_to_hub() if also_catalog else {"ok": True, "skipped": "also_catalog=0"} return {"ok": True, "hub": base, "payload": payload, "response": r.json(), "catalog": cat} except Exception as exc: return {"ok": False, "error": str(exc)[:300], "payload": payload} def push_catalog_to_hub() -> dict[str, Any]: """Edge → hub: publish all local ops-neko slots for VPS assign dropdown.""" import httpx import socket 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"} edge_label = str(cfg.get("ops_neko_edge_label") or "").strip() if not edge_label: try: edge_label = socket.gethostname() or "physical" except Exception: edge_label = "physical" items = [] for row in list_enriched(): slot = int(row.get("slot") or 0) if slot < 1: continue studio = None try: from . import youtube_neko as yn studio = yn.studio_snapshot_for_ref(f"ops:{slot}", max_age_sec=180.0) # Drop empty snapshots to keep payload light if not (studio.get("received_at") or studio.get("on_air") or studio.get("live_page_open")): studio = None except Exception: studio = None items.append( { "id": str(row.get("id") or ""), "slot": slot, "name": str(row.get("name") or f"Ops Neko {slot}"), "open_url": str(row.get("open_url") or ""), "running": bool(row.get("running")), "studio": studio, } ) payload = {"edge_id": edge_label, "edge_label": edge_label, "instances": items} # Push assign Studio on_air so VPS live-map matches physical receiving-first. assign_lives: list[dict[str, Any]] = [] try: import time as _time from . import yt_assign_db from . import yt_studio_db from . import youtube_neko as yn since = _time.time() - 180.0 seen_cid: set[str] = set() for g in yt_assign_db.list_groups(include_urls=False): if not g.get("enabled"): continue gid = str(g.get("id") or "").strip() cid = str(g.get("youtube_channel_id") or "").strip() pk = str(g.get("channel_pk") or "").strip() if not cid or cid in seen_cid: continue snap = {} try: snap = yn.studio_snapshot_for_group(g, max_age_sec=180.0) except Exception: snap = {} on_air = bool(snap.get("on_air") or snap.get("encoder_receiving")) st = str(snap.get("live_status") or "").lower() if not on_air or st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: # Fall back to recent DB samples (local CDP poll). try: samples = yt_studio_db.list_samples(group_id=gid, since_ts=since, limit=3) except Exception: samples = [] hit = None for s in samples: sst = str(s.get("live_status") or "").lower() if sst in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}: continue if s.get("on_air") or sst == "live": hit = s break if not hit: continue assign_lives.append( { "group_id": gid, "channel_pk": pk, "youtube_channel_id": cid, "name": str(g.get("name") or ""), "on_air": True, "live_status": str(hit.get("live_status") or "live"), "health": str(hit.get("health") or ""), "viewer_count": hit.get("viewer_count"), "studio_url": str(hit.get("studio_url") or "")[:200], "neko_ref": str(hit.get("neko_ref") or ""), "ts": float(hit.get("ts") or _time.time()), } ) seen_cid.add(cid) continue assign_lives.append( { "group_id": gid, "channel_pk": pk, "youtube_channel_id": cid, "name": str(g.get("name") or ""), "on_air": True, "live_status": st or "live", "health": str(snap.get("health") or ""), "viewer_count": snap.get("viewer_count"), "studio_url": str(snap.get("url") or "")[:200], "neko_ref": str(snap.get("neko_ref") or ""), "ts": float(snap.get("received_at") or _time.time()), } ) seen_cid.add(cid) except Exception: assign_lives = [] if assign_lives: payload["assign_lives"] = assign_lives url = f"{base}/api/ops/neko/hub/catalog" 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, "count": len(items), "response": r.json()} except Exception as exc: return {"ok": False, "error": str(exc)[:300], "payload": payload} def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[str, Any]: """Physical edge: ensure ops-neko Chrome has YouTube Live Control Room open (待开播).""" from . import youtube_neko as yn slot_i = int(slot or 0) if slot_i < 1: return {"ok": False, "error": "bad_slot"} name = _container_name(slot_i) if not _container_running(slot_i): try: start_slot(slot_i) except Exception: pass if not _container_running(slot_i): return {"ok": False, "slot": slot_i, "error": "ops_neko_not_running"} yt = str(youtube_channel_id or "").strip() if not yt: try: inst = next( (r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == slot_i), None, ) gid = str((inst or {}).get("bind_remote_group_id") or "").strip() if gid: cards = pull_remote_cards() for c in cards.get("cards") or []: if str(c.get("id") or "") == gid: yt = str(c.get("youtube_channel_id") or "").strip() break except Exception: pass studio_url = yn.studio_live_control_url(yt) opened = yn._cdp_ensure_live_studio_in_container(name, studio_url=studio_url) try: # Never inject fake live_status=ready — that made hub think Studio was good while NODATA. payload: dict[str, Any] = { "neko_ref": f"ops-{slot_i}", "neko_instance_id": f"ops-{slot_i}", "source": "ops_cdp_ensure", "url": str((opened or {}).get("url") or studio_url)[:400], "live_status": "waiting", "signals": {"path": "/livestreaming", "pending_go_live": True}, } try: urls_py = ( "import json,urllib.request\n" "tabs=json.loads(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4).read())\n" "live=[t.get('url') for t in tabs if 'livestreaming' in (t.get('url') or '').lower()]\n" "print(json.dumps({'ok':bool(live),'url':(live[0] if live else '')}))\n" ) code, out = yn._run(["docker", "exec", name, "python3", "-c", urls_py], timeout=15) if code == 0 and out: row = json.loads((out or "").strip().split("\n")[-1] or "{}") if isinstance(row, dict) and row.get("url"): payload["url"] = str(row.get("url"))[:400] except Exception: pass # Prefer full DOM scrape when script is available inside the container / on host. scraped = False for scrape_path in ( "/etc/neko/cdp_studio_scrape.py", "/opt/douyinWEB/backend/neko/cdp_studio_scrape.py", ): try: code, out = yn._run( ["docker", "exec", name, "python3", scrape_path], timeout=20, ) if code != 0 or not (out or "").strip(): continue row = json.loads((out or "").strip().split("\n")[-1] or "{}") if isinstance(row, dict) and row.get("ok"): if row.get("url"): payload["url"] = str(row.get("url"))[:400] st = str(row.get("live_status") or "waiting").strip().lower() or "waiting" if st == "ready": st = "waiting" payload["live_status"] = st payload["text"] = str(row.get("text") or "")[:2200] payload["signals"] = { "path": "/livestreaming", "nodata": bool(row.get("nodata")), "encoder_receiving": bool(row.get("encoder_receiving")), "encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost", "session_live": bool(row.get("session_live")) or st in {"live", "encoder_lost"}, "pending_go_live": st == "waiting" and not bool(row.get("session_live")) and st != "encoder_lost", } scraped = True break except Exception: continue if not scraped: try: from pathlib import Path host_scrape = Path(__file__).resolve().parents[1] / "neko" / "cdp_studio_scrape.py" if host_scrape.is_file(): code, out = yn._run( [ "bash", "-lc", f"docker exec -i {name} python3 - < {host_scrape.as_posix()}", ], timeout=25, ) if code == 0 and (out or "").strip(): row = json.loads((out or "").strip().split("\n")[-1] or "{}") if isinstance(row, dict) and row.get("ok"): if row.get("url"): payload["url"] = str(row.get("url"))[:400] st = str(row.get("live_status") or "waiting").strip().lower() or "waiting" if st == "ready": st = "waiting" payload["live_status"] = st payload["text"] = str(row.get("text") or "")[:2200] payload["signals"] = { "path": "/livestreaming", "nodata": bool(row.get("nodata")), "encoder_receiving": bool(row.get("encoder_receiving")), "encoder_lost": bool(row.get("encoder_lost")) or st == "encoder_lost", "session_live": bool(row.get("session_live")) or st in {"live", "encoder_lost"}, "pending_go_live": st == "waiting" and not bool(row.get("session_live")) and st != "encoder_lost", } except Exception: pass yn.ingest_studio_telemetry(payload) except Exception: pass return {"ok": bool(opened.get("ok")), "slot": slot_i, "studio_url": studio_url, "cdp": opened} def ensure_bound_slots_live_studio() -> dict[str, Any]: """Edge heartbeat: bound/running ops slots keep Live Control Room open.""" cards_by_id: dict[str, dict[str, Any]] = {} try: pulled = pull_remote_cards() for c in pulled.get("cards") or []: cid = str(c.get("id") or "").strip() if cid: cards_by_id[cid] = c except Exception: pass results: list[dict[str, Any]] = [] for row in ops_neko_db.list_instances(): slot = int(row.get("slot") or 0) if slot < 1 or not _container_running(slot): continue gid = str(row.get("bind_remote_group_id") or "").strip() yt = "" should = bool(gid) if gid and gid in cards_by_id: yt = str(cards_by_id[gid].get("youtube_channel_id") or "").strip() should = True if not should: for card in cards_by_id.values(): if int(card.get("ops_neko_slot") or 0) == slot and ( str(card.get("neko_open_prefer") or "").lower() == "remote" or card.get("ops_neko_bound") ): yt = str(card.get("youtube_channel_id") or "").strip() should = True break if not should: continue results.append(ensure_slot_live_studio(slot, youtube_channel_id=yt)) return { "ok": True, "ensured": sum(1 for r in results if r.get("ok")), "results": results, } def pair_as_edge(*, hub_base: str, token: str, public_base: str = "") -> dict[str, Any]: """Physical: save edge peer credentials then push catalog (realtime registry).""" from . import db hub = str(hub_base or "").strip().rstrip("/") tok = str(token or "").strip() if not tok: tok = str(db.get_settings_map().get("ops_neko_peer_token") or "").strip() if not hub or not tok: return {"ok": False, "error": "需要 hub 域名与 token"} peer = ops_neko_db.save_peer( role="edge", peer_base_url=hub, public_base=public_base if public_base is not None else None, token=tok, ) cards = pull_remote_cards() try: ensure_bound_slots_live_studio() except Exception: pass catalog = push_catalog_to_hub() try: from . import ops_neko_sync ops_neko_sync.kick() except Exception: pass return { "ok": bool(catalog.get("ok") or cards.get("ok")), "peer": peer, "cards": cards, "catalog": catalog, "realtime": True, "hint": "已连接:后台每 5 秒自动同步实例目录到 VPS,无需再点配对", }